From 1f64835fabe9f3471c368da5169d2805a800cde8 Mon Sep 17 00:00:00 2001 From: Robin Date: Fri, 1 Apr 2022 10:36:10 -0400 Subject: [PATCH] Update video rooms to new design specs (#8207) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Remove radio component * "Voice room" → "video room" * Remove interactivity from video room tiles * Update connection state when joining via widget * Simplify room header buttons for video rooms * Split out video room creation into a separate menu option * Simplify room options for video rooms * Update video room tile layout * Tell the Jitsi widget whether it's a video channel * Update tests * "Voice" → "video" in more places * Fix tests * Re-add frame to immersive Jitsi widgets * Comment ack * Make updateDevices more readable * Type FacePile --- res/css/_components.scss | 1 - res/css/structures/_RoomView.scss | 4 +- res/css/views/elements/_FacePile.scss | 2 +- res/css/views/rooms/_RoomList.scss | 5 +- res/css/views/rooms/_RoomListHeader.scss | 5 +- res/css/views/rooms/_RoomTile.scss | 256 ++++++++--------- res/css/views/voip/_VoiceChannelRadio.scss | 121 -------- res/img/voip/voice-room.svg | 3 - src/Lifecycle.ts | 3 + src/components/structures/LeftPanel.tsx | 2 - src/components/structures/MatrixChat.tsx | 6 +- src/components/structures/RoomView.tsx | 41 ++- src/components/structures/SpaceRoomView.tsx | 51 ++-- .../views/context_menus/RoomContextMenu.tsx | 96 ++++--- .../views/dialogs/CreateRoomDialog.tsx | 38 +-- src/components/views/elements/FacePile.tsx | 54 +--- .../views/right_panel/RoomSummaryCard.tsx | 25 +- src/components/views/rooms/RoomHeader.tsx | 1 + src/components/views/rooms/RoomList.tsx | 55 +++- src/components/views/rooms/RoomListHeader.tsx | 71 +++-- src/components/views/rooms/RoomTile.tsx | 217 ++++++-------- .../views/voip/VoiceChannelRadio.tsx | 91 ------ src/createRoom.ts | 10 +- src/i18n/strings/en_EN.json | 29 +- src/settings/Settings.tsx | 4 +- src/stores/VideoChannelStore.ts | 164 +++++++++++ src/stores/VoiceChannelStore.ts | 267 ------------------ ...ceChannelUtils.ts => VideoChannelUtils.ts} | 18 +- src/utils/WidgetUtils.ts | 3 + src/utils/space.tsx | 4 +- test/components/views/rooms/RoomTile-test.tsx | 68 ++--- .../views/voip/VoiceChannelRadio-test.tsx | 107 ------- .../src/usecases/create-room.ts | 2 +- test/stores/VideoChannelStore-test.ts | 83 ++++++ test/stores/VoiceChannelStore-test.ts | 95 ------- test/test-utils/index.ts | 2 +- test/test-utils/video.ts | 39 +++ test/test-utils/voice.ts | 60 ---- 38 files changed, 798 insertions(+), 1305 deletions(-) delete mode 100644 res/css/views/voip/_VoiceChannelRadio.scss delete mode 100644 res/img/voip/voice-room.svg delete mode 100644 src/components/views/voip/VoiceChannelRadio.tsx create mode 100644 src/stores/VideoChannelStore.ts delete mode 100644 src/stores/VoiceChannelStore.ts rename src/utils/{VoiceChannelUtils.ts => VideoChannelUtils.ts} (72%) delete mode 100644 test/components/views/voip/VoiceChannelRadio-test.tsx create mode 100644 test/stores/VideoChannelStore-test.ts delete mode 100644 test/stores/VoiceChannelStore-test.ts create mode 100644 test/test-utils/video.ts delete mode 100644 test/test-utils/voice.ts diff --git a/res/css/_components.scss b/res/css/_components.scss index 4c72550c15..3f3038ccfd 100644 --- a/res/css/_components.scss +++ b/res/css/_components.scss @@ -314,4 +314,3 @@ @import "./views/voip/_DialPadModal.scss"; @import "./views/voip/_PiPContainer.scss"; @import "./views/voip/_VideoFeed.scss"; -@import "./views/voip/_VoiceChannelRadio.scss"; diff --git a/res/css/structures/_RoomView.scss b/res/css/structures/_RoomView.scss index 10dbfae0ce..3547225ce7 100644 --- a/res/css/structures/_RoomView.scss +++ b/res/css/structures/_RoomView.scss @@ -218,9 +218,9 @@ hr.mx_RoomView_myReadMarker { margin-right: calc($container-gap-width / 2); width: auto; height: 100%; + padding-top: 33px; // to match the right panel chat heading - background: none; - border: none; + border-radius: 8px; } .mx_RoomView_callStatusBar .mx_UploadBar_uploadProgressInner { diff --git a/res/css/views/elements/_FacePile.scss b/res/css/views/elements/_FacePile.scss index fcde5eab83..3e83446b0e 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; - > * + * { + > .mx_FacePile_face + .mx_FacePile_face { margin-right: -8px; } diff --git a/res/css/views/rooms/_RoomList.scss b/res/css/views/rooms/_RoomList.scss index 029c5b6cdb..2763ad653f 100644 --- a/res/css/views/rooms/_RoomList.scss +++ b/res/css/views/rooms/_RoomList.scss @@ -21,9 +21,12 @@ limitations under the License. .mx_RoomList_iconPlus::before { mask-image: url('$(res)/img/element-icons/roomlist/plus-circle.svg'); } -.mx_RoomList_iconCreateNewRoom::before { +.mx_RoomList_iconNewRoom::before { mask-image: url('$(res)/img/element-icons/roomlist/hash-plus.svg'); } +.mx_RoomList_iconNewVideoRoom::before { + mask-image: url('$(res)/img/element-icons/call/video-call.svg'); +} .mx_RoomList_iconAddExistingRoom::before { mask-image: url('$(res)/img/element-icons/roomlist/hash.svg'); } diff --git a/res/css/views/rooms/_RoomListHeader.scss b/res/css/views/rooms/_RoomListHeader.scss index 442456ff0e..c4bc8c151f 100644 --- a/res/css/views/rooms/_RoomListHeader.scss +++ b/res/css/views/rooms/_RoomListHeader.scss @@ -103,9 +103,12 @@ limitations under the License. .mx_RoomListHeader_iconStartChat::before { mask-image: url('$(res)/img/element-icons/roomlist/member-plus.svg'); } -.mx_RoomListHeader_iconCreateRoom::before { +.mx_RoomListHeader_iconNewRoom::before { mask-image: url('$(res)/img/element-icons/roomlist/hash-plus.svg'); } +.mx_RoomListHeader_iconNewVideoRoom::before { + mask-image: url('$(res)/img/element-icons/call/video-call.svg'); +} .mx_RoomListHeader_iconExplore::before { mask-image: url('$(res)/img/element-icons/roomlist/hash-search.svg'); } diff --git a/res/css/views/rooms/_RoomTile.scss b/res/css/views/rooms/_RoomTile.scss index bf19e0632f..23fb4f1e9a 100644 --- a/res/css/views/rooms/_RoomTile.scss +++ b/res/css/views/rooms/_RoomTile.scss @@ -19,11 +19,12 @@ limitations under the License. margin-bottom: 4px; padding: 4px; + // The tile is also a flexbox row itself + display: flex; contain: content; // Not strict as it will break when resizing a sublist vertically box-sizing: border-box; - // The tile is also a flexbox row itself - display: flex; + font-size: $font-13px; &.mx_RoomTile_selected, &:hover, @@ -37,163 +38,136 @@ limitations under the License. margin-right: 10px; } - .mx_RoomTile_details { + .mx_RoomTile_titleContainer { + height: 32px; + min-width: 0; + flex-basis: 0; flex-grow: 1; - min-width: 0; // allow flex to shrink it + margin-right: 8px; // spacing to buttons/badges + + // Create a new column layout flexbox for the title parts display: flex; flex-direction: column; + justify-content: center; - .mx_RoomTile_primaryDetails { - height: 32px; - display: flex; - flex-wrap: wrap; + .mx_RoomTile_title, .mx_RoomTile_subtitle { + width: 100%; - .mx_RoomTile_titleContainer { - min-width: 0; - flex-basis: 0; - flex-grow: 1; - margin-right: 8px; // spacing to buttons/badges + // Ellipsize any text overflow + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + } - // Create a new column layout flexbox for the title parts - display: flex; - flex-direction: column; - justify-content: center; + .mx_RoomTile_title { + font-size: $font-14px; + line-height: $font-18px; - .mx_RoomTile_title, .mx_RoomTile_subtitle { - width: 100%; - - // Ellipsize any text overflow - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - } - - .mx_RoomTile_title { - font-size: $font-14px; - line-height: $font-18px; - } - - .mx_RoomTile_title.mx_RoomTile_titleHasUnreadEvents { - font-weight: 600; - } - - .mx_RoomTile_subtitle { - font-size: $font-13px; - line-height: $font-18px; - color: $secondary-content; - } - - .mx_RoomTile_subtitle.mx_RoomTile_voiceIndicator { - &::before { - display: inline-block; - vertical-align: text-bottom; - content: ''; - background-color: $secondary-content; - mask-image: url('$(res)/img/voip/voice-room.svg'); - mask-size: 16px; - width: 16px; - height: 16px; - margin-right: 4px; - } - - &.mx_RoomTile_voiceIndicator_active { - color: $accent; - - &::before { - background-color: $accent; - } - } - } - - .mx_RoomTile_titleWithSubtitle { - margin-top: -3px; // shift the title up a bit more - } - } - - .mx_RoomTile_notificationsButton { - margin-left: 4px; // spacing between buttons - } - - .mx_RoomTile_badgeContainer { - height: 16px; - // don't set width so that it takes no space when there is no badge to show - margin: auto 0; // vertically align - - // Create a flexbox to make aligning dot badges easier - display: flex; - align-items: center; - - .mx_NotificationBadge { - margin-right: 2px; // centering - } - - .mx_NotificationBadge_dot { - // make the smaller dot occupy the same width for centering - margin-left: 5px; - margin-right: 7px; - } - } - - // The context menu buttons are hidden by default - .mx_RoomTile_menuButton, - .mx_RoomTile_notificationsButton { - width: 20px; - min-width: 20px; // yay flex - height: 20px; - margin-top: auto; - margin-bottom: auto; - position: relative; - display: none; - - &::before { - top: 2px; - left: 2px; - content: ''; - width: 16px; - height: 16px; - position: absolute; - mask-position: center; - mask-size: contain; - mask-repeat: no-repeat; - background: $primary-content; - } - } - - // If the room has an overriden notification setting then we always show the notifications menu button - .mx_RoomTile_notificationsButton.mx_RoomTile_notificationsButton_show { - display: block; - } - - .mx_RoomTile_menuButton::before { - mask-image: url('$(res)/img/element-icons/context-menu.svg'); + &.mx_RoomTile_titleHasUnreadEvents { + font-weight: 600; } } - .mx_RoomTile_voiceChannel { - width: 100%; - display: flex; - align-items: center; - - .mx_FacePile { - margin: 6px 0 4px; - } - - .mx_RoomTile_connectVoiceButton { - font-weight: 600; - padding-left: 10px; - padding-right: 10px; + .mx_RoomTile_subtitle { + line-height: $font-18px; + color: $secondary-content; + .mx_RoomTile_videoIndicator { &::before { + display: inline-block; + vertical-align: text-bottom; content: ''; - background-color: $accent; - mask-image: url('$(res)/img/voip/voice-room.svg'); + background-color: $secondary-content; + mask-image: url('$(res)/img/element-icons/call/video-call.svg'); mask-size: 16px; width: 16px; height: 16px; margin-right: 4px; } + + &.mx_RoomTile_videoIndicator_active { + color: $accent; + + &::before { + background-color: $accent; + } + } + } + + .mx_RoomTile_videoParticipants::before { + display: inline-block; + vertical-align: text-bottom; + content: ''; + background-color: $secondary-content; + mask-image: url('$(res)/img/element-icons/group-members.svg'); + mask-size: 16px; + width: 16px; + height: 16px; + margin-right: 2px; } } + + .mx_RoomTile_titleWithSubtitle { + margin-top: -3px; // shift the title up a bit more + } + } + + .mx_RoomTile_notificationsButton { + margin-left: 4px; // spacing between buttons + } + + .mx_RoomTile_badgeContainer { + height: 16px; + // don't set width so that it takes no space when there is no badge to show + margin: auto 0; // vertically align + + // Create a flexbox to make aligning dot badges easier + display: flex; + align-items: center; + + .mx_NotificationBadge { + margin-right: 2px; // centering + } + + .mx_NotificationBadge_dot { + // make the smaller dot occupy the same width for centering + margin-left: 5px; + margin-right: 7px; + } + } + + // The context menu buttons are hidden by default + .mx_RoomTile_menuButton, + .mx_RoomTile_notificationsButton { + width: 20px; + min-width: 20px; // yay flex + height: 20px; + margin-top: auto; + margin-bottom: auto; + position: relative; + display: none; + + &::before { + top: 2px; + left: 2px; + content: ''; + width: 16px; + height: 16px; + position: absolute; + mask-position: center; + mask-size: contain; + mask-repeat: no-repeat; + background: $primary-content; + } + } + + // If the room has an overriden notification setting then we always show the notifications menu button + .mx_RoomTile_notificationsButton.mx_RoomTile_notificationsButton_show { + display: block; + } + + .mx_RoomTile_menuButton::before { + mask-image: url('$(res)/img/element-icons/context-menu.svg'); } &:not(.mx_RoomTile_minimized) { @@ -222,10 +196,6 @@ limitations under the License. .mx_DecoratedRoomAvatar, .mx_RoomTile_avatarContainer { margin-right: 0; } - - .mx_RoomTile_details { - display: none; - } } } diff --git a/res/css/views/voip/_VoiceChannelRadio.scss b/res/css/views/voip/_VoiceChannelRadio.scss deleted file mode 100644 index d67a5b312f..0000000000 --- a/res/css/views/voip/_VoiceChannelRadio.scss +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2022 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_VoiceChannelRadio { - background-color: $system; - - > .mx_VoiceChannelRadio_statusBar { - display: flex; - padding: 12px 16px; - align-items: center; - gap: 12px; - - > .mx_VoiceChannelRadio_titleContainer { - flex-grow: 1; - - > .mx_VoiceChannelRadio_status { - font-size: $font-15px; - color: $accent; - - &::before { - content: ''; - display: inline-block; - margin-right: 4px; - width: 11px; - height: 11px; - background-color: $accent; - mask-image: url('$(res)/img/voip/signal-bars.svg'); - mask-position: center; - mask-size: contain; - mask-repeat: no-repeat; - } - } - - > .mx_VoiceChannelRadio_name { - font-size: $font-13px; - color: $secondary-content; - } - } - - > .mx_VoiceChannelRadio_disconnectButton::before { - content: ''; - display: block; - width: 36px; - height: 36px; - background-color: $tertiary-content; - mask-image: url('$(res)/img/element-icons/call/hangup.svg'); - mask-position: center; - mask-size: 24px; - mask-repeat: no-repeat; - } - } - - > .mx_VoiceChannelRadio_controlBar { - display: flex; - border-top: 1px solid $quinary-content; - padding: 12px 16px; - align-items: center; - justify-content: space-between; - - > .mx_AccessibleButton { - font-size: $font-15px; - padding: 6px 0; - - &.mx_VoiceChannelRadio_button_active { - padding: 6px 12px; - background-color: $quinary-content; - border-radius: 8px; - font-weight: 600; - } - } - - > .mx_VoiceChannelRadio_videoButton::before { - content: ''; - display: inline-block; - margin-right: 8px; - width: 16px; - height: 16px; - background-color: $primary-content; - vertical-align: sub; - mask-image: url('$(res)/img/voip/call-view/cam-off.svg'); - mask-position: center; - mask-size: contain; - mask-repeat: no-repeat; - } - - > .mx_VoiceChannelRadio_videoButton.mx_VoiceChannelRadio_button_active::before { - mask-image: url('$(res)/img/voip/call-view/cam-on.svg'); - } - - > .mx_VoiceChannelRadio_audioButton::before { - content: ''; - display: inline-block; - margin-right: 4px; - width: 16px; - height: 16px; - background-color: $primary-content; - vertical-align: sub; - mask-image: url('$(res)/img/voip/call-view/mic-off.svg'); - mask-position: center; - mask-size: contain; - mask-repeat: no-repeat; - } - - > .mx_VoiceChannelRadio_audioButton.mx_VoiceChannelRadio_button_active::before { - mask-image: url('$(res)/img/voip/call-view/mic-on.svg'); - } - } -} diff --git a/res/img/voip/voice-room.svg b/res/img/voip/voice-room.svg deleted file mode 100644 index db62957ee3..0000000000 --- a/res/img/voip/voice-room.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/Lifecycle.ts b/src/Lifecycle.ts index 85f0535851..a919a9c287 100644 --- a/src/Lifecycle.ts +++ b/src/Lifecycle.ts @@ -36,6 +36,7 @@ import dis from './dispatcher/dispatcher'; import DMRoomMap from './utils/DMRoomMap'; import Modal from './Modal'; import ActiveWidgetStore from './stores/ActiveWidgetStore'; +import VideoChannelStore from "./stores/VideoChannelStore"; import PlatformPeg from "./PlatformPeg"; import { sendLoginRequest } from "./Login"; import * as StorageManager from './utils/StorageManager'; @@ -796,6 +797,7 @@ async function startMatrixClient(startSyncing = true): Promise { IntegrationManagers.sharedInstance().startWatching(); ActiveWidgetStore.instance.start(); CallHandler.instance.start(); + if (SettingsStore.getValue("feature_video_rooms")) VideoChannelStore.instance.start(); // Start Mjolnir even though we haven't checked the feature flag yet. Starting // the thing just wastes CPU cycles, but should result in no actual functionality @@ -909,6 +911,7 @@ export function stopMatrixClient(unsetClient = true): void { UserActivity.sharedInstance().stop(); TypingStore.sharedInstance().reset(); Presence.stop(); + if (SettingsStore.getValue("feature_video_rooms")) VideoChannelStore.instance.stop(); ActiveWidgetStore.instance.stop(); IntegrationManagers.sharedInstance().stopWatching(); Mjolnir.sharedInstance().stop(); diff --git a/src/components/structures/LeftPanel.tsx b/src/components/structures/LeftPanel.tsx index 987e8c2966..db6d4be1d8 100644 --- a/src/components/structures/LeftPanel.tsx +++ b/src/components/structures/LeftPanel.tsx @@ -41,7 +41,6 @@ import { UPDATE_EVENT } from "../../stores/AsyncStore"; import IndicatorScrollbar from "./IndicatorScrollbar"; import RoomBreadcrumbs from "../views/rooms/RoomBreadcrumbs"; import SettingsStore from "../../settings/SettingsStore"; -import VoiceChannelRadio from "../views/voip/VoiceChannelRadio"; import { KeyBindingAction } from "../../accessibility/KeyboardShortcuts"; import { shouldShowComponent } from "../../customisations/helpers/UIComponents"; import { UIComponent } from "../../settings/UIFeature"; @@ -441,7 +440,6 @@ export default class LeftPanel extends React.Component { { roomList } - { SettingsStore.getValue("feature_voice_rooms") && } ); diff --git a/src/components/structures/MatrixChat.tsx b/src/components/structures/MatrixChat.tsx index 302989ed5f..969486c536 100644 --- a/src/components/structures/MatrixChat.tsx +++ b/src/components/structures/MatrixChat.tsx @@ -31,6 +31,7 @@ import { defer, IDeferred, QueryDict } from "matrix-js-sdk/src/utils"; import { logger } from "matrix-js-sdk/src/logger"; import { throttle } from "lodash"; import { CryptoEvent } from "matrix-js-sdk/src/crypto"; +import { RoomType } from "matrix-js-sdk/src/@types/event"; // focus-visible is a Polyfill for the :focus-visible CSS pseudo-attribute used by _AccessibleButton.scss import 'focus-visible'; @@ -677,7 +678,7 @@ export default class MatrixChat extends React.PureComponent { break; } case 'view_create_room': - this.createRoom(payload.public, payload.defaultName); + this.createRoom(payload.public, payload.defaultName, payload.type); // View the welcome or home page if we need something to look at this.viewSomethingBehindModal(); @@ -994,8 +995,9 @@ export default class MatrixChat extends React.PureComponent { this.setPage(PageType.LegacyGroupView); } - private async createRoom(defaultPublic = false, defaultName?: string) { + private async createRoom(defaultPublic = false, defaultName?: string, type?: RoomType) { const modal = Modal.createTrackedDialog('Create Room', '', CreateRoomDialog, { + type, defaultPublic, defaultName, }); diff --git a/src/components/structures/RoomView.tsx b/src/components/structures/RoomView.tsx index fe9f85c900..ab06369406 100644 --- a/src/components/structures/RoomView.tsx +++ b/src/components/structures/RoomView.tsx @@ -75,7 +75,7 @@ import EffectsOverlay from "../views/elements/EffectsOverlay"; import { containsEmoji } from '../../effects/utils'; import { CHAT_EFFECTS } from '../../effects'; import WidgetStore from "../../stores/WidgetStore"; -import { getVoiceChannel } from "../../utils/VoiceChannelUtils"; +import { getVideoChannel } from "../../utils/VideoChannelUtils"; import AppTile from "../views/elements/AppTile"; import { UPDATE_EVENT } from "../../stores/AsyncStore"; import Notifier from "../../Notifier"; @@ -375,7 +375,7 @@ export class RoomView extends React.Component { }; private getMainSplitContentType = (room: Room) => { - if (SettingsStore.getValue("feature_voice_rooms") && room.isCallRoom()) { + if (SettingsStore.getValue("feature_video_rooms") && room.isCallRoom()) { return MainSplitContentType.Video; } if (WidgetLayoutStore.instance.hasMaximisedWidget(room)) { @@ -2140,7 +2140,7 @@ export class RoomView extends React.Component { ; break; case MainSplitContentType.Video: { - const app = getVoiceChannel(this.state.room.roomId); + const app = getVideoChannel(this.state.room.roomId); if (!app) break; mainSplitContentClassName = "mx_MainSplit_video"; mainSplitBody = { const mainSplitContentClasses = classNames("mx_RoomView_body", mainSplitContentClassName); let excludedRightPanelPhaseButtons = [RightPanelPhases.Timeline]; + let onCallPlaced = this.onCallPlaced; let onAppsClick = this.onAppsClick; let onForgetClick = this.onForgetClick; let onSearchClick = this.onSearchClick; - if (this.state.mainSplitContentType !== MainSplitContentType.Timeline) { - // Disable phase buttons and action button to have a simplified header - // and enable (not disable) the RightPanelPhases.Timeline button - excludedRightPanelPhaseButtons = [ - RightPanelPhases.ThreadPanel, - RightPanelPhases.PinnedMessages, - ]; - onAppsClick = null; - onForgetClick = null; - onSearchClick = null; + + // Simplify the header for other main split types + switch (this.state.mainSplitContentType) { + case MainSplitContentType.MaximisedWidget: + excludedRightPanelPhaseButtons = [ + RightPanelPhases.ThreadPanel, + RightPanelPhases.PinnedMessages, + ]; + onAppsClick = null; + onForgetClick = null; + onSearchClick = null; + break; + case MainSplitContentType.Video: + excludedRightPanelPhaseButtons = [ + RightPanelPhases.ThreadPanel, + RightPanelPhases.PinnedMessages, + RightPanelPhases.NotificationPanel, + ]; + onCallPlaced = null; + onAppsClick = null; + onForgetClick = null; + onSearchClick = null; } return ( @@ -2189,7 +2202,7 @@ export class RoomView extends React.Component { e2eStatus={this.state.e2eStatus} onAppsClick={this.state.hasPinnedWidgets ? onAppsClick : null} appsShown={this.state.showApps} - onCallPlaced={this.onCallPlaced} + onCallPlaced={onCallPlaced} excludedRightPanelPhaseButtons={excludedRightPanelPhaseButtons} /> diff --git a/src/components/structures/SpaceRoomView.tsx b/src/components/structures/SpaceRoomView.tsx index ba46cdc921..f6f8ae3f47 100644 --- a/src/components/structures/SpaceRoomView.tsx +++ b/src/components/structures/SpaceRoomView.tsx @@ -15,7 +15,7 @@ limitations under the License. */ import React, { RefObject, useContext, useRef, useState } from "react"; -import { EventType } from "matrix-js-sdk/src/@types/event"; +import { EventType, RoomType } from "matrix-js-sdk/src/@types/event"; import { JoinRule, Preset } from "matrix-js-sdk/src/@types/partials"; import { Room, RoomEvent } from "matrix-js-sdk/src/models/room"; import { logger } from "matrix-js-sdk/src/logger"; @@ -29,6 +29,7 @@ import RoomTopic from "../views/elements/RoomTopic"; import InlineSpinner from "../views/elements/InlineSpinner"; import { inviteMultipleToRoom, showRoomInviteDialog } from "../../RoomInvite"; import { useRoomMembers } from "../../hooks/useRoomMembers"; +import { useFeatureEnabled } from "../../hooks/useSettings"; import createRoom, { IOpts } from "../../createRoom"; import Field from "../views/elements/Field"; import { useTypedEventEmitter } from "../../hooks/useEventEmitter"; @@ -57,7 +58,7 @@ import { } from "../../utils/space"; import SpaceHierarchy, { showRoom } from "./SpaceHierarchy"; import MemberAvatar from "../views/avatars/MemberAvatar"; -import { RoomFacePile } from "../views/elements/FacePile"; +import FacePile from "../views/elements/FacePile"; import { AddExistingToSpace, defaultDmsRenderer, @@ -297,7 +298,7 @@ const SpacePreview = ({ space, onJoinButtonClicked, onRejectButtonClicked }: ISp } - { space.getJoinRule() === "public" && } + { space.getJoinRule() === "public" && }
{ joinButtons }
@@ -309,6 +310,7 @@ const SpaceLandingAddButton = ({ space }) => { const [menuDisplayed, handle, openMenu, closeMenu] = useContextMenu(); const canCreateRoom = shouldShowComponent(UIComponent.CreateRooms); const canCreateSpace = shouldShowComponent(UIComponent.CreateSpaces); + const videoRoomsEnabled = useFeatureEnabled("feature_video_rooms"); let contextMenu; if (menuDisplayed) { @@ -322,20 +324,35 @@ const SpaceLandingAddButton = ({ space }) => { compact > - { canCreateRoom && { - e.preventDefault(); - e.stopPropagation(); - closeMenu(); + { canCreateRoom && <> + { + e.preventDefault(); + e.stopPropagation(); + closeMenu(); - PosthogTrackers.trackInteraction("WebSpaceHomeCreateRoomButton", e); - if (await showCreateNewRoom(space)) { - defaultDispatcher.fire(Action.UpdateSpaceHierarchy); - } - }} - /> } + PosthogTrackers.trackInteraction("WebSpaceHomeCreateRoomButton", e); + if (await showCreateNewRoom(space)) { + defaultDispatcher.fire(Action.UpdateSpaceHierarchy); + } + }} + /> + { videoRoomsEnabled && { + e.preventDefault(); + e.stopPropagation(); + closeMenu(); + + if (await showCreateNewRoom(space, RoomType.UnstableCall)) { + defaultDispatcher.fire(Action.UpdateSpaceHierarchy); + } + }} + /> } + } {
- + { inviteButton } { settingsButton }
diff --git a/src/components/views/context_menus/RoomContextMenu.tsx b/src/components/views/context_menus/RoomContextMenu.tsx index 1d2ca8f171..35ecf97a9c 100644 --- a/src/components/views/context_menus/RoomContextMenu.tsx +++ b/src/components/views/context_menus/RoomContextMenu.tsx @@ -35,7 +35,7 @@ import { EchoChamber } from "../../../stores/local-echo/EchoChamber"; import { RoomNotifState } from "../../../RoomNotifs"; import Modal from "../../../Modal"; import ExportDialog from "../dialogs/ExportDialog"; -import { useSettingValue } from "../../../hooks/useSettings"; +import { useFeatureEnabled } from "../../../hooks/useSettings"; import { usePinnedEvents } from "../right_panel/PinnedMessagesCard"; import RoomViewStore from "../../../stores/RoomViewStore"; import { RightPanelPhases } from '../../../stores/right-panel/RightPanelStorePhases'; @@ -105,6 +105,7 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => { } const isDm = DMRoomMap.shared().getUserIdForRoomId(room.roomId); + const isVideoRoom = useFeatureEnabled("feature_video_rooms") && room.isCallRoom(); let inviteOption: JSX.Element; if (room.canInvite(cli.getUserId()) && !isDm) { @@ -233,11 +234,27 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => { />; } - const pinningEnabled = useSettingValue("feature_pinning"); + let filesOption: JSX.Element; + if (!isVideoRoom) { + filesOption = { + ev.preventDefault(); + ev.stopPropagation(); + + ensureViewingRoom(ev); + RightPanelStore.instance.pushCard({ phase: RightPanelPhases.FilePanel }, false); + onFinished(); + }} + label={_t("Files")} + iconClassName="mx_RoomTile_iconFiles" + />; + } + + const pinningEnabled = useFeatureEnabled("feature_pinning"); const pinCount = usePinnedEvents(pinningEnabled && room)?.length; let pinsOption: JSX.Element; - if (pinningEnabled) { + if (pinningEnabled && !isVideoRoom) { pinsOption = { ev.preventDefault(); @@ -256,6 +273,37 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => { ; } + let widgetsOption: JSX.Element; + if (!isVideoRoom) { + widgetsOption = { + ev.preventDefault(); + ev.stopPropagation(); + + ensureViewingRoom(ev); + RightPanelStore.instance.setCard({ phase: RightPanelPhases.RoomSummary }, false); + onFinished(); + }} + label={_t("Widgets")} + iconClassName="mx_RoomTile_iconWidgets" + />; + } + + let exportChatOption: JSX.Element; + if (!isVideoRoom) { + exportChatOption = { + ev.preventDefault(); + ev.stopPropagation(); + + Modal.createTrackedDialog('Export room dialog', '', ExportDialog, { room }); + onFinished(); + }} + label={_t("Export chat")} + iconClassName="mx_RoomTile_iconExport" + />; + } + const onTagRoom = (ev: ButtonEvent, tagId: TagID) => { ev.preventDefault(); ev.stopPropagation(); @@ -295,35 +343,9 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => { { notificationOption } { favouriteOption } { peopleOption } - - { - ev.preventDefault(); - ev.stopPropagation(); - - ensureViewingRoom(ev); - RightPanelStore.instance.pushCard({ phase: RightPanelPhases.FilePanel }, false); - onFinished(); - }} - label={_t("Files")} - iconClassName="mx_RoomTile_iconFiles" - /> - + { filesOption } { pinsOption } - - { - ev.preventDefault(); - ev.stopPropagation(); - - ensureViewingRoom(ev); - RightPanelStore.instance.setCard({ phase: RightPanelPhases.RoomSummary }, false); - onFinished(); - }} - label={_t("Widgets")} - iconClassName="mx_RoomTile_iconWidgets" - /> - + { widgetsOption } { lowPriorityOption } { copyLinkOption } @@ -343,17 +365,7 @@ const RoomContextMenu = ({ room, onFinished, ...props }: IProps) => { iconClassName="mx_RoomTile_iconSettings" /> - { - ev.preventDefault(); - ev.stopPropagation(); - - Modal.createTrackedDialog('Export room dialog', '', ExportDialog, { room }); - onFinished(); - }} - label={_t("Export chat")} - iconClassName="mx_RoomTile_iconExport" - /> + { exportChatOption } { SettingsStore.getValue("developerMode") && { diff --git a/src/components/views/dialogs/CreateRoomDialog.tsx b/src/components/views/dialogs/CreateRoomDialog.tsx index 4b7b0caa8f..feec344313 100644 --- a/src/components/views/dialogs/CreateRoomDialog.tsx +++ b/src/components/views/dialogs/CreateRoomDialog.tsx @@ -21,15 +21,12 @@ import { RoomType } from "matrix-js-sdk/src/@types/event"; import { JoinRule, Preset, Visibility } from "matrix-js-sdk/src/@types/partials"; import SdkConfig from '../../../SdkConfig'; -import SettingsStore from "../../../settings/SettingsStore"; import withValidation, { IFieldState } from '../elements/Validation'; import { _t } from '../../../languageHandler'; import { MatrixClientPeg } from '../../../MatrixClientPeg'; import { IOpts, privateShouldBeEncrypted } from "../../../createRoom"; import { replaceableComponent } from "../../../utils/replaceableComponent"; -import Heading from "../typography/Heading"; import Field from "../elements/Field"; -import StyledRadioGroup from "../elements/StyledRadioGroup"; import RoomAliasField from "../elements/RoomAliasField"; import LabelledToggleSwitch from "../elements/LabelledToggleSwitch"; import DialogButtons from "../elements/DialogButtons"; @@ -40,6 +37,7 @@ import { getKeyBindingsManager } from "../../../KeyBindingsManager"; import { KeyBindingAction } from "../../../accessibility/KeyboardShortcuts"; interface IProps { + type?: RoomType; defaultPublic?: boolean; defaultName?: string; parentSpace?: Room; @@ -48,7 +46,6 @@ interface IProps { } interface IState { - type?: RoomType; joinRule: JoinRule; isPublic: boolean; isEncrypted: boolean; @@ -80,7 +77,6 @@ export default class CreateRoomDialog extends React.Component { } this.state = { - type: null, isPublic: this.props.defaultPublic || false, isEncrypted: this.props.defaultEncrypted ?? privateShouldBeEncrypted(), joinRule, @@ -100,7 +96,7 @@ export default class CreateRoomDialog extends React.Component { private roomCreateOptions() { const opts: IOpts = {}; const createOpts: IOpts["createOpts"] = opts.createOpts = {}; - opts.roomType = this.state.type; + opts.roomType = this.props.type; createOpts.name = this.state.name; if (this.state.joinRule === JoinRule.Public) { @@ -180,10 +176,6 @@ export default class CreateRoomDialog extends React.Component { this.props.onFinished(false); }; - private onTypeChange = (type: RoomType | "text") => { - this.setState({ type: type === "text" ? null : type }); - }; - private onNameChange = (ev: ChangeEvent) => { this.setState({ name: ev.target.value }); }; @@ -229,6 +221,8 @@ export default class CreateRoomDialog extends React.Component { }); render() { + const isVideoRoom = this.props.type === RoomType.UnstableCall; + let aliasField; if (this.state.joinRule === JoinRule.Public) { const domain = MatrixClientPeg.get().getDomain(); @@ -319,8 +313,12 @@ export default class CreateRoomDialog extends React.Component { ); } - let title = _t("Create a room"); - if (!this.props.parentSpace) { + let title; + if (isVideoRoom) { + title = _t("Create a video room"); + } else if (this.props.parentSpace) { + title = _t("Create a room"); + } else { title = this.state.joinRule === JoinRule.Public ? _t('Create a public room') : _t('Create a private room'); } @@ -333,20 +331,6 @@ export default class CreateRoomDialog extends React.Component { >
- { SettingsStore.getValue("feature_voice_rooms") ? <> - { _t("Room type") } - - - { _t("Room details") } - : null } {
- diff --git a/src/components/views/elements/FacePile.tsx b/src/components/views/elements/FacePile.tsx index ba246c4843..bb39cc7957 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, ReactNode, useContext } from "react"; +import React, { FC, 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"; @@ -26,48 +26,17 @@ import TextWithTooltip from "../elements/TextWithTooltip"; import { useRoomMembers } from "../../../hooks/useRoomMembers"; import MatrixClientContext from "../../../contexts/MatrixClientContext"; -interface IProps extends HTMLAttributes { - faces: ReactNode[]; - overflow: boolean; - tooltip?: ReactNode; - children?: ReactNode; -} - -const FacePile = ({ faces, overflow, tooltip, children, ...props }: IProps) => { - const pileContents = <> - { overflow ? : null } - { faces } - ; - - return
- { tooltip ? ( - - { pileContents } - - ) : ( -
- { pileContents } -
- ) } - { children } -
; -}; - -export default FacePile; - const DEFAULT_NUM_FACES = 5; -const isKnownMember = (member: RoomMember) => !!DMRoomMap.shared().getDMRoomsForUserId(member.userId)?.length; - -interface IRoomProps extends HTMLAttributes { +interface IProps extends HTMLAttributes { room: Room; onlyKnownUsers?: boolean; numShown?: number; } -export const RoomFacePile = ( - { room, onlyKnownUsers = true, numShown = DEFAULT_NUM_FACES, ...props }: IRoomProps, -) => { +const isKnownMember = (member: RoomMember) => !!DMRoomMap.shared().getDMRoomsForUserId(member.userId)?.length; + +const FacePile: FC = ({ room, onlyKnownUsers = true, numShown = DEFAULT_NUM_FACES, ...props }) => { const cli = useContext(MatrixClientContext); const isJoined = room.getMyMembership() === "join"; let members = useRoomMembers(room); @@ -89,8 +58,6 @@ export const RoomFacePile = ( // 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(", "); - const faces = shownMembers.map(m => - ); let tooltip: ReactNode; if (props.onClick) { @@ -123,9 +90,16 @@ export const RoomFacePile = ( } } - return numShown} tooltip={tooltip}> + return
+ + { 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/right_panel/RoomSummaryCard.tsx b/src/components/views/right_panel/RoomSummaryCard.tsx index b0cc55101a..65654f37ea 100644 --- a/src/components/views/right_panel/RoomSummaryCard.tsx +++ b/src/components/views/right_panel/RoomSummaryCard.tsx @@ -42,7 +42,7 @@ import { UIComponent, UIFeature } from "../../../settings/UIFeature"; import { ChevronFace, ContextMenuTooltipButton, useContextMenu } from "../../structures/ContextMenu"; import WidgetContextMenu from "../context_menus/WidgetContextMenu"; import { useRoomMemberCount } from "../../../hooks/useRoomMembers"; -import { useSettingValue } from "../../../hooks/useSettings"; +import { useFeatureEnabled } from "../../../hooks/useSettings"; import { usePinnedEvents } from "./PinnedMessagesCard"; import { Container, MAX_PINNED, WidgetLayoutStore } from "../../../stores/widgets/WidgetLayoutStore"; import RoomName from "../elements/RoomName"; @@ -269,6 +269,7 @@ const RoomSummaryCard: React.FC = ({ room, onClose }) => { const isRoomEncrypted = useIsEncrypted(cli, room); const roomContext = useContext(RoomContext); const e2eStatus = roomContext.e2eStatus; + const isVideoRoom = useFeatureEnabled("feature_video_rooms") && room.isCallRoom(); const alias = room.getCanonicalAlias() || room.getAltAliases()[0] || ""; const header = @@ -297,7 +298,7 @@ const RoomSummaryCard: React.FC = ({ room, onClose }) => { ; const memberCount = useRoomMemberCount(room); - const pinningEnabled = useSettingValue("feature_pinning"); + const pinningEnabled = useFeatureEnabled("feature_pinning"); const pinCount = usePinnedEvents(pinningEnabled && room)?.length; return @@ -308,18 +309,19 @@ const RoomSummaryCard: React.FC = ({ room, onClose }) => { { memberCount }
- - { pinningEnabled && } - } + { !isVideoRoom && + } @@ -330,6 +332,7 @@ const RoomSummaryCard: React.FC = ({ room, onClose }) => { { SettingsStore.getValue(UIFeature.Widgets) + && !isVideoRoom && shouldShowComponent(UIComponent.AddIntegrations) && } diff --git a/src/components/views/rooms/RoomHeader.tsx b/src/components/views/rooms/RoomHeader.tsx index 9df1ba663c..1a71290890 100644 --- a/src/components/views/rooms/RoomHeader.tsx +++ b/src/components/views/rooms/RoomHeader.tsx @@ -206,6 +206,7 @@ export default class RoomHeader extends React.Component { const buttons: JSX.Element[] = []; if (this.props.inRoom && + this.props.onCallPlaced && !this.context.tombstone && SettingsStore.getValue("showCallButtonsInComposer") ) { diff --git a/src/components/views/rooms/RoomList.tsx b/src/components/views/rooms/RoomList.tsx index d54ac55ffb..b7e1f87dc5 100644 --- a/src/components/views/rooms/RoomList.tsx +++ b/src/components/views/rooms/RoomList.tsx @@ -16,6 +16,7 @@ limitations under the License. import React, { ComponentType, createRef, ReactComponentElement, RefObject } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; +import { RoomType } from "matrix-js-sdk/src/@types/event"; import * as fbEmitter from "fbemitter"; import { EventType } from "matrix-js-sdk/src/@types/event"; @@ -222,8 +223,8 @@ const UntaggedAuxButton = ({ tabIndex }: IAuxButtonProps) => { showCreateRoom ? (<> { e.preventDefault(); e.stopPropagation(); @@ -235,6 +236,19 @@ const UntaggedAuxButton = ({ tabIndex }: IAuxButtonProps) => { tooltip={canAddRooms ? undefined : _t("You do not have permissions to create new rooms in this space")} /> + { SettingsStore.getValue("feature_video_rooms") && { + e.preventDefault(); + e.stopPropagation(); + closeMenu(); + showCreateNewRoom(activeSpace, RoomType.UnstableCall); + }} + disabled={!canAddRooms} + tooltip={canAddRooms ? undefined + : _t("You do not have permissions to create new rooms in this space")} + /> } { ; } else if (menuDisplayed) { contextMenuContent = - { showCreateRoom && { - e.preventDefault(); - e.stopPropagation(); - closeMenu(); - defaultDispatcher.dispatch({ action: "view_create_room" }); - PosthogTrackers.trackInteraction("WebRoomListRoomsSublistPlusMenuCreateRoomItem", e); - }} - /> } + { showCreateRoom && <> + { + e.preventDefault(); + e.stopPropagation(); + closeMenu(); + defaultDispatcher.dispatch({ action: "view_create_room" }); + PosthogTrackers.trackInteraction("WebRoomListRoomsSublistPlusMenuCreateRoomItem", e); + }} + /> + { SettingsStore.getValue("feature_video_rooms") && { + e.preventDefault(); + e.stopPropagation(); + closeMenu(); + defaultDispatcher.dispatch({ + action: "view_create_room", + type: RoomType.UnstableCall, + }); + }} + /> } + } { const allRoomsInHome = useEventEmitterState(SpaceStore.instance, UPDATE_HOME_BEHAVIOUR, () => { return SpaceStore.instance.allRoomsInHome; }); + const videoRoomsEnabled = useFeatureEnabled("feature_video_rooms"); const pendingActions = usePendingActions(); const filterCondition = RoomListStore.instance.getFirstNameFilterCondition(); @@ -195,19 +197,31 @@ const RoomListHeader = ({ onVisibilityChange }: IProps) => { />; } - let createNewRoomOption: JSX.Element; + let newRoomOptions: JSX.Element; if (activeSpace?.currentState.maySendStateEvent(EventType.RoomAvatar, cli.getUserId())) { - createNewRoomOption = { - e.preventDefault(); - e.stopPropagation(); - showCreateNewRoom(activeSpace); - PosthogTrackers.trackInteraction("WebRoomListHeaderPlusMenuCreateRoomItem", e); - closePlusMenu(); - }} - />; + newRoomOptions = <> + { + e.preventDefault(); + e.stopPropagation(); + showCreateNewRoom(activeSpace); + PosthogTrackers.trackInteraction("WebRoomListHeaderPlusMenuCreateRoomItem", e); + closePlusMenu(); + }} + /> + { videoRoomsEnabled && { + e.preventDefault(); + e.stopPropagation(); + showCreateNewRoom(activeSpace, RoomType.UnstableCall); + closePlusMenu(); + }} + /> } + ; } contextMenu = { > { inviteOption } - { createNewRoomOption } + { newRoomOptions } { ; } else if (plusMenuDisplayed) { - let startChatOpt: JSX.Element; - let createRoomOpt: JSX.Element; + let newRoomOpts: JSX.Element; let joinRoomOpt: JSX.Element; if (canCreateRooms) { - startChatOpt = ( + newRoomOpts = <> { closePlusMenu(); }} /> - ); - createRoomOpt = ( { e.preventDefault(); e.stopPropagation(); @@ -291,7 +302,20 @@ const RoomListHeader = ({ onVisibilityChange }: IProps) => { closePlusMenu(); }} /> - ); + { videoRoomsEnabled && { + e.preventDefault(); + e.stopPropagation(); + defaultDispatcher.dispatch({ + action: "view_create_room", + type: RoomType.UnstableCall, + }); + closePlusMenu(); + }} + /> } + ; } if (canExploreRooms) { joinRoomOpt = ( @@ -314,8 +338,7 @@ const RoomListHeader = ({ onVisibilityChange }: IProps) => { compact > - { startChatOpt } - { createRoomOpt } + { newRoomOpts } { joinRoomOpt } ; diff --git a/src/components/views/rooms/RoomTile.tsx b/src/components/views/rooms/RoomTile.tsx index bdea7ea9f8..a2557506e2 100644 --- a/src/components/views/rooms/RoomTile.tsx +++ b/src/components/views/rooms/RoomTile.tsx @@ -33,10 +33,7 @@ import { _t } from "../../../languageHandler"; import { ChevronFace, ContextMenuTooltipButton } from "../../structures/ContextMenu"; import { DefaultTagID, TagID } from "../../../stores/room-list/models"; import { MessagePreviewStore } from "../../../stores/room-list/MessagePreviewStore"; -import BaseAvatar from "../avatars/BaseAvatar"; -import MemberAvatar from "../avatars/MemberAvatar"; import DecoratedRoomAvatar from "../avatars/DecoratedRoomAvatar"; -import FacePile from "../elements/FacePile"; import { RoomNotifState } from "../../../RoomNotifs"; import { MatrixClientPeg } from "../../../MatrixClientPeg"; import NotificationBadge from "./NotificationBadge"; @@ -55,17 +52,16 @@ import IconizedContextMenu, { IconizedContextMenuOptionList, IconizedContextMenuRadio, } from "../context_menus/IconizedContextMenu"; -import VoiceChannelStore, { VoiceChannelEvent, IJitsiParticipant } from "../../../stores/VoiceChannelStore"; -import { getConnectedMembers } from "../../../utils/VoiceChannelUtils"; +import VideoChannelStore, { VideoChannelEvent, IJitsiParticipant } from "../../../stores/VideoChannelStore"; +import { getConnectedMembers } from "../../../utils/VideoChannelUtils"; import { replaceableComponent } from "../../../utils/replaceableComponent"; import PosthogTrackers from "../../../PosthogTrackers"; import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload"; import { KeyBindingAction } from "../../../accessibility/KeyboardShortcuts"; import { getKeyBindingsManager } from "../../../KeyBindingsManager"; -enum VoiceConnectionState { +enum VideoStatus { Disconnected, - Connecting, Connected, } @@ -83,10 +79,10 @@ interface IState { notificationsMenuPosition: PartialDOMRect; generalMenuPosition: PartialDOMRect; messagePreview?: string; - voiceConnectionState: VoiceConnectionState; - // Active voice channel members, according to room state - voiceMembers: RoomMember[]; - // Active voice channel members, according to Jitsi + videoStatus: VideoStatus; + // Active video channel members, according to room state + videoMembers: RoomMember[]; + // Active video channel members, according to Jitsi jitsiParticipants: IJitsiParticipant[]; } @@ -106,27 +102,28 @@ export default class RoomTile extends React.PureComponent { private roomTileRef = createRef(); private notificationState: NotificationState; private roomProps: RoomEchoChamber; - private isVoiceRoom: boolean; + private isVideoRoom: boolean; constructor(props: IProps) { super(props); + const videoConnected = VideoChannelStore.instance.roomId === this.props.room.roomId; + this.state = { selected: ActiveRoomObserver.activeRoomId === this.props.room.roomId, notificationsMenuPosition: null, generalMenuPosition: null, // generatePreview() will return nothing if the user has previews disabled messagePreview: "", - voiceConnectionState: VoiceChannelStore.instance.roomId === this.props.room.roomId ? - VoiceConnectionState.Connected : VoiceConnectionState.Disconnected, - voiceMembers: [], - jitsiParticipants: [], + videoStatus: videoConnected ? VideoStatus.Connected : VideoStatus.Disconnected, + videoMembers: getConnectedMembers(this.props.room.currentState), + jitsiParticipants: videoConnected ? VideoChannelStore.instance.participants : [], }; this.generatePreview(); this.notificationState = RoomNotificationStateStore.instance.getRoomState(this.props.room); this.roomProps = EchoChamber.forRoom(this.props.room); - this.isVoiceRoom = SettingsStore.getValue("feature_voice_rooms") && this.props.room.isCallRoom(); + this.isVideoRoom = SettingsStore.getValue("feature_video_rooms") && this.props.room.isCallRoom(); } private onRoomNameUpdate = (room: Room) => { @@ -165,8 +162,9 @@ export default class RoomTile extends React.PureComponent { MessagePreviewStore.getPreviewChangedEventName(this.props.room), this.onRoomPreviewChanged, ); - prevProps.room?.currentState?.off(RoomStateEvent.Events, this.updateVoiceMembers); - this.props.room?.currentState?.on(RoomStateEvent.Events, this.updateVoiceMembers); + prevProps.room?.currentState?.off(RoomStateEvent.Events, this.updateVideoMembers); + this.props.room?.currentState?.on(RoomStateEvent.Events, this.updateVideoMembers); + this.updateVideoStatus(); prevProps.room?.off(RoomEvent.Name, this.onRoomNameUpdate); this.props.room?.on(RoomEvent.Name, this.onRoomNameUpdate); } @@ -177,7 +175,6 @@ export default class RoomTile extends React.PureComponent { if (this.state.selected) { this.scrollIntoView(); } - this.updateVoiceMembers(); ActiveRoomObserver.addListener(this.props.room.roomId, this.onActiveRoomUpdate); this.dispatcherRef = defaultDispatcher.register(this.onAction); @@ -188,7 +185,13 @@ export default class RoomTile extends React.PureComponent { this.notificationState.on(NotificationStateEvents.Update, this.onNotificationUpdate); this.roomProps.on(PROPERTY_UPDATED, this.onRoomPropertyUpdate); this.props.room?.on(RoomEvent.Name, this.onRoomNameUpdate); - this.props.room?.currentState?.on(RoomStateEvent.Events, this.updateVoiceMembers); + this.props.room?.currentState?.on(RoomStateEvent.Events, this.updateVideoMembers); + + VideoChannelStore.instance.on(VideoChannelEvent.Connect, this.updateVideoStatus); + VideoChannelStore.instance.on(VideoChannelEvent.Disconnect, this.updateVideoStatus); + if (VideoChannelStore.instance.roomId === this.props.room.roomId) { + VideoChannelStore.instance.on(VideoChannelEvent.Participants, this.updateJitsiParticipants); + } } public componentWillUnmount() { @@ -198,13 +201,16 @@ export default class RoomTile extends React.PureComponent { MessagePreviewStore.getPreviewChangedEventName(this.props.room), this.onRoomPreviewChanged, ); - this.props.room.currentState.off(RoomStateEvent.Events, this.updateVoiceMembers); + this.props.room.currentState.off(RoomStateEvent.Events, this.updateVideoMembers); this.props.room.off(RoomEvent.Name, this.onRoomNameUpdate); } ActiveRoomObserver.removeListener(this.props.room.roomId, this.onActiveRoomUpdate); defaultDispatcher.unregister(this.dispatcherRef); this.notificationState.off(NotificationStateEvents.Update, this.onNotificationUpdate); this.roomProps.off(PROPERTY_UPDATED, this.onRoomPropertyUpdate); + + VideoChannelStore.instance.off(VideoChannelEvent.Connect, this.updateVideoStatus); + VideoChannelStore.instance.off(VideoChannelEvent.Disconnect, this.updateVideoStatus); } private onAction = (payload: ActionPayload) => { @@ -255,11 +261,6 @@ export default class RoomTile extends React.PureComponent { metricsTrigger: "RoomList", metricsViaKeyboard: ev.type !== "click", }); - - // Connect to the voice channel if this is a voice room - if (this.isVoiceRoom && this.state.voiceConnectionState === VoiceConnectionState.Disconnected) { - await this.connectVoice(); - } }; private onActiveRoomUpdate = (isActive: boolean) => { @@ -584,87 +585,24 @@ export default class RoomTile extends React.PureComponent { ); } - private updateVoiceMembers = () => { - this.setState({ voiceMembers: getConnectedMembers(this.props.room.currentState) }); + private updateVideoMembers = () => { + this.setState({ videoMembers: getConnectedMembers(this.props.room.currentState) }); + }; + + private updateVideoStatus = () => { + if (VideoChannelStore.instance.roomId === this.props.room?.roomId) { + this.setState({ videoStatus: VideoStatus.Connected }); + VideoChannelStore.instance.on(VideoChannelEvent.Participants, this.updateJitsiParticipants); + } else { + this.setState({ videoStatus: VideoStatus.Disconnected }); + VideoChannelStore.instance.off(VideoChannelEvent.Participants, this.updateJitsiParticipants); + } }; private updateJitsiParticipants = (participants: IJitsiParticipant[]) => { this.setState({ jitsiParticipants: participants }); }; - private renderVoiceChannel(): React.ReactElement | null { - let faces; - if (this.state.voiceConnectionState === VoiceConnectionState.Connected) { - faces = this.state.jitsiParticipants.map(p => - , - ); - } else if (this.state.voiceMembers.length) { - faces = this.state.voiceMembers.map(m => - , - ); - } else { - return null; - } - - // TODO: The below "join" button will eventually show up on text rooms - // with an active voice channel, but that isn't implemented yet - return
- - { this.isVoiceRoom ? null : ( - - { _t("Join") } - - ) } -
; - } - - private async connectVoice() { - this.setState({ voiceConnectionState: VoiceConnectionState.Connecting }); - // TODO: Actually wait for the widget to be ready, instead of guessing. - // This hack is only in place until we find out for sure whether design - // wants the room view to open when connecting voice, or if this should - // somehow connect in the background. Until then, it's not worth the - // effort to solve this properly. - await new Promise(resolve => setTimeout(resolve, 1000)); - - const waitForConnect = VoiceChannelStore.instance.connect(this.props.room.roomId); - // Participant data comes down the event channel quickly, so prepare in advance - VoiceChannelStore.instance.on(VoiceChannelEvent.Participants, this.updateJitsiParticipants); - try { - await waitForConnect; - this.setState({ voiceConnectionState: VoiceConnectionState.Connected }); - - VoiceChannelStore.instance.once(VoiceChannelEvent.Disconnect, () => { - this.setState({ - voiceConnectionState: VoiceConnectionState.Disconnected, - jitsiParticipants: [], - }), - VoiceChannelStore.instance.off(VoiceChannelEvent.Participants, this.updateJitsiParticipants); - }); - } catch (e) { - // If it failed, clean up our advance preparations - logger.error("Failed to connect voice", e); - VoiceChannelStore.instance.off(VoiceChannelEvent.Participants, this.updateJitsiParticipants); - } - } - public render(): React.ReactElement { const classes = classNames({ 'mx_RoomTile': true, @@ -692,34 +630,44 @@ export default class RoomTile extends React.PureComponent { } let subtitle; - if (this.isVoiceRoom) { - switch (this.state.voiceConnectionState) { - case VoiceConnectionState.Disconnected: - subtitle = ( -
- { _t("Voice room") } -
- ); + if (this.isVideoRoom) { + let videoText: string; + let videoActive: boolean; + let participantCount: number; + + switch (this.state.videoStatus) { + case VideoStatus.Disconnected: + videoText = _t("Video"); + videoActive = false; + participantCount = this.state.videoMembers.length; break; - case VoiceConnectionState.Connecting: - subtitle = ( -
- { _t("Connecting...") } -
- ); - break; - case VoiceConnectionState.Connected: - subtitle = ( -
- { _t("Connected") } -
- ); + case VideoStatus.Connected: + videoText = _t("Connected"); + videoActive = true; + participantCount = this.state.jitsiParticipants.length; } + + subtitle = ( +
+ + { videoText } + + { participantCount ? <> + { " · " } + + { participantCount } + + : null } +
+ ); } else if (this.showMessagePreview && this.state.messagePreview) { subtitle = (
{ displayBadge={this.props.isMinimized} tooltipProps={{ tabIndex: isActive ? 0 : -1 }} /> -
-
- { titleContainer } - { badge } - { this.renderGeneralMenu() } - { this.renderNotificationsMenu(isActive) } -
- { this.renderVoiceChannel() } -
+ { titleContainer } + { badge } + { this.renderGeneralMenu() } + { this.renderNotificationsMenu(isActive) } } diff --git a/src/components/views/voip/VoiceChannelRadio.tsx b/src/components/views/voip/VoiceChannelRadio.tsx deleted file mode 100644 index 3a3e362e5b..0000000000 --- a/src/components/views/voip/VoiceChannelRadio.tsx +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2022 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, { FC, useState, useContext } from "react"; -import classNames from "classnames"; - -import { _t } from "../../../languageHandler"; -import { useEventEmitter } from "../../../hooks/useEventEmitter"; -import MatrixClientContext from "../../../contexts/MatrixClientContext"; -import VoiceChannelStore, { VoiceChannelEvent } from "../../../stores/VoiceChannelStore"; -import DecoratedRoomAvatar from "../avatars/DecoratedRoomAvatar"; -import AccessibleButton from "../elements/AccessibleButton"; -import AccessibleTooltipButton from "../elements/AccessibleTooltipButton"; - -const _VoiceChannelRadio: FC<{ roomId: string }> = ({ roomId }) => { - const cli = useContext(MatrixClientContext); - const room = cli.getRoom(roomId); - const store = VoiceChannelStore.instance; - - const [audioMuted, setAudioMuted] = useState(store.audioMuted); - const [videoMuted, setVideoMuted] = useState(store.videoMuted); - - useEventEmitter(store, VoiceChannelEvent.MuteAudio, () => setAudioMuted(true)); - useEventEmitter(store, VoiceChannelEvent.UnmuteAudio, () => setAudioMuted(false)); - useEventEmitter(store, VoiceChannelEvent.MuteVideo, () => setVideoMuted(true)); - useEventEmitter(store, VoiceChannelEvent.UnmuteVideo, () => setVideoMuted(false)); - - return
-
- -
-
{ _t("Connected") }
-
{ room.name }
-
- store.disconnect()} - /> -
-
- videoMuted ? store.unmuteVideo() : store.muteVideo()} - > - { videoMuted ? _t("Video off") : _t("Video") } - - audioMuted ? store.unmuteAudio() : store.muteAudio()} - > - { audioMuted ? _t("Mic off") : _t("Mic") } - -
-
; -}; - -const VoiceChannelRadio: FC<{}> = () => { - const store = VoiceChannelStore.instance; - - const [activeChannel, setActiveChannel] = useState(VoiceChannelStore.instance.roomId); - useEventEmitter(store, VoiceChannelEvent.Connect, () => - setActiveChannel(VoiceChannelStore.instance.roomId), - ); - useEventEmitter(store, VoiceChannelEvent.Disconnect, () => - setActiveChannel(null), - ); - - return activeChannel ? <_VoiceChannelRadio roomId={activeChannel} /> : null; -}; - -export default VoiceChannelRadio; diff --git a/src/createRoom.ts b/src/createRoom.ts index 91eb1b45e9..adfca7dd3a 100644 --- a/src/createRoom.ts +++ b/src/createRoom.ts @@ -42,7 +42,7 @@ import { isJoinedOrNearlyJoined } from "./utils/membership"; import { VIRTUAL_ROOM_EVENT_TYPE } from "./CallHandler"; import SpaceStore from "./stores/spaces/SpaceStore"; import { makeSpaceParentEvent } from "./utils/space"; -import { VOICE_CHANNEL_MEMBER, addVoiceChannel } from "./utils/VoiceChannelUtils"; +import { VIDEO_CHANNEL_MEMBER, addVideoChannel } from "./utils/VideoChannelUtils"; import { Action } from "./dispatcher/actions"; import ErrorDialog from "./components/views/dialogs/ErrorDialog"; import Spinner from "./components/views/elements/Spinner"; @@ -128,11 +128,11 @@ export default async function createRoom(opts: IOpts): Promise { [RoomCreateTypeField]: opts.roomType, }; - // In voice rooms, allow all users to send voice member updates + // In video rooms, allow all users to send video member updates if (opts.roomType === RoomType.UnstableCall) { createOpts.power_level_content_override = { events: { - [VOICE_CHANNEL_MEMBER]: 0, + [VIDEO_CHANNEL_MEMBER]: 0, // Annoyingly, we have to reiterate all the defaults here [EventType.RoomName]: 50, [EventType.RoomAvatar]: 50, @@ -262,9 +262,9 @@ export default async function createRoom(opts: IOpts): Promise { return SpaceStore.instance.addRoomToSpace(opts.parentSpace, roomId, [client.getDomain()], opts.suggested); } }).then(() => { - // Set up voice rooms with a Jitsi widget + // Set up video rooms with a Jitsi widget if (opts.roomType === RoomType.UnstableCall) { - return addVoiceChannel(roomId, createOpts.name); + return addVideoChannel(roomId, createOpts.name); } }).then(function() { // NB createRoom doesn't block on the client seeing the echo that the diff --git a/src/i18n/strings/en_EN.json b/src/i18n/strings/en_EN.json index 05182353e2..dea47408e9 100644 --- a/src/i18n/strings/en_EN.json +++ b/src/i18n/strings/en_EN.json @@ -868,7 +868,7 @@ "Message Pinning": "Message Pinning", "Threaded messaging": "Threaded messaging", "Custom user status messages": "Custom user status messages", - "Voice & video rooms (under active development)": "Voice & video rooms (under active development)", + "Video rooms (under active development)": "Video rooms (under active development)", "Render simple counters in room header": "Render simple counters in room header", "Multiple integration managers (requires manual setup)": "Multiple integration managers (requires manual setup)", "Try out new ways to ignore people (experimental)": "Try out new ways to ignore people (experimental)", @@ -1002,12 +1002,6 @@ "Your camera is turned off": "Your camera is turned off", "Your camera is still enabled": "Your camera is still enabled", "Dial": "Dial", - "Connected": "Connected", - "Disconnect": "Disconnect", - "Video off": "Video off", - "Video": "Video", - "Mic off": "Mic off", - "Mic": "Mic", "Dialpad": "Dialpad", "Mute the microphone": "Mute the microphone", "Unmute the microphone": "Unmute the microphone", @@ -1359,6 +1353,7 @@ "The identity server you have chosen does not have any terms of service.": "The identity server you have chosen does not have any terms of service.", "Disconnect identity server": "Disconnect identity server", "Disconnect from the identity server ?": "Disconnect from the identity server ?", + "Disconnect": "Disconnect", "You should remove your personal data from identity server before disconnecting. Unfortunately, identity server is currently offline or cannot be reached.": "You should remove your personal data from identity server before disconnecting. Unfortunately, identity server is currently offline or cannot be reached.", "You should:": "You should:", "check your browser plugins for anything that might block the identity server (such as Privacy Badger)": "check your browser plugins for anything that might block the identity server (such as Privacy Badger)", @@ -1757,8 +1752,9 @@ "Add people": "Add people", "Start chat": "Start chat", "Explore rooms": "Explore rooms", - "Create new room": "Create new room", + "New room": "New room", "You do not have permissions to create new rooms in this space": "You do not have permissions to create new rooms in this space", + "New video room": "New video room", "Add existing room": "Add existing room", "You do not have permissions to add rooms to this space": "You do not have permissions to add rooms to this space", "Explore public rooms": "Explore public rooms", @@ -1851,9 +1847,10 @@ "Low Priority": "Low Priority", "Copy room link": "Copy room link", "Leave": "Leave", - "Join": "Join", - "Voice room": "Voice room", - "Connecting...": "Connecting...", + "Video": "Video", + "Connected": "Connected", + "%(count)s participants|other": "%(count)s participants", + "%(count)s participants|one": "1 participant", "%(count)s unread messages including mentions.|other": "%(count)s unread messages including mentions.", "%(count)s unread messages including mentions.|one": "1 unread mention.", "%(count)s unread messages.|other": "%(count)s unread messages.", @@ -2207,6 +2204,7 @@ "Application window": "Application window", "Share content": "Share content", "Backspace": "Backspace", + "Join": "Join", "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.", "Something went wrong!": "Something went wrong!", "%(nameList)s %(transitionList)s": "%(nameList)s %(transitionList)s", @@ -2420,20 +2418,18 @@ "Enable end-to-end encryption": "Enable end-to-end encryption", "You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.", "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.": "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.", + "Create a video room": "Create a video room", "Create a room": "Create a room", "Create a public room": "Create a public room", "Create a private room": "Create a private room", - "Room type": "Room type", - "Text room": "Text room", - "Voice & video room": "Voice & video room", - "Room details": "Room details", "Topic (optional)": "Topic (optional)", "Room visibility": "Room visibility", "Private room (invite only)": "Private room (invite only)", "Public room": "Public room", "Visible to space members": "Visible to space members", "Block anyone not part of %(serverName)s from ever joining this room.": "Block anyone not part of %(serverName)s from ever joining this room.", - "Create Room": "Create Room", + "Create video room": "Create video room", + "Create room": "Create room", "Anyone in will be able to find and join.": "Anyone in will be able to find and join.", "Anyone will be able to find and join this space, not just members of .": "Anyone will be able to find and join this space, not just members of .", "Only people invited will be able to find and join this space.": "Only people invited will be able to find and join this space.", @@ -3021,6 +3017,7 @@ "Unable to look up room ID from server": "Unable to look up room ID from server", "Preview": "Preview", "View": "View", + "Create new room": "Create new room", "No results for \"%(query)s\"": "No results for \"%(query)s\"", "Try different words or check for typos. Some results may not be visible as they're private and you need an invite to join them.": "Try different words or check for typos. Some results may not be visible as they're private and you need an invite to join them.", "Find a room…": "Find a room…", diff --git a/src/settings/Settings.tsx b/src/settings/Settings.tsx index 452c2185c5..f25a4bf8ce 100644 --- a/src/settings/Settings.tsx +++ b/src/settings/Settings.tsx @@ -237,10 +237,10 @@ export const SETTINGS: {[setting: string]: ISetting} = { default: false, controller: new CustomStatusController(), }, - "feature_voice_rooms": { + "feature_video_rooms": { isFeature: true, labsGroup: LabGroup.Rooms, - displayName: _td("Voice & video rooms (under active development)"), + displayName: _td("Video rooms (under active development)"), supportedLevels: LEVELS_FEATURE, default: false, // Reload to ensure that the left panel etc. get remounted diff --git a/src/stores/VideoChannelStore.ts b/src/stores/VideoChannelStore.ts new file mode 100644 index 0000000000..6bd1b621e4 --- /dev/null +++ b/src/stores/VideoChannelStore.ts @@ -0,0 +1,164 @@ +/* +Copyright 2022 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 { logger } from "matrix-js-sdk/src/logger"; +import { ClientWidgetApi, IWidgetApiRequest } from "matrix-widget-api"; + +import { MatrixClientPeg } from "../MatrixClientPeg"; +import { ElementWidgetActions } from "./widgets/ElementWidgetActions"; +import { WidgetMessagingStore } from "./widgets/WidgetMessagingStore"; +import ActiveWidgetStore, { ActiveWidgetStoreEvent } from "./ActiveWidgetStore"; +import { + VIDEO_CHANNEL, + VIDEO_CHANNEL_MEMBER, + IVideoChannelMemberContent, + getVideoChannel, +} from "../utils/VideoChannelUtils"; +import WidgetUtils from "../utils/WidgetUtils"; + +export enum VideoChannelEvent { + Connect = "connect", + Disconnect = "disconnect", + Participants = "participants", +} + +export interface IJitsiParticipant { + avatarURL: string; + displayName: string; + formattedDisplayName: string; + participantId: string; +} + +/* + * Holds information about the currently active video channel. + */ +export default class VideoChannelStore extends EventEmitter { + private static _instance: VideoChannelStore; + + public static get instance(): VideoChannelStore { + if (!VideoChannelStore._instance) { + VideoChannelStore._instance = new VideoChannelStore(); + } + return VideoChannelStore._instance; + } + + private readonly cli = MatrixClientPeg.get(); + private activeChannel: ClientWidgetApi; + private _roomId: string; + private _participants: IJitsiParticipant[]; + + public get roomId(): string { + return this._roomId; + } + + public get participants(): IJitsiParticipant[] { + return this._participants; + } + + public start = () => { + ActiveWidgetStore.instance.on(ActiveWidgetStoreEvent.Update, this.onActiveWidgetUpdate); + }; + + public stop = () => { + ActiveWidgetStore.instance.off(ActiveWidgetStoreEvent.Update, this.onActiveWidgetUpdate); + }; + + private setConnected = async (roomId: string) => { + const jitsi = getVideoChannel(roomId); + if (!jitsi) throw new Error(`No video channel in room ${roomId}`); + + const messaging = WidgetMessagingStore.instance.getMessagingForUid(WidgetUtils.getWidgetUid(jitsi)); + if (!messaging) throw new Error(`Failed to bind video channel in room ${roomId}`); + + this.activeChannel = messaging; + this._roomId = roomId; + this._participants = []; + + this.activeChannel.once(`action:${ElementWidgetActions.HangupCall}`, this.onHangup); + this.activeChannel.on(`action:${ElementWidgetActions.CallParticipants}`, this.onParticipants); + + this.emit(VideoChannelEvent.Connect); + + // Tell others that we're connected, by adding our device to room state + await this.updateDevices(devices => Array.from(new Set(devices).add(this.cli.getDeviceId()))); + }; + + private setDisconnected = async () => { + this.activeChannel.off(`action:${ElementWidgetActions.HangupCall}`, this.onHangup); + this.activeChannel.off(`action:${ElementWidgetActions.CallParticipants}`, this.onParticipants); + + this.activeChannel = null; + this._participants = null; + + try { + // Tell others that we're disconnected, by removing our device from room state + await this.updateDevices(devices => { + const devicesSet = new Set(devices); + devicesSet.delete(this.cli.getDeviceId()); + return Array.from(devicesSet); + }); + } finally { + // Save this for last, since updateDevices needs the room ID + this._roomId = null; + this.emit(VideoChannelEvent.Disconnect); + } + }; + + private ack = (ev: CustomEvent) => { + // Even if we don't have a reply to a given widget action, we still need + // to give the widget API something to acknowledge receipt + this.activeChannel.transport.reply(ev.detail, {}); + }; + + private updateDevices = async (fn: (devices: string[]) => string[]) => { + if (!this.roomId) { + logger.error("Tried to update devices while disconnected"); + return; + } + + const room = this.cli.getRoom(this.roomId); + const devicesState = room.currentState.getStateEvents(VIDEO_CHANNEL_MEMBER, this.cli.getUserId()); + const devices = devicesState?.getContent()?.devices ?? []; + + await this.cli.sendStateEvent( + this.roomId, VIDEO_CHANNEL_MEMBER, { devices: fn(devices) }, this.cli.getUserId(), + ); + }; + + private onHangup = async (ev: CustomEvent) => { + this.ack(ev); + await this.setDisconnected(); + }; + + private onParticipants = (ev: CustomEvent) => { + this._participants = ev.detail.data.participants as IJitsiParticipant[]; + this.emit(VideoChannelEvent.Participants, ev.detail.data.participants); + this.ack(ev); + }; + + private onActiveWidgetUpdate = async () => { + if (this.activeChannel) { + // We got disconnected from the previous video channel, so clean up + await this.setDisconnected(); + } + + // If the new active widget is a video channel, that means we joined + if (ActiveWidgetStore.instance.getPersistentWidgetId() === VIDEO_CHANNEL) { + await this.setConnected(ActiveWidgetStore.instance.getPersistentRoomId()); + } + }; +} diff --git a/src/stores/VoiceChannelStore.ts b/src/stores/VoiceChannelStore.ts deleted file mode 100644 index 9e77a0094b..0000000000 --- a/src/stores/VoiceChannelStore.ts +++ /dev/null @@ -1,267 +0,0 @@ -/* -Copyright 2022 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 { logger } from "matrix-js-sdk/src/logger"; -import { ClientWidgetApi, IWidgetApiRequest } from "matrix-widget-api"; - -import { MatrixClientPeg } from "../MatrixClientPeg"; -import { ElementWidgetActions } from "./widgets/ElementWidgetActions"; -import { WidgetMessagingStore } from "./widgets/WidgetMessagingStore"; -import { - VOICE_CHANNEL_MEMBER, - IVoiceChannelMemberContent, - getVoiceChannel, -} from "../utils/VoiceChannelUtils"; -import { timeout } from "../utils/promise"; -import WidgetUtils from "../utils/WidgetUtils"; - -export enum VoiceChannelEvent { - Connect = "connect", - Disconnect = "disconnect", - Participants = "participants", - MuteAudio = "mute_audio", - UnmuteAudio = "unmute_audio", - MuteVideo = "mute_video", - UnmuteVideo = "unmute_video", -} - -export interface IJitsiParticipant { - avatarURL: string; - displayName: string; - formattedDisplayName: string; - participantId: string; -} - -/* - * Holds information about the currently active voice channel. - */ -export default class VoiceChannelStore extends EventEmitter { - private static _instance: VoiceChannelStore; - private static readonly TIMEOUT = 8000; - - public static get instance(): VoiceChannelStore { - if (!VoiceChannelStore._instance) { - VoiceChannelStore._instance = new VoiceChannelStore(); - } - return VoiceChannelStore._instance; - } - - private readonly cli = MatrixClientPeg.get(); - private activeChannel: ClientWidgetApi; - private _roomId: string; - private _participants: IJitsiParticipant[]; - private _audioMuted: boolean; - private _videoMuted: boolean; - - public get roomId(): string { - return this._roomId; - } - - public get participants(): IJitsiParticipant[] { - return this._participants; - } - - public get audioMuted(): boolean { - return this._audioMuted; - } - - public get videoMuted(): boolean { - return this._videoMuted; - } - - public connect = async (roomId: string) => { - if (this.activeChannel) await this.disconnect(); - - const jitsi = getVoiceChannel(roomId); - if (!jitsi) throw new Error(`No voice channel in room ${roomId}`); - - const messaging = WidgetMessagingStore.instance.getMessagingForUid(WidgetUtils.getWidgetUid(jitsi)); - if (!messaging) throw new Error(`Failed to bind voice channel in room ${roomId}`); - - this.activeChannel = messaging; - this._roomId = roomId; - - // Participant data and mute state will come down the event pipeline very quickly, - // so prepare in advance - messaging.on(`action:${ElementWidgetActions.CallParticipants}`, this.onParticipants); - messaging.on(`action:${ElementWidgetActions.MuteAudio}`, this.onMuteAudio); - messaging.on(`action:${ElementWidgetActions.UnmuteAudio}`, this.onUnmuteAudio); - messaging.on(`action:${ElementWidgetActions.MuteVideo}`, this.onMuteVideo); - messaging.on(`action:${ElementWidgetActions.UnmuteVideo}`, this.onUnmuteVideo); - - // Actually perform the join - const waitForJoin = this.waitForAction(ElementWidgetActions.JoinCall); - messaging.transport.send(ElementWidgetActions.JoinCall, {}); - try { - await waitForJoin; - } catch (e) { - // If it timed out, clean up our advance preparations - this.activeChannel = null; - this._roomId = null; - - messaging.off(`action:${ElementWidgetActions.CallParticipants}`, this.onParticipants); - messaging.off(`action:${ElementWidgetActions.MuteAudio}`, this.onMuteAudio); - messaging.off(`action:${ElementWidgetActions.UnmuteAudio}`, this.onUnmuteAudio); - messaging.off(`action:${ElementWidgetActions.MuteVideo}`, this.onMuteVideo); - messaging.off(`action:${ElementWidgetActions.UnmuteVideo}`, this.onUnmuteVideo); - - throw e; - } - - messaging.once(`action:${ElementWidgetActions.HangupCall}`, this.onHangup); - - this.emit(VoiceChannelEvent.Connect); - - // Tell others that we're connected, by adding our device to room state - await this.updateDevices(devices => Array.from(new Set(devices).add(this.cli.getDeviceId()))); - }; - - public disconnect = async () => { - this.assertConnected(); - - const waitForHangup = this.waitForAction(ElementWidgetActions.HangupCall); - this.activeChannel.transport.send(ElementWidgetActions.HangupCall, {}); - await waitForHangup; - - // onHangup cleans up for us - }; - - public muteAudio = async () => { - this.assertConnected(); - - const waitForMute = this.waitForAction(ElementWidgetActions.MuteAudio); - this.activeChannel.transport.send(ElementWidgetActions.MuteAudio, {}); - await waitForMute; - }; - - public unmuteAudio = async () => { - this.assertConnected(); - - const waitForUnmute = this.waitForAction(ElementWidgetActions.UnmuteAudio); - this.activeChannel.transport.send(ElementWidgetActions.UnmuteAudio, {}); - await waitForUnmute; - }; - - public muteVideo = async () => { - this.assertConnected(); - - const waitForMute = this.waitForAction(ElementWidgetActions.MuteVideo); - this.activeChannel.transport.send(ElementWidgetActions.MuteVideo, {}); - await waitForMute; - }; - - public unmuteVideo = async () => { - this.assertConnected(); - - const waitForUnmute = this.waitForAction(ElementWidgetActions.UnmuteVideo); - this.activeChannel.transport.send(ElementWidgetActions.UnmuteVideo, {}); - await waitForUnmute; - }; - - private assertConnected = () => { - if (!this.activeChannel) throw new Error("Not connected to any voice channel"); - }; - - private waitForAction = async (action: ElementWidgetActions) => { - const wait = new Promise(resolve => - this.activeChannel.once(`action:${action}`, (ev: CustomEvent) => { - this.ack(ev); - resolve(); - }), - ); - if (await timeout(wait, false, VoiceChannelStore.TIMEOUT) === false) { - throw new Error("Communication with voice channel timed out"); - } - }; - - private ack = (ev: CustomEvent) => { - this.activeChannel.transport.reply(ev.detail, {}); - }; - - private updateDevices = async (fn: (devices: string[]) => string[]) => { - if (!this.roomId) { - logger.error("Tried to update devices while disconnected"); - return; - } - - const devices = this.cli.getRoom(this.roomId) - .currentState.getStateEvents(VOICE_CHANNEL_MEMBER, this.cli.getUserId()) - ?.getContent()?.devices ?? []; - - await this.cli.sendStateEvent( - this.roomId, VOICE_CHANNEL_MEMBER, { devices: fn(devices) }, this.cli.getUserId(), - ); - }; - - private onHangup = async (ev: CustomEvent) => { - this.ack(ev); - - this.activeChannel.off(`action:${ElementWidgetActions.CallParticipants}`, this.onParticipants); - this.activeChannel.off(`action:${ElementWidgetActions.MuteAudio}`, this.onMuteAudio); - this.activeChannel.off(`action:${ElementWidgetActions.UnmuteAudio}`, this.onUnmuteAudio); - this.activeChannel.off(`action:${ElementWidgetActions.MuteVideo}`, this.onMuteVideo); - this.activeChannel.off(`action:${ElementWidgetActions.UnmuteVideo}`, this.onUnmuteVideo); - - this.activeChannel = null; - this._participants = null; - this._audioMuted = null; - this._videoMuted = null; - - try { - // Tell others that we're disconnected, by removing our device from room state - await this.updateDevices(devices => { - const devicesSet = new Set(devices); - devicesSet.delete(this.cli.getDeviceId()); - return Array.from(devicesSet); - }); - } finally { - // Save this for last, since updateDevices needs the room ID - this._roomId = null; - this.emit(VoiceChannelEvent.Disconnect); - } - }; - - private onParticipants = (ev: CustomEvent) => { - this._participants = ev.detail.data.participants as IJitsiParticipant[]; - this.emit(VoiceChannelEvent.Participants, ev.detail.data.participants); - this.ack(ev); - }; - - private onMuteAudio = (ev: CustomEvent) => { - this._audioMuted = true; - this.emit(VoiceChannelEvent.MuteAudio); - this.ack(ev); - }; - - private onUnmuteAudio = (ev: CustomEvent) => { - this._audioMuted = false; - this.emit(VoiceChannelEvent.UnmuteAudio); - this.ack(ev); - }; - - private onMuteVideo = (ev: CustomEvent) => { - this._videoMuted = true; - this.emit(VoiceChannelEvent.MuteVideo); - this.ack(ev); - }; - - private onUnmuteVideo = (ev: CustomEvent) => { - this._videoMuted = false; - this.emit(VoiceChannelEvent.UnmuteVideo); - this.ack(ev); - }; -} diff --git a/src/utils/VoiceChannelUtils.ts b/src/utils/VideoChannelUtils.ts similarity index 72% rename from src/utils/VoiceChannelUtils.ts rename to src/utils/VideoChannelUtils.ts index bee6388ed4..d989324ed4 100644 --- a/src/utils/VoiceChannelUtils.ts +++ b/src/utils/VideoChannelUtils.ts @@ -22,26 +22,26 @@ import WidgetStore, { IApp } from "../stores/WidgetStore"; import { WidgetType } from "../widgets/WidgetType"; import WidgetUtils from "./WidgetUtils"; -export const VOICE_CHANNEL = "io.element.voice"; -export const VOICE_CHANNEL_MEMBER = "io.element.voice.member"; +export const VIDEO_CHANNEL = "io.element.video"; +export const VIDEO_CHANNEL_MEMBER = "io.element.video.member"; -export interface IVoiceChannelMemberContent { +export interface IVideoChannelMemberContent { // Connected device IDs devices: string[]; } -export const getVoiceChannel = (roomId: string): IApp => { +export const getVideoChannel = (roomId: string): IApp => { const apps = WidgetStore.instance.getApps(roomId); - return apps.find(app => WidgetType.JITSI.matches(app.type) && app.id === VOICE_CHANNEL); + return apps.find(app => WidgetType.JITSI.matches(app.type) && app.id === VIDEO_CHANNEL); }; -export const addVoiceChannel = async (roomId: string, roomName: string) => { - await WidgetUtils.addJitsiWidget(roomId, CallType.Voice, "Voice channel", VOICE_CHANNEL, roomName); +export const addVideoChannel = async (roomId: string, roomName: string) => { + await WidgetUtils.addJitsiWidget(roomId, CallType.Video, "Video channel", VIDEO_CHANNEL, roomName); }; export const getConnectedMembers = (state: RoomState): RoomMember[] => - state.getStateEvents(VOICE_CHANNEL_MEMBER) + state.getStateEvents(VIDEO_CHANNEL_MEMBER) // Must have a device connected and still be joined to the room - .filter(e => e.getContent().devices?.length) + .filter(e => e.getContent().devices?.length) .map(e => state.getMember(e.getStateKey())) .filter(member => member.membership === "join"); diff --git a/src/utils/WidgetUtils.ts b/src/utils/WidgetUtils.ts index 1515b77b2c..8537e03583 100644 --- a/src/utils/WidgetUtils.ts +++ b/src/utils/WidgetUtils.ts @@ -36,6 +36,7 @@ import { Jitsi } from "../widgets/Jitsi"; import { objectClone } from "./objects"; import { _t } from "../languageHandler"; import { IApp } from "../stores/WidgetStore"; +import { VIDEO_CHANNEL } from "./VideoChannelUtils"; // How long we wait for the state event echo to come back from the server // before waitFor[Room/User]Widget rejects its promise @@ -469,6 +470,7 @@ export default class WidgetUtils { conferenceId: confId, roomName: oobRoomName ?? MatrixClientPeg.get().getRoom(roomId)?.name, isAudioOnly: type === CallType.Voice, + isVideoChannel: widgetId === VIDEO_CHANNEL, domain, auth, }); @@ -515,6 +517,7 @@ export default class WidgetUtils { 'conferenceDomain=$domain', 'conferenceId=$conferenceId', 'isAudioOnly=$isAudioOnly', + 'isVideoChannel=$isVideoChannel', 'displayName=$matrix_display_name', 'avatarUrl=$matrix_avatar_url', 'userId=$matrix_user_id', diff --git a/src/utils/space.tsx b/src/utils/space.tsx index 442a411af8..9394f56c74 100644 --- a/src/utils/space.tsx +++ b/src/utils/space.tsx @@ -16,6 +16,7 @@ limitations under the License. import React from "react"; import { Room } from "matrix-js-sdk/src/models/room"; +import { RoomType } from "matrix-js-sdk/src/@types/event"; import { EventType } from "matrix-js-sdk/src/@types/event"; import { JoinRule } from "matrix-js-sdk/src/@types/partials"; @@ -92,12 +93,13 @@ export const showAddExistingRooms = (space: Room): void => { ); }; -export const showCreateNewRoom = async (space: Room): Promise => { +export const showCreateNewRoom = async (space: Room, type?: RoomType): Promise => { const modal = Modal.createTrackedDialog<[boolean, IOpts]>( "Space Landing", "Create Room", CreateRoomDialog, { + type, defaultPublic: space.getJoinRule() === JoinRule.Public, parentSpace: space, }, diff --git a/test/components/views/rooms/RoomTile-test.tsx b/test/components/views/rooms/RoomTile-test.tsx index 4e960afe46..b0a98c8b3c 100644 --- a/test/components/views/rooms/RoomTile-test.tsx +++ b/test/components/views/rooms/RoomTile-test.tsx @@ -28,21 +28,19 @@ import { mkRoom, mkEvent, } from "../../../test-utils"; -import { stubVoiceChannelStore } from "../../../test-utils/voice"; +import { stubVideoChannelStore } from "../../../test-utils/video"; import RoomTile from "../../../../src/components/views/rooms/RoomTile"; -import MemberAvatar from "../../../../src/components/views/avatars/MemberAvatar"; import SettingsStore from "../../../../src/settings/SettingsStore"; -import VoiceChannelStore, { VoiceChannelEvent } from "../../../../src/stores/VoiceChannelStore"; import { DefaultTagID } from "../../../../src/stores/room-list/models"; import DMRoomMap from "../../../../src/utils/DMRoomMap"; -import { VOICE_CHANNEL_MEMBER } from "../../../../src/utils/VoiceChannelUtils"; +import { VIDEO_CHANNEL_MEMBER } from "../../../../src/utils/VideoChannelUtils"; import { MatrixClientPeg } from "../../../../src/MatrixClientPeg"; import PlatformPeg from "../../../../src/PlatformPeg"; import BasePlatform from "../../../../src/BasePlatform"; -const mkVoiceChannelMember = (userId: string, devices: string[]): MatrixEvent => mkEvent({ +const mkVideoChannelMember = (userId: string, devices: string[]): MatrixEvent => mkEvent({ event: true, - type: VOICE_CHANNEL_MEMBER, + type: VIDEO_CHANNEL_MEMBER, room: "!1:example.org", user: userId, skey: userId, @@ -59,36 +57,25 @@ describe("RoomTile", () => { beforeEach(() => { const realGetValue = SettingsStore.getValue; SettingsStore.getValue = (name: string, roomId?: string): T => { - if (name === "feature_voice_rooms") { + if (name === "feature_video_rooms") { return true as unknown as T; } return realGetValue(name, roomId); }; stubClient(); - stubVoiceChannelStore(); - DMRoomMap.makeShared(); - cli = mocked(MatrixClientPeg.get()); - store = VoiceChannelStore.instance; + store = stubVideoChannelStore(); + DMRoomMap.makeShared(); }); afterEach(() => jest.clearAllMocks()); - describe("voice rooms", () => { + describe("video rooms", () => { const room = mkRoom(cli, "!1:example.org"); room.isCallRoom.mockReturnValue(true); - it("tracks connection state", async () => { - // Insert a breakpoint in the connect method, so we can see the intermediate connecting state - let continueJoin; - const breakpoint = new Promise(resolve => continueJoin = resolve); - const realConnect = store.connect; - store.connect = async () => { - await breakpoint; - await realConnect(); - }; - + it("tracks connection state", () => { const tile = mount( { tag={DefaultTagID.Untagged} />, ); - expect(tile.find(".mx_RoomTile_voiceIndicator").text()).toEqual("Voice room"); + expect(tile.find(".mx_RoomTile_videoIndicator").text()).toEqual("Video"); - act(() => { tile.simulate("click"); }); + act(() => { store.connect("!1:example.org"); }); tile.update(); - expect(tile.find(".mx_RoomTile_voiceIndicator").text()).toEqual("Connecting..."); - - // Now we confirm the join and wait for the store to update - const waitForConnect = new Promise(resolve => - store.once(VoiceChannelEvent.Connect, resolve), - ); - continueJoin(); - await waitForConnect; - // Wait exactly 2 ticks for the room tile to update - await Promise.resolve(); - await Promise.resolve(); + expect(tile.find(".mx_RoomTile_videoIndicator").text()).toEqual("Connected"); + act(() => { store.disconnect(); }); tile.update(); - expect(tile.find(".mx_RoomTile_voiceIndicator").text()).toEqual("Connected"); - - await store.disconnect(); - - tile.update(); - expect(tile.find(".mx_RoomTile_voiceIndicator").text()).toEqual("Voice room"); + expect(tile.find(".mx_RoomTile_videoIndicator").text()).toEqual("Video"); }); - it("displays connected members", async () => { + it("displays connected members", () => { mocked(room.currentState).getStateEvents.mockImplementation(mockStateEventImplementation([ // A user connected from 2 devices - mkVoiceChannelMember("@alice:example.org", ["device 1", "device 2"]), + mkVideoChannelMember("@alice:example.org", ["device 1", "device 2"]), // A disconnected user - mkVoiceChannelMember("@bob:example.org", []), + mkVideoChannelMember("@bob:example.org", []), // A user that claims to have a connected device, but has left the room - mkVoiceChannelMember("@chris:example.org", ["device 1"]), + mkVideoChannelMember("@chris:example.org", ["device 1"]), ])); mocked(room.currentState).getMember.mockImplementation(userId => ({ @@ -152,9 +125,8 @@ describe("RoomTile", () => { ); // Only Alice should display as connected - const avatar = tile.find(MemberAvatar); - expect(avatar.length).toEqual(1); - expect(avatar.props().member.userId).toEqual("@alice:example.org"); + const participants = tile.find(".mx_RoomTile_videoParticipants"); + expect(participants.text()).toEqual("1"); }); }); }); diff --git a/test/components/views/voip/VoiceChannelRadio-test.tsx b/test/components/views/voip/VoiceChannelRadio-test.tsx deleted file mode 100644 index b42ac0e089..0000000000 --- a/test/components/views/voip/VoiceChannelRadio-test.tsx +++ /dev/null @@ -1,107 +0,0 @@ -/* -Copyright 2022 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 { mount } from "enzyme"; -import { act } from "react-dom/test-utils"; -import { mocked } from "jest-mock"; - -import "../../../skinned-sdk"; -import { stubClient, mkStubRoom, wrapInMatrixClientContext } from "../../../test-utils"; -import { stubVoiceChannelStore } from "../../../test-utils/voice"; -import _VoiceChannelRadio from "../../../../src/components/views/voip/VoiceChannelRadio"; -import VoiceChannelStore from "../../../../src/stores/VoiceChannelStore"; -import DMRoomMap from "../../../../src/utils/DMRoomMap"; -import { MatrixClientPeg } from "../../../../src/MatrixClientPeg"; - -const VoiceChannelRadio = wrapInMatrixClientContext(_VoiceChannelRadio); - -describe("VoiceChannelRadio", () => { - const cli = mocked(MatrixClientPeg.get()); - const room = mkStubRoom("!1:example.org", "voice channel", cli); - room.isCallRoom = () => true; - - beforeEach(() => { - stubClient(); - stubVoiceChannelStore(); - DMRoomMap.makeShared(); - }); - - it("shows when connecting voice", async () => { - const radio = mount(); - expect(radio.children().children().exists()).toEqual(false); - - act(() => { VoiceChannelStore.instance.connect("!1:example.org"); }); - radio.update(); - expect(radio.children().children().exists()).toEqual(true); - }); - - it("hides when disconnecting voice", () => { - VoiceChannelStore.instance.connect("!1:example.org"); - const radio = mount(); - expect(radio.children().children().exists()).toEqual(true); - - act(() => { VoiceChannelStore.instance.disconnect(); }); - radio.update(); - expect(radio.children().children().exists()).toEqual(false); - }); - - describe("disconnect button", () => { - it("works", () => { - VoiceChannelStore.instance.connect("!1:example.org"); - const radio = mount(); - - act(() => { - radio.find("AccessibleButton.mx_VoiceChannelRadio_disconnectButton").simulate("click"); - }); - expect(VoiceChannelStore.instance.disconnect).toHaveBeenCalled(); - }); - }); - - describe("video button", () => { - it("works", () => { - VoiceChannelStore.instance.connect("!1:example.org"); - const radio = mount(); - - act(() => { - radio.find("AccessibleButton.mx_VoiceChannelRadio_videoButton").simulate("click"); - }); - expect(VoiceChannelStore.instance.unmuteVideo).toHaveBeenCalled(); - - act(() => { - radio.find("AccessibleButton.mx_VoiceChannelRadio_videoButton").simulate("click"); - }); - expect(VoiceChannelStore.instance.muteVideo).toHaveBeenCalled(); - }); - }); - - describe("audio button", () => { - it("works", () => { - VoiceChannelStore.instance.connect("!1:example.org"); - const radio = mount(); - - act(() => { - radio.find("AccessibleButton.mx_VoiceChannelRadio_audioButton").simulate("click"); - }); - expect(VoiceChannelStore.instance.unmuteAudio).toHaveBeenCalled(); - - act(() => { - radio.find("AccessibleButton.mx_VoiceChannelRadio_audioButton").simulate("click"); - }); - expect(VoiceChannelStore.instance.muteAudio).toHaveBeenCalled(); - }); - }); -}); diff --git a/test/end-to-end-tests/src/usecases/create-room.ts b/test/end-to-end-tests/src/usecases/create-room.ts index 8736e785ba..b0e7738fb4 100644 --- a/test/end-to-end-tests/src/usecases/create-room.ts +++ b/test/end-to-end-tests/src/usecases/create-room.ts @@ -36,7 +36,7 @@ export async function createRoom(session: ElementSession, roomName: string, encr const addRoomButton = await roomsSublist.$(".mx_RoomSublist_auxButton"); await addRoomButton.click(); - const createRoomButton = await session.query('.mx_AccessibleButton[aria-label="Create new room"]'); + const createRoomButton = await session.query('.mx_AccessibleButton[aria-label="New room"]'); await createRoomButton.click(); const roomNameInput = await session.query('.mx_CreateRoomDialog_name input'); diff --git a/test/stores/VideoChannelStore-test.ts b/test/stores/VideoChannelStore-test.ts new file mode 100644 index 0000000000..e1420195c1 --- /dev/null +++ b/test/stores/VideoChannelStore-test.ts @@ -0,0 +1,83 @@ +/* +Copyright 2022 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 { ClientWidgetApi, MatrixWidgetType } from "matrix-widget-api"; + +import "../skinned-sdk"; +import { stubClient, mkRoom } from "../test-utils"; +import { MatrixClientPeg } from "../../src/MatrixClientPeg"; +import WidgetStore from "../../src/stores/WidgetStore"; +import ActiveWidgetStore from "../../src/stores/ActiveWidgetStore"; +import { WidgetMessagingStore } from "../../src/stores/widgets/WidgetMessagingStore"; +import VideoChannelStore, { VideoChannelEvent } from "../../src/stores/VideoChannelStore"; +import { VIDEO_CHANNEL } from "../../src/utils/VideoChannelUtils"; + +describe("VideoChannelStore", () => { + stubClient(); + mkRoom(MatrixClientPeg.get(), "!1:example.org"); + + const videoStore = VideoChannelStore.instance; + const widgetStore = ActiveWidgetStore.instance; + + jest.spyOn(WidgetStore.instance, "getApps").mockReturnValue([{ + id: VIDEO_CHANNEL, + eventId: "$1:example.org", + roomId: "!1:example.org", + type: MatrixWidgetType.JitsiMeet, + url: "", + name: "Video channel", + creatorUserId: "@alice:example.org", + avatar_url: null, + }]); + jest.spyOn(WidgetMessagingStore.instance, "getMessagingForUid").mockReturnValue({ + on: () => {}, + off: () => {}, + once: () => {}, + transport: { + send: () => {}, + reply: () => {}, + }, + } as unknown as ClientWidgetApi); + + beforeEach(() => { + videoStore.start(); + }); + + afterEach(() => { + videoStore.stop(); + jest.clearAllMocks(); + }); + + it("tracks connection state", async () => { + expect(videoStore.roomId).toBeFalsy(); + + const waitForConnect = new Promise(resolve => + videoStore.once(VideoChannelEvent.Connect, resolve), + ); + widgetStore.setWidgetPersistence(VIDEO_CHANNEL, "!1:example.org", true); + await waitForConnect; + + expect(videoStore.roomId).toEqual("!1:example.org"); + + const waitForDisconnect = new Promise(resolve => + videoStore.once(VideoChannelEvent.Disconnect, resolve), + ); + widgetStore.setWidgetPersistence(VIDEO_CHANNEL, "!1:example.org", false); + await waitForDisconnect; + + expect(videoStore.roomId).toBeFalsy(); + }); +}); diff --git a/test/stores/VoiceChannelStore-test.ts b/test/stores/VoiceChannelStore-test.ts deleted file mode 100644 index cf70e7314c..0000000000 --- a/test/stores/VoiceChannelStore-test.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2022 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 { ClientWidgetApi, MatrixWidgetType } from "matrix-widget-api"; - -import "../skinned-sdk"; -import { stubClient } from "../test-utils"; -import WidgetStore from "../../src/stores/WidgetStore"; -import { WidgetMessagingStore } from "../../src/stores/widgets/WidgetMessagingStore"; -import { ElementWidgetActions } from "../../src/stores/widgets/ElementWidgetActions"; -import VoiceChannelStore, { VoiceChannelEvent } from "../../src/stores/VoiceChannelStore"; -import { VOICE_CHANNEL } from "../../src/utils/VoiceChannelUtils"; - -describe("VoiceChannelStore", () => { - // Set up mocks to simulate the remote end of the widget API - let messageSent; - let messageSendMock; - let onceMock; - beforeEach(() => { - stubClient(); - let resolveMessageSent; - messageSent = new Promise(resolve => resolveMessageSent = resolve); - messageSendMock = jest.fn().mockImplementation(() => resolveMessageSent()); - onceMock = jest.fn(); - - jest.spyOn(WidgetStore.instance, "getApps").mockReturnValue([{ - id: VOICE_CHANNEL, - eventId: "$1:example.org", - roomId: "!1:example.org", - type: MatrixWidgetType.JitsiMeet, - url: "", - name: "Voice channel", - creatorUserId: "@alice:example.org", - avatar_url: null, - }]); - jest.spyOn(WidgetMessagingStore.instance, "getMessagingForUid").mockReturnValue({ - on: () => {}, - off: () => {}, - once: onceMock, - transport: { - send: messageSendMock, - reply: () => {}, - }, - } as unknown as ClientWidgetApi); - }); - - it("connects and disconnects", async () => { - const store = VoiceChannelStore.instance; - - expect(store.roomId).toBeFalsy(); - - store.connect("!1:example.org"); - // Wait for the store to contact the widget API - await messageSent; - // Then, locate the callback that will confirm the join - const [, join] = onceMock.mock.calls.find(([action]) => - action === `action:${ElementWidgetActions.JoinCall}`, - ); - // Confirm the join, and wait for the store to update - const waitForConnect = new Promise(resolve => - store.once(VoiceChannelEvent.Connect, resolve), - ); - join({ detail: {} }); - await waitForConnect; - - expect(store.roomId).toEqual("!1:example.org"); - - store.disconnect(); - // Locate the callback that will perform the hangup - const [, hangup] = onceMock.mock.calls.find(([action]) => - action === `action:${ElementWidgetActions.HangupCall}`, - ); - // Hangup and wait for the store, once again - const waitForHangup = new Promise(resolve => - store.once(VoiceChannelEvent.Disconnect, resolve), - ); - hangup({ detail: {} }); - await waitForHangup; - - expect(store.roomId).toBeFalsy(); - }); -}); diff --git a/test/test-utils/index.ts b/test/test-utils/index.ts index b14bda3cbb..0859bd976b 100644 --- a/test/test-utils/index.ts +++ b/test/test-utils/index.ts @@ -4,6 +4,6 @@ export * from './location'; export * from './platform'; export * from './room'; export * from './test-utils'; -// TODO @@TR: Export voice.ts, which currently isn't exported here because it causes all tests to depend on skinning +// TODO @@TR: Export video.ts, which currently isn't exported here because it causes all tests to depend on skinning export * from './wrappers'; export * from './utilities'; diff --git a/test/test-utils/video.ts b/test/test-utils/video.ts new file mode 100644 index 0000000000..9130945215 --- /dev/null +++ b/test/test-utils/video.ts @@ -0,0 +1,39 @@ +/* +Copyright 2022 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 VideoChannelStore, { VideoChannelEvent } from "../../src/stores/VideoChannelStore"; + +class StubVideoChannelStore extends EventEmitter { + private _roomId: string; + public get roomId(): string { return this._roomId; } + + public connect = (roomId: string) => { + this._roomId = roomId; + this.emit(VideoChannelEvent.Connect); + }; + public disconnect = () => { + this._roomId = null; + this.emit(VideoChannelEvent.Disconnect); + }; +} + +export const stubVideoChannelStore = (): StubVideoChannelStore => { + const store = new StubVideoChannelStore(); + jest.spyOn(VideoChannelStore, "instance", "get").mockReturnValue(store as unknown as VideoChannelStore); + return store; +}; diff --git a/test/test-utils/voice.ts b/test/test-utils/voice.ts deleted file mode 100644 index 962e4c6c56..0000000000 --- a/test/test-utils/voice.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2022 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 VoiceChannelStore, { VoiceChannelEvent } from "../../src/stores/VoiceChannelStore"; - -class StubVoiceChannelStore extends EventEmitter { - private _roomId: string; - public get roomId(): string { return this._roomId; } - private _audioMuted: boolean; - public get audioMuted(): boolean { return this._audioMuted; } - private _videoMuted: boolean; - public get videoMuted(): boolean { return this._videoMuted; } - - public connect = jest.fn().mockImplementation(async (roomId: string) => { - this._roomId = roomId; - this._audioMuted = true; - this._videoMuted = true; - this.emit(VoiceChannelEvent.Connect); - }); - public disconnect = jest.fn().mockImplementation(async () => { - this._roomId = null; - this.emit(VoiceChannelEvent.Disconnect); - }); - public muteAudio = jest.fn().mockImplementation(async () => { - this._audioMuted = true; - this.emit(VoiceChannelEvent.MuteAudio); - }); - public unmuteAudio = jest.fn().mockImplementation(async () => { - this._audioMuted = false; - this.emit(VoiceChannelEvent.UnmuteAudio); - }); - public muteVideo = jest.fn().mockImplementation(async () => { - this._videoMuted = true; - this.emit(VoiceChannelEvent.MuteVideo); - }); - public unmuteVideo = jest.fn().mockImplementation(async () => { - this._videoMuted = false; - this.emit(VoiceChannelEvent.UnmuteVideo); - }); -} - -export const stubVoiceChannelStore = () => { - jest.spyOn(VoiceChannelStore, "instance", "get") - .mockReturnValue(new StubVoiceChannelStore() as unknown as VoiceChannelStore); -};