/* Copyright 2021 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React, {RefObject, useContext, useRef, useState} from "react"; import {EventType} from "matrix-js-sdk/src/@types/event"; import {Room} from "matrix-js-sdk/src/models/room"; import {EventSubscription} from "fbemitter"; import MatrixClientContext from "../../contexts/MatrixClientContext"; import RoomAvatar from "../views/avatars/RoomAvatar"; import {_t} from "../../languageHandler"; import AccessibleButton from "../views/elements/AccessibleButton"; import RoomName from "../views/elements/RoomName"; import RoomTopic from "../views/elements/RoomTopic"; import InlineSpinner from "../views/elements/InlineSpinner"; import {inviteMultipleToRoom, showRoomInviteDialog} from "../../RoomInvite"; import {useRoomMembers} from "../../hooks/useRoomMembers"; import createRoom, {IOpts, Preset} from "../../createRoom"; import Field from "../views/elements/Field"; import {useEventEmitter} from "../../hooks/useEventEmitter"; import withValidation from "../views/elements/Validation"; import * as Email from "../../email"; import defaultDispatcher from "../../dispatcher/dispatcher"; import {Action} from "../../dispatcher/actions"; import ResizeNotifier from "../../utils/ResizeNotifier" import MainSplit from './MainSplit'; import ErrorBoundary from "../views/elements/ErrorBoundary"; import {ActionPayload} from "../../dispatcher/payloads"; import RightPanel from "./RightPanel"; import RightPanelStore from "../../stores/RightPanelStore"; import {RightPanelPhases} from "../../stores/RightPanelStorePhases"; import {SetRightPanelPhasePayload} from "../../dispatcher/payloads/SetRightPanelPhasePayload"; import {useStateArray} from "../../hooks/useStateArray"; import SpacePublicShare from "../views/spaces/SpacePublicShare"; import {showAddExistingRooms, showCreateNewRoom, shouldShowSpaceSettings, showSpaceSettings} from "../../utils/space"; import {showRoom, SpaceHierarchy} from "./SpaceRoomDirectory"; import MemberAvatar from "../views/avatars/MemberAvatar"; import {useStateToggle} from "../../hooks/useStateToggle"; import SpaceStore from "../../stores/SpaceStore"; import FacePile from "../views/elements/FacePile"; import {AddExistingToSpace} from "../views/dialogs/AddExistingToSpaceDialog"; import {sleep} from "../../utils/promise"; import {calculateRoomVia} from "../../utils/permalinks/Permalinks"; import {ChevronFace, ContextMenuButton, useContextMenu} from "./ContextMenu"; import IconizedContextMenu, { IconizedContextMenuOption, IconizedContextMenuOptionList, } from "../views/context_menus/IconizedContextMenu"; import AccessibleTooltipButton from "../views/elements/AccessibleTooltipButton"; interface IProps { space: Room; justCreatedOpts?: IOpts; resizeNotifier: ResizeNotifier; onJoinButtonClicked(): void; onRejectButtonClicked(): void; } interface IState { phase: Phase; showRightPanel: boolean; myMembership: string; } enum Phase { Landing, PublicCreateRooms, PublicShare, PrivateScope, PrivateInvite, PrivateCreateRooms, PrivateExistingRooms, } const RoomMemberCount = ({ room, children }) => { const members = useRoomMembers(room); const count = members.length; if (children) return children(count); return count; }; const useMyRoomMembership = (room: Room) => { const [membership, setMembership] = useState(room.getMyMembership()); useEventEmitter(room, "Room.myMembership", () => { setMembership(room.getMyMembership()); }); return membership; }; const SpaceInfo = ({ space }) => { const joinRule = space.getJoinRule(); let visibilitySection; if (joinRule === "public") { visibilitySection = { _t("Public space") } ; } else { visibilitySection = { _t("Private space") } ; } return
{ visibilitySection } { joinRule === "public" && {(count) => count > 0 ? ( { defaultDispatcher.dispatch({ action: Action.SetRightPanelPhase, phase: RightPanelPhases.RoomMemberList, refireParams: { space }, }); }} > { _t("%(count)s members", { count }) } ) : null} }
}; const SpacePreview = ({ space, onJoinButtonClicked, onRejectButtonClicked }) => { const cli = useContext(MatrixClientContext); const myMembership = useMyRoomMembership(space); const [busy, setBusy] = useState(false); let inviterSection; let joinButtons; if (myMembership === "invite") { const inviteSender = space.getMember(cli.getUserId())?.events.member?.getSender(); const inviter = inviteSender && space.getMember(inviteSender); if (inviteSender) { inviterSection =
{ _t(" invites you", {}, { inviter: () => { inviter.name || inviteSender }, }) }
{ inviter ?
{ inviteSender }
: null }
; } joinButtons = <> { setBusy(true); onRejectButtonClicked(); }} > { _t("Reject") } { setBusy(true); onJoinButtonClicked(); }} > { _t("Accept") } ; } else { joinButtons = ( { setBusy(true); onJoinButtonClicked(); }} > { _t("Join") } ) } if (busy) { joinButtons = ; } return
{ inviterSection }

{(topic, ref) =>
{ topic }
}
{ space.getJoinRule() === "public" && }
{ joinButtons }
; }; const SpaceLandingAddButton = ({ space, onNewRoomAdded }) => { const cli = useContext(MatrixClientContext); const [menuDisplayed, handle, openMenu, closeMenu] = useContextMenu(); let contextMenu; if (menuDisplayed) { const rect = handle.current.getBoundingClientRect(); contextMenu = { e.preventDefault(); e.stopPropagation(); closeMenu(); if (await showCreateNewRoom(cli, space)) { onNewRoomAdded(); } }} /> { e.preventDefault(); e.stopPropagation(); closeMenu(); const [added] = await showAddExistingRooms(cli, space); if (added) { onNewRoomAdded(); } }} /> ; } return <> { _t("Add") } { contextMenu } ; }; const SpaceLanding = ({ space }) => { const cli = useContext(MatrixClientContext); const myMembership = useMyRoomMembership(space); const userId = cli.getUserId(); let inviteButton; if (myMembership === "join" && space.canInvite(userId)) { inviteButton = ( { showRoomInviteDialog(space.roomId); }} > { _t("Invite") } ); } const canAddRooms = myMembership === "join" && space.currentState.maySendStateEvent(EventType.SpaceChild, userId); const [refreshToken, forceUpdate] = useStateToggle(false); let addRoomButton; if (canAddRooms) { addRoomButton = ; } let settingsButton; if (shouldShowSpaceSettings(cli, space)) { settingsButton = { showSpaceSettings(cli, space); }} title={_t("Settings")} />; } const onMembersClick = () => { defaultDispatcher.dispatch({ action: Action.SetRightPanelPhase, phase: RightPanelPhases.RoomMemberList, refireParams: { space }, }); }; return
{(name) => { const tags = { name: () =>

{ name }

}; return _t("Welcome to ", {}, tags) as JSX.Element; }}
{ inviteButton } { settingsButton }

; }; const SpaceSetupFirstRooms = ({ space, title, description, onFinished }) => { const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const numFields = 3; const placeholders = [_t("General"), _t("Random"), _t("Support")]; // TODO vary default prefills for "Just Me" spaces const [roomNames, setRoomName] = useStateArray(numFields, [_t("General"), _t("Random"), ""]); const fields = new Array(numFields).fill(0).map((_, i) => { const name = "roomName" + i; return setRoomName(i, ev.target.value)} autoFocus={i === 2} />; }); const onNextClick = async () => { setError(""); setBusy(true); try { await Promise.all(roomNames.map(name => name.trim()).filter(Boolean).map(name => { return createRoom({ createOpts: { preset: space.getJoinRule() === "public" ? Preset.PublicChat : Preset.PrivateChat, name, }, spinner: false, encryption: false, andView: false, inlineErrors: true, parentSpace: space, }); })); onFinished(); } catch (e) { console.error("Failed to create initial space rooms", e); setError(_t("Failed to create initial space rooms")); } setBusy(false); }; let onClick = onFinished; let buttonLabel = _t("Skip for now"); if (roomNames.some(name => name.trim())) { onClick = onNextClick; buttonLabel = busy ? _t("Creating rooms...") : _t("Continue"); } return

{ title }

{ description }
{ error &&
{ error }
} { fields }
{ buttonLabel }
; }; const SpaceAddExistingRooms = ({ space, onFinished }) => { const [selectedToAdd, setSelectedToAdd] = useState(new Set()); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); let onClick = onFinished; let buttonLabel = _t("Skip for now"); if (selectedToAdd.size > 0) { onClick = async () => { setBusy(true); for (const room of selectedToAdd) { const via = calculateRoomVia(room); try { await SpaceStore.instance.addRoomToSpace(space, room.roomId, via).catch(async e => { if (e.errcode === "M_LIMIT_EXCEEDED") { await sleep(e.data.retry_after_ms); return SpaceStore.instance.addRoomToSpace(space, room.roomId, via); // retry } throw e; }); } catch (e) { console.error("Failed to add rooms to space", e); setError(_t("Failed to add rooms to space")); break; } } setBusy(false); }; buttonLabel = busy ? _t("Adding...") : _t("Add"); } return

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

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

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

{ _t("It's just you at the moment, it will be even better with others.") }
{ _t("Go to my first room") }
; }; const SpaceSetupPrivateScope = ({ space, onFinished }) => { return

{ _t("Who are you working with?") }

{ _t("Make sure the right people have access to %(name)s", { name: space.name }) }
{ onFinished(false) }} >

{ _t("Just me") }

{ _t("A private space to organise your rooms") }
{ onFinished(true) }} >

{ _t("Me and my teammates") }

{ _t("A private space for you and your teammates") }
; }; const validateEmailRules = withValidation({ rules: [{ key: "email", test: ({ value }) => !value || Email.looksValid(value), invalid: () => _t("Doesn't look like a valid email address"), }], }); const SpaceSetupPrivateInvite = ({ space, onFinished }) => { const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const numFields = 3; const fieldRefs: RefObject[] = [useRef(), useRef(), useRef()]; const [emailAddresses, setEmailAddress] = useStateArray(numFields, ""); const fields = new Array(numFields).fill(0).map((_, i) => { const name = "emailAddress" + i; return setEmailAddress(i, ev.target.value)} ref={fieldRefs[i]} onValidate={validateEmailRules} autoFocus={i === 0} />; }); const onNextClick = async () => { setError(""); for (let i = 0; i < fieldRefs.length; i++) { const fieldRef = fieldRefs[i]; const valid = await fieldRef.current.validate({ allowEmpty: true }); if (valid === false) { // true/null are allowed fieldRef.current.focus(); fieldRef.current.validate({ allowEmpty: true, focused: true }); return; } } setBusy(true); const targetIds = emailAddresses.map(name => name.trim()).filter(Boolean); try { const result = await inviteMultipleToRoom(space.roomId, targetIds); const failedUsers = Object.keys(result.states).filter(a => result.states[a] === "error"); if (failedUsers.length > 0) { console.log("Failed to invite users to space: ", result); setError(_t("Failed to invite the following users to your space: %(csvUsers)s", { csvUsers: failedUsers.join(", "), })); } else { onFinished(); } } catch (err) { console.error("Failed to invite users to space: ", err); setError(_t("We couldn't invite those users. Please check the users you want to invite and try again.")); } setBusy(false); }; let onClick = onFinished; let buttonLabel = _t("Skip for now"); if (emailAddresses.some(name => name.trim())) { onClick = onNextClick; buttonLabel = busy ? _t("Inviting...") : _t("Continue") } return

{ _t("Invite your teammates") }

{ _t("Make sure the right people have access. You can invite more later.") }
{ error &&
{ error }
} { fields }
showRoomInviteDialog(space.roomId)} > { _t("Invite by username") }
{ buttonLabel }
; }; export default class SpaceRoomView extends React.PureComponent { static contextType = MatrixClientContext; private readonly creator: string; private readonly dispatcherRef: string; private readonly rightPanelStoreToken: EventSubscription; constructor(props, context) { super(props, context); let phase = Phase.Landing; this.creator = this.props.space.currentState.getStateEvents(EventType.RoomCreate, "")?.getSender(); const showSetup = this.props.justCreatedOpts && this.context.getUserId() === this.creator; if (showSetup) { phase = this.props.justCreatedOpts.createOpts.preset === Preset.PublicChat ? Phase.PublicCreateRooms : Phase.PrivateScope; } this.state = { phase, showRightPanel: RightPanelStore.getSharedInstance().isOpenForRoom, myMembership: this.props.space.getMyMembership(), }; this.dispatcherRef = defaultDispatcher.register(this.onAction); this.rightPanelStoreToken = RightPanelStore.getSharedInstance().addListener(this.onRightPanelStoreUpdate); this.context.on("Room.myMembership", this.onMyMembership); } componentWillUnmount() { defaultDispatcher.unregister(this.dispatcherRef); this.rightPanelStoreToken.remove(); this.context.off("Room.myMembership", this.onMyMembership); } private onMyMembership = (room: Room, myMembership: string) => { if (room.roomId === this.props.space.roomId) { this.setState({ myMembership }); } }; private onRightPanelStoreUpdate = () => { this.setState({ showRightPanel: RightPanelStore.getSharedInstance().isOpenForRoom, }); }; private onAction = (payload: ActionPayload) => { if (payload.action !== Action.ViewUser && payload.action !== "view_3pid_invite") return; if (payload.action === Action.ViewUser && payload.member) { defaultDispatcher.dispatch({ action: Action.SetRightPanelPhase, phase: RightPanelPhases.SpaceMemberInfo, refireParams: { space: this.props.space, member: payload.member, }, }); } else if (payload.action === "view_3pid_invite" && payload.event) { defaultDispatcher.dispatch({ action: Action.SetRightPanelPhase, phase: RightPanelPhases.Space3pidMemberInfo, refireParams: { space: this.props.space, event: payload.event, }, }); } else { defaultDispatcher.dispatch({ action: Action.SetRightPanelPhase, phase: RightPanelPhases.SpaceMemberList, refireParams: { space: this.props.space }, }); } }; private goToFirstRoom = async () => { // TODO actually go to the first room const childRooms = SpaceStore.instance.getChildRooms(this.props.space.roomId); if (childRooms.length) { const room = childRooms[0]; defaultDispatcher.dispatch({ action: "view_room", room_id: room.roomId, }); return; } let suggestedRooms = SpaceStore.instance.suggestedRooms; if (SpaceStore.instance.activeSpace !== this.props.space) { // the space store has the suggested rooms loaded for a different space, fetch the right ones suggestedRooms = (await SpaceStore.instance.fetchSuggestedRooms(this.props.space, 1)).rooms; } if (suggestedRooms.length) { const room = suggestedRooms[0]; defaultDispatcher.dispatch({ action: "view_room", room_id: room.room_id, oobData: { avatarUrl: room.avatar_url, name: room.name || room.canonical_alias || room.aliases.pop() || _t("Empty room"), }, }); return; } this.setState({ phase: Phase.Landing }); }; private renderBody() { switch (this.state.phase) { case Phase.Landing: if (this.state.myMembership === "join") { return ; } else { return ; } case Phase.PublicCreateRooms: return this.setState({ phase: Phase.PublicShare })} />; case Phase.PublicShare: return ; case Phase.PrivateScope: return { this.setState({ phase: invite ? Phase.PrivateInvite : Phase.PrivateExistingRooms }); }} />; case Phase.PrivateInvite: return this.setState({ phase: Phase.PrivateCreateRooms })} />; case Phase.PrivateCreateRooms: return this.setState({ phase: Phase.Landing })} />; case Phase.PrivateExistingRooms: return this.setState({ phase: Phase.Landing })} />; } } render() { const rightPanel = this.state.showRightPanel && this.state.phase === Phase.Landing ? : null; return
{ this.renderBody() }
; } }