diff --git a/.eslintrc.js b/.eslintrc.js index 99695b7a03..4959b133a0 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -15,7 +15,6 @@ module.exports = { "prefer-promise-reject-errors": "off", "no-async-promise-executor": "off", "quotes": "off", - "indent": "off", }, overrides: [{ diff --git a/.gitignore b/.gitignore index e1dd7726e1..50aa10fbfd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ /*.log package-lock.json +/coverage /node_modules /lib diff --git a/CHANGELOG.md b/CHANGELOG.md index ec73756ff9..d459b4e94a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,121 @@ +Changes in [3.19.0](https://github.com/matrix-org/matrix-react-sdk/releases/tag/v3.19.0) (2021-04-26) +===================================================================================================== +[Full Changelog](https://github.com/matrix-org/matrix-react-sdk/compare/v3.19.0-rc.1...v3.19.0) + + * Upgrade to JS SDK 10.0.0 + * [Release] Dynamic max and min zoom in the new ImageView + [\#5927](https://github.com/matrix-org/matrix-react-sdk/pull/5927) + * [Release] Add a WheelEvent normalization function + [\#5911](https://github.com/matrix-org/matrix-react-sdk/pull/5911) + * Add a WheelEvent normalization function + [\#5904](https://github.com/matrix-org/matrix-react-sdk/pull/5904) + * [Release] Use floats for image background opacity + [\#5907](https://github.com/matrix-org/matrix-react-sdk/pull/5907) + +Changes in [3.19.0-rc.1](https://github.com/matrix-org/matrix-react-sdk/releases/tag/v3.19.0-rc.1) (2021-04-21) +=============================================================================================================== +[Full Changelog](https://github.com/matrix-org/matrix-react-sdk/compare/v3.18.0...v3.19.0-rc.1) + + * Upgrade to JS SDK 10.0.0-rc.1 + * Translations update from Weblate + [\#5896](https://github.com/matrix-org/matrix-react-sdk/pull/5896) + * Fix sticky tags header in room list + [\#5895](https://github.com/matrix-org/matrix-react-sdk/pull/5895) + * Fix spaces filtering sometimes lagging behind or behaving oddly + [\#5893](https://github.com/matrix-org/matrix-react-sdk/pull/5893) + * Fix issue with spaces context switching looping and breaking + [\#5894](https://github.com/matrix-org/matrix-react-sdk/pull/5894) + * Improve RoomList render time when filtering + [\#5874](https://github.com/matrix-org/matrix-react-sdk/pull/5874) + * Avoid being stuck in a space + [\#5891](https://github.com/matrix-org/matrix-react-sdk/pull/5891) + * [Spaces] Context switching + [\#5795](https://github.com/matrix-org/matrix-react-sdk/pull/5795) + * Warn when you attempt to leave room that you are the only member of + [\#5415](https://github.com/matrix-org/matrix-react-sdk/pull/5415) + * Ensure PersistedElement are unmounted on application logout + [\#5884](https://github.com/matrix-org/matrix-react-sdk/pull/5884) + * Add missing space in seshat dialog and the corresponding string + [\#5866](https://github.com/matrix-org/matrix-react-sdk/pull/5866) + * A tiny change to make the Add existing rooms dialog a little nicer + [\#5885](https://github.com/matrix-org/matrix-react-sdk/pull/5885) + * Remove weird margin from the file panel + [\#5889](https://github.com/matrix-org/matrix-react-sdk/pull/5889) + * Trigger lazy loading when filtering using spaces + [\#5882](https://github.com/matrix-org/matrix-react-sdk/pull/5882) + * Fix typo in method call in add existing to space dialog + [\#5883](https://github.com/matrix-org/matrix-react-sdk/pull/5883) + * New Image View fixes/improvements + [\#5872](https://github.com/matrix-org/matrix-react-sdk/pull/5872) + * Limit voice recording length + [\#5871](https://github.com/matrix-org/matrix-react-sdk/pull/5871) + * Clean up add existing to space dialog and include DMs in it too + [\#5881](https://github.com/matrix-org/matrix-react-sdk/pull/5881) + * Fix unknown slash command error exploding + [\#5853](https://github.com/matrix-org/matrix-react-sdk/pull/5853) + * Switch to a spec conforming email validation Regexp + [\#5852](https://github.com/matrix-org/matrix-react-sdk/pull/5852) + * Cleanup unused state in MessageComposer + [\#5877](https://github.com/matrix-org/matrix-react-sdk/pull/5877) + * Pulse animation for voice messages recording state + [\#5869](https://github.com/matrix-org/matrix-react-sdk/pull/5869) + * Don't include invisible rooms in notify summary + [\#5875](https://github.com/matrix-org/matrix-react-sdk/pull/5875) + * Properly disable composer access when recording a voice message + [\#5870](https://github.com/matrix-org/matrix-react-sdk/pull/5870) + * Stabilise starting a DM with multiple people flow + [\#5862](https://github.com/matrix-org/matrix-react-sdk/pull/5862) + * Render msgOption only if showReadReceipts is enabled + [\#5864](https://github.com/matrix-org/matrix-react-sdk/pull/5864) + * Labs: Add quick/cheap "do not disturb" flag + [\#5873](https://github.com/matrix-org/matrix-react-sdk/pull/5873) + * Fix ReadReceipts animations + [\#5836](https://github.com/matrix-org/matrix-react-sdk/pull/5836) + * Add tooltips to message previews + [\#5859](https://github.com/matrix-org/matrix-react-sdk/pull/5859) + * IRC Layout fix layout spacing in replies + [\#5855](https://github.com/matrix-org/matrix-react-sdk/pull/5855) + * Move user to welcome_page if continuing with previous session + [\#5849](https://github.com/matrix-org/matrix-react-sdk/pull/5849) + * Improve image view + [\#5521](https://github.com/matrix-org/matrix-react-sdk/pull/5521) + * Add a button to reset personal encryption state during login + [\#5819](https://github.com/matrix-org/matrix-react-sdk/pull/5819) + * Fix js-sdk import in SlashCommands + [\#5850](https://github.com/matrix-org/matrix-react-sdk/pull/5850) + * Fix useRoomPowerLevels hook + [\#5854](https://github.com/matrix-org/matrix-react-sdk/pull/5854) + * Prevent state events being rendered with invalid state keys + [\#5851](https://github.com/matrix-org/matrix-react-sdk/pull/5851) + * Give server ACLs a name in 'roles & permissions' tab + [\#5838](https://github.com/matrix-org/matrix-react-sdk/pull/5838) + * Don't hide notification badge on the home space button as it has no menu + [\#5845](https://github.com/matrix-org/matrix-react-sdk/pull/5845) + * User Info hide disambiguation as we always show MXID anyway + [\#5843](https://github.com/matrix-org/matrix-react-sdk/pull/5843) + * Improve kick state to not show if the target was not joined to begin with + [\#5846](https://github.com/matrix-org/matrix-react-sdk/pull/5846) + * Fix space store wrongly switching to a non-space filter + [\#5844](https://github.com/matrix-org/matrix-react-sdk/pull/5844) + * Tweak appearance of invite reason + [\#5847](https://github.com/matrix-org/matrix-react-sdk/pull/5847) + * Update Inter font to v3.18 + [\#5840](https://github.com/matrix-org/matrix-react-sdk/pull/5840) + * Enable sharing historical keys on invite + [\#5839](https://github.com/matrix-org/matrix-react-sdk/pull/5839) + * Add ability to hide post-login encryption setup with customisation point + [\#5834](https://github.com/matrix-org/matrix-react-sdk/pull/5834) + * Use LaTeX and TeX delimiters by default + [\#5515](https://github.com/matrix-org/matrix-react-sdk/pull/5515) + * Clone author's deps fork for Netlify previews + [\#5837](https://github.com/matrix-org/matrix-react-sdk/pull/5837) + * Show drop file UI only if dragging a file + [\#5827](https://github.com/matrix-org/matrix-react-sdk/pull/5827) + * Ignore punctuation when filtering rooms + [\#5824](https://github.com/matrix-org/matrix-react-sdk/pull/5824) + * Resizable CallView + [\#5710](https://github.com/matrix-org/matrix-react-sdk/pull/5710) + Changes in [3.18.0](https://github.com/matrix-org/matrix-react-sdk/releases/tag/v3.18.0) (2021-04-12) ===================================================================================================== [Full Changelog](https://github.com/matrix-org/matrix-react-sdk/compare/v3.18.0-rc.1...v3.18.0) diff --git a/package.json b/package.json index 7c190c68bf..e54de8a96c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "matrix-react-sdk", - "version": "3.18.0", + "version": "3.19.0", "description": "SDK for matrix.org using React", "author": "matrix.org", "repository": { @@ -23,9 +23,7 @@ "package.json" ], "bin": { - "reskindex": "scripts/reskindex.js", - "matrix-gen-i18n": "scripts/gen-i18n.js", - "matrix-prune-i18n": "scripts/prune-i18n.js" + "reskindex": "scripts/reskindex.js" }, "main": "./src/index.js", "matrix_src_main": "./src/index.js", @@ -35,7 +33,7 @@ "prepublishOnly": "yarn build", "i18n": "matrix-gen-i18n", "prunei18n": "matrix-prune-i18n", - "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", + "diff-i18n": "cp src/i18n/strings/en_EN.json src/i18n/strings/en_EN_orig.json && matrix-gen-i18n && matrix-compare-i18n-files src/i18n/strings/en_EN_orig.json src/i18n/strings/en_EN.json", "reskindex": "node scripts/reskindex.js -h header", "reskindex:watch": "node scripts/reskindex.js -h header -w", "rethemendex": "res/css/rethemendex.sh", @@ -51,7 +49,8 @@ "lint:types": "tsc --noEmit --jsx react", "lint:style": "stylelint 'res/css/**/*.scss'", "test": "jest", - "test:e2e": "./test/end-to-end-tests/run.sh --app-url http://localhost:8080" + "test:e2e": "./test/end-to-end-tests/run.sh --app-url http://localhost:8080", + "coverage": "yarn test --coverage" }, "dependencies": { "@babel/runtime": "^7.12.5", @@ -160,6 +159,7 @@ "jest-fetch-mock": "^3.0.3", "matrix-mock-request": "^1.2.3", "matrix-react-test-utils": "^0.2.2", + "matrix-web-i18n": "github:matrix-org/matrix-web-i18n", "olm": "https://packages.matrix.org/npm/olm/olm-3.2.1.tgz", "react-test-renderer": "^16.14.0", "rimraf": "^3.0.2", @@ -189,6 +189,12 @@ }, "transformIgnorePatterns": [ "/node_modules/(?!matrix-js-sdk).+$" + ], + "collectCoverageFrom": [ + "/src/**/*.{js,ts,tsx}" + ], + "coverageReporters": [ + "text" ] } } diff --git a/res/css/_components.scss b/res/css/_components.scss index a2b507aa98..ace4e9abe1 100644 --- a/res/css/_components.scss +++ b/res/css/_components.scss @@ -250,6 +250,8 @@ @import "./views/toasts/_AnalyticsToast.scss"; @import "./views/toasts/_NonUrgentEchoFailureToast.scss"; @import "./views/verification/_VerificationShowSas.scss"; +@import "./views/voice_messages/_PlayPauseButton.scss"; +@import "./views/voice_messages/_PlaybackContainer.scss"; @import "./views/voice_messages/_Waveform.scss"; @import "./views/voip/_CallContainer.scss"; @import "./views/voip/_CallView.scss"; diff --git a/res/css/structures/_FilePanel.scss b/res/css/structures/_FilePanel.scss index 2aa068b674..7b975110e1 100644 --- a/res/css/structures/_FilePanel.scss +++ b/res/css/structures/_FilePanel.scss @@ -22,7 +22,6 @@ limitations under the License. } .mx_FilePanel .mx_RoomView_messageListWrapper { - margin-right: 20px; flex-direction: row; align-items: center; justify-content: center; diff --git a/res/css/structures/_RoomStatusBar.scss b/res/css/structures/_RoomStatusBar.scss index 5bf2aee3ae..8cc00aba0f 100644 --- a/res/css/structures/_RoomStatusBar.scss +++ b/res/css/structures/_RoomStatusBar.scss @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -.mx_RoomStatusBar { +.mx_RoomStatusBar:not(.mx_RoomStatusBar_unsentMessages) { margin-left: 65px; min-height: 50px; } @@ -68,6 +68,99 @@ limitations under the License. min-height: 58px; } +.mx_RoomStatusBar_unsentMessages { + > div[role="alert"] { + // cheat some basic alignment + display: flex; + align-items: center; + min-height: 70px; + margin: 12px; + padding-left: 16px; + background-color: $header-panel-bg-color; + border-radius: 4px; + } + + .mx_RoomStatusBar_unsentBadge { + margin-right: 12px; + + .mx_NotificationBadge { + // Override sizing from the default badge + width: 24px !important; + height: 24px !important; + border-radius: 24px !important; + + .mx_NotificationBadge_count { + font-size: $font-16px !important; // override default + } + } + } + + .mx_RoomStatusBar_unsentTitle { + color: $warning-color; + font-size: $font-15px; + } + + .mx_RoomStatusBar_unsentDescription { + font-size: $font-12px; + } + + .mx_RoomStatusBar_unsentButtonBar { + flex-grow: 1; + text-align: right; + margin-right: 22px; + color: $muted-fg-color; + + .mx_AccessibleButton { + padding: 5px 10px; + padding-left: 28px; // 16px for the icon, 2px margin to text, 10px regular padding + display: inline-block; + position: relative; + + &:nth-child(2) { + border-left: 1px solid $resend-button-divider-color; + } + + &::before { + content: ''; + position: absolute; + left: 10px; // inset for regular button padding + background-color: $muted-fg-color; + mask-repeat: no-repeat; + mask-position: center; + mask-size: contain; + } + + &.mx_RoomStatusBar_unsentCancelAllBtn::before { + mask-image: url('$(res)/img/element-icons/trashcan.svg'); + width: 12px; + height: 16px; + top: calc(50% - 8px); // text sizes are dynamic + } + + &.mx_RoomStatusBar_unsentResendAllBtn { + padding-left: 34px; // 28px from above, but +6px to account for the wider icon + + &::before { + mask-image: url('$(res)/img/element-icons/retry.svg'); + width: 18px; + height: 18px; + top: calc(50% - 9px); // text sizes are dynamic + } + } + } + + .mx_InlineSpinner { + vertical-align: middle; + margin-right: 5px; + top: 1px; // just to help the vertical alignment be slightly better + + & + span { + margin-right: 10px; // same margin/padding as the rightmost button + } + } + } +} + .mx_RoomStatusBar_connectionLostBar img { padding-left: 10px; padding-right: 10px; @@ -103,7 +196,7 @@ limitations under the License. } .mx_MatrixChat_useCompactLayout { - .mx_RoomStatusBar { + .mx_RoomStatusBar:not(.mx_RoomStatusBar_unsentMessages) { min-height: 40px; } diff --git a/res/css/structures/_SpacePanel.scss b/res/css/structures/_SpacePanel.scss index 202eaf0f4d..59f2ea947c 100644 --- a/res/css/structures/_SpacePanel.scss +++ b/res/css/structures/_SpacePanel.scss @@ -35,7 +35,7 @@ $activeBorderColor: $secondary-fg-color; .mx_SpacePanel_spaceTreeWrapper { flex: 1; - overflow-y: scroll; + padding: 8px 8px 16px 0; } .mx_SpacePanel_toggleCollapse { @@ -59,11 +59,10 @@ $activeBorderColor: $secondary-fg-color; margin: 0; list-style: none; padding: 0; - padding-left: 16px; - } - .mx_AutoHideScrollbar { - padding: 8px 0 16px; + > .mx_SpaceItem { + padding-left: 16px; + } } .mx_SpaceButton_toggleCollapse { diff --git a/res/css/structures/_SpaceRoomDirectory.scss b/res/css/structures/_SpaceRoomDirectory.scss index dcceee6371..c7d087d8e0 100644 --- a/res/css/structures/_SpaceRoomDirectory.scss +++ b/res/css/structures/_SpaceRoomDirectory.scss @@ -26,7 +26,10 @@ limitations under the License. word-break: break-word; display: flex; flex-direction: column; +} +.mx_SpaceRoomDirectory, +.mx_SpaceRoomView_landing { .mx_Dialog_title { display: flex; @@ -56,65 +59,63 @@ limitations under the License. } } - .mx_Dialog_content { - .mx_AccessibleButton_kind_link { - padding: 0; - } + .mx_AccessibleButton_kind_link { + padding: 0; + } - .mx_SearchBox { - margin: 24px 0 16px; - } + .mx_SearchBox { + margin: 24px 0 16px; + } - .mx_SpaceRoomDirectory_noResults { - text-align: center; + .mx_SpaceRoomDirectory_noResults { + text-align: center; - > div { - font-size: $font-15px; - line-height: $font-24px; - color: $secondary-fg-color; - } - } - - .mx_SpaceRoomDirectory_listHeader { - display: flex; - min-height: 32px; - align-items: center; + > div { font-size: $font-15px; line-height: $font-24px; - color: $primary-fg-color; + color: $secondary-fg-color; + } + } - .mx_AccessibleButton { - padding: 2px 8px; - font-weight: normal; + .mx_SpaceRoomDirectory_listHeader { + display: flex; + min-height: 32px; + align-items: center; + font-size: $font-15px; + line-height: $font-24px; + color: $primary-fg-color; - & + .mx_AccessibleButton { - margin-left: 16px; - } - } + .mx_AccessibleButton { + padding: 2px 8px; + font-weight: normal; - > span { - margin-left: auto; + & + .mx_AccessibleButton { + margin-left: 16px; } } - .mx_SpaceRoomDirectory_error { - position: relative; - font-weight: $font-semi-bold; - color: $notice-primary-color; - font-size: $font-15px; - line-height: $font-18px; - margin: 20px auto 12px; - padding-left: 24px; - width: max-content; + > span { + margin-left: auto; + } + } - &::before { - content: ""; - position: absolute; - height: 16px; - width: 16px; - left: 0; - background-image: url("$(res)/img/element-icons/warning-badge.svg"); - } + .mx_SpaceRoomDirectory_error { + position: relative; + font-weight: $font-semi-bold; + color: $notice-primary-color; + font-size: $font-15px; + line-height: $font-18px; + margin: 20px auto 12px; + padding-left: 24px; + width: max-content; + + &::before { + content: ""; + position: absolute; + height: 16px; + width: 16px; + left: 0; + background-image: url("$(res)/img/element-icons/warning-badge.svg"); } } } diff --git a/res/css/structures/_SpaceRoomView.scss b/res/css/structures/_SpaceRoomView.scss index 2e7cfb55d9..553919d862 100644 --- a/res/css/structures/_SpaceRoomView.scss +++ b/res/css/structures/_SpaceRoomView.scss @@ -81,6 +81,16 @@ $SpaceRoomViewInnerWidth: 428px; color: $secondary-fg-color; margin-top: 12px; margin-bottom: 24px; + max-width: $SpaceRoomViewInnerWidth; + } + + .mx_AddExistingToSpace { + max-width: $SpaceRoomViewInnerWidth; + + .mx_AddExistingToSpace_content { + height: calc(100vh - 360px); + max-height: 400px; + } } .mx_SpaceRoomView_buttons { @@ -214,45 +224,15 @@ $SpaceRoomViewInnerWidth: 428px; .mx_SpaceRoomView_info { display: inline-block; - margin: 0; + margin: 0 auto 0 0; } .mx_FacePile { display: inline-block; - margin-left: auto; margin-right: 12px; .mx_FacePile_faces { cursor: pointer; - - > span:hover { - .mx_BaseAvatar { - filter: brightness(0.8); - } - } - - > span:first-child { - position: relative; - - .mx_BaseAvatar { - filter: brightness(0.8); - } - - &::before { - content: ""; - z-index: 1; - position: absolute; - top: 0; - left: 0; - height: 30px; - width: 30px; - background: #ffffff; // white icon fill - mask-position: center; - mask-size: 24px; - mask-repeat: no-repeat; - mask-image: url('$(res)/img/element-icons/room/ellipsis.svg'); - } - } } } diff --git a/res/css/views/dialogs/_AddExistingToSpaceDialog.scss b/res/css/views/dialogs/_AddExistingToSpaceDialog.scss index a7cfd7bde6..84f965e6bd 100644 --- a/res/css/views/dialogs/_AddExistingToSpaceDialog.scss +++ b/res/css/views/dialogs/_AddExistingToSpaceDialog.scss @@ -21,6 +21,66 @@ limitations under the License. } } +.mx_AddExistingToSpace { + .mx_SearchBox { + // To match the space around the title + margin: 0 0 15px 0; + flex-grow: 0; + } + + .mx_AddExistingToSpace_content { + flex-grow: 1; + } + + .mx_AddExistingToSpace_noResults { + display: block; + margin-top: 24px; + } + + .mx_AddExistingToSpace_section { + &:not(:first-child) { + margin-top: 24px; + } + + > h3 { + margin: 0; + color: $secondary-fg-color; + font-size: $font-12px; + font-weight: $font-semi-bold; + line-height: $font-15px; + } + + .mx_AddExistingToSpace_entry { + display: flex; + margin-top: 12px; + + .mx_BaseAvatar { + margin-right: 12px; + } + + .mx_AddExistingToSpace_entry_name { + font-size: $font-15px; + line-height: 30px; + flex-grow: 1; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + margin-right: 12px; + } + + .mx_Checkbox { + align-items: center; + } + } + } + + .mx_AddExistingToSpace_section_spaces { + .mx_BaseAvatar_image { + border-radius: 8px; + } + } +} + .mx_AddExistingToSpaceDialog { width: 480px; color: $primary-fg-color; @@ -100,11 +160,6 @@ limitations under the License. } } - .mx_SearchBox { - margin: 0; - flex-grow: 0; - } - .mx_AddExistingToSpaceDialog_errorText { font-weight: $font-semi-bold; font-size: $font-12px; @@ -113,52 +168,8 @@ limitations under the License. margin-bottom: 28px; } - .mx_AddExistingToSpaceDialog_content { - flex-grow: 1; - - .mx_AddExistingToSpaceDialog_noResults { - display: block; - margin-top: 24px; - } - } - - .mx_AddExistingToSpaceDialog_section { - margin-top: 24px; - - > h3 { - margin: 0; - color: $secondary-fg-color; - font-size: $font-12px; - font-weight: $font-semi-bold; - line-height: $font-15px; - } - - .mx_AddExistingToSpaceDialog_entry { - display: flex; - margin-top: 12px; - - .mx_BaseAvatar { - margin-right: 12px; - } - - .mx_AddExistingToSpaceDialog_entry_name { - font-size: $font-15px; - line-height: 30px; - flex-grow: 1; - } - - .mx_FormButton { - min-width: 92px; - font-weight: normal; - box-sizing: border-box; - } - } - } - - .mx_AddExistingToSpaceDialog_section_spaces { - .mx_BaseAvatar_image { - border-radius: 8px; - } + .mx_AddExistingToSpace { + display: contents; } .mx_AddExistingToSpaceDialog_footer { @@ -189,8 +200,4 @@ limitations under the License. padding: 0; } } - - .mx_FormButton { - padding: 8px 22px; - } } diff --git a/res/css/views/elements/_FacePile.scss b/res/css/views/elements/_FacePile.scss index 9a992f59d1..c691baffb5 100644 --- a/res/css/views/elements/_FacePile.scss +++ b/res/css/views/elements/_FacePile.scss @@ -20,7 +20,7 @@ limitations under the License. flex-direction: row-reverse; vertical-align: middle; - > span + span { + > .mx_FacePile_face + .mx_FacePile_face { margin-right: -8px; } @@ -31,9 +31,32 @@ limitations under the License. .mx_BaseAvatar_initial { margin: 1px; // to offset the border on the image } + + .mx_FacePile_more { + position: relative; + border-radius: 100%; + width: 30px; + height: 30px; + background-color: $groupFilterPanel-bg-color; + + &::before { + content: ""; + z-index: 1; + position: absolute; + top: 0; + left: 0; + height: inherit; + width: inherit; + background: $tertiary-fg-color; + mask-position: center; + mask-size: 20px; + mask-repeat: no-repeat; + mask-image: url('$(res)/img/element-icons/room/ellipsis.svg'); + } + } } - > span { + .mx_FacePile_summary { margin-left: 12px; font-size: $font-14px; line-height: $font-24px; diff --git a/res/css/views/elements/_ImageView.scss b/res/css/views/elements/_ImageView.scss index 93ebcc2d56..71035dadc3 100644 --- a/res/css/views/elements/_ImageView.scss +++ b/res/css/views/elements/_ImageView.scss @@ -31,8 +31,7 @@ limitations under the License. .mx_ImageView_image { pointer-events: all; - max-width: 95%; - max-height: 95%; + flex-shrink: 0; } .mx_ImageView_panel { diff --git a/res/css/views/messages/_MessageActionBar.scss b/res/css/views/messages/_MessageActionBar.scss index 1254b496b5..3ecbef0d1f 100644 --- a/res/css/views/messages/_MessageActionBar.scss +++ b/res/css/views/messages/_MessageActionBar.scss @@ -105,3 +105,11 @@ limitations under the License. .mx_MessageActionBar_optionsButton::after { mask-image: url('$(res)/img/element-icons/context-menu.svg'); } + +.mx_MessageActionBar_resendButton::after { + mask-image: url('$(res)/img/element-icons/retry.svg'); +} + +.mx_MessageActionBar_cancelButton::after { + mask-image: url('$(res)/img/element-icons/trashcan.svg'); +} diff --git a/res/css/views/messages/_ReactionsRowButton.scss b/res/css/views/messages/_ReactionsRowButton.scss index 7158ffc027..c132fa5a0f 100644 --- a/res/css/views/messages/_ReactionsRowButton.scss +++ b/res/css/views/messages/_ReactionsRowButton.scss @@ -34,6 +34,10 @@ limitations under the License. border-color: $reaction-row-button-selected-border-color; } + &.mx_AccessibleButton_disabled { + cursor: not-allowed; + } + .mx_ReactionsRowButton_content { max-width: 100px; overflow: hidden; diff --git a/res/css/views/rooms/_EventTile.scss b/res/css/views/rooms/_EventTile.scss index 2b3e179c54..5d1dd04383 100644 --- a/res/css/views/rooms/_EventTile.scss +++ b/res/css/views/rooms/_EventTile.scss @@ -214,10 +214,6 @@ $left-gutter: 64px; color: $accent-fg-color; } -.mx_EventTile_notSent { - color: $event-notsent-color; -} - .mx_EventTile_receiptSent, .mx_EventTile_receiptSending { // We don't use `position: relative` on the element because then it won't line diff --git a/res/css/views/rooms/_RoomSublist.scss b/res/css/views/rooms/_RoomSublist.scss index 92a475694e..9d52e40819 100644 --- a/res/css/views/rooms/_RoomSublist.scss +++ b/res/css/views/rooms/_RoomSublist.scss @@ -18,6 +18,10 @@ limitations under the License. margin-left: 8px; margin-bottom: 4px; + &.mx_RoomSublist_hidden { + display: none; + } + .mx_RoomSublist_headerContainer { // Create a flexbox to make alignment easy display: flex; @@ -37,7 +41,9 @@ limitations under the License. // The combined height must be set in the LeftPanel component for sticky headers // to work correctly. padding-bottom: 8px; - height: 24px; + // Allow the container to collapse on itself if its children + // are not in the normal document flow + max-height: 24px; color: $roomlist-header-color; .mx_RoomSublist_stickable { diff --git a/res/css/views/rooms/_VoiceRecordComposerTile.scss b/res/css/views/rooms/_VoiceRecordComposerTile.scss index 8100a03890..e99e1a00e1 100644 --- a/res/css/views/rooms/_VoiceRecordComposerTile.scss +++ b/res/css/views/rooms/_VoiceRecordComposerTile.scss @@ -35,44 +35,40 @@ limitations under the License. } } -.mx_VoiceRecordComposerTile_waveformContainer { - padding: 5px; - padding-right: 4px; // there's 1px from the waveform itself, so account for that - padding-left: 15px; // +10px for the live circle, +5px for regular padding - background-color: $voice-record-waveform-bg-color; - border-radius: 12px; - margin-right: 12px; // isolate from stop button +.mx_VoiceRecordComposerTile_delete { + width: 14px; // w&h are size of icon + height: 18px; + vertical-align: middle; + margin-right: 7px; // distance from left edge of waveform container (container has some margin too) + background-color: $muted-fg-color; + mask-repeat: no-repeat; + mask-size: contain; + mask-image: url('$(res)/img/element-icons/trashcan.svg'); +} - // Cheat at alignment a bit - display: flex; - align-items: center; +.mx_VoiceMessagePrimaryContainer { + // Note: remaining class properties are in the PlayerContainer CSS. + + margin: 6px; // force the composer area to put a gutter around us + margin-right: 12px; // isolate from stop button position: relative; // important for the live circle - color: $voice-record-waveform-fg-color; - font-size: $font-14px; + &.mx_VoiceRecordComposerTile_recording { + padding-left: 16px; // +10px for the live circle, +6px for regular padding - &::before { - animation: recording-pulse 2s infinite; + &::before { + animation: recording-pulse 2s infinite; - content: ''; - background-color: $voice-record-live-circle-color; - width: 10px; - height: 10px; - position: absolute; - left: 8px; - top: 16px; // vertically center - border-radius: 10px; - } - - .mx_Waveform_bar { - background-color: $voice-record-waveform-fg-color; - } - - .mx_Clock { - padding-right: 8px; // isolate from waveform - padding-left: 10px; // isolate from live circle - width: 42px; // we're not using a monospace font, so fake it + content: ''; + background-color: $voice-record-live-circle-color; + width: 10px; + height: 10px; + position: absolute; + left: 8px; + top: 16px; // vertically center + border-radius: 10px; + } } } diff --git a/res/css/views/voice_messages/_PlayPauseButton.scss b/res/css/views/voice_messages/_PlayPauseButton.scss new file mode 100644 index 0000000000..c8ab162694 --- /dev/null +++ b/res/css/views/voice_messages/_PlayPauseButton.scss @@ -0,0 +1,51 @@ +/* +Copyright 2021 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_PlayPauseButton { + position: relative; + width: 32px; + height: 32px; + border-radius: 32px; + background-color: $primary-bg-color; + + &::before { + content: ''; + position: absolute; // sizing varies by icon + background-color: $muted-fg-color; + mask-repeat: no-repeat; + mask-size: contain; + } + + &.mx_PlayPauseButton_disabled::before { + opacity: 0.5; + } + + &.mx_PlayPauseButton_play::before { + width: 13px; + height: 16px; + top: 8px; // center + left: 12px; // center + mask-image: url('$(res)/img/element-icons/play.svg'); + } + + &.mx_PlayPauseButton_pause::before { + width: 10px; + height: 12px; + top: 10px; // center + left: 11px; // center + mask-image: url('$(res)/img/element-icons/pause.svg'); + } +} diff --git a/res/css/views/voice_messages/_PlaybackContainer.scss b/res/css/views/voice_messages/_PlaybackContainer.scss new file mode 100644 index 0000000000..49bd81ef81 --- /dev/null +++ b/res/css/views/voice_messages/_PlaybackContainer.scss @@ -0,0 +1,54 @@ +/* +Copyright 2021 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. +*/ + +// Dev note: there's no actual component called . These classes +// are shared amongst multiple voice message components. + +// Container for live recording and playback controls +.mx_VoiceMessagePrimaryContainer { + padding: 6px; // makes us 4px taller than the send/stop button + padding-right: 5px; // there's 1px from the waveform itself, so account for that + background-color: $voice-record-waveform-bg-color; + border-radius: 12px; + + // Cheat at alignment a bit + display: flex; + align-items: center; + + color: $voice-record-waveform-fg-color; + font-size: $font-14px; + + .mx_Waveform { + // We want the bars to be 2px shorter than the play/pause button in the waveform control + height: 28px; // default is 30px, so we're subtracting the 2px border off the bars + + .mx_Waveform_bar { + background-color: $voice-record-waveform-incomplete-fg-color; + + &.mx_Waveform_bar_100pct { + // Small animation to remove the mechanical feel of progress + transition: background-color 250ms ease; + background-color: $voice-record-waveform-fg-color; + } + } + } + + .mx_Clock { + padding-right: 4px; // isolate from waveform + padding-left: 8px; // isolate from live circle + width: 40px; // we're not using a monospace font, so fake it + } +} diff --git a/res/css/views/voip/_CallView.scss b/res/css/views/voip/_CallView.scss index d13272c8c0..7292e325df 100644 --- a/res/css/views/voip/_CallView.scss +++ b/res/css/views/voip/_CallView.scss @@ -17,7 +17,7 @@ limitations under the License. .mx_CallView { border-radius: 8px; - background-color: $voipcall-plinth-color; + background-color: $dark-panel-bg-color; padding-left: 8px; padding-right: 8px; // XXX: CallContainer sets pointer-events: none - should probably be set back in a better place @@ -40,7 +40,8 @@ limitations under the License. width: 320px; padding-bottom: 8px; margin-top: 10px; - box-shadow: 0px 14px 24px rgba(0, 0, 0, 0.08); + background-color: $voipcall-plinth-color; + box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.20); border-radius: 8px; .mx_CallView_voice { diff --git a/res/img/element-icons/pause.svg b/res/img/element-icons/pause.svg new file mode 100644 index 0000000000..293c0a10d8 --- /dev/null +++ b/res/img/element-icons/pause.svg @@ -0,0 +1,4 @@ + + + + diff --git a/res/img/element-icons/play.svg b/res/img/element-icons/play.svg new file mode 100644 index 0000000000..339e20b729 --- /dev/null +++ b/res/img/element-icons/play.svg @@ -0,0 +1,3 @@ + + + diff --git a/res/img/element-icons/retry.svg b/res/img/element-icons/retry.svg new file mode 100644 index 0000000000..09448d6458 --- /dev/null +++ b/res/img/element-icons/retry.svg @@ -0,0 +1,3 @@ + + + diff --git a/res/img/element-icons/trashcan.svg b/res/img/element-icons/trashcan.svg new file mode 100644 index 0000000000..f8fb8b5c46 --- /dev/null +++ b/res/img/element-icons/trashcan.svg @@ -0,0 +1,3 @@ + + + diff --git a/res/themes/dark/css/_dark.scss b/res/themes/dark/css/_dark.scss index bd7057c3e4..f9983dce9e 100644 --- a/res/themes/dark/css/_dark.scss +++ b/res/themes/dark/css/_dark.scss @@ -63,6 +63,8 @@ $input-invalid-border-color: $warning-color; $field-focused-label-bg-color: $bg-color; +$resend-button-divider-color: #b9bec64a; // muted-text with a 4A opacity. + // scrollbars $scrollbar-thumb-color: rgba(255, 255, 255, 0.2); $scrollbar-track-color: transparent; @@ -85,7 +87,7 @@ $dialog-close-fg-color: #9fa9ba; $dialog-background-bg-color: $header-panel-bg-color; $lightbox-background-bg-color: #000; -$lightbox-background-bg-opacity: 85%; +$lightbox-background-bg-opacity: 0.85; $settings-grey-fg-color: #a2a2a2; $settings-profile-placeholder-bg-color: #21262c; @@ -110,7 +112,7 @@ $header-divider-color: $header-panel-text-primary-color; $composer-e2e-icon-color: $header-panel-text-primary-color; // this probably shouldn't have it's own colour -$voipcall-plinth-color: #21262c; +$voipcall-plinth-color: #394049; // ******************** diff --git a/res/themes/legacy-dark/css/_legacy-dark.scss b/res/themes/legacy-dark/css/_legacy-dark.scss index 9b2365a621..194e89e548 100644 --- a/res/themes/legacy-dark/css/_legacy-dark.scss +++ b/res/themes/legacy-dark/css/_legacy-dark.scss @@ -61,6 +61,8 @@ $input-invalid-border-color: $warning-color; $field-focused-label-bg-color: $bg-color; +$resend-button-divider-color: $muted-fg-color; + // scrollbars $scrollbar-thumb-color: rgba(255, 255, 255, 0.2); $scrollbar-track-color: transparent; @@ -83,7 +85,7 @@ $dialog-close-fg-color: #9fa9ba; $dialog-background-bg-color: $header-panel-bg-color; $lightbox-background-bg-color: #000; -$lightbox-background-bg-opacity: 85%; +$lightbox-background-bg-opacity: 0.85; $settings-grey-fg-color: #a2a2a2; $settings-profile-placeholder-bg-color: #e7e7e7; @@ -107,7 +109,7 @@ $header-divider-color: $header-panel-text-primary-color; $composer-e2e-icon-color: $header-panel-text-primary-color; // this probably shouldn't have it's own colour -$voipcall-plinth-color: #f2f5f8; +$voipcall-plinth-color: #394049; // ******************** diff --git a/res/themes/legacy-light/css/_legacy-light.scss b/res/themes/legacy-light/css/_legacy-light.scss index 0956f433b2..d7352e5684 100644 --- a/res/themes/legacy-light/css/_legacy-light.scss +++ b/res/themes/legacy-light/css/_legacy-light.scss @@ -97,6 +97,8 @@ $input-invalid-border-color: $warning-color; $field-focused-label-bg-color: #ffffff; +$resend-button-divider-color: $input-darker-bg-color; + $button-bg-color: $accent-color; $button-fg-color: white; @@ -127,7 +129,7 @@ $dialog-close-fg-color: #c1c1c1; $dialog-background-bg-color: #e9e9e9; $lightbox-background-bg-color: #000; -$lightbox-background-bg-opacity: 95%; +$lightbox-background-bg-opacity: 0.95; $imagebody-giflabel: rgba(0, 0, 0, 0.7); $imagebody-giflabel-border: rgba(0, 0, 0, 0.2); @@ -174,7 +176,7 @@ $composer-e2e-icon-color: #91a1c0; $header-divider-color: #91a1c0; // this probably shouldn't have it's own colour -$voipcall-plinth-color: #f2f5f8; +$voipcall-plinth-color: #F4F6FA; // ******************** @@ -194,6 +196,7 @@ $voice-record-stop-border-color: #E3E8F0; $voice-record-stop-symbol-color: #ff4b55; $voice-record-waveform-bg-color: #E3E8F0; $voice-record-waveform-fg-color: $muted-fg-color; +$voice-record-waveform-incomplete-fg-color: #C1C6CD; $voice-record-live-circle-color: #ff4b55; $roomtile-preview-color: #9e9e9e; diff --git a/res/themes/light/css/_light.scss b/res/themes/light/css/_light.scss index b307dbaba3..20ccc2ee41 100644 --- a/res/themes/light/css/_light.scss +++ b/res/themes/light/css/_light.scss @@ -91,6 +91,8 @@ $field-focused-label-bg-color: #ffffff; $button-bg-color: $accent-color; $button-fg-color: white; +$resend-button-divider-color: $input-darker-bg-color; + // apart from login forms, which have stronger border $strong-input-border-color: #c7c7c7; @@ -118,7 +120,7 @@ $dialog-close-fg-color: #c1c1c1; $dialog-background-bg-color: #e9e9e9; $lightbox-background-bg-color: #000; -$lightbox-background-bg-opacity: 95%; +$lightbox-background-bg-opacity: 0.95; $imagebody-giflabel: rgba(0, 0, 0, 0.7); $imagebody-giflabel-border: rgba(0, 0, 0, 0.2); @@ -165,7 +167,7 @@ $composer-e2e-icon-color: #91A1C0; $header-divider-color: #91A1C0; // this probably shouldn't have it's own colour -$voipcall-plinth-color: #f2f5f8; +$voipcall-plinth-color: #F4F6FA; // ******************** @@ -184,6 +186,7 @@ $voice-record-stop-border-color: #E3E8F0; $voice-record-stop-symbol-color: #ff4b55; // $warning-color, but without letting people change it in themes $voice-record-waveform-bg-color: #E3E8F0; $voice-record-waveform-fg-color: $muted-fg-color; +$voice-record-waveform-incomplete-fg-color: #C1C6CD; $voice-record-live-circle-color: #ff4b55; // $warning-color, but without letting people change it in themes $roomtile-preview-color: $secondary-fg-color; diff --git a/scripts/compare-file.js b/scripts/compare-file.js deleted file mode 100644 index f53275ebfa..0000000000 --- a/scripts/compare-file.js +++ /dev/null @@ -1,10 +0,0 @@ -const fs = require("fs"); - -if (process.argv.length < 4) throw new Error("Missing source and target file arguments"); - -const sourceFile = fs.readFileSync(process.argv[2], 'utf8'); -const targetFile = fs.readFileSync(process.argv[3], 'utf8'); - -if (sourceFile !== targetFile) { - throw new Error("Files do not match"); -} diff --git a/scripts/gen-i18n.js b/scripts/gen-i18n.js deleted file mode 100755 index 91733469f7..0000000000 --- a/scripts/gen-i18n.js +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env node - -/* -Copyright 2017 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. -*/ - -/** - * Regenerates the translations en_EN file by walking the source tree and - * parsing each file with the appropriate parser. Emits a JSON file with the - * translatable strings mapped to themselves in the order they appeared - * in the files and grouped by the file they appeared in. - * - * Usage: node scripts/gen-i18n.js - */ -const fs = require('fs'); -const path = require('path'); - -const walk = require('walk'); - -const parser = require("@babel/parser"); -const traverse = require("@babel/traverse"); - -const TRANSLATIONS_FUNCS = ['_t', '_td']; - -const INPUT_TRANSLATIONS_FILE = 'src/i18n/strings/en_EN.json'; -const OUTPUT_FILE = 'src/i18n/strings/en_EN.json'; - -// NB. The sync version of walk is broken for single files so we walk -// all of res rather than just res/home.html. -// https://git.daplie.com/Daplie/node-walk/merge_requests/1 fixes it, -// or if we get bored waiting for it to be merged, we could switch -// to a project that's actively maintained. -const SEARCH_PATHS = ['src', 'res']; - -function getObjectValue(obj, key) { - for (const prop of obj.properties) { - if (prop.key.type === 'Identifier' && prop.key.name === key) { - return prop.value; - } - } - return null; -} - -function getTKey(arg) { - if (arg.type === 'Literal' || arg.type === "StringLiteral") { - return arg.value; - } else if (arg.type === 'BinaryExpression' && arg.operator === '+') { - return getTKey(arg.left) + getTKey(arg.right); - } else if (arg.type === 'TemplateLiteral') { - return arg.quasis.map((q) => { - return q.value.raw; - }).join(''); - } - return null; -} - -function getFormatStrings(str) { - // Match anything that starts with % - // We could make a regex that matched the full placeholder, but this - // would just not match invalid placeholders and so wouldn't help us - // detect the invalid ones. - // Also note that for simplicity, this just matches a % character and then - // anything up to the next % character (or a single %, or end of string). - const formatStringRe = /%([^%]+|%|$)/g; - const formatStrings = new Set(); - - let match; - while ( (match = formatStringRe.exec(str)) !== null ) { - const placeholder = match[1]; // Minus the leading '%' - if (placeholder === '%') continue; // Literal % is %% - - const placeholderMatch = placeholder.match(/^\((.*?)\)(.)/); - if (placeholderMatch === null) { - throw new Error("Invalid format specifier: '"+match[0]+"'"); - } - if (placeholderMatch.length < 3) { - throw new Error("Malformed format specifier"); - } - const placeholderName = placeholderMatch[1]; - const placeholderFormat = placeholderMatch[2]; - - if (placeholderFormat !== 's') { - throw new Error(`'${placeholderFormat}' used as format character: you probably meant 's'`); - } - - formatStrings.add(placeholderName); - } - - return formatStrings; -} - -function getTranslationsJs(file) { - const contents = fs.readFileSync(file, { encoding: 'utf8' }); - - const trs = new Set(); - - try { - const plugins = [ - // https://babeljs.io/docs/en/babel-parser#plugins - "classProperties", - "objectRestSpread", - "throwExpressions", - "exportDefaultFrom", - "decorators-legacy", - ]; - - if (file.endsWith(".js") || file.endsWith(".jsx")) { - // all JS is assumed to be flow or react - plugins.push("flow", "jsx"); - } else if (file.endsWith(".ts")) { - // TS can't use JSX unless it's a TSX file (otherwise angle casts fail) - plugins.push("typescript"); - } else if (file.endsWith(".tsx")) { - // When the file is a TSX file though, enable JSX parsing - plugins.push("typescript", "jsx"); - } - - const babelParsed = parser.parse(contents, { - allowImportExportEverywhere: true, - errorRecovery: true, - sourceFilename: file, - tokens: true, - plugins, - }); - traverse.default(babelParsed, { - enter: (p) => { - const node = p.node; - if (p.isCallExpression() && node.callee && TRANSLATIONS_FUNCS.includes(node.callee.name)) { - const tKey = getTKey(node.arguments[0]); - - // This happens whenever we call _t with non-literals (ie. whenever we've - // had to use a _td to compensate) so is expected. - if (tKey === null) return; - - // check the format string against the args - // We only check _t: _td has no args - if (node.callee.name === '_t') { - try { - const placeholders = getFormatStrings(tKey); - for (const placeholder of placeholders) { - if (node.arguments.length < 2) { - throw new Error(`Placeholder found ('${placeholder}') but no substitutions given`); - } - const value = getObjectValue(node.arguments[1], placeholder); - if (value === null) { - throw new Error(`No value found for placeholder '${placeholder}'`); - } - } - - // Validate tag replacements - if (node.arguments.length > 2) { - const tagMap = node.arguments[2]; - for (const prop of tagMap.properties || []) { - if (prop.key.type === 'Literal') { - const tag = prop.key.value; - // RegExp same as in src/languageHandler.js - const regexp = new RegExp(`(<${tag}>(.*?)<\\/${tag}>|<${tag}>|<${tag}\\s*\\/>)`); - if (!tKey.match(regexp)) { - throw new Error(`No match for ${regexp} in ${tKey}`); - } - } - } - } - - } catch (e) { - console.log(); - console.error(`ERROR: ${file}:${node.loc.start.line} ${tKey}`); - console.error(e); - process.exit(1); - } - } - - let isPlural = false; - if (node.arguments.length > 1 && node.arguments[1].type === 'ObjectExpression') { - const countVal = getObjectValue(node.arguments[1], 'count'); - if (countVal) { - isPlural = true; - } - } - - if (isPlural) { - trs.add(tKey + "|other"); - const plurals = enPlurals[tKey]; - if (plurals) { - for (const pluralType of Object.keys(plurals)) { - trs.add(tKey + "|" + pluralType); - } - } - } else { - trs.add(tKey); - } - } - }, - }); - } catch (e) { - console.error(e); - process.exit(1); - } - - return trs; -} - -function getTranslationsOther(file) { - const contents = fs.readFileSync(file, { encoding: 'utf8' }); - - const trs = new Set(); - - // Taken from element-web src/components/structures/HomePage.js - const translationsRegex = /_t\(['"]([\s\S]*?)['"]\)/mg; - let matches; - while (matches = translationsRegex.exec(contents)) { - trs.add(matches[1]); - } - return trs; -} - -// gather en_EN plural strings from the input translations file: -// the en_EN strings are all in the source with the exception of -// pluralised strings, which we need to pull in from elsewhere. -const inputTranslationsRaw = JSON.parse(fs.readFileSync(INPUT_TRANSLATIONS_FILE, { encoding: 'utf8' })); -const enPlurals = {}; - -for (const key of Object.keys(inputTranslationsRaw)) { - const parts = key.split("|"); - if (parts.length > 1) { - const plurals = enPlurals[parts[0]] || {}; - plurals[parts[1]] = inputTranslationsRaw[key]; - enPlurals[parts[0]] = plurals; - } -} - -const translatables = new Set(); - -const walkOpts = { - listeners: { - names: function(root, nodeNamesArray) { - // Sort the names case insensitively and alphabetically to - // maintain some sense of order between the different strings. - nodeNamesArray.sort((a, b) => { - a = a.toLowerCase(); - b = b.toLowerCase(); - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); - }, - file: function(root, fileStats, next) { - const fullPath = path.join(root, fileStats.name); - - let trs; - if (fileStats.name.endsWith('.js') || fileStats.name.endsWith('.ts') || fileStats.name.endsWith('.tsx')) { - trs = getTranslationsJs(fullPath); - } else if (fileStats.name.endsWith('.html')) { - trs = getTranslationsOther(fullPath); - } else { - return; - } - console.log(`${fullPath} (${trs.size} strings)`); - for (const tr of trs.values()) { - // Convert DOS line endings to unix - translatables.add(tr.replace(/\r\n/g, "\n")); - } - }, - } -}; - -for (const path of SEARCH_PATHS) { - if (fs.existsSync(path)) { - walk.walkSync(path, walkOpts); - } -} - -const trObj = {}; -for (const tr of translatables) { - if (tr.includes("|")) { - if (inputTranslationsRaw[tr]) { - trObj[tr] = inputTranslationsRaw[tr]; - } else { - trObj[tr] = tr.split("|")[0]; - } - } else { - trObj[tr] = tr; - } -} - -fs.writeFileSync( - OUTPUT_FILE, - JSON.stringify(trObj, translatables.values(), 4) + "\n" -); - -console.log(); -console.log(`Wrote ${translatables.size} strings to ${OUTPUT_FILE}`); diff --git a/scripts/prune-i18n.js b/scripts/prune-i18n.js deleted file mode 100755 index b4fe8d69f5..0000000000 --- a/scripts/prune-i18n.js +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env node - -/* -Copyright 2017 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. -*/ - -/* - * Looks through all the translation files and removes any strings - * which don't appear in en_EN.json. - * Use this if you remove a translation, but merge any outstanding changes - * from weblate first or you'll need to resolve the conflict in weblate. - */ - -const fs = require('fs'); -const path = require('path'); - -const I18NDIR = 'src/i18n/strings'; - -const enStringsRaw = JSON.parse(fs.readFileSync(path.join(I18NDIR, 'en_EN.json'))); - -const enStrings = new Set(); -for (const str of Object.keys(enStringsRaw)) { - const parts = str.split('|'); - if (parts.length > 1) { - enStrings.add(parts[0]); - } else { - enStrings.add(str); - } -} - -for (const filename of fs.readdirSync(I18NDIR)) { - if (filename === 'en_EN.json') continue; - if (filename === 'basefile.json') continue; - if (!filename.endsWith('.json')) continue; - - const trs = JSON.parse(fs.readFileSync(path.join(I18NDIR, filename))); - const oldLen = Object.keys(trs).length; - for (const tr of Object.keys(trs)) { - const parts = tr.split('|'); - const trKey = parts.length > 1 ? parts[0] : tr; - if (!enStrings.has(trKey)) { - delete trs[tr]; - } - } - - const removed = oldLen - Object.keys(trs).length; - if (removed > 0) { - console.log(`${filename}: removed ${removed} translations`); - // XXX: This is totally relying on the impl serialising the JSON object in the - // same order as they were parsed from the file. JSON.stringify() has a specific argument - // that can be used to control the order, but JSON.parse() lacks any kind of equivalent. - // Empirically this does maintain the order on my system, so I'm going to leave it like - // this for now. - fs.writeFileSync(path.join(I18NDIR, filename), JSON.stringify(trs, undefined, 4) + "\n"); - } -} diff --git a/src/@types/global.d.ts b/src/@types/global.d.ts index ee0963e537..0ab26ef943 100644 --- a/src/@types/global.d.ts +++ b/src/@types/global.d.ts @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020-2021 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. @@ -39,7 +39,9 @@ import {ModalWidgetStore} from "../stores/ModalWidgetStore"; import { WidgetLayoutStore } from "../stores/widgets/WidgetLayoutStore"; import VoipUserMapper from "../VoipUserMapper"; import {SpaceStoreClass} from "../stores/SpaceStore"; -import {VoiceRecording} from "../voice/VoiceRecording"; +import TypingStore from "../stores/TypingStore"; +import { EventIndexPeg } from "../indexing/EventIndexPeg"; +import {VoiceRecordingStore} from "../stores/VoiceRecordingStore"; declare global { interface Window { @@ -71,12 +73,16 @@ declare global { mxModalWidgetStore: ModalWidgetStore; mxVoipUserMapper: VoipUserMapper; mxSpaceStore: SpaceStoreClass; - mxVoiceRecorder: typeof VoiceRecording; + mxVoiceRecordingStore: VoiceRecordingStore; + mxTypingStore: TypingStore; + mxEventIndexPeg: EventIndexPeg; } interface Document { // https://developer.mozilla.org/en-US/docs/Web/API/Document/hasStorageAccess hasStorageAccess?: () => Promise; + // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccess + requestStorageAccess?: () => Promise; // Safari & IE11 only have this prefixed: we used prefixed versions // previously so let's continue to support them for now @@ -129,4 +135,30 @@ declare global { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/columnNumber columnNumber?: number; } + + // https://github.com/microsoft/TypeScript/issues/28308#issuecomment-650802278 + interface AudioWorkletProcessor { + readonly port: MessagePort; + process( + inputs: Float32Array[][], + outputs: Float32Array[][], + parameters: Record + ): boolean; + } + + // https://github.com/microsoft/TypeScript/issues/28308#issuecomment-650802278 + const AudioWorkletProcessor: { + prototype: AudioWorkletProcessor; + new (options?: AudioWorkletNodeOptions): AudioWorkletProcessor; + }; + + // https://github.com/microsoft/TypeScript/issues/28308#issuecomment-650802278 + function registerProcessor( + name: string, + processorCtor: (new ( + options?: AudioWorkletNodeOptions + ) => AudioWorkletProcessor) & { + parameterDescriptors?: AudioParamDescriptor[]; + } + ); } diff --git a/src/Avatar.ts b/src/Avatar.ts index 76c88faa1c..d218ae8b46 100644 --- a/src/Avatar.ts +++ b/src/Avatar.ts @@ -27,11 +27,7 @@ export type ResizeMethod = "crop" | "scale"; export function avatarUrlForMember(member: RoomMember, width: number, height: number, resizeMethod: ResizeMethod) { let url: string; if (member?.getMxcAvatarUrl()) { - url = mediaFromMxc(member.getMxcAvatarUrl()).getThumbnailOfSourceHttp( - Math.floor(width * window.devicePixelRatio), - Math.floor(height * window.devicePixelRatio), - resizeMethod, - ); + url = mediaFromMxc(member.getMxcAvatarUrl()).getThumbnailOfSourceHttp(width, height, resizeMethod); } if (!url) { // member can be null here currently since on invites, the JS SDK @@ -44,11 +40,7 @@ export function avatarUrlForMember(member: RoomMember, width: number, height: nu export function avatarUrlForUser(user: User, width: number, height: number, resizeMethod?: ResizeMethod) { if (!user.avatarUrl) return null; - return mediaFromMxc(user.avatarUrl).getThumbnailOfSourceHttp( - Math.floor(width * window.devicePixelRatio), - Math.floor(height * window.devicePixelRatio), - resizeMethod, - ); + return mediaFromMxc(user.avatarUrl).getThumbnailOfSourceHttp(width, height, resizeMethod); } function isValidHexColor(color: string): boolean { diff --git a/src/BasePlatform.ts b/src/BasePlatform.ts index b6012d7597..5483ea6874 100644 --- a/src/BasePlatform.ts +++ b/src/BasePlatform.ts @@ -258,7 +258,7 @@ export default abstract class BasePlatform { return null; } - setLanguage(preferredLangs: string[]) {} + async setLanguage(preferredLangs: string[]) {} setSpellCheckLanguages(preferredLangs: string[]) {} diff --git a/src/CallHandler.tsx b/src/CallHandler.tsx index be687a4474..91fd7e4c7d 100644 --- a/src/CallHandler.tsx +++ b/src/CallHandler.tsx @@ -59,7 +59,6 @@ import {MatrixClientPeg} from './MatrixClientPeg'; import PlatformPeg from './PlatformPeg'; import Modal from './Modal'; import { _t } from './languageHandler'; -import { createNewMatrixCall } from 'matrix-js-sdk/src/webrtc/call'; import dis from './dispatcher/dispatcher'; import WidgetUtils from './utils/WidgetUtils'; import WidgetEchoStore from './stores/WidgetEchoStore'; @@ -86,6 +85,8 @@ import { Action } from './dispatcher/actions'; import VoipUserMapper from './VoipUserMapper'; import { addManagedHybridWidget, isManagedHybridWidgetEnabled } from './widgets/ManagedHybrid'; import { randomUppercaseString, randomLowercaseString } from "matrix-js-sdk/src/randomstring"; +import SdkConfig from './SdkConfig'; +import { ensureDMExists, findDMForUser } from './createRoom'; export const PROTOCOL_PSTN = 'm.protocol.pstn'; export const PROTOCOL_PSTN_PREFIXED = 'im.vector.protocol.pstn'; @@ -167,6 +168,11 @@ export default class CallHandler { private invitedRoomsAreVirtual = new Map(); private invitedRoomCheckInProgress = false; + // Map of the asserted identity users after we've looked them up using the API. + // We need to be be able to determine the mapped room synchronously, so we + // do the async lookup when we get new information and then store these mappings here + private assertedIdentityNativeUsers = new Map(); + static sharedInstance() { if (!window.mxCallHandler) { window.mxCallHandler = new CallHandler() @@ -179,8 +185,19 @@ export default class CallHandler { * Gets the user-facing room associated with a call (call.roomId may be the call "virtual room" * if a voip_mxid_translate_pattern is set in the config) */ - public static roomIdForCall(call: MatrixCall): string { + public roomIdForCall(call: MatrixCall): string { if (!call) return null; + + const voipConfig = SdkConfig.get()['voip']; + + if (voipConfig && voipConfig.obeyAssertedIdentity) { + const nativeUser = this.assertedIdentityNativeUsers[call.callId]; + if (nativeUser) { + const room = findDMForUser(MatrixClientPeg.get(), nativeUser); + if (room) return room.roomId + } + } + return VoipUserMapper.sharedInstance().nativeRoomForVirtualRoom(call.roomId) || call.roomId; } @@ -379,14 +396,14 @@ export default class CallHandler { // We don't allow placing more than one call per room, but that doesn't mean there // can't be more than one, eg. in a glare situation. This checks that the given call // is the call we consider 'the' call for its room. - const mappedRoomId = CallHandler.roomIdForCall(call); + const mappedRoomId = this.roomIdForCall(call); const callForThisRoom = this.getCallForRoom(mappedRoomId); return callForThisRoom && call.callId === callForThisRoom.callId; } private setCallListeners(call: MatrixCall) { - const mappedRoomId = CallHandler.roomIdForCall(call); + let mappedRoomId = CallHandler.sharedInstance().roomIdForCall(call); call.on(CallEvent.Error, (err: CallError) => { if (!this.matchesCallForThisRoom(call)) return; @@ -500,6 +517,42 @@ export default class CallHandler { this.setCallListeners(newCall); this.setCallState(newCall, newCall.state); }); + call.on(CallEvent.AssertedIdentityChanged, async () => { + if (!this.matchesCallForThisRoom(call)) return; + + console.log(`Call ID ${call.callId} got new asserted identity:`, call.getRemoteAssertedIdentity()); + + const newAssertedIdentity = call.getRemoteAssertedIdentity().id; + let newNativeAssertedIdentity = newAssertedIdentity; + if (newAssertedIdentity) { + const response = await this.sipNativeLookup(newAssertedIdentity); + if (response.length) newNativeAssertedIdentity = response[0].userid; + } + console.log(`Asserted identity ${newAssertedIdentity} mapped to ${newNativeAssertedIdentity}`); + + if (newNativeAssertedIdentity) { + this.assertedIdentityNativeUsers[call.callId] = newNativeAssertedIdentity; + + // If we don't already have a room with this user, make one. This will be slightly odd + // if they called us because we'll be inviting them, but there's not much we can do about + // this if we want the actual, native room to exist (which we do). This is why it's + // important to only obey asserted identity in trusted environments, since anyone you're + // on a call with can cause you to send a room invite to someone. + await ensureDMExists(MatrixClientPeg.get(), newNativeAssertedIdentity); + + const newMappedRoomId = this.roomIdForCall(call); + console.log(`Old room ID: ${mappedRoomId}, new room ID: ${newMappedRoomId}`); + if (newMappedRoomId !== mappedRoomId) { + this.removeCallForRoom(mappedRoomId); + mappedRoomId = newMappedRoomId; + this.calls.set(mappedRoomId, call); + dis.dispatch({ + action: Action.CallChangeRoom, + call, + }); + } + } + }); } private async logCallStats(call: MatrixCall, mappedRoomId: string) { @@ -551,7 +604,7 @@ export default class CallHandler { } private setCallState(call: MatrixCall, status: CallState) { - const mappedRoomId = CallHandler.roomIdForCall(call); + const mappedRoomId = CallHandler.sharedInstance().roomIdForCall(call); console.log( `Call state in ${mappedRoomId} changed to ${status}`, @@ -639,7 +692,7 @@ export default class CallHandler { const timeUntilTurnCresExpire = MatrixClientPeg.get().getTurnServersExpiry() - Date.now(); console.log("Current turn creds expire in " + timeUntilTurnCresExpire + " ms"); - const call = createNewMatrixCall(MatrixClientPeg.get(), mappedRoomId); + const call = MatrixClientPeg.get().createCall(mappedRoomId); this.calls.set(roomId, call); if (transferee) { @@ -673,7 +726,7 @@ export default class CallHandler { call.placeScreenSharingCall( remoteElement, localElement, - async () : Promise => { + async (): Promise => { const {finished} = Modal.createDialog(DesktopCapturerSourcePicker); const [source] = await finished; return source; @@ -772,7 +825,7 @@ export default class CallHandler { const call = payload.call as MatrixCall; - const mappedRoomId = CallHandler.roomIdForCall(call); + const mappedRoomId = CallHandler.sharedInstance().roomIdForCall(call); if (this.getCallForRoom(mappedRoomId)) { // ignore multiple incoming calls to the same room return; diff --git a/src/GroupAddressPicker.js b/src/GroupAddressPicker.js index e7ae3217bb..d956189f0d 100644 --- a/src/GroupAddressPicker.js +++ b/src/GroupAddressPicker.js @@ -148,13 +148,15 @@ function _onGroupAddRoomFinished(groupId, addrs, addRoomsPublicly) { const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to add the following room to the group', - '', ErrorDialog, - { - title: _t( - "Failed to add the following rooms to %(groupId)s:", - {groupId}, - ), - description: errorList.join(", "), - }); + '', + ErrorDialog, + { + title: _t( + "Failed to add the following rooms to %(groupId)s:", + {groupId}, + ), + description: errorList.join(", "), + }, + ); }); } diff --git a/src/HtmlUtils.tsx b/src/HtmlUtils.tsx index 1dc342fac5..6b2568d68c 100644 --- a/src/HtmlUtils.tsx +++ b/src/HtmlUtils.tsx @@ -130,11 +130,14 @@ export function sanitizedHtmlNode(insaneHtml: string) { return
; } -export function sanitizedHtmlNodeInnerText(insaneHtml: string) { - const saneHtml = sanitizeHtml(insaneHtml, sanitizeHtmlParams); - const contentDiv = document.createElement("div"); - contentDiv.innerHTML = saneHtml; - return contentDiv.innerText; +export function getHtmlText(insaneHtml: string) { + return sanitizeHtml(insaneHtml, { + allowedTags: [], + allowedAttributes: {}, + selfClosing: [], + allowedSchemes: [], + disallowedTagsMode: 'discard', + }) } /** diff --git a/src/IdentityAuthClient.js b/src/IdentityAuthClient.js index 1687adf13b..9239c1bc75 100644 --- a/src/IdentityAuthClient.js +++ b/src/IdentityAuthClient.js @@ -163,7 +163,7 @@ export default class IdentityAuthClient {
), button: _t("Trust"), - }); + }); const [confirmed] = await finished; if (confirmed) { // eslint-disable-next-line react-hooks/rules-of-hooks diff --git a/src/KeyBindingsManager.ts b/src/KeyBindingsManager.ts index d862f10c02..aac14bde20 100644 --- a/src/KeyBindingsManager.ts +++ b/src/KeyBindingsManager.ts @@ -231,8 +231,10 @@ export class KeyBindingsManager { /** * Finds a matching KeyAction for a given KeyboardEvent */ - private getAction(getters: KeyBindingGetter[], ev: KeyboardEvent | React.KeyboardEvent) - : T | undefined { + private getAction( + getters: KeyBindingGetter[], + ev: KeyboardEvent | React.KeyboardEvent, + ): T | undefined { for (const getter of getters) { const bindings = getter(); const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, isMac)); diff --git a/src/Login.ts b/src/Login.ts index db3c4c11e4..d584df7dfe 100644 --- a/src/Login.ts +++ b/src/Login.ts @@ -1,9 +1,6 @@ /* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2017 Vector Creations Ltd -Copyright 2018 New Vector Ltd +Copyright 2015-2021 The Matrix.org Foundation C.I.C. Copyright 2019 Michael Telatynski <7t3chguy@gmail.com> -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. @@ -59,7 +56,7 @@ export type LoginFlow = ISSOFlow | IPasswordFlow; // TODO: Move this to JS SDK /* eslint-disable camelcase */ interface ILoginParams { - identifier?: string; + identifier?: object; password?: string; token?: string; device_id?: string; diff --git a/src/PasswordReset.js b/src/PasswordReset.js index 6fe6ca82cc..88ae00d088 100644 --- a/src/PasswordReset.js +++ b/src/PasswordReset.js @@ -54,7 +54,7 @@ export default class PasswordReset { return res; }, function(err) { if (err.errcode === 'M_THREEPID_NOT_FOUND') { - err.message = _t('This email address was not found'); + err.message = _t('This email address was not found'); } else if (err.httpStatus) { err.message = err.message + ` (Status ${err.httpStatus})`; } diff --git a/src/Resend.js b/src/Resend.js index bf69e59c1a..f1e5fb38f5 100644 --- a/src/Resend.js +++ b/src/Resend.js @@ -21,11 +21,11 @@ import { EventStatus } from 'matrix-js-sdk/src/models/event'; export default class Resend { static resendUnsentEvents(room) { - room.getPendingEvents().filter(function(ev) { + return Promise.all(room.getPendingEvents().filter(function(ev) { return ev.status === EventStatus.NOT_SENT; - }).forEach(function(event) { - Resend.resend(event); - }); + }).map(function(event) { + return Resend.resend(event); + })); } static cancelUnsentEvents(room) { @@ -38,7 +38,7 @@ export default class Resend { static resend(event) { const room = MatrixClientPeg.get().getRoom(event.getRoomId()); - MatrixClientPeg.get().resendEvent(event, room).then(function(res) { + return MatrixClientPeg.get().resendEvent(event, room).then(function(res) { dis.dispatch({ action: 'message_sent', event: event, diff --git a/src/ScalarAuthClient.js b/src/ScalarAuthClient.ts similarity index 84% rename from src/ScalarAuthClient.js rename to src/ScalarAuthClient.ts index 200b4fd7b9..a09c3494a8 100644 --- a/src/ScalarAuthClient.js +++ b/src/ScalarAuthClient.ts @@ -1,6 +1,5 @@ /* -Copyright 2016 OpenMarket Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2016, 2019, 2021 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. @@ -17,13 +16,14 @@ limitations under the License. import url from 'url'; import SettingsStore from "./settings/SettingsStore"; -import { Service, startTermsFlow, TermsNotSignedError } from './Terms'; +import { Service, startTermsFlow, TermsInteractionCallback, TermsNotSignedError } from './Terms'; import {MatrixClientPeg} from "./MatrixClientPeg"; import request from "browser-request"; import SdkConfig from "./SdkConfig"; import {WidgetType} from "./widgets/WidgetType"; import {SERVICE_TYPES} from "matrix-js-sdk/src/service-types"; +import { Room } from "matrix-js-sdk/src/models/room"; // The version of the integration manager API we're intending to work with const imApiVersion = "1.1"; @@ -31,9 +31,11 @@ const imApiVersion = "1.1"; // TODO: Generify the name of this class and all components within - it's not just for Scalar. export default class ScalarAuthClient { - constructor(apiUrl, uiUrl) { - this.apiUrl = apiUrl; - this.uiUrl = uiUrl; + private scalarToken: string; + private termsInteractionCallback: TermsInteractionCallback; + private isDefaultManager: boolean; + + constructor(private apiUrl: string, private uiUrl: string) { this.scalarToken = null; // `undefined` to allow `startTermsFlow` to fallback to a default // callback if this is unset. @@ -46,7 +48,7 @@ export default class ScalarAuthClient { this.isDefaultManager = apiUrl === configApiUrl && configUiUrl === uiUrl; } - _writeTokenToStore() { + private writeTokenToStore() { window.localStorage.setItem("mx_scalar_token_at_" + this.apiUrl, this.scalarToken); if (this.isDefaultManager) { // We remove the old token from storage to migrate upwards. This is safe @@ -56,7 +58,7 @@ export default class ScalarAuthClient { } } - _readTokenFromStore() { + private readTokenFromStore(): string { let token = window.localStorage.getItem("mx_scalar_token_at_" + this.apiUrl); if (!token && this.isDefaultManager) { token = window.localStorage.getItem("mx_scalar_token"); @@ -64,33 +66,33 @@ export default class ScalarAuthClient { return token; } - _readToken() { + private readToken(): string { if (this.scalarToken) return this.scalarToken; - return this._readTokenFromStore(); + return this.readTokenFromStore(); } setTermsInteractionCallback(callback) { this.termsInteractionCallback = callback; } - connect() { + connect(): Promise { return this.getScalarToken().then((tok) => { this.scalarToken = tok; }); } - hasCredentials() { + hasCredentials(): boolean { return this.scalarToken != null; // undef or null } // Returns a promise that resolves to a scalar_token string - getScalarToken() { - const token = this._readToken(); + getScalarToken(): Promise { + const token = this.readToken(); if (!token) { return this.registerForToken(); } else { - return this._checkToken(token).catch((e) => { + return this.checkToken(token).catch((e) => { if (e instanceof TermsNotSignedError) { // retrying won't help this throw e; @@ -100,7 +102,7 @@ export default class ScalarAuthClient { } } - _getAccountName(token) { + private getAccountName(token: string): Promise { const url = this.apiUrl + "/account"; return new Promise(function(resolve, reject) { @@ -125,8 +127,8 @@ export default class ScalarAuthClient { }); } - _checkToken(token) { - return this._getAccountName(token).then(userId => { + private checkToken(token: string): Promise { + return this.getAccountName(token).then(userId => { const me = MatrixClientPeg.get().getUserId(); if (userId !== me) { throw new Error("Scalar token is owned by someone else: " + me); @@ -154,7 +156,7 @@ export default class ScalarAuthClient { parsedImRestUrl.pathname = ''; return startTermsFlow([new Service( SERVICE_TYPES.IM, - parsedImRestUrl.format(), + url.format(parsedImRestUrl), token, )], this.termsInteractionCallback).then(() => { return token; @@ -165,22 +167,22 @@ export default class ScalarAuthClient { }); } - registerForToken() { + registerForToken(): Promise { // Get openid bearer token from the HS as the first part of our dance return MatrixClientPeg.get().getOpenIdToken().then((tokenObject) => { // Now we can send that to scalar and exchange it for a scalar token return this.exchangeForScalarToken(tokenObject); }).then((token) => { // Validate it (this mostly checks to see if the IM needs us to agree to some terms) - return this._checkToken(token); + return this.checkToken(token); }).then((token) => { this.scalarToken = token; - this._writeTokenToStore(); + this.writeTokenToStore(); return token; }); } - exchangeForScalarToken(openidTokenObject) { + exchangeForScalarToken(openidTokenObject: any): Promise { const scalarRestUrl = this.apiUrl; return new Promise(function(resolve, reject) { @@ -194,7 +196,7 @@ export default class ScalarAuthClient { if (err) { reject(err); } else if (response.statusCode / 100 !== 2) { - reject({statusCode: response.statusCode}); + reject(new Error(`Scalar request failed: ${response.statusCode}`)); } else if (!body || !body.scalar_token) { reject(new Error("Missing scalar_token in response")); } else { @@ -204,7 +206,7 @@ export default class ScalarAuthClient { }); } - getScalarPageTitle(url) { + getScalarPageTitle(url: string): Promise { let scalarPageLookupUrl = this.apiUrl + '/widgets/title_lookup'; scalarPageLookupUrl = this.getStarterLink(scalarPageLookupUrl); scalarPageLookupUrl += '&curl=' + encodeURIComponent(url); @@ -218,7 +220,7 @@ export default class ScalarAuthClient { if (err) { reject(err); } else if (response.statusCode / 100 !== 2) { - reject({statusCode: response.statusCode}); + reject(new Error(`Scalar request failed: ${response.statusCode}`)); } else if (!body) { reject(new Error("Missing page title in response")); } else { @@ -240,10 +242,10 @@ export default class ScalarAuthClient { * @param {string} widgetId The widget ID to disable assets for * @return {Promise} Resolves on completion */ - disableWidgetAssets(widgetType: WidgetType, widgetId) { + disableWidgetAssets(widgetType: WidgetType, widgetId: string): Promise { let url = this.apiUrl + '/widgets/set_assets_state'; url = this.getStarterLink(url); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { request({ method: 'GET', // XXX: Actions shouldn't be GET requests uri: url, @@ -257,7 +259,7 @@ export default class ScalarAuthClient { if (err) { reject(err); } else if (response.statusCode / 100 !== 2) { - reject({statusCode: response.statusCode}); + reject(new Error(`Scalar request failed: ${response.statusCode}`)); } else if (!body) { reject(new Error("Failed to set widget assets state")); } else { @@ -267,7 +269,7 @@ export default class ScalarAuthClient { }); } - getScalarInterfaceUrlForRoom(room, screen, id) { + getScalarInterfaceUrlForRoom(room: Room, screen: string, id: string): string { const roomId = room.roomId; const roomName = room.name; let url = this.uiUrl; @@ -284,7 +286,7 @@ export default class ScalarAuthClient { return url; } - getStarterLink(starterLinkUrl) { + getStarterLink(starterLinkUrl: string): string { return starterLinkUrl + "?scalar_token=" + encodeURIComponent(this.scalarToken); } } diff --git a/src/SlashCommands.tsx b/src/SlashCommands.tsx index f99868f5e0..6ce1439164 100644 --- a/src/SlashCommands.tsx +++ b/src/SlashCommands.tsx @@ -1222,4 +1222,5 @@ export function getCommand(input: string) { args, }; } + return {}; } diff --git a/src/Terms.js b/src/Terms.ts similarity index 87% rename from src/Terms.js rename to src/Terms.ts index 6ae89f9a2c..1bdff36cbc 100644 --- a/src/Terms.js +++ b/src/Terms.ts @@ -1,5 +1,5 @@ /* -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2019, 2021 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. @@ -17,7 +17,7 @@ limitations under the License. import classNames from 'classnames'; import {MatrixClientPeg} from './MatrixClientPeg'; -import * as sdk from './'; +import * as sdk from '.'; import Modal from './Modal'; export class TermsNotSignedError extends Error {} @@ -32,13 +32,30 @@ export class Service { * @param {string} baseUrl The Base URL of the service (ie. before '/_matrix') * @param {string} accessToken The user's access token for the service */ - constructor(serviceType, baseUrl, accessToken) { - this.serviceType = serviceType; - this.baseUrl = baseUrl; - this.accessToken = accessToken; + constructor(public serviceType: string, public baseUrl: string, public accessToken: string) { } } +interface Policy { + // @ts-ignore: No great way to express indexed types together with other keys + version: string; + [lang: string]: { + url: string; + }; +} +type Policies = { + [policy: string]: Policy, +}; + +export type TermsInteractionCallback = ( + policiesAndServicePairs: { + service: Service, + policies: Policies, + }[], + agreedUrls: string[], + extraClassNames?: string, +) => Promise; + /** * Start a flow where the user is presented with terms & conditions for some services * @@ -51,8 +68,8 @@ export class Service { * if they cancel. */ export async function startTermsFlow( - services, - interactionCallback = dialogTermsInteractionCallback, + services: Service[], + interactionCallback: TermsInteractionCallback = dialogTermsInteractionCallback, ) { const termsPromises = services.map( (s) => MatrixClientPeg.get().getTerms(s.serviceType, s.baseUrl), @@ -77,7 +94,7 @@ export async function startTermsFlow( * } */ - const terms = await Promise.all(termsPromises); + const terms: { policies: Policies }[] = await Promise.all(termsPromises); const policiesAndServicePairs = terms.map((t, i) => { return { 'service': services[i], 'policies': t.policies }; }); // fetch the set of agreed policy URLs from account data @@ -158,10 +175,13 @@ export async function startTermsFlow( } export function dialogTermsInteractionCallback( - policiesAndServicePairs, - agreedUrls, - extraClassNames, -) { + policiesAndServicePairs: { + service: Service, + policies: { [policy: string]: Policy }, + }[], + agreedUrls: string[], + extraClassNames?: string, +): Promise { return new Promise((resolve, reject) => { console.log("Terms that need agreement", policiesAndServicePairs); const TermsDialog = sdk.getComponent("views.dialogs.TermsDialog"); diff --git a/src/TextForEvent.js b/src/TextForEvent.js index a6787c647d..86f9ff20f4 100644 --- a/src/TextForEvent.js +++ b/src/TextForEvent.js @@ -547,17 +547,23 @@ function textForMjolnirEvent(event) { // else the entity !== prevEntity - count as a removal & add if (USER_RULE_TYPES.includes(event.getType())) { - return _t("%(senderName)s changed a rule that was banning users matching %(oldGlob)s to matching " + + return _t( + "%(senderName)s changed a rule that was banning users matching %(oldGlob)s to matching " + "%(newGlob)s for %(reason)s", - {senderName, oldGlob: prevEntity, newGlob: entity, reason}); + {senderName, oldGlob: prevEntity, newGlob: entity, reason}, + ); } else if (ROOM_RULE_TYPES.includes(event.getType())) { - return _t("%(senderName)s changed a rule that was banning rooms matching %(oldGlob)s to matching " + + return _t( + "%(senderName)s changed a rule that was banning rooms matching %(oldGlob)s to matching " + "%(newGlob)s for %(reason)s", - {senderName, oldGlob: prevEntity, newGlob: entity, reason}); + {senderName, oldGlob: prevEntity, newGlob: entity, reason}, + ); } else if (SERVER_RULE_TYPES.includes(event.getType())) { - return _t("%(senderName)s changed a rule that was banning servers matching %(oldGlob)s to matching " + + return _t( + "%(senderName)s changed a rule that was banning servers matching %(oldGlob)s to matching " + "%(newGlob)s for %(reason)s", - {senderName, oldGlob: prevEntity, newGlob: entity, reason}); + {senderName, oldGlob: prevEntity, newGlob: entity, reason}, + ); } // Unknown type. We'll say something but we shouldn't end up here. diff --git a/src/Unread.js b/src/Unread.js index ddf225ac64..12c15eb6af 100644 --- a/src/Unread.js +++ b/src/Unread.js @@ -45,7 +45,7 @@ export function eventTriggersUnreadCount(ev) { } export function doesRoomHaveUnreadMessages(room) { - const myUserId = MatrixClientPeg.get().credentials.userId; + const myUserId = MatrixClientPeg.get().getUserId(); // get the most recent read receipt sent by our account. // N.B. this is NOT a read marker (RM, aka "read up to marker"), diff --git a/src/VoipUserMapper.ts b/src/VoipUserMapper.ts index 4f5613b4a8..e5bed2e812 100644 --- a/src/VoipUserMapper.ts +++ b/src/VoipUserMapper.ts @@ -57,7 +57,11 @@ export default class VoipUserMapper { if (!virtualRoom) return null; const virtualRoomEvent = virtualRoom.getAccountData(VIRTUAL_ROOM_EVENT_TYPE); if (!virtualRoomEvent || !virtualRoomEvent.getContent()) return null; - return virtualRoomEvent.getContent()['native_room'] || null; + const nativeRoomID = virtualRoomEvent.getContent()['native_room']; + const nativeRoom = MatrixClientPeg.get().getRoom(nativeRoomID); + if (!nativeRoom || nativeRoom.getMyMembership() !== 'join') return null; + + return nativeRoomID; } public isVirtualRoom(room: Room): boolean { diff --git a/src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.js b/src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.tsx similarity index 90% rename from src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.js rename to src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.tsx index be3368b87b..0710c513da 100644 --- a/src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.js +++ b/src/async-components/views/dialogs/eventindex/ManageEventIndexDialog.tsx @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020-2021 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. @@ -16,7 +16,6 @@ limitations under the License. import React from 'react'; import * as sdk from '../../../../index'; -import PropTypes from 'prop-types'; import { _t } from '../../../../languageHandler'; import SdkConfig from '../../../../SdkConfig'; import SettingsStore from "../../../../settings/SettingsStore"; @@ -26,14 +25,23 @@ import {formatBytes, formatCountLong} from "../../../../utils/FormattingUtils"; import EventIndexPeg from "../../../../indexing/EventIndexPeg"; import {SettingLevel} from "../../../../settings/SettingLevel"; +interface IProps { + onFinished: (confirmed: boolean) => void; +} + +interface IState { + eventIndexSize: number; + eventCount: number; + crawlingRoomsCount: number; + roomCount: number; + currentRoom: string; + crawlerSleepTime: number; +} + /* * Allows the user to introspect the event index state and disable it. */ -export default class ManageEventIndexDialog extends React.Component { - static propTypes = { - onFinished: PropTypes.func.isRequired, - }; - +export default class ManageEventIndexDialog extends React.Component { constructor(props) { super(props); @@ -84,7 +92,7 @@ export default class ManageEventIndexDialog extends React.Component { } } - async componentDidMount(): void { + async componentDidMount(): Promise { let eventIndexSize = 0; let crawlingRoomsCount = 0; let roomCount = 0; @@ -123,14 +131,14 @@ export default class ManageEventIndexDialog extends React.Component { }); } - _onDisable = async () => { + private onDisable = async () => { Modal.createTrackedDialogAsync("Disable message search", "Disable message search", import("./DisableEventIndexDialog"), null, null, /* priority = */ false, /* static = */ true, ); }; - _onCrawlerSleepTimeChange = (e) => { + private onCrawlerSleepTimeChange = (e) => { this.setState({crawlerSleepTime: e.target.value}); SettingsStore.setValue("crawlerSleepTime", null, SettingLevel.DEVICE, e.target.value); }; @@ -144,7 +152,7 @@ export default class ManageEventIndexDialog extends React.Component { crawlerState = _t("Not currently indexing messages for any room."); } else { crawlerState = ( - _t("Currently indexing: %(currentRoom)s", { currentRoom: this.state.currentRoom }) + _t("Currently indexing: %(currentRoom)s", { currentRoom: this.state.currentRoom }) ); } @@ -169,7 +177,7 @@ export default class ManageEventIndexDialog extends React.Component { label={_t('Message downloading sleep time(ms)')} type='number' value={this.state.crawlerSleepTime} - onChange={this._onCrawlerSleepTimeChange} /> + onChange={this.onCrawlerSleepTimeChange} /> ); @@ -188,7 +196,7 @@ export default class ManageEventIndexDialog extends React.Component { onPrimaryButtonClick={this.props.onFinished} primaryButtonClass="primary" cancelButton={_t("Disable")} - onCancel={this._onDisable} + onCancel={this.onDisable} cancelButtonClass="danger" /> diff --git a/src/async-components/views/dialogs/security/CreateKeyBackupDialog.js b/src/async-components/views/dialogs/security/CreateKeyBackupDialog.js index 863ee2b427..ab4f605c83 100644 --- a/src/async-components/views/dialogs/security/CreateKeyBackupDialog.js +++ b/src/async-components/views/dialogs/security/CreateKeyBackupDialog.js @@ -498,9 +498,9 @@ export default class CreateKeyBackupDialog extends React.PureComponent { title={this._titleForPhase(this.state.phase)} hasCancel={[PHASE_PASSPHRASE, PHASE_DONE].includes(this.state.phase)} > -
- {content} -
+
+ {content} +
); } diff --git a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js index 84cb58536a..7b7d552c43 100644 --- a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js +++ b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js @@ -856,9 +856,9 @@ export default class CreateSecretStorageDialog extends React.PureComponent { hasCancel={this.props.hasCancel && [PHASE_PASSPHRASE].includes(this.state.phase)} fixedWidth={false} > -
- {content} -
+
+ {content} +
); } diff --git a/src/async-components/views/dialogs/security/ExportE2eKeysDialog.js b/src/async-components/views/dialogs/security/ExportE2eKeysDialog.js index eeb68b94bd..60f2ca9168 100644 --- a/src/async-components/views/dialogs/security/ExportE2eKeysDialog.js +++ b/src/async-components/views/dialogs/security/ExportE2eKeysDialog.js @@ -170,8 +170,11 @@ export default class ExportE2eKeysDialog extends React.Component {
-
-
- -
-
- -
+
+ +
+
+ +
-
- -
-
- -
+
+ +
+
+ +
diff --git a/src/components/structures/FilePanel.js b/src/components/structures/FilePanel.js index 32db5c251c..d5e4b092e2 100644 --- a/src/components/structures/FilePanel.js +++ b/src/components/structures/FilePanel.js @@ -200,10 +200,10 @@ class FilePanel extends React.Component { previousPhase={RightPanelPhases.RoomSummary} >
- { _t("You must register to use this functionality", - {}, - { 'a': (sub) => { sub } }) - } + { _t("You must register to use this functionality", + {}, + { 'a': (sub) => { sub } }) + }
; } else if (this.noRoom) { diff --git a/src/components/structures/GroupFilterPanel.js b/src/components/structures/GroupFilterPanel.js index 976b2d81a5..7c050e7433 100644 --- a/src/components/structures/GroupFilterPanel.js +++ b/src/components/structures/GroupFilterPanel.js @@ -153,17 +153,17 @@ class GroupFilterPanel extends React.Component { type="draggable-TagTile" > { (provided, snapshot) => ( -
- { this.renderGlobalIcon() } - { tags } -
- {createButton} -
- { provided.placeholder } +
+ { this.renderGlobalIcon() } + { tags } +
+ {createButton}
+ { provided.placeholder } +
) } diff --git a/src/components/structures/GroupView.js b/src/components/structures/GroupView.js index ed6167cbe7..3ab009d7b8 100644 --- a/src/components/structures/GroupView.js +++ b/src/components/structures/GroupView.js @@ -43,7 +43,7 @@ import {mediaFromMxc} from "../../customisations/Media"; import {replaceableComponent} from "../../utils/replaceableComponent"; const LONG_DESC_PLACEHOLDER = _td( -`

HTML for your community's page

+ `

HTML for your community's page

Use the long description to introduce new members to the community, or distribute some important links @@ -110,14 +110,16 @@ class CategoryRoomList extends React.Component { const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to add the following room to the group summary', - '', ErrorDialog, - { - title: _t( - "Failed to add the following rooms to the summary of %(groupId)s:", - {groupId: this.props.groupId}, - ), - description: errorList.join(", "), - }); + '', + ErrorDialog, + { + title: _t( + "Failed to add the following rooms to the summary of %(groupId)s:", + {groupId: this.props.groupId}, + ), + description: errorList.join(", "), + }, + ); }); }, }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true); @@ -146,8 +148,8 @@ class CategoryRoomList extends React.Component { let catHeader =

; if (this.props.category && this.props.category.profile) { catHeader =
- { this.props.category.profile.name } -
; + { this.props.category.profile.name } +
; } return
{ catHeader } @@ -190,13 +192,14 @@ class FeaturedRoom extends React.Component { Modal.createTrackedDialog( 'Failed to remove room from group summary', '', ErrorDialog, - { - title: _t( - "Failed to remove the room from the summary of %(groupId)s", - {groupId: this.props.groupId}, - ), - description: _t("The room '%(roomName)s' could not be removed from the summary.", {roomName}), - }); + { + title: _t( + "Failed to remove the room from the summary of %(groupId)s", + {groupId: this.props.groupId}, + ), + description: _t("The room '%(roomName)s' could not be removed from the summary.", {roomName}), + }, + ); }); }; @@ -283,13 +286,14 @@ class RoleUserList extends React.Component { Modal.createTrackedDialog( 'Failed to add the following users to the community summary', '', ErrorDialog, - { - title: _t( - "Failed to add the following users to the summary of %(groupId)s:", - {groupId: this.props.groupId}, - ), - description: errorList.join(", "), - }); + { + title: _t( + "Failed to add the following users to the summary of %(groupId)s:", + {groupId: this.props.groupId}, + ), + description: errorList.join(", "), + }, + ); }); }, }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true); @@ -299,11 +303,11 @@ class RoleUserList extends React.Component { const TintableSvg = sdk.getComponent("elements.TintableSvg"); const addButton = this.props.editing ? ( - -
- { _t('Add a User') } -
-
) :
; + +
+ { _t('Add a User') } +
+ ) :
; const userNodes = this.props.users.map((u) => { return - { _t("Leave %(groupName)s?", {groupName: this.props.groupId}) } - { warnings } + { _t("Leave %(groupName)s?", {groupName: this.props.groupId}) } + { warnings } ), button: _t("Leave"), @@ -1055,10 +1061,11 @@ export default class GroupView extends React.Component { return null; } - const membershipButtonClasses = classnames([ - 'mx_RoomHeader_textButton', - 'mx_GroupView_textButton', - ], + const membershipButtonClasses = classnames( + [ + 'mx_RoomHeader_textButton', + 'mx_GroupView_textButton', + ], membershipButtonExtraClasses, ); diff --git a/src/components/structures/LeftPanel.tsx b/src/components/structures/LeftPanel.tsx index cbfc7b476b..44b404bd3a 100644 --- a/src/components/structures/LeftPanel.tsx +++ b/src/components/structures/LeftPanel.tsx @@ -154,7 +154,7 @@ export default class LeftPanel extends React.Component { private doStickyHeaders(list: HTMLDivElement) { const topEdge = list.scrollTop; const bottomEdge = list.offsetHeight + list.scrollTop; - const sublists = list.querySelectorAll(".mx_RoomSublist"); + const sublists = list.querySelectorAll(".mx_RoomSublist:not(.mx_RoomSublist_hidden)"); const headerRightMargin = 15; // calculated from margins and widths to align with non-sticky tiles const headerStickyWidth = list.clientWidth - headerRightMargin; @@ -347,7 +347,7 @@ export default class LeftPanel extends React.Component { if (element) { classes = element.classList; } - } while (element && !cssClasses.some(c => classes.contains(c))); + } while (element && (!cssClasses.some(c => classes.contains(c)) || element.offsetParent === null)); if (element) { element.focus(); diff --git a/src/components/structures/MatrixChat.tsx b/src/components/structures/MatrixChat.tsx index d9ed7d061b..078b296295 100644 --- a/src/components/structures/MatrixChat.tsx +++ b/src/components/structures/MatrixChat.tsx @@ -1096,8 +1096,22 @@ export default class MatrixChat extends React.PureComponent { const roomToLeave = MatrixClientPeg.get().getRoom(roomId); const isSpace = roomToLeave?.isSpaceRoom(); // Show a warning if there are additional complications. - const joinRules = roomToLeave.currentState.getStateEvents('m.room.join_rules', ''); const warnings = []; + + const memberCount = roomToLeave.currentState.getJoinedMemberCount(); + if (memberCount === 1) { + warnings.push(( + + {' '/* Whitespace, otherwise the sentences get smashed together */ } + { _t("You are the only person here. " + + "If you leave, no one will be able to join in the future, including you.") } + + )); + + return warnings; + } + + const joinRules = roomToLeave.currentState.getStateEvents('m.room.join_rules', ''); if (joinRules) { const rule = joinRules.getContent().join_rule; if (rule !== "public") { diff --git a/src/components/structures/MessagePanel.js b/src/components/structures/MessagePanel.js index 132d9ab4c3..c93f07fa0f 100644 --- a/src/components/structures/MessagePanel.js +++ b/src/components/structures/MessagePanel.js @@ -427,8 +427,10 @@ export default class MessagePanel extends React.Component { // we get a new DOM node (restarting the animation) when the ghost // moves to a different event. return ( -
  • +
  • { hr }
  • ); @@ -1014,13 +1016,13 @@ class CreationGrouper { ret.push( - { eventTiles } + { eventTiles } , ); @@ -1222,11 +1224,11 @@ class MemberGrouper { ret.push( - { eventTiles } + { eventTiles } , ); diff --git a/src/components/structures/RoomSearch.tsx b/src/components/structures/RoomSearch.tsx index a64feed42c..34682877e0 100644 --- a/src/components/structures/RoomSearch.tsx +++ b/src/components/structures/RoomSearch.tsx @@ -17,6 +17,8 @@ limitations under the License. import * as React from "react"; import { createRef } from "react"; import classNames from "classnames"; +import { Room } from "matrix-js-sdk/src/models/room"; + import defaultDispatcher from "../../dispatcher/dispatcher"; import { _t } from "../../languageHandler"; import { ActionPayload } from "../../dispatcher/payloads"; @@ -26,7 +28,7 @@ import RoomListStore from "../../stores/room-list/RoomListStore"; import { NameFilterCondition } from "../../stores/room-list/filters/NameFilterCondition"; import { getKeyBindingsManager, RoomListAction } from "../../KeyBindingsManager"; import {replaceableComponent} from "../../utils/replaceableComponent"; -import SpaceStore, {UPDATE_SELECTED_SPACE} from "../../stores/SpaceStore"; +import SpaceStore, {UPDATE_SELECTED_SPACE, UPDATE_TOP_LEVEL_SPACES} from "../../stores/SpaceStore"; interface IProps { isMinimized: boolean; @@ -40,6 +42,7 @@ interface IProps { interface IState { query: string; focused: boolean; + inSpaces: boolean; } @replaceableComponent("structures.RoomSearch") @@ -54,11 +57,13 @@ export default class RoomSearch extends React.PureComponent { this.state = { query: "", focused: false, + inSpaces: false, }; this.dispatcherRef = defaultDispatcher.register(this.onAction); // clear filter when changing spaces, in future we may wish to maintain a filter per-space SpaceStore.instance.on(UPDATE_SELECTED_SPACE, this.clearInput); + SpaceStore.instance.on(UPDATE_TOP_LEVEL_SPACES, this.onSpaces); } public componentDidUpdate(prevProps: Readonly, prevState: Readonly): void { @@ -79,8 +84,15 @@ export default class RoomSearch extends React.PureComponent { public componentWillUnmount() { defaultDispatcher.unregister(this.dispatcherRef); SpaceStore.instance.off(UPDATE_SELECTED_SPACE, this.clearInput); + SpaceStore.instance.off(UPDATE_TOP_LEVEL_SPACES, this.onSpaces); } + private onSpaces = (spaces: Room[]) => { + this.setState({ + inSpaces: spaces.length > 0, + }); + }; + private onAction = (payload: ActionPayload) => { if (payload.action === 'view_room' && payload.clear_search) { this.clearInput(); @@ -152,6 +164,11 @@ export default class RoomSearch extends React.PureComponent { 'mx_RoomSearch_inputExpanded': this.state.query || this.state.focused, }); + let placeholder = _t("Filter"); + if (this.state.inSpaces) { + placeholder = _t("Filter all spaces"); + } + let icon = (
    ); @@ -165,7 +182,7 @@ export default class RoomSearch extends React.PureComponent { onBlur={this.onBlur} onChange={this.onChange} onKeyDown={this.onKeyDown} - placeholder={_t("Filter")} + placeholder={placeholder} autoComplete="off" /> ); diff --git a/src/components/structures/RoomStatusBar.js b/src/components/structures/RoomStatusBar.js index 54b6fee233..b2f0c70bd7 100644 --- a/src/components/structures/RoomStatusBar.js +++ b/src/components/structures/RoomStatusBar.js @@ -1,5 +1,5 @@ /* -Copyright 2015-2020 The Matrix.org Foundation C.I.C. +Copyright 2015-2021 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. @@ -20,16 +20,20 @@ import { _t, _td } from '../../languageHandler'; import {MatrixClientPeg} from '../../MatrixClientPeg'; import Resend from '../../Resend'; import dis from '../../dispatcher/dispatcher'; -import {messageForResourceLimitError, messageForSendError} from '../../utils/ErrorUtils'; +import {messageForResourceLimitError} from '../../utils/ErrorUtils'; import {Action} from "../../dispatcher/actions"; import {replaceableComponent} from "../../utils/replaceableComponent"; import {EventStatus} from "matrix-js-sdk/src/models/event"; +import NotificationBadge from "../views/rooms/NotificationBadge"; +import {StaticNotificationState} from "../../stores/notifications/StaticNotificationState"; +import AccessibleButton from "../views/elements/AccessibleButton"; +import InlineSpinner from "../views/elements/InlineSpinner"; const STATUS_BAR_HIDDEN = 0; const STATUS_BAR_EXPANDED = 1; const STATUS_BAR_EXPANDED_LARGE = 2; -function getUnsentMessages(room) { +export function getUnsentMessages(room) { if (!room) { return []; } return room.getPendingEvents().filter(function(ev) { return ev.status === EventStatus.NOT_SENT; @@ -76,6 +80,7 @@ export default class RoomStatusBar extends React.Component { syncState: MatrixClientPeg.get().getSyncState(), syncStateData: MatrixClientPeg.get().getSyncStateData(), unsentMessages: getUnsentMessages(this.props.room), + isResending: false, }; componentDidMount() { @@ -109,7 +114,10 @@ export default class RoomStatusBar extends React.Component { }; _onResendAllClick = () => { - Resend.resendUnsentEvents(this.props.room); + Resend.resendUnsentEvents(this.props.room).then(() => { + this.setState({isResending: false}); + }); + this.setState({isResending: true}); dis.fire(Action.FocusComposer); }; @@ -120,9 +128,10 @@ export default class RoomStatusBar extends React.Component { _onRoomLocalEchoUpdated = (event, room, oldEventId, oldStatus) => { if (room.roomId !== this.props.room.roomId) return; - + const messages = getUnsentMessages(this.props.room); this.setState({ - unsentMessages: getUnsentMessages(this.props.room), + unsentMessages: messages, + isResending: messages.length > 0 && this.state.isResending, }); }; @@ -141,7 +150,7 @@ export default class RoomStatusBar extends React.Component { _getSize() { if (this._shouldShowConnectionError()) { return STATUS_BAR_EXPANDED; - } else if (this.state.unsentMessages.length > 0) { + } else if (this.state.unsentMessages.length > 0 || this.state.isResending) { return STATUS_BAR_EXPANDED_LARGE; } return STATUS_BAR_HIDDEN; @@ -162,7 +171,6 @@ export default class RoomStatusBar extends React.Component { _getUnsentMessageContent() { const unsentMessages = this.state.unsentMessages; - if (!unsentMessages.length) return null; let title; @@ -192,89 +200,92 @@ export default class RoomStatusBar extends React.Component { } else if (resourceLimitError) { title = messageForResourceLimitError( resourceLimitError.data.limit_type, - resourceLimitError.data.admin_contact, { - 'monthly_active_user': _td( - "Your message wasn't sent because this homeserver has hit its Monthly Active User Limit. " + - "Please contact your service administrator to continue using the service.", - ), - 'hs_disabled': _td( - "Your message wasn't sent because this homeserver has been blocked by it's administrator. " + - "Please contact your service administrator to continue using the service.", - ), - '': _td( - "Your message wasn't sent because this homeserver has exceeded a resource limit. " + - "Please contact your service administrator to continue using the service.", - ), - }); - } else if ( - unsentMessages.length === 1 && - unsentMessages[0].error && - unsentMessages[0].error.data && - unsentMessages[0].error.data.error - ) { - title = messageForSendError(unsentMessages[0].error.data) || unsentMessages[0].error.data.error; + resourceLimitError.data.admin_contact, + { + 'monthly_active_user': _td( + "Your message wasn't sent because this homeserver has hit its Monthly Active User Limit. " + + "Please contact your service administrator to continue using the service.", + ), + 'hs_disabled': _td( + "Your message wasn't sent because this homeserver has been blocked by it's administrator. " + + "Please contact your service administrator to continue using the service.", + ), + '': _td( + "Your message wasn't sent because this homeserver has exceeded a resource limit. " + + "Please contact your service administrator to continue using the service.", + ), + }, + ); } else { - title = _t('%(count)s of your messages have not been sent.', { count: unsentMessages.length }); + title = _t('Some of your messages have not been sent'); } - const content = _t("%(count)s Resend all or cancel all " + - "now. You can also select individual messages to resend or cancel.", - { count: unsentMessages.length }, - { - 'resendText': (sub) => - { sub }, - 'cancelText': (sub) => - { sub }, - }, - ); + let buttonRow = <> + + {_t("Delete all")} + + + {_t("Retry all")} + + ; + if (this.state.isResending) { + buttonRow = <> + + {/* span for css */} + {_t("Sending")} + ; + } - return
    - -
    -
    - { title } -
    -
    - { content } + return <> +
    +
    +
    + +
    +
    +
    + { title } +
    +
    + { _t("You can select all or individual messages to retry or delete") } +
    +
    +
    + {buttonRow} +
    -
    ; + ; } - // return suitable content for the main (text) part of the status bar. - _getContent() { + render() { if (this._shouldShowConnectionError()) { return ( -
    - /!\ -
    -
    - { _t('Connectivity to the server has been lost.') } -
    -
    - { _t('Sent messages will be stored until your connection has returned.') } +
    +
    +
    + /!\ +
    +
    + {_t('Connectivity to the server has been lost.')} +
    +
    + {_t('Sent messages will be stored until your connection has returned.')} +
    +
    ); } - if (this.state.unsentMessages.length > 0) { + if (this.state.unsentMessages.length > 0 || this.state.isResending) { return this._getUnsentMessageContent(); } return null; } - - render() { - const content = this._getContent(); - - return ( -
    -
    - { content } -
    -
    - ); - } } diff --git a/src/components/structures/RoomView.tsx b/src/components/structures/RoomView.tsx index 7168b7d139..5108643673 100644 --- a/src/components/structures/RoomView.tsx +++ b/src/components/structures/RoomView.tsx @@ -190,6 +190,9 @@ export interface IState { rejectError?: Error; hasPinnedWidgets?: boolean; dragCounter: number; + // whether or not a spaces context switch brought us here, + // if it did we don't want the room to be marked as read as soon as it is loaded. + wasContextSwitch?: boolean; } @replaceableComponent("structures.RoomView") @@ -326,6 +329,7 @@ export default class RoomView extends React.Component { shouldPeek: this.state.matrixClientIsReady && RoomViewStore.shouldPeek(), showingPinned: SettingsStore.getValue("PinnedEvents.isOpen", roomId), showReadReceipts: SettingsStore.getValue("showReadReceipts", roomId), + wasContextSwitch: RoomViewStore.getWasContextSwitch(), }; if (!initial && this.state.shouldPeek && !newState.shouldPeek) { @@ -2014,6 +2018,7 @@ export default class RoomView extends React.Component { timelineSet={this.state.room.getUnfilteredTimelineSet()} showReadReceipts={this.state.showReadReceipts} manageReadReceipts={!this.state.isPeeking} + sendReadReceiptOnLoad={!this.state.wasContextSwitch} manageReadMarkers={!this.state.isPeeking} hidden={hideMessagePanel} highlightedEventId={highlightedEventId} diff --git a/src/components/structures/ScrollPanel.js b/src/components/structures/ScrollPanel.js index 976734680c..5c5062633d 100644 --- a/src/components/structures/ScrollPanel.js +++ b/src/components/structures/ScrollPanel.js @@ -525,7 +525,7 @@ export default class ScrollPanel extends React.Component { */ scrollRelative = mult => { const scrollNode = this._getScrollNode(); - const delta = mult * scrollNode.clientHeight * 0.5; + const delta = mult * scrollNode.clientHeight * 0.9; scrollNode.scrollBy(0, delta); this._saveScrollState(); }; @@ -884,16 +884,20 @@ export default class ScrollPanel extends React.Component { // give the
      an explicit role=list because Safari+VoiceOver seems to think an ordered-list with // list-style-type: none; is no longer a list - return ( - { this.props.fixedChildren } -
      -
        - { this.props.children } -
      -
      -
      - ); + className={`mx_ScrollPanel ${this.props.className}`} + style={this.props.style} + > + { this.props.fixedChildren } +
      +
        + { this.props.children } +
      +
      + + ); } } diff --git a/src/components/structures/SpaceRoomDirectory.tsx b/src/components/structures/SpaceRoomDirectory.tsx index 930cfa15a9..8d6c9f0a70 100644 --- a/src/components/structures/SpaceRoomDirectory.tsx +++ b/src/components/structures/SpaceRoomDirectory.tsx @@ -136,7 +136,7 @@ const Tile: React.FC = ({ let url: string; if (room.avatar_url) { - url = mediaFromMxc(room.avatar_url).getSquareThumbnailHttp(Math.floor(20 * window.devicePixelRatio)); + url = mediaFromMxc(room.avatar_url).getSquareThumbnailHttp(20); } let description = _t("%(count)s members", { count: room.num_joined_members }); @@ -312,11 +312,12 @@ export const HierarchyLevel = ({ // mutate argument refreshToken to force a reload export const useSpaceSummary = (cli: MatrixClient, space: Room, refreshToken?: any): [ + null, ISpaceSummaryRoom[], - Map>, - Map>, - Map>, -] | [] => { + Map>?, + Map>?, + Map>?, +] | [Error] => { // TODO pagination return useAsyncMemo(async () => { try { @@ -336,13 +337,12 @@ export const useSpaceSummary = (cli: MatrixClient, space: Room, refreshToken?: a } }); - return [data.rooms as ISpaceSummaryRoom[], parentChildRelations, viaMap, childParentRelations]; + return [null, data.rooms as ISpaceSummaryRoom[], parentChildRelations, viaMap, childParentRelations]; } catch (e) { console.error(e); // TODO + return [e]; } - - return []; - }, [space, refreshToken], []); + }, [space, refreshToken], [undefined]); }; export const SpaceHierarchy: React.FC = ({ @@ -358,7 +358,7 @@ export const SpaceHierarchy: React.FC = ({ const [selected, setSelected] = useState(new Map>()); // Map> - const [rooms, parentChildMap, viaMap, childParentMap] = useSpaceSummary(cli, space, refreshToken); + const [summaryError, rooms, parentChildMap, viaMap, childParentMap] = useSpaceSummary(cli, space, refreshToken); const roomsMap = useMemo(() => { if (!rooms) return null; @@ -397,6 +397,10 @@ export const SpaceHierarchy: React.FC = ({ const [removing, setRemoving] = useState(false); const [saving, setSaving] = useState(false); + if (summaryError) { + return

      {_t("Your server does not support showing space hierarchies.")}

      ; + } + let content; if (roomsMap) { const numRooms = Array.from(roomsMap.values()).filter(r => r.room_type !== RoomType.Space).length; @@ -538,10 +542,8 @@ export const SpaceHierarchy: React.FC = ({ { children } ; - } else if (!rooms) { - content = ; } else { - content =

      {_t("Your server does not support showing space hierarchies.")}

      ; + content = ; } // TODO loading state/error state diff --git a/src/components/structures/SpaceRoomView.tsx b/src/components/structures/SpaceRoomView.tsx index 31358a3731..cdf9dc02d3 100644 --- a/src/components/structures/SpaceRoomView.tsx +++ b/src/components/structures/SpaceRoomView.tsx @@ -51,6 +51,9 @@ import MemberAvatar from "../views/avatars/MemberAvatar"; import {useStateToggle} from "../../hooks/useStateToggle"; import SpaceStore from "../../stores/SpaceStore"; import FacePile from "../views/elements/FacePile"; +import {AddExistingToSpace} from "../views/dialogs/AddExistingToSpaceDialog"; +import {allSettled} from "../../utils/promise"; +import {calculateRoomVia} from "../../utils/permalinks/Permalinks"; interface IProps { space: Room; @@ -354,7 +357,7 @@ const SpaceSetupFirstRooms = ({ space, title, description, onFinished }) => { let buttonLabel = _t("Skip for now"); if (roomNames.some(name => name.trim())) { onClick = onNextClick; - buttonLabel = busy ? _t("Creating rooms...") : _t("Continue") + buttonLabel = busy ? _t("Creating rooms...") : _t("Continue"); } return
      @@ -376,6 +379,65 @@ const SpaceSetupFirstRooms = ({ space, title, description, onFinished }) => {
      ; }; +const SpaceAddExistingRooms = ({ space, onFinished }) => { + const [selectedToAdd, setSelectedToAdd] = useState(new Set()); + + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + + let onClick = onFinished; + let buttonLabel = _t("Skip for now"); + if (selectedToAdd.size > 0) { + onClick = async () => { + // TODO rate limiting + setBusy(true); + try { + await allSettled(Array.from(selectedToAdd).map((room) => + SpaceStore.instance.addRoomToSpace(space, room.roomId, calculateRoomVia(room)))); + onFinished(true); + } catch (e) { + console.error("Failed to add rooms to space", e); + setError(_t("Failed to add rooms to space")); + } + setBusy(false); + }; + buttonLabel = busy ? _t("Adding...") : _t("Add"); + } + + return
      +

      { _t("What do you want to organise?") }

      +
      + { _t("Pick rooms or conversations to add. This is just a space for you, " + + "no one will be informed. You can add more later.") } +
      + + { error &&
      { error }
      } + + { + if (checked) { + selectedToAdd.add(room); + } else { + selectedToAdd.delete(room); + } + setSelectedToAdd(new Set(selectedToAdd)); + }} + /> + +
      + + { buttonLabel } + +
      +
      ; +}; + const SpaceSetupPublicShare = ({ space, onFinished }) => { return

      { _t("Share %(name)s", { name: space.name }) }

      @@ -659,7 +721,7 @@ export default class SpaceRoomView extends React.PureComponent { return { - this.setState({ phase: invite ? Phase.PrivateInvite : Phase.PrivateCreateRooms }); + this.setState({ phase: invite ? Phase.PrivateInvite : Phase.PrivateExistingRooms }); }} />; case Phase.PrivateInvite: @@ -675,6 +737,11 @@ export default class SpaceRoomView extends React.PureComponent { "You can add more later too, including already existing ones.")} onFinished={() => this.setState({ phase: Phase.Landing })} />; + case Phase.PrivateExistingRooms: + return this.setState({ phase: Phase.Landing })} + />; } } diff --git a/src/components/structures/TimelinePanel.js b/src/components/structures/TimelinePanel.js index 12f5d6e890..8cc344f66b 100644 --- a/src/components/structures/TimelinePanel.js +++ b/src/components/structures/TimelinePanel.js @@ -68,6 +68,7 @@ class TimelinePanel extends React.Component { showReadReceipts: PropTypes.bool, // Enable managing RRs and RMs. These require the timelineSet to have a room. manageReadReceipts: PropTypes.bool, + sendReadReceiptOnLoad: PropTypes.bool, manageReadMarkers: PropTypes.bool, // true to give the component a 'display: none' style. @@ -126,6 +127,7 @@ class TimelinePanel extends React.Component { // event tile heights. (See _unpaginateEvents) timelineCap: Number.MAX_VALUE, className: 'mx_RoomView_messagePanel', + sendReadReceiptOnLoad: true, }; constructor(props) { @@ -785,8 +787,10 @@ class TimelinePanel extends React.Component { return; } const lastDisplayedEvent = this.state.events[lastDisplayedIndex]; - this._setReadMarker(lastDisplayedEvent.getId(), - lastDisplayedEvent.getTs()); + this._setReadMarker( + lastDisplayedEvent.getId(), + lastDisplayedEvent.getTs(), + ); // the read-marker should become invisible, so that if the user scrolls // down, they don't see it. @@ -872,7 +876,7 @@ class TimelinePanel extends React.Component { // The messagepanel knows where the RM is, so we must have loaded // the relevant event. this._messagePanel.current.scrollToEvent(this.state.readMarkerEventId, - 0, 1/3); + 0, 1/3); return; } @@ -1044,12 +1048,14 @@ class TimelinePanel extends React.Component { } if (eventId) { this._messagePanel.current.scrollToEvent(eventId, pixelOffset, - offsetBase); + offsetBase); } else { this._messagePanel.current.scrollToBottom(); } - this.sendReadReceipt(); + if (this.props.sendReadReceiptOnLoad) { + this.sendReadReceipt(); + } }); }; @@ -1418,8 +1424,8 @@ class TimelinePanel extends React.Component { ['PREPARED', 'CATCHUP'].includes(this.state.clientSyncState) ); const events = this.state.firstVisibleEventIndex - ? this.state.events.slice(this.state.firstVisibleEventIndex) - : this.state.events; + ? this.state.events.slice(this.state.firstVisibleEventIndex) + : this.state.events; return ( void, +} + +interface IState { + loginView: number; + keyBackupNeeded: boolean; + busy: boolean; + password: string; + errorText: string; + flows: LoginFlow[]; +} + +@replaceableComponent("structures.auth.SoftLogout") +export default class SoftLogout extends React.Component { + constructor(props) { + super(props); this.state = { loginView: LOGIN_VIEW.LOADING, keyBackupNeeded: true, // assume we do while we figure it out (see componentDidMount) - busy: false, password: "", errorText: "", + flows: [], }; } @@ -72,7 +83,7 @@ export default class SoftLogout extends React.Component { return; } - this._initLogin(); + this.initLogin(); const cli = MatrixClientPeg.get(); if (cli.isCryptoEnabled()) { @@ -94,7 +105,7 @@ export default class SoftLogout extends React.Component { }); }; - async _initLogin() { + private async initLogin() { const queryParams = this.props.realQueryParams; const hasAllParams = queryParams && queryParams['loginToken']; if (hasAllParams) { @@ -189,7 +200,7 @@ export default class SoftLogout extends React.Component { }); } - _renderSignInSection() { + private renderSignInSection() { if (this.state.loginView === LOGIN_VIEW.LOADING) { const Spinner = sdk.getComponent("elements.Spinner"); return ; @@ -247,7 +258,7 @@ export default class SoftLogout extends React.Component { } // else we already have a message and should use it (key backup warning) const loginType = this.state.loginView === LOGIN_VIEW.CAS ? "cas" : "sso"; - const flow = this.state.flows.find(flow => flow.type === "m.login." + loginType); + const flow = this.state.flows.find(flow => flow.type === "m.login." + loginType) as ISSOFlow; return (
      @@ -289,7 +300,7 @@ export default class SoftLogout extends React.Component {

      {_t("Sign in")}

      - {this._renderSignInSection()} + {this.renderSignInSection()}

      {_t("Clear personal data")}

      diff --git a/src/components/views/auth/InteractiveAuthEntryComponents.js b/src/components/views/auth/InteractiveAuthEntryComponents.js index 6cbecd22ee..e34349c474 100644 --- a/src/components/views/auth/InteractiveAuthEntryComponents.js +++ b/src/components/views/auth/InteractiveAuthEntryComponents.js @@ -169,7 +169,7 @@ export class PasswordAuthEntry extends React.Component { { submitButtonOrSpinner }
      - { errorSection } + { errorSection }
      ); } @@ -375,7 +375,7 @@ export class TermsAuthEntry extends React.Component { if (this.props.showContinue !== false) { // XXX: button classes submitButton = ; + onClick={this._trySubmit} disabled={!allChecked}>{_t("Accept")}; } return ( diff --git a/src/components/views/avatars/MemberAvatar.tsx b/src/components/views/avatars/MemberAvatar.tsx index c79cbc0d32..3205ca372c 100644 --- a/src/components/views/avatars/MemberAvatar.tsx +++ b/src/components/views/avatars/MemberAvatar.tsx @@ -68,8 +68,8 @@ export default class MemberAvatar extends React.Component { let imageUrl = null; if (props.member.getMxcAvatarUrl()) { imageUrl = mediaFromMxc(props.member.getMxcAvatarUrl()).getThumbnailOfSourceHttp( - Math.floor(props.width * window.devicePixelRatio), - Math.floor(props.height * window.devicePixelRatio), + props.width, + props.height, props.resizeMethod, ); } diff --git a/src/components/views/avatars/RoomAvatar.tsx b/src/components/views/avatars/RoomAvatar.tsx index ad0eb45a52..4693d907ba 100644 --- a/src/components/views/avatars/RoomAvatar.tsx +++ b/src/components/views/avatars/RoomAvatar.tsx @@ -93,8 +93,8 @@ export default class RoomAvatar extends React.Component { let oobAvatar = null; if (props.oobData.avatarUrl) { oobAvatar = mediaFromMxc(props.oobData.avatarUrl).getThumbnailOfSourceHttp( - Math.floor(props.width * window.devicePixelRatio), - Math.floor(props.height * window.devicePixelRatio), + props.width, + props.height, props.resizeMethod, ); } @@ -109,12 +109,7 @@ export default class RoomAvatar extends React.Component { private static getRoomAvatarUrl(props: IProps): string { if (!props.room) return null; - return Avatar.avatarUrlForRoom( - props.room, - Math.floor(props.width * window.devicePixelRatio), - Math.floor(props.height * window.devicePixelRatio), - props.resizeMethod, - ); + return Avatar.avatarUrlForRoom(props.room, props.width, props.height, props.resizeMethod); } private onRoomAvatarClick = () => { diff --git a/src/components/views/context_menus/MessageContextMenu.js b/src/components/views/context_menus/MessageContextMenu.js index f86cd26f32..35efd12c9c 100644 --- a/src/components/views/context_menus/MessageContextMenu.js +++ b/src/components/views/context_menus/MessageContextMenu.js @@ -1,8 +1,6 @@ /* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2018 New Vector Ltd Copyright 2019 Michael Telatynski <7t3chguy@gmail.com> -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2015, 2016, 2018, 2019, 2021 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. @@ -34,7 +32,7 @@ import {MenuItem} from "../../structures/ContextMenu"; import {EventType} from "matrix-js-sdk/src/@types/event"; import {replaceableComponent} from "../../../utils/replaceableComponent"; -function canCancel(eventStatus) { +export function canCancel(eventStatus) { return eventStatus === EventStatus.QUEUED || eventStatus === EventStatus.NOT_SENT; } @@ -98,21 +96,6 @@ export default class MessageContextMenu extends React.Component { return content.pinned && Array.isArray(content.pinned) && content.pinned.includes(this.props.mxEvent.getId()); } - onResendClick = () => { - Resend.resend(this.props.mxEvent); - this.closeMenu(); - }; - - onResendEditClick = () => { - Resend.resend(this.props.mxEvent.replacingEvent()); - this.closeMenu(); - }; - - onResendRedactionClick = () => { - Resend.resend(this.props.mxEvent.localRedactionEvent()); - this.closeMenu(); - }; - onResendReactionsClick = () => { for (const reaction of this._getUnsentReactions()) { Resend.resend(reaction); @@ -170,29 +153,6 @@ export default class MessageContextMenu extends React.Component { this.closeMenu(); }; - onCancelSendClick = () => { - const mxEvent = this.props.mxEvent; - const editEvent = mxEvent.replacingEvent(); - const redactEvent = mxEvent.localRedactionEvent(); - const pendingReactions = this._getPendingReactions(); - - if (editEvent && canCancel(editEvent.status)) { - Resend.removeFromQueue(editEvent); - } - if (redactEvent && canCancel(redactEvent.status)) { - Resend.removeFromQueue(redactEvent); - } - if (pendingReactions.length) { - for (const reaction of pendingReactions) { - Resend.removeFromQueue(reaction); - } - } - if (canCancel(mxEvent.status)) { - Resend.removeFromQueue(this.props.mxEvent); - } - this.closeMenu(); - }; - onForwardClick = () => { if (this.props.onCloseDialog) this.props.onCloseDialog(); dis.dispatch({ @@ -285,20 +245,9 @@ export default class MessageContextMenu extends React.Component { const me = cli.getUserId(); const mxEvent = this.props.mxEvent; const eventStatus = mxEvent.status; - const editStatus = mxEvent.replacingEvent() && mxEvent.replacingEvent().status; - const redactStatus = mxEvent.localRedactionEvent() && mxEvent.localRedactionEvent().status; const unsentReactionsCount = this._getUnsentReactions().length; - const pendingReactionsCount = this._getPendingReactions().length; - const allowCancel = canCancel(mxEvent.status) || - canCancel(editStatus) || - canCancel(redactStatus) || - pendingReactionsCount !== 0; - let resendButton; - let resendEditButton; let resendReactionsButton; - let resendRedactionButton; let redactButton; - let cancelButton; let forwardButton; let pinButton; let unhidePreviewButton; @@ -309,22 +258,6 @@ export default class MessageContextMenu extends React.Component { // status is SENT before remote-echo, null after const isSent = !eventStatus || eventStatus === EventStatus.SENT; if (!mxEvent.isRedacted()) { - if (eventStatus === EventStatus.NOT_SENT) { - resendButton = ( - - { _t('Resend') } - - ); - } - - if (editStatus === EventStatus.NOT_SENT) { - resendEditButton = ( - - { _t('Resend edit') } - - ); - } - if (unsentReactionsCount !== 0) { resendReactionsButton = ( @@ -334,14 +267,6 @@ export default class MessageContextMenu extends React.Component { } } - if (redactStatus === EventStatus.NOT_SENT) { - resendRedactionButton = ( - - { _t('Resend removal') } - - ); - } - if (isSent && this.state.canRedact) { redactButton = ( @@ -350,14 +275,6 @@ export default class MessageContextMenu extends React.Component { ); } - if (allowCancel) { - cancelButton = ( - - { _t('Cancel Sending') } - - ); - } - if (isContentActionable(mxEvent)) { forwardButton = ( @@ -433,7 +350,7 @@ export default class MessageContextMenu extends React.Component { > { _t('Source URL') } - ); + ); } if (this.props.collapseReplyThread) { @@ -455,12 +372,8 @@ export default class MessageContextMenu extends React.Component { return (
      - { resendButton } - { resendEditButton } { resendReactionsButton } - { resendRedactionButton } { redactButton } - { cancelButton } { forwardButton } { pinButton } { viewSourceButton } diff --git a/src/components/views/dialogs/AddExistingToSpaceDialog.tsx b/src/components/views/dialogs/AddExistingToSpaceDialog.tsx index 04bec39238..1f45a76008 100644 --- a/src/components/views/dialogs/AddExistingToSpaceDialog.tsx +++ b/src/components/views/dialogs/AddExistingToSpaceDialog.tsx @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React, {useState} from "react"; +import React, {useContext, useState} from "react"; import classNames from "classnames"; import {Room} from "matrix-js-sdk/src/models/room"; import {MatrixClient} from "matrix-js-sdk/src/client"; @@ -33,6 +33,7 @@ import {allSettled} from "../../../utils/promise"; import DMRoomMap from "../../../utils/DMRoomMap"; import {calculateRoomVia} from "../../../utils/permalinks/Permalinks"; import StyledCheckbox from "../elements/StyledCheckbox"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; interface IProps extends IDialogProps { matrixClient: MatrixClient; @@ -41,43 +42,122 @@ interface IProps extends IDialogProps { } const Entry = ({ room, checked, onChange }) => { - return
      + return ; +}; + +interface IAddExistingToSpaceProps { + space: Room; + selected: Set; + onChange(checked: boolean, room: Room): void; +} + +export const AddExistingToSpace: React.FC = ({ space, selected, onChange }) => { + const cli = useContext(MatrixClientContext); + const [query, setQuery] = useState(""); + const lcQuery = query.toLowerCase(); + + const existingSubspaces = SpaceStore.instance.getChildSpaces(space.roomId); + const existingSubspacesSet = new Set(existingSubspaces); + const existingRoomsSet = new Set(SpaceStore.instance.getChildRooms(space.roomId)); + + const joinRule = space.getJoinRule(); + const [spaces, rooms, dms] = cli.getVisibleRooms().reduce((arr, room) => { + if (room.getMyMembership() !== "join") return arr; + if (!room.name.toLowerCase().includes(lcQuery)) return arr; + + if (room.isSpaceRoom()) { + if (room !== space && !existingSubspacesSet.has(room)) { + arr[0].push(room); + } + } else if (!existingRoomsSet.has(room)) { + if (!DMRoomMap.shared().getUserIdForRoomId(room.roomId)) { + arr[1].push(room); + } else if (joinRule !== "public") { + // Only show DMs for non-public spaces as they make very little sense in spaces other than "Just Me" ones. + arr[2].push(room); + } + } + return arr; + }, [[], [], []]); + + return
      + + + { rooms.length > 0 ? ( +
      +

      { _t("Rooms") }

      + { rooms.map(room => { + return { + onChange(checked, room); + }} + />; + }) } +
      + ) : undefined } + + { spaces.length > 0 ? ( +
      +

      { _t("Spaces") }

      + { spaces.map(space => { + return { + onChange(checked, space); + }} + />; + }) } +
      + ) : null } + + { dms.length > 0 ? ( +
      +

      { _t("Direct Messages") }

      + { dms.map(room => { + return { + onChange(checked, room); + }} + />; + }) } +
      + ) : null } + + { spaces.length + rooms.length + dms.length < 1 ? + { _t("No results") } + : undefined } +
      ; }; const AddExistingToSpaceDialog: React.FC = ({ matrixClient: cli, space, onCreateRoomClick, onFinished }) => { - const [query, setQuery] = useState(""); - const lcQuery = query.toLowerCase(); - const [selectedSpace, setSelectedSpace] = useState(space); - const [selectedToAdd, setSelectedToAdd] = useState(new Set()); - const existingSubspaces = SpaceStore.instance.getChildSpaces(space.roomId); - const existingSubspacesSet = new Set(existingSubspaces); - const spaces = SpaceStore.instance.getSpaces().filter(s => { - return !existingSubspacesSet.has(s) // not already in space - && space !== s // not the top-level space - && selectedSpace !== s // not the selected space - && s.name.toLowerCase().includes(lcQuery); // contains query - }); - - const existingRooms = SpaceStore.instance.getChildRooms(space.roomId); - const existingRoomsSet = new Set(existingRooms); - const rooms = cli.getVisibleRooms().filter(room => { - return !existingRoomsSet.has(room) // not already in space - && !room.isSpaceRoom() // not a space itself - && room.name.toLowerCase().includes(lcQuery) // contains query - && !DMRoomMap.shared().getUserIdForRoomId(room.roomId); // not a DM - }); + const [selectedToAdd, setSelectedToAdd] = useState(new Set()); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); let spaceOptionSection; - if (existingSubspacesSet.size > 0) { + if (existingSubspaces.length > 0) { const options = [space, ...existingSubspaces].map((space) => { const classes = classNames("mx_AddExistingToSpaceDialog_dropdownOption", { mx_AddExistingToSpaceDialog_dropdownOptionActive: space === selectedSpace, @@ -117,65 +197,26 @@ const AddExistingToSpaceDialog: React.FC = ({ matrixClient: cli, space, return { error &&
      { error }
      } - - - { rooms.length > 0 ? ( -
      -

      { _t("Rooms") }

      - { rooms.map(room => { - return { - if (checked) { - selectedToAdd.add(room); - } else { - selectedToAdd.delete(room); - } - setSelectedToAdd(new Set(selectedToAdd)); - }} - />; - }) } -
      - ) : undefined } - - { spaces.length > 0 ? ( -
      -

      { _t("Spaces") }

      - { spaces.map(space => { - return { - if (checked) { - selectedToAdd.add(space); - } else { - selectedToAdd.delete(space); - } - setSelectedToAdd(new Set(selectedToAdd)); - }} - />; - }) } -
      - ) : null } - - { spaces.length + rooms.length < 1 ? - { _t("No results") } - : undefined } -
      + + { + if (checked) { + selectedToAdd.add(room); + } else { + selectedToAdd.delete(room); + } + setSelectedToAdd(new Set(selectedToAdd)); + }} + /> +
      @@ -189,6 +230,7 @@ const AddExistingToSpaceDialog: React.FC = ({ matrixClient: cli, space, kind="primary" disabled={busy || selectedToAdd.size < 1} onClick={async () => { + // TODO rate limiting setBusy(true); try { await allSettled(Array.from(selectedToAdd).map((room) => diff --git a/src/components/views/dialogs/BugReportDialog.js b/src/components/views/dialogs/BugReportDialog.js index 8948c14c7c..cbe0130649 100644 --- a/src/components/views/dialogs/BugReportDialog.js +++ b/src/components/views/dialogs/BugReportDialog.js @@ -184,7 +184,7 @@ export default class BugReportDialog extends React.Component { return (
      diff --git a/src/components/views/dialogs/ChangelogDialog.js b/src/components/views/dialogs/ChangelogDialog.js index 50bc13cff5..efbeba3977 100644 --- a/src/components/views/dialogs/ChangelogDialog.js +++ b/src/components/views/dialogs/ChangelogDialog.js @@ -95,7 +95,7 @@ export default class ChangelogDialog extends React.Component { description={content} button={_t("Update")} onFinished={this.props.onFinished} - /> + /> ); } } diff --git a/src/components/views/dialogs/ConfirmWipeDeviceDialog.js b/src/components/views/dialogs/ConfirmWipeDeviceDialog.js index 4faaad0f7e..333e1522f1 100644 --- a/src/components/views/dialogs/ConfirmWipeDeviceDialog.js +++ b/src/components/views/dialogs/ConfirmWipeDeviceDialog.js @@ -39,9 +39,12 @@ export default class ConfirmWipeDeviceDialog extends React.Component { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); return ( - +

      {_t( diff --git a/src/components/views/dialogs/DevtoolsDialog.js b/src/components/views/dialogs/DevtoolsDialog.js index 9f5513e0a3..8a035263cc 100644 --- a/src/components/views/dialogs/DevtoolsDialog.js +++ b/src/components/views/dialogs/DevtoolsDialog.js @@ -70,8 +70,16 @@ class GenericEditor extends React.PureComponent { } textInput(id, label) { - return ; + return ; } } @@ -155,7 +163,7 @@ export class SendCustomEvent extends GenericEditor {
      + autoComplete="off" value={this.state.evContent} onChange={this._onChange} element="textarea" />

      @@ -239,7 +247,7 @@ class SendAccountData extends GenericEditor {
      + autoComplete="off" value={this.state.evContent} onChange={this._onChange} element="textarea" />
      @@ -315,15 +323,15 @@ class FilteredList extends React.PureComponent { const TruncatedList = sdk.getComponent("elements.TruncatedList"); return
      + type="text" autoComplete="off" value={this.props.query} onChange={this.onQuery} + className="mx_TextInputDialog_input mx_DevTools_RoomStateExplorer_query" + // force re-render so that autoFocus is applied when this component is re-used + key={this.props.children[0] ? this.props.children[0].key : ''} /> + getChildCount={this.getChildCount} + truncateAt={this.state.truncateAt} + createOverflowElement={this.createOverflowElement} />
      ; } } @@ -647,7 +655,7 @@ function VerificationRequest({txnId, request}) { /* Note that request.timeout is a getter, so its value changes */ const id = setInterval(() => { - setRequestTimeout(request.timeout); + setRequestTimeout(request.timeout); }, 500); return () => { clearInterval(id); }; @@ -941,35 +949,35 @@ class SettingsExplorer extends React.Component { /> - - - - - + + + + + - {allSettings.map(i => ( - - + - - - - ))} + + + + + + ))}
      {_t("Setting ID")}{_t("Value")}{_t("Value in this room")}
      {_t("Setting ID")}{_t("Value")}{_t("Value in this room")}
      - this.onViewClick(e, i)}> - {i} - - this.onEditClick(e, i)} - className='mx_DevTools_SettingsExplorer_edit' - > + {allSettings.map(i => ( +
      + this.onViewClick(e, i)}> + {i} + + this.onEditClick(e, i)} + className='mx_DevTools_SettingsExplorer_edit' + > ✏ - - - {this.renderSettingValue(SettingsStore.getValue(i))} - - - {this.renderSettingValue(SettingsStore.getValue(i, room.roomId))} - -
      + {this.renderSettingValue(SettingsStore.getValue(i))} + + + {this.renderSettingValue(SettingsStore.getValue(i, room.roomId))} + +
      @@ -998,11 +1006,11 @@ class SettingsExplorer extends React.Component {
      - - - - - + + + + + {LEVEL_ORDER.map(lvl => ( diff --git a/src/components/views/dialogs/IncomingSasDialog.js b/src/components/views/dialogs/IncomingSasDialog.js index f18b7a9d0c..5df02d7a6f 100644 --- a/src/components/views/dialogs/IncomingSasDialog.js +++ b/src/components/views/dialogs/IncomingSasDialog.js @@ -130,7 +130,7 @@ export default class IncomingSasDialog extends React.Component { const oppProfile = this.state.opponentProfile; if (oppProfile) { const url = oppProfile.avatar_url - ? mediaFromMxc(oppProfile.avatar_url).getSquareThumbnailHttp(Math.floor(48 * window.devicePixelRatio)) + ? mediaFromMxc(oppProfile.avatar_url).getSquareThumbnailHttp(48) : null; profile =
      +

      {_t("Enable 'Manage Integrations' in Settings to do this.")}

      diff --git a/src/components/views/dialogs/IntegrationsImpossibleDialog.js b/src/components/views/dialogs/IntegrationsImpossibleDialog.js index 9bc9d02ba6..e14d40aaef 100644 --- a/src/components/views/dialogs/IntegrationsImpossibleDialog.js +++ b/src/components/views/dialogs/IntegrationsImpossibleDialog.js @@ -37,9 +37,12 @@ export default class IntegrationsImpossibleDialog extends React.Component { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); return ( - +

      {_t( diff --git a/src/components/views/dialogs/KeySignatureUploadFailedDialog.js b/src/components/views/dialogs/KeySignatureUploadFailedDialog.js index 25eb7a90d2..bcb4d4f9b9 100644 --- a/src/components/views/dialogs/KeySignatureUploadFailedDialog.js +++ b/src/components/views/dialogs/KeySignatureUploadFailedDialog.js @@ -24,7 +24,7 @@ export default function KeySignatureUploadFailedDialog({ source, continuation, onFinished, - }) { +}) { const RETRIES = 2; const BaseDialog = sdk.getComponent('dialogs.BaseDialog'); const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); @@ -84,10 +84,10 @@ export default function KeySignatureUploadFailedDialog({ } else { body = (

      {success ? - {_t("Upload completed")} : - cancelled ? - {_t("Cancelled signature upload")} : - {_t("Unable to upload")}} + {_t("Upload completed")} : + cancelled ? + {_t("Cancelled signature upload")} : + {_t("Unable to upload")}} + {content} ); diff --git a/src/components/views/dialogs/RoomSettingsDialog.js b/src/components/views/dialogs/RoomSettingsDialog.js index 9c2f23ef22..b6c4d42243 100644 --- a/src/components/views/dialogs/RoomSettingsDialog.js +++ b/src/components/views/dialogs/RoomSettingsDialog.js @@ -116,8 +116,12 @@ export default class RoomSettingsDialog extends React.Component { const roomName = MatrixClientPeg.get().getRoom(this.props.roomId).name; return ( - +
      diff --git a/src/components/views/dialogs/ServerPickerDialog.tsx b/src/components/views/dialogs/ServerPickerDialog.tsx index 4abc0a88b1..62a2b95c68 100644 --- a/src/components/views/dialogs/ServerPickerDialog.tsx +++ b/src/components/views/dialogs/ServerPickerDialog.tsx @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020-2021 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. @@ -110,7 +110,7 @@ export default class ServerPickerDialog extends React.PureComponent diff --git a/src/components/views/dialogs/SeshatResetDialog.tsx b/src/components/views/dialogs/SeshatResetDialog.tsx index 135f5d8197..63654ca949 100644 --- a/src/components/views/dialogs/SeshatResetDialog.tsx +++ b/src/components/views/dialogs/SeshatResetDialog.tsx @@ -36,7 +36,7 @@ export default class SeshatResetDialog extends React.PureComponent {_t("You most likely do not want to reset your event index store")}
      {_t("If you do, please note that none of your messages will be deleted, " + - "but the search experience might be degraded for a few moments" + + "but the search experience might be degraded for a few moments " + "whilst the index is recreated", )}

      diff --git a/src/components/views/dialogs/SessionRestoreErrorDialog.js b/src/components/views/dialogs/SessionRestoreErrorDialog.js index 50d7fbea09..43e73a2f83 100644 --- a/src/components/views/dialogs/SessionRestoreErrorDialog.js +++ b/src/components/views/dialogs/SessionRestoreErrorDialog.js @@ -98,7 +98,7 @@ export default class SessionRestoreErrorDialog extends React.Component { "may be incompatible with this version. Close this window and return " + "to the more recent version.", { brand }, - ) }

      + ) }

      { _t( "Clearing your browser's storage may fix the problem, but will sign you " + diff --git a/src/components/views/dialogs/StorageEvictedDialog.js b/src/components/views/dialogs/StorageEvictedDialog.js index 15c5347644..1e17ab1738 100644 --- a/src/components/views/dialogs/StorageEvictedDialog.js +++ b/src/components/views/dialogs/StorageEvictedDialog.js @@ -45,10 +45,12 @@ export default class StorageEvictedDialog extends React.Component { let logRequest; if (SdkConfig.get().bug_report_endpoint_url) { logRequest = _t( - "To help us prevent this in future, please send us logs.", {}, - { - a: text => {text}, - }); + "To help us prevent this in future, please send us logs.", + {}, + { + a: text => {text}, + }, + ); } return ( diff --git a/src/components/views/dialogs/UserSettingsDialog.js b/src/components/views/dialogs/UserSettingsDialog.js index eb9eaeb5dd..e7f6953589 100644 --- a/src/components/views/dialogs/UserSettingsDialog.js +++ b/src/components/views/dialogs/UserSettingsDialog.js @@ -155,8 +155,12 @@ export default class UserSettingsDialog extends React.Component { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); return ( - +

      diff --git a/src/components/views/dialogs/VerificationRequestDialog.js b/src/components/views/dialogs/VerificationRequestDialog.js index 205597a1c4..9281275e6a 100644 --- a/src/components/views/dialogs/VerificationRequestDialog.js +++ b/src/components/views/dialogs/VerificationRequestDialog.js @@ -52,11 +52,13 @@ export default class VerificationRequestDialog extends React.Component { const title = request && request.isSelfVerification ? _t("Verify other login") : _t("Verification Request"); - return + return +

      {_t("The widget will verify your user ID, but won't be able to perform actions for you:")} diff --git a/src/components/views/dialogs/security/ConfirmDestroyCrossSigningDialog.js b/src/components/views/dialogs/security/ConfirmDestroyCrossSigningDialog.js index 43fb25f152..e71983b074 100644 --- a/src/components/views/dialogs/security/ConfirmDestroyCrossSigningDialog.js +++ b/src/components/views/dialogs/security/ConfirmDestroyCrossSigningDialog.js @@ -40,10 +40,11 @@ export default class ConfirmDestroyCrossSigningDialog extends React.Component { return ( + className='mx_ConfirmDestroyCrossSigningDialog' + hasCancel={true} + onFinished={this.props.onFinished} + title={_t("Destroy cross-signing keys?")} + >

      {_t( diff --git a/src/components/views/dialogs/security/RestoreKeyBackupDialog.js b/src/components/views/dialogs/security/RestoreKeyBackupDialog.js index 1fafe03d95..4ac15ab5a3 100644 --- a/src/components/views/dialogs/security/RestoreKeyBackupDialog.js +++ b/src/components/views/dialogs/security/RestoreKeyBackupDialog.js @@ -373,21 +373,24 @@ export default class RestoreKeyBackupDialog extends React.PureComponent { {_t( "If you've forgotten your Security Phrase you can "+ "use your Security Key or " + - "set up new recovery options" - , {}, { - button1: s => - {s} - , - button2: s => - {s} - , - })} + "set up new recovery options", + {}, + { + button1: s => + {s} + , + button2: s => + {s} + , + })}

      ; } else { title = _t("Enter Security Key"); @@ -435,15 +438,17 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
      {_t( "If you've forgotten your Security Key you can "+ - "" - , {}, { - button: s => - {s} - , - })} + "", + {}, + { + button: s => + {s} + , + }, + )}
      ; } @@ -452,9 +457,9 @@ export default class RestoreKeyBackupDialog extends React.PureComponent { onFinished={this.props.onFinished} title={title} > -
      - {content} -
      +
      + {content} +
      ); } diff --git a/src/components/views/elements/ActionButton.js b/src/components/views/elements/ActionButton.js index 1714891cb5..9903c631b2 100644 --- a/src/components/views/elements/ActionButton.js +++ b/src/components/views/elements/ActionButton.js @@ -70,8 +70,8 @@ export default class ActionButton extends React.Component { } const icon = this.props.iconPath ? - () : - undefined; + () : + undefined; const classNames = ["mx_RoleButton"]; if (this.props.className) { diff --git a/src/components/views/elements/AppTile.js b/src/components/views/elements/AppTile.js index e206fda797..b898ad2ebc 100644 --- a/src/components/views/elements/AppTile.js +++ b/src/components/views/elements/AppTile.js @@ -109,7 +109,7 @@ export default class AppTile extends React.Component { const childContentProtocol = u.protocol; if (parentContentProtocol === 'https:' && childContentProtocol !== 'https:') { console.warn("Refusing to load mixed-content app:", - parentContentProtocol, childContentProtocol, window.location, this.props.app.url); + parentContentProtocol, childContentProtocol, window.location, this.props.app.url); return true; } return false; diff --git a/src/components/views/elements/EditableItemList.js b/src/components/views/elements/EditableItemList.js index ff62f169fa..d8ec5af278 100644 --- a/src/components/views/elements/EditableItemList.js +++ b/src/components/views/elements/EditableItemList.js @@ -65,12 +65,18 @@ export class EditableItem extends React.Component { {_t("Are you sure?")} - + {_t("Yes")} - + {_t("No")}
      @@ -121,11 +127,15 @@ export default class EditableItemList extends React.Component { _renderNewItemField() { return ( -
      + + autoComplete="off" value={this.props.newItem || ""} onChange={this._onNewItemChanged} + list={this.props.suggestionsListId} /> {_t("Add")} diff --git a/src/components/views/elements/EditableText.js b/src/components/views/elements/EditableText.js index 638fd02553..7c38ac1777 100644 --- a/src/components/views/elements/EditableText.js +++ b/src/components/views/elements/EditableText.js @@ -221,13 +221,15 @@ export default class EditableText extends React.Component {
      ; } else { // show the content editable div, but manually manage its contents as react and contentEditable don't play nice together - editableEl =
      ; + editableEl =
      ; } return editableEl; diff --git a/src/components/views/elements/FacePile.tsx b/src/components/views/elements/FacePile.tsx index e223744352..aeca2e844b 100644 --- a/src/components/views/elements/FacePile.tsx +++ b/src/components/views/elements/FacePile.tsx @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React, { HTMLAttributes } from "react"; +import React, { HTMLAttributes, ReactNode, useContext } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; import { RoomMember } from "matrix-js-sdk/src/models/room-member"; import { sortBy } from "lodash"; @@ -24,6 +24,7 @@ import { _t } from "../../../languageHandler"; import DMRoomMap from "../../../utils/DMRoomMap"; import TextWithTooltip from "../elements/TextWithTooltip"; import { useRoomMembers } from "../../../hooks/useRoomMembers"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; const DEFAULT_NUM_FACES = 5; @@ -36,6 +37,7 @@ interface IProps extends HTMLAttributes { const isKnownMember = (member: RoomMember) => !!DMRoomMap.shared().getDMRoomsForUserId(member.userId)?.length; const FacePile = ({ room, onlyKnownUsers = true, numShown = DEFAULT_NUM_FACES, ...props }: IProps) => { + const cli = useContext(MatrixClientContext); let members = useRoomMembers(room); // sort users with an explicit avatar first @@ -46,21 +48,42 @@ const FacePile = ({ room, onlyKnownUsers = true, numShown = DEFAULT_NUM_FACES, . // sort known users first iteratees.unshift(member => isKnownMember(member)); } - if (members.length < 1) return null; - const shownMembers = sortBy(members, iteratees).slice(0, numShown); + // exclude ourselves from the shown members list + const shownMembers = sortBy(members.filter(m => m.userId !== cli.getUserId()), iteratees).slice(0, numShown); + if (shownMembers.length < 1) return null; + + // We reverse the order of the shown faces in CSS to simplify their visual overlap, + // reverse members in tooltip order to make the order between the two match up. + const commaSeparatedMembers = shownMembers.map(m => m.rawDisplayName).reverse().join(", "); + + let tooltip: ReactNode; + if (props.onClick) { + tooltip =
      +
      + { _t("View all %(count)s members", { count: members.length }) } +
      +
      + { _t("Including %(commaSeparatedMembers)s", { commaSeparatedMembers }) } +
      +
      ; + } else { + tooltip = _t("%(count)s members including %(commaSeparatedMembers)s", { + count: members.length, + commaSeparatedMembers, + }); + } + return
      -
      - { shownMembers.map(member => { - return - - ; - }) } -
      - { onlyKnownUsers && + + { members.length > numShown ? : null } + { shownMembers.map(m => + )} + + { onlyKnownUsers && { _t("%(count)s people you know have already joined", { count: members.length }) } } -
      +
      ; }; export default FacePile; diff --git a/src/components/views/elements/Field.tsx b/src/components/views/elements/Field.tsx index f5754da9ae..59d9a11596 100644 --- a/src/components/views/elements/Field.tsx +++ b/src/components/views/elements/Field.tsx @@ -262,7 +262,7 @@ export default class Field extends React.PureComponent { tooltipClassName={classNames("mx_Field_tooltip", tooltipClassName)} visible={(this.state.focused && this.props.forceTooltipVisible) || this.state.feedbackVisible} label={tooltipContent || this.state.feedback} - forceOnRight + alignment={Tooltip.Alignment.Right} />; } diff --git a/src/components/views/elements/ImageView.tsx b/src/components/views/elements/ImageView.tsx index dad62521da..fcacae2d39 100644 --- a/src/components/views/elements/ImageView.tsx +++ b/src/components/views/elements/ImageView.tsx @@ -32,17 +32,17 @@ import dis from '../../../dispatcher/dispatcher'; import {replaceableComponent} from "../../../utils/replaceableComponent"; import {RoomPermalinkCreator} from "../../../utils/permalinks/Permalinks" import {MatrixEvent} from "matrix-js-sdk/src/models/event"; +import {normalizeWheelEvent} from "../../../utils/Mouse"; -const MIN_ZOOM = 100; -const MAX_ZOOM = 300; +// Max scale to keep gaps around the image +const MAX_SCALE = 0.95; // This is used for the buttons -const ZOOM_STEP = 10; +const ZOOM_STEP = 0.10; // This is used for mouse wheel events -const ZOOM_COEFFICIENT = 10; +const ZOOM_COEFFICIENT = 0.0025; // If we have moved only this much we can zoom const ZOOM_DISTANCE = 10; - interface IProps { src: string, // the source of the image being displayed name?: string, // the main title ('name') for the image @@ -61,8 +61,10 @@ interface IProps { } interface IState { - rotation: number, zoom: number, + minZoom: number, + maxZoom: number, + rotation: number, translationX: number, translationY: number, moving: boolean, @@ -74,8 +76,10 @@ export default class ImageView extends React.Component { constructor(props) { super(props); this.state = { + zoom: 0, + minZoom: MAX_SCALE, + maxZoom: MAX_SCALE, rotation: 0, - zoom: MIN_ZOOM, translationX: 0, translationY: 0, moving: false, @@ -86,6 +90,8 @@ export default class ImageView extends React.Component { // XXX: Refs to functional components private contextMenuButton = createRef(); private focusLock = createRef(); + private imageWrapper = createRef(); + private image = createRef(); private initX = 0; private initY = 0; @@ -98,12 +104,87 @@ export default class ImageView extends React.Component { // We have to use addEventListener() because the listener // needs to be passive in order to work with Chromium this.focusLock.current.addEventListener('wheel', this.onWheel, { passive: false }); + // We want to recalculate zoom whenever the window's size changes + window.addEventListener("resize", this.calculateZoom); + // After the image loads for the first time we want to calculate the zoom + this.image.current.addEventListener("load", this.calculateZoom); + // Try to precalculate the zoom from width and height props + this.calculateZoom(); } componentWillUnmount() { this.focusLock.current.removeEventListener('wheel', this.onWheel); } + private calculateZoom = () => { + const image = this.image.current; + const imageWrapper = this.imageWrapper.current; + + const width = this.props.width || image.naturalWidth; + const height = this.props.height || image.naturalHeight; + + const zoomX = imageWrapper.clientWidth / width; + const zoomY = imageWrapper.clientHeight / height; + + // If the image is smaller in both dimensions set its the zoom to 1 to + // display it in its original size + if (zoomX >= 1 && zoomY >= 1) { + this.setState({ + zoom: 1, + minZoom: 1, + maxZoom: 1, + }); + return; + } + // We set minZoom to the min of the zoomX and zoomY to avoid overflow in + // any direction. We also multiply by MAX_SCALE to get a gap around the + // image by default + const minZoom = Math.min(zoomX, zoomY) * MAX_SCALE; + + if (this.state.zoom <= this.state.minZoom) this.setState({zoom: minZoom}); + this.setState({ + minZoom: minZoom, + maxZoom: 1, + }); + } + + private zoom(delta: number) { + const newZoom = this.state.zoom + delta; + + if (newZoom <= this.state.minZoom) { + this.setState({ + zoom: this.state.minZoom, + translationX: 0, + translationY: 0, + }); + return; + } + if (newZoom >= this.state.maxZoom) { + this.setState({zoom: this.state.maxZoom}); + return; + } + + this.setState({ + zoom: newZoom, + }); + } + + private onWheel = (ev: WheelEvent) => { + ev.stopPropagation(); + ev.preventDefault(); + + const {deltaY} = normalizeWheelEvent(ev); + this.zoom(-(deltaY * ZOOM_COEFFICIENT)); + }; + + private onZoomInClick = () => { + this.zoom(ZOOM_STEP); + }; + + private onZoomOutClick = () => { + this.zoom(-ZOOM_STEP); + }; + private onKeyDown = (ev: KeyboardEvent) => { if (ev.key === Key.ESCAPE) { ev.stopPropagation(); @@ -112,29 +193,6 @@ export default class ImageView extends React.Component { } }; - private onWheel = (ev: WheelEvent) => { - ev.stopPropagation(); - ev.preventDefault(); - const newZoom = this.state.zoom - (ev.deltaY * ZOOM_COEFFICIENT); - - if (newZoom <= MIN_ZOOM) { - this.setState({ - zoom: MIN_ZOOM, - translationX: 0, - translationY: 0, - }); - return; - } - if (newZoom >= MAX_ZOOM) { - this.setState({zoom: MAX_ZOOM}); - return; - } - - this.setState({ - zoom: newZoom, - }); - }; - private onRotateCounterClockwiseClick = () => { const cur = this.state.rotation; const rotationDegrees = cur - 90; @@ -147,31 +205,6 @@ export default class ImageView extends React.Component { this.setState({ rotation: rotationDegrees }); }; - private onZoomInClick = () => { - if (this.state.zoom >= MAX_ZOOM) { - this.setState({zoom: MAX_ZOOM}); - return; - } - - this.setState({ - zoom: this.state.zoom + ZOOM_STEP, - }); - }; - - private onZoomOutClick = () => { - if (this.state.zoom <= MIN_ZOOM) { - this.setState({ - zoom: MIN_ZOOM, - translationX: 0, - translationY: 0, - }); - return; - } - this.setState({ - zoom: this.state.zoom - ZOOM_STEP, - }); - }; - private onDownloadClick = () => { const a = document.createElement("a"); a.href = this.props.src; @@ -209,9 +242,13 @@ export default class ImageView extends React.Component { ev.stopPropagation(); ev.preventDefault(); + // Don't do anything if we pressed any + // other button than the left one + if (ev.button !== 0) return; + // Zoom in if we are completely zoomed out - if (this.state.zoom === MIN_ZOOM) { - this.setState({zoom: MAX_ZOOM}); + if (this.state.zoom === this.state.minZoom) { + this.setState({zoom: this.state.maxZoom}); return; } @@ -244,7 +281,7 @@ export default class ImageView extends React.Component { Math.abs(this.state.translationY - this.previousY) < ZOOM_DISTANCE ) { this.setState({ - zoom: MIN_ZOOM, + zoom: this.state.minZoom, translationX: 0, translationY: 0, }); @@ -279,17 +316,20 @@ export default class ImageView extends React.Component { render() { const showEventMeta = !!this.props.mxEvent; + const zoomingDisabled = this.state.maxZoom === this.state.minZoom; let cursor; if (this.state.moving) { cursor= "grabbing"; - } else if (this.state.zoom === MIN_ZOOM) { + } else if (zoomingDisabled) { + cursor = "default"; + } else if (this.state.zoom === this.state.minZoom) { cursor = "zoom-in"; } else { cursor = "zoom-out"; } const rotationDegrees = this.state.rotation + "deg"; - const zoomPercentage = this.state.zoom/100; + const zoom = this.state.zoom; const translatePixelsX = this.state.translationX + "px"; const translatePixelsY = this.state.translationY + "px"; // The order of the values is important! @@ -301,7 +341,7 @@ export default class ImageView extends React.Component { transition: this.state.moving ? null : "transform 200ms ease 0s", transform: `translateX(${translatePixelsX}) translateY(${translatePixelsY}) - scale(${zoomPercentage}) + scale(${zoom}) rotate(${rotationDegrees})`, }; @@ -373,6 +413,25 @@ export default class ImageView extends React.Component { ); } + let zoomOutButton; + let zoomInButton; + if (!zoomingDisabled) { + zoomOutButton = ( + + + ); + zoomInButton = ( + + + ); + } + return ( { title={_t("Rotate Left")} onClick={ this.onRotateCounterClockwiseClick }> - - - - + {zoomOutButton} + {zoomInButton} { {this.renderContextMenu()}
      -
      +
      :
      ; return (
      diff --git a/src/components/views/elements/LabelledToggleSwitch.js b/src/components/views/elements/LabelledToggleSwitch.js index e6378f0e6a..ef60eeed7b 100644 --- a/src/components/views/elements/LabelledToggleSwitch.js +++ b/src/components/views/elements/LabelledToggleSwitch.js @@ -46,8 +46,12 @@ export default class LabelledToggleSwitch extends React.Component { // This is a minimal version of a SettingsFlag let firstPart = {this.props.label}; - let secondPart = ; + let secondPart = ; if (this.props.toggleInFront) { const temp = firstPart; diff --git a/src/components/views/elements/LanguageDropdown.js b/src/components/views/elements/LanguageDropdown.js index 2e961be700..b8734c5afb 100644 --- a/src/components/views/elements/LanguageDropdown.js +++ b/src/components/views/elements/LanguageDropdown.js @@ -60,10 +60,10 @@ export default class LanguageDropdown extends React.Component { // doesn't know this, therefore we do this. const language = SettingsStore.getValue("language", null, /*excludeDefault:*/true); if (language) { - this.props.onOptionChange(language); + this.props.onOptionChange(language); } else { - const language = languageHandler.normalizeLanguageKey(languageHandler.getLanguageFromBrowser()); - this.props.onOptionChange(language); + const language = languageHandler.normalizeLanguageKey(languageHandler.getLanguageFromBrowser()); + this.props.onOptionChange(language); } } } diff --git a/src/components/views/elements/PersistedElement.js b/src/components/views/elements/PersistedElement.js index f504b3e97f..701c140a19 100644 --- a/src/components/views/elements/PersistedElement.js +++ b/src/components/views/elements/PersistedElement.js @@ -139,6 +139,8 @@ export default class PersistedElement extends React.Component { _onAction(payload) { if (payload.action === 'timeline_resize') { this._repositionChild(); + } else if (payload.action === 'logout') { + PersistedElement.destroyElement(this.props.persistKey); } } diff --git a/src/components/views/elements/Pill.js b/src/components/views/elements/Pill.js index a8e16813e6..ace41db39d 100644 --- a/src/components/views/elements/Pill.js +++ b/src/components/views/elements/Pill.js @@ -225,19 +225,19 @@ class Pill extends React.Component { } break; case Pill.TYPE_USER_MENTION: { - // If this user is not a member of this room, default to the empty member - const member = this.state.member; - if (member) { - userId = member.userId; - member.rawDisplayName = member.rawDisplayName || ''; - linkText = member.rawDisplayName; - if (this.props.shouldShowPillAvatar) { - avatar =
      -
      {_t("Level")}{_t("Settable at global")}{_t("Settable at room")}
      {_t("Level")}{_t("Settable at global")}{_t("Settable at room")}
      {_t("Homeserver feature support:")} {homeserverSupportsCrossSigning ? _t("exists") : _t("not found")}
      + {errorSection} {actionRow} diff --git a/src/components/views/settings/DevicesPanel.js b/src/components/views/settings/DevicesPanel.js index e7d300b0f8..b1ad605a37 100644 --- a/src/components/views/settings/DevicesPanel.js +++ b/src/components/views/settings/DevicesPanel.js @@ -214,7 +214,7 @@ export default class DevicesPanel extends React.Component { const deleteButton = this.state.deleting ? : - { _t("Delete %(count)s sessions", {count: this.state.selectedDevices.length}) } + { _t("Delete %(count)s sessions", {count: this.state.selectedDevices.length})} ; const classes = classNames(this.props.className, "mx_DevicesPanel"); diff --git a/src/components/views/settings/E2eAdvancedPanel.js b/src/components/views/settings/E2eAdvancedPanel.tsx similarity index 100% rename from src/components/views/settings/E2eAdvancedPanel.js rename to src/components/views/settings/E2eAdvancedPanel.tsx diff --git a/src/components/views/settings/EventIndexPanel.js b/src/components/views/settings/EventIndexPanel.tsx similarity index 65% rename from src/components/views/settings/EventIndexPanel.js rename to src/components/views/settings/EventIndexPanel.tsx index d1a02de16d..fa84063ee8 100644 --- a/src/components/views/settings/EventIndexPanel.js +++ b/src/components/views/settings/EventIndexPanel.tsx @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020-2021 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. @@ -28,10 +28,17 @@ import {SettingLevel} from "../../../settings/SettingLevel"; import {replaceableComponent} from "../../../utils/replaceableComponent"; import SeshatResetDialog from '../dialogs/SeshatResetDialog'; +interface IState { + enabling: boolean; + eventIndexSize: number; + roomCount: number; + eventIndexingEnabled: boolean; +} + @replaceableComponent("views.settings.EventIndexPanel") -export default class EventIndexPanel extends React.Component { - constructor() { - super(); +export default class EventIndexPanel extends React.Component<{}, IState> { + constructor(props) { + super(props); this.state = { enabling: false, @@ -68,7 +75,7 @@ export default class EventIndexPanel extends React.Component { } } - async componentDidMount(): void { + componentDidMount(): void { this.updateState(); } @@ -102,8 +109,10 @@ export default class EventIndexPanel extends React.Component { }); } - _onManage = async () => { + private onManage = async () => { Modal.createTrackedDialogAsync('Message search', 'Message search', + // @ts-ignore: TS doesn't seem to like the type of this now that it + // has also been converted to TS as well, but I can't figure out why... import('../../../async-components/views/dialogs/eventindex/ManageEventIndexDialog'), { onFinished: () => {}, @@ -111,7 +120,7 @@ export default class EventIndexPanel extends React.Component { ); } - _onEnable = async () => { + private onEnable = async () => { this.setState({ enabling: true, }); @@ -123,14 +132,13 @@ export default class EventIndexPanel extends React.Component { await this.updateState(); } - _confirmEventStoreReset = () => { - const self = this; + private confirmEventStoreReset = () => { const { close } = Modal.createDialog(SeshatResetDialog, { onFinished: async (success) => { if (success) { await SettingsStore.setValue('enableEventIndexing', null, SettingLevel.DEVICE, false); await EventIndexPeg.deleteEventIndex(); - await self._onEnable(); + await this.onEnable(); close(); } }, @@ -145,20 +153,19 @@ export default class EventIndexPanel extends React.Component { if (EventIndexPeg.get() !== null) { eventIndexingSettings = (
      -
      - {_t("Securely cache encrypted messages locally for them " + - "to appear in search results, using %(size)s to store messages from %(rooms)s rooms.", - { - size: formatBytes(this.state.eventIndexSize, 0), - // This drives the singular / plural string - // selection for "room" / "rooms" only. - count: this.state.roomCount, - rooms: formatCountLong(this.state.roomCount), - }, - )} -
      +
      {_t( + "Securely cache encrypted messages locally for them " + + "to appear in search results, using %(size)s to store messages from %(rooms)s rooms.", + { + size: formatBytes(this.state.eventIndexSize, 0), + // This drives the singular / plural string + // selection for "room" / "rooms" only. + count: this.state.roomCount, + rooms: formatCountLong(this.state.roomCount), + }, + )}
      - + {_t("Manage")}
      @@ -167,13 +174,13 @@ export default class EventIndexPanel extends React.Component { } else if (!this.state.eventIndexingEnabled && EventIndexPeg.supportIsInstalled()) { eventIndexingSettings = (
      -
      - {_t( "Securely cache encrypted messages locally for them to " + - "appear in search results.")} -
      +
      {_t( + "Securely cache encrypted messages locally for them to " + + "appear in search results.", + )}
      + onClick={this.onEnable}> {_t("Enable")} {this.state.enabling ? :
      } @@ -188,40 +195,36 @@ export default class EventIndexPanel extends React.Component { ); eventIndexingSettings = ( -
      +
      {_t( + "%(brand)s is missing some components required for securely " + + "caching encrypted messages locally. If you'd like to " + + "experiment with this feature, build a custom %(brand)s Desktop " + + "with search components added.", { - _t( "%(brand)s is missing some components required for securely " + - "caching encrypted messages locally. If you'd like to " + - "experiment with this feature, build a custom %(brand)s Desktop " + - "with search components added.", - { - brand, - }, - { - 'nativeLink': (sub) => {sub}, - }, - ) - } -
      + brand, + }, + { + nativeLink: sub => {sub}, + }, + )}
      ); } else if (!EventIndexPeg.platformHasSupport()) { eventIndexingSettings = ( -
      +
      {_t( + "%(brand)s can't securely cache encrypted messages locally " + + "while running in a web browser. Use %(brand)s Desktop " + + "for encrypted messages to appear in search results.", { - _t( "%(brand)s can't securely cache encrypted messages locally " + - "while running in a web browser. Use %(brand)s Desktop " + - "for encrypted messages to appear in search results.", - { - brand, - }, - { - 'desktopLink': (sub) => {sub}, - }, - ) - } -
      + brand, + }, + { + desktopLink: sub => {sub}, + }, + )}
      ); } else { eventIndexingSettings = ( @@ -233,19 +236,18 @@ export default class EventIndexPanel extends React.Component { }

      {EventIndexPeg.error && ( -
      - {_t("Advanced")} - - {EventIndexPeg.error.message} - -

      - - {_t("Reset")} - -

      -
      +
      + {_t("Advanced")} + + {EventIndexPeg.error.message} + +

      + + {_t("Reset")} + +

      +
      )} -
      ); } diff --git a/src/components/views/settings/Notifications.js b/src/components/views/settings/Notifications.js index 25fe434994..5756536085 100644 --- a/src/components/views/settings/Notifications.js +++ b/src/components/views/settings/Notifications.js @@ -100,7 +100,7 @@ export default class Notifications extends React.Component { MatrixClientPeg.get().setPushRuleEnabled( 'global', self.state.masterPushRule.kind, self.state.masterPushRule.rule_id, !checked, ).then(function() { - self._refreshFromServer(); + self._refreshFromServer(); }); }; @@ -580,12 +580,12 @@ export default class Notifications extends React.Component { "vectorRuleId": "_keywords", "description": ( - { _t('Messages containing keywords', - {}, - { 'span': (sub) => - {sub}, - }, - )} + { _t('Messages containing keywords', + {}, + { 'span': (sub) => + {sub}, + }, + )} ), "vectorState": self.state.vectorContentRules.vectorState, @@ -743,8 +743,8 @@ export default class Notifications extends React.Component { emailNotificationsRow(address, label) { return ; + onChange={this.onEnableEmailNotificationsChange.bind(this, address)} + label={label} key={`emailNotif_${label}`} />; } render() { @@ -757,8 +757,8 @@ export default class Notifications extends React.Component { let masterPushRuleDiv; if (this.state.masterPushRule) { masterPushRuleDiv = ; + onChange={this.onEnableNotificationsChange} + label={_t('Enable notifications for this account')} />; } let clearNotificationsButton; @@ -874,16 +874,16 @@ export default class Notifications extends React.Component { { spinner } + onChange={this.onEnableDesktopNotificationsChange} + label={_t('Enable desktop notifications for this session')} /> + onChange={this.onEnableDesktopNotificationBodyChange} + label={_t('Show message in desktop notification')} /> + onChange={this.onEnableAudioNotificationsChange} + label={_t('Enable audible notifications for this session')} /> { emailNotificationsRows } diff --git a/src/components/views/settings/ProfileSettings.js b/src/components/views/settings/ProfileSettings.js index 971b868751..9ecf369eba 100644 --- a/src/components/views/settings/ProfileSettings.js +++ b/src/components/views/settings/ProfileSettings.js @@ -170,8 +170,12 @@ export default class ProfileSettings extends React.Component { noValidate={true} className="mx_ProfileSettings_profileForm" > - +
      {_t("Profile")} diff --git a/src/components/views/settings/SetIdServer.js b/src/components/views/settings/SetIdServer.tsx similarity index 89% rename from src/components/views/settings/SetIdServer.js rename to src/components/views/settings/SetIdServer.tsx index fa2a36476d..05d1f83387 100644 --- a/src/components/views/settings/SetIdServer.js +++ b/src/components/views/settings/SetIdServer.tsx @@ -1,5 +1,5 @@ /* -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -16,7 +16,6 @@ limitations under the License. import url from 'url'; import React from 'react'; -import PropTypes from 'prop-types'; import {_t} from "../../../languageHandler"; import * as sdk from '../../../index'; import {MatrixClientPeg} from "../../../MatrixClientPeg"; @@ -28,6 +27,7 @@ import {abbreviateUrl, unabbreviateUrl} from "../../../utils/UrlUtils"; import { getDefaultIdentityServerUrl, doesIdentityServerHaveTerms } from '../../../utils/IdentityServerUtils'; import {timeout} from "../../../utils/promise"; import {replaceableComponent} from "../../../utils/replaceableComponent"; +import { ActionPayload } from '../../../dispatcher/payloads'; // We'll wait up to this long when checking for 3PID bindings on the IS. const REACHABILITY_TIMEOUT = 10000; // ms @@ -59,16 +59,28 @@ async function checkIdentityServerUrl(u) { } } -@replaceableComponent("views.settings.SetIdServer") -export default class SetIdServer extends React.Component { - static propTypes = { - // Whether or not the ID server is missing terms. This affects the text - // shown to the user. - missingTerms: PropTypes.bool, - }; +interface IProps { + // Whether or not the ID server is missing terms. This affects the text + // shown to the user. + missingTerms: boolean; +} - constructor() { - super(); +interface IState { + defaultIdServer?: string; + currentClientIdServer: string; + idServer?: string; + error?: string; + busy: boolean; + disconnectBusy: boolean; + checking: boolean; +} + +@replaceableComponent("views.settings.SetIdServer") +export default class SetIdServer extends React.Component { + private dispatcherRef: string; + + constructor(props) { + super(props); let defaultIdServer = ''; if (!MatrixClientPeg.get().getIdentityServerUrl() && getDefaultIdentityServerUrl()) { @@ -96,7 +108,7 @@ export default class SetIdServer extends React.Component { dis.unregister(this.dispatcherRef); } - onAction = (payload) => { + private onAction = (payload: ActionPayload) => { // We react to changes in the ID server in the event the user is staring at this form // when changing their identity server on another device. if (payload.action !== "id_server_changed") return; @@ -106,13 +118,13 @@ export default class SetIdServer extends React.Component { }); }; - _onIdentityServerChanged = (ev) => { + private onIdentityServerChanged = (ev) => { const u = ev.target.value; this.setState({idServer: u}); }; - _getTooltip = () => { + private getTooltip = () => { if (this.state.checking) { const InlineSpinner = sdk.getComponent('views.elements.InlineSpinner'); return
      @@ -126,11 +138,11 @@ export default class SetIdServer extends React.Component { } }; - _idServerChangeEnabled = () => { + private idServerChangeEnabled = () => { return !!this.state.idServer && !this.state.busy; }; - _saveIdServer = (fullUrl) => { + private saveIdServer = (fullUrl) => { // Account data change will update localstorage, client, etc through dispatcher MatrixClientPeg.get().setAccountData("m.identity_server", { base_url: fullUrl, @@ -143,7 +155,7 @@ export default class SetIdServer extends React.Component { }); }; - _checkIdServer = async (e) => { + private checkIdServer = async (e) => { e.preventDefault(); const { idServer, currentClientIdServer } = this.state; @@ -166,14 +178,14 @@ export default class SetIdServer extends React.Component { // Double check that the identity server even has terms of service. const hasTerms = await doesIdentityServerHaveTerms(fullUrl); if (!hasTerms) { - const [confirmed] = await this._showNoTermsWarning(fullUrl); + const [confirmed] = await this.showNoTermsWarning(fullUrl); save = confirmed; } // Show a general warning, possibly with details about any bound // 3PIDs that would be left behind. if (save && currentClientIdServer && fullUrl !== currentClientIdServer) { - const [confirmed] = await this._showServerChangeWarning({ + const [confirmed] = await this.showServerChangeWarning({ title: _t("Change identity server"), unboundMessage: _t( "Disconnect from the identity server and " + @@ -189,7 +201,7 @@ export default class SetIdServer extends React.Component { } if (save) { - this._saveIdServer(fullUrl); + this.saveIdServer(fullUrl); } } catch (e) { console.error(e); @@ -204,7 +216,7 @@ export default class SetIdServer extends React.Component { }); }; - _showNoTermsWarning(fullUrl) { + private showNoTermsWarning(fullUrl) { const QuestionDialog = sdk.getComponent("views.dialogs.QuestionDialog"); const { finished } = Modal.createTrackedDialog('No Terms Warning', '', QuestionDialog, { title: _t("Identity server has no terms of service"), @@ -223,10 +235,10 @@ export default class SetIdServer extends React.Component { return finished; } - _onDisconnectClicked = async () => { + private onDisconnectClicked = async () => { this.setState({disconnectBusy: true}); try { - const [confirmed] = await this._showServerChangeWarning({ + const [confirmed] = await this.showServerChangeWarning({ title: _t("Disconnect identity server"), unboundMessage: _t( "Disconnect from the identity server ?", {}, @@ -235,14 +247,14 @@ export default class SetIdServer extends React.Component { button: _t("Disconnect"), }); if (confirmed) { - this._disconnectIdServer(); + this.disconnectIdServer(); } } finally { this.setState({disconnectBusy: false}); } }; - async _showServerChangeWarning({ title, unboundMessage, button }) { + private async showServerChangeWarning({ title, unboundMessage, button }) { const { currentClientIdServer } = this.state; let threepids = []; @@ -318,7 +330,7 @@ export default class SetIdServer extends React.Component { return finished; } - _disconnectIdServer = () => { + private disconnectIdServer = () => { // Account data change will update localstorage, client, etc through dispatcher MatrixClientPeg.get().setAccountData("m.identity_server", { base_url: null, // clear @@ -371,7 +383,7 @@ export default class SetIdServer extends React.Component { let discoSection; if (idServerUrl) { - let discoButtonContent = _t("Disconnect"); + let discoButtonContent: React.ReactNode = _t("Disconnect"); let discoBodyText = _t( "Disconnecting from your identity server will mean you " + "won't be discoverable by other users and you won't be " + @@ -391,14 +403,14 @@ export default class SetIdServer extends React.Component { } discoSection =
      {discoBodyText} - + {discoButtonContent}
      ; } return ( - + {sectionTitle} @@ -411,15 +423,15 @@ export default class SetIdServer extends React.Component { autoComplete="off" placeholder={this.state.defaultIdServer} value={this.state.idServer} - onChange={this._onIdentityServerChanged} - tooltipContent={this._getTooltip()} + onChange={this.onIdentityServerChanged} + tooltipContent={this.getTooltip()} tooltipClassName="mx_SetIdServer_tooltip" disabled={this.state.busy} forceValidity={this.state.error ? false : null} /> {_t("Change")} {discoSection} diff --git a/src/components/views/settings/account/EmailAddresses.js b/src/components/views/settings/account/EmailAddresses.js index 1ebd374173..a36369cf88 100644 --- a/src/components/views/settings/account/EmailAddresses.js +++ b/src/components/views/settings/account/EmailAddresses.js @@ -90,12 +90,18 @@ export class ExistingEmailAddress extends React.Component { {_t("Remove %(email)s?", {email: this.props.email.address} )} - + {_t("Remove")} - + {_t("Cancel")}
      @@ -228,21 +234,28 @@ export default class EmailAddresses extends React.Component { ); if (this.state.verifying) { addButton = ( -
      -
      {_t("We've sent you an email to verify your address. Please follow the instructions there and then click the button below.")}
      - - {_t("Continue")} - -
      +
      +
      {_t("We've sent you an email to verify your address. Please follow the instructions there and then click the button below.")}
      + + {_t("Continue")} + +
      ); } return (
      {existingEmailElements} -
      + {_t("Remove %(phone)s?", {phone: this.props.msisdn.address})} - + {_t("Remove")} - + {_t("Cancel")}
      @@ -246,8 +252,11 @@ export default class PhoneNumbers extends React.Component { value={this.state.newPhoneNumberCode} onChange={this._onChangeNewPhoneNumberCode} /> - + {_t("Continue")} diff --git a/src/components/views/settings/tabs/room/GeneralRoomSettingsTab.js b/src/components/views/settings/tabs/room/GeneralRoomSettingsTab.js index cd4a043622..139cfd5fbd 100644 --- a/src/components/views/settings/tabs/room/GeneralRoomSettingsTab.js +++ b/src/components/views/settings/tabs/room/GeneralRoomSettingsTab.js @@ -80,9 +80,11 @@ export default class GeneralRoomSettingsTab extends React.Component { flairSection = <> {_t("Flair")}
      - +
      ; } @@ -97,8 +99,8 @@ export default class GeneralRoomSettingsTab extends React.Component {
      {_t("Room Addresses")}
      + canSetCanonicalAlias={canSetCanonical} canSetAliases={canSetAliases} + canonicalAliasEvent={canonicalAliasEv} aliasEvents={aliasEvents} />
      {_t("Other")}
      { flairSection } diff --git a/src/components/views/settings/tabs/room/NotificationSettingsTab.js b/src/components/views/settings/tabs/room/NotificationSettingsTab.js index baefb5ae20..fa56fa2cb6 100644 --- a/src/components/views/settings/tabs/room/NotificationSettingsTab.js +++ b/src/components/views/settings/tabs/room/NotificationSettingsTab.js @@ -155,7 +155,7 @@ export default class NotificationsSettingsTab extends React.Component {
      {_t("Notification sound")}: {this.state.currentSound}
      - {_t("Reset")} + {_t("Reset")}
      @@ -167,11 +167,11 @@ export default class NotificationsSettingsTab extends React.Component { {currentUploadedFile} - {_t("Browse")} + {_t("Browse")} - {_t("Save")} + {_t("Save")}
      diff --git a/src/components/views/settings/tabs/room/RolesRoomSettingsTab.js b/src/components/views/settings/tabs/room/RolesRoomSettingsTab.tsx similarity index 89% rename from src/components/views/settings/tabs/room/RolesRoomSettingsTab.js rename to src/components/views/settings/tabs/room/RolesRoomSettingsTab.tsx index 59a175906d..4fa521f598 100644 --- a/src/components/views/settings/tabs/room/RolesRoomSettingsTab.js +++ b/src/components/views/settings/tabs/room/RolesRoomSettingsTab.tsx @@ -1,5 +1,5 @@ /* -Copyright 2019, 2021 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -15,7 +15,6 @@ limitations under the License. */ import React from 'react'; -import PropTypes from 'prop-types'; import {_t, _td} from "../../../../../languageHandler"; import {MatrixClientPeg} from "../../../../../MatrixClientPeg"; import * as sdk from "../../../../.."; @@ -23,6 +22,9 @@ import AccessibleButton from "../../../elements/AccessibleButton"; import Modal from "../../../../../Modal"; import {replaceableComponent} from "../../../../../utils/replaceableComponent"; import {EventType} from "matrix-js-sdk/src/@types/event"; +import { RoomMember } from "matrix-js-sdk/src/models/room-member"; +import { MatrixEvent } from "matrix-js-sdk/src/models/event"; +import { RoomState } from "matrix-js-sdk/src/models/room-state"; const plEventsToLabels = { // These will be translated for us later. @@ -63,15 +65,15 @@ function parseIntWithDefault(val, def) { return isNaN(res) ? def : res; } -export class BannedUser extends React.Component { - static propTypes = { - canUnban: PropTypes.bool, - member: PropTypes.object.isRequired, // js-sdk RoomMember - by: PropTypes.string.isRequired, - reason: PropTypes.string, - }; +interface IBannedUserProps { + canUnban?: boolean; + member: RoomMember; + by: string; + reason?: string; +} - _onUnbanClick = (e) => { +export class BannedUser extends React.Component { + private onUnbanClick = (e) => { MatrixClientPeg.get().unban(this.props.member.roomId, this.props.member.userId).catch((err) => { const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); console.error("Failed to unban: " + err); @@ -87,8 +89,10 @@ export class BannedUser extends React.Component { if (this.props.canUnban) { unbanButton = ( - + { _t('Unban') } ); @@ -107,29 +111,29 @@ export class BannedUser extends React.Component { } } -@replaceableComponent("views.settings.tabs.room.RolesRoomSettingsTab") -export default class RolesRoomSettingsTab extends React.Component { - static propTypes = { - roomId: PropTypes.string.isRequired, - }; +interface IProps { + roomId: string; +} - componentDidMount(): void { - MatrixClientPeg.get().on("RoomState.members", this._onRoomMembership); +@replaceableComponent("views.settings.tabs.room.RolesRoomSettingsTab") +export default class RolesRoomSettingsTab extends React.Component { + componentDidMount() { + MatrixClientPeg.get().on("RoomState.members", this.onRoomMembership); } - componentWillUnmount(): void { + componentWillUnmount() { const client = MatrixClientPeg.get(); if (client) { - client.removeListener("RoomState.members", this._onRoomMembership); + client.removeListener("RoomState.members", this.onRoomMembership); } } - _onRoomMembership = (event, state, member) => { + private onRoomMembership = (event: MatrixEvent, state: RoomState, member: RoomMember) => { if (state.roomId !== this.props.roomId) return; this.forceUpdate(); }; - _populateDefaultPlEvents(eventsSection, stateLevel, eventsLevel) { + private populateDefaultPlEvents(eventsSection: Record, stateLevel: number, eventsLevel: number) { for (const desiredEvent of Object.keys(plEventsToShow)) { if (!(desiredEvent in eventsSection)) { eventsSection[desiredEvent] = (plEventsToShow[desiredEvent].isState ? stateLevel : eventsLevel); @@ -137,7 +141,7 @@ export default class RolesRoomSettingsTab extends React.Component { } } - _onPowerLevelsChanged = (value, powerLevelKey) => { + private onPowerLevelsChanged = (inputValue: string, powerLevelKey: string) => { const client = MatrixClientPeg.get(); const room = client.getRoom(this.props.roomId); const plEvent = room.currentState.getStateEvents('m.room.power_levels', ''); @@ -148,7 +152,7 @@ export default class RolesRoomSettingsTab extends React.Component { const eventsLevelPrefix = "event_levels_"; - value = parseInt(value); + const value = parseInt(inputValue); if (powerLevelKey.startsWith(eventsLevelPrefix)) { // deep copy "events" object, Object.assign itself won't deep copy @@ -182,7 +186,7 @@ export default class RolesRoomSettingsTab extends React.Component { }); }; - _onUserPowerLevelChanged = (value, powerLevelKey) => { + private onUserPowerLevelChanged = (value: string, powerLevelKey: string) => { const client = MatrixClientPeg.get(); const room = client.getRoom(this.props.roomId); const plEvent = room.currentState.getStateEvents('m.room.power_levels', ''); @@ -266,7 +270,7 @@ export default class RolesRoomSettingsTab extends React.Component { currentUserLevel = defaultUserLevel; } - this._populateDefaultPlEvents( + this.populateDefaultPlEvents( eventsLevels, parseIntWithDefault(plContent.state_default, powerLevelDescriptors.state_default.defaultValue), parseIntWithDefault(plContent.events_default, powerLevelDescriptors.events_default.defaultValue), @@ -288,7 +292,7 @@ export default class RolesRoomSettingsTab extends React.Component { label={user} key={user} powerLevelKey={user} // Will be sent as the second parameter to `onChange` - onChange={this._onUserPowerLevelChanged} + onChange={this.onUserPowerLevelChanged} />, ); } else if (userLevels[user] < defaultUserLevel) { // muted @@ -299,7 +303,7 @@ export default class RolesRoomSettingsTab extends React.Component { label={user} key={user} powerLevelKey={user} // Will be sent as the second parameter to `onChange` - onChange={this._onUserPowerLevelChanged} + onChange={this.onUserPowerLevelChanged} />, ); } @@ -345,8 +349,9 @@ export default class RolesRoomSettingsTab extends React.Component { if (sender) bannedBy = sender.name; return ( + member={member} reason={banEvent.reason} + by={bannedBy} + /> ); })} @@ -373,7 +378,7 @@ export default class RolesRoomSettingsTab extends React.Component { usersDefault={defaultUserLevel} disabled={!canChangeLevels || currentUserLevel < value} powerLevelKey={key} // Will be sent as the second parameter to `onChange` - onChange={this._onPowerLevelsChanged} + onChange={this.onPowerLevelsChanged} />
      ; }); @@ -398,7 +403,7 @@ export default class RolesRoomSettingsTab extends React.Component { usersDefault={defaultUserLevel} disabled={!canChangeLevels || currentUserLevel < eventsLevels[eventType]} powerLevelKey={"event_levels_" + eventType} - onChange={this._onPowerLevelsChanged} + onChange={this.onPowerLevelsChanged} />
      ); diff --git a/src/components/views/settings/tabs/room/SecurityRoomSettingsTab.js b/src/components/views/settings/tabs/room/SecurityRoomSettingsTab.tsx similarity index 79% rename from src/components/views/settings/tabs/room/SecurityRoomSettingsTab.js rename to src/components/views/settings/tabs/room/SecurityRoomSettingsTab.tsx index ce883c6d23..02bbcfb751 100644 --- a/src/components/views/settings/tabs/room/SecurityRoomSettingsTab.js +++ b/src/components/views/settings/tabs/room/SecurityRoomSettingsTab.tsx @@ -1,5 +1,5 @@ /* -Copyright 2019 New Vector Ltd +Copyright 2019-2021 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. @@ -15,7 +15,7 @@ limitations under the License. */ import React from 'react'; -import PropTypes from 'prop-types'; +import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import {_t} from "../../../../../languageHandler"; import {MatrixClientPeg} from "../../../../../MatrixClientPeg"; import * as sdk from "../../../../.."; @@ -26,64 +26,92 @@ import StyledRadioGroup from '../../../elements/StyledRadioGroup'; import {SettingLevel} from "../../../../../settings/SettingLevel"; import SettingsStore from "../../../../../settings/SettingsStore"; import {UIFeature} from "../../../../../settings/UIFeature"; -import {replaceableComponent} from "../../../../../utils/replaceableComponent"; +import { replaceableComponent } from "../../../../../utils/replaceableComponent"; + +// Knock and private are reserved keywords which are not yet implemented. +enum JoinRule { + Public = "public", + Knock = "knock", + Invite = "invite", + Private = "private", +} + +enum GuestAccess { + CanJoin = "can_join", + Forbidden = "forbidden", +} + +enum HistoryVisibility { + Invited = "invited", + Joined = "joined", + Shared = "shared", + WorldReadable = "world_readable", +} + +interface IProps { + roomId: string; +} + +interface IState { + joinRule: JoinRule; + guestAccess: GuestAccess; + history: HistoryVisibility; + hasAliases: boolean; + encrypted: boolean; +} @replaceableComponent("views.settings.tabs.room.SecurityRoomSettingsTab") -export default class SecurityRoomSettingsTab extends React.Component { - static propTypes = { - roomId: PropTypes.string.isRequired, - }; - - constructor() { - super(); +export default class SecurityRoomSettingsTab extends React.Component { + constructor(props) { + super(props); this.state = { - joinRule: "invite", - guestAccess: "can_join", - history: "shared", + joinRule: JoinRule.Invite, + guestAccess: GuestAccess.CanJoin, + history: HistoryVisibility.Shared, hasAliases: false, encrypted: false, }; } // TODO: [REACT-WARNING] Move this to constructor - async UNSAFE_componentWillMount(): void { // eslint-disable-line camelcase - MatrixClientPeg.get().on("RoomState.events", this._onStateEvent); + async UNSAFE_componentWillMount() { // eslint-disable-line camelcase + MatrixClientPeg.get().on("RoomState.events", this.onStateEvent); const room = MatrixClientPeg.get().getRoom(this.props.roomId); const state = room.currentState; - const joinRule = this._pullContentPropertyFromEvent( + const joinRule: JoinRule = this.pullContentPropertyFromEvent( state.getStateEvents("m.room.join_rules", ""), 'join_rule', - 'invite', + JoinRule.Invite, ); - const guestAccess = this._pullContentPropertyFromEvent( + const guestAccess: GuestAccess = this.pullContentPropertyFromEvent( state.getStateEvents("m.room.guest_access", ""), 'guest_access', - 'forbidden', + GuestAccess.Forbidden, ); - const history = this._pullContentPropertyFromEvent( + const history: HistoryVisibility = this.pullContentPropertyFromEvent( state.getStateEvents("m.room.history_visibility", ""), 'history_visibility', - 'shared', + HistoryVisibility.Shared, ); const encrypted = MatrixClientPeg.get().isRoomEncrypted(this.props.roomId); this.setState({joinRule, guestAccess, history, encrypted}); - const hasAliases = await this._hasAliases(); + const hasAliases = await this.hasAliases(); this.setState({hasAliases}); } - _pullContentPropertyFromEvent(event, key, defaultValue) { + private pullContentPropertyFromEvent(event: MatrixEvent, key: string, defaultValue: T): T { if (!event || !event.getContent()) return defaultValue; return event.getContent()[key] || defaultValue; } - componentWillUnmount(): void { - MatrixClientPeg.get().removeListener("RoomState.events", this._onStateEvent); + componentWillUnmount() { + MatrixClientPeg.get().removeListener("RoomState.events", this.onStateEvent); } - _onStateEvent = (e) => { + private onStateEvent = (e: MatrixEvent) => { const refreshWhenTypes = [ 'm.room.join_rules', 'm.room.guest_access', @@ -93,7 +121,7 @@ export default class SecurityRoomSettingsTab extends React.Component { if (refreshWhenTypes.includes(e.getType())) this.forceUpdate(); }; - _onEncryptionChange = (e) => { + private onEncryptionChange = (e: React.ChangeEvent) => { Modal.createTrackedDialog('Enable encryption', '', QuestionDialog, { title: _t('Enable encryption?'), description: _t( @@ -102,10 +130,9 @@ export default class SecurityRoomSettingsTab extends React.Component { "may prevent many bots and bridges from working correctly. Learn more about encryption.", {}, { - 'a': (sub) => { - return {sub}; - }, + a: sub => {sub}, }, ), onFinished: (confirm) => { @@ -127,12 +154,12 @@ export default class SecurityRoomSettingsTab extends React.Component { }); }; - _fixGuestAccess = (e) => { + private fixGuestAccess = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); - const joinRule = "invite"; - const guestAccess = "can_join"; + const joinRule = JoinRule.Invite; + const guestAccess = GuestAccess.CanJoin; const beforeJoinRule = this.state.joinRule; const beforeGuestAccess = this.state.guestAccess; @@ -149,7 +176,7 @@ export default class SecurityRoomSettingsTab extends React.Component { }); }; - _onRoomAccessRadioToggle = (roomAccess) => { + private onRoomAccessRadioToggle = (roomAccess: string) => { // join_rule // INVITE | PUBLIC // ----------------------+---------------- @@ -163,20 +190,20 @@ export default class SecurityRoomSettingsTab extends React.Component { // invite them, you clearly want them to join, whether they're a // guest or not. In practice, guest_access should probably have // been implemented as part of the join_rules enum. - let joinRule = "invite"; - let guestAccess = "can_join"; + let joinRule = JoinRule.Invite; + let guestAccess = GuestAccess.CanJoin; switch (roomAccess) { case "invite_only": // no change - use defaults above break; case "public_no_guests": - joinRule = "public"; - guestAccess = "forbidden"; + joinRule = JoinRule.Public; + guestAccess = GuestAccess.Forbidden; break; case "public_with_guests": - joinRule = "public"; - guestAccess = "can_join"; + joinRule = JoinRule.Public; + guestAccess = GuestAccess.CanJoin; break; } @@ -195,7 +222,7 @@ export default class SecurityRoomSettingsTab extends React.Component { }); }; - _onHistoryRadioToggle = (history) => { + private onHistoryRadioToggle = (history: HistoryVisibility) => { const beforeHistory = this.state.history; this.setState({history: history}); MatrixClientPeg.get().sendStateEvent(this.props.roomId, "m.room.history_visibility", { @@ -206,11 +233,11 @@ export default class SecurityRoomSettingsTab extends React.Component { }); }; - _updateBlacklistDevicesFlag = (checked) => { + private updateBlacklistDevicesFlag = (checked: boolean) => { MatrixClientPeg.get().getRoom(this.props.roomId).setBlacklistUnverifiedDevices(checked); }; - async _hasAliases() { + private async hasAliases(): Promise { const cli = MatrixClientPeg.get(); if (await cli.doesServerSupportUnstableFeature("org.matrix.msc2432")) { const response = await cli.unstableGetLocalAliases(this.props.roomId); @@ -224,7 +251,7 @@ export default class SecurityRoomSettingsTab extends React.Component { } } - _renderRoomAccess() { + private renderRoomAccess() { const client = MatrixClientPeg.get(); const room = client.getRoom(this.props.roomId); const joinRule = this.state.joinRule; @@ -240,7 +267,7 @@ export default class SecurityRoomSettingsTab extends React.Component { {_t("Guests cannot join this room even if explicitly invited.")}  - {_t("Click here to fix")} + {_t("Click here to fix")}
      ); @@ -265,7 +292,7 @@ export default class SecurityRoomSettingsTab extends React.Component { ; } @@ -356,7 +383,7 @@ export default class SecurityRoomSettingsTab extends React.Component { let historySection = (<> {_t("Who can read history?")}
      - {this._renderHistory()} + {this.renderHistory()}
      ); if (!SettingsStore.getValue(UIFeature.RoomHistorySettings)) { @@ -373,15 +400,16 @@ export default class SecurityRoomSettingsTab extends React.Component {
      {_t("Once enabled, encryption cannot be disabled.")}
      - +
      {encryptionSettings}
      {_t("Who can access this room?")}
      - {this._renderRoomAccess()} + {this.renderRoomAccess()}
      {historySection} diff --git a/src/components/views/settings/tabs/user/GeneralUserSettingsTab.js b/src/components/views/settings/tabs/user/GeneralUserSettingsTab.js index b1ad9f3d23..5118414903 100644 --- a/src/components/views/settings/tabs/user/GeneralUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/GeneralUserSettingsTab.js @@ -192,7 +192,11 @@ export default class GeneralUserSettingsTab extends React.Component { SettingsStore.setValue("language", null, SettingLevel.DEVICE, newLanguage); this.setState({language: newLanguage}); - PlatformPeg.get().reload(); + const platform = PlatformPeg.get(); + if (platform) { + platform.setLanguage(newLanguage); + platform.reload(); + } }; _onSpellCheckLanguagesChange = (languages) => { @@ -319,8 +323,11 @@ export default class GeneralUserSettingsTab extends React.Component { return (
      {_t("Language and region")} - +
      ); } @@ -329,8 +336,10 @@ export default class GeneralUserSettingsTab extends React.Component { return (
      {_t("Spell check dictionaries")} - +
      ); } diff --git a/src/components/views/settings/tabs/user/HelpUserSettingsTab.js b/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx similarity index 75% rename from src/components/views/settings/tabs/user/HelpUserSettingsTab.js rename to src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx index e16ee686f5..a009ead064 100644 --- a/src/components/views/settings/tabs/user/HelpUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx @@ -1,6 +1,5 @@ /* -Copyright 2019 New Vector Ltd -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -16,27 +15,31 @@ limitations under the License. */ import React from 'react'; -import PropTypes from 'prop-types'; import {_t, getCurrentLanguage} from "../../../../../languageHandler"; import {MatrixClientPeg} from "../../../../../MatrixClientPeg"; import AccessibleButton from "../../../elements/AccessibleButton"; import SdkConfig from "../../../../../SdkConfig"; import createRoom from "../../../../../createRoom"; import Modal from "../../../../../Modal"; -import * as sdk from "../../../../../"; +import * as sdk from "../../../../.."; import PlatformPeg from "../../../../../PlatformPeg"; import * as KeyboardShortcuts from "../../../../../accessibility/KeyboardShortcuts"; import UpdateCheckButton from "../../UpdateCheckButton"; -import {replaceableComponent} from "../../../../../utils/replaceableComponent"; +import { replaceableComponent } from "../../../../../utils/replaceableComponent"; + +interface IProps { + closeSettingsFn: () => {}; +} + +interface IState { + appVersion: string; + canUpdate: boolean; +} @replaceableComponent("views.settings.tabs.user.HelpUserSettingsTab") -export default class HelpUserSettingsTab extends React.Component { - static propTypes = { - closeSettingsFn: PropTypes.func.isRequired, - }; - - constructor() { - super(); +export default class HelpUserSettingsTab extends React.Component { + constructor(props) { + super(props); this.state = { appVersion: null, @@ -53,7 +56,7 @@ export default class HelpUserSettingsTab extends React.Component { }); } - _onClearCacheAndReload = (e) => { + private onClearCacheAndReload = (e) => { if (!PlatformPeg.get()) return; // Dev note: please keep this log line, it's useful when troubleshooting a MatrixClient suddenly @@ -65,7 +68,7 @@ export default class HelpUserSettingsTab extends React.Component { }); }; - _onBugReport = (e) => { + private onBugReport = (e) => { const BugReportDialog = sdk.getComponent("dialogs.BugReportDialog"); if (!BugReportDialog) { return; @@ -73,7 +76,7 @@ export default class HelpUserSettingsTab extends React.Component { Modal.createTrackedDialog('Bug Report Dialog', '', BugReportDialog, {}); }; - _onStartBotChat = (e) => { + private onStartBotChat = (e) => { this.props.closeSettingsFn(); createRoom({ dmUserId: SdkConfig.get().welcomeUserId, @@ -81,7 +84,7 @@ export default class HelpUserSettingsTab extends React.Component { }); }; - _showSpoiler = (event) => { + private showSpoiler = (event) => { const target = event.target; target.innerHTML = target.getAttribute('data-spoiler'); @@ -93,7 +96,7 @@ export default class HelpUserSettingsTab extends React.Component { selection.addRange(range); }; - _renderLegal() { + private renderLegal() { const tocLinks = SdkConfig.get().terms_and_conditions_links; if (!tocLinks) return null; @@ -114,7 +117,7 @@ export default class HelpUserSettingsTab extends React.Component { ); } - _renderCredits() { + private renderCredits() { // Note: This is not translated because it is legal text. // Also,   is ugly but necessary. return ( @@ -122,28 +125,28 @@ export default class HelpUserSettingsTab extends React.Component { {_t("Credits")}
      @@ -188,7 +191,7 @@ export default class HelpUserSettingsTab extends React.Component { }, )}
      - + {_t("Chat with %(brand)s Bot", { brand })}
      @@ -212,28 +215,27 @@ export default class HelpUserSettingsTab extends React.Component {
      {_t('Bug reporting')}
      - { - _t( "If you've submitted a bug via GitHub, debug logs can help " + - "us track down the problem. Debug logs contain application " + - "usage data including your username, the IDs or aliases of " + - "the rooms or groups you have visited and the usernames of " + - "other users. They do not contain messages.", - ) - } + {_t( + "If you've submitted a bug via GitHub, debug logs can help " + + "us track down the problem. Debug logs contain application " + + "usage data including your username, the IDs or aliases of " + + "the rooms or groups you have visited and the usernames of " + + "other users. They do not contain messages.", + )}
      - + {_t("Submit debug logs")}
      - { - _t( "To report a Matrix-related security issue, please read the Matrix.org " + - "Security Disclosure Policy.", {}, - { - 'a': (sub) => - {sub}, - }) - } + {_t( + "To report a Matrix-related security issue, please read the Matrix.org " + + "Security Disclosure Policy.", {}, + { + a: sub => {sub}, + }, + )}
      ); @@ -260,20 +262,21 @@ export default class HelpUserSettingsTab extends React.Component { {updateButton}
      - {this._renderLegal()} - {this._renderCredits()} + {this.renderLegal()} + {this.renderCredits()}
      {_t("Advanced")}
      {_t("Homeserver is")} {MatrixClientPeg.get().getHomeserverUrl()}
      {_t("Identity Server is")} {MatrixClientPeg.get().getIdentityServerUrl()}
      {_t("Access Token:") + ' '} - + <{ _t("click to reveal") }>
      - + {_t("Clear cache and reload")}
      diff --git a/src/components/views/settings/tabs/user/MjolnirUserSettingsTab.js b/src/components/views/settings/tabs/user/MjolnirUserSettingsTab.tsx similarity index 90% rename from src/components/views/settings/tabs/user/MjolnirUserSettingsTab.js rename to src/components/views/settings/tabs/user/MjolnirUserSettingsTab.tsx index 91f6728a7a..6997defea9 100644 --- a/src/components/views/settings/tabs/user/MjolnirUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/MjolnirUserSettingsTab.tsx @@ -1,5 +1,5 @@ /* -Copyright 2019, 2020 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -25,10 +25,16 @@ import {MatrixClientPeg} from "../../../../../MatrixClientPeg"; import * as sdk from "../../../../../index"; import {replaceableComponent} from "../../../../../utils/replaceableComponent"; +interface IState { + busy: boolean; + newPersonalRule: string; + newList: string; +} + @replaceableComponent("views.settings.tabs.user.MjolnirUserSettingsTab") -export default class MjolnirUserSettingsTab extends React.Component { - constructor() { - super(); +export default class MjolnirUserSettingsTab extends React.Component<{}, IState> { + constructor(props) { + super(props); this.state = { busy: false, @@ -37,15 +43,15 @@ export default class MjolnirUserSettingsTab extends React.Component { }; } - _onPersonalRuleChanged = (e) => { + private onPersonalRuleChanged = (e) => { this.setState({newPersonalRule: e.target.value}); }; - _onNewListChanged = (e) => { + private onNewListChanged = (e) => { this.setState({newList: e.target.value}); }; - _onAddPersonalRule = async (e) => { + private onAddPersonalRule = async (e) => { e.preventDefault(); e.stopPropagation(); @@ -72,7 +78,7 @@ export default class MjolnirUserSettingsTab extends React.Component { } }; - _onSubscribeList = async (e) => { + private onSubscribeList = async (e) => { e.preventDefault(); e.stopPropagation(); @@ -94,7 +100,7 @@ export default class MjolnirUserSettingsTab extends React.Component { } }; - async _removePersonalRule(rule: ListRule) { + private async removePersonalRule(rule: ListRule) { this.setState({busy: true}); try { const list = Mjolnir.sharedInstance().getPersonalList(); @@ -112,7 +118,7 @@ export default class MjolnirUserSettingsTab extends React.Component { } } - async _unsubscribeFromList(list: BanList) { + private async unsubscribeFromList(list: BanList) { this.setState({busy: true}); try { await Mjolnir.sharedInstance().unsubscribeFromList(list.roomId); @@ -130,7 +136,7 @@ export default class MjolnirUserSettingsTab extends React.Component { } } - _viewListRules(list: BanList) { + private viewListRules(list: BanList) { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); const room = MatrixClientPeg.get().getRoom(list.roomId); @@ -161,7 +167,7 @@ export default class MjolnirUserSettingsTab extends React.Component { }); } - _renderPersonalBanListRules() { + private renderPersonalBanListRules() { const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); const list = Mjolnir.sharedInstance().getPersonalList(); @@ -174,7 +180,7 @@ export default class MjolnirUserSettingsTab extends React.Component {
    1. this._removePersonalRule(rule)} + onClick={() => this.removePersonalRule(rule)} disabled={this.state.busy} > {_t("Remove")} @@ -192,7 +198,7 @@ export default class MjolnirUserSettingsTab extends React.Component { ); } - _renderSubscribedBanLists() { + private renderSubscribedBanLists() { const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); const personalList = Mjolnir.sharedInstance().getPersonalList(); @@ -209,14 +215,14 @@ export default class MjolnirUserSettingsTab extends React.Component {
    2. this._unsubscribeFromList(list)} + onClick={() => this.unsubscribeFromList(list)} disabled={this.state.busy} > {_t("Unsubscribe")}   this._viewListRules(list)} + onClick={() => this.viewListRules(list)} disabled={this.state.busy} > {_t("View rules")} @@ -271,21 +277,21 @@ export default class MjolnirUserSettingsTab extends React.Component { )}
    3. - {this._renderPersonalBanListRules()} + {this.renderPersonalBanListRules()}
      -
      + {_t("Ignore")} @@ -303,20 +309,20 @@ export default class MjolnirUserSettingsTab extends React.Component { )}
      - {this._renderSubscribedBanLists()} + {this.renderSubscribedBanLists()}
      - + {_t("Subscribe")} diff --git a/src/components/views/settings/tabs/user/PreferencesUserSettingsTab.js b/src/components/views/settings/tabs/user/PreferencesUserSettingsTab.tsx similarity index 80% rename from src/components/views/settings/tabs/user/PreferencesUserSettingsTab.js rename to src/components/views/settings/tabs/user/PreferencesUserSettingsTab.tsx index 0cd3dd6698..f02c5c9ce0 100644 --- a/src/components/views/settings/tabs/user/PreferencesUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/PreferencesUserSettingsTab.tsx @@ -1,5 +1,5 @@ /* -Copyright 2019 New Vector Ltd +Copyright 2019-2021 The Matrix.org Foundation C.I.C. Copyright 2019 Michael Telatynski <7t3chguy@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,10 +23,24 @@ import Field from "../../../elements/Field"; import * as sdk from "../../../../.."; import PlatformPeg from "../../../../../PlatformPeg"; import {SettingLevel} from "../../../../../settings/SettingLevel"; -import {replaceableComponent} from "../../../../../utils/replaceableComponent"; +import { replaceableComponent } from "../../../../../utils/replaceableComponent"; + +interface IState { + autoLaunch: boolean; + autoLaunchSupported: boolean; + warnBeforeExit: boolean; + warnBeforeExitSupported: boolean; + alwaysShowMenuBarSupported: boolean; + alwaysShowMenuBar: boolean; + minimizeToTraySupported: boolean; + minimizeToTray: boolean; + autocompleteDelay: string; + readMarkerInViewThresholdMs: string; + readMarkerOutOfViewThresholdMs: string; +} @replaceableComponent("views.settings.tabs.user.PreferencesUserSettingsTab") -export default class PreferencesUserSettingsTab extends React.Component { +export default class PreferencesUserSettingsTab extends React.Component<{}, IState> { static ROOM_LIST_SETTINGS = [ 'breadcrumbs', ]; @@ -68,8 +82,8 @@ export default class PreferencesUserSettingsTab extends React.Component { // Autocomplete delay (niche text box) ]; - constructor() { - super(); + constructor(props) { + super(props); this.state = { autoLaunch: false, @@ -89,7 +103,7 @@ export default class PreferencesUserSettingsTab extends React.Component { }; } - async componentDidMount(): void { + async componentDidMount() { const platform = PlatformPeg.get(); const autoLaunchSupported = await platform.supportsAutoLaunch(); @@ -128,38 +142,38 @@ export default class PreferencesUserSettingsTab extends React.Component { }); } - _onAutoLaunchChange = (checked) => { + private onAutoLaunchChange = (checked: boolean) => { PlatformPeg.get().setAutoLaunchEnabled(checked).then(() => this.setState({autoLaunch: checked})); }; - _onWarnBeforeExitChange = (checked) => { + private onWarnBeforeExitChange = (checked: boolean) => { PlatformPeg.get().setWarnBeforeExit(checked).then(() => this.setState({warnBeforeExit: checked})); } - _onAlwaysShowMenuBarChange = (checked) => { + private onAlwaysShowMenuBarChange = (checked: boolean) => { PlatformPeg.get().setAutoHideMenuBarEnabled(!checked).then(() => this.setState({alwaysShowMenuBar: checked})); }; - _onMinimizeToTrayChange = (checked) => { + private onMinimizeToTrayChange = (checked: boolean) => { PlatformPeg.get().setMinimizeToTrayEnabled(checked).then(() => this.setState({minimizeToTray: checked})); }; - _onAutocompleteDelayChange = (e) => { + private onAutocompleteDelayChange = (e: React.ChangeEvent) => { this.setState({autocompleteDelay: e.target.value}); SettingsStore.setValue("autocompleteDelay", null, SettingLevel.DEVICE, e.target.value); }; - _onReadMarkerInViewThresholdMs = (e) => { + private onReadMarkerInViewThresholdMs = (e: React.ChangeEvent) => { this.setState({readMarkerInViewThresholdMs: e.target.value}); SettingsStore.setValue("readMarkerInViewThresholdMs", null, SettingLevel.DEVICE, e.target.value); }; - _onReadMarkerOutOfViewThresholdMs = (e) => { + private onReadMarkerOutOfViewThresholdMs = (e: React.ChangeEvent) => { this.setState({readMarkerOutOfViewThresholdMs: e.target.value}); SettingsStore.setValue("readMarkerOutOfViewThresholdMs", null, SettingLevel.DEVICE, e.target.value); }; - _renderGroup(settingIds) { + private renderGroup(settingIds: string[]): React.ReactNodeArray { const SettingsFlag = sdk.getComponent("views.elements.SettingsFlag"); return settingIds.filter(SettingsStore.isEnabled).map(i => { return ; @@ -171,7 +185,7 @@ export default class PreferencesUserSettingsTab extends React.Component { if (this.state.autoLaunchSupported) { autoLaunchOption = ; } @@ -179,7 +193,7 @@ export default class PreferencesUserSettingsTab extends React.Component { if (this.state.warnBeforeExitSupported) { warnBeforeExitOption = ; } @@ -187,7 +201,7 @@ export default class PreferencesUserSettingsTab extends React.Component { if (this.state.alwaysShowMenuBarSupported) { autoHideMenuOption = ; } @@ -195,7 +209,7 @@ export default class PreferencesUserSettingsTab extends React.Component { if (this.state.minimizeToTraySupported) { minimizeToTrayOption = ; } @@ -205,22 +219,22 @@ export default class PreferencesUserSettingsTab extends React.Component {
      {_t("Room list")} - {this._renderGroup(PreferencesUserSettingsTab.ROOM_LIST_SETTINGS)} + {this.renderGroup(PreferencesUserSettingsTab.ROOM_LIST_SETTINGS)}
      {_t("Composer")} - {this._renderGroup(PreferencesUserSettingsTab.COMPOSER_SETTINGS)} + {this.renderGroup(PreferencesUserSettingsTab.COMPOSER_SETTINGS)}
      {_t("Timeline")} - {this._renderGroup(PreferencesUserSettingsTab.TIMELINE_SETTINGS)} + {this.renderGroup(PreferencesUserSettingsTab.TIMELINE_SETTINGS)}
      {_t("General")} - {this._renderGroup(PreferencesUserSettingsTab.GENERAL_SETTINGS)} + {this.renderGroup(PreferencesUserSettingsTab.GENERAL_SETTINGS)} {minimizeToTrayOption} {autoHideMenuOption} {autoLaunchOption} @@ -229,17 +243,17 @@ export default class PreferencesUserSettingsTab extends React.Component { label={_t('Autocomplete delay (ms)')} type='number' value={this.state.autocompleteDelay} - onChange={this._onAutocompleteDelayChange} /> + onChange={this.onAutocompleteDelayChange} /> + onChange={this.onReadMarkerInViewThresholdMs} /> + onChange={this.onReadMarkerOutOfViewThresholdMs} />
      ); diff --git a/src/components/views/settings/tabs/user/SecurityUserSettingsTab.js b/src/components/views/settings/tabs/user/SecurityUserSettingsTab.js index 8a70811399..53ed511b0a 100644 --- a/src/components/views/settings/tabs/user/SecurityUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/SecurityUserSettingsTab.js @@ -255,15 +255,18 @@ export default class SecurityUserSettingsTab extends React.Component { _renderIgnoredUsers() { const {waitingUnignored, ignoredUserIds} = this.state; - if (!ignoredUserIds || ignoredUserIds.length === 0) return null; - - const userIds = ignoredUserIds - .map((u) => ); + const userIds = !ignoredUserIds?.length + ? _t('You have no ignored users.') + : ignoredUserIds.map((u) => { + return ( + + ); + }); return (
      diff --git a/src/components/views/settings/tabs/user/VoiceUserSettingsTab.js b/src/components/views/settings/tabs/user/VoiceUserSettingsTab.js index d8adab55f6..362059f8ed 100644 --- a/src/components/views/settings/tabs/user/VoiceUserSettingsTab.js +++ b/src/components/views/settings/tabs/user/VoiceUserSettingsTab.js @@ -176,8 +176,8 @@ export default class VoiceUserSettingsTab extends React.Component { const defaultDevice = getDefaultDevice(audioOutputs); speakerDropdown = ( + value={this.state.activeAudioOutput || defaultDevice} + onChange={this._setAudioOutput}> {this._renderDeviceOptions(audioOutputs, 'audioOutput')} ); @@ -188,8 +188,8 @@ export default class VoiceUserSettingsTab extends React.Component { const defaultDevice = getDefaultDevice(audioInputs); microphoneDropdown = ( + value={this.state.activeAudioInput || defaultDevice} + onChange={this._setAudioInput}> {this._renderDeviceOptions(audioInputs, 'audioInput')} ); @@ -200,8 +200,8 @@ export default class VoiceUserSettingsTab extends React.Component { const defaultDevice = getDefaultDevice(videoInputs); webcamDropdown = ( + value={this.state.activeVideoInput || defaultDevice} + onChange={this._setVideoInput}> {this._renderDeviceOptions(videoInputs, 'videoInput')} ); diff --git a/src/components/views/spaces/SpacePanel.tsx b/src/components/views/spaces/SpacePanel.tsx index bacf1bd929..36ab423885 100644 --- a/src/components/views/spaces/SpacePanel.tsx +++ b/src/components/views/spaces/SpacePanel.tsx @@ -25,7 +25,12 @@ import SpaceCreateMenu from "./SpaceCreateMenu"; import {SpaceItem} from "./SpaceTreeLevel"; import AccessibleTooltipButton from "../elements/AccessibleTooltipButton"; import {useEventEmitter} from "../../../hooks/useEventEmitter"; -import SpaceStore, {HOME_SPACE, UPDATE_SELECTED_SPACE, UPDATE_TOP_LEVEL_SPACES} from "../../../stores/SpaceStore"; +import SpaceStore, { + HOME_SPACE, + UPDATE_INVITED_SPACES, + UPDATE_SELECTED_SPACE, + UPDATE_TOP_LEVEL_SPACES, +} from "../../../stores/SpaceStore"; import AutoHideScrollbar from "../../structures/AutoHideScrollbar"; import {SpaceNotificationState} from "../../../stores/notifications/SpaceNotificationState"; import NotificationBadge from "../rooms/NotificationBadge"; @@ -105,19 +110,21 @@ const SpaceButton: React.FC = ({ ; } -const useSpaces = (): [Room[], Room | null] => { +const useSpaces = (): [Room[], Room[], Room | null] => { + const [invites, setInvites] = useState(SpaceStore.instance.invitedSpaces); + useEventEmitter(SpaceStore.instance, UPDATE_INVITED_SPACES, setInvites); const [spaces, setSpaces] = useState(SpaceStore.instance.spacePanelSpaces); useEventEmitter(SpaceStore.instance, UPDATE_TOP_LEVEL_SPACES, setSpaces); const [activeSpace, setActiveSpace] = useState(SpaceStore.instance.activeSpace); useEventEmitter(SpaceStore.instance, UPDATE_SELECTED_SPACE, setActiveSpace); - return [spaces, activeSpace]; + return [invites, spaces, activeSpace]; }; const SpacePanel = () => { // We don't need the handle as we position the menu in a constant location // eslint-disable-next-line @typescript-eslint/no-unused-vars const [menuDisplayed, handle, openMenu, closeMenu] = useContextMenu(); - const [spaces, activeSpace] = useSpaces(); + const [invites, spaces, activeSpace] = useSpaces(); const [isPanelCollapsed, setPanelCollapsed] = useState(true); const newClasses = classNames("mx_SpaceButton_new", { @@ -209,6 +216,13 @@ const SpacePanel = () => { notificationState={SpaceStore.instance.getNotificationState(HOME_SPACE)} isNarrow={isPanelCollapsed} /> + { invites.map(s => setPanelCollapsed(false)} + />) } { spaces.map(s => { super(props); this.state = { - collapsed: !props.isNested, // default to collapsed for root items + collapsed: !props.isNested, // default to collapsed for root items contextMenuPosition: null, }; } @@ -83,6 +85,7 @@ export class SpaceItem extends React.PureComponent { } private onContextMenu = (ev: React.MouseEvent) => { + if (this.props.space.getMyMembership() !== "join") return; ev.preventDefault(); ev.stopPropagation(); this.setState({ @@ -185,6 +188,8 @@ export class SpaceItem extends React.PureComponent { }; private renderContextMenu(): React.ReactElement { + if (this.props.space.getMyMembership() !== "join") return null; + let contextMenu = null; if (this.state.contextMenuPosition) { const userId = this.context.getUserId(); @@ -300,7 +305,9 @@ export class SpaceItem extends React.PureComponent { mx_SpaceButton_hasMenuOpen: !!this.state.contextMenuPosition, mx_SpaceButton_narrow: isNarrow, }); - const notificationState = SpaceStore.instance.getNotificationState(space.roomId); + const notificationState = space.getMyMembership() === "invite" + ? StaticNotificationState.forSymbol("!", NotificationColor.Red) + : SpaceStore.instance.getNotificationState(space.roomId); let childItems; if (childSpaces && !collapsed) { diff --git a/src/components/views/verification/VerificationCancelled.js b/src/components/views/verification/VerificationCancelled.js index 0bbaea1804..c57094d9b5 100644 --- a/src/components/views/verification/VerificationCancelled.js +++ b/src/components/views/verification/VerificationCancelled.js @@ -29,14 +29,14 @@ export default class VerificationCancelled extends React.Component { render() { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); return
      -

      {_t( - "The other party cancelled the verification.", - )}

      - +

      {_t( + "The other party cancelled the verification.", + )}

      +
      ; } } diff --git a/src/components/views/voice_messages/Clock.tsx b/src/components/views/voice_messages/Clock.tsx index 6c256957e9..23e6762c52 100644 --- a/src/components/views/voice_messages/Clock.tsx +++ b/src/components/views/voice_messages/Clock.tsx @@ -29,14 +29,20 @@ interface IState { * displayed, making it possible to see "82:29". */ @replaceableComponent("views.voice_messages.Clock") -export default class Clock extends React.PureComponent { +export default class Clock extends React.Component { public constructor(props) { super(props); } + shouldComponentUpdate(nextProps: Readonly, nextState: Readonly, nextContext: any): boolean { + const currentFloor = Math.floor(this.props.seconds); + const nextFloor = Math.floor(nextProps.seconds); + return currentFloor !== nextFloor; + } + public render() { const minutes = Math.floor(this.props.seconds / 60).toFixed(0).padStart(2, '0'); - const seconds = Math.round(this.props.seconds % 60).toFixed(0).padStart(2, '0'); // hide millis + const seconds = Math.floor(this.props.seconds % 60).toFixed(0).padStart(2, '0'); // hide millis return {minutes}:{seconds}; } } diff --git a/src/components/views/voice_messages/LiveRecordingClock.tsx b/src/components/views/voice_messages/LiveRecordingClock.tsx index 5e9006c6ab..b82539eb16 100644 --- a/src/components/views/voice_messages/LiveRecordingClock.tsx +++ b/src/components/views/voice_messages/LiveRecordingClock.tsx @@ -31,7 +31,7 @@ interface IState { * A clock for a live recording. */ @replaceableComponent("views.voice_messages.LiveRecordingClock") -export default class LiveRecordingClock extends React.Component { +export default class LiveRecordingClock extends React.PureComponent { public constructor(props) { super(props); @@ -39,12 +39,6 @@ export default class LiveRecordingClock extends React.Component this.props.recorder.liveData.onUpdate(this.onRecordingUpdate); } - shouldComponentUpdate(nextProps: Readonly, nextState: Readonly, nextContext: any): boolean { - const currentFloor = Math.floor(this.state.seconds); - const nextFloor = Math.floor(nextState.seconds); - return currentFloor !== nextFloor; - } - private onRecordingUpdate = (update: IRecordingUpdate) => { this.setState({seconds: update.timeSeconds}); }; diff --git a/src/components/views/voice_messages/LiveRecordingWaveform.tsx b/src/components/views/voice_messages/LiveRecordingWaveform.tsx index c1f5e97fff..e7c34c9177 100644 --- a/src/components/views/voice_messages/LiveRecordingWaveform.tsx +++ b/src/components/views/voice_messages/LiveRecordingWaveform.tsx @@ -20,6 +20,7 @@ import {replaceableComponent} from "../../../utils/replaceableComponent"; import {arrayFastResample, arraySeed} from "../../../utils/arrays"; import {percentageOf} from "../../../utils/numbers"; import Waveform from "./Waveform"; +import {PLAYBACK_WAVEFORM_SAMPLES} from "../../../voice/Playback"; interface IProps { recorder: VoiceRecording; @@ -29,8 +30,6 @@ interface IState { heights: number[]; } -const DOWNSAMPLE_TARGET = 35; // number of bars we want - /** * A waveform which shows the waveform of a live recording */ @@ -39,14 +38,14 @@ export default class LiveRecordingWaveform extends React.PureComponent { // The waveform and the downsample target are pretty close, so we should be fine to // do this, despite the docs on arrayFastResample. - const bars = arrayFastResample(Array.from(update.waveform), DOWNSAMPLE_TARGET); + const bars = arrayFastResample(Array.from(update.waveform), PLAYBACK_WAVEFORM_SAMPLES); this.setState({ // The incoming data is between zero and one, but typically even screaming into a // microphone won't send you over 0.6, so we artificially adjust the gain for the diff --git a/src/components/views/voice_messages/PlayPauseButton.tsx b/src/components/views/voice_messages/PlayPauseButton.tsx new file mode 100644 index 0000000000..1f87eb012d --- /dev/null +++ b/src/components/views/voice_messages/PlayPauseButton.tsx @@ -0,0 +1,61 @@ +/* +Copyright 2021 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. +*/ + +import React, {ReactNode} from "react"; +import {replaceableComponent} from "../../../utils/replaceableComponent"; +import AccessibleTooltipButton from "../elements/AccessibleTooltipButton"; +import {_t} from "../../../languageHandler"; +import {Playback, PlaybackState} from "../../../voice/Playback"; +import classNames from "classnames"; + +interface IProps { + // Playback instance to manipulate. Cannot change during the component lifecycle. + playback: Playback; + + // The playback phase to render. Able to change during the component lifecycle. + playbackPhase: PlaybackState; +} + +/** + * Displays a play/pause button (activating the play/pause function of the recorder) + * to be displayed in reference to a recording. + */ +@replaceableComponent("views.voice_messages.PlayPauseButton") +export default class PlayPauseButton extends React.PureComponent { + public constructor(props) { + super(props); + } + + private onClick = async () => { + await this.props.playback.toggle(); + }; + + public render(): ReactNode { + const isPlaying = this.props.playback.isPlaying; + const isDisabled = this.props.playbackPhase === PlaybackState.Decoding; + const classes = classNames('mx_PlayPauseButton', { + 'mx_PlayPauseButton_play': !isPlaying, + 'mx_PlayPauseButton_pause': isPlaying, + 'mx_PlayPauseButton_disabled': isDisabled, + }); + return ; + } +} diff --git a/src/components/views/voice_messages/PlaybackClock.tsx b/src/components/views/voice_messages/PlaybackClock.tsx new file mode 100644 index 0000000000..2e8ec9a3e7 --- /dev/null +++ b/src/components/views/voice_messages/PlaybackClock.tsx @@ -0,0 +1,71 @@ +/* +Copyright 2021 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. +*/ + +import React from "react"; +import {replaceableComponent} from "../../../utils/replaceableComponent"; +import Clock from "./Clock"; +import {Playback, PlaybackState} from "../../../voice/Playback"; +import {UPDATE_EVENT} from "../../../stores/AsyncStore"; + +interface IProps { + playback: Playback; +} + +interface IState { + seconds: number; + durationSeconds: number; + playbackPhase: PlaybackState; +} + +/** + * A clock for a playback of a recording. + */ +@replaceableComponent("views.voice_messages.PlaybackClock") +export default class PlaybackClock extends React.PureComponent { + public constructor(props) { + super(props); + + this.state = { + seconds: this.props.playback.clockInfo.timeSeconds, + // we track the duration on state because we won't really know what the clip duration + // is until the first time update, and as a PureComponent we are trying to dedupe state + // updates as much as possible. This is just the easiest way to avoid a forceUpdate() or + // member property to track "did we get a duration". + durationSeconds: this.props.playback.clockInfo.durationSeconds, + playbackPhase: PlaybackState.Stopped, // assume not started, so full clock + }; + this.props.playback.on(UPDATE_EVENT, this.onPlaybackUpdate); + this.props.playback.clockInfo.liveData.onUpdate(this.onTimeUpdate); + } + + private onPlaybackUpdate = (ev: PlaybackState) => { + // Convert Decoding -> Stopped because we don't care about the distinction here + if (ev === PlaybackState.Decoding) ev = PlaybackState.Stopped; + this.setState({playbackPhase: ev}); + }; + + private onTimeUpdate = (time: number[]) => { + this.setState({seconds: time[0], durationSeconds: time[1]}); + }; + + public render() { + let seconds = this.state.seconds; + if (this.state.playbackPhase === PlaybackState.Stopped) { + seconds = this.state.durationSeconds; + } + return ; + } +} diff --git a/src/components/views/voice_messages/PlaybackWaveform.tsx b/src/components/views/voice_messages/PlaybackWaveform.tsx new file mode 100644 index 0000000000..123af5dfa5 --- /dev/null +++ b/src/components/views/voice_messages/PlaybackWaveform.tsx @@ -0,0 +1,68 @@ +/* +Copyright 2021 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. +*/ + +import React from "react"; +import {replaceableComponent} from "../../../utils/replaceableComponent"; +import {arraySeed, arrayTrimFill} from "../../../utils/arrays"; +import Waveform from "./Waveform"; +import {Playback, PLAYBACK_WAVEFORM_SAMPLES} from "../../../voice/Playback"; +import {percentageOf} from "../../../utils/numbers"; + +interface IProps { + playback: Playback; +} + +interface IState { + heights: number[]; + progress: number; +} + +/** + * A waveform which shows the waveform of a previously recorded recording + */ +@replaceableComponent("views.voice_messages.PlaybackWaveform") +export default class PlaybackWaveform extends React.PureComponent { + public constructor(props) { + super(props); + + this.state = { + heights: this.toHeights(this.props.playback.waveform), + progress: 0, // default no progress + }; + + this.props.playback.waveformData.onUpdate(this.onWaveformUpdate); + this.props.playback.clockInfo.liveData.onUpdate(this.onTimeUpdate); + } + + private toHeights(waveform: number[]) { + const seed = arraySeed(0, PLAYBACK_WAVEFORM_SAMPLES); + return arrayTrimFill(waveform, PLAYBACK_WAVEFORM_SAMPLES, seed); + } + + private onWaveformUpdate = (waveform: number[]) => { + this.setState({heights: this.toHeights(waveform)}); + }; + + private onTimeUpdate = (time: number[]) => { + // Track percentages to very coarse precision, otherwise 0.002 ends up highlighting a bar. + const progress = Number(percentageOf(time[0], 0, time[1]).toFixed(1)); + this.setState({progress}); + }; + + public render() { + return ; + } +} diff --git a/src/components/views/voice_messages/RecordingPlayback.tsx b/src/components/views/voice_messages/RecordingPlayback.tsx new file mode 100644 index 0000000000..776997cec2 --- /dev/null +++ b/src/components/views/voice_messages/RecordingPlayback.tsx @@ -0,0 +1,62 @@ +/* +Copyright 2021 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. +*/ + +import {Playback, PlaybackState} from "../../../voice/Playback"; +import React, {ReactNode} from "react"; +import {UPDATE_EVENT} from "../../../stores/AsyncStore"; +import PlaybackWaveform from "./PlaybackWaveform"; +import PlayPauseButton from "./PlayPauseButton"; +import PlaybackClock from "./PlaybackClock"; + +interface IProps { + // Playback instance to render. Cannot change during component lifecycle: create + // an all-new component instead. + playback: Playback; +} + +interface IState { + playbackPhase: PlaybackState; +} + +export default class RecordingPlayback extends React.PureComponent { + constructor(props: IProps) { + super(props); + + this.state = { + playbackPhase: PlaybackState.Decoding, // default assumption + }; + + // We don't need to de-register: the class handles this for us internally + this.props.playback.on(UPDATE_EVENT, this.onPlaybackUpdate); + + // Don't wait for the promise to complete - it will emit a progress update when it + // is done, and it's not meant to take long anyhow. + // noinspection JSIgnoredPromiseFromCall + this.props.playback.prepare(); + } + + private onPlaybackUpdate = (ev: PlaybackState) => { + this.setState({playbackPhase: ev}); + }; + + public render(): ReactNode { + return
      + + + +
      + } +} diff --git a/src/components/views/voice_messages/Waveform.tsx b/src/components/views/voice_messages/Waveform.tsx index 5fa68dcadc..840a5a12b3 100644 --- a/src/components/views/voice_messages/Waveform.tsx +++ b/src/components/views/voice_messages/Waveform.tsx @@ -16,9 +16,11 @@ limitations under the License. import React from "react"; import {replaceableComponent} from "../../../utils/replaceableComponent"; +import classNames from "classnames"; interface IProps { relHeights: number[]; // relative heights (0-1) + progress: number; // percent complete, 0-1, default 100% } interface IState { @@ -28,9 +30,16 @@ interface IState { * A simple waveform component. This renders bars (centered vertically) for each * height provided in the component properties. Updating the properties will update * the rendered waveform. + * + * For CSS purposes, a mx_Waveform_bar_100pct class is added when the bar should be + * "filled", as a demonstration of the progress property. */ @replaceableComponent("views.voice_messages.Waveform") export default class Waveform extends React.PureComponent { + public static defaultProps = { + progress: 1, + }; + public constructor(props) { super(props); } @@ -38,7 +47,13 @@ export default class Waveform extends React.PureComponent { public render() { return
      {this.props.relHeights.map((h, i) => { - return ; + const progress = this.props.progress; + const isCompleteBar = (i / this.props.relHeights.length) <= progress && progress > 0; + const classes = classNames({ + 'mx_Waveform_bar': true, + 'mx_Waveform_bar_100pct': isCompleteBar, + }); + return ; })}
      ; } diff --git a/src/components/views/voip/CallPreview.tsx b/src/components/views/voip/CallPreview.tsx index 29de068b0c..d31afddec9 100644 --- a/src/components/views/voip/CallPreview.tsx +++ b/src/components/views/voip/CallPreview.tsx @@ -27,6 +27,7 @@ import SettingsStore from "../../../settings/SettingsStore"; import { CallEvent, CallState, MatrixCall } from 'matrix-js-sdk/src/webrtc/call'; import { MatrixClientPeg } from '../../../MatrixClientPeg'; import {replaceableComponent} from "../../../utils/replaceableComponent"; +import { Action } from '../../../dispatcher/actions'; const SHOW_CALL_IN_STATES = [ CallState.Connected, @@ -142,6 +143,7 @@ export default class CallPreview extends React.Component { switch (payload.action) { // listen for call state changes to prod the render method, which // may hide the global CallView if the call it is tracking is dead + case Action.CallChangeRoom: case 'call_state': { const [primaryCall, secondaryCalls] = getPrimarySecondaryCalls( CallHandler.sharedInstance().getAllActiveCallsNotInRoom(this.state.roomId), diff --git a/src/components/views/voip/CallView.tsx b/src/components/views/voip/CallView.tsx index 8a6ed75fee..6745713845 100644 --- a/src/components/views/voip/CallView.tsx +++ b/src/components/views/voip/CallView.tsx @@ -208,7 +208,7 @@ export default class CallView extends React.Component { }; private onExpandClick = () => { - const userFacingRoomId = CallHandler.roomIdForCall(this.props.call); + const userFacingRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.call); dis.dispatch({ action: 'view_room', room_id: userFacingRoomId, @@ -337,7 +337,7 @@ export default class CallView extends React.Component { }; private onRoomAvatarClick = () => { - const userFacingRoomId = CallHandler.roomIdForCall(this.props.call); + const userFacingRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.call); dis.dispatch({ action: 'view_room', room_id: userFacingRoomId, @@ -345,7 +345,7 @@ export default class CallView extends React.Component { } private onSecondaryRoomAvatarClick = () => { - const userFacingRoomId = CallHandler.roomIdForCall(this.props.secondaryCall); + const userFacingRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.secondaryCall); dis.dispatch({ action: 'view_room', @@ -354,7 +354,7 @@ export default class CallView extends React.Component { } private onCallResumeClick = () => { - const userFacingRoomId = CallHandler.roomIdForCall(this.props.call); + const userFacingRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.call); CallHandler.sharedInstance().setActiveCallRoomId(userFacingRoomId); } @@ -365,8 +365,8 @@ export default class CallView extends React.Component { public render() { const client = MatrixClientPeg.get(); - const callRoomId = CallHandler.roomIdForCall(this.props.call); - const secondaryCallRoomId = CallHandler.roomIdForCall(this.props.secondaryCall); + const callRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.call); + const secondaryCallRoomId = CallHandler.sharedInstance().roomIdForCall(this.props.secondaryCall); const callRoom = client.getRoom(callRoomId); const secCallRoom = this.props.secondaryCall ? client.getRoom(secondaryCallRoomId) : null; @@ -482,11 +482,13 @@ export default class CallView extends React.Component { const isOnHold = this.state.isLocalOnHold || this.state.isRemoteOnHold; let holdTransferContent; if (transfereeCall) { - const transferTargetRoom = MatrixClientPeg.get().getRoom(CallHandler.roomIdForCall(this.props.call)); + const transferTargetRoom = MatrixClientPeg.get().getRoom( + CallHandler.sharedInstance().roomIdForCall(this.props.call), + ); const transferTargetName = transferTargetRoom ? transferTargetRoom.name : _t("unknown person"); const transfereeRoom = MatrixClientPeg.get().getRoom( - CallHandler.roomIdForCall(transfereeCall), + CallHandler.sharedInstance().roomIdForCall(transfereeCall), ); const transfereeName = transfereeRoom ? transfereeRoom.name : _t("unknown person"); diff --git a/src/components/views/voip/CallViewForRoom.tsx b/src/components/views/voip/CallViewForRoom.tsx index 878b6af20f..7540dbc8d9 100644 --- a/src/components/views/voip/CallViewForRoom.tsx +++ b/src/components/views/voip/CallViewForRoom.tsx @@ -22,6 +22,7 @@ import dis from '../../../dispatcher/dispatcher'; import {Resizable} from "re-resizable"; import ResizeNotifier from "../../../utils/ResizeNotifier"; import {replaceableComponent} from "../../../utils/replaceableComponent"; +import { Action } from '../../../dispatcher/actions'; interface IProps { // What room we should display the call for @@ -62,6 +63,7 @@ export default class CallViewForRoom extends React.Component { private onAction = (payload) => { switch (payload.action) { + case Action.CallChangeRoom: case 'call_state': { const newCall = this.getCall(); if (newCall !== this.state.call) { diff --git a/src/components/views/voip/IncomingCallBox.tsx b/src/components/views/voip/IncomingCallBox.tsx index 0ca2a196c2..2abdc0641d 100644 --- a/src/components/views/voip/IncomingCallBox.tsx +++ b/src/components/views/voip/IncomingCallBox.tsx @@ -72,7 +72,7 @@ export default class IncomingCallBox extends React.Component { e.stopPropagation(); dis.dispatch({ action: 'answer', - room_id: CallHandler.roomIdForCall(this.state.incomingCall), + room_id: CallHandler.sharedInstance().roomIdForCall(this.state.incomingCall), }); }; @@ -80,7 +80,7 @@ export default class IncomingCallBox extends React.Component { e.stopPropagation(); dis.dispatch({ action: 'reject', - room_id: CallHandler.roomIdForCall(this.state.incomingCall), + room_id: CallHandler.sharedInstance().roomIdForCall(this.state.incomingCall), }); }; @@ -91,7 +91,7 @@ export default class IncomingCallBox extends React.Component { let room = null; if (this.state.incomingCall) { - room = MatrixClientPeg.get().getRoom(CallHandler.roomIdForCall(this.state.incomingCall)); + room = MatrixClientPeg.get().getRoom(CallHandler.sharedInstance().roomIdForCall(this.state.incomingCall)); } const caller = room ? room.name : _t("Unknown caller"); diff --git a/src/customisations/Media.ts b/src/customisations/Media.ts index b651e40a3b..f9d957b60c 100644 --- a/src/customisations/Media.ts +++ b/src/customisations/Media.ts @@ -96,6 +96,9 @@ export class Media { */ public getThumbnailHttp(width: number, height: number, mode: ResizeMethod = "scale"): string | null | undefined { if (!this.hasThumbnail) return null; + // scale using the device pixel ratio to keep images clear + width = Math.floor(width * window.devicePixelRatio); + height = Math.floor(height * window.devicePixelRatio); return this.client.mxcUrlToHttp(this.thumbnailMxc, width, height, mode); } @@ -107,6 +110,9 @@ export class Media { * @returns {string} The HTTP URL which points to the thumbnail. */ public getThumbnailOfSourceHttp(width: number, height: number, mode: ResizeMethod = "scale"): string { + // scale using the device pixel ratio to keep images clear + width = Math.floor(width * window.devicePixelRatio); + height = Math.floor(height * window.devicePixelRatio); return this.client.mxcUrlToHttp(this.srcMxc, width, height, mode); } @@ -117,6 +123,7 @@ export class Media { * @returns {string} An HTTP URL for the thumbnail. */ public getSquareThumbnailHttp(dim: number): string { + dim = Math.floor(dim * window.devicePixelRatio); // scale using the device pixel ratio to keep images clear if (this.hasThumbnail) { return this.getThumbnailHttp(dim, dim, 'crop'); } diff --git a/src/dispatcher/actions.ts b/src/dispatcher/actions.ts index cd32c3743f..46c962f160 100644 --- a/src/dispatcher/actions.ts +++ b/src/dispatcher/actions.ts @@ -114,6 +114,9 @@ export enum Action { */ VirtualRoomSupportUpdated = "virtual_room_support_updated", + // Probably would be better to have a VoIP states in a store and have the store emit changes + CallChangeRoom = "call_change_room", + /** * Fired when an upload has started. Should be used with UploadStartedPayload. */ diff --git a/src/editor/autocomplete.ts b/src/editor/autocomplete.ts index 2f56494ea0..240ed2d96b 100644 --- a/src/editor/autocomplete.ts +++ b/src/editor/autocomplete.ts @@ -125,10 +125,8 @@ export default class AutocompleteWrapperModel { case "at-room": return [this.partCreator.atRoomPill(completionId), this.partCreator.plain(completion.suffix)]; case "user": - // not using suffix here, because we also need to calculate - // the suffix when clicking a display name to insert a mention, - // which happens in createMentionParts - return this.partCreator.createMentionParts(this.partIndex, text, completionId); + // Insert suffix only if the pill is the part with index 0 - we are at the start of the composer + return this.partCreator.createMentionParts(this.partIndex === 0, text, completionId); case "command": // command needs special handling for auto complete, but also renders as plain texts return [(this.partCreator as CommandPartCreator).command(text)]; diff --git a/src/editor/parts.ts b/src/editor/parts.ts index ccd90da3e2..02c5d64895 100644 --- a/src/editor/parts.ts +++ b/src/editor/parts.ts @@ -341,11 +341,7 @@ class RoomPillPart extends PillPart { setAvatar(node: HTMLElement) { let initialLetter = ""; - let avatarUrl = Avatar.avatarUrlForRoom( - this.room, - 16 * window.devicePixelRatio, - 16 * window.devicePixelRatio, - "crop"); + let avatarUrl = Avatar.avatarUrlForRoom(this.room, 16, 16, "crop"); if (!avatarUrl) { initialLetter = Avatar.getInitialLetter(this.room ? this.room.name : this.resourceId); avatarUrl = Avatar.defaultAvatarUrlForString(this.room ? this.room.roomId : this.resourceId); @@ -383,11 +379,7 @@ class UserPillPart extends PillPart { } const name = this.member.name || this.member.userId; const defaultAvatarUrl = Avatar.defaultAvatarUrlForString(this.member.userId); - const avatarUrl = Avatar.avatarUrlForMember( - this.member, - 16 * window.devicePixelRatio, - 16 * window.devicePixelRatio, - "crop"); + const avatarUrl = Avatar.avatarUrlForMember(this.member, 16, 16, "crop"); let initialLetter = ""; if (avatarUrl === defaultAvatarUrl) { initialLetter = Avatar.getInitialLetter(name); @@ -543,9 +535,9 @@ export class PartCreator { return new UserPillPart(userId, displayName, member); } - createMentionParts(partIndex: number, displayName: string, userId: string) { + createMentionParts(insertTrailingCharacter: boolean, displayName: string, userId: string) { const pill = this.userPill(displayName, userId); - const postfix = this.plain(partIndex === 0 ? ": " : " "); + const postfix = this.plain(insertTrailingCharacter ? ": " : " "); return [pill, postfix]; } } diff --git a/src/editor/serialize.ts b/src/editor/serialize.ts index 5167e3d376..7cf9d9bb9d 100644 --- a/src/editor/serialize.ts +++ b/src/editor/serialize.ts @@ -61,9 +61,9 @@ export function htmlSerializeIfNeeded(model: EditorModel, {forceHTML = false} = // const inlinePattern = "(?:^|\\s)(?Transfer to %(transferee)s": "Konzultace s %(transferTarget)s. Převod na %(transferee)s", + "Warn before quitting": "Varovat před ukončením", + "Invite to just this room": "Pozvat jen do této místnosti", + "Quick actions": "Rychlé akce", + "Invite messages are hidden by default. Click to show the message.": "Zprávy s pozvánkou jsou ve výchozím nastavení skryté. Kliknutím zobrazíte zprávu.", + "Record a voice message": "Nahrát hlasovou zprávu", + "Stop & send recording": "Zastavit a odeslat záznam", + "Accept on your other login…": "Přijměte ve svém dalším přihlášení…", + "%(count)s people you know have already joined|other": "%(count)s lidí, které znáte, se již připojili", + "Add existing rooms": "Přidat stávající místnosti", + "Adding...": "Přidávání...", + "We couldn't create your DM.": "Nemohli jsme vytvořit vaši přímou zprávu.", + "Consult first": "Nejprve se poraďte", + "You most likely do not want to reset your event index store": "Pravděpodobně nechcete resetovat úložiště indexů událostí", + "Reset event store": "Resetovat úložiště událostí", + "Reset event store?": "Resetovat úložiště událostí?", + "Verify other login": "Ověřit další přihlášení", + "Avatar": "Avatar", + "Verification requested": "Žádost ověření", + "Please choose a strong password": "Vyberte silné heslo", + "What are some things you want to discuss in %(spaceName)s?": "O kterých tématech chcete diskutovat v %(spaceName)s?", + "Let's create a room for each of them.": "Vytvořme pro každé z nich místnost.", + "Use another login": "Použijte jiné přihlašovací jméno", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Bez ověření nebudete mít přístup ke všem svým zprávám a ostatním se můžete zobrazit jako nedůvěryhodný." } diff --git a/src/i18n/strings/cy.json b/src/i18n/strings/cy.json index 99c5296be5..b99b834636 100644 --- a/src/i18n/strings/cy.json +++ b/src/i18n/strings/cy.json @@ -8,5 +8,8 @@ "The version of %(brand)s": "Fersiwn %(brand)s", "Whether or not you're logged in (we don't record your username)": "Os ydych wedi mewngofnodi ai peidio (nid ydym yn cofnodi'ch enw defnyddiwr)", "Your language of choice": "Eich iaith o ddewis", - "The version of %(brand)s": "Fersiwn %(brand)s" + "Sign In": "Mewngofnodi", + "Create Account": "Creu Cyfrif", + "Dismiss": "Wfftio", + "Explore rooms": "Archwilio Ystafelloedd" } diff --git a/src/i18n/strings/da.json b/src/i18n/strings/da.json index 1f4eef4d93..ca28295c4f 100644 --- a/src/i18n/strings/da.json +++ b/src/i18n/strings/da.json @@ -54,7 +54,7 @@ "OK": "OK", "Search": "Søg", "Custom Server Options": "Brugerdefinerede serverindstillinger", - "Dismiss": "Afskedige", + "Dismiss": "Afslut", "powered by Matrix": "Drevet af Matrix", "Close": "Luk", "Cancel": "Afbryd", @@ -618,5 +618,45 @@ "Unable to access microphone": "Kan ikke tilgå mikrofonen", "The call could not be established": "Opkaldet kunne ikke etableres", "Call Declined": "Opkald afvist", - "Folder": "Mappe" + "Folder": "Mappe", + "We couldn't log you in": "Vi kunne ikke logge dig ind", + "Try again": "Prøv igen", + "Already in call": "", + "You're already in a call with this person.": "Du har allerede i et opkald med denne person.", + "Chile": "Chile", + "Call failed because webcam or microphone could not be accessed. Check that:": "Opkald fejlede på grund af kamera og mikrofon ikke kunne nås. Tjek dette:", + "Call failed because microphone could not be accessed. Check that a microphone is plugged in and set up correctly.": "Opkald fejlede på grund af mikrofon ikke kunne nås. Tjek at din mikrofon er tilsluttet og sat op rigtigt.", + "India": "Indien", + "Iceland": "Island", + "Hong Kong": "Hong Kong", + "Greenland": "Grønland", + "Greece": "Grækenland", + "Ghana": "Ghana", + "Germany": "Tyskland", + "Faroe Islands": "Færøerne", + "Estonia": "Estonien", + "Ecuador": "Ecuador", + "Czech Republic": "Tjekkiet", + "Colombia": "Colombien", + "Chad": "Chad", + "Bulgaria": "Bulgarien", + "Brazil": "Brazilien", + "Bosnia": "Bosnien", + "Bolivia": "Bolivien", + "Belarus": "Hviderusland", + "Austria": "Østrig", + "Australia": "Australien", + "Armenia": "Armenien", + "Argentina": "Argentina", + "Antarctica": "Antarktis", + "Angola": "Angola", + "Albania": "Albanien", + "Afghanistan": "Afghanistan", + "United States": "Amerikas Forenede Stater", + "United Kingdom": "Storbritanien", + "This will end the conference for everyone. Continue?": "Dette vil afbryde opkaldet for alle. Fortsæt?", + "No other application is using the webcam": "Ingen anden application bruger kameraet", + "A microphone and webcam are plugged in and set up correctly": "En mikrofon og kamera er tilsluttet og sat op rigtigt", + "Croatia": "Kroatien", + "Answered Elsewhere": "Svaret andet sted" } diff --git a/src/i18n/strings/de_DE.json b/src/i18n/strings/de_DE.json index d22b9ebfb7..9551f00e55 100644 --- a/src/i18n/strings/de_DE.json +++ b/src/i18n/strings/de_DE.json @@ -11,7 +11,7 @@ "The email address linked to your account must be entered.": "Es muss die mit dem Benutzerkonto verbundene E-Mail-Adresse eingegeben werden.", "Name": "Name", "Session ID": "Sitzungs-ID", - "Displays action": "Zeigt Aktionen an", + "Displays action": "Als Aktionen anzeigen", "Bans user with given id": "Verbannt den Benutzer mit der angegebenen ID", "Deops user with given id": "Setzt das Berechtigungslevel beim Benutzer mit der angegebenen ID zurück", "Invites user with given id to current room": "Lädt den Benutzer mit der angegebenen ID in den aktuellen Raum ein", @@ -25,8 +25,8 @@ "Warning!": "Warnung!", "Error": "Fehler", "Advanced": "Erweitert", - "Anyone who knows the room's link, apart from guests": "Alle, die den Raum-Link kennen (ausgenommen Gäste)", - "Anyone who knows the room's link, including guests": "Alle, die den Raum-Link kennen (auch Gäste)", + "Anyone who knows the room's link, apart from guests": "Alle, die den Raumlink kennen (ausgenommen Gäste)", + "Anyone who knows the room's link, including guests": "Alle, die den Raumlink kennen (auch Gäste)", "Are you sure you want to reject the invitation?": "Bist du sicher, dass du die Einladung ablehnen willst?", "Banned users": "Verbannte Benutzer", "Continue": "Fortfahren", @@ -50,7 +50,7 @@ "Homeserver is": "Der Heimserver ist", "Identity Server is": "Der Identitätsserver ist", "I have verified my email address": "Ich habe meine E-Mail-Adresse verifiziert", - "Import E2E room keys": "E2E-Raum-Schlüssel importieren", + "Import E2E room keys": "E2E-Raumschlüssel importieren", "Invalid Email Address": "Ungültige E-Mail-Adresse", "Sign in with": "Anmelden mit", "Leave room": "Raum verlassen", @@ -78,7 +78,7 @@ "Someone": "Jemand", "Success": "Erfolg", "This doesn't appear to be a valid email address": "Dies scheint keine gültige E-Mail-Adresse zu sein", - "This room is not accessible by remote Matrix servers": "Remote-Matrix-Server können auf diesen Raum nicht zugreifen", + "This room is not accessible by remote Matrix servers": "Ferngesteuerte Matrixserver können auf diesen Raum nicht zugreifen", "Admin": "Administrator", "Server may be unavailable, overloaded, or you hit a bug.": "Server ist nicht verfügbar, überlastet oder du bist auf einen Softwarefehler gestoßen.", "Labs": "Labor", @@ -115,7 +115,7 @@ "You are already in a call.": "Du bist bereits in einem Gespräch.", "You cannot place a call with yourself.": "Du kannst keinen Anruf mit dir selbst starten.", "You cannot place VoIP calls in this browser.": "VoIP-Gespräche werden von diesem Browser nicht unterstützt.", - "Your email address does not appear to be associated with a Matrix ID on this Homeserver.": "Deine E-Mail-Adresse scheint nicht mit einer Matrix-ID auf diesem Homeserver verbunden zu sein.", + "Your email address does not appear to be associated with a Matrix ID on this Homeserver.": "Deine E-Mail-Adresse scheint nicht mit einer Matrix-ID auf diesem Heimserver verbunden zu sein.", "Sun": "So", "Mon": "Mo", "Tue": "Di", @@ -126,12 +126,12 @@ "Jan": "Jan", "Feb": "Feb", "Mar": "Mrz", - "Apr": "April", + "Apr": "Apr", "May": "Mai", "Jun": "Jun", "Jul": "Jul", "Aug": "Aug", - "Sep": "Sep", + "Sep": "Sept", "Oct": "Okt", "Nov": "Nov", "Dec": "Dez", @@ -155,7 +155,7 @@ "%(userId)s from %(fromPowerLevel)s to %(toPowerLevel)s": "%(userId)s von %(fromPowerLevel)s zu %(toPowerLevel)s", "%(senderName)s invited %(targetName)s.": "%(senderName)s hat %(targetName)s eingeladen.", "%(targetName)s joined the room.": "%(targetName)s hat den Raum betreten.", - "%(senderName)s kicked %(targetName)s.": "%(senderName)s hat %(targetName)s gekickt.", + "%(senderName)s kicked %(targetName)s.": "%(senderName)s hat %(targetName)s rausgeworfen.", "%(targetName)s left the room.": "%(targetName)s hat den Raum verlassen.", "%(senderName)s made future room history visible to all room members, from the point they are invited.": "%(senderName)s hat den Chatverlauf für alle Raummitglieder ab ihrer Einladung sichtbar gemacht.", "%(senderName)s made future room history visible to all room members, from the point they joined.": "%(senderName)s hat den Chatverlauf für alle Raummitglieder ab ihrem Beitreten sichtbar gemacht.", @@ -190,7 +190,7 @@ "click to reveal": "anzeigen", "Failed to forget room %(errCode)s": "Das Entfernen des Raums ist fehlgeschlagen %(errCode)s", "and %(count)s others...|other": "und %(count)s weitere...", - "and %(count)s others...|one": "und ein(e) weitere(r)...", + "and %(count)s others...|one": "und ein weiterer...", "Are you sure?": "Bist du sicher?", "Attachment": "Anhang", "Ban": "Bannen", @@ -204,14 +204,14 @@ "Failed to ban user": "Verbannen des Benutzers fehlgeschlagen", "Failed to change power level": "Ändern der Berechtigungsstufe fehlgeschlagen", "Failed to join room": "Betreten des Raumes ist fehlgeschlagen", - "Failed to kick": "Kicken fehlgeschlagen", + "Failed to kick": "Rauswurf fehlgeschlagen", "Failed to mute user": "Stummschalten des Nutzers fehlgeschlagen", "Failed to reject invite": "Ablehnen der Einladung ist fehlgeschlagen", "Failed to set display name": "Anzeigename konnte nicht gesetzt werden", "Fill screen": "Fülle Bildschirm", "Incorrect verification code": "Falscher Verifizierungscode", "Join Room": "Raum beitreten", - "Kick": "Kicken", + "Kick": "Rausschmeißen", "not specified": "nicht angegeben", "No more results": "Keine weiteren Ergebnisse", "No results": "Keine Ergebnisse", @@ -237,8 +237,8 @@ "Autoplay GIFs and videos": "Videos und GIFs automatisch abspielen", "%(items)s and %(lastItem)s": "%(items)s und %(lastItem)s", "%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s": "%(weekDayName)s, %(day)s. %(monthName)s %(fullYear)s %(time)s", - "Access Token:": "Zugangs-Token:", - "Always show message timestamps": "Nachrichten-Zeitstempel immer anzeigen", + "Access Token:": "Zugangstoken:", + "Always show message timestamps": "Nachrichtenzeitstempel immer anzeigen", "Authentication": "Authentifizierung", "An error has occurred.": "Ein Fehler ist aufgetreten.", "Confirm password": "Passwort bestätigen", @@ -282,7 +282,7 @@ "If you don't specify an email address, you won't be able to reset your password. Are you sure?": "Wenn du keine E-Mail-Adresse angibst, wirst du nicht in der Lage sein, dein Passwort zurückzusetzen. Bist du sicher?", "Error decrypting audio": "Entschlüsseln des Audios fehlgeschlagen", "Error decrypting image": "Entschlüsselung des Bilds fehlgeschlagen", - "Error decrypting video": "Video-Entschlüsselung fehlgeschlagen", + "Error decrypting video": "Videoentschlüsselung fehlgeschlagen", "Import room keys": "Raum-Schlüssel importieren", "File to import": "Zu importierende Datei", "Failed to invite the following users to the %(roomName)s room:": "Folgende Benutzer konnten nicht in den Raum \"%(roomName)s\" eingeladen werden:", @@ -302,7 +302,7 @@ "Idle": "Abwesend", "Ongoing conference call%(supportedText)s.": "Laufendes Konferenzgespräch%(supportedText)s.", "You are about to be taken to a third-party site so you can authenticate your account for use with %(integrationsUrl)s. Do you wish to continue?": "Um dein Konto für die Verwendung von %(integrationsUrl)s zu authentifizieren, wirst du jetzt auf die Website eines Drittanbieters weitergeleitet. Möchtest du fortfahren?", - "Start automatically after system login": "Nach System-Login automatisch starten", + "Start automatically after system login": "Nach Systemstart automatisch starten", "Jump to first unread message.": "Zur ersten ungelesenen Nachricht springen.", "Options": "Optionen", "Invited": "Eingeladen", @@ -380,19 +380,19 @@ "(could not connect media)": "(Medienverbindung konnte nicht hergestellt werden)", "(no answer)": "(keine Antwort)", "(unknown failure: %(reason)s)": "(Unbekannter Fehler: %(reason)s)", - "Your browser does not support the required cryptography extensions": "Dein Browser unterstützt die benötigten Verschlüsselungs-Erweiterungen nicht", + "Your browser does not support the required cryptography extensions": "Dein Browser unterstützt die benötigten Verschlüsselungserweiterungen nicht", "Not a valid %(brand)s keyfile": "Keine gültige %(brand)s-Schlüsseldatei", "Authentication check failed: incorrect password?": "Authentifizierung fehlgeschlagen: Falsches Passwort?", "Do you want to set an email address?": "Möchtest du eine E-Mail-Adresse setzen?", "This will allow you to reset your password and receive notifications.": "Dies ermöglicht es dir, dein Passwort zurückzusetzen und Benachrichtigungen zu empfangen.", "Skip": "Überspringen", - "Check for update": "Nach Updates suchen", + "Check for update": "Nach Aktualisierung suchen", "Add a widget": "Widget hinzufügen", "Allow": "Erlauben", "Delete widget": "Widget entfernen", "Define the power level of a user": "Berechtigungsstufe einers Benutzers setzen", "Edit": "Bearbeiten", - "Enable automatic language detection for syntax highlighting": "Automatische Spracherkennung für die Syntax-Hervorhebung", + "Enable automatic language detection for syntax highlighting": "Automatische Spracherkennung für die Syntaxhervorhebung", "To get started, please pick a username!": "Um zu starten, wähle bitte einen Nutzernamen!", "Unable to create widget.": "Widget kann nicht erstellt werden.", "You are not in this room.": "Du bist nicht in diesem Raum.", @@ -443,7 +443,7 @@ "The user '%(displayName)s' could not be removed from the summary.": "Der Benutzer '%(displayName)s' konnte nicht aus der Übersicht entfernt werden.", "Unknown": "Unbekannt", "Failed to add the following rooms to %(groupId)s:": "Die folgenden Räume konnten nicht zu %(groupId)s hinzugefügt werden:", - "Matrix Room ID": "Matrix-Raum-ID", + "Matrix Room ID": "Matrixraum-ID", "email address": "E-Mail-Adresse", "Try using one of the following valid address types: %(validTypesList)s.": "Bitte einen der folgenden gültigen Adresstypen verwenden: %(validTypesList)s.", "Failed to remove '%(roomName)s' from %(groupId)s": "Entfernen von '%(roomName)s' aus %(groupId)s fehlgeschlagen", @@ -451,7 +451,7 @@ "Pinned Messages": "Angeheftete Nachrichten", "%(senderName)s changed the pinned messages for the room.": "%(senderName)s hat die angehefteten Nachrichten für diesen Raum geändert.", "Jump to read receipt": "Zur Lesebestätigung springen", - "Message Pinning": "Nachrichten-Anheftung", + "Message Pinning": "Nachrichtenanheftung", "Long Description (HTML)": "Lange Beschreibung (HTML)", "Jump to message": "Zur Nachricht springen", "No pinned messages.": "Keine angehefteten Nachrichten vorhanden.", @@ -476,12 +476,12 @@ "New community ID (e.g. +foo:%(localDomain)s)": "Neue Community-ID (z. B. +foo:%(localDomain)s)", "Remove from community": "Aus Community entfernen", "Failed to remove user from community": "Entfernen des Benutzers aus der Community fehlgeschlagen", - "Filter community members": "Community-Mitglieder filtern", - "Filter community rooms": "Community-Räume filtern", + "Filter community members": "Communitymitglieder filtern", + "Filter community rooms": "Communityräume filtern", "Failed to remove room from community": "Entfernen des Raumes aus der Community fehlgeschlagen", - "Removing a room from the community will also remove it from the community page.": "Das Entfernen eines Raumes aus der Community wird ihn auch von der Community-Seite entfernen.", + "Removing a room from the community will also remove it from the community page.": "Das Entfernen eines Raumes aus der Community wird ihn auch von der Communityseite entfernen.", "Create Community": "Community erstellen", - "Community Name": "Community-Name", + "Community Name": "Communityname", "Community ID": "Community-ID", "example": "Beispiel", "Add rooms to the community summary": "Fügt Räume zur Community-Übersicht hinzu", @@ -539,10 +539,10 @@ "were banned %(count)s times|one": "wurden verbannt", "was banned %(count)s times|other": "wurde %(count)s-mal verbannt", "was banned %(count)s times|one": "wurde verbannt", - "were kicked %(count)s times|other": "wurden %(count)s-mal gekickt", - "were kicked %(count)s times|one": "wurden gekickt", - "was kicked %(count)s times|other": "wurde %(count)s-mal gekickt", - "was kicked %(count)s times|one": "wurde gekickt", + "were kicked %(count)s times|other": "wurden %(count)s-mal rausgeworfen", + "were kicked %(count)s times|one": "wurden rausgeworfen", + "was kicked %(count)s times|other": "wurde %(count)s-mal rausgeworfen", + "was kicked %(count)s times|one": "wurde rausgeworfen", "%(severalUsers)schanged their name %(count)s times|other": "%(severalUsers)shaben %(count)s-mal ihren Namen geändert", "%(severalUsers)schanged their name %(count)s times|one": "%(severalUsers)shaben ihren Namen geändert", "%(oneUser)schanged their name %(count)s times|other": "%(oneUser)shat %(count)s-mal den Namen geändert", @@ -551,7 +551,7 @@ "%(oneUser)schanged their avatar %(count)s times|other": "%(oneUser)shat das Profilbild %(count)s-mal geändert", "%(oneUser)schanged their avatar %(count)s times|one": "%(oneUser)shat das Profilbild geändert", "Disinvite this user?": "Einladung für diesen Benutzer zurückziehen?", - "Kick this user?": "Diesen Benutzer kicken?", + "Kick this user?": "Diesen Benutzer rausschmeißen?", "Unban this user?": "Verbannung für diesen Benutzer aufheben?", "Ban this user?": "Diesen Benutzer verbannen?", "Members only (since the point in time of selecting this option)": "Mitglieder", @@ -577,12 +577,12 @@ "The visibility of '%(roomName)s' in %(groupId)s could not be updated.": "Die Sichtbarkeit von '%(roomName)s' in %(groupId)s konnte nicht aktualisiert werden.", "Visibility in Room List": "Sichtbarkeit in Raumliste", "Visible to everyone": "Für alle sichtbar", - "Only visible to community members": "Nur für Community-Mitglieder sichtbar", + "Only visible to community members": "Nur für Communitymitglieder sichtbar", "Community Invites": "Community-Einladungen", "Notify the whole room": "Alle im Raum benachrichtigen", "Room Notification": "Raum-Benachrichtigung", "These rooms are displayed to community members on the community page. Community members can join the rooms by clicking on them.": "Diese Räume werden Community-Mitgliedern auf der Community-Seite angezeigt. Community-Mitglieder können diesen Räumen beitreten, indem sie diese anklicken.", - "Show these rooms to non-members on the community page and room list?": "Sollen diese Räume öffentlich sichtbar auf der Community-Seite und in der Raum-Liste angezeigt werden?", + "Show these rooms to non-members on the community page and room list?": "Sollen diese Räume öffentlich auf der Community-Seite und in der Raum-Liste angezeigt werden?", "

      HTML for your community's page

      \n

      \n Use the long description to introduce new members to the community, or distribute\n some important links\n

      \n

      \n You can even use 'img' tags\n

      \n": "

      HTML für deine Community-Seite

      \n

      \n Nutze die ausführliche Beschreibung, um neuen Mitgliedern diese Community vorzustellen\n oder um wichtige Links bereitzustellen.\n

      \n

      \n Du kannst sogar 'img'-Tags (HTML) verwenden\n

      \n", "Your community hasn't got a Long Description, a HTML page to show to community members.
      Click here to open settings and give it one!": "Deine Community hat noch keine ausführliche Beschreibung, d. h. eine HTML-Seite, die Community-Mitgliedern angezeigt wird.
      Hier klicken, um die Einstellungen zu öffnen und eine Beschreibung zu erstellen!", "Enable inline URL previews by default": "URL-Vorschau standardmäßig aktivieren", @@ -627,12 +627,12 @@ "The version of %(brand)s": "Die %(brand)s-Version", "Your language of choice": "Deine ausgewählte Sprache", "Whether or not you're using the Richtext mode of the Rich Text Editor": "Ob du den Richtext-Modus des Editors benutzt oder nicht", - "Your homeserver's URL": "Deine Homeserver-URL", + "Your homeserver's URL": "Deine Heimserver-URL", "%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s": "%(weekDayName)s, %(day)s. %(monthName)s %(fullYear)s", "You will not be able to undo this change as you are demoting yourself, if you are the last privileged user in the room it will be impossible to regain privileges.": "Du wirst nicht in der Lage sein, die Änderung zurückzusetzen, da du dich degradierst. Wenn du der letze Nutzer mit Berechtigungen bist, wird es unmöglich sein die Privilegien zurückzubekommen.", "Community IDs cannot be empty.": "Community-IDs können nicht leer sein.", "Learn more about how we use analytics.": "Lerne mehr darüber, wie wir die Analysedaten nutzen.", - "Where this page includes identifiable information, such as a room, user or group ID, that data is removed before being sent to the server.": "Wenn diese Seite identifizierbare Informationen wie Raum-, Nutzer- oder Gruppen-ID enthält, werden diese Daten entfernt bevor sie an den Server gesendet werden.", + "Where this page includes identifiable information, such as a room, user or group ID, that data is removed before being sent to the server.": "Wenn diese Seite identifizierbare Informationen wie Raum-, Nutzer- oder Gruppen-ID enthält, werden diese Daten entfernt, bevor sie an den Server gesendet werden.", "Which officially provided instance you are using, if any": "Welche offiziell angebotene Instanz du nutzt, wenn überhaupt eine", "In reply to ": "Als Antwort auf ", "This room is not public. You will not be able to rejoin without an invite.": "Dies ist kein öffentlicher Raum. Du wirst diesen nicht ohne Einladung wieder beitreten können.", @@ -654,14 +654,14 @@ "Changes made to your community name and avatar might not be seen by other users for up to 30 minutes.": "Änderungen am Namen und Bild deiner Community werden evtl. erst nach 30 Minuten von anderen Nutzern gesehen werden.", "Join this community": "Community beitreten", "Leave this community": "Community verlassen", - "You don't currently have any stickerpacks enabled": "Du hast aktuell keine Stickerpacks aktiviert", + "You don't currently have any stickerpacks enabled": "Du hast aktuell keine Stickerpakete aktiviert", "Hide Stickers": "Sticker ausblenden", "Show Stickers": "Sticker anzeigen", "Who can join this community?": "Wer kann dieser Community beitreten?", "Everyone": "Jeder", - "Stickerpack": "Stickerpack", + "Stickerpack": "Stickerpaket", "Fetching third party location failed": "Das Abrufen des Drittanbieterstandorts ist fehlgeschlagen", - "Send Account Data": "Benutzerkonto-Daten senden", + "Send Account Data": "Benutzerkontodaten senden", "All notifications are currently disabled for all targets.": "Aktuell sind alle Benachrichtigungen für alle Ziele deaktiviert.", "Uploading report": "Lade Bericht hoch", "Sunday": "Sonntag", @@ -676,8 +676,8 @@ "Changelog": "Änderungsprotokoll", "Waiting for response from server": "Auf Antwort vom Server warten", "Send Custom Event": "Benutzerdefiniertes Event senden", - "Advanced notification settings": "Erweiterte Benachrichtigungs-Einstellungen", - "Failed to send logs: ": "Senden von Logs fehlgeschlagen: ", + "Advanced notification settings": "Erweiterte Benachrichtigungseinstellungen", + "Failed to send logs: ": "Senden von Protokolldateien fehlgeschlagen: ", "Forget": "Entfernen", "You cannot delete this image. (%(code)s)": "Das Bild kann nicht gelöscht werden. (%(code)s)", "Cancel Sending": "Senden abbrechen", @@ -694,12 +694,12 @@ "Please set a password!": "Bitte setze ein Passwort!", "You have successfully set a password!": "Du hast erfolgreich ein Passwort gesetzt!", "An error occurred whilst saving your email notification preferences.": "Beim Speichern deiner E-Mail-Benachrichtigungseinstellungen ist ein Fehler aufgetreten.", - "Explore Room State": "Raum-Status erkunden", + "Explore Room State": "Raumstatus erkunden", "Source URL": "Quell-URL", "Messages sent by bot": "Nachrichten von Bots", "Filter results": "Ergebnisse filtern", "Members": "Mitglieder", - "No update available.": "Kein Update verfügbar.", + "No update available.": "Keine Aktualisierung verfügbar.", "Noisy": "Laut", "Collecting app version information": "App-Versionsinformationen werden abgerufen", "Keywords": "Schlüsselwörter", @@ -714,9 +714,9 @@ "Remove %(name)s from the directory?": "Soll der Raum %(name)s aus dem Verzeichnis entfernt werden?", "%(brand)s uses many advanced browser features, some of which are not available or experimental in your current browser.": "%(brand)s nutzt zahlreiche fortgeschrittene Browser-Funktionen, die teilweise in deinem aktuell verwendeten Browser noch nicht verfügbar sind oder sich noch im experimentellen Status befinden.", "Developer Tools": "Entwicklerwerkzeuge", - "Preparing to send logs": "Senden von Logs wird vorbereitet", + "Preparing to send logs": "Senden von Protokolldateien wird vorbereitet", "Remember, you can always set an email address in user settings if you change your mind.": "Vergiss nicht, dass du in den Benutzereinstellungen jederzeit eine E-Mail-Adresse setzen kannst, wenn du deine Meinung änderst.", - "Explore Account Data": "Konto-Daten erkunden", + "Explore Account Data": "Kontodaten erkunden", "All messages (noisy)": "Alle Nachrichten (laut)", "Saturday": "Samstag", "I understand the risks and wish to continue": "Ich verstehe die Risiken und möchte fortfahren", @@ -729,33 +729,33 @@ "Enable them now": "Diese jetzt aktivieren", "Toolbox": "Werkzeugkasten", "Collecting logs": "Protokolle werden abgerufen", - "You must specify an event type!": "Du musst einen Event-Typ spezifizieren!", + "You must specify an event type!": "Du musst einen Eventtyp spezifizieren!", "(HTTP status %(httpStatus)s)": "(HTTP-Status %(httpStatus)s)", "Invite to this room": "In diesen Raum einladen", "Wednesday": "Mittwoch", "You cannot delete this message. (%(code)s)": "Diese Nachricht kann nicht gelöscht werden. (%(code)s)", "Quote": "Zitat", - "Send logs": "Logdateien übermitteln", + "Send logs": "Protokolldateien übermitteln", "All messages": "Alle Nachrichten", "Call invitation": "Anrufe", - "Downloading update...": "Update wird heruntergeladen...", - "State Key": "Status-Schlüssel", + "Downloading update...": "Aktualisierung wird heruntergeladen...", + "State Key": "Statusschlüssel", "Failed to send custom event.": "Senden des benutzerdefinierten Events fehlgeschlagen.", "What's new?": "Was ist neu?", "Notify me for anything else": "Über alles andere benachrichtigen", "When I'm invited to a room": "Einladungen", - "Can't update user notification settings": "Benachrichtigungs-Einstellungen des Benutzers konnten nicht aktualisiert werden", + "Can't update user notification settings": "Benachrichtigungseinstellungen des Benutzers konnten nicht aktualisiert werden", "Notify for all other messages/rooms": "Benachrichtigungen für alle anderen Mitteilungen/Räume aktivieren", "Unable to look up room ID from server": "Es ist nicht möglich, die Raum-ID auf dem Server nachzuschlagen", "Couldn't find a matching Matrix room": "Konnte keinen entsprechenden Matrix-Raum finden", "All Rooms": "In allen Räumen", "Thursday": "Donnerstag", "Search…": "Suchen…", - "Logs sent": "Logs gesendet", + "Logs sent": "Protokolldateien gesendet", "Back": "Zurück", "Reply": "Antworten", "Show message in desktop notification": "Nachrichteninhalt in der Desktopbenachrichtigung anzeigen", - "Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited and the usernames of other users. They do not contain messages.": "Fehlerberichte enthalten Anwendungsdaten wie deinen Nutzernamen, Raum- und Gruppen-ID's und Aliase die du besucht hast sowie Nutzernamen anderer Nutzer. Sie enthalten keine Nachrichten.", + "Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited and the usernames of other users. They do not contain messages.": "Fehlerberichte enthalten Anwendungsdaten wie deinen Nutzernamen, Raum- und Gruppen-IDs und Aliase die du besucht hast sowie Nutzernamen anderer Nutzer. Sie enthalten keine Nachrichten.", "Unhide Preview": "Vorschau wieder anzeigen", "Unable to join network": "Es ist nicht möglich, dem Netzwerk beizutreten", "Sorry, your browser is not able to run %(brand)s.": "Es tut uns leid, aber dein Browser kann %(brand)s nicht ausführen.", @@ -770,18 +770,18 @@ "Mentions only": "Nur, wenn du erwähnt wirst", "You can now return to your account after signing out, and sign in on other devices.": "Du kannst nun zu deinem Benutzerkonto zurückkehren, nachdem du dich abgemeldet hast. Anschließend kannst du dich an anderen Geräten anmelden.", "Enable email notifications": "Benachrichtigungen per E-Mail", - "Event Type": "Event-Typ", + "Event Type": "Eventtyp", "Download this file": "Datei herunterladen", "Pin Message": "Nachricht anheften", "Failed to change settings": "Einstellungen konnten nicht geändert werden", "View Community": "Community ansehen", "Event sent!": "Event gesendet!", - "View Source": "Quellcode ansehen", - "Event Content": "Event-Inhalt", + "View Source": "Rohdaten anzeigen", + "Event Content": "Eventinhalt", "Thank you!": "Danke!", "Uploaded on %(date)s by %(user)s": "Hochgeladen: %(date)s von %(user)s", "With your current browser, the look and feel of the application may be completely incorrect, and some or all features may not function. If you want to try it anyway you can continue, but you are on your own in terms of any issues you may encounter!": "In deinem aktuell verwendeten Browser können Aussehen und Handhabung der Anwendung unter Umständen noch komplett fehlerhaft sein, so dass einige bzw. im Extremfall alle Funktionen nicht zur Verfügung stehen. Du kannst es trotzdem versuchen und fortfahren, bist dabei aber bezüglich aller auftretenden Probleme auf dich allein gestellt!", - "Checking for an update...": "Nach Updates suchen...", + "Checking for an update...": "Nach Aktualisierung suchen...", "Missing roomId.": "Fehlende Raum-ID.", "Every page you use in the app": "Jede Seite, die du in der App benutzt", "e.g. ": "z. B. ", @@ -795,11 +795,11 @@ "We encountered an error trying to restore your previous session.": "Wir haben ein Problem beim Wiederherstellen deiner vorherigen Sitzung festgestellt.", "Clearing your browser's storage may fix the problem, but will sign you out and cause any encrypted chat history to become unreadable.": "Den Browser-Speicher zu löschen kann das Problem lösen, wird dich aber abmelden und verschlüsselte Chats unlesbar machen.", "Collapse Reply Thread": "Antwort-Thread zusammenklappen", - "Enable widget screenshots on supported widgets": "Widget-Screenshots bei unterstützten Widgets aktivieren", + "Enable widget screenshots on supported widgets": "Bildschirmfotos bei unterstützten Widgets aktivieren", "Send analytics data": "Analysedaten senden", "e.g. %(exampleValue)s": "z.B. %(exampleValue)s", "Muted Users": "Stummgeschaltete Benutzer", - "This will make your account permanently unusable. You will not be able to log in, and no one will be able to re-register the same user ID. This will cause your account to leave all rooms it is participating in, and it will remove your account details from your identity server. This action is irreversible.": "Dies wird deinen Konto permanent unbenutzbar machen. Du wirst nicht in der Lage sein, dich anzumelden und keiner wird dieselbe Benutzer-ID erneut registrieren können. Alle Räume, in denen der Account ist, werden verlassen und deine Account-Daten werden vom Identitätsserver gelöscht. Diese Aktion ist unumkehrbar.", + "This will make your account permanently unusable. You will not be able to log in, and no one will be able to re-register the same user ID. This will cause your account to leave all rooms it is participating in, and it will remove your account details from your identity server. This action is irreversible.": "Dies wird deinen Konto permanent unbenutzbar machen. Du wirst nicht in der Lage sein, dich anzumelden und keiner wird dieselbe Benutzer-ID erneut registrieren können. Alle Räume, in denen dein Konto ist, werden verlassen und deine Kontodaten werden vom Identitätsserver gelöscht. Diese Aktion ist unumkehrbar.", "Deactivating your account does not by default cause us to forget messages you have sent. If you would like us to forget your messages, please tick the box below.": "Standardmäßig werden die von dir gesendeten Nachrichten beim Deaktiveren nicht gelöscht. Wenn du dies von uns möchtest, aktivere das Auswahlfeld unten.", "Message visibility in Matrix is similar to email. Our forgetting your messages means that messages you have sent will not be shared with any new or unregistered users, but registered users who already have access to these messages will still have access to their copy.": "Die Sichtbarkeit der Nachrichten in Matrix ist vergleichbar mit E-Mails: Wenn wir deine Nachrichten vergessen heißt das, dass diese nicht mit neuen oder nicht registrierten Nutzern teilen werden, aber registrierte Nutzer, die bereits zugriff haben, werden Zugriff auf ihre Kopie behalten.", "Please forget all messages I have sent when my account is deactivated (Warning: this will cause future users to see an incomplete view of conversations)": "Bitte vergesst alle Nachrichten, die ich gesendet habe, wenn mein Konto deaktiviert wird. (Warnung: Zukünftige Nutzer werden eine unvollständige Konversation sehen)", @@ -821,7 +821,7 @@ "Share Message": "Nachricht teilen", "No Audio Outputs detected": "Keine Audioausgabe erkannt", "Audio Output": "Audioausgabe", - "In encrypted rooms, like this one, URL previews are disabled by default to ensure that your homeserver (where the previews are generated) cannot gather information about links you see in this room.": "In verschlüsselten Räumen wie diesem ist die Link-Vorschau standardmäßig deaktiviert, damit dein Heimserver (der die Vorschau erzeugt) keine Informationen über Links in diesem Raum bekommt.", + "In encrypted rooms, like this one, URL previews are disabled by default to ensure that your homeserver (where the previews are generated) cannot gather information about links you see in this room.": "In verschlüsselten Räumen wie diesem ist die Linkvorschau standardmäßig deaktiviert, damit dein Heimserver (der die Vorschau erzeugt) keine Informationen über Links in diesem Raum bekommt.", "When someone puts a URL in their message, a URL preview can be shown to give more information about that link such as the title, description, and an image from the website.": "Die URL-Vorschau kann Informationen wie den Titel, die Beschreibung sowie ein Vorschaubild der Website enthalten.", "The email field must not be blank.": "Das E-Mail-Feld darf nicht leer sein.", "The phone number field must not be blank.": "Das Telefonnummern-Feld darf nicht leer sein.", @@ -838,10 +838,10 @@ "Failed to remove widget": "Widget konnte nicht entfernt werden", "An error ocurred whilst trying to remove the widget from the room": "Ein Fehler trat auf während versucht wurde, das Widget aus diesem Raum zu entfernen", "System Alerts": "Systembenachrichtigung", - "Only room administrators will see this warning": "Nur Raum-Administratoren werden diese Nachricht sehen", + "Only room administrators will see this warning": "Nur Raumadministratoren werden diese Nachricht sehen", "Please contact your service administrator to continue using the service.": "Bitte kontaktiere deinen Systemadministrator, um diesen Dienst weiter zu nutzen.", - "This homeserver has hit its Monthly Active User limit.": "Dieser Heimserver hat sein Limit an monatlich aktiven Nutzern erreicht.", - "This homeserver has exceeded one of its resource limits.": "Dieser Heimserver hat einen seiner Ressourcen-Limits überschritten.", + "This homeserver has hit its Monthly Active User limit.": "Dieser Heimserver hat seinen Grenzwert an monatlich aktiven Nutzern erreicht.", + "This homeserver has exceeded one of its resource limits.": "Dieser Heimserver hat einen seiner Ressourcengrenzwert überschritten.", "Upgrade Room Version": "Raum-Version aufrüsten", "Create a new room with the same name, description and avatar": "Einen neuen Raum mit demselben Namen, Beschreibung und Profilbild erstellen", "Update any local room aliases to point to the new room": "Alle lokalen Raum-Aliase aktualisieren, damit sie auf den neuen Raum zeigen", @@ -850,8 +850,8 @@ "Your message wasn't sent because this homeserver has hit its Monthly Active User Limit. Please contact your service administrator to continue using the service.": "Deine Nachricht wurde nicht gesendet, weil dieser Heimserver sein Limit an monatlich aktiven Benutzern erreicht hat. Bitte kontaktiere deinen Systemadministrator um diesen Dienst weiter zu nutzen.", "Your message wasn't sent because this homeserver has exceeded a resource limit. Please contact your service administrator to continue using the service.": "Deine Nachricht wurde nicht gesendet, weil dieser Heimserver ein Ressourcen-Limit erreicht hat. Bitte kontaktiere deinen Systemadministrator um diesen Dienst weiter zu nutzen.", "Please contact your service administrator to continue using this service.": "Bitte kontaktiere deinen Systemadministrator um diesen Dienst weiter zu nutzen.", - "Sorry, your homeserver is too old to participate in this room.": "Sorry, dein Homeserver ist zu alt, um an diesem Raum teilzunehmen.", - "Please contact your homeserver administrator.": "Bitte setze dich mit der Administration deines Homeservers in Verbindung.", + "Sorry, your homeserver is too old to participate in this room.": "Leider ist dein Heimserver zu alt, um an diesem Raum teilzunehmen.", + "Please contact your homeserver administrator.": "Bitte setze dich mit der Administration deines Heimservers in Verbindung.", "Legal": "Rechtliches", "This room has been replaced and is no longer active.": "Dieser Raum wurde ersetzt und ist nicht länger aktiv.", "The conversation continues here.": "Die Konversation wird hier fortgesetzt.", @@ -860,11 +860,11 @@ "Failed to upgrade room": "Konnte Raum nicht aufrüsten", "The room upgrade could not be completed": "Die Raum-Aufrüstung konnte nicht fertiggestellt werden", "Upgrade this room to version %(version)s": "Diesen Raum zur Version %(version)s aufrüsten", - "Forces the current outbound group session in an encrypted room to be discarded": "Erzwingt, dass die aktuell ausgehende Gruppen-Sitzung in einem verschlüsseltem Raum verworfen wird", + "Forces the current outbound group session in an encrypted room to be discarded": "Erzwingt, dass die aktuell ausgehende Gruppensitzung in einem verschlüsseltem Raum verworfen wird", "Unable to connect to Homeserver. Retrying...": "Verbindung mit Heimserver nicht möglich. Versuche erneut...", "%(senderName)s set the main address for this room to %(address)s.": "%(senderName)s hat die Hauptadresse zu diesem Raum auf %(address)s gesetzt.", "%(senderName)s removed the main address for this room.": "%(senderName)s hat die Hauptadresse von diesem Raum entfernt.", - "Before submitting logs, you must create a GitHub issue to describe your problem.": "Bevor du Log-Dateien übermittelst, musst du ein GitHub-Issue erstellen um dein Problem zu beschreiben.", + "Before submitting logs, you must create a GitHub issue to describe your problem.": "Bevor du Protokolldateien übermittelst, musst du auf GitHub einen \"Issue\" erstellen um dein Problem zu beschreiben.", "%(brand)s now uses 3-5x less memory, by only loading information about other users when needed. Please wait whilst we resynchronise with the server!": "%(brand)s benutzt nun 3 - 5-mal weniger Arbeitsspeicher, indem Informationen über andere Nutzer erst bei Bedarf geladen werden. Bitte warte, während die Daten erneut mit dem Server abgeglichen werden!", "Updating %(brand)s": "Aktualisiere %(brand)s", "You've previously used %(brand)s on %(host)s with lazy loading of members enabled. In this version lazy loading is disabled. As the local cache is not compatible between these two settings, %(brand)s needs to resync your account.": "Du hast zuvor %(brand)s auf %(host)s ohne das verzögerte Laden von Mitgliedern genutzt. In dieser Version war das verzögerte Laden deaktiviert. Da die lokal zwischengespeicherten Daten zwischen diesen Einstellungen nicht kompatibel sind, muss %(brand)s dein Konto neu synchronisieren.", @@ -880,7 +880,7 @@ "Delete Backup": "Sicherung löschen", "Backup version: ": "Sicherungsversion: ", "Algorithm: ": "Algorithmus: ", - "To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this": "Um zu vermeiden, dass dein Chat-Verlauf verloren geht, musst du deine Raum-Schlüssel exportieren, bevor du dich abmeldest. Dazu musst du auf die neuere Version von %(brand)s zurückgehen", + "To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this": "Um zu vermeiden, dass dein Chatverlauf verloren geht, musst du deine Raumschlüssel exportieren, bevor du dich abmeldest. Dazu musst du auf die neuere Version von %(brand)s zurückgehen", "Incompatible Database": "Inkompatible Datenbanken", "Continue With Encryption Disabled": "Mit deaktivierter Verschlüsselung fortfahren", "Next": "Weiter", @@ -933,14 +933,14 @@ "Encrypted messages in group chats": "Verschlüsselte Gruppenchats", "Use a longer keyboard pattern with more turns": "Nutze ein längeres Tastaturmuster mit mehr Abwechslung", "Straight rows of keys are easy to guess": "Gerade Reihen von Tasten sind einfach zu erraten", - "Custom user status messages": "Angepasste Nutzerstatus-Nachrichten", + "Custom user status messages": "Angepasste Nutzerstatusnachrichten", "Unable to load key backup status": "Konnte Status der Schlüsselsicherung nicht laden", "Don't ask again": "Nicht erneut fragen", "Set up": "Einrichten", "Please review and accept all of the homeserver's policies": "Bitte prüfe und akzeptiere alle Richtlinien des Heimservers", "Failed to load group members": "Gruppenmitglieder konnten nicht geladen werden", "That doesn't look like a valid email address": "Sieht nicht nach einer gültigen E-Mail-Adresse aus", - "Unable to load commit detail: %(msg)s": "Konnte Commit-Details nicht laden: %(msg)s", + "Unable to load commit detail: %(msg)s": "Konnte Übermittlungsdetails nicht laden: %(msg)s", "Checking...": "Überprüfe...", "Unable to load backup status": "Konnte Sicherungsstatus nicht laden", "Failed to decrypt %(failedCount)s sessions!": "Konnte %(failedCount)s Sitzungen nicht entschlüsseln!", @@ -960,12 +960,12 @@ "If you didn't set the new recovery method, an attacker may be trying to access your account. Change your account password and set a new recovery method immediately in Settings.": "Wenn du die neue Wiederherstellungsmethode nicht festgelegt hast, versucht ein Angreifer möglicherweise, auf dein Konto zuzugreifen. Ändere dein Kontopasswort und lege sofort eine neue Wiederherstellungsmethode in den Einstellungen fest.", "Set up Secure Messages": "Richte sichere Nachrichten ein", "Go to Settings": "Gehe zu Einstellungen", - "Sign in with single sign-on": "Melde dich mit „Single Sign-On“ an", + "Sign in with single sign-on": "Einmalanmeldung nutzen", "Unrecognised address": "Nicht erkannte Adresse", "User %(user_id)s may or may not exist": "Unklar, ob Benutzer %(user_id)s existiert", "Prompt before sending invites to potentially invalid matrix IDs": "Warnen, bevor du Einladungen zu ungültigen Matrix-IDs sendest", "The following users may not exist": "Eventuell existieren folgende Benutzer nicht", - "Unable to find profiles for the Matrix IDs listed below - would you like to invite them anyway?": "Profile für die unteren Matrix IDs wurden nicht gefunden - willst Du sie trotzdem einladen?", + "Unable to find profiles for the Matrix IDs listed below - would you like to invite them anyway?": "Profile für die unteren Matrix-IDs wurden nicht gefunden - willst Du sie trotzdem einladen?", "Invite anyway and never warn me again": "Trotzdem einladen und mich nicht mehr warnen", "Invite anyway": "Trotzdem einladen", "Whether or not you're logged in (we don't record your username)": "Ob du angemeldet bist oder nicht (wir speichern deinen Benutzernamen nicht)", @@ -976,16 +976,16 @@ "%(names)s and %(count)s others are typing …|other": "%(names)s und %(count)s andere tippen…", "%(names)s and %(count)s others are typing …|one": "%(names)s und eine weitere Person tippen…", "%(names)s and %(lastPerson)s are typing …": "%(names)s und %(lastPerson)s tippen…", - "Render simple counters in room header": "Einfache Zähler in Raum-Kopfzeile anzeigen", - "Enable Emoji suggestions while typing": "Emoji-Vorschläge während Eingabe", + "Render simple counters in room header": "Einfache Zähler in Raumkopfzeile anzeigen", + "Enable Emoji suggestions while typing": "Emojivorschläge während Eingabe", "Show a placeholder for removed messages": "Zeigt einen Platzhalter für gelöschte Nachrichten an", - "Show join/leave messages (invites/kicks/bans unaffected)": "Betreten oder Verlassen von Benutzern (ausgen. Kicks/Bans)", - "Show avatar changes": "Avatar-Änderungen anzeigen", + "Show join/leave messages (invites/kicks/bans unaffected)": "Betreten oder Verlassen von Benutzern (ausgen. Einladungen/Rauswürfe/Banne)", + "Show avatar changes": "Avataränderungen anzeigen", "Show display name changes": "Änderungen von Anzeigenamen", "Send typing notifications": "Tippbenachrichtigungen senden", "Show avatars in user and room mentions": "Avatare in Benutzer- und Raumerwähnungen", "Enable big emoji in chat": "Große Emojis im Chat anzeigen", - "Enable Community Filter Panel": "Community-Filter-Panel", + "Enable Community Filter Panel": "Community-Filtertafel", "Messages containing my username": "Nachrichten mit meinem Benutzernamen", "The other party cancelled the verification.": "Die Gegenstelle hat die Überprüfung abgebrochen.", "Verified!": "Verifiziert!", @@ -1020,15 +1020,15 @@ "For help with using %(brand)s, click here.": "Um Hilfe zur Benutzung von %(brand)s zu erhalten, klicke hier.", "For help with using %(brand)s, click here or start a chat with our bot using the button below.": "Um Hilfe zur Benutzung von %(brand)s zu erhalten, klicke hier oder beginne einen Chat mit unserem Bot. Klicke dazu auf den unteren Knopf.", "Chat with %(brand)s Bot": "Chatte mit dem %(brand)s-Bot", - "Help & About": "Hilfe & Über", + "Help & About": "Hilfe und Über", "Bug reporting": "Fehler melden", "FAQ": "Häufige Fragen", "Versions": "Versionen", - "Room Addresses": "Raum-Adressen", + "Room Addresses": "Raumadressen", "Deactivating your account is a permanent action - be careful!": "Die Deaktivierung deines Kontos ist unwiderruflich - sei vorsichtig!", "Preferences": "Chats", "Room list": "Raumliste", - "The file '%(fileName)s' exceeds this homeserver's size limit for uploads": "Die Datei '%(fileName)s' überschreitet die maximale Uploadgröße deines Homeservers", + "The file '%(fileName)s' exceeds this homeserver's size limit for uploads": "Die Datei '%(fileName)s' überschreitet die maximale Uploadgröße deines Heimservers", "This room has no topic.": "Dieser Raum hat kein Thema.", "%(senderDisplayName)s made the room public to whoever knows the link.": "%(senderDisplayName)s hat den Raum für jeden, der den Link kennt, öffentlich gemacht.", "%(senderDisplayName)s made the room invite only.": "%(senderDisplayName)s hat den Raum auf eingeladene Benutzer beschränkt.", @@ -1036,7 +1036,7 @@ "%(senderDisplayName)s has allowed guests to join the room.": "%(senderDisplayName)s erlaubte Gäste diesem Raum beizutreten.", "%(senderDisplayName)s has prevented guests from joining the room.": "%(senderDisplayName)s hat Gästen verboten, diesem Raum beizutreten.", "%(senderDisplayName)s changed guest access to %(rule)s": "%(senderDisplayName)s änderte den Gastzugriff auf '%(rule)s'", - "Group & filter rooms by custom tags (refresh to apply changes)": "Gruppiere & filtere Räume nach eigenen Tags (neu laden um Änderungen zu übernehmen)", + "Group & filter rooms by custom tags (refresh to apply changes)": "Gruppiere und filtere Räume nach eigenen Tags (neu laden um Änderungen zu übernehmen)", "Unable to find a supported verification method.": "Konnte keine unterstützte Verifikationsmethode finden.", "Dog": "Hund", "Cat": "Katze", @@ -1102,7 +1102,7 @@ "Pin": "Anheften", "Timeline": "Chatverlauf", "Autocomplete delay (ms)": "Verzögerung zur Autovervollständigung (ms)", - "Roles & Permissions": "Rollen & Berechtigungen", + "Roles & Permissions": "Rollen und Berechtigungen", "Changes to who can read history will only apply to future messages in this room. The visibility of existing history will be unchanged.": "Änderungen an der Sichtbarkeit des Chatverlaufs gelten nur für zukünftige Nachrichten. Die Sichtbarkeit des existierenden Verlaufs bleibt unverändert.", "Security & Privacy": "Sicherheit", "Encryption": "Verschlüsselung", @@ -1125,7 +1125,7 @@ "Are you sure? You will lose your encrypted messages if your keys are not backed up properly.": "Bist du sicher? Du wirst alle deine verschlüsselten Nachrichten verlieren, wenn deine Schlüssel nicht gut gesichert sind.", "Encrypted messages are secured with end-to-end encryption. Only you and the recipient(s) have the keys to read these messages.": "Verschlüsselte Nachrichten sind mit Ende-zu-Ende-Verschlüsselung gesichert. Nur du und der/die Empfänger haben die Schlüssel um diese Nachrichten zu lesen.", "Restore from Backup": "Von Sicherung wiederherstellen", - "Back up your keys before signing out to avoid losing them.": "Damit du deine Schlüssel nicht verlierst, sichere sie, bevor du dich abmeldest.", + "Back up your keys before signing out to avoid losing them.": "Um deine Schlüssel nicht zu verlieren, musst du sie vor der Abmeldung sichern.", "Start using Key Backup": "Beginne Schlüsselsicherung zu nutzen", "Credits": "Danksagungen", "Starting backup...": "Starte Sicherung...", @@ -1149,7 +1149,7 @@ "Report bugs & give feedback": "Melde Fehler & gib Rückmeldungen", "Update status": "Aktualisiere Status", "Set status": "Setze Status", - "Hide": "Verberge", + "Hide": "Verbergen", "This homeserver would like to make sure you are not a robot.": "Dieser Heimserver möchte sicherstellen, dass du kein Roboter bist.", "Server Name": "Servername", "Your Modular server": "Dein Modular-Server", @@ -1207,11 +1207,11 @@ "Change permissions": "Ändere Berechtigungen", "Change topic": "Ändere das Thema", "Modify widgets": "Widgets bearbeiten", - "Default role": "Standard Rolle", + "Default role": "Standard-Rolle", "Send messages": "Nachrichten senden", "Invite users": "Benutzer einladen", "Change settings": "Einstellungen ändern", - "Kick users": "Benutzer kicken", + "Kick users": "Benutzer rauswerfen", "Ban users": "Benutzer verbannen", "Remove messages": "Nachrichten löschen", "Notify everyone": "Jeden benachrichtigen", @@ -1220,8 +1220,8 @@ "Enable encryption?": "Verschlüsselung aktivieren?", "Once enabled, encryption for a room cannot be disabled. Messages sent in an encrypted room cannot be seen by the server, only by the participants of the room. Enabling encryption may prevent many bots and bridges from working correctly. Learn more about encryption.": "Sobald aktiviert, kann die Verschlüsselung für einen Raum nicht mehr deaktiviert werden. Nachrichten in einem verschlüsselten Raum können nur noch von Teilnehmern aber nicht mehr vom Server gelesen werden. Einige Bots und Brücken werden vielleicht nicht mehr funktionieren. Erfahre mehr über Verschlüsselung.", "Error updating main address": "Fehler beim Aktualisieren der Hauptadresse", - "There was an error updating the room's main address. It may not be allowed by the server or a temporary failure occurred.": "Es gab ein Problem beim Aktualisieren der Raum-Hauptadresse. Es kann sein, dass es vom Server verboten ist oder ein temporäres Problem auftrat.", - "Error updating flair": "Abzeichen-Aktualisierung fehlgeschlagen", + "There was an error updating the room's main address. It may not be allowed by the server or a temporary failure occurred.": "Es gab ein Problem beim Aktualisieren der Raumhauptadresse. Es kann sein, dass es vom Server verboten ist oder ein temporäres Problem auftrat.", + "Error updating flair": "Abzeichenaktualisierung fehlgeschlagen", "There was an error updating the flair for this room. The server may not allow it or a temporary error occurred.": "Es gab ein Problem beim Aktualisieren des Abzeichens für diesen Raum. Es kann sein, dass der Server es nicht erlaubt oder ein temporäres Problem auftrat.", "Power level": "Berechtigungsstufe", "Room Settings - %(roomName)s": "Raumeinstellungen - %(roomName)s", @@ -1238,28 +1238,28 @@ "You cannot modify widgets in this room.": "Du darfst in diesem Raum keine Widgets verändern.", "Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)": "Ob du die \"Breadcrumbs\"-Funktion nutzt oder nicht (Avatare oberhalb der Raumliste)", "The server does not support the room version specified.": "Der Server unterstützt die angegebene Raumversion nicht.", - "Warning: Upgrading a room will not automatically migrate room members to the new version of the room. We'll post a link to the new room in the old version of the room - room members will have to click this link to join the new room.": "Achtung: Ein Raum-Upgrade wird die Mitglieder des Raumes nicht automatisch auf die neue Version migrieren. Wir werden in der alten Raumversion einen Link zum neuen Raum posten - Raum-Mitglieder müssen dann auf diesen Link klicken um dem neuen Raum beizutreten.", + "Warning: Upgrading a room will not automatically migrate room members to the new version of the room. We'll post a link to the new room in the old version of the room - room members will have to click this link to join the new room.": "Achtung: Ein Raum-Upgrade wird die Mitglieder des Raumes nicht automatisch auf die neue Version migrieren. Wir werden in der alten Raumversion einen Link zum neuen Raum posten - Raummitglieder müssen dann auf diesen Link klicken um dem neuen Raum beizutreten.", "Replying With Files": "Mit Dateien antworten", - "At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "Momentan ist es nicht möglich mit einer Datei zu antworten. Möchtest Du die Datei hochladen ohne zu antworten?", + "At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "Momentan ist es nicht möglich mit einer Datei zu antworten. Möchtest Du die Datei hochladen, ohne zu antworten?", "The file '%(fileName)s' failed to upload.": "Die Datei \"%(fileName)s\" konnte nicht hochgeladen werden.", "Changes your avatar in this current room only": "Ändert deinen Avatar für diesen Raum", "Unbans user with given ID": "Entbannt den Benutzer mit der angegebenen ID", "Sends the given message coloured as a rainbow": "Sendet die Nachricht in Regenbogenfarben", - "Adds a custom widget by URL to the room": "Fügt ein Benutzer-Widget über eine URL zum Raum hinzu", + "Adds a custom widget by URL to the room": "Fügt ein Benutzerwidget über eine URL zum Raum hinzu", "Please supply a https:// or http:// widget URL": "Bitte gib eine mit https:// oder http:// beginnende Widget-URL an", "Sends the given emote coloured as a rainbow": "Zeigt Aktionen in Regenbogenfarben", "%(senderName)s made no change.": "%(senderName)s hat keine Änderung vorgenommen.", "%(senderName)s revoked the invitation for %(targetDisplayName)s to join the room.": "%(senderName)s hat die Einladung zum Raumbeitritt für %(targetDisplayName)s zurückgezogen.", "Cannot reach homeserver": "Der Heimserver ist nicht erreichbar", - "Ensure you have a stable internet connection, or get in touch with the server admin": "Stelle sicher, dass du eine stabile Internetverbindung hast oder wende dich an deinen Server-Administrator", + "Ensure you have a stable internet connection, or get in touch with the server admin": "Stelle sicher, dass du eine stabile Internetverbindung hast oder wende dich an deinen Serveradministrator", "Ask your %(brand)s admin to check your config for incorrect or duplicate entries.": "Wende dich an deinen %(brand)s-Admin um deine Konfiguration auf ungültige oder doppelte Einträge zu überprüfen.", - "Unexpected error resolving identity server configuration": "Ein unerwarteter Fehler ist beim Laden der Identitätsserver-Konfiguration aufgetreten", + "Unexpected error resolving identity server configuration": "Ein unerwarteter Fehler ist beim Laden der Identitätsserverkonfiguration aufgetreten", "Cannot reach identity server": "Der Identitätsserver ist nicht erreichbar", - "You can register, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dich registrieren, aber manche Funktionen werden erst wieder verfügbar sein, wenn der Identitätsserver wieder online ist. Wenn diese Warnmeldung weiterhin angezeigt wird, überprüfe deine Konfiguration oder kontaktiere die Server-Administration.", - "You can reset your password, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dein Passwort zurücksetzen, aber manche Funktionen werden nicht verfügbar sein, bis der Identitätsserver wieder online ist. Wenn du diese Warnmeldung weiterhin siehst, überprüfe deine Konfiguration oder kontaktiere die Server-Administration.", - "You can log in, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dich einloggen, aber manche Funktionen werden nicht verfügbar sein bis der Identitätsserver wieder online ist. Wenn du diese Warnmeldung weiterhin siehst, überprüfe deine Konfiguration oder kontaktiere deinen Server-Administrator.", + "You can register, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dich registrieren, aber manche Funktionen werden erst wieder verfügbar sein, wenn der Identitätsserver wieder online ist. Wenn diese Warnmeldung weiterhin angezeigt wird, überprüfe deine Konfiguration oder kontaktiere die Serveradministration.", + "You can reset your password, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dein Passwort zurücksetzen, aber manche Funktionen werden nicht verfügbar sein, bis der Identitätsserver wieder online ist. Wenn du diese Warnmeldung weiterhin siehst, überprüfe deine Konfiguration oder kontaktiere die Serveradministrator.", + "You can log in, but some features will be unavailable until the identity server is back online. If you keep seeing this warning, check your configuration or contact a server admin.": "Du kannst dich anmelden, aber manche Funktionen werden nicht verfügbar sein bis der Identitätsserver wieder erreichbar ist. Wenn du diese Warnmeldung weiterhin siehst, überprüfe deine Konfiguration oder kontaktiere deinen Serveradministrator.", "No homeserver URL provided": "Keine Heimserver-URL angegeben", - "Unexpected error resolving homeserver configuration": "Ein unerwarteter Fehler ist beim Laden der Heimserver-Konfiguration aufgetreten", + "Unexpected error resolving homeserver configuration": "Ein unerwarteter Fehler ist beim Laden der Heimserverkonfiguration aufgetreten", "The user's homeserver does not support the version of the room.": "Die Raumversion wird vom Heimserver des Benutzers nicht unterstützt.", "Show hidden events in timeline": "Zeige versteckte Ereignisse in der Chronik", "Low bandwidth mode": "Modus für niedrige Bandbreite", @@ -1274,7 +1274,7 @@ " invited you": " hat dich eingeladen", "edited": "bearbeitet", "Edit message": "Nachricht bearbeiten", - "GitHub issue": "GitHub-Issue", + "GitHub issue": "\"Issue\" auf Github", "Upload files": "Dateien hochladen", "Upload all": "Alle hochladen", "Upload": "Hochladen", @@ -1298,16 +1298,16 @@ "Call failed due to misconfigured server": "Anruf aufgrund eines falsch konfigurierten Servers fehlgeschlagen", "Try using turn.matrix.org": "Versuche es mit turn.matrix.org", "You do not have the required permissions to use this command.": "Du hast nicht die erforderlichen Berechtigungen, diesen Befehl zu verwenden.", - "Multiple integration managers": "Mehrere Integrationsmanager", + "Multiple integration managers": "Mehrere Integrationsverwalter", "Public Name": "Öffentlicher Name", - "Identity Server URL must be HTTPS": "Die Identity-Server-URL über HTTPS erreichbar sein", + "Identity Server URL must be HTTPS": "Identitätsserver-URL muss HTTPS sein", "Could not connect to Identity Server": "Verbindung zum Identitätsserver konnte nicht hergestellt werden", "Checking server": "Server wird überprüft", "Identity server has no terms of service": "Der Identitätsserver hat keine Nutzungsbedingungen", "Disconnect": "Trennen", "Identity Server": "Identitätsserver", "Use an identity server": "Benutze einen Identitätsserver", - "Use an identity server to invite by email. Click continue to use the default identity server (%(defaultIdentityServerName)s) or manage in Settings.": "Benutze einen Identitätsserver, um andere mittels E-Mail einzuladen. Klicke auf fortfahren, um den Standard-Identitätsserver (%(defaultIdentityServerName)s) zu benutzen oder ändere ihn in den Einstellungen.", + "Use an identity server to invite by email. Click continue to use the default identity server (%(defaultIdentityServerName)s) or manage in Settings.": "Benutze einen Identitätsserver, um andere mittels E-Mail einzuladen. Klicke auf fortfahren, um den Standardidentitätsserver (%(defaultIdentityServerName)s) zu benutzen oder ändere ihn in den Einstellungen.", "ID": "ID", "Not a valid Identity Server (status code %(code)s)": "Ungültiger Identitätsserver (Fehlercode %(code)s)", "Terms of service not accepted or the identity server is invalid.": "Die Nutzungsbedingungen wurden nicht akzeptiert oder der Identitätsserver ist ungültig.", @@ -1328,8 +1328,8 @@ "Find a room…": "Einen Raum suchen…", "Find a room… (e.g. %(exampleRoom)s)": "Einen Raum suchen… (z.B. %(exampleRoom)s)", "If you can't find the room you're looking for, ask for an invite or Create a new room.": "Wenn du den gesuchten Raum nicht finden kannst, frage nach einer Einladung für den Raum oder Erstelle einen neuen Raum.", - "Alternatively, you can try to use the public server at turn.matrix.org, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.": "Alternativ kannst du versuchen, den öffentlichen Server unter turn.matrix.org zu verwenden. Allerdings wird dieser nicht so zuverlässig sein und du teilst deine IP-Adresse mit diesem Server. Du kannst dies auch in den Einstellungen konfigurieren.", - "This action requires accessing the default identity server to validate an email address or phone number, but the server does not have any terms of service.": "Diese Handlung erfordert es, auf den Standard-Identitätsserver zuzugreifen, um eine E-Mail Adresse oder Telefonnummer zu validieren, aber der Server hat keine Nutzungsbedingungen.", + "Alternatively, you can try to use the public server at turn.matrix.org, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.": "Alternativ kannst du versuchen, den öffentlichen Server unter turn.matrix.org zu verwenden. Allerdings wird dieser nicht so zuverlässig sein und du teilst deine IP-Adresse mit dem Server. Du kannst dies auch in den Einstellungen konfigurieren.", + "This action requires accessing the default identity server to validate an email address or phone number, but the server does not have any terms of service.": "Diese Handlung erfordert es, auf den Standardidentitätsserver zuzugreifen, um eine E-Mail-Adresse oder Telefonnummer zu validieren, aber der Server hat keine Nutzungsbedingungen.", "Only continue if you trust the owner of the server.": "Fahre nur fort, wenn du den Betreibern des Servers vertraust.", "Trust": "Vertrauen", "Custom (%(level)s)": "Benutzerdefinierte (%(level)s)", @@ -1368,7 +1368,7 @@ "%(num)s hours from now": "in %(num)s Stunden", "about a day from now": "in etwa einem Tag", "%(num)s days from now": "in %(num)s Tagen", - "Show info about bridges in room settings": "Information über Bridges in den Raumeinstellungen anzeigen", + "Show info about bridges in room settings": "Information über Brücken in den Raumeinstellungen anzeigen", "Enable message search in encrypted rooms": "Nachrichtensuche in verschlüsselten Räumen aktivieren", "Lock": "Schloss", "Later": "Später", @@ -1380,9 +1380,9 @@ "Manage": "Verwalten", "Securely cache encrypted messages locally for them to appear in search results.": "Speichere verschlüsselte Nachrichten lokal, sodass sie deinen Suchergebnissen erscheinen können.", "Enable": "Aktivieren", - "Connecting to integration manager...": "Verbinde mit Integrationsmanager...", - "Cannot connect to integration manager": "Verbindung zum Integrationsmanager fehlgeschlagen", - "The integration manager is offline or it cannot reach your homeserver.": "Der Integrationsmanager ist offline oder er kann den Heimserver nicht erreichen.", + "Connecting to integration manager...": "Verbinde mit Integrationsverwalter...", + "Cannot connect to integration manager": "Verbindung zum Integrationsverwalter fehlgeschlagen", + "The integration manager is offline or it cannot reach your homeserver.": "Der Integrationsverwalter ist offline oder er kann den Heimserver nicht erreichen.", "not stored": "nicht gespeichert", "Backup has a signature from unknown user with ID %(deviceId)s": "Die Sicherung hat eine Signatur von unbekanntem Nutzer mit ID %(deviceId)s", "Backup key stored: ": "Backup Schlüssel gespeichert: ", @@ -1394,10 +1394,10 @@ "wait and try again later": "warte und versuche es später erneut", "Disconnect anyway": "Verbindung trotzdem trennen", "You are still sharing your personal data on the identity server .": "Du teilst deine persönlichen Daten immer noch auf dem Identitätsserver .", - "We recommend that you remove your email addresses and phone numbers from the identity server before disconnecting.": "Wir empfehlen, dass du deine Email Adressen und Telefonnummern vom Identitätsserver löschst, bevor du die Verbindung trennst.", + "We recommend that you remove your email addresses and phone numbers from the identity server before disconnecting.": "Wir empfehlen, dass du deine E-Mail-Adressen und Telefonnummern vom Identitätsserver löschst, bevor du die Verbindung trennst.", "You are not currently using an identity server. To discover and be discoverable by existing contacts you know, add one below.": "Zur Zeit benutzt du keinen Identitätsserver. Trage unten einen Server ein, um Kontakte finden und von anderen gefunden zu werden.", - "Use an Integration Manager (%(serverName)s) to manage bots, widgets, and sticker packs.": "Nutze einen Integrationsmanager (%(serverName)s), um Bots, Widgets und Stickerpacks zu verwalten.", - "Use an Integration Manager to manage bots, widgets, and sticker packs.": "Verwende einen Integrationsmanager, um Bots, Widgets und Sticker Packs zu verwalten.", + "Use an Integration Manager (%(serverName)s) to manage bots, widgets, and sticker packs.": "Nutze einen Integrationsverwalter (%(serverName)s), um Bots, Widgets und Stickerpakete zu verwalten.", + "Use an Integration Manager to manage bots, widgets, and sticker packs.": "Verwende einen Integrationsverwalter, um Bots, Widgets und Stickerpakete zu verwalten.", "Manage integrations": "Integrationen verwalten", "Agree to the identity server (%(serverName)s) Terms of Service to allow yourself to be discoverable by email address or phone number.": "Stimme den Nutzungsbedingungen des Identitätsservers %(serverName)s zu, um dich per E-Mail-Adresse und Telefonnummer auffindbar zu machen.", "Clear cache and reload": "Zwischenspeicher löschen und neu laden", @@ -1416,25 +1416,25 @@ "View rules": "Regeln öffnen", "You are currently subscribed to:": "Du abonnierst momentan:", "⚠ These settings are meant for advanced users.": "⚠ Diese Einstellungen sind für fortgeschrittene Nutzer gedacht.", - "Whether you're using %(brand)s on a device where touch is the primary input mechanism": "Ob du %(brand)s auf einem Gerät verwendest, bei dem das Tasten die primäre Eingabemöglichkeit ist", - "Whether you're using %(brand)s as an installed Progressive Web App": "Ob du %(brand)s als installierte progressive Web-App verwendest", - "Your user agent": "Dein User-Agent", + "Whether you're using %(brand)s on a device where touch is the primary input mechanism": "Ob du %(brand)s auf einem Gerät verwendest, bei dem die Berührung die primäre Eingabemöglichkeit ist", + "Whether you're using %(brand)s as an installed Progressive Web App": "Ob du %(brand)s als installierte progressive Web-App (PWA) verwendest", + "Your user agent": "Dein Useragent", "If you cancel now, you won't complete verifying the other user.": "Wenn Sie jetzt abbrechen, werden Sie die Verifizierung des anderen Nutzers nicht beenden können.", "If you cancel now, you won't complete verifying your other session.": "Wenn Sie jetzt abbrechen, werden Sie die Verifizierung der anderen Sitzung nicht beenden können.", "Cancel entering passphrase?": "Eingabe der Passphrase abbrechen?", "Setting up keys": "Einrichten der Schlüssel", - "Encryption upgrade available": "Verschlüsselungs-Update verfügbar", - "Verifies a user, session, and pubkey tuple": "Verifiziert einen Benutzer, eine Sitzung und Pubkey-Tupel", + "Encryption upgrade available": "Verschlüsselungsaufstufung verfügbar", + "Verifies a user, session, and pubkey tuple": "Verifiziert einen Benutzer, eine Sitzung und die öffentlichen Schlüsselpaare", "Unknown (user, session) pair:": "Unbekanntes Nutzer-/Sitzungspaar:", "Session already verified!": "Sitzung bereits verifiziert!", "WARNING: Session already verified, but keys do NOT MATCH!": "WARNUNG: Die Sitzung wurde bereits verifiziert, aber die Schlüssel passen NICHT ZUSAMMEN!", - "WARNING: KEY VERIFICATION FAILED! The signing key for %(userId)s and session %(deviceId)s is \"%(fprint)s\" which does not match the provided key \"%(fingerprint)s\". This could mean your communications are being intercepted!": "ACHTUNG: SCHLÜSSEL-VERIFIZIERUNG FEHLGESCHLAGEN! Der Signierschlüssel für %(userId)s und Sitzung %(deviceId)s ist \"%(fprint)s\", was nicht mit dem bereitgestellten Schlüssel \"%(fingerprint)s\" übereinstimmt. Das könnte bedeuten, dass deine Kommunikation abgehört wird!", + "WARNING: KEY VERIFICATION FAILED! The signing key for %(userId)s and session %(deviceId)s is \"%(fprint)s\" which does not match the provided key \"%(fingerprint)s\". This could mean your communications are being intercepted!": "ACHTUNG: SCHLÜSSELVERIFIZIERUNG FEHLGESCHLAGEN! Der Signierschlüssel für %(userId)s und Sitzung %(deviceId)s ist \"%(fprint)s\", was nicht mit dem bereitgestellten Schlüssel \"%(fingerprint)s\" übereinstimmt. Das könnte bedeuten, dass deine Kommunikation abgehört wird!", "Never send encrypted messages to unverified sessions from this session": "Niemals verschlüsselte Nachrichten von dieser Sitzung zu unverifizierten Sitzungen senden", "Never send encrypted messages to unverified sessions in this room from this session": "Niemals verschlüsselte Nachrichten von dieser Sitzung zu unverifizierten Sitzungen in diesem Raum senden", - "Changing password will currently reset any end-to-end encryption keys on all sessions, making encrypted chat history unreadable, unless you first export your room keys and re-import them afterwards. In future this will be improved.": "Durch die Änderung des Passworts werden derzeit alle Ende-zu-Ende-Verschlüsselungsschlüssel in allen Sitzungen zurückgesetzt, sodass der verschlüsselte Chat-Verlauf nicht mehr lesbar ist, es sei denn, du exportierst zuerst deine Raumschlüssel und importierst sie anschließend wieder. In Zukunft wird dies verbessert werden.", + "Changing password will currently reset any end-to-end encryption keys on all sessions, making encrypted chat history unreadable, unless you first export your room keys and re-import them afterwards. In future this will be improved.": "Durch die Änderung des Passworts werden derzeit alle Ende-zu-Ende-Verschlüsselungsschlüssel in allen Sitzungen zurückgesetzt, sodass der verschlüsselte Chatverlauf nicht mehr lesbar ist, es sei denn, du exportierst zuerst deine Raumschlüssel und importierst sie anschließend wieder. In Zukunft wird dies verbessert werden.", "Delete %(count)s sessions|other": "%(count)s Sitzungen löschen", "Backup is not signed by any of your sessions": "Die Sicherung wurde von keiner deiner Sitzungen bestätigt", - "Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them": "Dein Passwort wurde erfolgreich geändert. Du erhältst keine Push-Benachrichtigungen zu anderen Sitzungen, bis du dich wieder bei diesen anmeldest", + "Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them": "Dein Passwort wurde erfolgreich geändert. Du erhältst keine Puschbenachrichtigungen zu anderen Sitzungen, bis du dich wieder bei diesen anmeldest", "Notification sound": "Benachrichtigungston", "Set a new custom sound": "Benutzerdefinierten Ton setzen", "Browse": "Durchsuchen", @@ -1461,7 +1461,7 @@ "If your other sessions do not have the key for this message you will not be able to decrypt them.": "Wenn deine anderen Sitzungen nicht über den Schlüssel für diese Nachricht verfügen, kannst du die Nachricht nicht entschlüsseln.", "Re-request encryption keys from your other sessions.": "Fordere die Schlüssel aus deinen anderen Sitzungen erneut an.", "Room %(name)s": "Raum %(name)s", - "Upgrading this room will shut down the current instance of the room and create an upgraded room with the same name.": "Ein Upgrade dieses Raums schaltet die aktuelle Instanz des Raums ab und erstellt einen aktualisierten Raum mit demselben Namen.", + "Upgrading this room will shut down the current instance of the room and create an upgraded room with the same name.": "Ein Aktualisierung dieses Raums deaktiviert die aktuelle Instanz des Raums und erstellt einen aktualisierten Raum mit demselben Namen.", "%(name)s (%(userId)s) signed in to a new session without verifying it:": "%(name)s (%(userId)s) hat sich zu einer neuen Sitzung angemeldet, ohne sie zu verifizieren:", "%(count)s verified sessions|other": "%(count)s verifizierte Sitzungen", "Hide verified sessions": "Verifizierte Sitzungen ausblenden", @@ -1594,7 +1594,7 @@ "This backup is trusted because it has been restored on this session": "Dieser Sicherung wird vertraut, da sie während dieser Sitzung wiederhergestellt wurde", "Enable desktop notifications for this session": "Desktopbenachrichtigungen in dieser Sitzung", "Enable audible notifications for this session": "Benachrichtigungstöne in dieser Sitzung", - "Integration Managers receive configuration data, and can modify widgets, send room invites, and set power levels on your behalf.": "Integrationsmanager erhalten Konfigurationsdaten und können Widgets modifizieren, Raumeinladungen verschicken und in deinem Namen Berechtigungslevel setzen.", + "Integration Managers receive configuration data, and can modify widgets, send room invites, and set power levels on your behalf.": "Integrationsverwalter erhalten Konfigurationsdaten und können Widgets modifizieren, Raumeinladungen verschicken und in deinem Namen Berechtigungslevel setzen.", "Read Marker lifetime (ms)": "Gültigkeitsdauer der Gelesen-Markierung (ms)", "Read Marker off-screen lifetime (ms)": "Gültigkeitsdauer der Gelesen-Markierung außerhalb des Bildschirms (ms)", "Session key:": "Sitzungsschlüssel:", @@ -1609,7 +1609,7 @@ "The encryption used by this room isn't supported.": "Die von diesem Raum verwendete Verschlüsselung wird nicht unterstützt.", "React": "Reagieren", "e.g. my-room": "z.B. mein-raum", - "Use an identity server to invite by email. Use the default (%(defaultIdentityServerName)s) or manage in Settings.": "Verwende einen Identitätsserver, um per E-Mail einzuladen. Nutze den Standard-Identitätsserver (%(defaultIdentityServerName)s) oder konfiguriere einen in den Einstellungen.", + "Use an identity server to invite by email. Use the default (%(defaultIdentityServerName)s) or manage in Settings.": "Verwende einen Identitätsserver, um per E-Mail einzuladen. Nutze den Standardidentitätsserver (%(defaultIdentityServerName)s) oder konfiguriere einen in den Einstellungen.", "Use an identity server to invite by email. Manage in Settings.": "Verwende einen Identitätsserver, um mit einer E-Mail-Adresse einzuladen. Diese können in den Einstellungen konfiguriert werden.", "Create a public room": "Öffentlichen Raum erstellen", "Show advanced": "Erweiterte Einstellungen", @@ -1633,11 +1633,11 @@ "Sends a message as html, without interpreting it as markdown": "Verschickt eine Nachricht im HTML-Format, ohne sie als Markdown zu darzustellen", "Show rooms with unread notifications first": "Räume mit ungelesenen Benachrichtigungen zuerst zeigen", "Show shortcuts to recently viewed rooms above the room list": "Kürzlich besuchte Räume anzeigen", - "Use Single Sign On to continue": "Einmal-Anmeldung zum Fortfahren nutzen", - "Confirm adding this email address by using Single Sign On to prove your identity.": "Bestätige die hinzugefügte E-Mail-Adresse mit der Einmal-Anmeldung, um deine Identität nachzuweisen.", - "Single Sign On": "Einmal-Anmeldung", + "Use Single Sign On to continue": "Einmalanmeldung zum Fortfahren nutzen", + "Confirm adding this email address by using Single Sign On to prove your identity.": "Bestätige die hinzugefügte E-Mail-Adresse mit der Einmalanmeldung, um deine Identität nachzuweisen.", + "Single Sign On": "Einmalanmeldung", "Confirm adding email": "Hinzugefügte E-Mail-Addresse bestätigen", - "Confirm adding this phone number by using Single Sign On to prove your identity.": "Bestätige die hinzugefügte Telefonnummer, indem du deine Identität mittels der Einmal-Anmeldung nachweist.", + "Confirm adding this phone number by using Single Sign On to prove your identity.": "Bestätige die hinzugefügte Telefonnummer, indem du deine Identität mittels der Einmalanmeldung nachweist.", "Click the button below to confirm adding this phone number.": "Klicke unten die Schaltfläche, um die hinzugefügte Telefonnummer zu bestätigen.", "If you cancel now, you won't complete your operation.": "Wenn du jetzt abbrichst, wirst du deinen Vorgang nicht fertigstellen.", "%(name)s is requesting verification": "%(name)s fordert eine Verifizierung an", @@ -1676,14 +1676,14 @@ "Forgotten your password?": "Passwort vergessen?", "You're signed out": "Du wurdest abgemeldet", "Warning: Your personal data (including encryption keys) is still stored in this session. Clear it if you're finished using this session, or want to sign in to another account.": "Achtung: Deine persönlichen Daten (einschließlich Verschlüsselungsschlüssel) sind noch in dieser Sitzung gespeichert. Lösche diese Daten, wenn du diese Sitzung nicht mehr benötigst, oder dich mit einem anderen Konto anmelden möchtest.", - "Confirm deleting these sessions by using Single Sign On to prove your identity.|other": "Melde dich mittels Single Sign-On an, um das Löschen der Sitzungen zu bestätigen.", - "Confirm deleting these sessions by using Single Sign On to prove your identity.|one": "Melde dich mittels Single Sign-On an, um das Löschen der Sitzung zu bestätigen.", + "Confirm deleting these sessions by using Single Sign On to prove your identity.|other": "Melde dich mittels Einmalanmeldung an, um das Löschen der Sitzungen zu bestätigen.", + "Confirm deleting these sessions by using Single Sign On to prove your identity.|one": "Bestätige das Löschen dieser Sitzung mittels Einmalanmeldung um deine Identität nachzuweisen.", "Confirm deleting these sessions": "Bestätige das Löschen dieser Sitzungen", "Click the button below to confirm deleting these sessions.|other": "Klicke den Knopf, um das Löschen dieser Sitzungen zu bestätigen.", "Click the button below to confirm deleting these sessions.|one": "Klicke den Knopf, um das Löschen dieser Sitzung zu bestätigen.", "Clear all data in this session?": "Alle Daten dieser Sitzung löschen?", "Clear all data": "Alle Daten löschen", - "Confirm your account deactivation by using Single Sign On to prove your identity.": "Bestätige das Löschen deines Kontos indem du dich mittels Single Sign-On anmeldest um deine Identität nachzuweisen.", + "Confirm your account deactivation by using Single Sign On to prove your identity.": "Bestätige das Löschen deines Kontos indem du dich mittels Einmalanmeldung anmeldest um deine Identität nachzuweisen.", "Confirm account deactivation": "Konto löschen bestätigen", "Confirm your identity by entering your account password below.": "Bestätige deine Identität, indem du unten dein Kontopasswort eingibst.", "Confirm your identity by verifying this login from one of your other sessions, granting it access to encrypted messages.": "Bestätige deine Identität indem du diesen Login von einer deiner anderen Sitzungen verifizierst um Zugriff auf deine verschlüsselten Nachrichten zu erhalten.", @@ -1710,21 +1710,21 @@ "eg: @bot:* or example.org": "z.B. @bot:* oder example.org", "Subscribed lists": "Abonnierte Listen", "Subscribing to a ban list will cause you to join it!": "Eine Verbotsliste abonnieren bedeutet ihr beizutreten!", - "If this isn't what you want, please use a different tool to ignore users.": "Wenn dies nicht das ist, was du willst, verwende ein anderes Tool, um Benutzer zu blockieren.", + "If this isn't what you want, please use a different tool to ignore users.": "Wenn dies nicht das ist, was du willst, verwende ein anderes Werkzeug, um Benutzer zu blockieren.", "Subscribe": "Abonnieren", "Always show the window menu bar": "Fenstermenüleiste immer anzeigen", "Show tray icon and minimize window to it on close": "Beim Schließen des Fensters in die Taskleiste minimieren", "Session ID:": "Sitzungs-ID:", "Message search": "Nachrichtensuche", - "Cross-signing": "Cross-Signing", + "Cross-signing": "Quersignierung", "This room is bridging messages to the following platforms. Learn more.": "Dieser Raum verbindet Nachrichten mit den folgenden Plattformen. Mehr erfahren.", "This room isn’t bridging messages to any platforms. Learn more.": "Dieser Raum verbindet keine Nachrichten mit anderen Plattformen. Mehr erfahren.", - "Bridges": "Bridges", + "Bridges": "Brücken", "Uploaded sound": "Hochgeladener Ton", "Upgrade this room to the recommended room version": "Aktualisiere diesen Raum auf die empfohlene Raumversion", "this room": "Dieser Raum", "View older messages in %(roomName)s.": "Zeige alte Nachrichten in %(roomName)s.", - "Send a bug report with logs": "Einen Fehlerbericht mit Logs senden", + "Send a bug report with logs": "Einen Fehlerbericht mit der Protokolldatei senden", "Verify all your sessions to ensure your account & messages are safe": "Verifiziere alle deine Sitzungen, um dein Konto und deine Nachrichten zu schützen", "Verify your other session using one of the options below.": "Verifiziere deine andere Sitzung mit einer der folgenden Optionen.", "You signed in to a new session without verifying it:": "Du hast dich in einer neuen Sitzung angemeldet ohne sie zu verifizieren:", @@ -1732,29 +1732,29 @@ "Upgrade": "Hochstufen", "Verify the new login accessing your account: %(name)s": "Verifiziere die neue Anmeldung an deinem Konto: %(name)s", "From %(deviceName)s (%(deviceId)s)": "Von %(deviceName)s (%(deviceId)s)", - "Your homeserver does not support cross-signing.": "Dein Heimserver unterstützt kein Cross-Signing.", + "Your homeserver does not support cross-signing.": "Dein Heimserver unterstützt keine Quersignierung.", "Cross-signing and secret storage are enabled.": "Cross-signing und der sichere Speicher wurden eingerichtet.", - "Your account has a cross-signing identity in secret storage, but it is not yet trusted by this session.": "Dein Konto hat eine Cross-Signing-Identität im sicheren Speicher, der von dieser Sitzung jedoch noch nicht vertraut wird.", + "Your account has a cross-signing identity in secret storage, but it is not yet trusted by this session.": "Dein Konto hat eine Quersignaturidentität im sicheren Speicher, der von dieser Sitzung jedoch noch nicht vertraut wird.", "Cross-signing and secret storage are not yet set up.": "Cross-Signing und der sichere Speicher sind noch nicht eingerichtet.", "Reset cross-signing and secret storage": "Cross-Signing und den sicheren Speicher zurücksetzen", "Bootstrap cross-signing and secret storage": "Richte Cross-Signing und den sicheren Speicher ein", "unexpected type": "unbekannter Typ", - "Cross-signing public keys:": "Öffentliche Cross-Signing-Schlüssel:", + "Cross-signing public keys:": "Öffentlicher Quersignaturschlüssel:", "in memory": "im Speicher", - "Cross-signing private keys:": "Private Cross-Signing-Schlüssel:", + "Cross-signing private keys:": "Private Quersignaturschlüssel:", "in secret storage": "im Schlüsselspeicher", "Self signing private key:": "Selbst signierter privater Schlüssel:", "cached locally": "lokal zwischengespeichert", "not found locally": "lokal nicht gefunden", - "User signing private key:": "Privater Benutzer-Schlüssel:", + "User signing private key:": "Privater Benutzerschlüssel:", "Session backup key:": "Sitzungswiederherstellungsschlüssel:", "Secret storage public key:": "Öffentlicher Schlüssel des sicheren Speichers:", "in account data": "in den Kontodaten", - "Homeserver feature support:": "Unterstützte Funktionen des Homeservers:", + "Homeserver feature support:": "Unterstützte Funktionen des Heimservers:", "exists": "existiert", "Delete sessions|other": "Sitzungen löschen", "Delete sessions|one": "Sitzung löschen", - "Individually verify each session used by a user to mark it as trusted, not trusting cross-signed devices.": "Alle Sitzungen einzeln verifizieren, anstatt auch Sitzungen zu vertrauen, die durch Cross-Signing verifiziert sind.", + "Individually verify each session used by a user to mark it as trusted, not trusting cross-signed devices.": "Alle Sitzungen einzeln verifizieren, anstatt auch Sitzungen zu vertrauen, die durch Quersignierungen verifiziert sind.", "Securely cache encrypted messages locally for them to appear in search results, using ": "Der Zwischenspeicher für die lokale Suche in verschlüsselten Nachrichten benötigt ", " to store messages from ": " um Nachrichten von ", "%(brand)s is missing some components required for securely caching encrypted messages locally. If you'd like to experiment with this feature, build a custom %(brand)s Desktop with search components added.": "Um verschlüsselte Nachrichten lokal zu durchsuchen, benötigt %(brand)s weitere Komponenten. Wenn du diese Funktion testen möchtest, kannst du dir deine eigene Version von %(brand)s Desktop mit der integrierten Suchfunktion kompilieren.", @@ -1783,7 +1783,7 @@ "Share": "Teilen", "You have not verified this user.": "Du hast diesen Nutzer nicht verifiziert.", "Everyone in this room is verified": "Alle in diesem Raum sind verifiziert", - "Mod": "Mod", + "Mod": "Moderator", "Invite only": "Nur auf Einladung", "Scroll to most recent messages": "Zur neusten Nachricht springen", "No recent messages by %(user)s found": "Keine neuen Nachrichten von %(user)s gefunden", @@ -1806,7 +1806,7 @@ "Re-join": "Wieder beitreten", "You were banned from %(roomName)s by %(memberName)s": "Du wurdest von %(memberName)s aus %(roomName)s verbannt", "Something went wrong with your invite to %(roomName)s": "Bei deiner Einladung zu %(roomName)s ist ein Fehler aufgetreten", - "An error (%(errcode)s) was returned while trying to validate your invite. You could try to pass this information on to a room admin.": "Während der Verifizierung deiner Einladung ist ein Fehler (%(errcode)s) aufgetreten. Du kannst diese Information einem Raum-Administrator weitergeben.", + "An error (%(errcode)s) was returned while trying to validate your invite. You could try to pass this information on to a room admin.": "Während der Verifizierung deiner Einladung ist ein Fehler (%(errcode)s) aufgetreten. Du kannst diese Information einem Raumadministrator weitergeben.", "You can only join it with a working invite.": "Du kannst nur mit einer gültigen Einladung beitreten.", "Try to join anyway": "Dennoch versuchen beizutreten", "You can still join it because this is a public room.": "Du kannst trotzdem beitreten, weil es ein öffentlicher Raum ist.", @@ -1817,7 +1817,7 @@ "Share this email in Settings to receive invites directly in %(brand)s.": "Teile diese E-Mail-Adresse in den Einstellungen, um Einladungen direkt in %(brand)s zu erhalten.", "%(roomName)s can't be previewed. Do you want to join it?": "Vorschau von %(roomName)s kann nicht angezeigt werden. Möchtest du den Raum betreten?", "This room doesn't exist. Are you sure you're at the right place?": "Dieser Raum existiert nicht. Bist du sicher, dass du hier richtig bist?", - "Try again later, or ask a room admin to check if you have access.": "Versuche es später erneut oder bitte einen Raum-Administrator zu prüfen, ob du berechtigt bist.", + "Try again later, or ask a room admin to check if you have access.": "Versuche es später erneut oder bitte einen Raumadministrator zu prüfen, ob du berechtigt bist.", "%(errcode)s was returned while trying to access the room. If you think you're seeing this message in error, please submit a bug report.": "%(errcode)s wurde beim Versuch den Raum zu betreten, zurückgegeben. Wenn du denkst dass diese Meldung nicht korrekt ist, erstelle bitte einen Fehlerbericht.", "%(count)s unread messages including mentions.|other": "%(count)s ungelesene Nachrichten einschließlich Erwähnungen.", "%(count)s unread messages including mentions.|one": "1 ungelesene Erwähnung.", @@ -1825,7 +1825,7 @@ "%(count)s unread messages.|one": "1 ungelesene Nachricht.", "Unread mentions.": "Ungelesene Erwähnungen.", "Unread messages.": "Ungelesene Nachrichten.", - "This room has already been upgraded.": "Diese Raum wurde bereits aktualisiert.", + "This room has already been upgraded.": "Dieser Raum wurde bereits aktualisiert.", "This room is running room version , which this homeserver has marked as unstable.": "Dieser Raum läuft mit der Raumversion , welche dieser Heimserver als instabil markiert hat.", "Unknown Command": "Unbekannter Befehl", "Unrecognised command: %(commandText)s": "Unbekannter Befehl: %(commandText)s", @@ -1860,7 +1860,7 @@ "%(role)s in %(roomName)s": "%(role)s in %(roomName)s", "This client does not support end-to-end encryption.": "Dieser Client unterstützt keine Ende-zu-Ende-Verschlüsselung.", "Verify by scanning": "Verifizierung durch Scannen eines QR-Codes", - "If you can't scan the code above, verify by comparing unique emoji.": "Wenn du den obigen Code nicht scannen kannst, verifiziere stattdessen durch den Emoji-Vergleich.", + "If you can't scan the code above, verify by comparing unique emoji.": "Wenn du den obigen Code nicht scannen kannst, verifiziere stattdessen durch den Emojivergleich.", "Verify all users in a room to ensure it's secure.": "Verifiziere alle Benutzer in einem Raum um die vollständige Sicherheit zu gewährleisten.", "In encrypted rooms, verify all users to ensure it’s secure.": "Verifiziere alle Benutzer in verschlüsselten Räumen, um die vollständige Sicherheit zu gewährleisten.", "You've successfully verified %(deviceName)s (%(deviceId)s)!": "Du hast %(deviceName)s (%(deviceId)s) erfolgreich verifiziert!", @@ -1890,13 +1890,13 @@ "Message deleted by %(name)s": "Nachricht von %(name)s gelöscht", "Edited at %(date)s. Click to view edits.": "Am %(date)s geändert. Klicke, um Änderungen anzuzeigen.", "Can't load this message": "Diese Nachricht kann nicht geladen werden", - "Submit logs": "Log-Dateien senden", + "Submit logs": "Protokolldateien senden", "Frequently Used": "Oft verwendet", - "Smileys & People": "Smileys & Leute", - "Animals & Nature": "Tiere & Natur", - "Food & Drink": "Essen & Trinken", + "Smileys & People": "Smileys und Leute", + "Animals & Nature": "Tiere und Natur", + "Food & Drink": "Essen und Trinken", "Activities": "Aktivitäten", - "Travel & Places": "Reisen & Orte", + "Travel & Places": "Reisen und Orte", "Objects": "Objekte", "Symbols": "Symbole", "Flags": "Flaggen", @@ -1935,16 +1935,16 @@ "Server name": "Servername", "Add a new server...": "Füge einen Server hinzu...", "%(networkName)s rooms": "%(networkName)s Räume", - "Matrix rooms": "Matrix Räume", + "Matrix rooms": "Matrixräume", "Close dialog": "Dialog schließen", - "Please tell us what went wrong or, better, create a GitHub issue that describes the problem.": "Bitte teile uns mit, was schief lief - oder besser, erstelle ein GitHub-Issue, das das Problem beschreibt.", + "Please tell us what went wrong or, better, create a GitHub issue that describes the problem.": "Bitte teile uns mit, was schief lief - oder besser, beschreibe das Problem auf GitHub in einem \"Issue\".", "Reminder: Your browser is unsupported, so your experience may be unpredictable.": "Warnung: Dein Browser wird nicht unterstützt. Die Anwendung kann instabil sein.", "Notes": "Notizen", "If there is additional context that would help in analysing the issue, such as what you were doing at the time, room IDs, user IDs, etc., please include those things here.": "Wenn du mehr Informationen hast, die uns bei Untersuchung des Problems helfen (z.B. was du gerade getan hast, Raum-IDs, Benutzer-IDs, etc.), gib sie bitte hier an.", "Removing…": "Löschen…", "Destroy cross-signing keys?": "Cross-Signing-Schlüssel zerstören?", "Clear cross-signing keys": "Cross-Signing-Schlüssel löschen", - "Enable end-to-end encryption": "Ende-zu-Ende Verschlüsselung aktivieren", + "Enable end-to-end encryption": "Ende-zu-Ende-Verschlüsselung aktivieren", "You can’t disable this later. Bridges & most bots won’t work yet.": "Du kannst dies später nicht mehr ändern. Bridges und die meisten Bots werden nicht funktionieren.", "Server did not require any authentication": "Der Server benötigt keine Authentifizierung", "Server did not return valid authentication information.": "Der Server lieferte keine gültigen Authentifizierungsinformationen.", @@ -2149,7 +2149,7 @@ "Unable to query secret storage status": "Status des sicheren Speichers kann nicht gelesen werden", "We'll store an encrypted copy of your keys on our server. Secure your backup with a recovery passphrase.": "Wir werden eine verschlüsselte Kopie deiner Schlüssel auf unserem Server speichern. Schütze deine Sicherung mit einer Wiederherstellungspassphrase.", "Without setting up Secure Message Recovery, you won't be able to restore your encrypted message history if you log out or use another session.": "Ohne eine Schlüsselsicherung kann dein verschlüsselter Nachrichtenverlauf nicht wiederhergestellt werden wenn du dich abmeldest oder eine andere Sitzung verwendest.", - "There was an error updating the room's alternative addresses. It may not be allowed by the server or a temporary failure occurred.": "Es gab einen Fehler beim Ändern des Raum-Aliases. Entweder erlaubt es der Server nicht oder es gab ein temporäres Problem.", + "There was an error updating the room's alternative addresses. It may not be allowed by the server or a temporary failure occurred.": "Es gab einen Fehler beim Ändern des Raumaliases. Entweder erlaubt es der Server nicht oder es gab ein temporäres Problem.", "Self-verification request": "Selbstverifikationsanfrage", "or another cross-signing capable Matrix client": "oder einen anderen Matrix Client der Cross-signing fähig ist", "%(brand)s is securely caching encrypted messages locally for them to appear in search results:": "%(brand)s verwendet einen sicheren Zwischenspeicher für verschlüsselte Nachrichten, damit sie in den Suchergebnissen angezeigt werden:", @@ -2185,7 +2185,7 @@ "Click the button below to confirm setting up encryption.": "Klick die Schaltfläche unten um die Einstellungen der Verschlüsselung zu bestätigen.", "Font scaling": "Schriftskalierung", "Font size": "Schriftgröße", - "IRC display name width": "Breite des IRC Anzeigenamens", + "IRC display name width": "Breite des IRC-Anzeigenamens", "Size must be a number": "Schriftgröße muss eine Zahl sein", "Custom font size can only be between %(min)s pt and %(max)s pt": "Eigene Schriftgröße kann nur eine Zahl zwischen %(min)s pt und %(max)s pt sein", "Use between %(min)s pt and %(max)s pt": "Verwende eine Zahl zwischen %(min)s pt und %(max)s pt", @@ -2200,9 +2200,9 @@ "Help us improve %(brand)s": "Hilf uns, %(brand)s zu verbessern", "Send anonymous usage data which helps us improve %(brand)s. This will use a cookie.": "Hilf uns, %(brand)s zu verbessern, indem du anonyme Nutzungsdaten schickst. Dies wird ein Cookie verwenden.", "I want to help": "Ich möchte helfen", - "Your homeserver has exceeded its user limit.": "Dein Heimserver hat das Benutzerlimit erreicht.", + "Your homeserver has exceeded its user limit.": "Dein Heimserver hat das Benutzergrenzwert erreicht.", "Your homeserver has exceeded one of its resource limits.": "Dein Heimserver hat eine seiner Ressourcengrenzen erreicht.", - "Contact your server admin.": "Kontaktiere deine Heimserver-Administration.", + "Contact your server admin.": "Kontaktiere deine Heimserveradministration.", "Ok": "Ok", "Set password": "Setze Passwort", "To return to your account in future you need to set a password": "Um dein Konto zukünftig wieder verwenden zu können, setze ein Passwort", @@ -2225,7 +2225,7 @@ "Address (optional)": "Adresse (optional)", "delete the address.": "lösche die Adresse.", "Use a different passphrase?": "Eine andere Passphrase verwenden?", - "Your server admin has disabled end-to-end encryption by default in private rooms & Direct Messages.": "Deine Server-Administration hat die Ende-zu-Ende-Verschlüsselung für private Räume und Direktnachrichten standardmäßig deaktiviert.", + "Your server admin has disabled end-to-end encryption by default in private rooms & Direct Messages.": "Deine Serveradministration hat die Ende-zu-Ende-Verschlüsselung für private Räume und Direktnachrichten standardmäßig deaktiviert.", "People": "Personen", "There was an error removing that address. It may no longer exist or a temporary error occurred.": "Beim Entfernen dieser Adresse ist ein Fehler aufgetreten. Vielleicht existiert sie nicht mehr oder es kam zu einem temporären Fehler.", "Set a room address to easily share your room with other people.": "Vergebe eine Raum-Adresse, um diesen Raum auf einfache Weise mit anderen Personen teilen zu können.", @@ -2258,12 +2258,12 @@ "Dark": "Dunkel", "Use the improved room list (will refresh to apply changes)": "Verwende die verbesserte Raumliste (lädt die Anwendung neu)", "Use custom size": "Verwende individuelle Größe", - "Hey you. You're the best!": "Hey du. Du bist der Beste!", + "Hey you. You're the best!": "Hey du. Du bist großartig.", "Message layout": "Nachrichtenlayout", "Compact": "Kompakt", "Modern": "Modern", "Use a system font": "Systemschriftart verwenden", - "System font name": "System-Schriftart", + "System font name": "Systemschriftart", "Customise your appearance": "Verändere das Erscheinungsbild", "Appearance Settings only affect this %(brand)s session.": "Einstellungen zum Erscheinungsbild wirken sich nur auf diese Sitzung aus.", "The authenticity of this encrypted message can't be guaranteed on this device.": "Die Echtheit dieser verschlüsselten Nachricht kann auf diesem Gerät nicht garantiert werden.", @@ -2363,7 +2363,7 @@ "We’re excited to announce Riot is now Element!": "Wir freuen uns bekanntzugeben: Riot ist jetzt Element!", "Learn more at element.io/previously-riot": "Erfahre mehr unter element.io/previously-riot", "The person who invited you already left the room.": "Die Person, die dich eingeladen hat, hat den Raum bereits verlassen.", - "The person who invited you already left the room, or their server is offline.": "Die Person, die dich eingeladen hat, hat den Raum bereits verlassen oder ihr Server ist offline.", + "The person who invited you already left the room, or their server is offline.": "Die Person, die dich eingeladen hat, hat den Raum bereits verlassen oder ihr Server ist nicht erreichbar bzw. aus.", "Change notification settings": "Benachrichtigungseinstellungen ändern", "Your server isn't responding to some requests.": "Dein Server antwortet auf einige Anfragen nicht.", "Go to Element": "Zu Element gehen", @@ -2429,7 +2429,7 @@ "Send %(count)s invites|other": "%(count)s Einladungen senden", "There was an error creating your community. The name may be taken or the server is unable to process your request.": "Beim Erstellen deiner Community ist ein Fehler aufgetreten. Entweder ist der Name schon vergeben oder der Server kann die Anfrage nicht verarbeiten.", "Community ID: +:%(domain)s": "Community-ID: +:%(domain)s", - "Explore community rooms": "Entdecke Community Räume", + "Explore community rooms": "Entdecke Communityräume", "You can change this later if needed.": "Falls nötig, kannst du es später noch ändern.", "What's the name of your community or team?": "Welchen Namen hat deine Community oder dein Team?", "Enter name": "Namen eingeben", @@ -2445,8 +2445,8 @@ "Use this when referencing your community to others. The community ID cannot be changed.": "Verwende dies, um deine Community von andere referenzieren zu lassen. Die Community-ID kann später nicht geändert werden.", "Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone.": "Private Räume können nur auf Einladung gefunden und betreten werden. Öffentliche Räume können von jedem gefunden und betreten werden.", "Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone in this community.": "Private Räume können nur auf Einladung gefunden und betreten werden. Öffentliche Räume können von jedem in dieser Community gefunden und betreten werden.", - "You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "Du solltest dies aktivieren, wenn der Raum nur für die Zusammenarbeit mit Benutzern von deinem Homeserver verwendet werden soll. Dies kann später nicht mehr geändert werden.", - "You might disable this if the room will be used for collaborating with external teams who have their own homeserver. This cannot be changed later.": "Du solltest dies deaktivieren, wenn der Raum für die Zusammenarbeit mit Benutzern von anderen Homeserver verwendet werden soll. Dies kann später nicht mehr geändert werden.", + "You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "Du solltest dies aktivieren, wenn der Raum nur für die Zusammenarbeit mit Benutzern von deinem Heimserver verwendet werden soll. Dies kann später nicht mehr geändert werden.", + "You might disable this if the room will be used for collaborating with external teams who have their own homeserver. This cannot be changed later.": "Du solltest dies deaktivieren, wenn der Raum für die Zusammenarbeit mit Benutzern von anderen Heimserver verwendet werden soll. Dies kann später nicht mehr geändert werden.", "Block anyone not part of %(serverName)s from ever joining this room.": "Betreten nur für Nutzer von %(serverName)s erlauben.", "Privacy": "Privatsphäre", "There was an error updating your community. The server is unable to process your request.": "Beim Aktualisieren deiner Community ist ein Fehler aufgetreten. Der Server kann deine Anfrage nicht verarbeiten.", @@ -2478,9 +2478,9 @@ "Group call modified by %(senderName)s": "Gruppenanruf wurde von %(senderName)s verändert", "Group call started by %(senderName)s": "Gruppenanruf von %(senderName)s gestartet", "Group call ended by %(senderName)s": "Gruppenanruf wurde von %(senderName)s beendet", - "Cross-signing is ready for use.": "Cross-Signing ist bereit zur Anwendung.", - "Cross-signing is not set up.": "Cross-Signing wurde nicht eingerichtet.", - "Backup version:": "Backup-Version:", + "Cross-signing is ready for use.": "Quersignaturen sind bereits in Anwendung.", + "Cross-signing is not set up.": "Quersignierung wurde nicht eingerichtet.", + "Backup version:": "Version der Sicherung:", "Algorithm:": "Algorithmus:", "Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Sichere deine Verschlüsselungsschlüssel mit deinen Kontodaten, falls du den Zugriff auf deine Sitzungen verlierst. Deine Schlüssel werden mit einem eindeutigen Wiederherstellungsschlüssel gesichert.", "Backup key stored:": "Sicherungsschlüssel gespeichert:", @@ -2488,15 +2488,15 @@ "Secret storage:": "Sicherer Speicher:", "ready": "bereit", "not ready": "nicht bereit", - "Secure Backup": "Sicheres Backup", + "Secure Backup": "Sichere Aufbewahrungskopie", "End Call": "Anruf beenden", "Remove the group call from the room?": "Konferenzgespräch aus diesem Raum entfernen?", "You don't have permission to remove the call from the room": "Du hast keine Berechtigung um den Konferenzanruf aus dem Raum zu entfernen", "Safeguard against losing access to encrypted messages & data": "Schütze dich vor dem Verlust verschlüsselter Nachrichten und Daten", "not found in storage": "nicht im Speicher gefunden", "Widgets": "Widgets", - "Edit widgets, bridges & bots": "Widgets, Bridges & Bots bearbeiten", - "Add widgets, bridges & bots": "Widgets, Bridges & Bots hinzufügen", + "Edit widgets, bridges & bots": "Widgets, Brücken und Bots bearbeiten", + "Add widgets, bridges & bots": "Widgets, Brücken und Bots hinzufügen", "You can only pin 2 widgets at a time": "Du kannst jeweils nur 2 Widgets anheften", "Minimize widget": "Widget minimieren", "Maximize widget": "Widget maximieren", @@ -2535,12 +2535,12 @@ "Hide Widgets": "Widgets verstecken", "%(senderName)s declined the call.": "%(senderName)s hat den Anruf abgelehnt.", "(an error occurred)": "(ein Fehler ist aufgetreten)", - "(their device couldn't start the camera / microphone)": "(ihr/sein Gerät konnte Kamera oder Mikrophon nicht starten)", + "(their device couldn't start the camera / microphone)": "(Gerät des Gegenübers konnte Kamera oder Mikrofon nicht starten)", "(connection failed)": "(Verbindung fehlgeschlagen)", "🎉 All servers are banned from participating! This room can no longer be used.": "🎉 Alle Server sind von der Teilnahme ausgeschlossen! Dieser Raum kann nicht mehr genutzt werden.", "%(senderDisplayName)s changed the server ACLs for this room.": "%(senderDisplayName)s hat die Server-ACLs für diesen Raum geändert.", "%(senderDisplayName)s set the server ACLs for this room.": "%(senderDisplayName)s hat die Server-ACLs für diesen Raum gesetzt.", - "The call was answered on another device.": "Der Anruf wurde an einem anderen Gerät angenommen.", + "The call was answered on another device.": "Der Anruf wurde auf einem anderen Gerät angenommen.", "Answered Elsewhere": "Anderswo beantwortet", "The call could not be established": "Der Anruf kann nicht getätigt werden", "The other party declined the call.": "Die andere Seite hat den Anruf abgelehnt.", @@ -2552,7 +2552,7 @@ "Report a bug": "Einen Fehler melden", "Add comment": "Kommentar hinzufügen", "Rate %(brand)s": "%(brand)s bewerten", - "Feedback sent": "Feedback gesendet", + "Feedback sent": "Rückmeldung gesendet", "Takes the call in the current room off hold": "Beendet das Halten des Anrufs", "Places the call in the current room on hold": "Den aktuellen Anruf halten", "Uzbekistan": "Usbekistan", @@ -2616,12 +2616,12 @@ "New version of %(brand)s is available": "Neue Version von %(brand)s verfügbar", "You ended the call": "Du hast den Anruf beendet", "%(senderName)s ended the call": "%(senderName)s hat den Anruf beendet", - "Use Command + Enter to send a message": "Benutze Betriebssystemtaste + Enter um eine Nachricht zu senden", + "Use Command + Enter to send a message": "Benutze Betriebssystemtaste + Eingabe um eine Nachricht zu senden", "Use Ctrl + Enter to send a message": "Nachrichten mit Strg + Enter senden", "Call Paused": "Anruf pausiert", "Securely cache encrypted messages locally for them to appear in search results, using %(size)s to store messages from %(rooms)s rooms.|other": "Verschlüsselte Nachrichten sicher lokal zwischenspeichern, um sie in Suchergebnissen finden zu können. Es werden %(size)s benötigt, um die Nachrichten von %(rooms)s Räumen zu speichern.", "Securely cache encrypted messages locally for them to appear in search results, using %(size)s to store messages from %(rooms)s rooms.|one": "Verschlüsselte Nachrichten sicher lokal zwischenspeichern, um sie in Suchergebnissen finden zu können. Es werden %(size)s benötigt, um die Nachrichten vom Raum %(rooms)s zu speichern.", - "Only the two of you are in this conversation, unless either of you invites anyone to join.": "Nur ihr zwei seid in dieser Konversation, außer ihr lädt jemanden neues ein.", + "Only the two of you are in this conversation, unless either of you invites anyone to join.": "Nur ihr zwei seid in dieser Konversation, außer ihr ladet jemanden Neues ein.", "This is the beginning of your direct message history with .": "Dies ist der Beginn deiner Direktnachrichten mit .", "Topic: %(topic)s (edit)": "Thema: %(topic)s (ändern)", "Topic: %(topic)s ": "Thema: %(topic)s ", @@ -2649,7 +2649,7 @@ "Decline All": "Alles ablehnen", "Go to Home View": "Zur Startseite gehen", "Filter rooms and people": "Räume und Personen filtern", - "%(creator)s created this DM.": "%(creator)s hat diese DM erstellt.", + "%(creator)s created this DM.": "%(creator)s hat diese Direktnachricht erstellt.", "Now, let's help you get started": "Nun, lassen Sie uns Ihnen den Einstieg erleichtern", "Welcome %(name)s": "Willkommen %(name)s", "Add a photo so people know it's you.": "Fügen Sie ein Foto hinzu, damit die Leute wissen, dass Sie es sind.", @@ -2659,7 +2659,7 @@ "Enter email address": "E-Mail-Adresse eingeben", "Open the link in the email to continue registration.": "Öffnen Sie den Link in der E-Mail, um mit der Registrierung fortzufahren.", "A confirmation email has been sent to %(emailAddress)s": "Eine Bestätigungs-E-Mail wurde an %(emailAddress)s gesendet", - "Use the + to make a new room or explore existing ones below": "Benutze das + um einen neuen Raum zu erstellen oder darunter um existierende Räume zu suchen", + "Use the + to make a new room or explore existing ones below": "Benutze das + um einen neuen Raum zu erstellen oder um existierende Räume zu entdecken", "Return to call": "Zurück zum Anruf", "Fill Screen": "Bildschirm ausfüllen", "Voice Call": "Sprachanruf", @@ -3023,7 +3023,7 @@ "Access your secure message history and set up secure messaging by entering your Security Key.": "Greife auf deinen sicheren Chatverlauf zu und richte die sichere Nachrichtenübermittlung ein, indem du deinen Sicherheitsschlüssel eingibst.", "If you've forgotten your Security Phrase you can use your Security Key or set up new recovery options": "Wenn du deine Sicherheitsphrase vergessen hast, kannst du deinen Sicherheitsschlüssel nutzen oder neue Wiederherstellungsoptionen einrichten", "Security Key mismatch": "Nicht übereinstimmende Sicherheitsschlüssel", - "Set my room layout for everyone": "Dieses Raum-Layout für alle setzen", + "Set my room layout for everyone": "Diese Raumgestaltung für alle setzen", "%(senderName)s has updated the widget layout": "%(senderName)s hat das Widget-Layout aktualisiert", "Search (must be enabled)": "Suche (muss aktiviert sein)", "Remember this": "Dies merken", @@ -3038,10 +3038,10 @@ "Use app": "App verwenden", "Element Web is experimental on mobile. For a better experience and the latest features, use our free native app.": "Element Web ist auf mobilen Endgeräten experimentell. Für eine bessere Erfahrung und die neuesten Erweiterungen, nutze unsere freie, native App.", "Use app for a better experience": "Nutze die App für eine bessere Erfahrung", - "We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.": "Wir haben deinen Browser gebeten, sich zu merken, bei welchem Homeserver du dich anmeldest, aber dein Browser hat dies leider vergessen. Gehe zur Anmeldeseite und versuche es erneut.", - "Show stickers button": "Sticker-Schaltfläche", - "Your homeserver rejected your log in attempt. This could be due to things just taking too long. Please try again. If this continues, please contact your homeserver administrator.": "Dein Homeserver hat deinen Anmeldeversuch abgelehnt. Vielleicht dauert der Prozess einfach zu lange. Bitte versuche es erneut. Wenn dies öfters passiert, wende dich bitte an deine Homeserver-Administration.", - "Your homeserver was unreachable and was not able to log you in. Please try again. If this continues, please contact your homeserver administrator.": "Dein Homeserver war nicht erreichbar und konnte dich nicht anmelden. Bitte versuche es erneut. Wenn dies öfters passiert, wende dich bitte an deine Homeserver-Administration.", + "We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.": "Wir haben deinen Browser gebeten, sich zu merken, bei welchem Heimserver du dich anmeldest, aber dein Browser hat dies leider vergessen. Gehe zur Anmeldeseite und versuche es erneut.", + "Show stickers button": "Stickerschaltfläche", + "Your homeserver rejected your log in attempt. This could be due to things just taking too long. Please try again. If this continues, please contact your homeserver administrator.": "Dein Heimserver hat deinen Anmeldeversuch abgelehnt. Vielleicht dauert der Prozess einfach zu lange. Bitte versuche es erneut. Wenn dies öfters passiert, wende dich bitte an deine Heimserveradministrator.", + "Your homeserver was unreachable and was not able to log you in. Please try again. If this continues, please contact your homeserver administrator.": "Dein Heimserver war nicht erreichbar und konnte dich nicht anmelden. Bitte versuche es erneut. Wenn dies öfters passiert, wende dich bitte an deine Heimserveradministrator.", "We couldn't log you in": "Wir konnten dich nicht anmelden", "Windows": "Fenster", "Screens": "Bildschirme", @@ -3076,8 +3076,8 @@ "Settable at global": "Global einstellbar", "Setting definition:": "Definition der Einstellung:", "Value in this room": "Wert in diesem Raum", - "Settings Explorer": "Einstellungs-Explorer", - "Values at explicit levels": "Werte für explizite Levels", + "Settings Explorer": "Einstellungsdurchsucher", + "Values at explicit levels": "Werte für explizite Stufen", "Settable at room": "Für den Raum einstellbar", "Room name": "Raumname", "%(count)s members|other": "%(count)s Mitglieder", @@ -3122,7 +3122,7 @@ "Invite members": "Mitglieder einladen", "Add some details to help people recognise it.": "Gib einige Infos über deinen neuen Space an.", "Spaces are new ways to group rooms and people. To join an existing space you'll need an invite.": "Mit Matrix-Spaces kannst du Räume und Personen gruppieren. Um einen existierenden Space zu betreten, musst du eingeladen werden.", - "Spaces prototype. Incompatible with Communities, Communities v2 and Custom Tags. Requires compatible homeserver for some features.": "Spaces Prototyp. Inkompatibel mit Communities, Communities v2 und Custom Tags. Für einige Features wird ein kompatibler Homeserver benötigt.", + "Spaces prototype. Incompatible with Communities, Communities v2 and Custom Tags. Requires compatible homeserver for some features.": "Spaces Prototyp. Inkompatibel mit Communities, Communities v2 und benutzerdefinierte Tags. Für einige Funktionen wird ein kompatibler Heimserver benötigt.", "Invite to this space": "In diesen Space enladen", "Verify this login to access your encrypted messages and prove to others that this login is really you.": "Verifiziere diese Anmeldung um deine Identität zu bestätigen und Zugriff auf verschlüsselte Nachrichten zu erhalten.", "What projects are you working on?": "An welchen Projekten arbeitest du gerade?", @@ -3204,5 +3204,47 @@ "Don't want to add an existing room?": "Willst du keinen existierenden Raum hinzufügen?", "Edit devices": "Sitzungen anzeigen", "Your private space ": "Dein privater Space ", - "Your public space ": "Dein öffentlicher Space " + "Your public space ": "Dein öffentlicher Space ", + "Quick actions": "Schnellaktionen", + "We couldn't create your DM.": "Wir konnten deine Direktnachricht nicht erstellen.", + "Adding...": "Hinzufügen...", + "Add existing rooms": "Bestehende Räume hinzufügen", + "Space selection": "Matrix-Space-Auswahl", + "%(count)s people you know have already joined|one": "%(count)s Person, die du kennst, ist schon beigetreten", + "%(count)s people you know have already joined|other": "%(count)s Leute, die du kennst, sind bereits beigetreten", + "Accept on your other login…": "Akzeptiere in deiner anderen Anmeldung…", + "Stop & send recording": "Stoppen und Aufzeichnung senden", + "Record a voice message": "Eine Sprachnachricht aufnehmen", + "Invite messages are hidden by default. Click to show the message.": "Einladungsnachrichten sind standardmäßig ausgeblendet. Klicken um diese anzuzeigen.", + "Warn before quitting": "Vor Beenden warnen", + "Spell check dictionaries": "Wörterbücher für Rechtschreibprüfung", + "Space options": "Matrix-Space-Optionen", + "Manage & explore rooms": "Räume entdecken und verwalten", + "unknown person": "unbekannte Person", + "Send and receive voice messages (in development)": "Sprachnachrichten senden und empfangen (in der Entwicklung)", + "Check your devices": "Überprüfe dein Gerät", + "%(deviceId)s from %(ip)s": "%(deviceId)s von %(ip)s", + "This homeserver has been blocked by it's administrator.": "Dieser Heimserver wurde von seiner Administration blockiert.", + "You have unverified logins": "Du hast nicht-bestätigte Anmeldungen", + "Review to ensure your account is safe": "Überprüfen, um sicher zu sein, dass dein Konto sicher ist", + "Message search initilisation failed": "Initialisierung der Nachrichtensuche fehlgeschlagen", + "Support": "Unterstützen", + "This room is suggested as a good one to join": "Dieser Raum wurde als gut zum Beitreten vorgeschlagen", + "Your message wasn't sent because this homeserver has been blocked by it's administrator. Please contact your service administrator to continue using the service.": "Deine Nachricht wurde nicht versendet, weil dieser Heimserver von dessen Administrator gesperrt wurde. Bitte kontaktiere deinen Dienstadministrator um den Dienst weiterzunutzen.", + "Verification requested": "Verifizierung angefragt", + "Avatar": "Avatar", + "Verify other login": "Andere Anmeldung verifizieren", + "Invited people will be able to read old messages.": "Eingeladene Leute werden ältere Nachrichten lesen können.", + "Sends the given message as a spoiler": "Die gegebene Nachricht als Spoiler senden", + "Values at explicit levels in this room:": "Werte für explizite Stufen in diesem Raum:", + "Values at explicit levels:": "Werte für explizite Stufen:", + "Values at explicit levels in this room": "Werte für explizite Stufen in diesem Raum", + "Confirm abort of host creation": "Bestätige das Abbrechen der Host-Erstellung", + "Are you sure you wish to abort creation of the host? The process cannot be continued.": "Soll die Host-Erstellung wirklich abgebrochen werden? Dieser Prozess kann nicht wieder fortgesetzt werden.", + "Invite to just this room": "Nur für diesen Raum einladen", + "Consult first": "Konsultiere zuerst", + "Reset event store?": "Ereigniss-Speicher zurück setzen?", + "You most likely do not want to reset your event index store": "Es ist wahrscheinlich, dass du den Ereigniss-Index-Speicher nicht zurück setzen möchtest", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Falls du dies tust, werden keine deiner Nachrichten gelöscht. Allerdings wird die Such-Funktion eine Weile lang schlecht funktionieren, bis der Index wieder hergestellt ist", + "Reset event store": "Ereignis-Speicher zurück setzen" } diff --git a/src/i18n/strings/en_EN.json b/src/i18n/strings/en_EN.json index d5f3a3cf88..e4d8c797ac 100644 --- a/src/i18n/strings/en_EN.json +++ b/src/i18n/strings/en_EN.json @@ -658,7 +658,6 @@ "No homeserver URL provided": "No homeserver URL provided", "Unexpected error resolving homeserver configuration": "Unexpected error resolving homeserver configuration", "Unexpected error resolving identity server configuration": "Unexpected error resolving identity server configuration", - "The message you are trying to send is too large.": "The message you are trying to send is too large.", "This homeserver has hit its Monthly Active User limit.": "This homeserver has hit its Monthly Active User limit.", "This homeserver has been blocked by its administrator.": "This homeserver has been blocked by its administrator.", "This homeserver has exceeded one of its resource limits.": "This homeserver has exceeded one of its resource limits.", @@ -900,6 +899,8 @@ "Incoming call": "Incoming call", "Decline": "Decline", "Accept": "Accept", + "Pause": "Pause", + "Play": "Play", "The other party cancelled the verification.": "The other party cancelled the verification.", "Verified!": "Verified!", "You've successfully verified this user.": "You've successfully verified this user.", @@ -1306,6 +1307,7 @@ "Cryptography": "Cryptography", "Session ID:": "Session ID:", "Session key:": "Session key:", + "You have no ignored users.": "You have no ignored users.", "Bulk options": "Bulk options", "Accept all %(invitedRooms)s invites": "Accept all %(invitedRooms)s invites", "Reject all %(invitedRooms)s invites": "Reject all %(invitedRooms)s invites", @@ -1453,6 +1455,7 @@ "Sending your message...": "Sending your message...", "Encrypting your message...": "Encrypting your message...", "Your message was sent": "Your message was sent", + "Failed to send": "Failed to send", "Please select the destination room for this message": "Please select the destination room for this message", "Scroll to most recent messages": "Scroll to most recent messages", "Close preview": "Close preview", @@ -1474,6 +1477,7 @@ "The conversation continues here.": "The conversation continues here.", "This room has been replaced and is no longer active.": "This room has been replaced and is no longer active.", "You do not have permission to post to this room": "You do not have permission to post to this room", + "%(seconds)ss left": "%(seconds)ss left", "Bold": "Bold", "Italics": "Italics", "Strikethrough": "Strikethrough", @@ -1551,6 +1555,8 @@ "Explore all public rooms": "Explore all public rooms", "Quick actions": "Quick actions", "Use the + to make a new room or explore existing ones below": "Use the + to make a new room or explore existing ones below", + "%(count)s results in all spaces|other": "%(count)s results in all spaces", + "%(count)s results in all spaces|one": "%(count)s result in all spaces", "%(count)s results|other": "%(count)s results", "%(count)s results|one": "%(count)s result", "This room": "This room", @@ -1647,7 +1653,8 @@ "Jump to first unread message.": "Jump to first unread message.", "Mark all as read": "Mark all as read", "Record a voice message": "Record a voice message", - "Stop & send recording": "Stop & send recording", + "Stop the recording": "Stop the recording", + "Delete recording": "Delete recording", "Error updating main address": "Error updating main address", "There was an error updating the room's main address. It may not be allowed by the server or a temporary failure occurred.": "There was an error updating the room's main address. It may not be allowed by the server or a temporary failure occurred.", "There was an error updating the room's alternative addresses. It may not be allowed by the server or a temporary failure occurred.": "There was an error updating the room's alternative addresses. It may not be allowed by the server or a temporary failure occurred.", @@ -1813,8 +1820,9 @@ "The encryption used by this room isn't supported.": "The encryption used by this room isn't supported.", "Error decrypting audio": "Error decrypting audio", "React": "React", - "Reply": "Reply", "Edit": "Edit", + "Retry": "Retry", + "Reply": "Reply", "Message Actions": "Message Actions", "Attachment": "Attachment", "Error decrypting attachment": "Error decrypting attachment", @@ -1918,11 +1926,17 @@ "Please create a new issue on GitHub so that we can investigate this bug.": "Please create a new issue on GitHub so that we can investigate this bug.", "collapse": "collapse", "expand": "expand", + "View all %(count)s members|other": "View all %(count)s members", + "View all %(count)s members|one": "View 1 member", + "Including %(commaSeparatedMembers)s": "Including %(commaSeparatedMembers)s", + "%(count)s members including %(commaSeparatedMembers)s|other": "%(count)s members including %(commaSeparatedMembers)s", + "%(count)s members including %(commaSeparatedMembers)s|one": "%(commaSeparatedMembers)s", "%(count)s people you know have already joined|other": "%(count)s people you know have already joined", - "Rotate Right": "Rotate Right", - "Rotate Left": "Rotate Left", + "%(count)s people you know have already joined|one": "%(count)s person you know has already joined", "Zoom out": "Zoom out", "Zoom in": "Zoom in", + "Rotate Right": "Rotate Right", + "Rotate Left": "Rotate Left", "Download": "Download", "Information": "Information", "View message": "View message", @@ -2012,10 +2026,11 @@ "Add a new server...": "Add a new server...", "%(networkName)s rooms": "%(networkName)s rooms", "Matrix rooms": "Matrix rooms", - "Space selection": "Space selection", - "Add existing rooms": "Add existing rooms", "Filter your rooms and spaces": "Filter your rooms and spaces", "Spaces": "Spaces", + "Direct Messages": "Direct Messages", + "Space selection": "Space selection", + "Add existing rooms": "Add existing rooms", "Don't want to add an existing room?": "Don't want to add an existing room?", "Create a new room": "Create a new room", "Failed to add rooms to space": "Failed to add rooms to space", @@ -2206,7 +2221,6 @@ "Suggestions": "Suggestions", "May include members not in %(communityName)s": "May include members not in %(communityName)s", "Recently Direct Messaged": "Recently Direct Messaged", - "Direct Messages": "Direct Messages", "Start a conversation with someone using their name, email address or username (like ).": "Start a conversation with someone using their name, email address or username (like ).", "Start a conversation with someone using their name or username (like ).": "Start a conversation with someone using their name or username (like ).", "This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click here": "This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click here", @@ -2312,7 +2326,7 @@ "About homeservers": "About homeservers", "Reset event store?": "Reset event store?", "You most likely do not want to reset your event index store": "You most likely do not want to reset your event index store", - "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few moments whilst the index is recreated": "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few moments whilst the index is recreated", "Reset event store": "Reset event store", "Sign out and remove encryption keys?": "Sign out and remove encryption keys?", "Clear Storage and Sign Out": "Clear Storage and Sign Out", @@ -2393,7 +2407,6 @@ "Confirm encryption setup": "Confirm encryption setup", "Click the button below to confirm setting up encryption.": "Click the button below to confirm setting up encryption.", "Unable to set up keys": "Unable to set up keys", - "Retry": "Retry", "Restoring keys from backup": "Restoring keys from backup", "Fetching keys from server...": "Fetching keys from server...", "%(completed)s of %(total)s keys restored": "%(completed)s of %(total)s keys restored", @@ -2422,10 +2435,7 @@ "Reject invitation": "Reject invitation", "Are you sure you want to reject the invitation?": "Are you sure you want to reject the invitation?", "Unable to reject invite": "Unable to reject invite", - "Resend edit": "Resend edit", "Resend %(unsentCount)s reaction(s)": "Resend %(unsentCount)s reaction(s)", - "Resend removal": "Resend removal", - "Cancel Sending": "Cancel Sending", "Forward Message": "Forward Message", "Pin Message": "Pin Message", "Unhide Preview": "Unhide Preview", @@ -2558,6 +2568,7 @@ "Failed to reject invitation": "Failed to reject invitation", "Cannot create rooms in this community": "Cannot create rooms in this community", "You do not have permission to create rooms in this community.": "You do not have permission to create rooms in this community.", + "You are the only person here. If you leave, no one will be able to join in the future, including you.": "You are the only person here. If you leave, no one will be able to join in the future, including you.", "This space is not public. You will not be able to rejoin without an invite.": "This space is not public. You will not be able to rejoin without an invite.", "This room is not public. You will not be able to rejoin without an invite.": "This room is not public. You will not be able to rejoin without an invite.", "Are you sure you want to leave the space '%(spaceName)s'?": "Are you sure you want to leave the space '%(spaceName)s'?", @@ -2606,16 +2617,18 @@ "If you can't find the room you're looking for, ask for an invite or Create a new room.": "If you can't find the room you're looking for, ask for an invite or Create a new room.", "Explore rooms in %(communityName)s": "Explore rooms in %(communityName)s", "Filter": "Filter", + "Filter all spaces": "Filter all spaces", "Clear filter": "Clear filter", "Filter rooms and people": "Filter rooms and people", "You can't send any messages until you review and agree to our terms and conditions.": "You can't send any messages until you review and agree to our terms and conditions.", "Your message wasn't sent because this homeserver has hit its Monthly Active User Limit. Please contact your service administrator to continue using the service.": "Your message wasn't sent because this homeserver has hit its Monthly Active User Limit. Please contact your service administrator to continue using the service.", "Your message wasn't sent because this homeserver has been blocked by it's administrator. Please contact your service administrator to continue using the service.": "Your message wasn't sent because this homeserver has been blocked by it's administrator. Please contact your service administrator to continue using the service.", "Your message wasn't sent because this homeserver has exceeded a resource limit. Please contact your service administrator to continue using the service.": "Your message wasn't sent because this homeserver has exceeded a resource limit. Please contact your service administrator to continue using the service.", - "%(count)s of your messages have not been sent.|other": "Some of your messages have not been sent.", - "%(count)s of your messages have not been sent.|one": "Your message was not sent.", - "%(count)s Resend all or cancel all now. You can also select individual messages to resend or cancel.|other": "Resend all or cancel all now. You can also select individual messages to resend or cancel.", - "%(count)s Resend all or cancel all now. You can also select individual messages to resend or cancel.|one": "Resend message or cancel message now.", + "Some of your messages have not been sent": "Some of your messages have not been sent", + "Delete all": "Delete all", + "Retry all": "Retry all", + "Sending": "Sending", + "You can select all or individual messages to retry or delete": "You can select all or individual messages to retry or delete", "Connectivity to the server has been lost.": "Connectivity to the server has been lost.", "Sent messages will be stored until your connection has returned.": "Sent messages will be stored until your connection has returned.", "You seem to be uploading files, are you sure you want to quit?": "You seem to be uploading files, are you sure you want to quit?", @@ -2635,6 +2648,7 @@ "%(count)s rooms|one": "%(count)s room", "This room is suggested as a good one to join": "This room is suggested as a good one to join", "Suggested": "Suggested", + "Your server does not support showing space hierarchies.": "Your server does not support showing space hierarchies.", "%(count)s rooms and %(numSpaces)s spaces|other": "%(count)s rooms and %(numSpaces)s spaces", "%(count)s rooms and %(numSpaces)s spaces|one": "%(count)s room and %(numSpaces)s spaces", "%(count)s rooms and 1 space|other": "%(count)s rooms and 1 space", @@ -2645,7 +2659,6 @@ "Mark as suggested": "Mark as suggested", "No results found": "No results found", "You may want to try a different search or check for typos.": "You may want to try a different search or check for typos.", - "Your server does not support showing space hierarchies.": "Your server does not support showing space hierarchies.", "Search names and description": "Search names and description", "If you can't find the room you're looking for, ask for an invite or create a new room.": "If you can't find the room you're looking for, ask for an invite or create a new room.", "Create room": "Create room", @@ -2660,6 +2673,8 @@ "Failed to create initial space rooms": "Failed to create initial space rooms", "Skip for now": "Skip for now", "Creating rooms...": "Creating rooms...", + "What do you want to organise?": "What do you want to organise?", + "Pick rooms or conversations to add. This is just a space for you, no one will be informed. You can add more later.": "Pick rooms or conversations to add. This is just a space for you, no one will be informed. You can add more later.", "Share %(name)s": "Share %(name)s", "It's just you at the moment, it will be even better with others.": "It's just you at the moment, it will be even better with others.", "Go to my first room": "Go to my first room", diff --git a/src/i18n/strings/en_US.json b/src/i18n/strings/en_US.json index a1275fb089..003da7ef8f 100644 --- a/src/i18n/strings/en_US.json +++ b/src/i18n/strings/en_US.json @@ -650,5 +650,12 @@ "Error upgrading room": "Error upgrading room", "Double check that your server supports the room version chosen and try again.": "Double check that your server supports the room version chosen and try again.", "Changes the avatar of the current room": "Changes the avatar of the current room", - "Changes your avatar in all rooms": "Changes your avatar in all rooms" + "Changes your avatar in all rooms": "Changes your avatar in all rooms", + "Favourited": "Favorited", + "Explore rooms": "Explore rooms", + "Click the button below to confirm adding this email address.": "Click the button below to confirm adding this email address.", + "Confirm adding email": "Confirm adding email", + "Single Sign On": "Single Sign On", + "Confirm adding this email address by using Single Sign On to prove your identity.": "Confirm adding this email address by using Single Sign On to prove your identity.", + "Use Single Sign On to continue": "Use Single Sign On to continue" } diff --git a/src/i18n/strings/es.json b/src/i18n/strings/es.json index c6e84570d6..d396cc318f 100644 --- a/src/i18n/strings/es.json +++ b/src/i18n/strings/es.json @@ -3188,5 +3188,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "De %(deviceName)s (%(deviceId)s) en", "Check your devices": "Comprueba tus dispositivos", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Alguien está iniciando sesión a tu cuenta: %(name)s (%(deviceID)s) en %(ip)s", - "You have unverified logins": "Tienes inicios de sesión sin verificar" + "You have unverified logins": "Tienes inicios de sesión sin verificar", + "Verification requested": "Verificación solicitada", + "Avatar": "Imagen de perfil", + "Verify other login": "Verificar otro inicio de sesión", + "Consult first": "Consultar primero", + "Invited people will be able to read old messages.": "Las personas invitadas podrán leer mensajes antiguos.", + "We couldn't create your DM.": "No hemos podido crear tu mensaje directo.", + "Adding...": "Añadiendo...", + "Add existing rooms": "Añadir salas existentes", + "%(count)s people you know have already joined|one": "%(count)s persona que ya conoces se ha unido", + "%(count)s people you know have already joined|other": "%(count)s personas que ya conoces se han unido", + "Accept on your other login…": "Acepta en tu otro inicio de sesión…", + "Stop & send recording": "Parar y enviar grabación", + "Record a voice message": "Grabar un mensaje de voz", + "Quick actions": "Acciones rápidas", + "Invite to just this room": "Invitar solo a esta sala", + "Warn before quitting": "Avisar antes de salir", + "Manage & explore rooms": "Gestionar y explorar salas", + "unknown person": "persona desconocida", + "Share decryption keys for room history when inviting users": "Compartir claves para descifrar el historial de la sala al invitar a gente", + "Send and receive voice messages (in development)": "Enviar y recibir mensajes de voz (en desarrollo)", + "%(deviceId)s from %(ip)s": "%(deviceId)s desde %(ip)s", + "Review to ensure your account is safe": "Revisa que tu cuenta esté segura", + "Sends the given message as a spoiler": "Envía el mensaje como un spoiler", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Consultando a %(transferTarget)s. Transferir a %(transferee)s", + "Message search initilisation failed": "Ha fallado la inicialización de la búsqueda de mensajes", + "Reset event store?": "¿Restablecer almacenamiento de eventos?", + "You most likely do not want to reset your event index store": "Lo más probable es que no quieras restablecer tu almacenamiento de índice de ecentos", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Si lo haces, ten en cuenta que no se borrarán tus mensajes, pero la experiencia de búsqueda será peor durante unos momentos mientras se recrea el índice", + "Reset event store": "Restablecer el almacenamiento de eventos", + "What are some things you want to discuss in %(spaceName)s?": "¿De qué quieres hablar en %(spaceName)s?", + "Let's create a room for each of them.": "Crearemos una sala para cada uno.", + "You can add more later too, including already existing ones.": "Puedes añadir más después, incluso si ya existen.", + "Please choose a strong password": "Por favor, elige una contraseña segura", + "Use another login": "Usar otro inicio de sesión", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifica tu identidad para acceder a mensajes cifrados y probar tu identidad a otros.", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Si no verificas no tendrás acceso a todos tus mensajes y puede que aparezcas como no confiable para otros usuarios.", + "Invite messages are hidden by default. Click to show the message.": "Los mensajes de invitación no se muestran por defecto. Haz clic para mostrarlo." } diff --git a/src/i18n/strings/et.json b/src/i18n/strings/et.json index 85f8cbb751..444475deea 100644 --- a/src/i18n/strings/et.json +++ b/src/i18n/strings/et.json @@ -2517,7 +2517,7 @@ "Join the conference from the room information card on the right": "Liitu konverentsiga selle jututoa infolehelt paremal", "Video conference ended by %(senderName)s": "%(senderName)s lõpetas video rühmakõne", "Video conference updated by %(senderName)s": "%(senderName)s uuendas video rühmakõne", - "Video conference started by %(senderName)s": "%(senderName)s alustas video rühmakõne", + "Video conference started by %(senderName)s": "%(senderName)s alustas video rühmakõnet", "End conference": "Lõpeta videokonverents", "This will end the conference for everyone. Continue?": "Sellega lõpetame kõikide osalejate jaoks videokonverentsi. Nõus?", "Ignored attempt to disable encryption": "Eirasin katset lõpetada krüptimise kasutamine", @@ -3226,5 +3226,42 @@ "Open": "Ava", "Check your devices": "Kontrolli oma seadmeid", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Uus sisselogimissessioon kasutab sinu Matrixi kontot: %(name)s %(deviceID)s aadressil %(ip)s", - "You have unverified logins": "Sul on verifitseerimata sisselogimissessioone" + "You have unverified logins": "Sul on verifitseerimata sisselogimissessioone", + "Manage & explore rooms": "Halda ja uuri jututubasid", + "Warn before quitting": "Hoiata enne rakenduse töö lõpetamist", + "Invite to just this room": "Kutsi vaid siia jututuppa", + "Quick actions": "Kiirtoimingud", + "Adding...": "Lisan...", + "Sends the given message as a spoiler": "Saadab selle sõnumi rõõmurikkujana", + "unknown person": "tundmatu isik", + "Send and receive voice messages (in development)": "Saada ja võta vastu häälsõnumeid (arendusjärgus)", + "%(deviceId)s from %(ip)s": "%(deviceId)s ip-aadressil %(ip)s", + "Review to ensure your account is safe": "Tagamaks, et su konto on sinu kontrolli all, vaata andmed üle", + "Share decryption keys for room history when inviting users": "Kasutajate kutsumisel jaga jututoa ajaloo võtmeid", + "Record a voice message": "Salvesta häälsõnum", + "Stop & send recording": "Lõpeta salvestamine ja saada häälsõnum", + "Add existing rooms": "Lisa olemasolevaid jututubasid", + "%(count)s people you know have already joined|other": "%(count)s sulle tuttavat kasutajat on juba liitunud", + "We couldn't create your DM.": "Otsesuhtluse loomine ei õnnestunud.", + "Invited people will be able to read old messages.": "Kutse saanud kasutajad saavad lugeda vanu sõnumeid.", + "Consult first": "Pea esmalt nõu", + "Reset event store?": "Kas lähtestame sündmuste andmekogu?", + "Reset event store": "Lähtesta sündmuste andmekogu", + "Verify other login": "Verifitseeri muu sisselogimissessioon", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Suhtlen teise osapoolega %(transferTarget)s. Saadan andmeid kasutajale %(transferee)s", + "Message search initilisation failed": "Sõnumite otsingu alustamine ei õnnestunud", + "Invite messages are hidden by default. Click to show the message.": "Kutsed on vaikimisi peidetud. Sõnumi nägemiseks klõpsi.", + "Accept on your other login…": "Nõustu oma teise sisselogimissessiooniga…", + "Avatar": "Tunnuspilt", + "Verification requested": "Verifitseerimistaotlus on saadetud", + "%(count)s people you know have already joined|one": "%(count)s sulle tuttav kasutaja on juba liitunud", + "You most likely do not want to reset your event index store": "Pigem sa siiski ei taha lähtestada sündmuste andmekogu ja selle indeksit", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Kui sa siiski soovid seda teha, siis sinu sõnumeid me ei kustuta, aga seniks kuni sõnumite indeks taustal uuesti luuakse, toimib otsing aeglaselt ja ebatõhusalt", + "You can add more later too, including already existing ones.": "Sa võid ka hiljem siia luua uusi jututubasid või lisada olemasolevaid.", + "What are some things you want to discuss in %(spaceName)s?": "Mida sa sooviksid arutada %(spaceName)s kogukonnakeskuses?", + "Please choose a strong password": "Palun tee üks korralik salasõna", + "Use another login": "Pruugi muud kasutajakontot", + "Verify your identity to access encrypted messages and prove your identity to others.": "Tagamaks ligipääsu oma krüptitud sõnumitele ja tõestamaks oma isikut teistele kasutajatale, verifitseeri end.", + "Let's create a room for each of them.": "Teeme siis iga teema jaoks oma jututoa.", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Ilma verifitseerimiseta sul puudub ligipääs kõikidele oma sõnumitele ning teised ei näe sinu kasutajakontot usaldusväärsena." } diff --git a/src/i18n/strings/fa.json b/src/i18n/strings/fa.json index 738f48733c..d036a55c23 100644 --- a/src/i18n/strings/fa.json +++ b/src/i18n/strings/fa.json @@ -311,5 +311,8 @@ "Your device resolution": "وضوح دستگاه شما", "e.g. ": "برای مثال ", "Every page you use in the app": "هر صفحه‌ی برنامه از که آن استفاده می‌کنید", - "e.g. %(exampleValue)s": "برای مثال %(exampleValue)s" + "e.g. %(exampleValue)s": "برای مثال %(exampleValue)s", + "Explore rooms": "کاوش اتاق", + "Sign In": "ورود", + "Create Account": "ایجاد اکانت" } diff --git a/src/i18n/strings/fr.json b/src/i18n/strings/fr.json index 01390329bb..fcc5ec9afe 100644 --- a/src/i18n/strings/fr.json +++ b/src/i18n/strings/fr.json @@ -3225,5 +3225,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Sur %(deviceName)s %(deviceId)s depuis %(ip)s", "Check your devices": "Vérifiez vos appareils", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Une nouvelle session a accès à votre compte : %(name)s %(deviceID)s depuis %(ip)s", - "You have unverified logins": "Vous avez des sessions non-vérifiées" + "You have unverified logins": "Vous avez des sessions non-vérifiées", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Sans vérification vous n’aurez pas accès à tous vos messages et n’apparaîtrez pas comme de confiance aux autres.", + "Verify your identity to access encrypted messages and prove your identity to others.": "Vérifiez votre identité pour accéder aux messages chiffrés et prouver votre identité aux autres.", + "Use another login": "Utiliser un autre identifiant", + "Please choose a strong password": "Merci de choisir un mot de passe fort", + "You can add more later too, including already existing ones.": "Vous pourrez en ajouter plus tard, y compris certains déjà existant.", + "Let's create a room for each of them.": "Créons un salon pour chacun d’entre eux.", + "What are some things you want to discuss in %(spaceName)s?": "De quoi voulez vous discuter dans %(spaceName)s ?", + "Verification requested": "Vérification requise", + "Avatar": "Avatar", + "Verify other login": "Vérifier l’autre connexion", + "Reset event store": "Réinitialiser le magasin d’événements", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Si vous le faites, notes qu’aucun de vos messages ne sera supprimé, mais la recherche pourrait être dégradée pendant quelques instants, le temps de recréer l’index", + "You most likely do not want to reset your event index store": "Il est probable que vous ne vouliez pas réinitialiser votre magasin d’index d’événements", + "Reset event store?": "Réinitialiser le magasin d’événements ?", + "Consult first": "Consulter d’abord", + "Invited people will be able to read old messages.": "Les personnes invitées pourront lire les anciens messages.", + "We couldn't create your DM.": "Nous n’avons pas pu créer votre message direct.", + "Adding...": "Ajout…", + "Add existing rooms": "Ajouter des salons existants", + "%(count)s people you know have already joined|one": "%(count)s personne que vous connaissez en fait déjà partie", + "%(count)s people you know have already joined|other": "%(count)s personnes que vous connaissez en font déjà partie", + "Accept on your other login…": "Acceptez sur votre autre connexion…", + "Stop & send recording": "Terminer et envoyer l’enregistrement", + "Record a voice message": "Enregistrer un message vocal", + "Invite messages are hidden by default. Click to show the message.": "Les messages d’invitation sont masqués par défaut. Cliquez pour voir le message.", + "Quick actions": "Actions rapides", + "Invite to just this room": "Inviter seulement dans ce salon", + "Warn before quitting": "Avertir avant de quitter", + "Message search initilisation failed": "Échec de l’initialisation de la recherche de message", + "Manage & explore rooms": "Gérer et découvrir les salons", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Consultation avec %(transferTarget)s. Transfert à %(transferee)s", + "unknown person": "personne inconnue", + "Share decryption keys for room history when inviting users": "Partager les clés de déchiffrement lors de l’invitation d’utilisateurs", + "Send and receive voice messages (in development)": "Envoyez et recevez des messages vocaux (en développement)", + "%(deviceId)s from %(ip)s": "%(deviceId)s depuis %(ip)s", + "Review to ensure your account is safe": "Vérifiez pour assurer la sécurité de votre compte", + "Sends the given message as a spoiler": "Envoie le message flouté" } diff --git a/src/i18n/strings/gl.json b/src/i18n/strings/gl.json index 026207030e..f6ebce684f 100644 --- a/src/i18n/strings/gl.json +++ b/src/i18n/strings/gl.json @@ -3248,5 +3248,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Desde %(deviceName)s%(deviceId)s en %(ip)s", "Check your devices": "Comproba os teus dispositivos", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Hai unha nova conexión á túa conta: %(name)s %(deviceID)s desde %(ip)s", - "You have unverified logins": "Tes conexións sen verificar" + "You have unverified logins": "Tes conexións sen verificar", + "Sends the given message as a spoiler": "Envía a mensaxe dada como un spoiler", + "Review to ensure your account is safe": "Revisa para asegurarte de que a túa conta está protexida", + "Share decryption keys for room history when inviting users": "Comparte chaves de descifrado para o historial da sala ao convidar usuarias", + "Warn before quitting": "Aviso antes de saír", + "Invite to just this room": "Convida só a esta sala", + "Stop & send recording": "Deter e enviar e a gravación", + "We couldn't create your DM.": "Non puidemos crear o teu MD.", + "Invited people will be able to read old messages.": "As persoas convidadas poderán ler as mensaxes antigas.", + "Reset event store?": "Restablecer almacenaxe do evento?", + "You most likely do not want to reset your event index store": "Probablemente non queiras restablecer o índice de almacenaxe do evento", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Se o fas, ten en conta que ningunha das mensaxes será eliminada, pero a experiencia de busca podería degradarse durante o tempo en que o índice volve a crearse", + "Avatar": "Avatar", + "Please choose a strong password": "Escolle un contrasinal forte", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifica a túa identidade para acceder a mensaxes cifradas e acreditar a túa identidade ante outras.", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Sen verificación, non terás acceso a tódalas túas mensaxes e poderías aparecer antes outras como non confiable.", + "%(deviceId)s from %(ip)s": "%(deviceId)s desde %(ip)s", + "Send and receive voice messages (in development)": "Enviar e recibir mensaxes de voz (en desenvolvemento)", + "unknown person": "persoa descoñecida", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Consultando con %(transferTarget)s. Transferir a %(transferee)s", + "Manage & explore rooms": "Xestionar e explorar salas", + "Message search initilisation failed": "Fallo a inicialización da busca de mensaxes", + "Quick actions": "Accións rápidas", + "Invite messages are hidden by default. Click to show the message.": "As mensaxes de convite están agochadas por defecto. Preme para amosar a mensaxe.", + "Record a voice message": "Gravar mensaxe de voz", + "Accept on your other login…": "Acepta na túa outra sesión…", + "%(count)s people you know have already joined|other": "%(count)s persoas que coñeces xa se uniron", + "%(count)s people you know have already joined|one": "%(count)s persoa que coñeces xa se uniu", + "Add existing rooms": "Engadir salas existentes", + "Adding...": "Engadindo...", + "Consult first": "Preguntar primeiro", + "Reset event store": "Restablecer almacenaxe de eventos", + "Verify other login": "Verificar outra conexión", + "Verification requested": "Verificación solicitada", + "What are some things you want to discuss in %(spaceName)s?": "Sobre que temas queres conversar en %(spaceName)s?", + "Let's create a room for each of them.": "Crea unha sala para cada un deles.", + "You can add more later too, including already existing ones.": "Podes engadir máis posteriormente, incluíndo os xa existentes.", + "Use another login": "Usar outra conexión" } diff --git a/src/i18n/strings/he.json b/src/i18n/strings/he.json index dda9902e72..5baa1d7c67 100644 --- a/src/i18n/strings/he.json +++ b/src/i18n/strings/he.json @@ -52,7 +52,7 @@ "Operation failed": "פעולה נכשלה", "Search": "חפש", "Custom Server Options": "הגדרות שרת מותאמות אישית", - "Dismiss": "שחרר", + "Dismiss": "התעלם", "powered by Matrix": "מופעל ע\"י Matrix", "Error": "שגיאה", "Remove": "הסר", diff --git a/src/i18n/strings/hi.json b/src/i18n/strings/hi.json index 75b14cca18..f71c024342 100644 --- a/src/i18n/strings/hi.json +++ b/src/i18n/strings/hi.json @@ -585,5 +585,8 @@ "You cannot modify widgets in this room.": "आप इस रूम में विजेट्स को संशोधित नहीं कर सकते।", "%(senderName)s revoked the invitation for %(targetDisplayName)s to join the room.": "%(senderName)s ने कमरे में शामिल होने के लिए %(targetDisplayName)s के निमंत्रण को रद्द कर दिया।", "User %(userId)s is already in the room": "उपयोगकर्ता %(userId)s पहले से ही रूम में है", - "The user must be unbanned before they can be invited.": "उपयोगकर्ता को आमंत्रित करने से पहले उन्हें प्रतिबंधित किया जाना चाहिए।" + "The user must be unbanned before they can be invited.": "उपयोगकर्ता को आमंत्रित करने से पहले उन्हें प्रतिबंधित किया जाना चाहिए।", + "Explore rooms": "रूम का अन्वेषण करें", + "Sign In": "साइन करना", + "Create Account": "खाता बनाएं" } diff --git a/src/i18n/strings/hr.json b/src/i18n/strings/hr.json index 527b86e0a7..2511771578 100644 --- a/src/i18n/strings/hr.json +++ b/src/i18n/strings/hr.json @@ -4,5 +4,6 @@ "Failed to verify email address: make sure you clicked the link in the email": "Nismo u mogućnosti verificirati Vašu email adresu. Provjerite dali ste kliknuli link u mailu", "The platform you're on": "Platforma na kojoj se nalazite", "The version of %(brand)s": "Verzija %(brand)s", - "Your language of choice": "Izabrani jezik" + "Your language of choice": "Izabrani jezik", + "Dismiss": "Odbaci" } diff --git a/src/i18n/strings/hu.json b/src/i18n/strings/hu.json index eaa77e809d..2ec5af8a17 100644 --- a/src/i18n/strings/hu.json +++ b/src/i18n/strings/hu.json @@ -3243,5 +3243,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Innen: %(deviceName)s (%(deviceId)s), %(ip)s", "Check your devices": "Ellenőrizze az eszközeit", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Új bejelentkezéssel hozzáférés történik a fiókjához: %(name)s (%(deviceID)s), %(ip)s", - "You have unverified logins": "Ellenőrizetlen bejelentkezései vannak" + "You have unverified logins": "Ellenőrizetlen bejelentkezései vannak", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Az ellenőrzés nélkül nem fér hozzá az összes üzenetéhez és mások számára megbízhatatlannak fog látszani.", + "Verify your identity to access encrypted messages and prove your identity to others.": "Ellenőrizze a személyazonosságát, hogy hozzáférjen a titkosított üzeneteihez és másoknak is bizonyítani tudja személyazonosságát.", + "Use another login": "Másik munkamenet használata", + "Please choose a strong password": "Kérem válasszon erős jelszót", + "You can add more later too, including already existing ones.": "Később is hozzáadhat többet, beleértve meglévőket is.", + "Let's create a room for each of them.": "Készítsünk szobát mindhez.", + "What are some things you want to discuss in %(spaceName)s?": "Mik azok amikről beszélni szeretne itt: %(spaceName)s?", + "Verification requested": "Hitelesítés kérés elküldve", + "Avatar": "Profilkép", + "Verify other login": "Másik munkamenet ellenőrzése", + "Reset event store": "Az esemény tárolót alaphelyzetbe állítása", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Ha ezt teszi, tudnia kell, hogy az üzenetek nem kerülnek törlésre de keresés nem lesz tökéletes amíg az indexek nem készülnek el újra", + "You most likely do not want to reset your event index store": "Az esemény index tárolót nagy valószínűséggel nem szeretné alaphelyzetbe állítani", + "Reset event store?": "Az esemény tárolót alaphelyzetbe állítja?", + "Consult first": "Kérjen először véleményt", + "Invited people will be able to read old messages.": "A meghívott személyek el tudják olvasni a régi üzeneteket.", + "We couldn't create your DM.": "Nem tudjuk elkészíteni a közvetlen üzenetét.", + "Adding...": "Hozzáadás…", + "Add existing rooms": "Létező szobák hozzáadása", + "%(count)s people you know have already joined|one": "%(count)s ismerős már csatlakozott", + "%(count)s people you know have already joined|other": "%(count)s ismerős már csatlakozott", + "Accept on your other login…": "Egy másik bejelentkezésében fogadta el…", + "Stop & send recording": "Megállít és a felvétel elküldése", + "Record a voice message": "Hang üzenet felvétele", + "Invite messages are hidden by default. Click to show the message.": "A meghívók alapesetben rejtve vannak. A megjelenítéshez kattintson.", + "Quick actions": "Gyors műveletek", + "Invite to just this room": "Meghívás csak ebbe a szobába", + "Warn before quitting": "Kilépés előtt figyelmeztet", + "Message search initilisation failed": "Üzenet keresés beállítása sikertelen", + "Manage & explore rooms": "Szobák kezelése és felderítése", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Egyeztetés vele: %(transferTarget)s. Átadás ide: %(transferee)s", + "unknown person": "ismeretlen személy", + "Share decryption keys for room history when inviting users": "Visszafejtéshez szükséges kulcsok megosztása a szoba előzményekhez felhasználók meghívásakor", + "Send and receive voice messages (in development)": "Hang üzenetek küldése és fogadása (fejlesztés alatt)", + "%(deviceId)s from %(ip)s": "%(deviceId)s innen: %(ip)s", + "Review to ensure your account is safe": "Tekintse át, hogy meggyőződjön arról, hogy a fiókja biztonságban van", + "Sends the given message as a spoiler": "A megadott üzenet szpojlerként küldése" } diff --git a/src/i18n/strings/it.json b/src/i18n/strings/it.json index 229b769c18..2d0edb77e6 100644 --- a/src/i18n/strings/it.json +++ b/src/i18n/strings/it.json @@ -3248,5 +3248,42 @@ "Check your devices": "Controlla i tuoi dispositivi", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Una nuova sessione sta accedendo al tuo account: %(name)s (%(deviceID)s) al %(ip)s", "You have unverified logins": "Hai accessi non verificati", - "Open": "Apri" + "Open": "Apri", + "Send and receive voice messages (in development)": "Invia e ricevi messaggi vocali (in sviluppo)", + "unknown person": "persona sconosciuta", + "Sends the given message as a spoiler": "Invia il messaggio come spoiler", + "Review to ensure your account is safe": "Controlla per assicurarti che l'account sia sicuro", + "%(deviceId)s from %(ip)s": "%(deviceId)s da %(ip)s", + "Share decryption keys for room history when inviting users": "Condividi le chiavi di decifrazione della cronologia della stanza quando inviti utenti", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Consultazione con %(transferTarget)s. Trasferisci a %(transferee)s", + "Manage & explore rooms": "Gestisci ed esplora le stanze", + "Invite to just this room": "Invita solo in questa stanza", + "%(count)s people you know have already joined|other": "%(count)s persone che conosci sono già entrate", + "%(count)s people you know have already joined|one": "%(count)s persona che conosci è già entrata", + "Message search initilisation failed": "Inizializzazione ricerca messaggi fallita", + "Add existing rooms": "Aggiungi stanze esistenti", + "Warn before quitting": "Avvisa prima di uscire", + "Invited people will be able to read old messages.": "Le persone invitate potranno leggere i vecchi messaggi.", + "You most likely do not want to reset your event index store": "Probabilmente non hai bisogno di reinizializzare il tuo archivio indice degli eventi", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Se lo fai, ricorda che nessuno dei tuoi messaggi verrà eliminato, ma l'esperienza di ricerca potrà peggiorare per qualche momento mentre l'indice viene ricreato", + "Avatar": "Avatar", + "Verification requested": "Verifica richiesta", + "What are some things you want to discuss in %(spaceName)s?": "Quali sono le cose di cui vuoi discutere in %(spaceName)s?", + "Please choose a strong password": "Scegli una password robusta", + "Quick actions": "Azioni rapide", + "Invite messages are hidden by default. Click to show the message.": "I messaggi di invito sono nascosti in modo predefinito. Clicca per mostrare il messaggio.", + "Record a voice message": "Registra un messaggio vocale", + "Stop & send recording": "Ferma e invia la registrazione", + "Accept on your other login…": "Accetta nella tua altra sessione…", + "Adding...": "Aggiunta...", + "We couldn't create your DM.": "Non abbiamo potuto creare il tuo messaggio diretto.", + "Consult first": "Prima consulta", + "Reset event store?": "Reinizializzare l'archivio eventi?", + "Reset event store": "Reinizializza archivio eventi", + "Verify other login": "Verifica l'altra sessione", + "Let's create a room for each of them.": "Creiamo una stanza per ognuno di essi.", + "You can add more later too, including already existing ones.": "Puoi aggiungerne anche altri in seguito, inclusi quelli già esistenti.", + "Use another login": "Usa un altro accesso", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifica la tua identità per accedere ai messaggi cifrati e provare agli altri che sei tu.", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Senza la verifica, non avrai accesso a tutti i tuoi messaggi e potresti apparire agli altri come non fidato." } diff --git a/src/i18n/strings/jbo.json b/src/i18n/strings/jbo.json index f2c9dc6e43..b19d4bb95d 100644 --- a/src/i18n/strings/jbo.json +++ b/src/i18n/strings/jbo.json @@ -580,5 +580,8 @@ "%(displayName)s cancelled verification.": ".i la'o zoi. %(displayName)s .zoi co'u co'a lacri", "Decrypt %(text)s": "nu facki le du'u mifra la'o zoi. %(text)s .zoi", "Download %(text)s": "nu kibycpa la'o zoi. %(text)s .zoi", - "Download this file": "nu kibycpa le vreji" + "Download this file": "nu kibycpa le vreji", + "Explore rooms": "nu facki le du'u ve zilbe'i", + "Create Account": "nu pa re'u co'a jaspu", + "Dismiss": "nu mipri" } diff --git a/src/i18n/strings/kab.json b/src/i18n/strings/kab.json index c4e0cc7099..b6e1b3020f 100644 --- a/src/i18n/strings/kab.json +++ b/src/i18n/strings/kab.json @@ -2,7 +2,7 @@ "Confirm": "Sentem", "Analytics": "Tiselḍin", "Error": "Tuccḍa", - "Dismiss": "Agi", + "Dismiss": "Agwi", "OK": "IH", "Permission Required": "Tasiregt tlaq", "Continue": "Kemmel", diff --git a/src/i18n/strings/ko.json b/src/i18n/strings/ko.json index 59bb68af94..f817dbc26b 100644 --- a/src/i18n/strings/ko.json +++ b/src/i18n/strings/ko.json @@ -1666,5 +1666,6 @@ "WARNING: KEY VERIFICATION FAILED! The signing key for %(userId)s and session %(deviceId)s is \"%(fprint)s\" which does not match the provided key \"%(fingerprint)s\". This could mean your communications are being intercepted!": "경고: 키 검증 실패! 제공된 키인 \"%(fingerprint)s\"가 사용자 %(userId)s와 %(deviceId)s 세션의 서명 키인 \"%(fprint)s\"와 일치하지 않습니다. 이는 통신이 탈취되고 있는 중일 수도 있다는 뜻입니다!", "The signing key you provided matches the signing key you received from %(userId)s's session %(deviceId)s. Session marked as verified.": "사용자 %(userId)s의 세션 %(deviceId)s에서 받은 서명 키와 당신이 제공한 서명 키가 일치합니다. 세션이 검증되었습니다.", "Show more": "더 보기", - "Changing password will currently reset any end-to-end encryption keys on all sessions, making encrypted chat history unreadable, unless you first export your room keys and re-import them afterwards. In future this will be improved.": "비밀번호를 변경한다면 방의 암호화 키를 내보낸 후 다시 가져오지 않는 이상 모든 종단간 암호화 키는 초기화 될 것이고, 암호화된 대화 내역은 읽을 수 없게 될 것입니다. 이 문제는 추후에 개선될 것입니다." + "Changing password will currently reset any end-to-end encryption keys on all sessions, making encrypted chat history unreadable, unless you first export your room keys and re-import them afterwards. In future this will be improved.": "비밀번호를 변경한다면 방의 암호화 키를 내보낸 후 다시 가져오지 않는 이상 모든 종단간 암호화 키는 초기화 될 것이고, 암호화된 대화 내역은 읽을 수 없게 될 것입니다. 이 문제는 추후에 개선될 것입니다.", + "Create Account": "계정 만들기" } diff --git a/src/i18n/strings/lt.json b/src/i18n/strings/lt.json index 6ba078ad64..83b59681e7 100644 --- a/src/i18n/strings/lt.json +++ b/src/i18n/strings/lt.json @@ -1184,7 +1184,7 @@ "Manage integrations": "Valdyti integracijas", "Integration Managers receive configuration data, and can modify widgets, send room invites, and set power levels on your behalf.": "Integracijų Tvarkytuvai gauna konfigūracijos duomenis ir jūsų vardu gali keisti valdiklius, siųsti kambario pakvietimus ir nustatyti galios lygius.", "Invalid theme schema.": "Klaidinga temos schema.", - "Error downloading theme information.": "Klaida parsisiunčiant temos informaciją.", + "Error downloading theme information.": "Klaida atsisiunčiant temos informaciją.", "Theme added!": "Tema pridėta!", "Custom theme URL": "Pasirinktinės temos URL", "Add theme": "Pridėti temą", @@ -2091,5 +2091,16 @@ "Successfully restored %(sessionCount)s keys": "Sėkmingai atkurti %(sessionCount)s raktai", "Warning: Your personal data (including encryption keys) is still stored in this session. Clear it if you're finished using this session, or want to sign in to another account.": "Įspėjimas: Jūsų asmeniniai duomenys (įskaitant šifravimo raktus) vis dar yra saugomi šiame seanse. Išvalykite juos, jei baigėte naudoti šį seansą, arba norite prisijungti prie kitos paskyros.", "Reason (optional)": "Priežastis (nebūtina)", - "Reason: %(reason)s": "Priežastis: %(reason)s" + "Reason: %(reason)s": "Priežastis: %(reason)s", + "Already have an account? Sign in here": "Jau turite paskyrą? Prisijunkite čia", + "Host account on": "Kurti paskyrą serveryje", + "Forgotten your password?": "Pamiršote savo slaptažodį?", + "Homeserver": "Serveris", + "New? Create account": "Naujas vartotojas? Sukurkite paskyrą", + "Forgot password?": "Pamiršote slaptažodį?", + "Preparing to download logs": "Ruošiamasi parsiųsti žurnalus", + "You can use the custom server options to sign into other Matrix servers by specifying a different homeserver URL. This allows you to use Element with an existing Matrix account on a different homeserver.": "Jūs galite naudoti serverio parinktis, norėdami prisijungti prie kitų Matrix serverių, nurodydami kitą serverio URL. Tai leidžia jums naudoti Element su egzistuojančia paskyra kitame serveryje.", + "Server Options": "Serverio Parinktys", + "Your homeserver": "Jūsų serveris", + "Download logs": "Parsisiųsti žurnalus" } diff --git a/src/i18n/strings/lv.json b/src/i18n/strings/lv.json index 4b07a93ea6..ed7da7dc6b 100644 --- a/src/i18n/strings/lv.json +++ b/src/i18n/strings/lv.json @@ -300,7 +300,7 @@ "You need to be logged in.": "Tev ir jāpierakstās.", "Your email address does not appear to be associated with a Matrix ID on this Homeserver.": "Jūsu epasta adrese nav piesaistīta nevienam Matrix ID šajā bāzes serverī.", "You seem to be in a call, are you sure you want to quit?": "Izskatās, ka atrodies zvana režīmā. Vai tiešām vēlies iziet?", - "You seem to be uploading files, are you sure you want to quit?": "Izskatās, ka šobrīd augšuplādē failus. Vai tiešām vēlies iziet?", + "You seem to be uploading files, are you sure you want to quit?": "Izskatās, ka šobrīd notiek failu augšupielāde. Vai tiešām vēlaties iziet?", "Sun": "Sv.", "Mon": "P.", "Tue": "O.", @@ -747,7 +747,7 @@ "Unhide Preview": "Rādīt priekšskatījumu", "Unable to join network": "Neizdodas pievienoties tīklam", "Sorry, your browser is not able to run %(brand)s.": "Atvaino, diemžēl tavs tīmekļa pārlūks nespēj darbināt %(brand)s.", - "Uploaded on %(date)s by %(user)s": "Augšuplādēja %(user)s %(date)s", + "Uploaded on %(date)s by %(user)s": "Augšupielādēja %(user)s %(date)s", "Messages in group chats": "Ziņas grupas čatos", "Yesterday": "Vakardien", "Error encountered (%(errorDetail)s).": "Gadījās kļūda (%(errorDetail)s).", @@ -1559,5 +1559,27 @@ "Verify this session": "Verificēt šo sesiju", "You signed in to a new session without verifying it:": "Jūs pierakstījāties jaunā sesijā, neveicot tās verifikāciju:", "You're already in a call with this person.": "Jums jau notiek zvans ar šo personu.", - "Already in call": "Notiek zvans" + "Already in call": "Notiek zvans", + "%(deviceId)s from %(ip)s": "%(deviceId)s no %(ip)s", + "%(count)s people you know have already joined|other": "%(count)s pazīstami cilvēki ir jau pievienojusies", + "%(count)s people you know have already joined|one": "%(count)s pazīstama persona ir jau pievienojusies", + "Saving...": "Saglabā…", + "%(count)s members|one": "%(count)s dalībnieks", + "Save Changes": "Saglabāt izmaiņas", + "%(count)s messages deleted.|other": "%(count)s ziņas ir dzēstas.", + "%(count)s messages deleted.|one": "%(count)s ziņa ir dzēsta.", + "Welcome to ": "Laipni lūdzam uz ", + "Room name": "Istabas nosaukums", + "%(count)s members|other": "%(count)s dalībnieki", + "Room List": "Istabu saraksts", + "Send as message": "Nosūtīt kā ziņu", + "%(brand)s URL": "%(brand)s URL", + "Send a message…": "Nosūtīt ziņu…", + "Send a reply…": "Nosūtīt atbildi…", + "Room version": "Istabas versija", + "Room list": "Istabu saraksts", + "Failed to set topic": "Neizdevās iestatīt tematu", + "Upload files": "Failu augšupielāde", + "These files are too large to upload. The file size limit is %(limit)s.": "Šie faili pārsniedz augšupielādes izmēra limitu %(limit)s.", + "Upload files (%(current)s of %(total)s)": "Failu augšupielāde (%(current)s no %(total)s)" } diff --git a/src/i18n/strings/ml.json b/src/i18n/strings/ml.json index 23740fefda..6183fe7de2 100644 --- a/src/i18n/strings/ml.json +++ b/src/i18n/strings/ml.json @@ -127,5 +127,8 @@ "Failed to change settings": "സജ്ജീകരണങ്ങള്‍ മാറ്റുന്നവാന്‍ സാധിച്ചില്ല", "View Source": "സോഴ്സ് കാണുക", "With your current browser, the look and feel of the application may be completely incorrect, and some or all features may not function. If you want to try it anyway you can continue, but you are on your own in terms of any issues you may encounter!": "നിങ്ങളുടെ ഇപ്പോളത്തെ ബ്രൌസര്‍ റയട്ട് പ്രവര്‍ത്തിപ്പിക്കാന്‍ പൂര്‍ണമായും പര്യാപത്മല്ല. പല ഫീച്ചറുകളും പ്രവര്‍ത്തിക്കാതെയിരിക്കാം. ഈ ബ്രൌസര്‍ തന്നെ ഉപയോഗിക്കണമെങ്കില്‍ മുന്നോട്ട് പോകാം. പക്ഷേ നിങ്ങള്‍ നേരിടുന്ന പ്രശ്നങ്ങള്‍ നിങ്ങളുടെ ഉത്തരവാദിത്തത്തില്‍ ആയിരിക്കും!", - "Checking for an update...": "അപ്ഡേറ്റ് ഉണ്ടോ എന്ന് തിരയുന്നു..." + "Checking for an update...": "അപ്ഡേറ്റ് ഉണ്ടോ എന്ന് തിരയുന്നു...", + "Explore rooms": "മുറികൾ കണ്ടെത്തുക", + "Sign In": "പ്രവേശിക്കുക", + "Create Account": "അക്കൗണ്ട് സൃഷ്ടിക്കുക" } diff --git a/src/i18n/strings/mn.json b/src/i18n/strings/mn.json index 0967ef424b..5e44298332 100644 --- a/src/i18n/strings/mn.json +++ b/src/i18n/strings/mn.json @@ -1 +1,6 @@ -{} +{ + "Explore rooms": "Өрөөнүүд үзэх", + "Sign In": "Нэвтрэх", + "Create Account": "Хэрэглэгч үүсгэх", + "Dismiss": "Орхих" +} diff --git a/src/i18n/strings/nb_NO.json b/src/i18n/strings/nb_NO.json index ee116fa5bd..d3be9cd2ea 100644 --- a/src/i18n/strings/nb_NO.json +++ b/src/i18n/strings/nb_NO.json @@ -1507,5 +1507,479 @@ "This will end the conference for everyone. Continue?": "Dette vil avslutte konferansen for alle. Fortsett?", "End conference": "Avslutt konferanse", "You're already in a call with this person.": "Du er allerede i en samtale med denne personen.", - "Already in call": "Allerede i en samtale" + "Already in call": "Allerede i en samtale", + "Are you sure you want to remove '%(roomName)s' from %(groupId)s?": "Er du sikke på at du vil fjerne '%(roomName)s' fra %(groupId)s?", + "Burundi": "Burundi", + "Burkina Faso": "Burkina Faso", + "Bulgaria": "Bulgaria", + "Brunei": "Brunei", + "Brazil": "Brazil", + "Botswana": "Botswana", + "Bolivia": "Bolivia", + "Bhutan": "Bhutan", + "Bermuda": "Bermuda", + "Benin": "Benin", + "Belize": "Belize", + "Belarus": "Hviterussland", + "Barbados": "Barbados", + "Bangladesh": "Bangladesh", + "Bahrain": "Bahrain", + "Bahamas": "Bahamas", + "Azerbaijan": "Azerbaijan", + "Austria": "Østerrike", + "Australia": "Australia", + "Aruba": "Aruba", + "Armenia": "Armenia", + "Argentina": "Argentina", + "Antigua & Barbuda": "Antigua og Barbuda", + "Antarctica": "Antarktis", + "Anguilla": "Anguilla", + "Angola": "Angola", + "Andorra": "Andorra", + "Algeria": "Algeria", + "Albania": "Albania", + "Åland Islands": "Åland", + "Afghanistan": "Afghanistan", + "United Kingdom": "Storbritannia", + "Your homeserver was unreachable and was not able to log you in. Please try again. If this continues, please contact your homeserver administrator.": "Din hjemmeserver kunne ikke nås, og kan derfor ikke logge deg inn. Vennligst prøv igjen. Hvis dette fortsetter, kontakt administratoren til din hjemmeserver.", + "Only continue if you trust the owner of the server.": "Fortsett kun om du stoler på eieren av serveren.", + "This action requires accessing the default identity server to validate an email address or phone number, but the server does not have any terms of service.": "Denne handlingen krever tilgang til standard identitetsserver for å kunne validere en epostaddresse eller telefonnummer, men serveren har ikke bruksvilkår.", + "Too Many Calls": "For mange samtaler", + "Call failed because webcam or microphone could not be accessed. Check that:": "Samtalen mislyktes fordi du fikk ikke tilgang til webkamera eller mikrofon. Sørg for at:", + "Unable to access webcam / microphone": "Ingen tilgang til webkamera / mikrofon", + "The call was answered on another device.": "Samtalen ble besvart på en annen enhet.", + "The call could not be established": "Samtalen kunne ikke etableres", + "The other party declined the call.": "Den andre parten avviste samtalen.", + "Call Declined": "Samtale avvist", + "Click the button below to confirm adding this phone number.": "Klikk knappen nedenfor for å bekrefte dette telefonnummeret.", + "Single Sign On": "Single Sign On", + "Confirm adding this phone number by using Single Sign On to prove your identity.": "Bekreft dette telefonnummeret ved å bruke Single Sign On for å bevise din identitet.", + "Confirm adding this email address by using Single Sign On to prove your identity.": "Befrekt denne e-postadressen ved å bruke Single Sign On for å bevise din identitet.", + "Show stickers button": "Vis klistremerkeknappen", + "Recently visited rooms": "Nylig besøkte rom", + "Windows": "Vinduer", + "Abort": "Avbryt", + "You have unverified logins": "Du har uverifiserte pålogginger", + "Check your devices": "Sjekk enhetene dine", + "Record a voice message": "Send en stemmebeskjed", + "Edit devices": "Rediger enheter", + "Homeserver": "Hjemmetjener", + "Edit Values": "Rediger verdier", + "Add existing room": "Legg til et eksisterende rom", + "Spell check dictionaries": "Stavesjekk-ordbøker", + "Invite to this space": "Inviter til dette området", + "Send message": "Send melding", + "Cookie Policy": "Infokapselretningslinjer", + "Invite to %(roomName)s": "Inviter til %(roomName)s", + "Resume": "Fortsett", + "Avatar": "Profilbilde", + "A confirmation email has been sent to %(emailAddress)s": "En bekreftelses-E-post har blitt sendt til %(emailAddress)s", + "Suggested Rooms": "Foreslåtte rom", + "Welcome %(name)s": "Velkommen, %(name)s", + "Upgrade to %(hostSignupBrand)s": "Oppgrader til %(hostSignupBrand)s", + "Verification requested": "Verifisering ble forespurt", + "%(count)s members|one": "%(count)s medlem", + "Removing...": "Fjerner …", + "No results found": "Ingen resultater ble funnet", + "Public space": "Offentlig område", + "Private space": "Privat område", + "Support": "Support", + "What projects are you working on?": "Hvilke prosjekter jobber du på?", + "Suggested": "Anbefalte", + "%(deviceId)s from %(ip)s": "%(deviceId)s fra %(ip)s", + "Accept on your other login…": "Aksepter på din andre pålogging …", + "Value:": "Verdi:", + "Leave Space": "Forlat området", + "View dev tools": "Vis utviklerverktøy", + "Saving...": "Lagrer …", + "Save Changes": "Lagre endringer", + "Verify other login": "Verifiser en annen pålogging", + "You don't have permission": "Du har ikke tillatelse", + "%(count)s rooms|other": "%(count)s rom", + "%(count)s rooms|one": "%(count)s rom", + "Invite by username": "Inviter etter brukernavn", + "Delete": "Slett", + "Your public space": "Ditt offentlige område", + "Your private space": "Ditt private område", + "Invite to %(spaceName)s": "Inviter til %(spaceName)s", + "%(count)s members|other": "%(count)s medlemmer", + "Random": "Tilfeldig", + "unknown person": "ukjent person", + "Public": "Offentlig", + "Private": "Privat", + "Click to copy": "Klikk for å kopiere", + "Share invite link": "Del invitasjonslenke", + "Leave space": "Forlat området", + "Warn before quitting": "Advar før avslutning", + "Quick actions": "Hurtigvalg", + "Screens": "Skjermer", + "%(count)s people you know have already joined|other": "%(count)s personer du kjenner har allerede blitt med", + "Add existing rooms": "Legg til eksisterende rom", + "Don't want to add an existing room?": "Vil du ikke legge til et eksisterende rom?", + "Create a new room": "Opprett et nytt rom", + "Adding...": "Legger til …", + "Settings Explorer": "Innstillingsutforsker", + "Value": "Verdi", + "Setting:": "Innstilling:", + "Caution:": "Advarsel:", + "Level": "Nivå", + "Privacy Policy": "Personvern", + "You should know": "Du bør vite", + "Room name": "Rommets navn", + "Skip for now": "Hopp over for nå", + "Creating rooms...": "Oppretter rom …", + "Share %(name)s": "Del %(name)s", + "Just me": "Bare meg selv", + "Inviting...": "Inviterer …", + "Please choose a strong password": "Vennligst velg et sterkt passord", + "New? Create account": "Er du ny her? Opprett en konto", + "Use another login": "Bruk en annen pålogging", + "Use Security Key or Phrase": "Bruk sikkerhetsnøkkel eller -frase", + "Use Security Key": "Bruk sikkerhetsnøkkel", + "Upgrade private room": "Oppgrader privat rom", + "Upgrade public room": "Oppgrader offentlig rom", + "Decline All": "Avslå alle", + "Enter Security Key": "Skriv inn sikkerhetsnøkkel", + "Germany": "Tyskland", + "Malta": "Malta", + "Uruguay": "Uruguay", + "Community settings": "Fellesskapsinnstillinger", + "You’re all caught up": "Du har lest deg opp på alt det nye", + "Remember this": "Husk dette", + "Move right": "Gå til høyre", + "Notify the whole room": "Varsle hele rommet", + "Got an account? Sign in": "Har du en konto? Logg på", + "You created this room.": "Du opprettet dette rommet.", + "Security Phrase": "Sikkerhetsfrase", + "Start a Conversation": "Start en samtale", + "Open dial pad": "Åpne nummerpanelet", + "Message deleted on %(date)s": "Meldingen ble slettet den %(date)s", + "Approve": "Godkjenn", + "Create community": "Opprett fellesskap", + "Already have an account? Sign in here": "Har du allerede en konto? Logg på", + "%(ssoButtons)s Or %(usernamePassword)s": "%(ssoButtons)s eller %(usernamePassword)s", + "That username already exists, please try another.": "Det brukernavnet finnes allerede, vennligst prøv et annet et", + "New here? Create an account": "Er du ny her? Opprett en konto", + "Now, let's help you get started": "Nå, la oss hjelpe deg med å komme i gang", + "Forgot password?": "Glemt passord?", + "Enter email address": "Legg inn e-postadresse", + "Enter phone number": "Skriv inn telefonnummer", + "Please enter the code it contains:": "Vennligst skriv inn koden den inneholder:", + "Token incorrect": "Sjetongen er feil", + "A text message has been sent to %(msisdn)s": "En SMS har blitt sendt til %(msisdn)s", + "Open the link in the email to continue registration.": "Åpne lenken i E-posten for å fortsette registreringen.", + "This room is public": "Dette rommet er offentlig", + "Move left": "Gå til venstre", + "Take a picture": "Ta et bilde", + "Hold": "Hold", + "Enter Security Phrase": "Skriv inn sikkerhetsfrase", + "Security Key": "Sikkerhetsnøkkel", + "Invalid Security Key": "Ugyldig sikkerhetsnøkkel", + "Wrong Security Key": "Feil sikkerhetsnøkkel", + "About homeservers": "Om hjemmetjenere", + "New Recovery Method": "Ny gjenopprettingsmetode", + "Generate a Security Key": "Generer en sikkerhetsnøkkel", + "Confirm your Security Phrase": "Bekreft sikkerhetsfrasen din", + "Your Security Key": "Sikkerhetsnøkkelen din", + "Repeat your Security Phrase...": "Gjenta sikkerhetsfrasen din", + "Set up with a Security Key": "Sett opp med en sikkerhetsnøkkel", + "Use app": "Bruk app", + "Learn more": "Lær mer", + "Use app for a better experience": "Bruk appen for en bedre opplevelse", + "Continue with %(provider)s": "Fortsett med %(provider)s", + "This address is already in use": "Denne adressen er allerede i bruk", + "In reply to ": "Som svar på ", + "%(oneUser)schanged their name %(count)s times|other": "%(oneUser)sendret navnet sitt %(count)s ganger", + "%(oneUser)shad their invitation withdrawn %(count)s times|one": "%(oneUser)sfikk sin invitasjon trukket tilbake", + "%(severalUsers)shad their invitations withdrawn %(count)s times|one": "%(severalUsers)sfikk sine invitasjoner trukket tilbake", + "%(oneUser)srejected their invitation %(count)s times|one": "%(oneUser)savslo invitasjonen sin", + "%(oneUser)sleft and rejoined %(count)s times|one": "%(oneUser)sforlot og ble med igjen", + "%(severalUsers)sleft and rejoined %(count)s times|one": "%(severalUsers)sforlot og ble med igjen", + "%(oneUser)sjoined and left %(count)s times|one": "%(oneUser)sble med og forlot igjen", + "%(severalUsers)sjoined and left %(count)s times|one": "%(severalUsers)sble med og forlot igjen", + "Information": "Informasjon", + "Add rooms to this community": "Legg til rom i dette fellesskapet", + "%(name)s cancelled verifying": "%(name)s avbrøt verifiseringen", + "You cancelled verifying %(name)s": "Du avbrøt verifiseringen av %(name)s", + "Invalid file%(extra)s": "Ugyldig fil%(extra)s", + "Failed to ban user": "Mislyktes i å bannlyse brukeren", + "Room settings": "Rominnstillinger", + "Show files": "Vis filer", + "Not encrypted": "Ikke kryptert", + "About": "Om", + "Widgets": "Komponenter", + "Room Info": "Rominfo", + "Favourited": "Favorittmerket", + "Forget Room": "Glem rommet", + "Show previews of messages": "Vis forhåndsvisninger av meldinger", + "Invalid URL": "Ugyldig URL", + "Continuing without email": "Fortsetter uten E-post", + "Are you sure you want to sign out?": "Er du sikker på at du vil logge av?", + "Transfer": "Overfør", + "Invite by email": "Inviter gjennom E-post", + "Waiting for partner to confirm...": "Venter på at partneren skal bekrefte …", + "Report a bug": "Rapporter en feil", + "Comment": "Kommentar", + "Add comment": "Legg til kommentar", + "Active Widgets": "Aktive moduler", + "Create a room in %(communityName)s": "Opprett et rom i %(communityName)s", + "Reason (optional)": "Årsak (valgfritt)", + "Send %(count)s invites|one": "Send %(count)s invitasjon", + "Send %(count)s invites|other": "Send %(count)s invitasjoner", + "Add another email": "Legg til en annen E-postadresse", + "%(count)s results|one": "%(count)s resultat", + "%(count)s results|other": "%(count)s resultater", + "Start a new chat": "Start en ny chat", + "Custom Tag": "Egendefinert merkelapp", + "Explore public rooms": "Utforsk offentlige rom", + "Explore community rooms": "Utforsk samfunnsrom", + "Invite to this community": "Inviter til dette fellesskapet", + "Verify the link in your inbox": "Verifiser lenken i innboksen din", + "Bridges": "Broer", + "Privacy": "Personvern", + "Reject all %(invitedRooms)s invites": "Avslå alle %(invitedRooms)s-invitasjoner", + "Upgrade Room Version": "Oppgrader romversjon", + "You cancelled verification.": "Du avbrøt verifiseringen.", + "Ask %(displayName)s to scan your code:": "Be %(displayName)s om å skanne koden:", + "Role": "Rolle", + "Failed to deactivate user": "Mislyktes i å deaktivere brukeren", + "Accept all %(invitedRooms)s invites": "Aksepter alle %(invitedRooms)s-invitasjoner", + "": "", + "Custom theme URL": "URL-en til et selvvalgt tema", + "not ready": "ikke klar", + "ready": "klar", + "Algorithm:": "Algoritme:", + "Backing up %(sessionsRemaining)s keys...": "Sikkerhetskopierer %(sessionsRemaining)s nøkler …", + "Away": "Borte", + "Start chat": "Start chat", + "Show Widgets": "Vis moduler", + "Hide Widgets": "Skjul moduler", + "Unknown for %(duration)s": "Ukjent i %(duration)s", + "Update %(brand)s": "Oppdater %(brand)s", + "You are currently ignoring:": "Du ignorerer for øyeblikket:", + "Unknown caller": "Ukjent oppringer", + "Dial pad": "Nummerpanel", + "%(name)s on hold": "%(name)s står på vent", + "Fill Screen": "Fyll skjermen", + "Voice Call": "Taleanrop", + "Video Call": "Videoanrop", + "sends confetti": "sender konfetti", + "System font name": "Systemskrifttypenavn", + "Use a system font": "Bruk en systemskrifttype", + "Waiting for answer": "Venter på svar", + "Call in progress": "Anrop pågår", + "Channel: ": "Kanal: ", + "Enable desktop notifications": "Aktiver skrivebordsvarsler", + "Don't miss a reply": "Ikke gå glipp av noen svar", + "Help us improve %(brand)s": "Hjelp oss å forbedre %(brand)s", + "Unknown App": "Ukjent app", + "Short keyboard patterns are easy to guess": "Korte tastatur mønstre er lett å gjette", + "This is similar to a commonly used password": "Dette ligner på et passord som er brukt mye", + "Predictable substitutions like '@' instead of 'a' don't help very much": "Forutsigbar erstatninger som ‘ @‘ istedet for ‘a’ hjelper ikke mye", + "Reversed words aren't much harder to guess": "Ord som er skrevet baklengs er vanskeligere å huske.", + "All-uppercase is almost as easy to guess as all-lowercase": "Bare store bokstaver er nesten like enkelt å gjette som bare små bokstaver", + "Capitalization doesn't help very much": "Store bokstaver er ikke spesielt nyttig", + "Use a longer keyboard pattern with more turns": "Bruke et lengre og mer uventet tastatur mønster", + "No need for symbols, digits, or uppercase letters": "Ikke nødvendig med symboler, sifre eller bokstaver", + "See images posted to this room": "Se bilder som er lagt ut i dette rommet", + "%(senderName)s declined the call.": "%(senderName)s avslo oppringingen.", + "(an error occurred)": "(en feil oppstod)", + "(connection failed)": "(tilkobling mislyktes)", + "Change the topic of this room": "Endre dette rommets tema", + "Effects": "Effekter", + "Zimbabwe": "Zimbabwe", + "Yemen": "Jemen", + "Zambia": "Zambia", + "Western Sahara": "Vest-Sahara", + "Wallis & Futuna": "Wallis og Futuna", + "Venezuela": "Venezuela", + "Vietnam": "Vietnam", + "Vatican City": "Vatikanstaten", + "Vanuatu": "Vanuatu", + "Uzbekistan": "Usbekistan", + "United Arab Emirates": "De forente arabiske emirater", + "Ukraine": "Ukraina", + "U.S. Virgin Islands": "De amerikanske jomfruøyene", + "Uganda": "Uganda", + "Tuvalu": "Tuvalu", + "Turks & Caicos Islands": "Turks- og Caicosøyene", + "Turkmenistan": "Turkmenistan", + "Tunisia": "Tunis", + "Turkey": "Tyrkia", + "Trinidad & Tobago": "Trinidad og Tobago", + "Tonga": "Tonga", + "Tokelau": "Tokelau", + "Togo": "Togo", + "Timor-Leste": "Timor-Leste", + "Thailand": "Thailand", + "Tanzania": "Tanzania", + "Tajikistan": "Tadsjikistan", + "Taiwan": "Taiwan", + "São Tomé & Príncipe": "São Tomé og Príncipe", + "Syria": "Syria", + "Sweden": "Sverige", + "Switzerland": "Sveits", + "Swaziland": "Swaziland", + "Svalbard & Jan Mayen": "Svalbard og Jan Mayen", + "Suriname": "Surinam", + "Sudan": "Sudan", + "St. Vincent & Grenadines": "St. Vincent og Grenadinene", + "St. Kitts & Nevis": "St. Kitts og Nevis", + "St. Helena": "St. Helena", + "Sri Lanka": "Sri Lanka", + "Spain": "Spania", + "South Sudan": "Sør-Sudan", + "South Korea": "Syd-Korea", + "Somalia": "Somalia", + "South Africa": "Sør-Afrika", + "Solomon Islands": "Solomonøyene", + "Slovenia": "Slovenia", + "Slovakia": "Slovakia", + "Sint Maarten": "Sint Maarten", + "Singapore": "Singapore", + "Sierra Leone": "Sierra Leone", + "Seychelles": "Seyschellene", + "Serbia": "Serbia", + "Saudi Arabia": "Saudi-Arabia", + "Senegal": "Senegal", + "San Marino": "San Marino", + "Samoa": "Samoa", + "Réunion": "Réunion", + "Rwanda": "Rwanda", + "Russia": "Russland", + "Qatar": "Qatar", + "Romania": "Romania", + "Puerto Rico": "Puerto Rico", + "Portugal": "Portugal", + "Poland": "Polen", + "Pitcairn Islands": "Pitcairn-øyene", + "Philippines": "Filippinene", + "Peru": "Peru", + "Papua New Guinea": "Papua New Guinea", + "Paraguay": "Paraguay", + "Panama": "Panama", + "Palestine": "Palestina", + "Pakistan": "Pakistan", + "Palau": "Palau", + "Oman": "Oman", + "Norway": "Norge", + "Northern Mariana Islands": "Northern Mariana Islands", + "North Korea": "Nord-Korea", + "Norfolk Island": "Norfolkøyene", + "Niue": "Niue", + "Nigeria": "Nigeria", + "Niger": "Niger", + "New Zealand": "New Zealand", + "Nicaragua": "Nicaragua", + "New Caledonia": "New Caledonia", + "Netherlands": "Nederland", + "Nepal": "Nepal", + "Nauru": "Nauru", + "Namibia": "Namibia", + "Myanmar": "Myanmar", + "Mozambique": "Mosambik", + "Morocco": "Marokko", + "Montenegro": "Montenegro", + "Montserrat": "Montserrat", + "Mongolia": "Mongolia", + "Monaco": "Monaco", + "Moldova": "Moldova", + "Micronesia": "Mikronesia", + "Mexico": "Mexico", + "Mayotte": "Mayotte", + "Mauritius": "Mauritius", + "Mauritania": "Mauretania", + "Martinique": "Martinique", + "Marshall Islands": "Marshall Islands", + "Maldives": "Maldivene", + "Mali": "Mali", + "Malaysia": "Malaysia", + "Malawi": "Malawi", + "Madagascar": "Madagaskar", + "Macedonia": "Nord-Makedonia", + "Macau": "Macau", + "Luxembourg": "Luxemburg", + "Lithuania": "Litauen", + "Liechtenstein": "Liechtenstein", + "Libya": "Libya", + "Liberia": "Liberia", + "Lesotho": "Lesotho", + "Lebanon": "Libanon", + "Latvia": "Latvia", + "Laos": "Laos", + "Kyrgyzstan": "Kirgistan", + "Kuwait": "Kuwait", + "Kosovo": "Kosovo", + "Kiribati": "Kiribati", + "Kazakhstan": "Kasakstan", + "Kenya": "Kenya", + "Jamaica": "Jamaica", + "Isle of Man": "Man", + "Iceland": "Island", + "Hungary": "Ungarn", + "Hong Kong": "Hong Kong", + "Honduras": "Honduras", + "Haiti": "Haiti", + "Guinea-Bissau": "Guinea-Bissau", + "Guyana": "Guyana", + "Guinea": "Guinea", + "Guernsey": "Guernsey", + "Guatemala": "Guatemala", + "Guam": "Guam", + "Guadeloupe": "Guadeloupe", + "Grenada": "Grenada", + "Greece": "Hellas", + "Greenland": "Grønland", + "Gibraltar": "Gibraltar", + "Ghana": "Ghana", + "Georgia": "Georgia", + "Gambia": "Gambia", + "Gabon": "Gabon", + "French Southern Territories": "De franske sørterritoriene", + "French Polynesia": "Fransk polynesia", + "French Guiana": "Fransk Guyana", + "France": "Frankrike", + "Finland": "Finnland", + "Fiji": "Fiji", + "Falkland Islands": "Falklandsøyene", + "Faroe Islands": "Færøyene", + "Ethiopia": "Etiopia", + "Estonia": "Estland", + "Eritrea": "Eritrea", + "Equatorial Guinea": "Ekvatorial-Guinea", + "El Salvador": "El Salvador", + "Egypt": "Egypt", + "Ecuador": "Ecuador", + "Dominican Republic": "Dominikanske republikk", + "Djibouti": "Djibouti", + "Dominica": "Dominica", + "Denmark": "Danmark", + "Côte d’Ivoire": "Elfenbenskysten", + "Czech Republic": "Tsjekkia", + "Cyprus": "Kypros", + "Curaçao": "Curaçao", + "Cuba": "Kuba", + "Colombia": "Colombia", + "Comoros": "Komorene", + "Cocos (Keeling) Islands": "Cocos- (Keeling) øyene", + "Christmas Island": "Juløya", + "China": "Kina", + "Chad": "Tsjad", + "Chile": "Chile", + "Central African Republic": "Sentralafrikanske republikk", + "Cayman Islands": "Caymanøyene", + "Caribbean Netherlands": "Karibisk Nederland", + "Cape Verde": "Kapp Verde", + "Canada": "Canada", + "Cameroon": "Kamerun", + "Cambodia": "Kambodsja", + "British Virgin Islands": "De britiske jomfruøyer", + "British Indian Ocean Territory": "Britiske havområder i det indiske hav", + "Bouvet Island": "Bouvetøya", + "Bosnia": "Bosnia", + "Croatia": "Kroatia", + "Costa Rica": "Costa Rica", + "Cook Islands": "Cook-øyene", + "All keys backed up": "Alle nøkler er sikkerhetskopiert", + "Secret storage:": "Hemmelig lagring:" } diff --git a/src/i18n/strings/nl.json b/src/i18n/strings/nl.json index ee99127e04..de98a878e8 100644 --- a/src/i18n/strings/nl.json +++ b/src/i18n/strings/nl.json @@ -198,7 +198,7 @@ "Join Room": "Gesprek toetreden", "%(targetName)s joined the room.": "%(targetName)s is tot het gesprek toegetreden.", "Jump to first unread message.": "Spring naar het eerste ongelezen bericht.", - "Labs": "Experimenteel", + "Labs": "Labs", "Last seen": "Laatst gezien", "Leave room": "Gesprek verlaten", "%(targetName)s left the room.": "%(targetName)s heeft het gesprek verlaten.", @@ -632,7 +632,7 @@ "The version of %(brand)s": "De versie van %(brand)s", "Your language of choice": "De door jou gekozen taal", "Which officially provided instance you are using, if any": "Welke officieel aangeboden instantie je eventueel gebruikt", - "Whether or not you're using the Richtext mode of the Rich Text Editor": "Of je de tekstverwerker al dan niet in de modus voor opgemaakte tekst gebruikt", + "Whether or not you're using the Richtext mode of the Rich Text Editor": "Of u de tekstverwerker al dan niet in de modus voor opgemaakte tekst gebruikt", "Your homeserver's URL": "De URL van je homeserver", "In reply to ": "Als antwoord op ", "This room is not public. You will not be able to rejoin without an invite.": "Dit is geen openbaar gesprek. Slechts op uitnodiging zult u opnieuw kunnen toetreden.", @@ -1255,7 +1255,7 @@ "The homeserver may be unavailable or overloaded.": "De homeserver is mogelijk onbereikbaar of overbelast.", "You have %(count)s unread notifications in a prior version of this room.|other": "U heeft %(count)s ongelezen meldingen in een vorige versie van dit gesprek.", "You have %(count)s unread notifications in a prior version of this room.|one": "U heeft %(count)s ongelezen meldingen in een vorige versie van dit gesprek.", - "Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)": "Of je de icoontjes voor recente gesprekken (boven de gesprekkenlijst) al dan niet gebruikt", + "Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)": "Of u de icoontjes voor recente gesprekken (boven de gesprekkenlijst) al dan niet gebruikt", "Replying With Files": "Beantwoorden met bestanden", "At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "Het is momenteel niet mogelijk met een bestand te antwoorden. Wil je dit bestand uploaden zonder te antwoorden?", "The file '%(fileName)s' failed to upload.": "Het bestand ‘%(fileName)s’ kon niet geüpload worden.", @@ -1758,7 +1758,7 @@ "Cancelling…": "Bezig met annuleren…", "%(brand)s is missing some components required for securely caching encrypted messages locally. If you'd like to experiment with this feature, build a custom %(brand)s Desktop with search components added.": "In %(brand)s ontbreken enige modulen vereist voor het veilig lokaal bewaren van versleutelde berichten. Wilt u deze functie uittesten, compileer dan een aangepaste versie van %(brand)s Desktop die de zoekmodulen bevat.", "This session is not backing up your keys, but you do have an existing backup you can restore from and add to going forward.": "Deze sessie maakt geen back-ups van uw sleutels, maar u beschikt over een reeds bestaande back-up waaruit u kunt herstellen en waaraan u nieuwe sleutels vanaf nu kunt toevoegen.", - "Customise your experience with experimental labs features. Learn more.": "Personaliseer uw ervaring met experimentele functies. Klik hier voor meer informatie.", + "Customise your experience with experimental labs features. Learn more.": "Personaliseer uw ervaring met experimentele labs functies. Lees verder.", "Cross-signing": "Kruiselings ondertekenen", "Your key share request has been sent - please check your other sessions for key share requests.": "Uw sleuteldeelverzoek is verstuurd - controleer de sleuteldeelverzoeken op uw andere sessies.", "Key share requests are sent to your other sessions automatically. If you rejected or dismissed the key share request on your other sessions, click here to request the keys for this session again.": "Sleuteldeelverzoeken worden automatisch naar andere sessies verstuurd. Als u op uw andere sessies het sleuteldeelverzoek geweigerd of genegeerd hebt, kunt u hier klikken op de sleutels voor deze sessie opnieuw aan te vragen.", @@ -3134,5 +3134,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Van %(deviceName)s (%(deviceId)s) op %(ip)s", "Check your devices": "Controleer uw apparaten", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Een nieuwe login heeft toegang tot uw account: %(name)s (%(deviceID)s) op %(ip)s", - "You have unverified logins": "U heeft ongeverifieerde logins" + "You have unverified logins": "U heeft ongeverifieerde logins", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Zonder verifiëren heeft u geen toegang tot al uw berichten en kan u als onvertrouwd aangemerkt staan bij anderen.", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifeer uw identiteit om toegang te krijgen tot uw versleutelde berichten en uw identiteit te bewijzen voor anderen.", + "Use another login": "Gebruik andere login", + "Please choose a strong password": "Kies een sterk wachtwoord", + "You can add more later too, including already existing ones.": "U kunt er later nog meer toevoegen, inclusief al bestaande gesprekken.", + "Let's create a room for each of them.": "Laten we voor elk een los gesprek maken.", + "What are some things you want to discuss in %(spaceName)s?": "Wat wilt u allemaal bespreken in %(spaceName)s?", + "Verification requested": "Verificatieverzocht", + "Avatar": "Avatar", + "Verify other login": "Verifieer andere login", + "You most likely do not want to reset your event index store": "U wilt waarschijnlijk niet uw gebeurtenisopslag-index resetten", + "Reset event store?": "Gebeurtenisopslag resetten?", + "Reset event store": "Gebeurtenisopslag resetten", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Als u dit wilt, let op uw berichten worden niet verwijderd, zal het zoeken tijdelijk minder goed werken terwijl we uw index opnieuw opbouwen", + "Consult first": "Eerst overleggen", + "Invited people will be able to read old messages.": "Uitgenodigde personen kunnen de oude berichten lezen.", + "We couldn't create your DM.": "We konden uw DM niet aanmaken.", + "Adding...": "Toevoegen...", + "Add existing rooms": "Bestaande gesprekken toevoegen", + "%(count)s people you know have already joined|one": "%(count)s persoon die u kent is al geregistreerd", + "%(count)s people you know have already joined|other": "%(count)s personen die u kent hebben zijn al geregistreerd", + "Accept on your other login…": "Accepteer op uw andere login…", + "Stop & send recording": "Stop & verstuur opname", + "Record a voice message": "Audiobericht opnemen", + "Invite messages are hidden by default. Click to show the message.": "Uitnodigingen zijn standaard verborgen. Klik om de uitnodigingen weer te geven.", + "Quick actions": "Snelle acties", + "Invite to just this room": "Uitnodigen voor alleen dit gesprek", + "Warn before quitting": "Waarschuwen voordat u afsluit", + "Message search initilisation failed": "Zoeken in berichten opstarten is mislukt", + "Manage & explore rooms": "Beheer & ontdek gesprekken", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Overleggen met %(transferTarget)s. Verstuur naar %(transferee)s", + "unknown person": "onbekend persoon", + "Share decryption keys for room history when inviting users": "Deel ontsleutelsleutels voor de gespreksgeschiedenis wanneer u personen uitnodigd", + "Send and receive voice messages (in development)": "Verstuur en ontvang audioberichten (in ontwikkeling)", + "%(deviceId)s from %(ip)s": "%(deviceId)s van %(ip)s", + "Review to ensure your account is safe": "Controleer om u te verzekeren dat uw account veilig is", + "Sends the given message as a spoiler": "Verstuurt het bericht als een spoiler" } diff --git a/src/i18n/strings/oc.json b/src/i18n/strings/oc.json index cd62ff69db..d882b04ac9 100644 --- a/src/i18n/strings/oc.json +++ b/src/i18n/strings/oc.json @@ -62,7 +62,7 @@ "Server error": "Error servidor", "Single Sign On": "Autentificacion unica", "Confirm": "Confirmar", - "Dismiss": "Far desaparéisser", + "Dismiss": "Refusar", "OK": "D’acòrdi", "Continue": "Contunhar", "Go Back": "En arrièr", @@ -118,7 +118,7 @@ "Incoming call": "Sonada entranta", "Accept": "Acceptar", "Start": "Començament", - "Cancelling…": "Anullacion...", + "Cancelling…": "Anullacion…", "Fish": "Pes", "Butterfly": "Parpalhòl", "Tree": "Arborescéncia", @@ -338,5 +338,13 @@ "Esc": "Escap", "Enter": "Entrada", "Space": "Espaci", - "End": "Fin" + "End": "Fin", + "Explore rooms": "Percórrer las salas", + "Create Account": "Crear un compte", + "Click the button below to confirm adding this email address.": "Clicatz sus lo boton aicí dejós per confirmar l'adicion de l'adreça e-mail.", + "Confirm adding email": "Confirmar l'adicion de l'adressa e-mail", + "Confirm adding this email address by using Single Sign On to prove your identity.": "Confirmatz l'adicion d'aquela adreça e-mail en utilizant l'autentificacion unica per provar la vòstra identitat.", + "Use Single Sign On to continue": "Utilizar l'autentificacion unica (SSO) per contunhar", + "This phone number is already in use": "Aquel numèro de telefòn es ja utilizat", + "This email address is already in use": "Aquela adreça e-mail es ja utilizada" } diff --git a/src/i18n/strings/pl.json b/src/i18n/strings/pl.json index 9fa9c7555e..ab9a478446 100644 --- a/src/i18n/strings/pl.json +++ b/src/i18n/strings/pl.json @@ -1277,8 +1277,8 @@ "Enable desktop notifications for this session": "Włącz powiadomienia na pulpicie dla tej sesji", "Enable audible notifications for this session": "Włącz powiadomienia dźwiękowe dla tej sesji", "Direct Messages": "Wiadomości bezpośrednie", - "Create Account": "Utwórz konto", - "Sign In": "Zaloguj się", + "Create Account": "Stwórz konto", + "Sign In": "Zaloguj", "a few seconds ago": "kilka sekund temu", "%(num)s minutes ago": "%(num)s minut temu", "%(num)s hours ago": "%(num)s godzin temu", diff --git a/src/i18n/strings/pt.json b/src/i18n/strings/pt.json index f72edc150d..4047aae760 100644 --- a/src/i18n/strings/pt.json +++ b/src/i18n/strings/pt.json @@ -569,5 +569,8 @@ "Try using turn.matrix.org": "Tente utilizar turn.matrix.org", "Whether you're using %(brand)s on a device where touch is the primary input mechanism": "Quer esteja a usar o %(brand)s num dispositivo onde o touch é o mecanismo de entrada primário", "Whether you're using %(brand)s as an installed Progressive Web App": "Quer esteja a usar o %(brand)s como uma Progressive Web App (PWA)", - "Your user agent": "O seu user agent" + "Your user agent": "O seu user agent", + "Explore rooms": "Explorar rooms", + "Sign In": "Iniciar sessão", + "Create Account": "Criar conta" } diff --git a/src/i18n/strings/pt_BR.json b/src/i18n/strings/pt_BR.json index 0ec835362a..8497ae7164 100644 --- a/src/i18n/strings/pt_BR.json +++ b/src/i18n/strings/pt_BR.json @@ -1175,7 +1175,7 @@ "Learn More": "Saiba mais", "Sign In or Create Account": "Faça login ou crie uma conta", "Use your account or create a new one to continue.": "Use sua conta ou crie uma nova para continuar.", - "Create Account": "Criar conta", + "Create Account": "Criar Conta", "Sign In": "Entrar", "Custom (%(level)s)": "Personalizado (%(level)s)", "Messages": "Mensagens", diff --git a/src/i18n/strings/ro.json b/src/i18n/strings/ro.json index aa87d0a912..062a89f2e3 100644 --- a/src/i18n/strings/ro.json +++ b/src/i18n/strings/ro.json @@ -70,5 +70,9 @@ "Add to community": "Adăugați la comunitate", "Failed to invite the following users to %(groupId)s:": "Nu a putut fi invitat următorii utilizatori %(groupId)s", "Failed to invite users to community": "Nu a fost posibilă invitarea utilizatorilor la comunitate", - "Failed to invite users to %(groupId)s": "Nu a fost posibilă invitarea utilizatorilor la %(groupId)s" + "Failed to invite users to %(groupId)s": "Nu a fost posibilă invitarea utilizatorilor la %(groupId)s", + "Explore rooms": "Explorează camerele", + "Sign In": "Autentificare", + "Create Account": "Înregistare", + "Dismiss": "Închide" } diff --git a/src/i18n/strings/ru.json b/src/i18n/strings/ru.json index 27a418c5c2..7db3758fd8 100644 --- a/src/i18n/strings/ru.json +++ b/src/i18n/strings/ru.json @@ -3169,5 +3169,46 @@ "Decrypted event source": "Расшифрованный исходный код", "%(count)s rooms and %(numSpaces)s spaces|one": "%(count)s комната и %(numSpaces)s пространств", "%(count)s rooms and %(numSpaces)s spaces|other": "%(count)s комнат и %(numSpaces)s пространств", - "If you can't find the room you're looking for, ask for an invite or create a new room.": "Если вы не можете найти комнату, попросите приглашение или создайте новую комнату." + "If you can't find the room you're looking for, ask for an invite or create a new room.": "Если вы не можете найти комнату, попросите приглашение или создайте новую комнату.", + "Values at explicit levels in this room:": "Значения уровня чувствительности в этой комнате:", + "Values at explicit levels:": "Значения уровня чувствительности:", + "Values at explicit levels in this room": "Значения уровня чувствительности в этой комнате", + "Values at explicit levels": "Значения уровня чувствительности", + "We'll create rooms for each of them. You can add more later too, including already existing ones.": "Мы создадим комнаты для каждого из них. Вы можете добавить ещё больше позже, включая уже существующие.", + "What projects are you working on?": "Над какими проектами вы работаете?", + "Invite by username": "Пригласить по имени пользователя", + "Make sure the right people have access. You can invite more later.": "Убедитесь, что правильные люди имеют доступ. Вы можете пригласить больше людей позже.", + "Invite your teammates": "Пригласите своих товарищей по команде", + "Inviting...": "Приглашение…", + "Failed to invite the following users to your space: %(csvUsers)s": "Не удалось пригласить следующих пользователей в ваше пространство: %(csvUsers)s", + "Me and my teammates": "Я и мои товарищи по команде", + "A private space for you and your teammates": "Приватное пространство для вас и ваших товарищей по команде", + "A private space to organise your rooms": "Приватное пространство для организации ваших комнат", + "Just me": "Только я", + "Make sure the right people have access to %(name)s": "Убедитесь, что правильные люди имеют доступ к %(name)s", + "Who are you working with?": "С кем ты работаешь?", + "Go to my first room": "Перейти в мою первую комнату", + "It's just you at the moment, it will be even better with others.": "Сейчас здесь только ты, с другими будет ещё лучше.", + "Share %(name)s": "Поделиться %(name)s", + "Creating rooms...": "Создание комнат…", + "Skip for now": "Пропустить сейчас", + "Failed to create initial space rooms": "Не удалось создать первоначальные комнаты пространства", + "Room name": "Название комнаты", + "Support": "Поддержка", + "Random": "Случайный", + "Welcome to ": "Добро пожаловать в ", + "Your server does not support showing space hierarchies.": "Ваш сервер не поддерживает отображение пространственных иерархий.", + "Add existing rooms & spaces": "Добавить существующие комнаты и пространства", + "Private space": "Приватное пространство", + "Public space": "Публичное пространство", + " invites you": " пригласил(а) тебя", + "Search names and description": "Искать имена и описание", + "You may want to try a different search or check for typos.": "Вы можете попробовать другой поиск или проверить опечатки.", + "No results found": "Результаты не найдены", + "Mark as suggested": "Отметить как рекомендуется", + "Mark as not suggested": "Отметить как не рекомендуется", + "Removing...": "Удаление…", + "Failed to remove some rooms. Try again later": "Не удалось удалить несколько комнат. Попробуйте позже", + "%(count)s rooms and 1 space|one": "%(count)s комната и одно пространство", + "%(count)s rooms and 1 space|other": "%(count)s комнат и одно пространство" } diff --git a/src/i18n/strings/sl.json b/src/i18n/strings/sl.json index 0e9bdb3d3e..aa2019ad45 100644 --- a/src/i18n/strings/sl.json +++ b/src/i18n/strings/sl.json @@ -27,5 +27,7 @@ "Your homeserver's URL": "URL domačega strežnika", "End": "Konec", "Use default": "Uporabi privzeto", - "Change": "Sprememba" + "Change": "Sprememba", + "Explore rooms": "Raziščite sobe", + "Create Account": "Registracija" } diff --git a/src/i18n/strings/sq.json b/src/i18n/strings/sq.json index 58d23e9395..ad768b59cb 100644 --- a/src/i18n/strings/sq.json +++ b/src/i18n/strings/sq.json @@ -874,7 +874,7 @@ "Incompatible Database": "Bazë të dhënash e Papërputhshme", "Continue With Encryption Disabled": "Vazhdo Me Fshehtëzimin të Çaktivizuar", "Unable to load! Check your network connectivity and try again.": "S’arrihet të ngarkohet! Kontrolloni lidhjen tuaj në rrjet dhe riprovoni.", - "Forces the current outbound group session in an encrypted room to be discarded": "", + "Forces the current outbound group session in an encrypted room to be discarded": "E detyron të hidhet tej sesionin e tanishëm outbound grupi në një dhomë të fshehtëzuar", "Delete Backup": "Fshije Kopjeruajtjen", "Unable to load key backup status": "S’arrihet të ngarkohet gjendje kopjeruajtjeje kyçesh", "Backup version: ": "Version kopjeruajtjeje: ", @@ -3240,5 +3240,37 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Nga %(deviceName)s (%(deviceId)s) te %(ip)s", "Check your devices": "Kontrolloni pajisjet tuaja", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "Në llogarinë tuaj po hyhet nga një palë kredenciale të reja: %(name)s (%(deviceID)s) te %(ip)s", - "You have unverified logins": "Keni kredenciale të erifikuar" + "You have unverified logins": "Keni kredenciale të erifikuar", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Pa e verifikuar, s’do të mund të hyni te krejt mesazhet tuaja dhe mund të dukeni jo i besueshëm për të tjerët.", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifikoni identitetin tuaj që të hyhet në mesazhe të fshehtëzuar dhe t’u provoni të tjerëve identitetin tuaj.", + "Use another login": "Përdorni të tjera kredenciale hyrjesh", + "Please choose a strong password": "Ju lutemi, zgjidhni një fjalëkalim të fuqishëm", + "You can add more later too, including already existing ones.": "Mund të shtoni edhe të tjera më vonë, përfshi ato ekzistueset tashmë.", + "Let's create a room for each of them.": "Le të krijojmë një dhomë për secilën prej tyre.", + "What are some things you want to discuss in %(spaceName)s?": "Cilat janë disa nga gjërat që doni të diskutoni në %(spaceName)s?", + "Verification requested": "U kërkua verifikim", + "Avatar": "Avatar", + "Verify other login": "Verifikoni kredencialet e tjera për hyrje", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Nëse e bëni, ju lutemi, kini parasysh se s’do të fshihet asnjë prej mesazheve tuaja, por puna me kërkimet mund të bjerë, për ca çaste, teksa rikrijohet treguesi", + "Consult first": "Konsultohu së pari", + "Invited people will be able to read old messages.": "Personat e ftuar do të jenë në gjendje të lexojnë mesazhe të vjetër.", + "We couldn't create your DM.": "S’e krijuam dot DM-në tuaj.", + "Adding...": "Po shtohet…", + "Add existing rooms": "Shtoni dhoma ekzistuese", + "%(count)s people you know have already joined|one": "%(count)s person që e njihni është bërë pjesë tashmë", + "%(count)s people you know have already joined|other": "%(count)s persona që i njihni janë bërë pjesë tashmë", + "Stop & send recording": "Ndale & dërgo incizimin", + "Record a voice message": "Incizoni një mesazh zanor", + "Invite messages are hidden by default. Click to show the message.": "Mesazhet e ftesave, si parazgjedhje, janë të fshehur. Klikoni që të shfaqet mesazhi.", + "Quick actions": "Veprime të shpejta", + "Invite to just this room": "Ftoje thjesht te kjo dhomë", + "Warn before quitting": "Sinjalizo përpara daljes", + "Message search initilisation failed": "Dështoi gatitje kërkimi mesazhesh", + "Manage & explore rooms": "Administroni & eksploroni dhoma", + "unknown person": "person i panjohur", + "Sends the given message as a spoiler": "E dërgon mesazhin e dhënë si spoiler", + "Share decryption keys for room history when inviting users": "Ndani me përdorues kyçe shfshehtëzimi, kur ftohen përdorues", + "Send and receive voice messages (in development)": "Dërgoni dhe merrni mesazhe zanorë (në zhvillim)", + "%(deviceId)s from %(ip)s": "%(deviceId)s prej %(ip)s", + "Review to ensure your account is safe": "Shqyrtojeni për t’u siguruar se llogaria është e parrezik" } diff --git a/src/i18n/strings/sr_Latn.json b/src/i18n/strings/sr_Latn.json index 19778858d0..96a5d89411 100644 --- a/src/i18n/strings/sr_Latn.json +++ b/src/i18n/strings/sr_Latn.json @@ -58,5 +58,6 @@ "Failed to invite users to the room:": "Nije uspelo pozivanje korisnika u sobu:", "You need to be logged in.": "Morate biti prijavljeni", "You need to be able to invite users to do that.": "Mora vam biti dozvoljeno da pozovete korisnike kako bi to uradili.", - "Failed to send request.": "Slanje zahteva nije uspelo." + "Failed to send request.": "Slanje zahteva nije uspelo.", + "Create Account": "Napravite nalog" } diff --git a/src/i18n/strings/sv.json b/src/i18n/strings/sv.json index a3147634c7..42a7f78268 100644 --- a/src/i18n/strings/sv.json +++ b/src/i18n/strings/sv.json @@ -3180,5 +3180,41 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "Från %(deviceName)s %(deviceId)s på %(ip)s", "Check your devices": "Kolla dina enheter", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "En ny inloggning kommer åt ditt konto: %(name)s %(deviceID)s på %(ip)s", - "You have unverified logins": "Du har overifierade inloggningar" + "You have unverified logins": "Du har overifierade inloggningar", + "%(count)s people you know have already joined|other": "%(count)s personer du känner har redan gått med", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "Om du gör det, observera att inga av dina meddelanden kommer att raderas, men din sökupplevelse kommer att degraderas en stund medans registret byggs upp igen", + "What are some things you want to discuss in %(spaceName)s?": "Vad är några saker du vill diskutera i %(spaceName)s?", + "You can add more later too, including already existing ones.": "Du kan lägga till flera senare också, inklusive redan existerande.", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "Tillfrågar %(transferTarget)s. %(transferTarget)sÖverför till %(transferee)s", + "Review to ensure your account is safe": "Granska för att försäkra dig om att ditt konto är säkert", + "%(deviceId)s from %(ip)s": "%(deviceId)s från %(ip)s", + "Send and receive voice messages (in development)": "Skicka och ta emot röstmeddelanden (under utveckling)", + "unknown person": "okänd person", + "Warn before quitting": "Varna innan avslutning", + "Invite to just this room": "Bjud in till bara det här rummet", + "Invite messages are hidden by default. Click to show the message.": "Inbjudningsmeddelanden är dolda som förval. Klicka för att visa meddelandet.", + "Record a voice message": "Spela in ett röstmeddelande", + "Stop & send recording": "Stoppa och skicka inspelning", + "Accept on your other login…": "Acceptera på din andra inloggning…", + "%(count)s people you know have already joined|one": "%(count)s person du känner har redan gått med", + "Quick actions": "Snabbhandlingar", + "Add existing rooms": "Lägg till existerande rum", + "Adding...": "Lägger till…", + "We couldn't create your DM.": "Vi kunde inte skapa ditt DM.", + "Reset event store": "Återställ händelselagring", + "Invited people will be able to read old messages.": "Inbjudna personer kommer att kunna läsa gamla meddelanden.", + "Reset event store?": "Återställ händelselagring?", + "You most likely do not want to reset your event index store": "Du vill troligen inte återställa din händelseregisterlagring", + "Consult first": "Tillfråga först", + "Verify other login": "Verifiera annan inloggning", + "Avatar": "Avatar", + "Let's create a room for each of them.": "Låt oss skapa ett rum för varje.", + "Verification requested": "Verifiering begärd", + "Sends the given message as a spoiler": "Skickar det angivna meddelandet som en spoiler", + "Manage & explore rooms": "Hantera och utforska rum", + "Message search initilisation failed": "Initialisering av meddelandesökning misslyckades", + "Please choose a strong password": "Vänligen välj ett starkt lösenord", + "Use another login": "Använd annan inloggning", + "Verify your identity to access encrypted messages and prove your identity to others.": "Verifiera din identitet för att komma åt krypterade meddelanden och bevisa din identitet för andra.", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "Om du inte verifierar så kommer du inte ha åtkomst till alla dina meddelanden och kan synas som ej betrodd för andra." } diff --git a/src/i18n/strings/ta.json b/src/i18n/strings/ta.json index 9cb046ed39..4f87230ef3 100644 --- a/src/i18n/strings/ta.json +++ b/src/i18n/strings/ta.json @@ -179,5 +179,7 @@ "Mar": "மார்ச்", "Apr": "ஏப்ரல்", "May": "மே", - "Jun": "ஜூன்" + "Jun": "ஜூன்", + "Explore rooms": "அறைகளை ஆராயுங்கள்", + "Create Account": "உங்கள் கணக்கை துவங்குங்கள்" } diff --git a/src/i18n/strings/th.json b/src/i18n/strings/th.json index 811d549d54..16a9e521c2 100644 --- a/src/i18n/strings/th.json +++ b/src/i18n/strings/th.json @@ -26,7 +26,7 @@ "Results from DuckDuckGo": "ผลจาก DuckDuckGo", "%(brand)s version:": "เวอร์ชัน %(brand)s:", "Cancel": "ยกเลิก", - "Dismiss": "ไม่สนใจ", + "Dismiss": "ปิด", "Mute": "เงียบ", "Notifications": "การแจ้งเตือน", "Operation failed": "การดำเนินการล้มเหลว", @@ -378,5 +378,10 @@ "Unable to fetch notification target list": "ไม่สามารถรับรายชื่ออุปกรณ์แจ้งเตือน", "Quote": "อ้างอิง", "With your current browser, the look and feel of the application may be completely incorrect, and some or all features may not function. If you want to try it anyway you can continue, but you are on your own in terms of any issues you may encounter!": "การแสดงผลของโปรแกรมอาจผิดพลาด ฟังก์ชันบางอย่างหรือทั้งหมดอาจไม่ทำงานในเบราว์เซอร์ปัจจุบันของคุณ หากคุณต้องการลองดำเนินการต่อ คุณต้องรับมือกับปัญหาที่อาจจะเกิดขึ้นด้วยตัวคุณเอง!", - "Checking for an update...": "กำลังตรวจหาอัปเดต..." + "Checking for an update...": "กำลังตรวจหาอัปเดต...", + "Explore rooms": "สำรวจห้อง", + "Sign In": "ลงชื่อเข้า", + "Create Account": "สร้างบัญชี", + "Add Email Address": "เพิ่มที่อยู่อีเมล", + "Confirm": "ยืนยัน" } diff --git a/src/i18n/strings/vi.json b/src/i18n/strings/vi.json index 744310675c..eebbaef3d0 100644 --- a/src/i18n/strings/vi.json +++ b/src/i18n/strings/vi.json @@ -293,5 +293,7 @@ "Enable URL previews by default for participants in this room": "Bật mặc định xem trước nội dung đường link cho mọi người trong phòng", "Room Colour": "Màu phòng chat", "Enable widget screenshots on supported widgets": "Bật widget chụp màn hình cho các widget có hỗ trợ", - "Sign In": "Đăng nhập" + "Sign In": "Đăng nhập", + "Explore rooms": "Khám phá phòng chat", + "Create Account": "Tạo tài khoản" } diff --git a/src/i18n/strings/vls.json b/src/i18n/strings/vls.json index 1172804efa..75ab903ebe 100644 --- a/src/i18n/strings/vls.json +++ b/src/i18n/strings/vls.json @@ -1443,5 +1443,7 @@ "Terms of service not accepted or the identity server is invalid.": "Dienstvoorwoardn nie anveird, of den identiteitsserver is oungeldig.", "Enter a new identity server": "Gift e nieuwen identiteitsserver in", "Remove %(email)s?": "%(email)s verwydern?", - "Remove %(phone)s?": "%(phone)s verwydern?" + "Remove %(phone)s?": "%(phone)s verwydern?", + "Explore rooms": "Gesprekkn ountdekkn", + "Create Account": "Account anmoakn" } diff --git a/src/i18n/strings/zh_Hant.json b/src/i18n/strings/zh_Hant.json index 33abcfe74e..c9bb9bb2d7 100644 --- a/src/i18n/strings/zh_Hant.json +++ b/src/i18n/strings/zh_Hant.json @@ -3251,5 +3251,42 @@ "From %(deviceName)s (%(deviceId)s) at %(ip)s": "從 %(deviceName)s (%(deviceId)s) 於 %(ip)s", "Check your devices": "檢查您的裝置", "A new login is accessing your account: %(name)s (%(deviceID)s) at %(ip)s": "新登入正在存取您的帳號:%(name)s (%(deviceID)s) 於 %(ip)s", - "You have unverified logins": "您有未驗證的登入" + "You have unverified logins": "您有未驗證的登入", + "unknown person": "不明身份的人", + "Consulting with %(transferTarget)s. Transfer to %(transferee)s": "與 %(transferTarget)s 進行協商。轉讓至 %(transferee)s", + "Message search initilisation failed": "訊息搜尋初始化失敗", + "Invite to just this room": "邀請到此聊天室", + "If you do, please note that none of your messages will be deleted, but the search experience might be degraded for a few momentswhilst the index is recreated": "如果這樣做,請注意,您的任何訊息都不會被刪除,但是在重新建立索引的同時,搜索體驗可能會降低片刻", + "Let's create a room for each of them.": "讓我們為每個主題建立一個聊天室吧。", + "Verify your identity to access encrypted messages and prove your identity to others.": "驗證您的身份來存取已加密的訊息並對其他人證明您的身份。", + "Sends the given message as a spoiler": "將指定訊息以劇透傳送", + "Review to ensure your account is safe": "請審閱以確保您的帳號安全", + "%(deviceId)s from %(ip)s": "從 %(ip)s 而來的 %(deviceId)s", + "Send and receive voice messages (in development)": "傳送與接收語音訊息(開發中)", + "Share decryption keys for room history when inviting users": "邀請使用者時分享聊天室歷史紀錄的解密金鑰", + "Manage & explore rooms": "管理與探索聊天室", + "Warn before quitting": "離開前警告", + "Quick actions": "快速動作", + "Invite messages are hidden by default. Click to show the message.": "邀請訊息預設隱藏。點擊以顯示訊息。", + "Record a voice message": "錄製語音訊息", + "Stop & send recording": "停止並傳送錄音", + "Accept on your other login…": "接受您的其他登入……", + "%(count)s people you know have already joined|other": "%(count)s 個您認識的人已加入", + "%(count)s people you know have already joined|one": "%(count)s 個您認識的人已加入", + "Add existing rooms": "新增既有聊天室", + "Adding...": "正在新增……", + "We couldn't create your DM.": "我們無法建立您的直接訊息。", + "Invited people will be able to read old messages.": "被邀請的人將能閱讀舊訊息。", + "Consult first": "先協商", + "Reset event store?": "重設活動儲存?", + "You most likely do not want to reset your event index store": "您很可能不想重設您的活動索引儲存", + "Reset event store": "重設活動儲存", + "Verify other login": "驗證其他登入", + "Avatar": "大頭貼", + "Verification requested": "已請求驗證", + "What are some things you want to discuss in %(spaceName)s?": "您想在 %(spaceName)s 中討論什麼?", + "You can add more later too, including already existing ones.": "您稍後可以新增更多內容,包含既有的。", + "Please choose a strong password": "請選擇強密碼", + "Use another login": "使用其他登入", + "Without verifying, you won’t have access to all your messages and may appear as untrusted to others.": "未經驗證,您將無法存取您的所有訊息,且可能不被其他人信任。" } diff --git a/src/indexing/BaseEventIndexManager.ts b/src/indexing/BaseEventIndexManager.ts index 2474406618..6349f31524 100644 --- a/src/indexing/BaseEventIndexManager.ts +++ b/src/indexing/BaseEventIndexManager.ts @@ -1,5 +1,5 @@ /* -Copyright 2019, 2020 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -133,6 +133,10 @@ export default abstract class BaseEventIndexManager { throw new Error("Unimplemented"); } + async isEventIndexEmpty(): Promise { + throw new Error("Unimplemented"); + } + /** * Check if our event index is empty. */ diff --git a/src/indexing/EventIndex.js b/src/indexing/EventIndex.js index 2dcdb9e3a3..1cb44f240d 100644 --- a/src/indexing/EventIndex.js +++ b/src/indexing/EventIndex.js @@ -127,8 +127,13 @@ export default class EventIndex extends EventEmitter { this.crawlerCheckpoints.push(forwardCheckpoint); } } catch (e) { - console.log("EventIndex: Error adding initial checkpoints for room", - room.roomId, backCheckpoint, forwardCheckpoint, e); + console.log( + "EventIndex: Error adding initial checkpoints for room", + room.roomId, + backCheckpoint, + forwardCheckpoint, + e, + ); } })); } @@ -379,8 +384,12 @@ export default class EventIndex extends EventEmitter { try { await indexManager.addCrawlerCheckpoint(checkpoint); } catch (e) { - console.log("EventIndex: Error adding new checkpoint for room", - room.roomId, checkpoint, e); + console.log( + "EventIndex: Error adding new checkpoint for room", + room.roomId, + checkpoint, + e, + ); } this.crawlerCheckpoints.push(checkpoint); @@ -459,7 +468,7 @@ export default class EventIndex extends EventEmitter { } catch (e) { if (e.httpStatus === 403) { console.log("EventIndex: Removing checkpoint as we don't have ", - "permissions to fetch messages from this room.", checkpoint); + "permissions to fetch messages from this room.", checkpoint); try { await indexManager.removeCrawlerCheckpoint(checkpoint); } catch (e) { @@ -589,7 +598,7 @@ export default class EventIndex extends EventEmitter { // to do here anymore. if (!newCheckpoint) { console.log("EventIndex: The server didn't return a valid ", - "new checkpoint, not continuing the crawl.", checkpoint); + "new checkpoint, not continuing the crawl.", checkpoint); continue; } @@ -599,12 +608,12 @@ export default class EventIndex extends EventEmitter { // the new checkpoint to be used by the crawler. if (eventsAlreadyAdded === true && newCheckpoint.fullCrawl !== true) { console.log("EventIndex: Checkpoint had already all events", - "added, stopping the crawl", checkpoint); + "added, stopping the crawl", checkpoint); await indexManager.removeCrawlerCheckpoint(newCheckpoint); } else { if (eventsAlreadyAdded === true) { console.log("EventIndex: Checkpoint had already all events", - "added, but continuing due to a full crawl", checkpoint); + "added, but continuing due to a full crawl", checkpoint); } this.crawlerCheckpoints.push(newCheckpoint); } @@ -776,8 +785,14 @@ export default class EventIndex extends EventEmitter { * @returns {Promise} Resolves to true if events were added to the * timeline, false otherwise. */ - async populateFileTimeline(timelineSet, timeline, room, limit = 10, - fromEvent = null, direction = EventTimeline.BACKWARDS) { + async populateFileTimeline( + timelineSet, + timeline, + room, + limit = 10, + fromEvent = null, + direction = EventTimeline.BACKWARDS, + ) { const matrixEvents = await this.loadFileEvents(room, limit, fromEvent, direction); // If this is a normal fill request, not a pagination request, we need @@ -807,7 +822,7 @@ export default class EventIndex extends EventEmitter { } console.log("EventIndex: Populating file panel with", matrixEvents.length, - "events and setting the pagination token to", paginationToken); + "events and setting the pagination token to", paginationToken); timeline.setPaginationToken(paginationToken, EventTimeline.BACKWARDS); return ret; diff --git a/src/indexing/EventIndexPeg.js b/src/indexing/EventIndexPeg.ts similarity index 94% rename from src/indexing/EventIndexPeg.js rename to src/indexing/EventIndexPeg.ts index 7004efc554..4356d882d5 100644 --- a/src/indexing/EventIndexPeg.js +++ b/src/indexing/EventIndexPeg.ts @@ -1,5 +1,5 @@ /* -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -27,12 +27,11 @@ import {SettingLevel} from "../settings/SettingLevel"; const INDEX_VERSION = 1; -class EventIndexPeg { - constructor() { - this.index = null; - this._supportIsInstalled = false; - this.error = null; - } +export class EventIndexPeg { + public index: EventIndex = null; + public error: Error = null; + + private _supportIsInstalled = false; /** * Initialize the EventIndexPeg and if event indexing is enabled initialize @@ -181,7 +180,7 @@ class EventIndexPeg { } } -if (!global.mxEventIndexPeg) { - global.mxEventIndexPeg = new EventIndexPeg(); +if (!window.mxEventIndexPeg) { + window.mxEventIndexPeg = new EventIndexPeg(); } -export default global.mxEventIndexPeg; +export default window.mxEventIndexPeg; diff --git a/src/linkify-matrix.js b/src/linkify-matrix.js index 1a40fde26f..84a131f23a 100644 --- a/src/linkify-matrix.js +++ b/src/linkify-matrix.js @@ -255,7 +255,7 @@ matrixLinkify.options = { target: function(href, type) { if (type === 'url') { const transformed = tryTransformPermalinkToLocalHref(href); - if (transformed !== href || href.match(matrixLinkify.ELEMENT_URL_PATTERN)) { + if (transformed !== href || decodeURIComponent(href).match(matrixLinkify.ELEMENT_URL_PATTERN)) { return null; } else { return '_blank'; diff --git a/src/mjolnir/BanList.js b/src/mjolnir/BanList.ts similarity index 100% rename from src/mjolnir/BanList.js rename to src/mjolnir/BanList.ts diff --git a/src/mjolnir/ListRule.js b/src/mjolnir/ListRule.ts similarity index 100% rename from src/mjolnir/ListRule.js rename to src/mjolnir/ListRule.ts diff --git a/src/mjolnir/Mjolnir.js b/src/mjolnir/Mjolnir.ts similarity index 100% rename from src/mjolnir/Mjolnir.js rename to src/mjolnir/Mjolnir.ts diff --git a/src/stores/CustomRoomTagStore.js b/src/stores/CustomRoomTagStore.js index edfc0003cf..55c9699f7a 100644 --- a/src/stores/CustomRoomTagStore.js +++ b/src/stores/CustomRoomTagStore.js @@ -124,15 +124,15 @@ class CustomRoomTagStore extends EventEmitter { const tags = Object.assign({}, oldTags, tag); this._setState({tags}); } + break; } - break; case 'on_client_not_viable': case 'on_logged_out': { // we assume to always have a tags object in the state this._state = {tags: {}}; RoomListStore.instance.off(LISTS_UPDATE_EVENT, this._onListsUpdated); + break; } - break; } } diff --git a/src/stores/GroupFilterOrderStore.js b/src/stores/GroupFilterOrderStore.js index 492322146e..b18abaa001 100644 --- a/src/stores/GroupFilterOrderStore.js +++ b/src/stores/GroupFilterOrderStore.js @@ -168,7 +168,7 @@ class GroupFilterOrderStore extends Store { Analytics.trackEvent('FilterStore', 'select_tag'); } - break; + break; case 'deselect_tags': if (payload.tag) { // if a tag is passed, only deselect that tag @@ -181,7 +181,7 @@ class GroupFilterOrderStore extends Store { }); } Analytics.trackEvent('FilterStore', 'deselect_tags'); - break; + break; case 'on_client_not_viable': case 'on_logged_out': { // Reset state without pushing an update to the view, which generally assumes that @@ -207,8 +207,8 @@ class GroupFilterOrderStore extends Store { groupIds.forEach(groupId => { const rooms = GroupStore.getGroupRooms(groupId) - .map(r => client.getRoom(r.roomId)) // to Room objects - .filter(r => r !== null && r !== undefined); // filter out rooms we haven't joined from the group + .map(r => client.getRoom(r.roomId)) // to Room objects + .filter(r => r !== null && r !== undefined); // filter out rooms we haven't joined from the group const badge = rooms && RoomNotifs.aggregateNotificationCount(rooms); changedBadges[groupId] = (badge && badge.count !== 0) ? badge : undefined; }); diff --git a/src/stores/RoomViewStore.tsx b/src/stores/RoomViewStore.tsx index 601c77cdf3..fe2e0a66b2 100644 --- a/src/stores/RoomViewStore.tsx +++ b/src/stores/RoomViewStore.tsx @@ -60,6 +60,10 @@ const INITIAL_STATE = { replyingToEvent: null, shouldPeek: false, + + viaServers: [], + + wasContextSwitch: false, }; /** @@ -113,6 +117,8 @@ class RoomViewStore extends Store { this.setState({ roomId: null, roomAlias: null, + viaServers: [], + wasContextSwitch: false, }); break; case 'view_room_error': @@ -191,6 +197,8 @@ class RoomViewStore extends Store { replyingToEvent: null, // pull the user out of Room Settings isEditingSettings: false, + viaServers: payload.via_servers, + wasContextSwitch: payload.context_switch, }; // Allow being given an event to be replied to when switching rooms but sanity check its for this room @@ -226,6 +234,8 @@ class RoomViewStore extends Store { roomAlias: payload.room_alias, roomLoading: true, roomLoadError: null, + viaServers: payload.via_servers, + wasContextSwitch: payload.context_switch, }); try { const result = await MatrixClientPeg.get().getRoomIdForAlias(payload.room_alias); @@ -251,6 +261,8 @@ class RoomViewStore extends Store { room_alias: payload.room_alias, auto_join: payload.auto_join, oob_data: payload.oob_data, + viaServers: payload.via_servers, + wasContextSwitch: payload.context_switch, }); } } @@ -272,9 +284,10 @@ class RoomViewStore extends Store { const cli = MatrixClientPeg.get(); const address = this.state.roomAlias || this.state.roomId; + const viaServers = this.state.viaServers || []; try { await retry(() => cli.joinRoom(address, { - viaServers: payload.via_servers, + viaServers, ...payload.opts, }), NUM_JOIN_RETRY, (err) => { // if we received a Gateway timeout then retry @@ -419,6 +432,10 @@ class RoomViewStore extends Store { public shouldPeek() { return this.state.shouldPeek; } + + public getWasContextSwitch() { + return this.state.wasContextSwitch; + } } let singletonRoomViewStore = null; diff --git a/src/stores/SpaceStore.tsx b/src/stores/SpaceStore.tsx index 52060f86a5..ec6227e45e 100644 --- a/src/stores/SpaceStore.tsx +++ b/src/stores/SpaceStore.tsx @@ -46,11 +46,14 @@ export const HOME_SPACE = Symbol("home-space"); export const SUGGESTED_ROOMS = Symbol("suggested-rooms"); export const UPDATE_TOP_LEVEL_SPACES = Symbol("top-level-spaces"); +export const UPDATE_INVITED_SPACES = Symbol("invited-spaces"); export const UPDATE_SELECTED_SPACE = Symbol("selected-space"); // Space Room ID/HOME_SPACE will be emitted when a Space's children change const MAX_SUGGESTED_ROOMS = 20; +const getSpaceContextKey = (space?: Room) => `mx_space_context_${space?.roomId || "home_space"}`; + const partitionSpacesAndRooms = (arr: Room[]): [Room[], Room[]] => { // [spaces, rooms] return arr.reduce((result, room: Room) => { result[room.isSpaceRoom() ? 0 : 1].push(room); @@ -91,6 +94,11 @@ export class SpaceStoreClass extends AsyncStoreWithClient { // The space currently selected in the Space Panel - if null then `Home` is selected private _activeSpace?: Room = null; private _suggestedRooms: ISpaceSummaryRoom[] = []; + private _invitedSpaces = new Set(); + + public get invitedSpaces(): Room[] { + return Array.from(this._invitedSpaces); + } public get spacePanelSpaces(): Room[] { return this.rootSpaces; @@ -104,13 +112,41 @@ export class SpaceStoreClass extends AsyncStoreWithClient { return this._suggestedRooms; } - public async setActiveSpace(space: Room | null) { - if (space === this.activeSpace) return; + public async setActiveSpace(space: Room | null, contextSwitch = true) { + if (space === this.activeSpace || (space && !space?.isSpaceRoom())) return; this._activeSpace = space; this.emit(UPDATE_SELECTED_SPACE, this.activeSpace); this.emit(SUGGESTED_ROOMS, this._suggestedRooms = []); + if (contextSwitch) { + // view last selected room from space + const roomId = window.localStorage.getItem(getSpaceContextKey(this.activeSpace)); + + // if the space being selected is an invite then always view that invite + // else if the last viewed room in this space is joined then view that + // else view space home or home depending on what is being clicked on + if (space?.getMyMembership !== "invite" && + this.matrixClient?.getRoom(roomId)?.getMyMembership() === "join" + ) { + defaultDispatcher.dispatch({ + action: "view_room", + room_id: roomId, + context_switch: true, + }); + } else if (space) { + defaultDispatcher.dispatch({ + action: "view_room", + room_id: space.roomId, + context_switch: true, + }); + } else { + defaultDispatcher.dispatch({ + action: "view_home_page", + }); + } + } + // persist space selected if (space) { window.localStorage.setItem(ACTIVE_SPACE_LS_KEY, space.roomId); @@ -159,7 +195,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { const childEvents = room?.currentState.getStateEvents(EventType.SpaceChild).filter(ev => ev.getContent()?.via); return sortBy(childEvents, getOrder) .map(ev => this.matrixClient.getRoom(ev.getStateKey())) - .filter(room => room?.getMyMembership() === "join") || []; + .filter(room => room?.getMyMembership() === "join" || room?.getMyMembership() === "invite") || []; } public getChildRooms(spaceId: string): Room[] { @@ -167,7 +203,8 @@ export class SpaceStoreClass extends AsyncStoreWithClient { } public getChildSpaces(spaceId: string): Room[] { - return this.getChildren(spaceId).filter(r => r.isSpaceRoom()); + // don't show invited subspaces as they surface at the top level for better visibility + return this.getChildren(spaceId).filter(r => r.isSpaceRoom() && r.getMyMembership() === "join"); } public getParents(roomId: string, canonicalOnly = false): Room[] { @@ -189,25 +226,27 @@ export class SpaceStoreClass extends AsyncStoreWithClient { return sortBy(parents, r => r.roomId)?.[0] || null; } - public getSpaces = () => { - return this.matrixClient.getRooms().filter(r => r.isSpaceRoom() && r.getMyMembership() === "join"); - }; - public getSpaceFilteredRoomIds = (space: Room | null): Set => { return this.spaceFilteredRooms.get(space?.roomId || HOME_SPACE) || new Set(); }; private rebuild = throttle(() => { - // get all most-upgraded rooms & spaces except spaces which have been left (historical) - const visibleRooms = this.matrixClient.getVisibleRooms().filter(r => { - return !r.isSpaceRoom() || r.getMyMembership() === "join"; - }); + const [visibleSpaces, visibleRooms] = partitionSpacesAndRooms(this.matrixClient.getVisibleRooms()); + const [joinedSpaces, invitedSpaces] = visibleSpaces.reduce((arr, s) => { + if (s.getMyMembership() === "join") { + arr[0].push(s); + } else if (s.getMyMembership() === "invite") { + arr[1].push(s); + } + return arr; + }, [[], []]); - const unseenChildren = new Set(visibleRooms); + // exclude invited spaces from unseenChildren as they will be forcibly shown at the top level of the treeview + const unseenChildren = new Set([...visibleRooms, ...joinedSpaces]); const backrefs = new EnhancedMap>(); // Sort spaces by room ID to force the cycle breaking to be deterministic - const spaces = sortBy(visibleRooms.filter(r => r.isSpaceRoom()), space => space.roomId); + const spaces = sortBy(joinedSpaces, space => space.roomId); // TODO handle cleaning up links when a Space is removed spaces.forEach(space => { @@ -271,6 +310,10 @@ export class SpaceStoreClass extends AsyncStoreWithClient { this.onRoomsUpdate(); // TODO only do this if a change has happened this.emit(UPDATE_TOP_LEVEL_SPACES, this.spacePanelSpaces); + + // build initial state of invited spaces as we would have missed the emitted events about the room at launch + this._invitedSpaces = new Set(invitedSpaces); + this.emit(UPDATE_INVITED_SPACES, this.invitedSpaces); }, 100, {trailing: true, leading: true}); onSpaceUpdate = () => { @@ -278,6 +321,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { } private showInHomeSpace = (room: Room) => { + if (room.isSpaceRoom()) return false; return !this.parentMap.get(room.roomId)?.size // put all orphaned rooms in the Home Space || DMRoomMap.shared().getUserIdForRoomId(room.roomId) // put all DMs in the Home Space || RoomListStore.instance.getTagsForRoom(room).includes(DefaultTagID.Favourite) // show all favourites @@ -308,8 +352,8 @@ export class SpaceStoreClass extends AsyncStoreWithClient { const oldFilteredRooms = this.spaceFilteredRooms; this.spaceFilteredRooms = new Map(); - // put all invites (rooms & spaces) in the Home Space - const invites = this.matrixClient.getRooms().filter(r => r.getMyMembership() === "invite"); + // put all room invites in the Home Space + const invites = visibleRooms.filter(r => !r.isSpaceRoom() && r.getMyMembership() === "invite"); this.spaceFilteredRooms.set(HOME_SPACE, new Set(invites.map(room => room.roomId))); visibleRooms.forEach(room => { @@ -362,31 +406,43 @@ export class SpaceStoreClass extends AsyncStoreWithClient { this.spaceFilteredRooms.forEach((roomIds, s) => { // Update NotificationStates - const rooms = this.matrixClient.getRooms().filter(room => roomIds.has(room.roomId)); - this.getNotificationState(s)?.setRooms(rooms); + this.getNotificationState(s)?.setRooms(visibleRooms.filter(room => roomIds.has(room.roomId))); }); }, 100, {trailing: true, leading: true}); - private onRoom = (room: Room) => { - if (room?.isSpaceRoom()) { - this.onSpaceUpdate(); - this.emit(room.roomId); - } else { + private onRoom = (room: Room, newMembership?: string, oldMembership?: string) => { + const membership = newMembership || room.getMyMembership(); + + if (!room.isSpaceRoom()) { // this.onRoomUpdate(room); this.onRoomsUpdate(); - } - if (room.getMyMembership() === "join") { - if (!room.isSpaceRoom()) { + if (membership === "join") { + // the user just joined a room, remove it from the suggested list if it was there const numSuggestedRooms = this._suggestedRooms.length; this._suggestedRooms = this._suggestedRooms.filter(r => r.room_id !== room.roomId); if (numSuggestedRooms !== this._suggestedRooms.length) { this.emit(SUGGESTED_ROOMS, this._suggestedRooms); } - } else if (room.roomId === RoomViewStore.getRoomId()) { - // if the user was looking at the space and then joined: select that space - this.setActiveSpace(room); } + return; + } + + // Space + if (membership === "invite") { + this._invitedSpaces.add(room); + this.emit(UPDATE_INVITED_SPACES, this.invitedSpaces); + } else if (oldMembership === "invite" && membership !== "join") { + this._invitedSpaces.delete(room); + this.emit(UPDATE_INVITED_SPACES, this.invitedSpaces); + } else { + this.onSpaceUpdate(); + this.emit(room.roomId); + } + + if (membership === "join" && room.roomId === RoomViewStore.getRoomId()) { + // if the user was looking at the space and then joined: select that space + this.setActiveSpace(room); } }; @@ -421,11 +477,11 @@ export class SpaceStoreClass extends AsyncStoreWithClient { } }; - private onRoomAccountData = (ev: MatrixEvent, room: Room, lastEvent: MatrixEvent) => { + private onRoomAccountData = (ev: MatrixEvent, room: Room, lastEvent?: MatrixEvent) => { if (ev.getType() === EventType.Tag && !room.isSpaceRoom()) { // If the room was in favourites and now isn't or the opposite then update its position in the trees - const oldTags = lastEvent.getContent()?.tags; - const newTags = ev.getContent()?.tags; + const oldTags = lastEvent?.getContent()?.tags || {}; + const newTags = ev.getContent()?.tags || {}; if (!!oldTags[DefaultTagID.Favourite] !== !!newTags[DefaultTagID.Favourite]) { this.onRoomUpdate(room); } @@ -450,6 +506,17 @@ export class SpaceStoreClass extends AsyncStoreWithClient { } }; + protected async reset() { + this.rootSpaces = []; + this.orphanedRooms = new Set(); + this.parentMap = new EnhancedMap(); + this.notificationStateMap = new Map(); + this.spaceFilteredRooms = new Map(); + this._activeSpace = null; + this._suggestedRooms = []; + this._invitedSpaces = new Set(); + } + protected async onNotReady() { if (!SettingsStore.getValue("feature_spaces")) return; if (this.matrixClient) { @@ -459,7 +526,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { this.matrixClient.removeListener("Room.accountData", this.onRoomAccountData); this.matrixClient.removeListener("accountData", this.onAccountData); } - await this.reset({}); + await this.reset(); } protected async onReady() { @@ -488,24 +555,31 @@ export class SpaceStoreClass extends AsyncStoreWithClient { case "view_room": { const room = this.matrixClient?.getRoom(payload.room_id); - if (room?.getMyMembership() === "join") { - if (room.isSpaceRoom()) { - this.setActiveSpace(room); - } else if (!this.spaceFilteredRooms.get(this._activeSpace?.roomId || HOME_SPACE).has(room.roomId)) { - // TODO maybe reverse these first 2 clauses once space panel active is fixed - let parent = this.rootSpaces.find(s => this.spaceFilteredRooms.get(s.roomId)?.has(room.roomId)); - if (!parent) { - parent = this.getCanonicalParent(room.roomId); - } - if (!parent) { - const parents = Array.from(this.parentMap.get(room.roomId) || []); - parent = parents.find(p => this.matrixClient.getRoom(p)); - } - if (parent) { - this.setActiveSpace(parent); - } + // Don't auto-switch rooms when reacting to a context-switch + // as this is not helpful and can create loops of rooms/space switching + if (!room || payload.context_switch) break; + + if (room.isSpaceRoom()) { + // Don't context switch when navigating to the space room + // as it will cause you to end up in the wrong room + this.setActiveSpace(room, false); + } else if (!this.getSpaceFilteredRoomIds(this.activeSpace).has(room.roomId)) { + let parent = this.getCanonicalParent(room.roomId); + if (!parent) { + parent = this.rootSpaces.find(s => this.spaceFilteredRooms.get(s.roomId)?.has(room.roomId)); } + if (!parent) { + const parents = Array.from(this.parentMap.get(room.roomId) || []); + parent = parents.find(p => this.matrixClient.getRoom(p)); + } + // don't trigger a context switch when we are switching a space to match the chosen room + this.setActiveSpace(parent || null, false); } + + // Persist last viewed room from a space + // we don't await setActiveSpace above as we only care about this.activeSpace being up to date + // synchronously for the below code - everything else can and should be async. + window.localStorage.setItem(getSpaceContextKey(this.activeSpace), payload.room_id); break; } case "after_leave_room": @@ -525,6 +599,28 @@ export class SpaceStoreClass extends AsyncStoreWithClient { this.notificationStateMap.set(key, state); return state; } + + // traverse space tree with DFS calling fn on each space including the given root one, + // if includeRooms is true then fn will be called on each leaf room, if it is present in multiple sub-spaces + // then fn will be called with it multiple times. + public traverseSpace( + spaceId: string, + fn: (roomId: string) => void, + includeRooms = false, + parentPath?: Set, + ) { + if (parentPath && parentPath.has(spaceId)) return; // prevent cycles + + fn(spaceId); + + const newPath = new Set(parentPath).add(spaceId); + const [childSpaces, childRooms] = partitionSpacesAndRooms(this.getChildren(spaceId)); + + if (includeRooms) { + childRooms.forEach(r => fn(r.roomId)); + } + childSpaces.forEach(s => this.traverseSpace(s.roomId, fn, includeRooms, newPath)); + } } export default class SpaceStore { diff --git a/src/stores/TypingStore.js b/src/stores/TypingStore.ts similarity index 84% rename from src/stores/TypingStore.js rename to src/stores/TypingStore.ts index e86d698eac..d5177a33a0 100644 --- a/src/stores/TypingStore.js +++ b/src/stores/TypingStore.ts @@ -1,5 +1,5 @@ /* -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2019, 2021 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. @@ -25,15 +25,23 @@ const TYPING_SERVER_TIMEOUT = 30000; * Tracks typing state for users. */ export default class TypingStore { + private typingStates: { + [roomId: string]: { + isTyping: boolean, + userTimer: Timer, + serverTimer: Timer, + }, + }; + constructor() { this.reset(); } static sharedInstance(): TypingStore { - if (global.mxTypingStore === undefined) { - global.mxTypingStore = new TypingStore(); + if (window.mxTypingStore === undefined) { + window.mxTypingStore = new TypingStore(); } - return global.mxTypingStore; + return window.mxTypingStore; } /** @@ -41,7 +49,7 @@ export default class TypingStore { * MatrixClientPeg client changes. */ reset() { - this._typingStates = { + this.typingStates = { // "roomId": { // isTyping: bool, // Whether the user is typing or not // userTimer: Timer, // Local timeout for "user has stopped typing" @@ -59,14 +67,14 @@ export default class TypingStore { if (!SettingsStore.getValue('sendTypingNotifications')) return; if (SettingsStore.getValue('lowBandwidth')) return; - let currentTyping = this._typingStates[roomId]; + let currentTyping = this.typingStates[roomId]; if ((!isTyping && !currentTyping) || (currentTyping && currentTyping.isTyping === isTyping)) { // No change in state, so don't do anything. We'll let the timer run its course. return; } if (!currentTyping) { - currentTyping = this._typingStates[roomId] = { + currentTyping = this.typingStates[roomId] = { isTyping: isTyping, serverTimer: new Timer(TYPING_SERVER_TIMEOUT), userTimer: new Timer(TYPING_USER_TIMEOUT), @@ -78,7 +86,7 @@ export default class TypingStore { if (isTyping) { if (!currentTyping.serverTimer.isRunning()) { currentTyping.serverTimer.restart().finished().then(() => { - const currentTyping = this._typingStates[roomId]; + const currentTyping = this.typingStates[roomId]; if (currentTyping) currentTyping.isTyping = false; // The server will (should) time us out on typing, so we don't diff --git a/src/stores/VoiceRecordingStore.ts b/src/stores/VoiceRecordingStore.ts index e1685de529..8ee44359fb 100644 --- a/src/stores/VoiceRecordingStore.ts +++ b/src/stores/VoiceRecordingStore.ts @@ -73,10 +73,10 @@ export class VoiceRecordingStore extends AsyncStoreWithClient { */ public disposeRecording(): Promise { if (this.state.recording) { - // Stop for good measure, but completely async because we're not concerned with this - // passing or failing. - this.state.recording.stop().catch(e => console.error("Error stopping recording", e)); + this.state.recording.destroy(); // stops internally } return this.updateState({recording: null}); } } + +window.mxVoiceRecordingStore = VoiceRecordingStore.instance; diff --git a/src/stores/WidgetEchoStore.js b/src/stores/WidgetEchoStore.ts similarity index 71% rename from src/stores/WidgetEchoStore.js rename to src/stores/WidgetEchoStore.ts index 3aef1beb3e..09120d6108 100644 --- a/src/stores/WidgetEchoStore.js +++ b/src/stores/WidgetEchoStore.ts @@ -1,6 +1,5 @@ /* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2018-2021 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. @@ -16,6 +15,8 @@ limitations under the License. */ import EventEmitter from 'events'; +import { IWidget } from 'matrix-widget-api'; +import MatrixEvent from "matrix-js-sdk/src/models/event"; import {WidgetType} from "../widgets/WidgetType"; /** @@ -23,14 +24,20 @@ import {WidgetType} from "../widgets/WidgetType"; * proxying through state from the js-sdk. */ class WidgetEchoStore extends EventEmitter { + private roomWidgetEcho: { + [roomId: string]: { + [widgetId: string]: IWidget, + }, + }; + constructor() { super(); - this._roomWidgetEcho = { + this.roomWidgetEcho = { // Map as below. Object is the content of the widget state event, // so for widgets that have been deleted locally, the object is empty. // roomId: { - // widgetId: [object] + // widgetId: IWidget // } }; } @@ -42,14 +49,14 @@ class WidgetEchoStore extends EventEmitter { * and we don't really need the actual widget events anyway since we just want to * show a spinner / prevent widgets being added twice. * - * @param {Room} roomId The ID of the room to get widgets for + * @param {string} roomId The ID of the room to get widgets for * @param {MatrixEvent[]} currentRoomWidgets Current widgets for the room * @returns {MatrixEvent[]} List of widgets in the room, minus any pending removal */ - getEchoedRoomWidgets(roomId, currentRoomWidgets) { + getEchoedRoomWidgets(roomId: string, currentRoomWidgets: MatrixEvent[]): MatrixEvent[] { const echoedWidgets = []; - const roomEchoState = Object.assign({}, this._roomWidgetEcho[roomId]); + const roomEchoState = Object.assign({}, this.roomWidgetEcho[roomId]); for (const w of currentRoomWidgets) { const widgetId = w.getStateKey(); @@ -65,8 +72,8 @@ class WidgetEchoStore extends EventEmitter { return echoedWidgets; } - roomHasPendingWidgetsOfType(roomId, currentRoomWidgets, type: WidgetType) { - const roomEchoState = Object.assign({}, this._roomWidgetEcho[roomId]); + roomHasPendingWidgetsOfType(roomId: string, currentRoomWidgets: MatrixEvent[], type?: WidgetType): boolean { + const roomEchoState = Object.assign({}, this.roomWidgetEcho[roomId]); // any widget IDs that are already in the room are not pending, so // echoes for them don't count as pending. @@ -85,20 +92,20 @@ class WidgetEchoStore extends EventEmitter { } } - roomHasPendingWidgets(roomId, currentRoomWidgets) { + roomHasPendingWidgets(roomId: string, currentRoomWidgets: MatrixEvent[]): boolean { return this.roomHasPendingWidgetsOfType(roomId, currentRoomWidgets); } - setRoomWidgetEcho(roomId, widgetId, state) { - if (this._roomWidgetEcho[roomId] === undefined) this._roomWidgetEcho[roomId] = {}; + setRoomWidgetEcho(roomId: string, widgetId: string, state: IWidget) { + if (this.roomWidgetEcho[roomId] === undefined) this.roomWidgetEcho[roomId] = {}; - this._roomWidgetEcho[roomId][widgetId] = state; + this.roomWidgetEcho[roomId][widgetId] = state; this.emit('update', roomId, widgetId); } - removeRoomWidgetEcho(roomId, widgetId) { - delete this._roomWidgetEcho[roomId][widgetId]; - if (Object.keys(this._roomWidgetEcho[roomId]).length === 0) delete this._roomWidgetEcho[roomId]; + removeRoomWidgetEcho(roomId: string, widgetId: string) { + delete this.roomWidgetEcho[roomId][widgetId]; + if (Object.keys(this.roomWidgetEcho[roomId]).length === 0) delete this.roomWidgetEcho[roomId]; this.emit('update', roomId, widgetId); } } diff --git a/src/stores/notifications/StaticNotificationState.ts b/src/stores/notifications/StaticNotificationState.ts index 0392ed3716..b18aa78e0f 100644 --- a/src/stores/notifications/StaticNotificationState.ts +++ b/src/stores/notifications/StaticNotificationState.ts @@ -18,6 +18,8 @@ import { NotificationColor } from "./NotificationColor"; import { NotificationState } from "./NotificationState"; export class StaticNotificationState extends NotificationState { + public static readonly RED_EXCLAMATION = StaticNotificationState.forSymbol("!", NotificationColor.Red); + constructor(symbol: string, count: number, color: NotificationColor) { super(); this._symbol = symbol; diff --git a/src/stores/room-list/RoomListStore.ts b/src/stores/room-list/RoomListStore.ts index 88df05b5d0..6e9216423a 100644 --- a/src/stores/room-list/RoomListStore.ts +++ b/src/stores/room-list/RoomListStore.ts @@ -599,13 +599,13 @@ export class RoomListStoreClass extends AsyncStoreWithClient { private getPlausibleRooms(): Room[] { if (!this.matrixClient) return []; - let rooms = [ - ...this.matrixClient.getVisibleRooms(), - // also show space invites in the room list - ...this.matrixClient.getRooms().filter(r => r.isSpaceRoom() && r.getMyMembership() === "invite"), - ].filter(r => VisibilityProvider.instance.isRoomVisible(r)); + let rooms = this.matrixClient.getVisibleRooms().filter(r => VisibilityProvider.instance.isRoomVisible(r)); - if (this.prefilterConditions.length > 0) { + // if spaces are enabled only consider the prefilter conditions when there are no runtime conditions + // for the search all spaces feature + if (this.prefilterConditions.length > 0 + && (!SettingsStore.getValue("feature_spaces") || !this.filterConditions.length) + ) { rooms = rooms.filter(r => { for (const filter of this.prefilterConditions) { if (!filter.isVisible(r)) { @@ -679,6 +679,10 @@ export class RoomListStoreClass extends AsyncStoreWithClient { if (this.algorithm) { this.algorithm.addFilterCondition(filter); } + // Runtime filters with spaces disable prefiltering for the search all spaces effect + if (SettingsStore.getValue("feature_spaces")) { + promise = this.recalculatePrefiltering(); + } } promise.then(() => this.updateFn.trigger()); } @@ -702,6 +706,10 @@ export class RoomListStoreClass extends AsyncStoreWithClient { if (this.algorithm) { this.algorithm.removeFilterCondition(filter); + // Runtime filters with spaces disable prefiltering for the search all spaces effect + if (SettingsStore.getValue("feature_spaces")) { + promise = this.recalculatePrefiltering(); + } } } idx = this.prefilterConditions.indexOf(filter); diff --git a/src/stores/room-list/SpaceWatcher.ts b/src/stores/room-list/SpaceWatcher.ts index d26f563a91..13e1d83901 100644 --- a/src/stores/room-list/SpaceWatcher.ts +++ b/src/stores/room-list/SpaceWatcher.ts @@ -28,12 +28,22 @@ export class SpaceWatcher { private activeSpace: Room = SpaceStore.instance.activeSpace; constructor(private store: RoomListStoreClass) { - this.filter.updateSpace(this.activeSpace); // get the filter into a consistent state + this.updateFilter(); // get the filter into a consistent state store.addFilter(this.filter); SpaceStore.instance.on(UPDATE_SELECTED_SPACE, this.onSelectedSpaceUpdated); } - private onSelectedSpaceUpdated = (activeSpace) => { - this.filter.updateSpace(this.activeSpace = activeSpace); + private onSelectedSpaceUpdated = (activeSpace: Room) => { + this.activeSpace = activeSpace; + this.updateFilter(); + }; + + private updateFilter = () => { + if (this.activeSpace) { + SpaceStore.instance.traverseSpace(this.activeSpace.roomId, roomId => { + this.store.matrixClient?.getRoom(roomId)?.loadMembersIfNeeded(); + }); + } + this.filter.updateSpace(this.activeSpace); }; } diff --git a/src/stores/room-list/filters/SpaceFilterCondition.ts b/src/stores/room-list/filters/SpaceFilterCondition.ts index ad0ab88868..43bdcb3879 100644 --- a/src/stores/room-list/filters/SpaceFilterCondition.ts +++ b/src/stores/room-list/filters/SpaceFilterCondition.ts @@ -42,10 +42,16 @@ export class SpaceFilterCondition extends EventEmitter implements IFilterConditi private onStoreUpdate = async (): Promise => { const beforeRoomIds = this.roomIds; - this.roomIds = SpaceStore.instance.getSpaceFilteredRoomIds(this.space); + // clone the set as it may be mutated by the space store internally + this.roomIds = new Set(SpaceStore.instance.getSpaceFilteredRoomIds(this.space)); if (setHasDiff(beforeRoomIds, this.roomIds)) { this.emit(FILTER_CHANGED); + // XXX: Room List Store has a bug where updates to the pre-filter during a local echo of a + // tags transition seem to be ignored, so refire in the next tick to work around it + setImmediate(() => { + this.emit(FILTER_CHANGED); + }); } }; diff --git a/src/stores/room-list/filters/VisibilityProvider.ts b/src/stores/room-list/filters/VisibilityProvider.ts index 388bb061e3..f212b1f9d9 100644 --- a/src/stores/room-list/filters/VisibilityProvider.ts +++ b/src/stores/room-list/filters/VisibilityProvider.ts @@ -37,7 +37,11 @@ export class VisibilityProvider { await VoipUserMapper.sharedInstance().onNewInvitedRoom(room); } - public isRoomVisible(room: Room): boolean { + public isRoomVisible(room?: Room): boolean { + if (!room) { + return false; + } + if ( CallHandler.sharedInstance().getSupportsVirtualRooms() && VoipUserMapper.sharedInstance().isVirtualRoom(room) diff --git a/src/stores/room-list/previews/MessageEventPreview.ts b/src/stores/room-list/previews/MessageEventPreview.ts index deed7dcf2c..b900afc13f 100644 --- a/src/stores/room-list/previews/MessageEventPreview.ts +++ b/src/stores/room-list/previews/MessageEventPreview.ts @@ -20,7 +20,7 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { _t } from "../../../languageHandler"; import { getSenderName, isSelf, shouldPrefixMessagesIn } from "./utils"; import ReplyThread from "../../../components/views/elements/ReplyThread"; -import { sanitizedHtmlNodeInnerText } from "../../../HtmlUtils"; +import { getHtmlText } from "../../../HtmlUtils"; export class MessageEventPreview implements IPreview { public getTextFor(event: MatrixEvent, tagId?: TagID): string { @@ -55,7 +55,7 @@ export class MessageEventPreview implements IPreview { } if (hasHtml) { - body = sanitizedHtmlNodeInnerText(body); + body = getHtmlText(body); } if (msgtype === 'm.emote') { diff --git a/src/utils/AutoDiscoveryUtils.js b/src/utils/AutoDiscoveryUtils.tsx similarity index 91% rename from src/utils/AutoDiscoveryUtils.js rename to src/utils/AutoDiscoveryUtils.tsx index 614aa4cea8..e3a7fd2d0b 100644 --- a/src/utils/AutoDiscoveryUtils.js +++ b/src/utils/AutoDiscoveryUtils.tsx @@ -1,6 +1,5 @@ /* -Copyright 2019 New Vector Ltd -Copyright 2019, 2020 The Matrix.org Foundation C.I.C. +Copyright 2019-2021 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. @@ -15,13 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import {AutoDiscovery} from "matrix-js-sdk/src/autodiscovery"; import {_t, _td, newTranslatableError} from "../languageHandler"; import {makeType} from "./TypeUtils"; import SdkConfig from '../SdkConfig'; -const LIVELINESS_DISCOVERY_ERRORS = [ +const LIVELINESS_DISCOVERY_ERRORS: string[] = [ AutoDiscovery.ERROR_INVALID_HOMESERVER, AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER, ]; @@ -40,17 +39,23 @@ export class ValidatedServerConfig { warning: string; } +export interface IAuthComponentState { + serverIsAlive: boolean; + serverErrorIsFatal: boolean; + serverDeadError?: ReactNode; +} + export default class AutoDiscoveryUtils { /** * Checks if a given error or error message is considered an error * relating to the liveliness of the server. Must be an error returned * from this AutoDiscoveryUtils class. - * @param {string|Error} error The error to check + * @param {string | Error} error The error to check * @returns {boolean} True if the error is a liveliness error. */ - static isLivelinessError(error: string|Error): boolean { + static isLivelinessError(error: string | Error): boolean { if (!error) return false; - return !!LIVELINESS_DISCOVERY_ERRORS.find(e => e === error || e === error.message); + return !!LIVELINESS_DISCOVERY_ERRORS.find(e => typeof error === "string" ? e === error : e === error.message); } /** @@ -61,7 +66,7 @@ export default class AutoDiscoveryUtils { * implementation for known values. * @returns {*} The state for the component, given the error. */ - static authComponentStateForError(err: string | Error | null, pageName = "login"): Object { + static authComponentStateForError(err: string | Error | null, pageName = "login"): IAuthComponentState { if (!err) { return { serverIsAlive: true, @@ -70,7 +75,7 @@ export default class AutoDiscoveryUtils { }; } let title = _t("Cannot reach homeserver"); - let body = _t("Ensure you have a stable internet connection, or get in touch with the server admin"); + let body: ReactNode = _t("Ensure you have a stable internet connection, or get in touch with the server admin"); if (!AutoDiscoveryUtils.isLivelinessError(err)) { const brand = SdkConfig.get().brand; title = _t("Your %(brand)s is misconfigured", { brand }); @@ -92,7 +97,7 @@ export default class AutoDiscoveryUtils { } let isFatalError = true; - const errorMessage = err.message ? err.message : err; + const errorMessage = typeof err === "string" ? err : err.message; if (errorMessage === AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER) { isFatalError = false; title = _t("Cannot reach identity server"); @@ -141,7 +146,10 @@ export default class AutoDiscoveryUtils { * @returns {Promise} Resolves to the validated configuration. */ static async validateServerConfigWithStaticUrls( - homeserverUrl: string, identityUrl: string, syntaxOnly = false): ValidatedServerConfig { + homeserverUrl: string, + identityUrl?: string, + syntaxOnly = false, + ): Promise { if (!homeserverUrl) { throw newTranslatableError(_td("No homeserver URL provided")); } @@ -171,7 +179,7 @@ export default class AutoDiscoveryUtils { * @param {string} serverName The homeserver domain name (eg: "matrix.org") to validate. * @returns {Promise} Resolves to the validated configuration. */ - static async validateServerName(serverName: string): ValidatedServerConfig { + static async validateServerName(serverName: string): Promise { const result = await AutoDiscovery.findClientConfig(serverName); return AutoDiscoveryUtils.buildValidatedConfigFromDiscovery(serverName, result); } diff --git a/src/utils/DMRoomMap.ts b/src/utils/DMRoomMap.ts index e49b74c380..b166674043 100644 --- a/src/utils/DMRoomMap.ts +++ b/src/utils/DMRoomMap.ts @@ -55,6 +55,15 @@ export default class DMRoomMap { return DMRoomMap.sharedInstance; } + /** + * Set the shared instance to the instance supplied + * Used by tests + * @param inst the new shared instance + */ + public static setShared(inst: DMRoomMap) { + DMRoomMap.sharedInstance = inst; + } + /** * Returns a shared instance of the class * that uses the singleton matrix client diff --git a/src/utils/ErrorUtils.js b/src/utils/ErrorUtils.js index 2c6acd5503..b5bd5b0af0 100644 --- a/src/utils/ErrorUtils.js +++ b/src/utils/ErrorUtils.js @@ -49,12 +49,6 @@ export function messageForResourceLimitError(limitType, adminContact, strings, e } } -export function messageForSendError(errorData) { - if (errorData.errcode === "M_TOO_LARGE") { - return _t("The message you are trying to send is too large."); - } -} - export function messageForSyncError(err) { if (err.errcode === 'M_RESOURCE_LIMIT_EXCEEDED') { const limitError = messageForResourceLimitError( diff --git a/src/utils/MatrixGlob.js b/src/utils/MatrixGlob.ts similarity index 100% rename from src/utils/MatrixGlob.js rename to src/utils/MatrixGlob.ts diff --git a/src/utils/MegolmExportEncryption.js b/src/utils/MegolmExportEncryption.js index be7472901a..6f5c7104b1 100644 --- a/src/utils/MegolmExportEncryption.js +++ b/src/utils/MegolmExportEncryption.js @@ -310,8 +310,7 @@ function unpackMegolmKeyFile(data) { // look for the end line while (1) { const lineEnd = fileStr.indexOf('\n', lineStart); - const line = fileStr.slice(lineStart, lineEnd < 0 ? undefined : lineEnd) - .trim(); + const line = fileStr.slice(lineStart, lineEnd < 0 ? undefined : lineEnd).trim(); if (line === TRAILER_LINE) { break; } diff --git a/src/utils/Mouse.ts b/src/utils/Mouse.ts new file mode 100644 index 0000000000..a85c6492c4 --- /dev/null +++ b/src/utils/Mouse.ts @@ -0,0 +1,50 @@ +/* +Copyright 2021 Šimon Brandner + +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. +*/ + +/** + * Different browsers use different deltaModes. This causes different behaviour. + * To avoid that we use this function to convert any event to pixels. + * @param {WheelEvent} event to normalize + * @returns {WheelEvent} normalized event event + */ +export function normalizeWheelEvent(event: WheelEvent): WheelEvent { + const LINE_HEIGHT = 18; + + let deltaX; + let deltaY; + let deltaZ; + + if (event.deltaMode === 1) { // Units are lines + deltaX = (event.deltaX * LINE_HEIGHT); + deltaY = (event.deltaY * LINE_HEIGHT); + deltaZ = (event.deltaZ * LINE_HEIGHT); + } else { + deltaX = event.deltaX; + deltaY = event.deltaY; + deltaZ = event.deltaZ; + } + + return new WheelEvent( + "syntheticWheel", + { + deltaMode: 0, + deltaY: deltaY, + deltaX: deltaX, + deltaZ: deltaZ, + ...event, + }, + ); +} diff --git a/src/utils/Singleflight.ts b/src/utils/Singleflight.ts new file mode 100644 index 0000000000..c2a564ea3e --- /dev/null +++ b/src/utils/Singleflight.ts @@ -0,0 +1,126 @@ +/* +Copyright 2021 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. +*/ + +import {EnhancedMap} from "./maps"; + +// Inspired by https://pkg.go.dev/golang.org/x/sync/singleflight + +const keyMap = new EnhancedMap>(); + +/** + * Access class to get a singleflight context. Singleflights execute a + * function exactly once, unless instructed to forget about a result. + * + * Typically this is used to de-duplicate an action, such as a save button + * being pressed, without having to track state internally for an operation + * already being in progress. This doesn't expose a flag which can be used + * to disable a button, however it would be capable of returning a Promise + * from the first call. + * + * The result of the function call is cached indefinitely, just in case a + * second call comes through late. There are various functions named "forget" + * to have the cache be cleared of a result. + * + * Singleflights in our usecase are tied to an instance of something, combined + * with a string key to differentiate between multiple possible actions. This + * means that a "save" key will be scoped to the instance which defined it and + * not leak between other instances. This is done to avoid having to concatenate + * variables to strings to essentially namespace the field, for most cases. + */ +export class Singleflight { + private constructor() { + } + + /** + * A void marker to help with returning a value in a singleflight context. + * If your code doesn't return anything, return this instead. + */ + public static Void = Symbol("void"); + + /** + * Acquire a singleflight context. + * @param {Object} instance An instance to associate the context with. Can be any object. + * @param {string} key A string key relevant to that instance to namespace under. + * @returns {SingleflightContext} Returns the context to execute the function. + */ + public static for(instance: Object, key: string): SingleflightContext { + if (!instance || !key) throw new Error("An instance and key must be supplied"); + return new SingleflightContext(instance, key); + } + + /** + * Forgets all results for a given instance. + * @param {Object} instance The instance to forget about. + */ + public static forgetAllFor(instance: Object) { + keyMap.delete(instance); + } + + /** + * Forgets all cached results for all instances. Intended for use by tests. + */ + public static forgetAll() { + for (const k of keyMap.keys()) { + keyMap.remove(k); + } + } +} + +class SingleflightContext { + public constructor(private instance: Object, private key: string) { + } + + /** + * Forget this particular instance and key combination, discarding the result. + */ + public forget() { + const map = keyMap.get(this.instance); + if (!map) return; + map.remove(this.key); + if (!map.size) keyMap.remove(this.instance); + } + + /** + * Execute a function. If a result is already known, that will be returned instead + * of executing the provided function. However, if no result is known then the function + * will be called, with its return value cached. The function must return a value + * other than `undefined` - take a look at Singleflight.Void if you don't have a return + * to make. + * + * Note that this technically allows the caller to provide a different function each time: + * this is largely considered a bad idea and should not be done. Singleflights work off the + * premise that something needs to happen once, so duplicate executions will be ignored. + * + * For ideal performance and behaviour, functions which return promises are preferred. If + * a function is not returning a promise, it should return as soon as possible to avoid a + * second call potentially racing it. The promise returned by this function will be that + * of the first execution of the function, even on duplicate calls. + * @param {Function} fn The function to execute. + * @returns The recorded value. + */ + public do(fn: () => T): T { + const map = keyMap.getOrCreate(this.instance, new EnhancedMap()); + + // We have to manually getOrCreate() because we need to execute the fn + let val = map.get(this.key); + if (val === undefined) { + val = fn(); + map.set(this.key, val); + } + + return val; + } +} diff --git a/src/utils/StorageManager.js b/src/utils/StorageManager.ts similarity index 96% rename from src/utils/StorageManager.js rename to src/utils/StorageManager.ts index 23c27a2d1c..883c032771 100644 --- a/src/utils/StorageManager.js +++ b/src/utils/StorageManager.ts @@ -1,5 +1,5 @@ /* -Copyright 2019 New Vector Ltd +Copyright 2019-2021 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. @@ -32,15 +32,15 @@ try { const SYNC_STORE_NAME = "riot-web-sync"; const CRYPTO_STORE_NAME = "matrix-js-sdk:crypto"; -function log(msg) { +function log(msg: string) { console.log(`StorageManager: ${msg}`); } -function error(msg) { - console.error(`StorageManager: ${msg}`); +function error(msg: string, ...args: string[]) { + console.error(`StorageManager: ${msg}`, ...args); } -function track(action) { +function track(action: string) { Analytics.trackEvent("StorageManager", action); } @@ -73,7 +73,7 @@ export async function checkConsistency() { dataInLocalStorage = localStorage.length > 0; log(`Local storage contains data? ${dataInLocalStorage}`); - cryptoInited = localStorage.getItem("mx_crypto_initialised"); + cryptoInited = !!localStorage.getItem("mx_crypto_initialised"); log(`Crypto initialised? ${cryptoInited}`); } else { healthy = false; diff --git a/src/utils/Timer.js b/src/utils/Timer.ts similarity index 60% rename from src/utils/Timer.js rename to src/utils/Timer.ts index ca06237fbf..9760631d09 100644 --- a/src/utils/Timer.js +++ b/src/utils/Timer.ts @@ -1,5 +1,5 @@ /* -Copyright 2018 New Vector Ltd +Copyright 2018, 2021 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. @@ -26,44 +26,48 @@ Once a timer is finished or aborted, it can't be started again a new one through `clone()` or `cloneIfRun()`. */ export default class Timer { - constructor(timeout) { - this._timeout = timeout; - this._onTimeout = this._onTimeout.bind(this); - this._setNotStarted(); + private timerHandle: NodeJS.Timeout; + private startTs: number; + private promise: Promise; + private resolve: () => void; + private reject: (Error) => void; + + constructor(private timeout: number) { + this.setNotStarted(); } - _setNotStarted() { - this._timerHandle = null; - this._startTs = null; - this._promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; + private setNotStarted() { + this.timerHandle = null; + this.startTs = null; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; }).finally(() => { - this._timerHandle = null; + this.timerHandle = null; }); } - _onTimeout() { + private onTimeout = () => { const now = Date.now(); - const elapsed = now - this._startTs; - if (elapsed >= this._timeout) { - this._resolve(); - this._setNotStarted(); + const elapsed = now - this.startTs; + if (elapsed >= this.timeout) { + this.resolve(); + this.setNotStarted(); } else { - const delta = this._timeout - elapsed; - this._timerHandle = setTimeout(this._onTimeout, delta); + const delta = this.timeout - elapsed; + this.timerHandle = setTimeout(this.onTimeout, delta); } } - changeTimeout(timeout) { - if (timeout === this._timeout) { + changeTimeout(timeout: number) { + if (timeout === this.timeout) { return; } - const isSmallerTimeout = timeout < this._timeout; - this._timeout = timeout; + const isSmallerTimeout = timeout < this.timeout; + this.timeout = timeout; if (this.isRunning() && isSmallerTimeout) { - clearTimeout(this._timerHandle); - this._onTimeout(); + clearTimeout(this.timerHandle); + this.onTimeout(); } } @@ -73,8 +77,8 @@ export default class Timer { */ start() { if (!this.isRunning()) { - this._startTs = Date.now(); - this._timerHandle = setTimeout(this._onTimeout, this._timeout); + this.startTs = Date.now(); + this.timerHandle = setTimeout(this.onTimeout, this.timeout); } return this; } @@ -89,7 +93,7 @@ export default class Timer { // can be called in fast succession, // instead just take note and compare // when the already running timeout expires - this._startTs = Date.now(); + this.startTs = Date.now(); return this; } else { return this.start(); @@ -103,9 +107,9 @@ export default class Timer { */ abort() { if (this.isRunning()) { - clearTimeout(this._timerHandle); - this._reject(new Error("Timer was aborted.")); - this._setNotStarted(); + clearTimeout(this.timerHandle); + this.reject(new Error("Timer was aborted.")); + this.setNotStarted(); } return this; } @@ -116,10 +120,10 @@ export default class Timer { *@return {Promise} */ finished() { - return this._promise; + return this.promise; } isRunning() { - return this._timerHandle !== null; + return this.timerHandle !== null; } } diff --git a/src/utils/TypeUtils.js b/src/utils/TypeUtils.ts similarity index 100% rename from src/utils/TypeUtils.js rename to src/utils/TypeUtils.ts diff --git a/src/utils/arrays.ts b/src/utils/arrays.ts index 52308937f7..f7e693452b 100644 --- a/src/utils/arrays.ts +++ b/src/utils/arrays.ts @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020, 2021 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. @@ -15,23 +15,47 @@ limitations under the License. */ /** - * Quickly resample an array to have less data points. This isn't a perfect representation, - * though this does work best if given a large array to downsample to a much smaller array. - * @param {number[]} input The input array to downsample. + * Quickly resample an array to have less/more data points. If an input which is larger + * than the desired size is provided, it will be downsampled. Similarly, if the input + * is smaller than the desired size then it will be upsampled. + * @param {number[]} input The input array to resample. * @param {number} points The number of samples to end up with. - * @returns {number[]} The downsampled array. + * @returns {number[]} The resampled array. */ export function arrayFastResample(input: number[], points: number): number[] { - // Heavily inpired by matrix-media-repo (used with permission) + if (input.length === points) return input; // short-circuit a complicated call + + // Heavily inspired by matrix-media-repo (used with permission) // https://github.com/turt2live/matrix-media-repo/blob/abe72c87d2e29/util/util_audio/fastsample.go#L10 - const everyNth = Math.round(input.length / points); - const samples: number[] = []; - for (let i = 0; i < input.length; i += everyNth) { - samples.push(input[i]); + let samples: number[] = []; + if (input.length > points) { + // Danger: this loop can cause out of memory conditions if the input is too small. + const everyNth = Math.round(input.length / points); + for (let i = 0; i < input.length; i += everyNth) { + samples.push(input[i]); + } + } else { + // Smaller inputs mean we have to spread the values over the desired length. We + // end up overshooting the target length in doing this, so we'll resample down + // before returning. This recursion is risky, but mathematically should not go + // further than 1 level deep. + const spreadFactor = Math.ceil(points / input.length); + for (const val of input) { + samples.push(...arraySeed(val, spreadFactor)); + } + samples = arrayFastResample(samples, points); } + + // Sanity fill, just in case while (samples.length < points) { samples.push(input[input.length - 1]); } + + // Sanity trim, just in case + if (samples.length > points) { + samples = samples.slice(0, points); + } + return samples; } @@ -49,12 +73,32 @@ export function arraySeed(val: T, length: number): T[] { return a; } +/** + * Trims or fills the array to ensure it meets the desired length. The seed array + * given is pulled from to fill any missing slots - it is recommended that this be + * at least `len` long. The resulting array will be exactly `len` long, either + * trimmed from the source or filled with the some/all of the seed array. + * @param {T[]} a The array to trim/fill. + * @param {number} len The length to trim or fill to, as needed. + * @param {T[]} seed Values to pull from if the array needs filling. + * @returns {T[]} The resulting array of `len` length. + */ +export function arrayTrimFill(a: T[], len: number, seed: T[]): T[] { + // Dev note: we do length checks because the spread operator can result in some + // performance penalties in more critical code paths. As a utility, it should be + // as fast as possible to not cause a problem for the call stack, no matter how + // critical that stack is. + if (a.length === len) return a; + if (a.length > len) return a.slice(0, len); + return a.concat(seed.slice(0, len - a.length)); +} + /** * Clones an array as fast as possible, retaining references of the array's values. * @param a The array to clone. Must be defined. * @returns A copy of the array. */ -export function arrayFastClone(a: any[]): any[] { +export function arrayFastClone(a: T[]): T[] { return a.slice(0, a.length); } @@ -178,6 +222,13 @@ export class GroupedArray { constructor(private val: Map) { } + /** + * The value of this group, after all applicable alterations. + */ + public get value(): Map { + return this.val; + } + /** * Orders the grouping into an array using the provided key order. * @param keyOrder The key order. diff --git a/src/utils/enums.ts b/src/utils/enums.ts index f7f4787896..d3ca318c28 100644 --- a/src/utils/enums.ts +++ b/src/utils/enums.ts @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020, 2021 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. @@ -19,11 +19,23 @@ limitations under the License. * @param e The enum. * @returns The enum values. */ -export function getEnumValues(e: any): T[] { +export function getEnumValues(e: any): (string | number)[] { + // String-based enums will simply be objects ({Key: "value"}), but number-based + // enums will instead map themselves twice: in one direction for {Key: 12} and + // the reverse for easy lookup, presumably ({12: Key}). In the reverse mapping, + // the key is a string, not a number. + // + // For this reason, we try to determine what kind of enum we're dealing with. + const keys = Object.keys(e); - return keys - .filter(k => ['string', 'number'].includes(typeof(e[k]))) - .map(k => e[k]); + const values: (string | number)[] = []; + for (const key of keys) { + const value = e[key]; + if (Number.isFinite(value) || e[value.toString()] !== Number(key)) { + values.push(value); + } + } + return values; } /** diff --git a/src/utils/objects.ts b/src/utils/objects.ts index e7f4f0f907..2c9361beba 100644 --- a/src/utils/objects.ts +++ b/src/utils/objects.ts @@ -1,5 +1,5 @@ /* -Copyright 2020 The Matrix.org Foundation C.I.C. +Copyright 2020, 2021 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. @@ -141,3 +141,21 @@ export function objectKeyChanges(a: O, b: O): (keyof O)[] { export function objectClone(obj: O): O { return JSON.parse(JSON.stringify(obj)); } + +/** + * Converts a series of entries to an object. + * @param entries The entries to convert. + * @returns The converted object. + */ +// NOTE: Deprecated once we have Object.fromEntries() support. +// @ts-ignore - return type is complaining about non-string keys, but we know better +export function objectFromEntries(entries: Iterable<[K, V]>): {[k: K]: V} { + const obj: { + // @ts-ignore - same as return type + [k: K]: V} = {}; + for (const e of entries) { + // @ts-ignore - same as return type + obj[e[0]] = e[1]; + } + return obj; +} diff --git a/src/utils/permalinks/ElementPermalinkConstructor.js b/src/utils/permalinks/ElementPermalinkConstructor.ts similarity index 82% rename from src/utils/permalinks/ElementPermalinkConstructor.js rename to src/utils/permalinks/ElementPermalinkConstructor.ts index da7f5797ea..cd7f2b9d2c 100644 --- a/src/utils/permalinks/ElementPermalinkConstructor.js +++ b/src/utils/permalinks/ElementPermalinkConstructor.ts @@ -20,31 +20,31 @@ import PermalinkConstructor, {PermalinkParts} from "./PermalinkConstructor"; * Generates permalinks that self-reference the running webapp */ export default class ElementPermalinkConstructor extends PermalinkConstructor { - _elementUrl: string; + private elementUrl: string; constructor(elementUrl: string) { super(); - this._elementUrl = elementUrl; + this.elementUrl = elementUrl; - if (!this._elementUrl.startsWith("http:") && !this._elementUrl.startsWith("https:")) { + if (!this.elementUrl.startsWith("http:") && !this.elementUrl.startsWith("https:")) { throw new Error("Element prefix URL does not appear to be an HTTP(S) URL"); } } forEvent(roomId: string, eventId: string, serverCandidates: string[]): string { - return `${this._elementUrl}/#/room/${roomId}/${eventId}${this.encodeServerCandidates(serverCandidates)}`; + return `${this.elementUrl}/#/room/${roomId}/${eventId}${this.encodeServerCandidates(serverCandidates)}`; } - forRoom(roomIdOrAlias: string, serverCandidates: string[]): string { - return `${this._elementUrl}/#/room/${roomIdOrAlias}${this.encodeServerCandidates(serverCandidates)}`; + forRoom(roomIdOrAlias: string, serverCandidates?: string[]): string { + return `${this.elementUrl}/#/room/${roomIdOrAlias}${this.encodeServerCandidates(serverCandidates)}`; } forUser(userId: string): string { - return `${this._elementUrl}/#/user/${userId}`; + return `${this.elementUrl}/#/user/${userId}`; } forGroup(groupId: string): string { - return `${this._elementUrl}/#/group/${groupId}`; + return `${this.elementUrl}/#/group/${groupId}`; } forEntity(entityId: string): string { @@ -58,11 +58,11 @@ export default class ElementPermalinkConstructor extends PermalinkConstructor { } isPermalinkHost(testHost: string): boolean { - const parsedUrl = new URL(this._elementUrl); + const parsedUrl = new URL(this.elementUrl); return testHost === (parsedUrl.host || parsedUrl.hostname); // one of the hosts should match } - encodeServerCandidates(candidates: string[]) { + encodeServerCandidates(candidates?: string[]) { if (!candidates || candidates.length === 0) return ''; return `?via=${candidates.map(c => encodeURIComponent(c)).join("&via=")}`; } @@ -71,11 +71,11 @@ export default class ElementPermalinkConstructor extends PermalinkConstructor { // https://github.com/turt2live/matrix-js-bot-sdk/blob/7c4665c9a25c2c8e0fe4e509f2616505b5b66a1c/src/Permalinks.ts#L33-L61 // Adapted for Element's URL format parsePermalink(fullUrl: string): PermalinkParts { - if (!fullUrl || !fullUrl.startsWith(this._elementUrl)) { + if (!fullUrl || !fullUrl.startsWith(this.elementUrl)) { throw new Error("Does not appear to be a permalink"); } - const parts = fullUrl.substring(`${this._elementUrl}/#/`.length); + const parts = fullUrl.substring(`${this.elementUrl}/#/`.length); return ElementPermalinkConstructor.parseAppRoute(parts); } diff --git a/src/utils/permalinks/PermalinkConstructor.js b/src/utils/permalinks/PermalinkConstructor.ts similarity index 100% rename from src/utils/permalinks/PermalinkConstructor.js rename to src/utils/permalinks/PermalinkConstructor.ts diff --git a/src/utils/permalinks/Permalinks.js b/src/utils/permalinks/Permalinks.ts similarity index 76% rename from src/utils/permalinks/Permalinks.js rename to src/utils/permalinks/Permalinks.ts index bcf4d87136..015ecca22e 100644 --- a/src/utils/permalinks/Permalinks.js +++ b/src/utils/permalinks/Permalinks.ts @@ -17,6 +17,9 @@ limitations under the License. import isIp from "is-ip"; import * as utils from "matrix-js-sdk/src/utils"; import {Room} from "matrix-js-sdk/src/models/room"; +import {EventType} from "matrix-js-sdk/src/@types/event"; +import { MatrixEvent } from "matrix-js-sdk/src/models/event"; +import { RoomMember } from "matrix-js-sdk/src/models/room-member"; import {MatrixClientPeg} from "../../MatrixClientPeg"; import SpecPermalinkConstructor, {baseUrl as matrixtoBaseUrl} from "./SpecPermalinkConstructor"; @@ -74,29 +77,35 @@ const MAX_SERVER_CANDIDATES = 3; // the list and magically have the link work. export class RoomPermalinkCreator { + private room: Room; + private roomId: string; + private highestPlUserId: string; + private populationMap: { [serverName: string]: number }; + private bannedHostsRegexps: RegExp[]; + private allowedHostsRegexps: RegExp[]; + private _serverCandidates: string[]; + private started: boolean; + // We support being given a roomId as a fallback in the event the `room` object // doesn't exist or is not healthy for us to rely on. For example, loading a // permalink to a room which the MatrixClient doesn't know about. - constructor(room, roomId = null) { - this._room = room; - this._roomId = room ? room.roomId : roomId; - this._highestPlUserId = null; - this._populationMap = null; - this._bannedHostsRegexps = null; - this._allowedHostsRegexps = null; + constructor(room: Room, roomId: string = null) { + this.room = room; + this.roomId = room ? room.roomId : roomId; + this.highestPlUserId = null; + this.populationMap = null; + this.bannedHostsRegexps = null; + this.allowedHostsRegexps = null; this._serverCandidates = null; - this._started = false; + this.started = false; - if (!this._roomId) { + if (!this.roomId) { throw new Error("Failed to resolve a roomId for the permalink creator to use"); } - - this.onMembership = this.onMembership.bind(this); - this.onRoomState = this.onRoomState.bind(this); } load() { - if (!this._room || !this._room.currentState) { + if (!this.room || !this.room.currentState) { // Under rare and unknown circumstances it is possible to have a room with no // currentState, at least potentially at the early stages of joining a room. // To avoid breaking everything, we'll just warn rather than throw as well as @@ -104,23 +113,23 @@ export class RoomPermalinkCreator { console.warn("Tried to load a permalink creator with no room state"); return; } - this._updateAllowedServers(); - this._updateHighestPlUser(); - this._updatePopulationMap(); - this._updateServerCandidates(); + this.updateAllowedServers(); + this.updateHighestPlUser(); + this.updatePopulationMap(); + this.updateServerCandidates(); } start() { this.load(); - this._room.on("RoomMember.membership", this.onMembership); - this._room.on("RoomState.events", this.onRoomState); - this._started = true; + this.room.on("RoomMember.membership", this.onMembership); + this.room.on("RoomState.events", this.onRoomState); + this.started = true; } stop() { - this._room.removeListener("RoomMember.membership", this.onMembership); - this._room.removeListener("RoomState.events", this.onRoomState); - this._started = false; + this.room.removeListener("RoomMember.membership", this.onMembership); + this.room.removeListener("RoomState.events", this.onRoomState); + this.started = false; } get serverCandidates() { @@ -128,44 +137,44 @@ export class RoomPermalinkCreator { } isStarted() { - return this._started; + return this.started; } - forEvent(eventId) { - return getPermalinkConstructor().forEvent(this._roomId, eventId, this._serverCandidates); + forEvent(eventId: string): string { + return getPermalinkConstructor().forEvent(this.roomId, eventId, this._serverCandidates); } - forShareableRoom() { - if (this._room) { + forShareableRoom(): string { + if (this.room) { // Prefer to use canonical alias for permalink if possible - const alias = this._room.getCanonicalAlias(); + const alias = this.room.getCanonicalAlias(); if (alias) { return getPermalinkConstructor().forRoom(alias, this._serverCandidates); } } - return getPermalinkConstructor().forRoom(this._roomId, this._serverCandidates); + return getPermalinkConstructor().forRoom(this.roomId, this._serverCandidates); } - forRoom() { - return getPermalinkConstructor().forRoom(this._roomId, this._serverCandidates); + forRoom(): string { + return getPermalinkConstructor().forRoom(this.roomId, this._serverCandidates); } - onRoomState(event) { + private onRoomState = (event: MatrixEvent) => { switch (event.getType()) { - case "m.room.server_acl": - this._updateAllowedServers(); - this._updateHighestPlUser(); - this._updatePopulationMap(); - this._updateServerCandidates(); + case EventType.RoomServerAcl: + this.updateAllowedServers(); + this.updateHighestPlUser(); + this.updatePopulationMap(); + this.updateServerCandidates(); return; - case "m.room.power_levels": - this._updateHighestPlUser(); - this._updateServerCandidates(); + case EventType.RoomPowerLevels: + this.updateHighestPlUser(); + this.updateServerCandidates(); return; } } - onMembership(evt, member, oldMembership) { + private onMembership = (evt: MatrixEvent, member: RoomMember, oldMembership: string) => { const userId = member.userId; const membership = member.membership; const serverName = getServerName(userId); @@ -173,17 +182,17 @@ export class RoomPermalinkCreator { const hasLeft = oldMembership === "join" && membership !== "join"; if (hasLeft) { - this._populationMap[serverName]--; + this.populationMap[serverName]--; } else if (hasJoined) { - this._populationMap[serverName]++; + this.populationMap[serverName]++; } - this._updateHighestPlUser(); - this._updateServerCandidates(); + this.updateHighestPlUser(); + this.updateServerCandidates(); } - _updateHighestPlUser() { - const plEvent = this._room.currentState.getStateEvents("m.room.power_levels", ""); + private updateHighestPlUser() { + const plEvent = this.room.currentState.getStateEvents("m.room.power_levels", ""); if (plEvent) { const content = plEvent.getContent(); if (content) { @@ -191,14 +200,14 @@ export class RoomPermalinkCreator { if (users) { const entries = Object.entries(users); const allowedEntries = entries.filter(([userId]) => { - const member = this._room.getMember(userId); + const member = this.room.getMember(userId); if (!member || member.membership !== "join") { return false; } const serverName = getServerName(userId); return !isHostnameIpAddress(serverName) && - !isHostInRegex(serverName, this._bannedHostsRegexps) && - isHostInRegex(serverName, this._allowedHostsRegexps); + !isHostInRegex(serverName, this.bannedHostsRegexps) && + isHostInRegex(serverName, this.allowedHostsRegexps); }); const maxEntry = allowedEntries.reduce((max, entry) => { return (entry[1] > max[1]) ? entry : max; @@ -206,20 +215,20 @@ export class RoomPermalinkCreator { const [userId, powerLevel] = maxEntry; // object wasn't empty, and max entry wasn't a demotion from the default if (userId !== null && powerLevel >= 50) { - this._highestPlUserId = userId; + this.highestPlUserId = userId; return; } } } } - this._highestPlUserId = null; + this.highestPlUserId = null; } - _updateAllowedServers() { + private updateAllowedServers() { const bannedHostsRegexps = []; let allowedHostsRegexps = [new RegExp(".*")]; // default allow everyone - if (this._room.currentState) { - const aclEvent = this._room.currentState.getStateEvents("m.room.server_acl", ""); + if (this.room.currentState) { + const aclEvent = this.room.currentState.getStateEvents("m.room.server_acl", ""); if (aclEvent && aclEvent.getContent()) { const getRegex = (hostname) => new RegExp("^" + utils.globToRegexp(hostname, false) + "$"); @@ -231,35 +240,35 @@ export class RoomPermalinkCreator { allowed.forEach(h => allowedHostsRegexps.push(getRegex(h))); } } - this._bannedHostsRegexps = bannedHostsRegexps; - this._allowedHostsRegexps = allowedHostsRegexps; + this.bannedHostsRegexps = bannedHostsRegexps; + this.allowedHostsRegexps = allowedHostsRegexps; } - _updatePopulationMap() { + private updatePopulationMap() { const populationMap: { [server: string]: number } = {}; - for (const member of this._room.getJoinedMembers()) { + for (const member of this.room.getJoinedMembers()) { const serverName = getServerName(member.userId); if (!populationMap[serverName]) { populationMap[serverName] = 0; } populationMap[serverName]++; } - this._populationMap = populationMap; + this.populationMap = populationMap; } - _updateServerCandidates() { + private updateServerCandidates() { let candidates = []; - if (this._highestPlUserId) { - candidates.push(getServerName(this._highestPlUserId)); + if (this.highestPlUserId) { + candidates.push(getServerName(this.highestPlUserId)); } - const serversByPopulation = Object.keys(this._populationMap) - .sort((a, b) => this._populationMap[b] - this._populationMap[a]) + const serversByPopulation = Object.keys(this.populationMap) + .sort((a, b) => this.populationMap[b] - this.populationMap[a]) .filter(a => { return !candidates.includes(a) && !isHostnameIpAddress(a) && - !isHostInRegex(a, this._bannedHostsRegexps) && - isHostInRegex(a, this._allowedHostsRegexps); + !isHostInRegex(a, this.bannedHostsRegexps) && + isHostInRegex(a, this.allowedHostsRegexps); }); const remainingServers = serversByPopulation.slice(0, MAX_SERVER_CANDIDATES - candidates.length); @@ -273,11 +282,11 @@ export function makeGenericPermalink(entityId: string): string { return getPermalinkConstructor().forEntity(entityId); } -export function makeUserPermalink(userId) { +export function makeUserPermalink(userId: string): string { return getPermalinkConstructor().forUser(userId); } -export function makeRoomPermalink(roomId) { +export function makeRoomPermalink(roomId: string): string { if (!roomId) { throw new Error("can't permalink a falsey roomId"); } @@ -296,7 +305,7 @@ export function makeRoomPermalink(roomId) { return permalinkCreator.forRoom(); } -export function makeGroupPermalink(groupId) { +export function makeGroupPermalink(groupId: string): string { return getPermalinkConstructor().forGroup(groupId); } @@ -337,7 +346,7 @@ export function tryTransformPermalinkToLocalHref(permalink: string): string { return permalink; } - const m = permalink.match(matrixLinkify.ELEMENT_URL_PATTERN); + const m = decodeURIComponent(permalink).match(matrixLinkify.ELEMENT_URL_PATTERN); if (m) { return m[1]; } @@ -402,8 +411,8 @@ function getPermalinkConstructor(): PermalinkConstructor { export function parsePermalink(fullUrl: string): PermalinkParts { const elementPrefix = SdkConfig.get()['permalinkPrefix']; - if (fullUrl.startsWith(matrixtoBaseUrl)) { - return new SpecPermalinkConstructor().parsePermalink(fullUrl); + if (decodeURIComponent(fullUrl).startsWith(matrixtoBaseUrl)) { + return new SpecPermalinkConstructor().parsePermalink(decodeURIComponent(fullUrl)); } else if (elementPrefix && fullUrl.startsWith(elementPrefix)) { return new ElementPermalinkConstructor(elementPrefix).parsePermalink(fullUrl); } @@ -428,24 +437,24 @@ export function parseAppLocalLink(localLink: string): PermalinkParts { return null; } -function getServerName(userId) { +function getServerName(userId: string): string { return userId.split(":").splice(1).join(":"); } -function getHostnameFromMatrixDomain(domain) { +function getHostnameFromMatrixDomain(domain: string): string { if (!domain) return null; return new URL(`https://${domain}`).hostname; } -function isHostInRegex(hostname, regexps) { +function isHostInRegex(hostname: string, regexps: RegExp[]) { hostname = getHostnameFromMatrixDomain(hostname); if (!hostname) return true; // assumed - if (regexps.length > 0 && !regexps[0].test) throw new Error(regexps[0]); + if (regexps.length > 0 && !regexps[0].test) throw new Error(regexps[0].toString()); return regexps.filter(h => h.test(hostname)).length > 0; } -function isHostnameIpAddress(hostname) { +function isHostnameIpAddress(hostname: string): boolean { hostname = getHostnameFromMatrixDomain(hostname); if (!hostname) return false; diff --git a/src/utils/permalinks/SpecPermalinkConstructor.js b/src/utils/permalinks/SpecPermalinkConstructor.ts similarity index 100% rename from src/utils/permalinks/SpecPermalinkConstructor.js rename to src/utils/permalinks/SpecPermalinkConstructor.ts diff --git a/src/voice/Playback.ts b/src/voice/Playback.ts new file mode 100644 index 0000000000..99b1f62866 --- /dev/null +++ b/src/voice/Playback.ts @@ -0,0 +1,141 @@ +/* +Copyright 2021 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. +*/ + +import EventEmitter from "events"; +import {UPDATE_EVENT} from "../stores/AsyncStore"; +import {arrayFastResample, arraySeed} from "../utils/arrays"; +import {SimpleObservable} from "matrix-widget-api"; +import {IDestroyable} from "../utils/IDestroyable"; +import {PlaybackClock} from "./PlaybackClock"; + +export enum PlaybackState { + Decoding = "decoding", + Stopped = "stopped", // no progress on timeline + Paused = "paused", // some progress on timeline + Playing = "playing", // active progress through timeline +} + +export const PLAYBACK_WAVEFORM_SAMPLES = 35; +const DEFAULT_WAVEFORM = arraySeed(0, PLAYBACK_WAVEFORM_SAMPLES); + +export class Playback extends EventEmitter implements IDestroyable { + private readonly context: AudioContext; + private source: AudioBufferSourceNode; + private state = PlaybackState.Decoding; + private audioBuf: AudioBuffer; + private resampledWaveform: number[]; + private waveformObservable = new SimpleObservable(); + private readonly clock: PlaybackClock; + + /** + * Creates a new playback instance from a buffer. + * @param {ArrayBuffer} buf The buffer containing the sound sample. + * @param {number[]} seedWaveform Optional seed waveform to present until the proper waveform + * can be calculated. Contains values between zero and one, inclusive. + */ + constructor(private buf: ArrayBuffer, seedWaveform = DEFAULT_WAVEFORM) { + super(); + this.context = new AudioContext(); + this.resampledWaveform = arrayFastResample(seedWaveform, PLAYBACK_WAVEFORM_SAMPLES); + this.waveformObservable.update(this.resampledWaveform); + this.clock = new PlaybackClock(this.context); + + // TODO: @@ TR: Calculate real waveform + } + + public get waveform(): number[] { + return this.resampledWaveform; + } + + public get waveformData(): SimpleObservable { + return this.waveformObservable; + } + + public get clockInfo(): PlaybackClock { + return this.clock; + } + + public get currentState(): PlaybackState { + return this.state; + } + + public get isPlaying(): boolean { + return this.currentState === PlaybackState.Playing; + } + + public emit(event: PlaybackState, ...args: any[]): boolean { + this.state = event; + super.emit(event, ...args); + super.emit(UPDATE_EVENT, event, ...args); + return true; // we don't ever care if the event had listeners, so just return "yes" + } + + public destroy() { + // noinspection JSIgnoredPromiseFromCall - not concerned about being called async here + this.stop(); + this.removeAllListeners(); + this.clock.destroy(); + this.waveformObservable.close(); + } + + public async prepare() { + this.audioBuf = await this.context.decodeAudioData(this.buf); + this.emit(PlaybackState.Stopped); // signal that we're not decoding anymore + this.clock.durationSeconds = this.audioBuf.duration; + } + + private onPlaybackEnd = async () => { + await this.context.suspend(); + this.emit(PlaybackState.Stopped); + }; + + public async play() { + // We can't restart a buffer source, so we need to create a new one if we hit the end + if (this.state === PlaybackState.Stopped) { + if (this.source) { + this.source.disconnect(); + this.source.removeEventListener("ended", this.onPlaybackEnd); + } + + this.source = this.context.createBufferSource(); + this.source.connect(this.context.destination); + this.source.buffer = this.audioBuf; + this.source.start(); // start immediately + this.source.addEventListener("ended", this.onPlaybackEnd); + } + + // We use the context suspend/resume functions because it allows us to pause a source + // node, but that still doesn't help us when the source node runs out (see above). + await this.context.resume(); + this.clock.flagStart(); + this.emit(PlaybackState.Playing); + } + + public async pause() { + await this.context.suspend(); + this.emit(PlaybackState.Paused); + } + + public async stop() { + await this.onPlaybackEnd(); + this.clock.flagStop(); + } + + public async toggle() { + if (this.isPlaying) await this.pause(); + else await this.play(); + } +} diff --git a/src/voice/PlaybackClock.ts b/src/voice/PlaybackClock.ts new file mode 100644 index 0000000000..06d6381691 --- /dev/null +++ b/src/voice/PlaybackClock.ts @@ -0,0 +1,78 @@ +/* +Copyright 2021 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. +*/ + +import {SimpleObservable} from "matrix-widget-api"; +import {IDestroyable} from "../utils/IDestroyable"; + +// Because keeping track of time is sufficiently complicated... +export class PlaybackClock implements IDestroyable { + private clipStart = 0; + private stopped = true; + private lastCheck = 0; + private observable = new SimpleObservable(); + private timerId: number; + private clipDuration = 0; + + public constructor(private context: AudioContext) { + } + + public get durationSeconds(): number { + return this.clipDuration; + } + + public set durationSeconds(val: number) { + this.clipDuration = val; + this.observable.update([this.timeSeconds, this.clipDuration]); + } + + public get timeSeconds(): number { + return (this.context.currentTime - this.clipStart) % this.clipDuration; + } + + public get liveData(): SimpleObservable { + return this.observable; + } + + private checkTime = () => { + const now = this.timeSeconds; + if (this.lastCheck !== now) { + this.observable.update([now, this.durationSeconds]); + this.lastCheck = now; + } + }; + + public flagStart() { + if (this.stopped) { + this.clipStart = this.context.currentTime; + this.stopped = false; + } + + if (!this.timerId) { + // case to number because the types are wrong + // 100ms interval to make sure the time is as accurate as possible + this.timerId = setInterval(this.checkTime, 100); + } + } + + public flagStop() { + this.stopped = true; + } + + public destroy() { + this.observable.close(); + if (this.timerId) clearInterval(this.timerId); + } +} diff --git a/src/voice/RecorderWorklet.ts b/src/voice/RecorderWorklet.ts new file mode 100644 index 0000000000..7343d37066 --- /dev/null +++ b/src/voice/RecorderWorklet.ts @@ -0,0 +1,67 @@ +/* +Copyright 2021 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. +*/ + +import {IAmplitudePayload, ITimingPayload, PayloadEvent, WORKLET_NAME} from "./consts"; +import {percentageOf} from "../utils/numbers"; + +// from AudioWorkletGlobalScope: https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletGlobalScope +declare const currentTime: number; +// declare const currentFrame: number; +// declare const sampleRate: number; + +class MxVoiceWorklet extends AudioWorkletProcessor { + private nextAmplitudeSecond = 0; + + process(inputs, outputs, parameters) { + // We only fire amplitude updates once a second to avoid flooding the recording instance + // with useless data. Much of the data would end up discarded, so we ratelimit ourselves + // here. + const currentSecond = Math.round(currentTime); + if (currentSecond === this.nextAmplitudeSecond) { + // We're expecting exactly one mono input source, so just grab the very first frame of + // samples for the analysis. + const monoChan = inputs[0][0]; + + // The amplitude of the frame's samples is effectively the loudness of the frame. This + // translates into a bar which can be rendered as part of the whole recording clip's + // waveform. + // + // We translate the amplitude down to 0-1 for sanity's sake. + const minVal = Math.min(...monoChan); + const maxVal = Math.max(...monoChan); + const amplitude = percentageOf(maxVal, -1, 1) - percentageOf(minVal, -1, 1); + + this.port.postMessage({ + ev: PayloadEvent.AmplitudeMark, + amplitude: amplitude, + forSecond: currentSecond, + }); + this.nextAmplitudeSecond++; + } + + // We mostly use this worklet to fire regular clock updates through to components + this.port.postMessage({ev: PayloadEvent.Timekeep, timeSeconds: currentTime}); + + // We're supposed to return false when we're "done" with the audio clip, but seeing as + // we are acting as a passive processor we are never truly "done". The browser will clean + // us up when it is done with us. + return true; + } +} + +registerProcessor(WORKLET_NAME, MxVoiceWorklet); + +export default null; // to appease module loaders (we never use the export) diff --git a/src/voice/VoiceRecording.ts b/src/voice/VoiceRecording.ts index 77c182fc54..eb705200ca 100644 --- a/src/voice/VoiceRecording.ts +++ b/src/voice/VoiceRecording.ts @@ -20,29 +20,71 @@ import {MatrixClient} from "matrix-js-sdk/src/client"; import CallMediaHandler from "../CallMediaHandler"; import {SimpleObservable} from "matrix-widget-api"; import {clamp} from "../utils/numbers"; +import EventEmitter from "events"; +import {IDestroyable} from "../utils/IDestroyable"; +import {Singleflight} from "../utils/Singleflight"; +import {PayloadEvent, WORKLET_NAME} from "./consts"; +import {UPDATE_EVENT} from "../stores/AsyncStore"; +import {Playback} from "./Playback"; const CHANNELS = 1; // stereo isn't important const SAMPLE_RATE = 48000; // 48khz is what WebRTC uses. 12khz is where we lose quality. const BITRATE = 24000; // 24kbps is pretty high quality for our use case in opus. +const TARGET_MAX_LENGTH = 120; // 2 minutes in seconds. Somewhat arbitrary, though longer == larger files. +const TARGET_WARN_TIME_LEFT = 10; // 10 seconds, also somewhat arbitrary. export interface IRecordingUpdate { waveform: number[]; // floating points between 0 (low) and 1 (high). timeSeconds: number; // float } -export class VoiceRecording { +export enum RecordingState { + Started = "started", + EndingSoon = "ending_soon", // emits an object with a single numerical value: secondsLeft + Ended = "ended", + Uploading = "uploading", + Uploaded = "uploaded", +} + +export class VoiceRecording extends EventEmitter implements IDestroyable { private recorder: Recorder; private recorderContext: AudioContext; private recorderSource: MediaStreamAudioSourceNode; private recorderStream: MediaStream; private recorderFFT: AnalyserNode; - private recorderProcessor: ScriptProcessorNode; - private buffer = new Uint8Array(0); + private recorderWorklet: AudioWorkletNode; + private buffer = new Uint8Array(0); // use this.audioBuffer to access private mxc: string; private recording = false; private observable: SimpleObservable; + private amplitudes: number[] = []; // at each second mark, generated + private playback: Playback; public constructor(private client: MatrixClient) { + super(); + } + + public get contentType(): string { + return "audio/ogg"; + } + + public get contentLength(): number { + return this.buffer.length; + } + + public get durationSeconds(): number { + if (!this.recorder) throw new Error("Duration not available without a recording"); + return this.recorderContext.currentTime; + } + + public get isRecording(): boolean { + return this.recording; + } + + public emit(event: string, ...args: any[]): boolean { + super.emit(event, ...args); + super.emit(UPDATE_EVENT, event, ...args); + return true; // we don't ever care if the event had listeners, so just return "yes" } private async makeRecorder() { @@ -66,18 +108,34 @@ export class VoiceRecording { // it makes the time domain less than helpful. this.recorderFFT.fftSize = 64; - // We use an audio processor to get accurate timing information. - // The size of the audio buffer largely decides how quickly we push timing/waveform data - // out of this class. Smaller buffers mean we update more frequently as we can't hold as - // many bytes. Larger buffers mean slower updates. For scale, 1024 gives us about 30Hz of - // updates and 2048 gives us about 20Hz. We use 1024 to get as close to perceived realtime - // as possible. Must be a power of 2. - this.recorderProcessor = this.recorderContext.createScriptProcessor(1024, CHANNELS, CHANNELS); + // Set up our worklet. We use this for timing information and waveform analysis: the + // web audio API prefers this be done async to avoid holding the main thread with math. + const mxRecorderWorkletPath = document.body.dataset.vectorRecorderWorkletScript; + if (!mxRecorderWorkletPath) { + throw new Error("Unable to create recorder: no worklet script registered"); + } + await this.recorderContext.audioWorklet.addModule(mxRecorderWorkletPath); + this.recorderWorklet = new AudioWorkletNode(this.recorderContext, WORKLET_NAME); // Connect our inputs and outputs this.recorderSource.connect(this.recorderFFT); - this.recorderSource.connect(this.recorderProcessor); - this.recorderProcessor.connect(this.recorderContext.destination); + this.recorderSource.connect(this.recorderWorklet); + this.recorderWorklet.connect(this.recorderContext.destination); + + // Dev note: we can't use `addEventListener` for some reason. It just doesn't work. + this.recorderWorklet.port.onmessage = (ev) => { + switch (ev.data['ev']) { + case PayloadEvent.Timekeep: + this.processAudioUpdate(ev.data['timeSeconds']); + break; + case PayloadEvent.AmplitudeMark: + // Sanity check to make sure we're adding about one sample per second + if (ev.data['forSecond'] === this.amplitudes.length) { + this.amplitudes.push(ev.data['amplitude']); + } + break; + } + }; this.recorder = new Recorder({ encoderPath, // magic from webpack @@ -104,6 +162,12 @@ export class VoiceRecording { }; } + private get audioBuffer(): Uint8Array { + // We need a clone of the buffer to avoid accidentally changing the position + // on the real thing. + return this.buffer.slice(0); + } + public get liveData(): SimpleObservable { if (!this.recording) throw new Error("No observable when not recording"); return this.observable; @@ -124,7 +188,7 @@ export class VoiceRecording { return this.mxc; } - private tryUpdateLiveData = (ev: AudioProcessingEvent) => { + private processAudioUpdate = (timeSeconds: number) => { if (!this.recording) return; // The time domain is the input to the FFT, which means we use an array of the same @@ -148,8 +212,32 @@ export class VoiceRecording { this.observable.update({ waveform: translatedData, - timeSeconds: ev.playbackTime, + timeSeconds: timeSeconds, }); + + // Now that we've updated the data/waveform, let's do a time check. We don't want to + // go horribly over the limit. We also emit a warning state if needed. + // + // We use the recorder's perspective of time to make sure we don't cut off the last + // frame of audio, otherwise we end up with a 1:59 clip (119.68 seconds). This extra + // safety can allow us to overshoot the target a bit, but at least when we say 2min + // maximum we actually mean it. + // + // In testing, recorder time and worker time lag by about 400ms, which is roughly the + // time needed to encode a sample/frame. + // + // Ref for recorderSeconds: https://github.com/chris-rudmin/opus-recorder#instance-fields + const recorderSeconds = this.recorder.encodedSamplePosition / 48000; + const secondsLeft = TARGET_MAX_LENGTH - recorderSeconds; + if (secondsLeft < 0) { // go over to make sure we definitely capture that last frame + // noinspection JSIgnoredPromiseFromCall - we aren't concerned with it overlapping + this.stop(); + } else if (secondsLeft <= TARGET_WARN_TIME_LEFT) { + Singleflight.for(this, "ending_soon").do(() => { + this.emit(RecordingState.EndingSoon, {secondsLeft}); + return Singleflight.Void; + }); + } }; public async start(): Promise { @@ -164,33 +252,61 @@ export class VoiceRecording { } this.observable = new SimpleObservable(); await this.makeRecorder(); - this.recorderProcessor.addEventListener("audioprocess", this.tryUpdateLiveData); await this.recorder.start(); this.recording = true; + this.emit(RecordingState.Started); } public async stop(): Promise { - if (!this.recording) { - throw new Error("No recording to stop"); - } + return Singleflight.for(this, "stop").do(async () => { + if (!this.recording) { + throw new Error("No recording to stop"); + } - // Disconnect the source early to start shutting down resources - this.recorderSource.disconnect(); - await this.recorder.stop(); + // Disconnect the source early to start shutting down resources + await this.recorder.stop(); // stop first to flush the last frame + this.recorderSource.disconnect(); + this.recorderWorklet.disconnect(); - // close the context after the recorder so the recorder doesn't try to - // connect anything to the context (this would generate a warning) - await this.recorderContext.close(); + // close the context after the recorder so the recorder doesn't try to + // connect anything to the context (this would generate a warning) + await this.recorderContext.close(); - // Now stop all the media tracks so we can release them back to the user/OS - this.recorderStream.getTracks().forEach(t => t.stop()); + // Now stop all the media tracks so we can release them back to the user/OS + this.recorderStream.getTracks().forEach(t => t.stop()); - // Finally do our post-processing and clean up - this.recording = false; - this.recorderProcessor.removeEventListener("audioprocess", this.tryUpdateLiveData); - await this.recorder.close(); + // Finally do our post-processing and clean up + this.recording = false; + await this.recorder.close(); + this.emit(RecordingState.Ended); - return this.buffer; + return this.audioBuffer; + }); + } + + /** + * Gets a playback instance for this voice recording. Note that the playback will not + * have been prepared fully, meaning the `prepare()` function needs to be called on it. + * + * The same playback instance is returned each time. + * + * @returns {Playback} The playback instance. + */ + public getPlayback(): Playback { + this.playback = Singleflight.for(this, "playback").do(() => { + return new Playback(this.audioBuffer.buffer, this.amplitudes); // cast to ArrayBuffer proper; + }); + return this.playback; + } + + public destroy() { + // noinspection JSIgnoredPromiseFromCall - not concerned about stop() being called async here + this.stop(); + this.removeAllListeners(); + Singleflight.forgetAllFor(this); + // noinspection JSIgnoredPromiseFromCall - not concerned about being called async here + this.playback?.destroy(); + this.observable.close(); } public async upload(): Promise { @@ -200,13 +316,13 @@ export class VoiceRecording { if (this.mxc) return this.mxc; - this.mxc = await this.client.uploadContent(new Blob([this.buffer], { - type: "audio/ogg", + this.emit(RecordingState.Uploading); + this.mxc = await this.client.uploadContent(new Blob([this.audioBuffer], { + type: this.contentType, }), { onlyContentUri: false, // to stop the warnings in the console }).then(r => r['content_uri']); + this.emit(RecordingState.Uploaded); return this.mxc; } } - -window.mxVoiceRecorder = VoiceRecording; diff --git a/src/voice/consts.ts b/src/voice/consts.ts new file mode 100644 index 0000000000..c530c60f0b --- /dev/null +++ b/src/voice/consts.ts @@ -0,0 +1,37 @@ +/* +Copyright 2021 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. +*/ + +export const WORKLET_NAME = "mx-voice-worklet"; + +export enum PayloadEvent { + Timekeep = "timekeep", + AmplitudeMark = "amplitude_mark", +} + +export interface IPayload { + ev: PayloadEvent; +} + +export interface ITimingPayload extends IPayload { + ev: PayloadEvent.Timekeep; + timeSeconds: number; +} + +export interface IAmplitudePayload extends IPayload { + ev: PayloadEvent.AmplitudeMark; + forSecond: number; + amplitude: number; +} diff --git a/test/CallHandler-test.ts b/test/CallHandler-test.ts new file mode 100644 index 0000000000..754610b223 --- /dev/null +++ b/test/CallHandler-test.ts @@ -0,0 +1,216 @@ +/* +Copyright 2021 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. +*/ + +import './skinned-sdk'; + +import CallHandler, { PlaceCallType } from '../src/CallHandler'; +import { stubClient, mkStubRoom } from './test-utils'; +import { MatrixClientPeg } from '../src/MatrixClientPeg'; +import dis from '../src/dispatcher/dispatcher'; +import { CallEvent, CallState } from 'matrix-js-sdk/src/webrtc/call'; +import DMRoomMap from '../src/utils/DMRoomMap'; +import EventEmitter from 'events'; +import { Action } from '../src/dispatcher/actions'; +import SdkConfig from '../src/SdkConfig'; + +const REAL_ROOM_ID = '$room1:example.org'; +const MAPPED_ROOM_ID = '$room2:example.org'; +const MAPPED_ROOM_ID_2 = '$room3:example.org'; + +function mkStubDM(roomId, userId) { + const room = mkStubRoom(roomId); + room.getJoinedMembers = jest.fn().mockReturnValue([ + { + userId: '@me:example.org', + name: 'Member', + rawDisplayName: 'Member', + roomId: roomId, + membership: 'join', + getAvatarUrl: () => 'mxc://avatar.url/image.png', + getMxcAvatarUrl: () => 'mxc://avatar.url/image.png', + }, + { + userId: userId, + name: 'Member', + rawDisplayName: 'Member', + roomId: roomId, + membership: 'join', + getAvatarUrl: () => 'mxc://avatar.url/image.png', + getMxcAvatarUrl: () => 'mxc://avatar.url/image.png', + }, + ]); + room.currentState.getMembers = room.getJoinedMembers; + + return room; +} + +class FakeCall extends EventEmitter { + roomId: string; + callId = "fake call id"; + + constructor(roomId) { + super(); + + this.roomId = roomId; + } + + setRemoteOnHold() {} + setRemoteAudioElement() {} + + placeVoiceCall() { + this.emit(CallEvent.State, CallState.Connected, null); + } +} + +describe('CallHandler', () => { + let dmRoomMap; + let callHandler; + let audioElement; + let fakeCall; + + beforeEach(() => { + stubClient(); + MatrixClientPeg.get().createCall = roomId => { + if (fakeCall && fakeCall.roomId !== roomId) { + throw new Error("Only one call is supported!"); + } + fakeCall = new FakeCall(roomId); + return fakeCall; + }; + + callHandler = new CallHandler(); + callHandler.start(); + + dmRoomMap = { + getUserIdForRoomId: roomId => { + if (roomId === REAL_ROOM_ID) { + return '@user1:example.org'; + } else if (roomId === MAPPED_ROOM_ID) { + return '@user2:example.org'; + } else if (roomId === MAPPED_ROOM_ID_2) { + return '@user3:example.org'; + } else { + return null; + } + }, + getDMRoomsForUserId: userId => { + if (userId === '@user2:example.org') { + return [MAPPED_ROOM_ID]; + } else if (userId === '@user3:example.org') { + return [MAPPED_ROOM_ID_2]; + } else { + return []; + } + }, + }; + DMRoomMap.setShared(dmRoomMap); + + audioElement = document.createElement('audio'); + audioElement.id = "remoteAudio"; + document.body.appendChild(audioElement); + }); + + afterEach(() => { + callHandler.stop(); + DMRoomMap.setShared(null); + // @ts-ignore + window.mxCallHandler = null; + MatrixClientPeg.unset(); + + document.body.removeChild(audioElement); + SdkConfig.unset(); + }); + + it('should move calls between rooms when remote asserted identity changes', async () => { + const realRoom = mkStubDM(REAL_ROOM_ID, '@user1:example.org'); + const mappedRoom = mkStubDM(MAPPED_ROOM_ID, '@user2:example.org'); + const mappedRoom2 = mkStubDM(MAPPED_ROOM_ID_2, '@user3:example.org'); + + MatrixClientPeg.get().getRoom = roomId => { + switch (roomId) { + case REAL_ROOM_ID: + return realRoom; + case MAPPED_ROOM_ID: + return mappedRoom; + case MAPPED_ROOM_ID_2: + return mappedRoom2; + } + }; + + dis.dispatch({ + action: 'place_call', + type: PlaceCallType.Voice, + room_id: REAL_ROOM_ID, + }, true); + + let dispatchHandle; + // wait for the call to be set up + await new Promise(resolve => { + dispatchHandle = dis.register(payload => { + if (payload.action === 'call_state') { + resolve(); + } + }); + }); + dis.unregister(dispatchHandle); + + // should start off in the actual room ID it's in at the protocol level + expect(callHandler.getCallForRoom(REAL_ROOM_ID)).toBe(fakeCall); + + let callRoomChangeEventCount = 0; + const roomChangePromise = new Promise(resolve => { + dispatchHandle = dis.register(payload => { + if (payload.action === Action.CallChangeRoom) { + ++callRoomChangeEventCount; + resolve(); + } + }); + }); + + // Now emit an asserted identity for user2: this should be ignored + // because we haven't set the config option to obey asserted identity + fakeCall.getRemoteAssertedIdentity = jest.fn().mockReturnValue({ + id: "@user2:example.org", + }); + fakeCall.emit(CallEvent.AssertedIdentityChanged); + + // Now set the config option + SdkConfig.put({ + voip: { + obeyAssertedIdentity: true, + }, + }); + + // ...and send another asserted identity event for a different user + fakeCall.getRemoteAssertedIdentity = jest.fn().mockReturnValue({ + id: "@user3:example.org", + }); + fakeCall.emit(CallEvent.AssertedIdentityChanged); + + await roomChangePromise; + dis.unregister(dispatchHandle); + + // If everything's gone well, we should have seen only one room change + // event and the call should now be in user 3's room. + // If it's not obeying any, the call will still be in REAL_ROOM_ID. + // If it incorrectly obeyed both asserted identity changes, either it will + // have just processed one and the call will be in the wrong room, or we'll + // have seen two room change dispatches. + expect(callRoomChangeEventCount).toEqual(1); + expect(callHandler.getCallForRoom(REAL_ROOM_ID)).toBeNull(); + expect(callHandler.getCallForRoom(MAPPED_ROOM_ID_2)).toBe(fakeCall); + }); +}); diff --git a/test/ScalarAuthClient-test.js b/test/ScalarAuthClient-test.js index 83f357811a..3435f70932 100644 --- a/test/ScalarAuthClient-test.js +++ b/test/ScalarAuthClient-test.js @@ -29,7 +29,7 @@ describe('ScalarAuthClient', function() { it('should request a new token if the old one fails', async function() { const sac = new ScalarAuthClient(); - sac._getAccountName = jest.fn((arg) => { + sac.getAccountName = jest.fn((arg) => { switch (arg) { case "brokentoken": return Promise.reject({ diff --git a/test/autocomplete/QueryMatcher-test.js b/test/autocomplete/QueryMatcher-test.js index 3d383f08d7..cae71841d4 100644 --- a/test/autocomplete/QueryMatcher-test.js +++ b/test/autocomplete/QueryMatcher-test.js @@ -177,7 +177,7 @@ describe('QueryMatcher', function() { const qm = new QueryMatcher(NONWORDOBJECTS, { keys: ["name"], shouldMatchWordsOnly: false, - }); + }); const results = qm.match('bob'); expect(results.length).toBe(1); diff --git a/test/components/views/dialogs/AccessSecretStorageDialog-test.js b/test/components/views/dialogs/AccessSecretStorageDialog-test.js index 13b39ab0d0..d9e07a2d74 100644 --- a/test/components/views/dialogs/AccessSecretStorageDialog-test.js +++ b/test/components/views/dialogs/AccessSecretStorageDialog-test.js @@ -26,9 +26,9 @@ describe("AccessSecretStorageDialog", function() { it("Closes the dialog if _onRecoveryKeyNext is called with a valid key", (done) => { const testInstance = TestRenderer.create( p && p.recoveryKey && p.recoveryKey == "a"} - onFinished={(v) => { - if (v) { done(); } + checkPrivateKey={(p) => p && p.recoveryKey && p.recoveryKey == "a"} + onFinished={(v) => { + if (v) { done(); } }} />, ); @@ -43,7 +43,7 @@ describe("AccessSecretStorageDialog", function() { it("Considers a valid key to be valid", async function() { const testInstance = TestRenderer.create( true} + checkPrivateKey={() => true} />, ); const v = "asdf"; @@ -61,7 +61,7 @@ describe("AccessSecretStorageDialog", function() { it("Notifies the user if they input an invalid Security Key", async function(done) { const testInstance = TestRenderer.create( false} + checkPrivateKey={async () => false} />, ); const e = { target: { value: "a" } }; @@ -87,12 +87,14 @@ describe("AccessSecretStorageDialog", function() { it("Notifies the user if they input an invalid passphrase", async function(done) { const testInstance = TestRenderer.create( false} - onFinished={() => {}} - keyInfo={ { passphrase: { - salt: 'nonempty', - iterations: 2, - } } } + checkPrivateKey={() => false} + onFinished={() => {}} + keyInfo={{ + passphrase: { + salt: 'nonempty', + iterations: 2, + }, + }} />, ); const e = { target: { value: "a" } }; diff --git a/test/components/views/elements/MemberEventListSummary-test.js b/test/components/views/elements/MemberEventListSummary-test.js index dd6febc7d7..95bf206d02 100644 --- a/test/components/views/elements/MemberEventListSummary-test.js +++ b/test/components/views/elements/MemberEventListSummary-test.js @@ -245,8 +245,7 @@ describe('MemberEventListSummary', function() { ); }); - it('truncates multiple sequences of repetitions with other events between', - function() { + it('truncates multiple sequences of repetitions with other events between', function() { const events = generateEvents([ { userId: "@user_1:some.domain", @@ -395,8 +394,7 @@ describe('MemberEventListSummary', function() { ); }); - it('correctly orders sequences of transitions by the order of their first event', - function() { + it('correctly orders sequences of transitions by the order of their first event', function() { const events = generateEvents([ { userId: "@user_2:some.domain", @@ -568,8 +566,7 @@ describe('MemberEventListSummary', function() { ); }); - it('handles invitation plurals correctly when there are multiple invites', - function() { + it('handles invitation plurals correctly when there are multiple invites', function() { const events = generateEvents([ { userId: "@user_1:some.domain", diff --git a/test/components/views/rooms/MemberList-test.js b/test/components/views/rooms/MemberList-test.js index 068d358dcd..093e5588d0 100644 --- a/test/components/views/rooms/MemberList-test.js +++ b/test/components/views/rooms/MemberList-test.js @@ -100,7 +100,7 @@ describe('MemberList', () => { memberList = r; }; root = ReactDOM.render(, parentDiv); + wrappedRef={gatherWrappedRef} />, parentDiv); }); afterEach((done) => { diff --git a/test/components/views/rooms/RoomList-test.js b/test/components/views/rooms/RoomList-test.js index fcdd71629e..bfb8e1afd4 100644 --- a/test/components/views/rooms/RoomList-test.js +++ b/test/components/views/rooms/RoomList-test.js @@ -29,7 +29,10 @@ function waitForRoomListStoreUpdate() { describe('RoomList', () => { function createRoom(opts) { - const room = new Room(generateRoomId(), null, client.getUserId()); + const room = new Room(generateRoomId(), MatrixClientPeg.get(), client.getUserId(), { + // The room list now uses getPendingEvents(), so we need a detached ordering. + pendingEventOrdering: "detached", + }); if (opts) { Object.assign(room, opts); } @@ -67,8 +70,9 @@ describe('RoomList', () => { root = ReactDOM.render( {}} /> - - , parentDiv); + , + parentDiv, + ); ReactTestUtils.findRenderedComponentWithType(root, RoomList); movingRoom = createRoom({name: 'Moving room'}); diff --git a/test/end-to-end-tests/src/session.js b/test/end-to-end-tests/src/session.js index 433baa5e48..4c611ef877 100644 --- a/test/end-to-end-tests/src/session.js +++ b/test/end-to-end-tests/src/session.js @@ -93,10 +93,10 @@ module.exports = class ElementSession { const type = req.resourceType(); const response = await req.response(); //if (type === 'xhr' || type === 'fetch') { - buffer += `${type} ${response.status()} ${req.method()} ${req.url()} \n`; - // if (req.method() === "POST") { - // buffer += " Post data: " + req.postData(); - // } + buffer += `${type} ${response.status()} ${req.method()} ${req.url()} \n`; + // if (req.method() === "POST") { + // buffer += " Post data: " + req.postData(); + // } //} }); return { diff --git a/test/end-to-end-tests/src/usecases/create-room.js b/test/end-to-end-tests/src/usecases/create-room.js index 35b9d5879e..3830e3e0da 100644 --- a/test/end-to-end-tests/src/usecases/create-room.js +++ b/test/end-to-end-tests/src/usecases/create-room.js @@ -21,15 +21,7 @@ async function openRoomDirectory(session) { } async function findSublist(session, name) { - const sublists = await session.queryAll('.mx_RoomSublist'); - for (const sublist of sublists) { - const header = await sublist.$('.mx_RoomSublist_headerText'); - const headerText = await session.innerText(header); - if (headerText.toLowerCase().includes(name.toLowerCase())) { - return sublist; - } - } - throw new Error(`could not find room list section that contains '${name}' in header`); + return await session.query(`.mx_RoomSublist[aria-label="${name}" i]`); } async function createRoom(session, roomName, encrypted=false) { diff --git a/test/end-to-end-tests/src/usecases/signup.js b/test/end-to-end-tests/src/usecases/signup.js index 804cee9599..a3391e99f3 100644 --- a/test/end-to-end-tests/src/usecases/signup.js +++ b/test/end-to-end-tests/src/usecases/signup.js @@ -31,6 +31,9 @@ module.exports = async function signup(session, username, password, homeserver) // accept homeserver await nextButton.click(); } + // Delay required because of local race condition on macOs + // Where the form is not query-able despite being present in the DOM + await session.delay(100); //fill out form const usernameField = await session.query("#mx_RegistrationForm_username"); const passwordField = await session.query("#mx_RegistrationForm_password"); diff --git a/test/end-to-end-tests/yarn.lock b/test/end-to-end-tests/yarn.lock index 2f4d9979fb..7f2cefb92e 100644 --- a/test/end-to-end-tests/yarn.lock +++ b/test/end-to-end-tests/yarn.lock @@ -37,9 +37,9 @@ assert-plus@1.0.0, assert-plus@^1.0.0: integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU= async-limiter@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8" - integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg== + version "1.0.1" + resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.1.tgz#dd379e94f0db8310b08291f9d64c3209766617fd" + integrity sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ== asynckit@^0.4.0: version "0.4.0" @@ -57,9 +57,9 @@ aws4@^1.8.0: integrity sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ== balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= + version "1.0.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" + integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== bcrypt-pbkdf@^1.0.0: version "1.0.2" @@ -81,6 +81,11 @@ brace-expansion@^1.1.7: balanced-match "^1.0.0" concat-map "0.0.1" +buffer-crc32@~0.2.3: + version "0.2.13" + resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" + integrity sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI= + buffer-from@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" @@ -120,7 +125,7 @@ concat-map@0.0.1: resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= -concat-stream@1.6.2: +concat-stream@^1.6.2: version "1.6.2" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== @@ -157,7 +162,7 @@ dashdash@^1.12.0: dependencies: assert-plus "^1.0.0" -debug@2.6.9: +debug@^2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== @@ -165,18 +170,18 @@ debug@2.6.9: ms "2.0.0" debug@^3.1.0: - version "3.2.6" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" - integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== + version "3.2.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.7.tgz#72580b7e9145fb39b6676f9c5e5fb100b934179a" + integrity sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ== dependencies: ms "^2.1.1" debug@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" - integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== + version "4.3.1" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.1.tgz#f0d229c505e0c6d8c49ac553d1b13dc183f6b2ee" + integrity sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ== dependencies: - ms "^2.1.1" + ms "2.1.2" delayed-stream@~1.0.0: version "1.0.0" @@ -250,14 +255,14 @@ extend@~3.0.2: integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== extract-zip@^1.6.6: - version "1.6.7" - resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-1.6.7.tgz#a840b4b8af6403264c8db57f4f1a74333ef81fe9" - integrity sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k= + version "1.7.0" + resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-1.7.0.tgz#556cc3ae9df7f452c493a0cfb51cc30277940927" + integrity sha512-xoh5G1W/PB0/27lXgMQyIhP5DSY/LhoCsOyZgb+6iMmRtCwVBo55uKaMoEYrDCKQhWvqEip5ZPKAc6eFNyf/MA== dependencies: - concat-stream "1.6.2" - debug "2.6.9" - mkdirp "0.5.1" - yauzl "2.4.1" + concat-stream "^1.6.2" + debug "^2.6.9" + mkdirp "^0.5.4" + yauzl "^2.10.0" extsprintf@1.3.0: version "1.3.0" @@ -279,10 +284,10 @@ fast-json-stable-stringify@^2.0.0: resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I= -fd-slicer@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65" - integrity sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU= +fd-slicer@~1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" + integrity sha1-JcfInLH5B3+IkbvmHY85Dq4lbx4= dependencies: pend "~1.2.0" @@ -313,9 +318,9 @@ getpass@^0.1.1: assert-plus "^1.0.0" glob@^7.1.3: - version "7.1.3" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1" - integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ== + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" @@ -374,7 +379,12 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3: +inherits@2, inherits@^2.0.3, inherits@~2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +inherits@^2.0.1: version "2.0.3" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4= @@ -442,9 +452,9 @@ mime-types@^2.1.12, mime-types@~2.1.19: mime-db "~1.38.0" mime@^2.0.3: - version "2.4.0" - resolved "https://registry.yarnpkg.com/mime/-/mime-2.4.0.tgz#e051fd881358585f3279df333fe694da0bcffdd6" - integrity sha512-ikBcWwyqXQSHKtciCcctu9YfPbFYZ4+gbHEmE0Q8jzcTYQg5dHCr3g2wwAZjPoJfQVXZq6KXAjpXOTf5/cjT7w== + version "2.5.2" + resolved "https://registry.yarnpkg.com/mime/-/mime-2.5.2.tgz#6e3dc6cc2b9510643830e5f19d5cb753da5eeabe" + integrity sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg== minimatch@^3.0.4: version "3.0.4" @@ -453,28 +463,33 @@ minimatch@^3.0.4: dependencies: brace-expansion "^1.1.7" -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0= +minimist@^1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" + integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== -mkdirp@0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM= +mkdirp@^0.5.4: + version "0.5.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" + integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== dependencies: - minimist "0.0.8" + minimist "^1.2.5" ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= -ms@^2.1.1: +ms@2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== +ms@^2.1.1: + version "2.1.3" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" + integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== + nth-check@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-1.0.2.tgz#b2bd295c37e3dd58a3bf0700376663ba4d9cf05c" @@ -517,9 +532,9 @@ performance-now@^2.1.0: integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= process-nextick-args@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" - integrity sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw== + version "2.0.1" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== progress@^2.0.1: version "2.0.3" @@ -527,9 +542,9 @@ progress@^2.0.1: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-from-env@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.0.0.tgz#33c50398f70ea7eb96d21f7b817630a55791c7ee" - integrity sha1-M8UDmPcOp+uW0h97gXYwpVeRx+4= + version "1.1.0" + resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" + integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== psl@^1.1.24, psl@^1.1.28: version "1.1.31" @@ -547,9 +562,9 @@ punycode@^2.1.0, punycode@^2.1.1: integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== puppeteer@^1.14.0: - version "1.14.0" - resolved "https://registry.yarnpkg.com/puppeteer/-/puppeteer-1.14.0.tgz#828c1926b307200d5fc8289b99df4e13e962d339" - integrity sha512-SayS2wUX/8LF8Yo2Rkpc5nkAu4Jg3qu+OLTDSOZtisVQMB2Z5vjlY2TdPi/5CgZKiZroYIiyUN3sRX63El9iaw== + version "1.20.0" + resolved "https://registry.yarnpkg.com/puppeteer/-/puppeteer-1.20.0.tgz#e3d267786f74e1d87cf2d15acc59177f471bbe38" + integrity sha512-bt48RDBy2eIwZPrkgbcwHtb51mj2nKvHOPMaSH2IsWiv7lOG9k9zhaRzpDZafrk05ajMc3cu+lSQYYOfH2DkVQ== dependencies: debug "^4.1.0" extract-zip "^1.6.6" @@ -566,9 +581,9 @@ qs@~6.5.2: integrity sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA== readable-stream@^2.2.2: - version "2.3.6" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" - integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== + version "2.3.7" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" @@ -630,9 +645,9 @@ request@^2.88.0: uuid "^3.3.2" rimraf@^2.6.1: - version "2.6.3" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" - integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== + version "2.7.1" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" + integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== dependencies: glob "^7.1.3" @@ -751,9 +766,10 @@ ws@^6.1.0: dependencies: async-limiter "~1.0.0" -yauzl@2.4.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.4.1.tgz#9528f442dab1b2284e58b4379bb194e22e0c4005" - integrity sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU= +yauzl@^2.10.0: + version "2.10.0" + resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9" + integrity sha1-x+sXyT4RLLEIb6bY5R+wZnt5pfk= dependencies: - fd-slicer "~1.0.1" + buffer-crc32 "~0.2.3" + fd-slicer "~1.1.0" diff --git a/test/stores/SpaceStore-test.ts b/test/stores/SpaceStore-test.ts new file mode 100644 index 0000000000..aef788647d --- /dev/null +++ b/test/stores/SpaceStore-test.ts @@ -0,0 +1,714 @@ +/* +Copyright 2021 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. +*/ + +import { EventEmitter } from "events"; +import { EventType } from "matrix-js-sdk/src/@types/event"; + +import "../skinned-sdk"; // Must be first for skinning to work +import SpaceStore, { + UPDATE_INVITED_SPACES, + UPDATE_SELECTED_SPACE, + UPDATE_TOP_LEVEL_SPACES +} from "../../src/stores/SpaceStore"; +import { resetAsyncStoreWithClient, setupAsyncStoreWithClient } from "../utils/test-utils"; +import { mkEvent, mkStubRoom, stubClient } from "../test-utils"; +import { EnhancedMap } from "../../src/utils/maps"; +import SettingsStore from "../../src/settings/SettingsStore"; +import DMRoomMap from "../../src/utils/DMRoomMap"; +import { MatrixClientPeg } from "../../src/MatrixClientPeg"; +import defaultDispatcher from "../../src/dispatcher/dispatcher"; + +type MatrixEvent = any; // importing from js-sdk upsets things + +jest.useFakeTimers(); + +const mockStateEventImplementation = (events: MatrixEvent[]) => { + const stateMap = new EnhancedMap>(); + events.forEach(event => { + stateMap.getOrCreate(event.getType(), new Map()).set(event.getStateKey(), event); + }); + + return (eventType: string, stateKey?: string) => { + if (stateKey || stateKey === "") { + return stateMap.get(eventType)?.get(stateKey) || null; + } + return Array.from(stateMap.get(eventType)?.values() || []); + }; +}; + +const emitPromise = (e: EventEmitter, k: string | symbol) => new Promise(r => e.once(k, r)); + +const testUserId = "@test:user"; + +let rooms = []; + +const mkRoom = (roomId: string) => { + const room = mkStubRoom(roomId); + room.currentState.getStateEvents.mockImplementation(mockStateEventImplementation([])); + rooms.push(room); + return room; +}; + +const mkSpace = (spaceId: string, children: string[] = []) => { + const space = mkRoom(spaceId); + space.isSpaceRoom.mockReturnValue(true); + space.currentState.getStateEvents.mockImplementation(mockStateEventImplementation(children.map(roomId => + mkEvent({ + event: true, + type: EventType.SpaceChild, + room: spaceId, + user: testUserId, + skey: roomId, + content: { via: [] }, + ts: Date.now(), + }), + ))); + return space; +}; + +const getValue = jest.fn(); +SettingsStore.getValue = getValue; + +const getUserIdForRoomId = jest.fn(); +// @ts-ignore +DMRoomMap.sharedInstance = { getUserIdForRoomId }; + +const fav1 = "!fav1:server"; +const fav2 = "!fav2:server"; +const fav3 = "!fav3:server"; +const dm1 = "!dm1:server"; +const dm1Partner = "@dm1Partner:server"; +const dm2 = "!dm2:server"; +const dm2Partner = "@dm2Partner:server"; +const dm3 = "!dm3:server"; +const dm3Partner = "@dm3Partner:server"; +const orphan1 = "!orphan1:server"; +const orphan2 = "!orphan2:server"; +const invite1 = "!invite1:server"; +const invite2 = "!invite2:server"; +const room1 = "!room1:server"; +const room2 = "!room2:server"; +const space1 = "!space1:server"; +const space2 = "!space2:server"; +const space3 = "!space3:server"; + +describe("SpaceStore", () => { + stubClient(); + const store = SpaceStore.instance; + const client = MatrixClientPeg.get(); + + const viewRoom = roomId => defaultDispatcher.dispatch({ action: "view_room", room_id: roomId }, true); + + const run = async () => { + client.getRoom.mockImplementation(roomId => rooms.find(room => room.roomId === roomId)); + await setupAsyncStoreWithClient(store, client); + jest.runAllTimers(); + }; + + beforeEach(() => { + jest.runAllTimers(); + client.getVisibleRooms.mockReturnValue(rooms = []); + getValue.mockImplementation(settingName => { + if (settingName === "feature_spaces") { + return true; + } + }); + }); + afterEach(async () => { + await resetAsyncStoreWithClient(store); + }); + + describe("static hierarchy resolution tests", () => { + it("handles no spaces", async () => { + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([]); + }); + + it("handles 3 joined top level spaces", async () => { + mkSpace("!space1:server"); + mkSpace("!space2:server"); + mkSpace("!space3:server"); + await run(); + + expect(store.spacePanelSpaces.sort()).toStrictEqual(client.getVisibleRooms().sort()); + expect(store.invitedSpaces).toStrictEqual([]); + }); + + it("handles a basic hierarchy", async () => { + mkSpace("!space1:server"); + mkSpace("!space2:server"); + mkSpace("!company:server", [ + mkSpace("!company_dept1:server", [ + mkSpace("!company_dept1_group1:server").roomId, + ]).roomId, + mkSpace("!company_dept2:server").roomId, + ]); + await run(); + + expect(store.spacePanelSpaces.map(r => r.roomId).sort()).toStrictEqual([ + "!space1:server", + "!space2:server", + "!company:server", + ].sort()); + expect(store.invitedSpaces).toStrictEqual([]); + + expect(store.getChildRooms("!space1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!space1:server")).toStrictEqual([]); + expect(store.getChildRooms("!space2:server")).toStrictEqual([]); + expect(store.getChildSpaces("!space2:server")).toStrictEqual([]); + expect(store.getChildRooms("!company:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company:server")).toStrictEqual([ + client.getRoom("!company_dept1:server"), + client.getRoom("!company_dept2:server"), + ]); + expect(store.getChildRooms("!company_dept1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept1:server")).toStrictEqual([ + client.getRoom("!company_dept1_group1:server"), + ]); + expect(store.getChildRooms("!company_dept1_group1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept1_group1:server")).toStrictEqual([]); + expect(store.getChildRooms("!company_dept2:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept2:server")).toStrictEqual([]); + }); + + it("handles a sub-space existing in multiple places in the space tree", async () => { + const subspace = mkSpace("!subspace:server"); + mkSpace("!space1:server"); + mkSpace("!space2:server"); + mkSpace("!company:server", [ + mkSpace("!company_dept1:server", [ + mkSpace("!company_dept1_group1:server", [subspace.roomId]).roomId, + ]).roomId, + mkSpace("!company_dept2:server", [subspace.roomId]).roomId, + subspace.roomId, + ]); + await run(); + + expect(store.spacePanelSpaces.map(r => r.roomId).sort()).toStrictEqual([ + "!space1:server", + "!space2:server", + "!company:server", + ].sort()); + expect(store.invitedSpaces).toStrictEqual([]); + + expect(store.getChildRooms("!space1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!space1:server")).toStrictEqual([]); + expect(store.getChildRooms("!space2:server")).toStrictEqual([]); + expect(store.getChildSpaces("!space2:server")).toStrictEqual([]); + expect(store.getChildRooms("!company:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company:server")).toStrictEqual([ + client.getRoom("!company_dept1:server"), + client.getRoom("!company_dept2:server"), + subspace, + ]); + expect(store.getChildRooms("!company_dept1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept1:server")).toStrictEqual([ + client.getRoom("!company_dept1_group1:server"), + ]); + expect(store.getChildRooms("!company_dept1_group1:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept1_group1:server")).toStrictEqual([subspace]); + expect(store.getChildRooms("!company_dept2:server")).toStrictEqual([]); + expect(store.getChildSpaces("!company_dept2:server")).toStrictEqual([subspace]); + }); + + it("handles full cycles", async () => { + mkSpace("!a:server", [ + mkSpace("!b:server", [ + mkSpace("!c:server", [ + "!a:server", + ]).roomId, + ]).roomId, + ]); + await run(); + + expect(store.spacePanelSpaces.map(r => r.roomId)).toStrictEqual(["!a:server"]); + expect(store.invitedSpaces).toStrictEqual([]); + + expect(store.getChildRooms("!a:server")).toStrictEqual([]); + expect(store.getChildSpaces("!a:server")).toStrictEqual([client.getRoom("!b:server")]); + expect(store.getChildRooms("!b:server")).toStrictEqual([]); + expect(store.getChildSpaces("!b:server")).toStrictEqual([client.getRoom("!c:server")]); + expect(store.getChildRooms("!c:server")).toStrictEqual([]); + expect(store.getChildSpaces("!c:server")).toStrictEqual([client.getRoom("!a:server")]); + }); + + it("handles partial cycles", async () => { + mkSpace("!b:server", [ + mkSpace("!a:server", [ + mkSpace("!c:server", [ + "!a:server", + ]).roomId, + ]).roomId, + ]); + await run(); + + expect(store.spacePanelSpaces.map(r => r.roomId)).toStrictEqual(["!b:server"]); + expect(store.invitedSpaces).toStrictEqual([]); + + expect(store.getChildRooms("!b:server")).toStrictEqual([]); + expect(store.getChildSpaces("!b:server")).toStrictEqual([client.getRoom("!a:server")]); + expect(store.getChildRooms("!a:server")).toStrictEqual([]); + expect(store.getChildSpaces("!a:server")).toStrictEqual([client.getRoom("!c:server")]); + expect(store.getChildRooms("!c:server")).toStrictEqual([]); + expect(store.getChildSpaces("!c:server")).toStrictEqual([client.getRoom("!a:server")]); + }); + + it("handles partial cycles with additional spaces coming off them", async () => { + // TODO this test should be failing right now + mkSpace("!a:server", [ + mkSpace("!b:server", [ + mkSpace("!c:server", [ + "!a:server", + mkSpace("!d:server").roomId, + ]).roomId, + ]).roomId, + ]); + await run(); + + expect(store.spacePanelSpaces.map(r => r.roomId)).toStrictEqual(["!a:server"]); + expect(store.invitedSpaces).toStrictEqual([]); + + expect(store.getChildRooms("!a:server")).toStrictEqual([]); + expect(store.getChildSpaces("!a:server")).toStrictEqual([client.getRoom("!b:server")]); + expect(store.getChildRooms("!b:server")).toStrictEqual([]); + expect(store.getChildSpaces("!b:server")).toStrictEqual([client.getRoom("!c:server")]); + expect(store.getChildRooms("!c:server")).toStrictEqual([]); + expect(store.getChildSpaces("!c:server")).toStrictEqual([ + client.getRoom("!a:server"), + client.getRoom("!d:server"), + ]); + expect(store.getChildRooms("!d:server")).toStrictEqual([]); + expect(store.getChildSpaces("!d:server")).toStrictEqual([]); + }); + + it("invite to a subspace is only shown at the top level", async () => { + mkSpace(invite1).getMyMembership.mockReturnValue("invite"); + mkSpace(space1, [invite1]); + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([client.getRoom(space1)]); + expect(store.getChildSpaces(space1)).toStrictEqual([]); + expect(store.getChildRooms(space1)).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([client.getRoom(invite1)]); + }); + + describe("test fixture 1", () => { + beforeEach(async () => { + [fav1, fav2, fav3, dm1, dm2, dm3, orphan1, orphan2, invite1, invite2, room1].forEach(mkRoom); + mkSpace(space1, [fav1, room1]); + mkSpace(space2, [fav1, fav2, fav3, room1]); + mkSpace(space3, [invite2]); + + [fav1, fav2, fav3].forEach(roomId => { + client.getRoom(roomId).tags = { + "m.favourite": { + order: 0.5, + }, + }; + }); + + [invite1, invite2].forEach(roomId => { + client.getRoom(roomId).getMyMembership.mockReturnValue("invite"); + }); + + getUserIdForRoomId.mockImplementation(roomId => { + return { + [dm1]: dm1Partner, + [dm2]: dm2Partner, + [dm3]: dm3Partner, + }[roomId]; + }); + await run(); + }); + + it("home space contains orphaned rooms", () => { + expect(store.getSpaceFilteredRoomIds(null).has(orphan1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(orphan2)).toBeTruthy(); + }); + + it("home space contains favourites", () => { + expect(store.getSpaceFilteredRoomIds(null).has(fav1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(fav2)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(fav3)).toBeTruthy(); + }); + + it("home space contains dm rooms", () => { + expect(store.getSpaceFilteredRoomIds(null).has(dm1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(dm2)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(dm3)).toBeTruthy(); + }); + + it("home space contains invites", () => { + expect(store.getSpaceFilteredRoomIds(null).has(invite1)).toBeTruthy(); + }); + + it("home space contains invites even if they are also shown in a space", () => { + expect(store.getSpaceFilteredRoomIds(null).has(invite2)).toBeTruthy(); + }); + + it("home space does not contain rooms/low priority from rooms within spaces", () => { + expect(store.getSpaceFilteredRoomIds(null).has(room1)).toBeFalsy(); + }); + + it("space contains child rooms", () => { + const space = client.getRoom(space1); + expect(store.getSpaceFilteredRoomIds(space).has(fav1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(space).has(room1)).toBeTruthy(); + }); + + it("space contains child favourites", () => { + const space = client.getRoom(space2); + expect(store.getSpaceFilteredRoomIds(space).has(fav1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(space).has(fav2)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(space).has(fav3)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(space).has(room1)).toBeTruthy(); + }); + + it("space contains child invites", () => { + const space = client.getRoom(space3); + expect(store.getSpaceFilteredRoomIds(space).has(invite2)).toBeTruthy(); + }); + }); + }); + + describe("hierarchy resolution update tests", () => { + let emitter: EventEmitter; + beforeEach(async () => { + emitter = new EventEmitter(); + client.on.mockImplementation(emitter.on.bind(emitter)); + client.removeListener.mockImplementation(emitter.removeListener.bind(emitter)); + }); + afterEach(() => { + client.on.mockReset(); + client.removeListener.mockReset(); + }); + + it("updates state when spaces are joined", async () => { + await run(); + expect(store.spacePanelSpaces).toStrictEqual([]); + const space = mkSpace(space1); + const prom = emitPromise(store, UPDATE_TOP_LEVEL_SPACES); + emitter.emit("Room", space); + await prom; + expect(store.spacePanelSpaces).toStrictEqual([space]); + expect(store.invitedSpaces).toStrictEqual([]); + }); + + it("updates state when spaces are left", async () => { + const space = mkSpace(space1); + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([space]); + space.getMyMembership.mockReturnValue("leave"); + const prom = emitPromise(store, UPDATE_TOP_LEVEL_SPACES); + emitter.emit("Room.myMembership", space, "leave", "join"); + await prom; + expect(store.spacePanelSpaces).toStrictEqual([]); + }); + + it("updates state when space invite comes in", async () => { + await run(); + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([]); + const space = mkSpace(space1); + space.getMyMembership.mockReturnValue("invite"); + const prom = emitPromise(store, UPDATE_INVITED_SPACES); + emitter.emit("Room", space); + await prom; + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([space]); + }); + + it("updates state when space invite is accepted", async () => { + const space = mkSpace(space1); + space.getMyMembership.mockReturnValue("invite"); + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([space]); + space.getMyMembership.mockReturnValue("join"); + const prom = emitPromise(store, UPDATE_TOP_LEVEL_SPACES); + emitter.emit("Room.myMembership", space, "join", "invite"); + await prom; + expect(store.spacePanelSpaces).toStrictEqual([space]); + expect(store.invitedSpaces).toStrictEqual([]); + }); + + it("updates state when space invite is rejected", async () => { + const space = mkSpace(space1); + space.getMyMembership.mockReturnValue("invite"); + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([space]); + space.getMyMembership.mockReturnValue("leave"); + const prom = emitPromise(store, UPDATE_INVITED_SPACES); + emitter.emit("Room.myMembership", space, "leave", "invite"); + await prom; + expect(store.spacePanelSpaces).toStrictEqual([]); + expect(store.invitedSpaces).toStrictEqual([]); + }); + + it("room invite gets added to relevant space filters", async () => { + const space = mkSpace(space1, [invite1]); + await run(); + + expect(store.spacePanelSpaces).toStrictEqual([space]); + expect(store.invitedSpaces).toStrictEqual([]); + expect(store.getChildSpaces(space1)).toStrictEqual([]); + expect(store.getChildRooms(space1)).toStrictEqual([]); + expect(store.getSpaceFilteredRoomIds(client.getRoom(space1)).has(invite1)).toBeFalsy(); + expect(store.getSpaceFilteredRoomIds(null).has(invite1)).toBeFalsy(); + + const invite = mkRoom(invite1); + invite.getMyMembership.mockReturnValue("invite"); + const prom = emitPromise(store, space1); + emitter.emit("Room", space); + await prom; + + expect(store.spacePanelSpaces).toStrictEqual([space]); + expect(store.invitedSpaces).toStrictEqual([]); + expect(store.getChildSpaces(space1)).toStrictEqual([]); + expect(store.getChildRooms(space1)).toStrictEqual([invite]); + expect(store.getSpaceFilteredRoomIds(client.getRoom(space1)).has(invite1)).toBeTruthy(); + expect(store.getSpaceFilteredRoomIds(null).has(invite1)).toBeTruthy(); + }); + }); + + describe("active space switching tests", () => { + const fn = jest.spyOn(store, "emit"); + + beforeEach(async () => { + mkRoom(room1); // not a space + mkSpace(space1, [ + mkSpace(space2).roomId, + ]); + mkSpace(space3).getMyMembership.mockReturnValue("invite"); + await run(); + await store.setActiveSpace(null); + expect(store.activeSpace).toBe(null); + }); + afterEach(() => { + fn.mockClear(); + }); + + it("switch to home space", async () => { + await store.setActiveSpace(client.getRoom(space1)); + fn.mockClear(); + + await store.setActiveSpace(null); + expect(fn).toHaveBeenCalledWith(UPDATE_SELECTED_SPACE, null); + expect(store.activeSpace).toBe(null); + }); + + it("switch to invited space", async () => { + const space = client.getRoom(space3); + await store.setActiveSpace(space); + expect(fn).toHaveBeenCalledWith(UPDATE_SELECTED_SPACE, space); + expect(store.activeSpace).toBe(space); + }); + + it("switch to top level space", async () => { + const space = client.getRoom(space1); + await store.setActiveSpace(space); + expect(fn).toHaveBeenCalledWith(UPDATE_SELECTED_SPACE, space); + expect(store.activeSpace).toBe(space); + }); + + it("switch to subspace", async () => { + const space = client.getRoom(space2); + await store.setActiveSpace(space); + expect(fn).toHaveBeenCalledWith(UPDATE_SELECTED_SPACE, space); + expect(store.activeSpace).toBe(space); + }); + + it("switch to unknown space is a nop", async () => { + expect(store.activeSpace).toBe(null); + const space = client.getRoom(room1); // not a space + await store.setActiveSpace(space); + expect(fn).not.toHaveBeenCalledWith(UPDATE_SELECTED_SPACE, space); + expect(store.activeSpace).toBe(null); + }); + }); + + describe("context switching tests", () => { + const fn = jest.spyOn(defaultDispatcher, "dispatch"); + + beforeEach(async () => { + [room1, room2, orphan1].forEach(mkRoom); + mkSpace(space1, [room1, room2]); + mkSpace(space2, [room2]); + await run(); + }); + afterEach(() => { + fn.mockClear(); + localStorage.clear(); + }); + + const getCurrentRoom = () => fn.mock.calls.reverse().find(([p]) => p.action === "view_room")?.[0].room_id; + + it("last viewed room in target space is the current viewed and in both spaces", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room2); + await store.setActiveSpace(client.getRoom(space2)); + viewRoom(room2); + await store.setActiveSpace(client.getRoom(space1)); + expect(getCurrentRoom()).toBe(room2); + }); + + it("last viewed room in target space is in the current space", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room2); + await store.setActiveSpace(client.getRoom(space2)); + expect(getCurrentRoom()).toBe(space2); + await store.setActiveSpace(client.getRoom(space1)); + expect(getCurrentRoom()).toBe(room2); + }); + + it("last viewed room in target space is not in the current space", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room1); + await store.setActiveSpace(client.getRoom(space2)); + viewRoom(room2); + await store.setActiveSpace(client.getRoom(space1)); + expect(getCurrentRoom()).toBe(room1); + }); + + it("last viewed room is target space is not known", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room1); + localStorage.setItem(`mx_space_context_${space2}`, orphan2); + await store.setActiveSpace(client.getRoom(space2)); + expect(getCurrentRoom()).toBe(space2); + }); + + it("no last viewed room in target space", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room1); + await store.setActiveSpace(client.getRoom(space2)); + expect(getCurrentRoom()).toBe(space2); + }); + + it("no last viewed room in home space", async () => { + await store.setActiveSpace(client.getRoom(space1)); + viewRoom(room1); + await store.setActiveSpace(null); + expect(fn.mock.calls[fn.mock.calls.length - 1][0]).toStrictEqual({ action: "view_home_page" }); + }); + }); + + describe("space auto switching tests", () => { + beforeEach(async () => { + [room1, room2, orphan1].forEach(mkRoom); + mkSpace(space1, [room1, room2]); + mkSpace(space2, [room1, room2]); + + client.getRoom(room2).currentState.getStateEvents.mockImplementation(mockStateEventImplementation([ + mkEvent({ + event: true, + type: EventType.SpaceParent, + room: room2, + user: testUserId, + skey: space2, + content: { via: [], canonical: true }, + ts: Date.now(), + }), + ])); + await run(); + }); + + it("no switch required, room is in current space", async () => { + viewRoom(room1); + await store.setActiveSpace(client.getRoom(space1), false); + viewRoom(room2); + expect(store.activeSpace).toBe(client.getRoom(space1)); + }); + + it("switch to canonical parent space for room", async () => { + viewRoom(room1); + await store.setActiveSpace(null, false); + viewRoom(room2); + expect(store.activeSpace).toBe(client.getRoom(space2)); + }); + + it("switch to first containing space for room", async () => { + viewRoom(room2); + await store.setActiveSpace(null, false); + viewRoom(room1); + expect(store.activeSpace).toBe(client.getRoom(space1)); + }); + + it("switch to home for orphaned room", async () => { + viewRoom(room1); + await store.setActiveSpace(client.getRoom(space1), false); + viewRoom(orphan1); + expect(store.activeSpace).toBeNull(); + }); + }); + + describe("traverseSpace", () => { + beforeEach(() => { + mkSpace("!a:server", [ + mkSpace("!b:server", [ + mkSpace("!c:server", [ + "!a:server", + mkRoom("!c-child:server").roomId, + mkRoom("!shared-child:server").roomId, + ]).roomId, + mkRoom("!b-child:server").roomId, + ]).roomId, + mkRoom("!a-child:server").roomId, + "!shared-child:server", + ]); + }); + + it("avoids cycles", () => { + const fn = jest.fn(); + store.traverseSpace("!b:server", fn); + + expect(fn).toBeCalledTimes(3); + expect(fn).toBeCalledWith("!a:server"); + expect(fn).toBeCalledWith("!b:server"); + expect(fn).toBeCalledWith("!c:server"); + }); + + it("including rooms", () => { + const fn = jest.fn(); + store.traverseSpace("!b:server", fn, true); + + expect(fn).toBeCalledTimes(8); // twice for shared-child + expect(fn).toBeCalledWith("!a:server"); + expect(fn).toBeCalledWith("!a-child:server"); + expect(fn).toBeCalledWith("!b:server"); + expect(fn).toBeCalledWith("!b-child:server"); + expect(fn).toBeCalledWith("!c:server"); + expect(fn).toBeCalledWith("!c-child:server"); + expect(fn).toBeCalledWith("!shared-child:server"); + }); + + it("excluding rooms", () => { + const fn = jest.fn(); + store.traverseSpace("!b:server", fn, false); + + expect(fn).toBeCalledTimes(3); + expect(fn).toBeCalledWith("!a:server"); + expect(fn).toBeCalledWith("!b:server"); + expect(fn).toBeCalledWith("!c:server"); + }); + }); +}); diff --git a/test/test-utils.js b/test/test-utils.js index d259fcb95f..6dc02463a5 100644 --- a/test/test-utils.js +++ b/test/test-utils.js @@ -64,6 +64,11 @@ export function createTestClient() { getRoomIdForAlias: jest.fn().mockResolvedValue(undefined), getRoomDirectoryVisibility: jest.fn().mockResolvedValue(undefined), getProfileInfo: jest.fn().mockResolvedValue({}), + getThirdpartyProtocols: jest.fn().mockResolvedValue({}), + getClientWellKnown: jest.fn().mockReturnValue(null), + supportsVoip: jest.fn().mockReturnValue(true), + getTurnServersExpiry: jest.fn().mockReturnValue(2^32), + getThirdpartyUser: jest.fn().mockResolvedValue([]), getAccountData: (type) => { return mkEvent({ type, @@ -79,6 +84,17 @@ export function createTestClient() { generateClientSecret: () => "t35tcl1Ent5ECr3T", isGuest: () => false, isCryptoEnabled: () => false, + getSpaceSummary: jest.fn().mockReturnValue({ + rooms: [], + events: [], + }), + + // Used by various internal bits we aren't concerned with (yet) + _sessionStore: { + store: { + getItem: jest.fn(), + }, + }, }; } @@ -88,8 +104,8 @@ export function createTestClient() { * @param {string} opts.type The event.type * @param {string} opts.room The event.room_id * @param {string} opts.user The event.user_id - * @param {string} opts.skey Optional. The state key (auto inserts empty string) - * @param {Number} opts.ts Optional. Timestamp for the event + * @param {string=} opts.skey Optional. The state key (auto inserts empty string) + * @param {number=} opts.ts Optional. Timestamp for the event * @param {Object} opts.content The event.content * @param {boolean} opts.event True to make a MatrixEvent. * @return {Object} a JSON object representing this event. @@ -224,7 +240,7 @@ export function mkStubRoom(roomId = null) { hasMembershipState: () => null, getVersion: () => '1', shouldUpgradeToVersion: () => null, - getMyMembership: () => "join", + getMyMembership: jest.fn().mockReturnValue("join"), maySendMessage: jest.fn().mockReturnValue(true), currentState: { getStateEvents: jest.fn(), @@ -233,17 +249,17 @@ export function mkStubRoom(roomId = null) { maySendEvent: jest.fn().mockReturnValue(true), members: [], }, - tags: { - "m.favourite": { - order: 0.5, - }, - }, + tags: {}, setBlacklistUnverifiedDevices: jest.fn(), on: jest.fn(), removeListener: jest.fn(), getDMInviter: jest.fn(), getAvatarUrl: () => 'mxc://avatar.url/room.png', getMxcAvatarUrl: () => 'mxc://avatar.url/room.png', + isSpaceRoom: jest.fn(() => false), + getUnreadNotificationCount: jest.fn(() => 0), + getEventReadUpTo: jest.fn(() => null), + timeline: [], }; } diff --git a/test/utils/MegolmExportEncryption-test.js b/test/utils/MegolmExportEncryption-test.js index e0ed5ba26a..07ec03860b 100644 --- a/test/utils/MegolmExportEncryption-test.js +++ b/test/utils/MegolmExportEncryption-test.js @@ -84,22 +84,22 @@ describe('MegolmExportEncryption', function() { it('should handle missing header', function() { const input=stringToArray(`-----`); return MegolmExportEncryption.decryptMegolmKeyFile(input, '') - .then((res) => { - throw new Error('expected to throw'); - }, (error) => { - expect(error.message).toEqual('Header line not found'); - }); + .then((res) => { + throw new Error('expected to throw'); + }, (error) => { + expect(error.message).toEqual('Header line not found'); + }); }); it('should handle missing trailer', function() { const input=stringToArray(`-----BEGIN MEGOLM SESSION DATA----- -----`); return MegolmExportEncryption.decryptMegolmKeyFile(input, '') - .then((res) => { - throw new Error('expected to throw'); - }, (error) => { - expect(error.message).toEqual('Trailer line not found'); - }); + .then((res) => { + throw new Error('expected to throw'); + }, (error) => { + expect(error.message).toEqual('Trailer line not found'); + }); }); it('should handle a too-short body', function() { @@ -109,11 +109,11 @@ cissyYBxjsfsAn -----END MEGOLM SESSION DATA----- `); return MegolmExportEncryption.decryptMegolmKeyFile(input, '') - .then((res) => { - throw new Error('expected to throw'); - }, (error) => { - expect(error.message).toEqual('Invalid file: too short'); - }); + .then((res) => { + throw new Error('expected to throw'); + }, (error) => { + expect(error.message).toEqual('Invalid file: too short'); + }); }); // TODO find a subtlecrypto shim which doesn't break this test diff --git a/test/utils/ShieldUtils-test.js b/test/utils/ShieldUtils-test.js index 8e3b19c1c4..fdf4f527ee 100644 --- a/test/utils/ShieldUtils-test.js +++ b/test/utils/ShieldUtils-test.js @@ -26,7 +26,7 @@ describe("mkClient self-test", function() { ["@TF:h", true], ["@FT:h", false], ["@FF:h", false]], - )("behaves well for user trust %s", (userId, trust) => { + )("behaves well for user trust %s", (userId, trust) => { expect(mkClient().checkUserTrust(userId).isCrossSigningVerified()).toBe(trust); }); @@ -35,7 +35,7 @@ describe("mkClient self-test", function() { ["@TF:h", false], ["@FT:h", true], ["@FF:h", false]], - )("behaves well for device trust %s", (userId, trust) => { + )("behaves well for device trust %s", (userId, trust) => { expect(mkClient().checkDeviceTrust(userId, "device").isVerified()).toBe(trust); }); }); @@ -128,7 +128,7 @@ describe("shieldStatusForMembership self-trust behaviour", function() { describe("shieldStatusForMembership other-trust behaviour", function() { beforeAll(() => { - DMRoomMap._sharedInstance = { + DMRoomMap.sharedInstance = { getUserIdForRoomId: (roomId) => roomId === "DM" ? "@any:h" : null, }; }); diff --git a/test/utils/Singleflight-test.ts b/test/utils/Singleflight-test.ts new file mode 100644 index 0000000000..80258701bb --- /dev/null +++ b/test/utils/Singleflight-test.ts @@ -0,0 +1,115 @@ +/* +Copyright 2021 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. +*/ + +import {Singleflight} from "../../src/utils/Singleflight"; + +describe('Singleflight', () => { + afterEach(() => { + Singleflight.forgetAll(); + }); + + it('should throw for bad context variables', () => { + const permutations: [Object, string][] = [ + [null, null], + [{}, null], + [null, "test"], + ]; + for (const p of permutations) { + try { + Singleflight.for(p[0], p[1]); + // noinspection ExceptionCaughtLocallyJS + throw new Error("failed to fail: " + JSON.stringify(p)); + } catch (e) { + expect(e.message).toBe("An instance and key must be supplied"); + } + } + }); + + it('should execute the function once', () => { + const instance = {}; + const key = "test"; + const val = {}; // unique object for reference check + const fn = jest.fn().mockReturnValue(val); + const sf = Singleflight.for(instance, key); + const r1 = sf.do(fn); + expect(r1).toBe(val); + expect(fn.mock.calls.length).toBe(1); + const r2 = sf.do(fn); + expect(r2).toBe(val); + expect(fn.mock.calls.length).toBe(1); + }); + + it('should execute the function once, even with new contexts', () => { + const instance = {}; + const key = "test"; + const val = {}; // unique object for reference check + const fn = jest.fn().mockReturnValue(val); + let sf = Singleflight.for(instance, key); + const r1 = sf.do(fn); + expect(r1).toBe(val); + expect(fn.mock.calls.length).toBe(1); + sf = Singleflight.for(instance, key); // RESET FOR TEST + const r2 = sf.do(fn); + expect(r2).toBe(val); + expect(fn.mock.calls.length).toBe(1); + }); + + it('should execute the function twice if the result was forgotten', () => { + const instance = {}; + const key = "test"; + const val = {}; // unique object for reference check + const fn = jest.fn().mockReturnValue(val); + const sf = Singleflight.for(instance, key); + const r1 = sf.do(fn); + expect(r1).toBe(val); + expect(fn.mock.calls.length).toBe(1); + sf.forget(); + const r2 = sf.do(fn); + expect(r2).toBe(val); + expect(fn.mock.calls.length).toBe(2); + }); + + it('should execute the function twice if the instance was forgotten', () => { + const instance = {}; + const key = "test"; + const val = {}; // unique object for reference check + const fn = jest.fn().mockReturnValue(val); + const sf = Singleflight.for(instance, key); + const r1 = sf.do(fn); + expect(r1).toBe(val); + expect(fn.mock.calls.length).toBe(1); + Singleflight.forgetAllFor(instance); + const r2 = sf.do(fn); + expect(r2).toBe(val); + expect(fn.mock.calls.length).toBe(2); + }); + + it('should execute the function twice if everything was forgotten', () => { + const instance = {}; + const key = "test"; + const val = {}; // unique object for reference check + const fn = jest.fn().mockReturnValue(val); + const sf = Singleflight.for(instance, key); + const r1 = sf.do(fn); + expect(r1).toBe(val); + expect(fn.mock.calls.length).toBe(1); + Singleflight.forgetAll(); + const r2 = sf.do(fn); + expect(r2).toBe(val); + expect(fn.mock.calls.length).toBe(2); + }); +}); + diff --git a/test/utils/arrays-test.ts b/test/utils/arrays-test.ts new file mode 100644 index 0000000000..c5be59ab43 --- /dev/null +++ b/test/utils/arrays-test.ts @@ -0,0 +1,327 @@ +/* +Copyright 2021 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. +*/ + +import { + arrayDiff, + arrayFastClone, + arrayFastResample, + arrayHasDiff, + arrayHasOrderChange, + arrayMerge, + arraySeed, + arrayTrimFill, + arrayUnion, + ArrayUtil, + GroupedArray, +} from "../../src/utils/arrays"; +import {objectFromEntries} from "../../src/utils/objects"; + +function expectSample(i: number, input: number[], expected: number[]) { + console.log(`Resample case index: ${i}`); // for debugging test failures + const result = arrayFastResample(input, expected.length); + expect(result).toBeDefined(); + expect(result).toHaveLength(expected.length); + expect(result).toEqual(expected); +} + +describe('arrays', () => { + describe('arrayFastResample', () => { + it('should downsample', () => { + [ + {input: [1, 2, 3, 4, 5], output: [1, 4]}, // Odd -> Even + {input: [1, 2, 3, 4, 5], output: [1, 3, 5]}, // Odd -> Odd + {input: [1, 2, 3, 4], output: [1, 2, 3]}, // Even -> Odd + {input: [1, 2, 3, 4], output: [1, 3]}, // Even -> Even + ].forEach((c, i) => expectSample(i, c.input, c.output)); + }); + + it('should upsample', () => { + [ + {input: [1, 2, 3], output: [1, 1, 2, 2, 3, 3]}, // Odd -> Even + {input: [1, 2, 3], output: [1, 1, 2, 2, 3]}, // Odd -> Odd + {input: [1, 2], output: [1, 1, 1, 2, 2]}, // Even -> Odd + {input: [1, 2], output: [1, 1, 1, 2, 2, 2]}, // Even -> Even + ].forEach((c, i) => expectSample(i, c.input, c.output)); + }); + + it('should maintain sample', () => { + [ + {input: [1, 2, 3], output: [1, 2, 3]}, // Odd + {input: [1, 2], output: [1, 2]}, // Even + ].forEach((c, i) => expectSample(i, c.input, c.output)); + }); + }); + + describe('arrayTrimFill', () => { + it('should shrink arrays', () => { + const input = [1, 2, 3]; + const output = [1, 2]; + const seed = [4, 5, 6]; + const result = arrayTrimFill(input, output.length, seed); + expect(result).toBeDefined(); + expect(result).toHaveLength(output.length); + expect(result).toEqual(output); + }); + + it('should expand arrays', () => { + const input = [1, 2, 3]; + const output = [1, 2, 3, 4, 5]; + const seed = [4, 5, 6]; + const result = arrayTrimFill(input, output.length, seed); + expect(result).toBeDefined(); + expect(result).toHaveLength(output.length); + expect(result).toEqual(output); + }); + + it('should keep arrays the same', () => { + const input = [1, 2, 3]; + const output = [1, 2, 3]; + const seed = [4, 5, 6]; + const result = arrayTrimFill(input, output.length, seed); + expect(result).toBeDefined(); + expect(result).toHaveLength(output.length); + expect(result).toEqual(output); + }); + }); + + describe('arraySeed', () => { + it('should create an array of given length', () => { + const val = 1; + const output = [val, val, val]; + const result = arraySeed(val, output.length); + expect(result).toBeDefined(); + expect(result).toHaveLength(output.length); + expect(result).toEqual(output); + }); + it('should maintain pointers', () => { + const val = {}; // this works because `{} !== {}`, which is what toEqual checks + const output = [val, val, val]; + const result = arraySeed(val, output.length); + expect(result).toBeDefined(); + expect(result).toHaveLength(output.length); + expect(result).toEqual(output); + }); + }); + + describe('arrayFastClone', () => { + it('should break pointer reference on source array', () => { + const val = {}; // we'll test to make sure the values maintain pointers too + const input = [val, val, val]; + const result = arrayFastClone(input); + expect(result).toBeDefined(); + expect(result).toHaveLength(input.length); + expect(result).toEqual(input); // we want the array contents to match... + expect(result).not.toBe(input); // ... but be a different reference + }); + }); + + describe('arrayHasOrderChange', () => { + it('should flag true on B ordering difference', () => { + const a = [1, 2, 3]; + const b = [3, 2, 1]; + const result = arrayHasOrderChange(a, b); + expect(result).toBe(true); + }); + + it('should flag false on no ordering difference', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3]; + const result = arrayHasOrderChange(a, b); + expect(result).toBe(false); + }); + + it('should flag true on A length > B length', () => { + const a = [1, 2, 3, 4]; + const b = [1, 2, 3]; + const result = arrayHasOrderChange(a, b); + expect(result).toBe(true); + }); + + it('should flag true on A length < B length', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3, 4]; + const result = arrayHasOrderChange(a, b); + expect(result).toBe(true); + }); + }); + + describe('arrayHasDiff', () => { + it('should flag true on A length > B length', () => { + const a = [1, 2, 3, 4]; + const b = [1, 2, 3]; + const result = arrayHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag true on A length < B length', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3, 4]; + const result = arrayHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag true on element differences', () => { + const a = [1, 2, 3]; + const b = [4, 5, 6]; + const result = arrayHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag false if same but order different', () => { + const a = [1, 2, 3]; + const b = [3, 1, 2]; + const result = arrayHasDiff(a, b); + expect(result).toBe(false); + }); + + it('should flag false if same', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3]; + const result = arrayHasDiff(a, b); + expect(result).toBe(false); + }); + }); + + describe('arrayDiff', () => { + it('should see added from A->B', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3, 4]; + const result = arrayDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(0); + expect(result.added).toEqual([4]); + }); + + it('should see removed from A->B', () => { + const a = [1, 2, 3]; + const b = [1, 2]; + const result = arrayDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(1); + expect(result.removed).toEqual([3]); + }); + + it('should see added and removed in the same set', () => { + const a = [1, 2, 3]; + const b = [1, 2, 4]; // note diff + const result = arrayDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(1); + expect(result.added).toEqual([4]); + expect(result.removed).toEqual([3]); + }); + }); + + describe('arrayUnion', () => { + it('should return a union', () => { + const a = [1, 2, 3]; + const b = [1, 2, 4]; // note diff + const result = arrayUnion(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(2); + expect(result).toEqual([1, 2]); + }); + + it('should return an empty array on no matches', () => { + const a = [1, 2, 3]; + const b = [4, 5, 6]; + const result = arrayUnion(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + }); + + describe('arrayMerge', () => { + it('should merge 3 arrays with deduplication', () => { + const a = [1, 2, 3]; + const b = [1, 2, 4, 5]; // note missing 3 + const c = [6, 7, 8, 9]; + const result = arrayMerge(a, b, c); + expect(result).toBeDefined(); + expect(result).toHaveLength(9); + expect(result).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it('should deduplicate a single array', () => { + // dev note: this is technically an edge case, but it is described behaviour if the + // function is only provided one function (it'll merge the array against itself) + const a = [1, 1, 2, 2, 3, 3]; + const result = arrayMerge(a); + expect(result).toBeDefined(); + expect(result).toHaveLength(3); + expect(result).toEqual([1, 2, 3]); + }); + }); + + describe('ArrayUtil', () => { + it('should maintain the pointer to the given array', () => { + const input = [1, 2, 3]; + const result = new ArrayUtil(input); + expect(result.value).toBe(input); + }); + + it('should group appropriately', () => { + const input = [['a', 1], ['b', 2], ['c', 3], ['a', 4], ['a', 5], ['b', 6]]; + const output = { + 'a': [['a', 1], ['a', 4], ['a', 5]], + 'b': [['b', 2], ['b', 6]], + 'c': [['c', 3]], + }; + const result = new ArrayUtil(input).groupBy(p => p[0]); + expect(result).toBeDefined(); + expect(result.value).toBeDefined(); + + const asObject = objectFromEntries(result.value.entries()); + expect(asObject).toMatchObject(output); + }); + }); + + describe('GroupedArray', () => { + it('should maintain the pointer to the given map', () => { + const input = new Map([ + ['a', [1, 2, 3]], + ['b', [7, 8, 9]], + ['c', [4, 5, 6]], + ]); + const result = new GroupedArray(input); + expect(result.value).toBe(input); + }); + + it('should ordering by the provided key order', () => { + const input = new Map([ + ['a', [1, 2, 3]], + ['b', [7, 8, 9]], // note counting diff + ['c', [4, 5, 6]], + ]); + const output = [4, 5, 6, 1, 2, 3, 7, 8, 9]; + const keyOrder = ['c', 'a', 'b']; // note weird order to cause the `output` to be strange + const result = new GroupedArray(input).orderBy(keyOrder); + expect(result).toBeDefined(); + expect(result.value).toBeDefined(); + expect(result.value).toEqual(output); + }); + }); +}); + diff --git a/test/utils/enums-test.ts b/test/utils/enums-test.ts new file mode 100644 index 0000000000..423b135f77 --- /dev/null +++ b/test/utils/enums-test.ts @@ -0,0 +1,67 @@ +/* +Copyright 2021 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. +*/ + +import {getEnumValues, isEnumValue} from "../../src/utils/enums"; + +enum TestStringEnum { + First = "__first__", + Second = "__second__", +} + +enum TestNumberEnum { + FirstKey = 10, + SecondKey = 20, +} + +describe('enums', () => { + describe('getEnumValues', () => { + it('should work on string enums', () => { + const result = getEnumValues(TestStringEnum); + expect(result).toBeDefined(); + expect(result).toHaveLength(2); + expect(result).toEqual(['__first__', '__second__']); + }); + + it('should work on number enums', () => { + const result = getEnumValues(TestNumberEnum); + expect(result).toBeDefined(); + expect(result).toHaveLength(2); + expect(result).toEqual([10, 20]); + }); + }); + + describe('isEnumValue', () => { + it('should return true on values in a string enum', () => { + const result = isEnumValue(TestStringEnum, '__first__'); + expect(result).toBe(true); + }); + + it('should return false on values not in a string enum', () => { + const result = isEnumValue(TestStringEnum, 'not a value'); + expect(result).toBe(false); + }); + + it('should return true on values in a number enum', () => { + const result = isEnumValue(TestNumberEnum, 10); + expect(result).toBe(true); + }); + + it('should return false on values not in a number enum', () => { + const result = isEnumValue(TestStringEnum, 99); + expect(result).toBe(false); + }); + }); +}); diff --git a/test/utils/iterables-test.ts b/test/utils/iterables-test.ts new file mode 100644 index 0000000000..9b30b6241c --- /dev/null +++ b/test/utils/iterables-test.ts @@ -0,0 +1,77 @@ +/* +Copyright 2021 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. +*/ + +import {iterableDiff, iterableUnion} from "../../src/utils/iterables"; + +describe('iterables', () => { + describe('iterableUnion', () => { + it('should return a union', () => { + const a = [1, 2, 3]; + const b = [1, 2, 4]; // note diff + const result = iterableUnion(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(2); + expect(result).toEqual([1, 2]); + }); + + it('should return an empty array on no matches', () => { + const a = [1, 2, 3]; + const b = [4, 5, 6]; + const result = iterableUnion(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + }); + + describe('iterableDiff', () => { + it('should see added from A->B', () => { + const a = [1, 2, 3]; + const b = [1, 2, 3, 4]; + const result = iterableDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(0); + expect(result.added).toEqual([4]); + }); + + it('should see removed from A->B', () => { + const a = [1, 2, 3]; + const b = [1, 2]; + const result = iterableDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(1); + expect(result.removed).toEqual([3]); + }); + + it('should see added and removed in the same set', () => { + const a = [1, 2, 3]; + const b = [1, 2, 4]; // note diff + const result = iterableDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(1); + expect(result.added).toEqual([4]); + expect(result.removed).toEqual([3]); + }); + }); +}); diff --git a/test/utils/maps-test.ts b/test/utils/maps-test.ts new file mode 100644 index 0000000000..8764a8f2cf --- /dev/null +++ b/test/utils/maps-test.ts @@ -0,0 +1,245 @@ +/* +Copyright 2021 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. +*/ + +import {EnhancedMap, mapDiff, mapKeyChanges} from "../../src/utils/maps"; + +describe('maps', () => { + describe('mapDiff', () => { + it('should indicate no differences when the pointers are the same', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const result = mapDiff(a, a); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.changed).toHaveLength(0); + }); + + it('should indicate no differences when there are none', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2], [3, 3]]); + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.changed).toHaveLength(0); + }); + + it('should indicate added properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2], [3, 3], [4, 4]]); + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(0); + expect(result.changed).toHaveLength(0); + expect(result.added).toEqual([4]); + }); + + it('should indicate removed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2]]); + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(1); + expect(result.changed).toHaveLength(0); + expect(result.removed).toEqual([3]); + }); + + it('should indicate changed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2], [3, 4]]); // note change + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.changed).toHaveLength(1); + expect(result.changed).toEqual([3]); + }); + + it('should indicate changed, added, and removed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 8], [4, 4]]); // note change + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(1); + expect(result.changed).toHaveLength(1); + expect(result.added).toEqual([4]); + expect(result.removed).toEqual([3]); + expect(result.changed).toEqual([2]); + }); + + it('should indicate changes for difference in pointers', () => { + const a = new Map([[1, {}]]); // {} always creates a new object + const b = new Map([[1, {}]]); + const result = mapDiff(a, b); + expect(result).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.changed).toHaveLength(1); + expect(result.changed).toEqual([1]); + }); + }); + + describe('mapKeyChanges', () => { + it('should indicate no changes for unchanged pointers', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const result = mapKeyChanges(a, a); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + + it('should indicate no changes for unchanged maps with different pointers', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2], [3, 3]]); + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + + it('should indicate changes for added properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 2], [3, 3], [4, 4]]); + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(1); + expect(result).toEqual([4]); + }); + + it('should indicate changes for removed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3], [4, 4]]); + const b = new Map([[1, 1], [2, 2], [3, 3]]); + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(1); + expect(result).toEqual([4]); + }); + + it('should indicate changes for changed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3], [4, 4]]); + const b = new Map([[1, 1], [2, 2], [3, 3], [4, 55]]); + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(1); + expect(result).toEqual([4]); + }); + + it('should indicate changes for properties with different pointers', () => { + const a = new Map([[1, {}]]); // {} always creates a new object + const b = new Map([[1, {}]]); + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(1); + expect(result).toEqual([1]); + }); + + it('should indicate changes for changed, added, and removed properties', () => { + const a = new Map([[1, 1], [2, 2], [3, 3]]); + const b = new Map([[1, 1], [2, 8], [4, 4]]); // note change + const result = mapKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(3); + expect(result).toEqual([3, 4, 2]); // order irrelevant, but the test cares + }); + }); + + describe('EnhancedMap', () => { + // Most of these tests will make sure it implements the Map class + + it('should be empty by default', () => { + const result = new EnhancedMap(); + expect(result.size).toBe(0); + }); + + it('should use the provided entries', () => { + const obj = {a: 1, b: 2}; + const result = new EnhancedMap(Object.entries(obj)); + expect(result.size).toBe(2); + expect(result.get('a')).toBe(1); + expect(result.get('b')).toBe(2); + }); + + it('should create keys if they do not exist', () => { + const key = 'a'; + const val = {}; // we'll check pointers + + const result = new EnhancedMap(); + expect(result.size).toBe(0); + + let get = result.getOrCreate(key, val); + expect(get).toBeDefined(); + expect(get).toBe(val); + expect(result.size).toBe(1); + + get = result.getOrCreate(key, 44); // specifically change `val` + expect(get).toBeDefined(); + expect(get).toBe(val); + expect(result.size).toBe(1); + + get = result.get(key); // use the base class function + expect(get).toBeDefined(); + expect(get).toBe(val); + expect(result.size).toBe(1); + }); + + it('should proxy remove to delete and return it', () => { + const val = {}; + const result = new EnhancedMap(); + result.set('a', val); + + expect(result.size).toBe(1); + + const removed = result.remove('a'); + expect(result.size).toBe(0); + expect(removed).toBeDefined(); + expect(removed).toBe(val); + }); + + it('should support removing unknown keys', () => { + const val = {}; + const result = new EnhancedMap(); + result.set('a', val); + + expect(result.size).toBe(1); + + const removed = result.remove('not-a'); + expect(result.size).toBe(1); + expect(removed).not.toBeDefined(); + }); + }); +}); diff --git a/test/utils/numbers-test.ts b/test/utils/numbers-test.ts new file mode 100644 index 0000000000..36e7d4f7e7 --- /dev/null +++ b/test/utils/numbers-test.ts @@ -0,0 +1,163 @@ +/* +Copyright 2021 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. +*/ + +import {clamp, defaultNumber, percentageOf, percentageWithin, sum} from "../../src/utils/numbers"; + +describe('numbers', () => { + describe('defaultNumber', () => { + it('should use the default when the input is not a number', () => { + const def = 42; + + let result = defaultNumber(null, def); + expect(result).toBe(def); + + result = defaultNumber(undefined, def); + expect(result).toBe(def); + + result = defaultNumber(Number.NaN, def); + expect(result).toBe(def); + }); + + it('should use the number when it is a number', () => { + const input = 24; + const def = 42; + const result = defaultNumber(input, def); + expect(result).toBe(input); + }); + }); + + describe('clamp', () => { + it('should clamp high numbers', () => { + const input = 101; + const min = 0; + const max = 100; + const result = clamp(input, min, max); + expect(result).toBe(max); + }); + + it('should clamp low numbers', () => { + const input = -1; + const min = 0; + const max = 100; + const result = clamp(input, min, max); + expect(result).toBe(min); + }); + + it('should not clamp numbers in range', () => { + const input = 50; + const min = 0; + const max = 100; + const result = clamp(input, min, max); + expect(result).toBe(input); + }); + + it('should clamp floats', () => { + const min = -0.10; + const max = +0.10; + + let result = clamp(-1.2, min, max); + expect(result).toBe(min); + + result = clamp(1.2, min, max); + expect(result).toBe(max); + + result = clamp(0.02, min, max); + expect(result).toBe(0.02); + }); + }); + + describe('sum', () => { + it('should sum', () => { // duh + const result = sum(1, 2, 1, 4); + expect(result).toBe(8); + }); + }); + + describe('percentageWithin', () => { + it('should work within 0-100', () => { + const result = percentageWithin(0.4, 0, 100); + expect(result).toBe(40); + }); + + it('should work within 0-100 when pct > 1', () => { + const result = percentageWithin(1.4, 0, 100); + expect(result).toBe(140); + }); + + it('should work within 0-100 when pct < 0', () => { + const result = percentageWithin(-1.4, 0, 100); + expect(result).toBe(-140); + }); + + it('should work with ranges other than 0-100', () => { + const result = percentageWithin(0.4, 10, 20); + expect(result).toBe(14); + }); + + it('should work with ranges other than 0-100 when pct > 1', () => { + const result = percentageWithin(1.4, 10, 20); + expect(result).toBe(24); + }); + + it('should work with ranges other than 0-100 when pct < 0', () => { + const result = percentageWithin(-1.4, 10, 20); + expect(result).toBe(-4); + }); + + it('should work with floats', () => { + const result = percentageWithin(0.4, 10.2, 20.4); + expect(result).toBe(14.28); + }); + }); + + // These are the inverse of percentageWithin + describe('percentageOf', () => { + it('should work within 0-100', () => { + const result = percentageOf(40, 0, 100); + expect(result).toBe(0.4); + }); + + it('should work within 0-100 when val > 100', () => { + const result = percentageOf(140, 0, 100); + expect(result).toBe(1.40); + }); + + it('should work within 0-100 when val < 0', () => { + const result = percentageOf(-140, 0, 100); + expect(result).toBe(-1.40); + }); + + it('should work with ranges other than 0-100', () => { + const result = percentageOf(14, 10, 20); + expect(result).toBe(0.4); + }); + + it('should work with ranges other than 0-100 when val > 100', () => { + const result = percentageOf(24, 10, 20); + expect(result).toBe(1.4); + }); + + it('should work with ranges other than 0-100 when val < 0', () => { + const result = percentageOf(-4, 10, 20); + expect(result).toBe(-1.4); + }); + + it('should work with floats', () => { + const result = percentageOf(14.28, 10.2, 20.4); + expect(result).toBe(0.4); + }); + }); +}); diff --git a/test/utils/objects-test.ts b/test/utils/objects-test.ts new file mode 100644 index 0000000000..b7a80e6761 --- /dev/null +++ b/test/utils/objects-test.ts @@ -0,0 +1,262 @@ +/* +Copyright 2021 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. +*/ + +import { + objectClone, + objectDiff, + objectExcluding, + objectFromEntries, + objectHasDiff, + objectKeyChanges, + objectShallowClone, + objectWithOnly, +} from "../../src/utils/objects"; + +describe('objects', () => { + describe('objectExcluding', () => { + it('should exclude the given properties', () => { + const input = {hello: "world", test: true}; + const output = {hello: "world"}; + const props = ["test", "doesnotexist"]; // we also make sure it doesn't explode on missing props + const result = objectExcluding(input, props); // any is to test the missing prop + expect(result).toBeDefined(); + expect(result).toMatchObject(output); + }); + }); + + describe('objectWithOnly', () => { + it('should exclusively use the given properties', () => { + const input = {hello: "world", test: true}; + const output = {hello: "world"}; + const props = ["hello", "doesnotexist"]; // we also make sure it doesn't explode on missing props + const result = objectWithOnly(input, props); // any is to test the missing prop + expect(result).toBeDefined(); + expect(result).toMatchObject(output); + }); + }); + + describe('objectShallowClone', () => { + it('should create a new object', () => { + const input = {test: 1}; + const result = objectShallowClone(input); + expect(result).toBeDefined(); + expect(result).not.toBe(input); + expect(result).toMatchObject(input); + }); + + it('should only clone the top level properties', () => { + const input = {a: 1, b: {c: 2}}; + const result = objectShallowClone(input); + expect(result).toBeDefined(); + expect(result).toMatchObject(input); + expect(result.b).toBe(input.b); + }); + + it('should support custom clone functions', () => { + const input = {a: 1, b: 2}; + const output = {a: 4, b: 8}; + const result = objectShallowClone(input, (k, v) => { + // XXX: inverted expectation for ease of assertion + expect(Object.keys(input)).toContain(k); + + return v * 4; + }); + expect(result).toBeDefined(); + expect(result).toMatchObject(output); + }); + }); + + describe('objectHasDiff', () => { + it('should return false for the same pointer', () => { + const a = {}; + const result = objectHasDiff(a, a); + expect(result).toBe(false); + }); + + it('should return true if keys for A > keys for B', () => { + const a = {a: 1, b: 2}; + const b = {a: 1}; + const result = objectHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should return true if keys for A < keys for B', () => { + const a = {a: 1}; + const b = {a: 1, b: 2}; + const result = objectHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should return false if the objects are the same but different pointers', () => { + const a = {a: 1, b: 2}; + const b = {a: 1, b: 2}; + const result = objectHasDiff(a, b); + expect(result).toBe(false); + }); + + it('should consider pointers when testing values', () => { + const a = {a: {}, b: 2}; // `{}` is shorthand for `new Object()` + const b = {a: {}, b: 2}; + const result = objectHasDiff(a, b); + expect(result).toBe(true); // even though the keys are the same, the value pointers vary + }); + }); + + describe('objectDiff', () => { + it('should return empty sets for the same object', () => { + const a = {a: 1, b: 2}; + const b = {a: 1, b: 2}; + const result = objectDiff(a, b); + expect(result).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(0); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + }); + + it('should return empty sets for the same object pointer', () => { + const a = {a: 1, b: 2}; + const result = objectDiff(a, a); + expect(result).toBeDefined(); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(0); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + }); + + it('should indicate when property changes are made', () => { + const a = {a: 1, b: 2}; + const b = {a: 11, b: 2}; + const result = objectDiff(a, b); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(1); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(0); + expect(result.changed).toEqual(['a']); + }); + + it('should indicate when properties are added', () => { + const a = {a: 1, b: 2}; + const b = {a: 1, b: 2, c: 3}; + const result = objectDiff(a, b); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(0); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(0); + expect(result.added).toEqual(['c']); + }); + + it('should indicate when properties are removed', () => { + const a = {a: 1, b: 2}; + const b = {a: 1}; + const result = objectDiff(a, b); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(0); + expect(result.added).toHaveLength(0); + expect(result.removed).toHaveLength(1); + expect(result.removed).toEqual(['b']); + }); + + it('should indicate when multiple aspects change', () => { + const a = {a: 1, b: 2, c: 3}; + const b: (typeof a | {d: number}) = {a: 1, b: 22, d: 4}; + const result = objectDiff(a, b); + expect(result.changed).toBeDefined(); + expect(result.added).toBeDefined(); + expect(result.removed).toBeDefined(); + expect(result.changed).toHaveLength(1); + expect(result.added).toHaveLength(1); + expect(result.removed).toHaveLength(1); + expect(result.changed).toEqual(['b']); + expect(result.removed).toEqual(['c']); + expect(result.added).toEqual(['d']); + }); + }); + + describe('objectKeyChanges', () => { + it('should return an empty set if no properties changed', () => { + const a = {a: 1, b: 2}; + const b = {a: 1, b: 2}; + const result = objectKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + + it('should return an empty set if no properties changed for the same pointer', () => { + const a = {a: 1, b: 2}; + const result = objectKeyChanges(a, a); + expect(result).toBeDefined(); + expect(result).toHaveLength(0); + }); + + it('should return properties which were changed, added, or removed', () => { + const a = {a: 1, b: 2, c: 3}; + const b: (typeof a | {d: number}) = {a: 1, b: 22, d: 4}; + const result = objectKeyChanges(a, b); + expect(result).toBeDefined(); + expect(result).toHaveLength(3); + expect(result).toEqual(['c', 'd', 'b']); // order isn't important, but the test cares + }); + }); + + describe('objectClone', () => { + it('should deep clone an object', () => { + const a = { + hello: "world", + test: { + another: "property", + test: 42, + third: { + prop: true, + }, + }, + }; + const result = objectClone(a); + expect(result).toBeDefined(); + expect(result).not.toBe(a); + expect(result).toMatchObject(a); + expect(result.test).not.toBe(a.test); + expect(result.test.third).not.toBe(a.test.third); + }); + }); + + describe('objectFromEntries', () => { + it('should create an object from an array of entries', () => { + const output = {a: 1, b: 2, c: 3}; + const result = objectFromEntries(Object.entries(output)); + expect(result).toBeDefined(); + expect(result).toMatchObject(output); + }); + + it('should maintain pointers in values', () => { + const output = {a: {}, b: 2, c: 3}; + const result = objectFromEntries(Object.entries(output)); + expect(result).toBeDefined(); + expect(result).toMatchObject(output); + expect(result['a']).toBe(output.a); + }); + }); +}); diff --git a/test/utils/sets-test.ts b/test/utils/sets-test.ts new file mode 100644 index 0000000000..98dc218309 --- /dev/null +++ b/test/utils/sets-test.ts @@ -0,0 +1,56 @@ +/* +Copyright 2021 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. +*/ + +import {setHasDiff} from "../../src/utils/sets"; + +describe('sets', () => { + describe('setHasDiff', () => { + it('should flag true on A length > B length', () => { + const a = new Set([1, 2, 3, 4]); + const b = new Set([1, 2, 3]); + const result = setHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag true on A length < B length', () => { + const a = new Set([1, 2, 3]); + const b = new Set([1, 2, 3, 4]); + const result = setHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag true on element differences', () => { + const a = new Set([1, 2, 3]); + const b = new Set([4, 5, 6]); + const result = setHasDiff(a, b); + expect(result).toBe(true); + }); + + it('should flag false if same but order different', () => { + const a = new Set([1, 2, 3]); + const b = new Set([3, 1, 2]); + const result = setHasDiff(a, b); + expect(result).toBe(false); + }); + + it('should flag false if same', () => { + const a = new Set([1, 2, 3]); + const b = new Set([1, 2, 3]); + const result = setHasDiff(a, b); + expect(result).toBe(false); + }); + }); +}); diff --git a/test/utils/test-utils.ts b/test/utils/test-utils.ts new file mode 100644 index 0000000000..af92987a3d --- /dev/null +++ b/test/utils/test-utils.ts @@ -0,0 +1,33 @@ +/* +Copyright 2021 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. +*/ + +import { MatrixClient } from "matrix-js-sdk/src/client"; +import { AsyncStoreWithClient } from "../../src/stores/AsyncStoreWithClient"; + +// These methods make some use of some private methods on the AsyncStoreWithClient to simplify getting into a consistent +// ready state without needing to wire up a dispatcher and pretend to be a js-sdk client. + +export const setupAsyncStoreWithClient = async (store: AsyncStoreWithClient, client: MatrixClient) => { + // @ts-ignore + store.readyStore.useUnitTestClient(client); + // @ts-ignore + await store.onReady(); +}; + +export const resetAsyncStoreWithClient = async (store: AsyncStoreWithClient) => { + // @ts-ignore + await store.onNotReady(); +}; diff --git a/yarn.lock b/yarn.lock index 66329cfa89..acdca26e55 100644 --- a/yarn.lock +++ b/yarn.lock @@ -26,6 +26,13 @@ dependencies: "@babel/highlight" "^7.10.4" +"@babel/code-frame@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.12.13.tgz#dcfc826beef65e75c50e21d3837d7d95798dd658" + integrity sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g== + dependencies: + "@babel/highlight" "^7.12.13" + "@babel/compat-data@^7.12.5", "@babel/compat-data@^7.12.7": version "7.12.7" resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.12.7.tgz#9329b4782a7d6bbd7eef57e11addf91ee3ef1e41" @@ -61,6 +68,15 @@ jsesc "^2.5.1" source-map "^0.5.0" +"@babel/generator@^7.13.16": + version "7.13.16" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.13.16.tgz#0befc287031a201d84cdfc173b46b320ae472d14" + integrity sha512-grBBR75UnKOcUWMp8WoDxNsWCFl//XCK6HWTrBQKTr5SV9f5g0pNOjdyzi/DTBv12S9GnYPInIXQBTky7OXEMg== + dependencies: + "@babel/types" "^7.13.16" + jsesc "^2.5.1" + source-map "^0.5.0" + "@babel/helper-annotate-as-pure@^7.10.4", "@babel/helper-annotate-as-pure@^7.12.10": version "7.12.10" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.12.10.tgz#54ab9b000e60a93644ce17b3f37d313aaf1d115d" @@ -130,6 +146,15 @@ "@babel/template" "^7.12.7" "@babel/types" "^7.12.11" +"@babel/helper-function-name@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.12.13.tgz#93ad656db3c3c2232559fd7b2c3dbdcbe0eb377a" + integrity sha512-TZvmPn0UOqmvi5G4vvw0qZTpVptGkB1GL61R6lKvrSdIxGm5Pky7Q3fpKiIkQCAtRCBUwB0PaThlx9vebCDSwA== + dependencies: + "@babel/helper-get-function-arity" "^7.12.13" + "@babel/template" "^7.12.13" + "@babel/types" "^7.12.13" + "@babel/helper-get-function-arity@^7.12.10": version "7.12.10" resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.10.tgz#b158817a3165b5faa2047825dfa61970ddcc16cf" @@ -137,6 +162,13 @@ dependencies: "@babel/types" "^7.12.10" +"@babel/helper-get-function-arity@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz#bc63451d403a3b3082b97e1d8b3fe5bd4091e583" + integrity sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg== + dependencies: + "@babel/types" "^7.12.13" + "@babel/helper-hoist-variables@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.10.4.tgz#d49b001d1d5a68ca5e6604dda01a6297f7c9381e" @@ -225,6 +257,13 @@ dependencies: "@babel/types" "^7.12.11" +"@babel/helper-split-export-declaration@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz#e9430be00baf3e88b0e13e6f9d4eaf2136372b05" + integrity sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg== + dependencies: + "@babel/types" "^7.12.13" + "@babel/helper-validator-identifier@^7.10.4", "@babel/helper-validator-identifier@^7.12.11": version "7.12.11" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz#c9a1f021917dcb5ccf0d4e453e399022981fc9ed" @@ -263,11 +302,25 @@ chalk "^2.0.0" js-tokens "^4.0.0" +"@babel/highlight@^7.12.13": + version "7.13.10" + resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.13.10.tgz#a8b2a66148f5b27d666b15d81774347a731d52d1" + integrity sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg== + dependencies: + "@babel/helper-validator-identifier" "^7.12.11" + chalk "^2.0.0" + js-tokens "^4.0.0" + "@babel/parser@^7.1.0", "@babel/parser@^7.12.10", "@babel/parser@^7.12.11", "@babel/parser@^7.12.7", "@babel/parser@^7.7.0": version "7.12.11" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.12.11.tgz#9ce3595bcd74bc5c466905e86c535b8b25011e79" integrity sha512-N3UxG+uuF4CMYoNj8AhnbAcJF0PiuJ9KHuy1lQmkYsxTer/MAH9UBNHsBoAX/4s6NvlDD047No8mYVGGzLL4hg== +"@babel/parser@^7.12.13", "@babel/parser@^7.13.16": + version "7.13.16" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.13.16.tgz#0f18179b0448e6939b1f3f5c4c355a3a9bcdfd37" + integrity sha512-6bAg36mCwuqLO0hbR+z7PHuqWiCeP7Dzg73OpQwsAB1Eb8HnGEz5xYBzCfbu+YjoaJsJs+qheDxVAuqbt3ILEw== + "@babel/plugin-proposal-async-generator-functions@^7.12.1": version "7.12.12" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.12.12.tgz#04b8f24fd4532008ab4e79f788468fd5a8476566" @@ -980,6 +1033,15 @@ "@babel/parser" "^7.12.7" "@babel/types" "^7.12.7" +"@babel/template@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.12.13.tgz#530265be8a2589dbb37523844c5bcb55947fb327" + integrity sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA== + dependencies: + "@babel/code-frame" "^7.12.13" + "@babel/parser" "^7.12.13" + "@babel/types" "^7.12.13" + "@babel/traverse@^7.1.0", "@babel/traverse@^7.10.4", "@babel/traverse@^7.12.1", "@babel/traverse@^7.12.10", "@babel/traverse@^7.12.12", "@babel/traverse@^7.12.5", "@babel/traverse@^7.7.0", "@babel/traverse@^7.7.4": version "7.12.12" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.12.12.tgz#d0cd87892704edd8da002d674bc811ce64743376" @@ -995,6 +1057,20 @@ globals "^11.1.0" lodash "^4.17.19" +"@babel/traverse@^7.13.17": + version "7.13.17" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.13.17.tgz#c85415e0c7d50ac053d758baec98b28b2ecfeea3" + integrity sha512-BMnZn0R+X6ayqm3C3To7o1j7Q020gWdqdyP50KEoVqaCO2c/Im7sYZSmVgvefp8TTMQ+9CtwuBp0Z1CZ8V3Pvg== + dependencies: + "@babel/code-frame" "^7.12.13" + "@babel/generator" "^7.13.16" + "@babel/helper-function-name" "^7.12.13" + "@babel/helper-split-export-declaration" "^7.12.13" + "@babel/parser" "^7.13.16" + "@babel/types" "^7.13.17" + debug "^4.1.0" + globals "^11.1.0" + "@babel/types@^7.0.0", "@babel/types@^7.10.4", "@babel/types@^7.10.5", "@babel/types@^7.12.1", "@babel/types@^7.12.10", "@babel/types@^7.12.11", "@babel/types@^7.12.12", "@babel/types@^7.12.5", "@babel/types@^7.12.7", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.4", "@babel/types@^7.7.0": version "7.12.12" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.12.12.tgz#4608a6ec313abbd87afa55004d373ad04a96c299" @@ -1004,6 +1080,14 @@ lodash "^4.17.19" to-fast-properties "^2.0.0" +"@babel/types@^7.12.13", "@babel/types@^7.13.16", "@babel/types@^7.13.17": + version "7.13.17" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.13.17.tgz#48010a115c9fba7588b4437dd68c9469012b38b4" + integrity sha512-RawydLgxbOPDlTLJNtoIypwdmAy//uQIzlKt2+iBiJaRlVuI6QLUxVAyWGNfOzp8Yu4L4lLIacoCyTNtpb4wiA== + dependencies: + "@babel/helper-validator-identifier" "^7.12.11" + to-fast-properties "^2.0.0" + "@bcoe/v8-coverage@^0.2.3": version "0.2.3" resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" @@ -5588,8 +5672,8 @@ mathml-tag-names@^2.1.3: integrity sha512-APMBEanjybaPzUrfqU0IMU5I0AswKMH7k8OTLs0vvV4KZpExkTkY87nR/zpbuTPj+gARop7aGUbl11pnDfW6xg== "matrix-js-sdk@github:matrix-org/matrix-js-sdk#develop": - version "9.11.0" - resolved "https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/e277de6e3d9bbb98fbfbbedd47d86ee85f6f47e5" + version "10.0.0" + resolved "https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/c8f69c0b7937b9064938c134d708c4d064b71315" dependencies: "@babel/runtime" "^7.12.5" another-json "^0.2.0" @@ -5614,6 +5698,14 @@ matrix-react-test-utils@^0.2.2: resolved "https://registry.yarnpkg.com/matrix-react-test-utils/-/matrix-react-test-utils-0.2.2.tgz#c87144d3b910c7edc544a6699d13c7c2bf02f853" integrity sha512-49+7gfV6smvBIVbeloql+37IeWMTD+fiywalwCqk8Dnz53zAFjKSltB3rmWHso1uecLtQEcPtCijfhzcLXAxTQ== +"matrix-web-i18n@github:matrix-org/matrix-web-i18n": + version "1.1.2" + resolved "https://codeload.github.com/matrix-org/matrix-web-i18n/tar.gz/63f9119bc0bc304e83d4e8e22364caa7850e7671" + dependencies: + "@babel/parser" "^7.13.16" + "@babel/traverse" "^7.13.17" + walk "^2.3.14" + matrix-widget-api@^0.1.0-beta.13: version "0.1.0-beta.13" resolved "https://registry.yarnpkg.com/matrix-widget-api/-/matrix-widget-api-0.1.0-beta.13.tgz#ebddc83eaef39bbb87b621a02a35902e1a29b9ef"