Merge branch 'develop' of github.com:matrix-org/matrix-react-sdk into t3chguy/feat/modal-widgets

 Conflicts:
	src/@types/global.d.ts
	src/FromWidgetPostMessageApi.js
	src/WidgetMessaging.js
	src/widgets/WidgetApi.ts
This commit is contained in:
Michael Telatynski 2020-10-19 19:46:07 +01:00
commit 00b1a03a3e
171 changed files with 5309 additions and 4610 deletions

View file

@ -23,7 +23,7 @@ import {Action} from "../../../dispatcher/actions";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import BaseAvatar from "./BaseAvatar";
interface IProps {
interface IProps extends Omit<React.ComponentProps<typeof BaseAvatar>, "name" | "idName" | "url"> {
member: RoomMember;
fallbackUserId?: string;
width: number;

View file

@ -22,6 +22,7 @@ import ImageView from '../elements/ImageView';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import Modal from '../../../Modal';
import * as Avatar from '../../../Avatar';
import {ResizeMethod} from "../../../Avatar";
interface IProps {
// Room may be left unset here, but if it is,
@ -32,7 +33,7 @@ interface IProps {
oobData?: any;
width?: number;
height?: number;
resizeMethod?: string;
resizeMethod?: ResizeMethod;
viewAvatarOnClick?: boolean;
}

View file

@ -1,304 +0,0 @@
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {createRef} from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import classnames from 'classnames';
import { Key } from '../../../Keyboard';
import { _t } from '../../../languageHandler';
import { SAFE_LOCALPART_REGEX } from '../../../Registration';
// The amount of time to wait for further changes to the input username before
// sending a request to the server
const USERNAME_CHECK_DEBOUNCE_MS = 250;
/*
* Prompt the user to set a display name.
*
* On success, `onFinished(true, newDisplayName)` is called.
*/
export default class SetMxIdDialog extends React.Component {
static propTypes = {
onFinished: PropTypes.func.isRequired,
// Called when the user requests to register with a different homeserver
onDifferentServerClicked: PropTypes.func.isRequired,
// Called if the user wants to switch to login instead
onLoginClick: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this._input_value = createRef();
this._uiAuth = createRef();
this.state = {
// The entered username
username: '',
// Indicate ongoing work on the username
usernameBusy: false,
// Indicate error with username
usernameError: '',
// Assume the homeserver supports username checking until "M_UNRECOGNIZED"
usernameCheckSupport: true,
// Whether the auth UI is currently being used
doingUIAuth: false,
// Indicate error with auth
authError: '',
};
}
componentDidMount() {
this._input_value.current.select();
this._matrixClient = MatrixClientPeg.get();
}
onValueChange = ev => {
this.setState({
username: ev.target.value,
usernameBusy: true,
usernameError: '',
}, () => {
if (!this.state.username || !this.state.usernameCheckSupport) {
this.setState({
usernameBusy: false,
});
return;
}
// Debounce the username check to limit number of requests sent
if (this._usernameCheckTimeout) {
clearTimeout(this._usernameCheckTimeout);
}
this._usernameCheckTimeout = setTimeout(() => {
this._doUsernameCheck().finally(() => {
this.setState({
usernameBusy: false,
});
});
}, USERNAME_CHECK_DEBOUNCE_MS);
});
};
onKeyUp = ev => {
if (ev.key === Key.ENTER) {
this.onSubmit();
}
};
onSubmit = ev => {
if (this._uiAuth.current) {
this._uiAuth.current.tryContinue();
}
this.setState({
doingUIAuth: true,
});
};
_doUsernameCheck() {
// We do a quick check ahead of the username availability API to ensure the
// user ID roughly looks okay from a Matrix perspective.
if (!SAFE_LOCALPART_REGEX.test(this.state.username)) {
this.setState({
usernameError: _t("A username can only contain lower case letters, numbers and '=_-./'"),
});
return Promise.reject();
}
// Check if username is available
return this._matrixClient.isUsernameAvailable(this.state.username).then(
(isAvailable) => {
if (isAvailable) {
this.setState({usernameError: ''});
}
},
(err) => {
// Indicate whether the homeserver supports username checking
const newState = {
usernameCheckSupport: err.errcode !== "M_UNRECOGNIZED",
};
console.error('Error whilst checking username availability: ', err);
switch (err.errcode) {
case "M_USER_IN_USE":
newState.usernameError = _t('Username not available');
break;
case "M_INVALID_USERNAME":
newState.usernameError = _t(
'Username invalid: %(errMessage)s',
{ errMessage: err.message},
);
break;
case "M_UNRECOGNIZED":
// This homeserver doesn't support username checking, assume it's
// fine and rely on the error appearing in registration step.
newState.usernameError = '';
break;
case undefined:
newState.usernameError = _t('Something went wrong!');
break;
default:
newState.usernameError = _t(
'An error occurred: %(error_string)s',
{ error_string: err.message },
);
break;
}
this.setState(newState);
},
);
}
_generatePassword() {
return Math.random().toString(36).slice(2);
}
_makeRegisterRequest = auth => {
// Not upgrading - changing mxids
const guestAccessToken = null;
if (!this._generatedPassword) {
this._generatedPassword = this._generatePassword();
}
return this._matrixClient.register(
this.state.username,
this._generatedPassword,
undefined, // session id: included in the auth dict already
auth,
{},
guestAccessToken,
);
};
_onUIAuthFinished = (success, response) => {
this.setState({
doingUIAuth: false,
});
if (!success) {
this.setState({ authError: response.message });
return;
}
this.props.onFinished(true, {
userId: response.user_id,
deviceId: response.device_id,
homeserverUrl: this._matrixClient.getHomeserverUrl(),
identityServerUrl: this._matrixClient.getIdentityServerUrl(),
accessToken: response.access_token,
password: this._generatedPassword,
});
};
render() {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
const InteractiveAuth = sdk.getComponent('structures.InteractiveAuth');
let auth;
if (this.state.doingUIAuth) {
auth = <InteractiveAuth
matrixClient={this._matrixClient}
makeRequest={this._makeRegisterRequest}
onAuthFinished={this._onUIAuthFinished}
inputs={{}}
poll={true}
ref={this._uiAuth}
continueIsManaged={true}
/>;
}
const inputClasses = classnames({
"mx_SetMxIdDialog_input": true,
"error": Boolean(this.state.usernameError),
});
let usernameIndicator = null;
if (this.state.usernameBusy) {
usernameIndicator = <div>{_t("Checking...")}</div>;
} else {
const usernameAvailable = this.state.username &&
this.state.usernameCheckSupport && !this.state.usernameError;
const usernameIndicatorClasses = classnames({
"error": Boolean(this.state.usernameError),
"success": usernameAvailable,
});
usernameIndicator = <div className={usernameIndicatorClasses} role="alert">
{ usernameAvailable ? _t('Username available') : this.state.usernameError }
</div>;
}
let authErrorIndicator = null;
if (this.state.authError) {
authErrorIndicator = <div className="error" role="alert">
{ this.state.authError }
</div>;
}
const canContinue = this.state.username &&
!this.state.usernameError &&
!this.state.usernameBusy;
return (
<BaseDialog className="mx_SetMxIdDialog"
onFinished={this.props.onFinished}
title={_t('To get started, please pick a username!')}
contentId='mx_Dialog_content'
>
<div className="mx_Dialog_content" id='mx_Dialog_content'>
<div className="mx_SetMxIdDialog_input_group">
<input type="text" ref={this._input_value} value={this.state.username}
autoFocus={true}
onChange={this.onValueChange}
onKeyUp={this.onKeyUp}
size="30"
className={inputClasses}
/>
</div>
{ usernameIndicator }
<p>
{ _t(
'This will be your account name on the <span></span> ' +
'homeserver, or you can pick a <a>different server</a>.',
{},
{
'span': <span>{ this.props.homeserverUrl }</span>,
'a': (sub) => <a href="#" onClick={this.props.onDifferentServerClicked}>{ sub }</a>,
},
) }
</p>
<p>
{ _t(
'If you already have a Matrix account you can <a>log in</a> instead.',
{},
{ 'a': (sub) => <a href="#" onClick={this.props.onLoginClick}>{ sub }</a> },
) }
</p>
{ auth }
{ authErrorIndicator }
</div>
<div className="mx_Dialog_buttons">
<input className="mx_Dialog_primary"
type="submit"
value={_t("Continue")}
onClick={this.onSubmit}
disabled={!canContinue}
/>
</div>
</BaseDialog>
);
}
}

View file

@ -1,128 +0,0 @@
/*
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
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 PropTypes from 'prop-types';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import Modal from '../../../Modal';
const WarmFuzzy = function(props) {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
let title = _t('You have successfully set a password!');
if (props.didSetEmail) {
title = _t('You have successfully set a password and an email address!');
}
const advice = _t('You can now return to your account after signing out, and sign in on other devices.');
let extraAdvice = null;
if (!props.didSetEmail) {
extraAdvice = _t('Remember, you can always set an email address in user settings if you change your mind.');
}
return <BaseDialog className="mx_SetPasswordDialog"
onFinished={props.onFinished}
title={ title }
>
<div className="mx_Dialog_content">
<p>
{ advice }
</p>
<p>
{ extraAdvice }
</p>
</div>
<div className="mx_Dialog_buttons">
<button
className="mx_Dialog_primary"
autoFocus={true}
onClick={props.onFinished}>
{ _t('Continue') }
</button>
</div>
</BaseDialog>;
};
/**
* Prompt the user to set a password
*
* On success, `onFinished()` when finished
*/
export default class SetPasswordDialog extends React.Component {
static propTypes = {
onFinished: PropTypes.func.isRequired,
};
state = {
error: null,
};
_onPasswordChanged = res => {
Modal.createDialog(WarmFuzzy, {
didSetEmail: res.didSetEmail,
onFinished: () => {
this.props.onFinished();
},
});
};
_onPasswordChangeError = err => {
let errMsg = err.error || "";
if (err.httpStatus === 403) {
errMsg = _t('Failed to change password. Is your password correct?');
} else if (err.httpStatus) {
errMsg += ' ' + _t(
'(HTTP status %(httpStatus)s)',
{ httpStatus: err.httpStatus },
);
}
this.setState({
error: errMsg,
});
};
render() {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
const ChangePassword = sdk.getComponent('views.settings.ChangePassword');
return (
<BaseDialog className="mx_SetPasswordDialog"
onFinished={this.props.onFinished}
title={ _t('Please set a password!') }
>
<div className="mx_Dialog_content">
<p>
{ _t('This will allow you to return to your account after signing out, and sign in on other sessions.') }
</p>
<ChangePassword
className="mx_SetPasswordDialog_change_password"
rowClassName=""
buttonClassNames="mx_Dialog_primary mx_SetPasswordDialog_change_password_button"
buttonKind="primary"
confirm={false}
autoFocusNewPasswordInput={true}
shouldAskForEmail={true}
onError={this._onPasswordChangeError}
onFinished={this._onPasswordChanged} />
<div className="error">
{ this.state.error }
</div>
</div>
</BaseDialog>
);
}
}

View file

@ -289,7 +289,12 @@ export default class AccessSecretStorageDialog extends React.PureComponent {
content = <div>
<p>{_t("Use your Security Key to continue.")}</p>
<form className="mx_AccessSecretStorageDialog_primaryContainer" onSubmit={this._onRecoveryKeyNext} spellCheck={false}>
<form
className="mx_AccessSecretStorageDialog_primaryContainer"
onSubmit={this._onRecoveryKeyNext}
spellCheck={false}
autoComplete="off"
>
<div className="mx_AccessSecretStorageDialog_recoveryKeyEntry">
<div className="mx_AccessSecretStorageDialog_recoveryKeyEntry_textInput">
<Field
@ -298,6 +303,7 @@ export default class AccessSecretStorageDialog extends React.PureComponent {
value={this.state.recoveryKey}
onChange={this._onRecoveryKeyChange}
forceValidity={this.state.recoveryKeyCorrect}
autoComplete="off"
/>
</div>
<span className="mx_AccessSecretStorageDialog_recoveryKeyEntry_entryControlSeparatorText">

View file

@ -62,7 +62,8 @@ export default class AccessibleTooltipButton extends React.PureComponent<IToolti
};
render() {
const {title, tooltip, children, tooltipClassName, ...props} = this.props;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {title, tooltip, children, tooltipClassName, forceHide, ...props} = this.props;
const tip = this.state.hover ? <Tooltip
className="mx_AccessibleTooltipButton_container"

View file

@ -18,11 +18,9 @@ limitations under the License.
*/
import url from 'url';
import qs from 'qs';
import React, {createRef} from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import WidgetMessaging from '../../../WidgetMessaging';
import AccessibleButton from './AccessibleButton';
import Modal from '../../../Modal';
import { _t } from '../../../languageHandler';
@ -34,37 +32,16 @@ import WidgetUtils from '../../../utils/WidgetUtils';
import dis from '../../../dispatcher/dispatcher';
import ActiveWidgetStore from '../../../stores/ActiveWidgetStore';
import classNames from 'classnames';
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
import {aboveLeftOf, ContextMenu, ContextMenuButton} from "../../structures/ContextMenu";
import PersistedElement from "./PersistedElement";
import {WidgetType} from "../../../widgets/WidgetType";
import {Capability} from "../../../widgets/WidgetApi";
import {sleep} from "../../../utils/promise";
import {SettingLevel} from "../../../settings/SettingLevel";
import WidgetStore from "../../../stores/WidgetStore";
import {Action} from "../../../dispatcher/actions";
const ALLOWED_APP_URL_SCHEMES = ['https:', 'http:'];
const ENABLE_REACT_PERF = false;
/**
* Does template substitution on a URL (or any string). Variables will be
* passed through encodeURIComponent.
* @param {string} uriTemplate The path with template variables e.g. '/foo/$bar'.
* @param {Object} variables The key/value pairs to replace the template
* variables with. E.g. { '$bar': 'baz' }.
* @return {string} The result of replacing all template variables e.g. '/foo/baz'.
*/
function uriFromTemplate(uriTemplate, variables) {
let out = uriTemplate;
for (const [key, val] of Object.entries(variables)) {
out = out.replace(
'$' + key, encodeURIComponent(val),
);
}
return out;
}
import {StopGapWidget} from "../../../stores/widgets/StopGapWidget";
import {ElementWidgetActions} from "../../../stores/widgets/ElementWidgetActions";
import {MatrixCapabilities} from "matrix-widget-api";
export default class AppTile extends React.Component {
constructor(props) {
@ -72,11 +49,14 @@ export default class AppTile extends React.Component {
// The key used for PersistedElement
this._persistKey = 'widget_' + this.props.app.id;
this._sgWidget = new StopGapWidget(this.props);
this._sgWidget.on("preparing", this._onWidgetPrepared);
this._sgWidget.on("ready", this._onWidgetReady);
this.iframe = null; // ref to the iframe (callback style)
this.state = this._getNewState(props);
this._onAction = this._onAction.bind(this);
this._onLoaded = this._onLoaded.bind(this);
this._onEditClick = this._onEditClick.bind(this);
this._onDeleteClick = this._onDeleteClick.bind(this);
this._onRevokeClicked = this._onRevokeClicked.bind(this);
@ -89,7 +69,6 @@ export default class AppTile extends React.Component {
this._onReloadWidgetClick = this._onReloadWidgetClick.bind(this);
this._contextMenuButton = createRef();
this._appFrame = createRef();
this._menu_bar = createRef();
}
@ -108,12 +87,10 @@ export default class AppTile extends React.Component {
return !!currentlyAllowedWidgets[newProps.app.eventId];
};
const PersistedElement = sdk.getComponent("elements.PersistedElement");
return {
initialising: true, // True while we are mangling the widget URL
// True while the iframe content is loading
loading: this.props.waitForIframeLoad && !PersistedElement.isMounted(this._persistKey),
widgetUrl: this._addWurlParams(newProps.app.url),
// Assume that widget has permission to load if we are the user who
// added it to the room, or if explicitly granted by the user
hasPermissionToLoad: newProps.userId === newProps.creatorUserId || hasPermissionToLoad(),
@ -124,43 +101,6 @@ export default class AppTile extends React.Component {
};
}
/**
* Does the widget support a given capability
* @param {string} capability Capability to check for
* @return {Boolean} True if capability supported
*/
_hasCapability(capability) {
return ActiveWidgetStore.widgetHasCapability(this.props.app.id, capability);
}
/**
* Add widget instance specific parameters to pass in wUrl
* Properties passed to widget instance:
* - widgetId
* - origin / parent URL
* @param {string} urlString Url string to modify
* @return {string}
* Url string with parameters appended.
* If url can not be parsed, it is returned unmodified.
*/
_addWurlParams(urlString) {
try {
const parsed = new URL(urlString);
// TODO: Replace these with proper widget params
// See https://github.com/matrix-org/matrix-doc/pull/1958/files#r405714833
parsed.searchParams.set('widgetId', this.props.app.id);
parsed.searchParams.set('parentUrl', window.location.href.split('#', 2)[0]);
// Replace the encoded dollar signs back to dollar signs. They have no special meaning
// in HTTP, but URL parsers encode them anyways.
return parsed.toString().replace(/%24/g, '$');
} catch (e) {
console.error("Failed to add widget URL params:", e);
return urlString;
}
}
isMixedContent() {
const parentContentProtocol = window.location.protocol;
const u = url.parse(this.props.app.url);
@ -176,7 +116,7 @@ export default class AppTile extends React.Component {
componentDidMount() {
// Only fetch IM token on mount if we're showing and have permission to load
if (this.props.show && this.state.hasPermissionToLoad) {
this.setScalarToken();
this._startWidget();
}
// Widget action listeners
@ -190,93 +130,45 @@ export default class AppTile extends React.Component {
// if it's not remaining on screen, get rid of the PersistedElement container
if (!ActiveWidgetStore.getWidgetPersistence(this.props.app.id)) {
ActiveWidgetStore.destroyPersistentWidget(this.props.app.id);
const PersistedElement = sdk.getComponent("elements.PersistedElement");
PersistedElement.destroyElement(this._persistKey);
}
if (this._sgWidget) {
this._sgWidget.stop();
}
}
// TODO: Generify the name of this function. It's not just scalar tokens.
/**
* Adds a scalar token to the widget URL, if required
* Component initialisation is only complete when this function has resolved
*/
setScalarToken() {
if (!WidgetUtils.isScalarUrl(this.props.app.url)) {
console.warn('Widget does not match integration manager, refusing to set auth token', url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
_resetWidget(newProps) {
if (this._sgWidget) {
this._sgWidget.stop();
}
this._sgWidget = new StopGapWidget(newProps);
this._sgWidget.on("preparing", this._onWidgetPrepared);
this._sgWidget.on("ready", this._onWidgetReady);
this._startWidget();
}
const managers = IntegrationManagers.sharedInstance();
if (!managers.hasManager()) {
console.warn("No integration manager - not setting scalar token", url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
}
// TODO: Pick the right manager for the widget
const defaultManager = managers.getPrimaryManager();
if (!WidgetUtils.isScalarUrl(defaultManager.apiUrl)) {
console.warn('Unknown integration manager, refusing to set auth token', url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
}
// Fetch the token before loading the iframe as we need it to mangle the URL
if (!this._scalarClient) {
this._scalarClient = defaultManager.getScalarClient();
}
this._scalarClient.getScalarToken().then((token) => {
// Append scalar_token as a query param if not already present
this._scalarClient.scalarToken = token;
const u = url.parse(this._addWurlParams(this.props.app.url));
const params = qs.parse(u.query);
if (!params.scalar_token) {
params.scalar_token = encodeURIComponent(token);
// u.search must be set to undefined, so that u.format() uses query parameters - https://nodejs.org/docs/latest/api/url.html#url_url_format_url_options
u.search = undefined;
u.query = params;
}
this.setState({
error: null,
widgetUrl: u.format(),
initialising: false,
});
// Fetch page title from remote content if not already set
if (!this.state.widgetPageTitle && params.url) {
this._fetchWidgetTitle(params.url);
}
}, (err) => {
console.error("Failed to get scalar_token", err);
this.setState({
error: err.message,
initialising: false,
});
_startWidget() {
this._sgWidget.prepare().then(() => {
this.setState({initialising: false});
});
}
_iframeRefChange = (ref) => {
this.iframe = ref;
if (ref) {
this._sgWidget.start(ref);
} else {
this._resetWidget(this.props);
}
};
// TODO: [REACT-WARNING] Replace with appropriate lifecycle event
UNSAFE_componentWillReceiveProps(nextProps) { // eslint-disable-line camelcase
if (nextProps.app.url !== this.props.app.url) {
this._getNewState(nextProps);
// Fetch IM token for new URL if we're showing and have permission to load
if (this.props.show && this.state.hasPermissionToLoad) {
this.setScalarToken();
this._resetWidget(nextProps);
}
}
@ -287,9 +179,9 @@ export default class AppTile extends React.Component {
loading: true,
});
}
// Fetch IM token now that we're showing if we already have permission to load
// Start the widget now that we're showing if we already have permission to load
if (this.state.hasPermissionToLoad) {
this.setScalarToken();
this._startWidget();
}
}
@ -319,7 +211,14 @@ export default class AppTile extends React.Component {
}
_onSnapshotClick() {
WidgetUtils.snapshotWidget(this.props.app);
this._sgWidget.widgetApi.takeScreenshot().then(data => {
dis.dispatch({
action: 'picture_snapshot',
file: data.screenshot,
});
}).catch(err => {
console.error("Failed to take screenshot: ", err);
});
}
/**
@ -327,35 +226,28 @@ export default class AppTile extends React.Component {
* @private
* @returns {Promise<*>} Resolves when the widget is terminated, or timeout passed.
*/
_endWidgetActions() {
let terminationPromise;
if (this._hasCapability(Capability.ReceiveTerminate)) {
// Wait for widget to terminate within a timeout
const timeout = 2000;
const messaging = ActiveWidgetStore.getWidgetMessaging(this.props.app.id);
terminationPromise = Promise.race([messaging.terminate(), sleep(timeout)]);
} else {
terminationPromise = Promise.resolve();
async _endWidgetActions() { // widget migration dev note: async to maintain signature
// HACK: This is a really dirty way to ensure that Jitsi cleans up
// its hold on the webcam. Without this, the widget holds a media
// stream open, even after death. See https://github.com/vector-im/element-web/issues/7351
if (this.iframe) {
// In practice we could just do `+= ''` to trick the browser
// into thinking the URL changed, however I can foresee this
// being optimized out by a browser. Instead, we'll just point
// the iframe at a page that is reasonably safe to use in the
// event the iframe doesn't wink away.
// This is relative to where the Element instance is located.
this.iframe.src = 'about:blank';
}
return terminationPromise.finally(() => {
// HACK: This is a really dirty way to ensure that Jitsi cleans up
// its hold on the webcam. Without this, the widget holds a media
// stream open, even after death. See https://github.com/vector-im/element-web/issues/7351
if (this._appFrame.current) {
// In practice we could just do `+= ''` to trick the browser
// into thinking the URL changed, however I can foresee this
// being optimized out by a browser. Instead, we'll just point
// the iframe at a page that is reasonably safe to use in the
// event the iframe doesn't wink away.
// This is relative to where the Element instance is located.
this._appFrame.current.src = 'about:blank';
}
if (WidgetType.JITSI.matches(this.props.app.type)) {
dis.dispatch({action: 'hangup_conference'});
}
// Delete the widget from the persisted store for good measure.
PersistedElement.destroyElement(this._persistKey);
});
// Delete the widget from the persisted store for good measure.
PersistedElement.destroyElement(this._persistKey);
this._sgWidget.stop({forceDestroy: true});
}
/* If user has permission to modify widgets, delete the widget,
@ -409,73 +301,21 @@ export default class AppTile extends React.Component {
this._revokeWidgetPermission();
}
/**
* Called when widget iframe has finished loading
*/
_onLoaded() {
// Destroy the old widget messaging before starting it back up again. Some widgets
// have startup routines that run when they are loaded, so we just need to reinitialize
// the messaging for them.
ActiveWidgetStore.delWidgetMessaging(this.props.app.id);
this._setupWidgetMessaging();
ActiveWidgetStore.setRoomId(this.props.app.id, this.props.room.roomId);
_onWidgetPrepared = () => {
this.setState({loading: false});
}
};
_setupWidgetMessaging() {
// FIXME: There's probably no reason to do this here: it should probably be done entirely
// in ActiveWidgetStore.
const widgetMessaging = new WidgetMessaging(
this.props.app.id,
this.props.app.url,
this._getRenderedUrl(),
this.props.userWidget,
this._appFrame.current.contentWindow,
);
ActiveWidgetStore.setWidgetMessaging(this.props.app.id, widgetMessaging);
widgetMessaging.getCapabilities().then((requestedCapabilities) => {
console.log(`Widget ${this.props.app.id} requested capabilities: ` + requestedCapabilities);
requestedCapabilities = requestedCapabilities || [];
// Allow whitelisted capabilities
let requestedWhitelistCapabilies = [];
if (this.props.whitelistCapabilities && this.props.whitelistCapabilities.length > 0) {
requestedWhitelistCapabilies = requestedCapabilities.filter(function(e) {
return this.indexOf(e)>=0;
}, this.props.whitelistCapabilities);
if (requestedWhitelistCapabilies.length > 0 ) {
console.log(`Widget ${this.props.app.id} allowing requested, whitelisted properties: ` +
requestedWhitelistCapabilies,
);
}
}
// TODO -- Add UI to warn about and optionally allow requested capabilities
ActiveWidgetStore.setWidgetCapabilities(this.props.app.id, requestedWhitelistCapabilies);
if (this.props.onCapabilityRequest) {
this.props.onCapabilityRequest(requestedCapabilities);
}
// We only tell Jitsi widgets that we're ready because they're realistically the only ones
// using this custom extension to the widget API.
if (WidgetType.JITSI.matches(this.props.app.type)) {
widgetMessaging.flagReadyToContinue();
}
}).catch((err) => {
console.log(`Failed to get capabilities for widget type ${this.props.app.type}`, this.props.app.id, err);
});
}
_onWidgetReady = () => {
if (WidgetType.JITSI.matches(this.props.app.type)) {
this._sgWidget.widgetApi.transport.send(ElementWidgetActions.ClientReady, {});
}
};
_onAction(payload) {
if (payload.widgetId === this.props.app.id) {
switch (payload.action) {
case 'm.sticker':
if (this._hasCapability('m.sticker')) {
if (this._sgWidget.widgetApi.hasCapability(MatrixCapabilities.StickerSending)) {
dis.dispatch({action: 'post_sticker_message', data: payload.data});
} else {
console.warn('Ignoring sticker message. Invalid capability');
@ -493,20 +333,6 @@ export default class AppTile extends React.Component {
}
}
/**
* Set remote content title on AppTile
* @param {string} url Url to check for title
*/
_fetchWidgetTitle(url) {
this._scalarClient.getScalarPageTitle(url).then((widgetPageTitle) => {
if (widgetPageTitle) {
this.setState({widgetPageTitle: widgetPageTitle});
}
}, (err) =>{
console.error("Failed to get page title", err);
});
}
_grantWidgetPermission() {
const roomId = this.props.room.roomId;
console.info("Granting permission for widget to load: " + this.props.app.eventId);
@ -516,7 +342,7 @@ export default class AppTile extends React.Component {
this.setState({hasPermissionToLoad: true});
// Fetch a token for the integration manager, now that we're allowed to
this.setScalarToken();
this._startWidget();
}).catch(err => {
console.error(err);
// We don't really need to do anything about this - the user will just hit the button again.
@ -535,6 +361,7 @@ export default class AppTile extends React.Component {
ActiveWidgetStore.destroyPersistentWidget(this.props.app.id);
const PersistedElement = sdk.getComponent("elements.PersistedElement");
PersistedElement.destroyElement(this._persistKey);
this._sgWidget.stop();
}).catch(err => {
console.error(err);
// We don't really need to do anything about this - the user will just hit the button again.
@ -564,6 +391,9 @@ export default class AppTile extends React.Component {
if (this.props.show) {
// if we were being shown, end the widget as we're about to be minimized.
this._endWidgetActions();
} else {
// restart the widget actions
this._resetWidget(this.props);
}
dis.dispatch({
action: 'appsDrawer',
@ -572,40 +402,6 @@ export default class AppTile extends React.Component {
}
}
/**
* Replace the widget template variables in a url with their values
*
* @param {string} u The URL with template variables
* @param {string} widgetType The widget's type
*
* @returns {string} url with temlate variables replaced
*/
_templatedUrl(u, widgetType: string) {
const targetData = {};
if (WidgetType.JITSI.matches(widgetType)) {
targetData['domain'] = 'jitsi.riot.im'; // v1 jitsi widgets have this hardcoded
}
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUser = MatrixClientPeg.get().getUser(myUserId);
const vars = Object.assign(targetData, this.props.app.data, {
'matrix_user_id': myUserId,
'matrix_room_id': this.props.room.roomId,
'matrix_display_name': myUser ? myUser.displayName : myUserId,
'matrix_avatar_url': myUser ? MatrixClientPeg.get().mxcUrlToHttp(myUser.avatarUrl) : '',
// TODO: Namespace themes through some standard
'theme': SettingsStore.getValue("theme"),
});
if (vars.conferenceId === undefined) {
// we'll need to parse the conference ID out of the URL for v1 Jitsi widgets
const parsedUrl = new URL(this.props.app.url);
vars.conferenceId = parsedUrl.searchParams.get("confId");
}
return uriFromTemplate(u, vars);
}
/**
* Whether we're using a local version of the widget rather than loading the
* actual widget URL
@ -615,67 +411,11 @@ export default class AppTile extends React.Component {
return WidgetType.JITSI.matches(this.props.app.type);
}
/**
* Get the URL used in the iframe
* In cases where we supply our own UI for a widget, this is an internal
* URL different to the one used if the widget is popped out to a separate
* tab / browser
*
* @returns {string} url
*/
_getRenderedUrl() {
let url;
if (WidgetType.JITSI.matches(this.props.app.type)) {
console.log("Replacing Jitsi widget URL with local wrapper");
url = WidgetUtils.getLocalJitsiWrapperUrl({
forLocalRender: true,
auth: this.props.app.data ? this.props.app.data.auth : null,
});
url = this._addWurlParams(url);
} else {
url = this._getSafeUrl(this.state.widgetUrl);
}
return this._templatedUrl(url, this.props.app.type);
}
_getPopoutUrl() {
if (WidgetType.JITSI.matches(this.props.app.type)) {
return this._templatedUrl(
WidgetUtils.getLocalJitsiWrapperUrl({
forLocalRender: false,
auth: this.props.app.data ? this.props.app.data.auth : null,
}),
this.props.app.type,
);
} else {
// use app.url, not state.widgetUrl, because we want the one without
// the wURL params for the popped-out version.
return this._templatedUrl(this._getSafeUrl(this.props.app.url), this.props.app.type);
}
}
_getSafeUrl(u) {
const parsedWidgetUrl = url.parse(u, true);
if (ENABLE_REACT_PERF) {
parsedWidgetUrl.search = null;
parsedWidgetUrl.query.react_perf = true;
}
let safeWidgetUrl = '';
if (ALLOWED_APP_URL_SCHEMES.includes(parsedWidgetUrl.protocol)) {
safeWidgetUrl = url.format(parsedWidgetUrl);
}
// Replace all the dollar signs back to dollar signs as they don't affect HTTP at all.
// We also need the dollar signs in-tact for variable substitution.
return safeWidgetUrl.replace(/%24/g, '$');
}
_getTileTitle() {
const name = this.formatAppTileName();
const titleSpacer = <span>&nbsp;-&nbsp;</span>;
let title = '';
if (this.state.widgetPageTitle && this.state.widgetPageTitle != this.formatAppTileName()) {
if (this.state.widgetPageTitle && this.state.widgetPageTitle !== this.formatAppTileName()) {
title = this.state.widgetPageTitle;
}
@ -698,9 +438,9 @@ export default class AppTile extends React.Component {
// twice from the same computer, which Jitsi can have problems with (audio echo/gain-loop).
if (WidgetType.JITSI.matches(this.props.app.type) && this.props.show) {
this._endWidgetActions().then(() => {
if (this._appFrame.current) {
if (this.iframe) {
// Reload iframe
this._appFrame.current.src = this._getRenderedUrl();
this.iframe.src = this._sgWidget.embedUrl;
this.setState({});
}
});
@ -708,13 +448,13 @@ export default class AppTile extends React.Component {
// Using Object.assign workaround as the following opens in a new window instead of a new tab.
// window.open(this._getPopoutUrl(), '_blank', 'noopener=yes');
Object.assign(document.createElement('a'),
{ target: '_blank', href: this._getPopoutUrl(), rel: 'noreferrer noopener'}).click();
{ target: '_blank', href: this._sgWidget.popoutUrl, rel: 'noreferrer noopener'}).click();
}
_onReloadWidgetClick() {
// Reload iframe in this way to avoid cross-origin restrictions
// eslint-disable-next-line no-self-assign
this._appFrame.current.src = this._appFrame.current.src;
this.iframe.src = this.iframe.src;
}
_onContextMenuClick = () => {
@ -760,7 +500,7 @@ export default class AppTile extends React.Component {
<AppPermission
roomId={this.props.room.roomId}
creatorUserId={this.props.creatorUserId}
url={this.state.widgetUrl}
url={this._sgWidget.embedUrl}
isRoomEncrypted={isEncrypted}
onPermissionGranted={this._grantWidgetPermission}
/>
@ -785,11 +525,11 @@ export default class AppTile extends React.Component {
{ this.state.loading && loadingElement }
<iframe
allow={iframeFeatures}
ref={this._appFrame}
src={this._getRenderedUrl()}
ref={this._iframeRefChange}
src={this._sgWidget.embedUrl}
allowFullScreen={true}
sandbox={sandboxFlags}
onLoad={this._onLoaded} />
/>
</div>
);
// if the widget would be allowed to remain on screen, we must put it in
@ -833,9 +573,10 @@ export default class AppTile extends React.Component {
const elementRect = this._contextMenuButton.current.getBoundingClientRect();
const canUserModify = this._canUserModify();
const showEditButton = Boolean(this._scalarClient && canUserModify);
const showEditButton = Boolean(this._sgWidget.isManagedByManager && canUserModify);
const showDeleteButton = (this.props.showDelete === undefined || this.props.showDelete) && canUserModify;
const showPictureSnapshotButton = this._hasCapability('m.capability.screenshot') && this.props.show;
const showPictureSnapshotButton = this.props.show && this._sgWidget.widgetApi &&
this._sgWidget.widgetApi.hasCapability(MatrixCapabilities.Screenshots);
const WidgetContextMenu = sdk.getComponent('views.context_menus.WidgetContextMenu');
contextMenu = (
@ -943,9 +684,6 @@ AppTile.propTypes = {
// NOTE -- Use with caution. This is intended to aid better integration / UX
// basic widget capabilities, e.g. injecting sticker message events.
whitelistCapabilities: PropTypes.array,
// Optional function to be called on widget capability request
// Called with an array of the requested capabilities
onCapabilityRequest: PropTypes.func,
// Is this an instance of a user widget
userWidget: PropTypes.bool,
};

View file

@ -1,5 +1,5 @@
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,15 +14,41 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {useEffect} from 'react';
import PropTypes from 'prop-types';
import React, {ReactChildren, useEffect} from 'react';
import {MatrixEvent} from "matrix-js-sdk/src/models/event";
import {RoomMember} from "matrix-js-sdk/src/models/room-member";
import MemberAvatar from '../avatars/MemberAvatar';
import { _t } from '../../../languageHandler';
import {MatrixEvent, RoomMember} from "matrix-js-sdk";
import {useStateToggle} from "../../../hooks/useStateToggle";
import AccessibleButton from "./AccessibleButton";
const EventListSummary = ({events, children, threshold=3, onToggle, startExpanded, summaryMembers=[], summaryText}) => {
interface IProps {
// An array of member events to summarise
events: MatrixEvent[];
// The minimum number of events needed to trigger summarisation
threshold?: number;
// Whether or not to begin with state.expanded=true
startExpanded?: boolean,
// The list of room members for which to show avatars next to the summary
summaryMembers?: RoomMember[],
// The text to show as the summary of this event list
summaryText?: string,
// An array of EventTiles to render when expanded
children: ReactChildren,
// Called when the event list expansion is toggled
onToggle?(): void;
}
const EventListSummary: React.FC<IProps> = ({
events,
children,
threshold = 3,
onToggle,
startExpanded,
summaryMembers = [],
summaryText,
}) => {
const [expanded, toggleExpanded] = useStateToggle(startExpanded);
// Whenever expanded changes call onToggle
@ -75,22 +101,4 @@ const EventListSummary = ({events, children, threshold=3, onToggle, startExpande
);
};
EventListSummary.propTypes = {
// An array of member events to summarise
events: PropTypes.arrayOf(PropTypes.instanceOf(MatrixEvent)).isRequired,
// An array of EventTiles to render when expanded
children: PropTypes.arrayOf(PropTypes.element).isRequired,
// The minimum number of events needed to trigger summarisation
threshold: PropTypes.number,
// Called when the event list expansion is toggled
onToggle: PropTypes.func,
// Whether or not to begin with state.expanded=true
startExpanded: PropTypes.bool,
// The list of room members for which to show avatars next to the summary
summaryMembers: PropTypes.arrayOf(PropTypes.instanceOf(RoomMember)),
// The text to show as the summary of this event list
summaryText: PropTypes.string,
};
export default EventListSummary;

View file

@ -80,27 +80,30 @@ export default class EventTilePreview extends React.Component<IProps, IState> {
private fakeEvent({userId, displayname, avatar_url: avatarUrl}: IState) {
// Fake it till we make it
const event = new MatrixEvent(JSON.parse(`{
"type": "m.room.message",
"sender": "${userId}",
"content": {
"m.new_content": {
"msgtype": "m.text",
"body": "${this.props.message}",
"displayname": "${displayname}",
"avatar_url": "${avatarUrl}"
},
"msgtype": "m.text",
"body": "${this.props.message}",
"displayname": "${displayname}",
"avatar_url": "${avatarUrl}"
/* eslint-disable quote-props */
const rawEvent = {
type: "m.room.message",
sender: userId,
content: {
"m.new_content": {
msgtype: "m.text",
body: this.props.message,
displayname: displayname,
avatar_url: avatarUrl,
},
"unsigned": {
"age": 97
},
"event_id": "$9999999999999999999999999999999999999999999",
"room_id": "!999999999999999999:matrix.org"
}`));
msgtype: "m.text",
body: this.props.message,
displayname: displayname,
avatar_url: avatarUrl,
},
unsigned: {
age: 97,
},
event_id: "$9999999999999999999999999999999999999999999",
room_id: "!999999999999999999:example.org",
};
const event = new MatrixEvent(rawEvent);
/* eslint-enable quote-props */
// Fake it more
event.sender = {

View file

@ -16,32 +16,60 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import React, { ReactChildren } from 'react';
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { RoomMember } from "matrix-js-sdk/src/models/room-member";
import { _t } from '../../../languageHandler';
import { formatCommaSeparatedList } from '../../../utils/FormattingUtils';
import * as sdk from "../../../index";
import {MatrixEvent} from "matrix-js-sdk";
import {isValid3pidInvite} from "../../../RoomInvite";
import { isValid3pidInvite } from "../../../RoomInvite";
import EventListSummary from "./EventListSummary";
export default class MemberEventListSummary extends React.Component {
static propTypes = {
// An array of member events to summarise
events: PropTypes.arrayOf(PropTypes.instanceOf(MatrixEvent)).isRequired,
// An array of EventTiles to render when expanded
children: PropTypes.array.isRequired,
// The maximum number of names to show in either each summary e.g. 2 would result "A, B and 234 others left"
summaryLength: PropTypes.number,
// The maximum number of avatars to display in the summary
avatarsMaxLength: PropTypes.number,
// The minimum number of events needed to trigger summarisation
threshold: PropTypes.number,
// Called when the MELS expansion is toggled
onToggle: PropTypes.func,
// Whether or not to begin with state.expanded=true
startExpanded: PropTypes.bool,
};
interface IProps {
// An array of member events to summarise
events: MatrixEvent[];
// The maximum number of names to show in either each summary e.g. 2 would result "A, B and 234 others left"
summaryLength?: number;
// The maximum number of avatars to display in the summary
avatarsMaxLength?: number;
// The minimum number of events needed to trigger summarisation
threshold?: number,
// Whether or not to begin with state.expanded=true
startExpanded?: boolean,
// An array of EventTiles to render when expanded
children: ReactChildren;
// Called when the MELS expansion is toggled
onToggle?(): void,
}
interface IUserEvents {
// The original event
mxEvent: MatrixEvent;
// The display name of the user (if not, then user ID)
displayName: string;
// The original index of the event in this.props.events
index: number;
}
enum TransitionType {
Joined = "joined",
Left = "left",
JoinedAndLeft = "joined_and_left",
LeftAndJoined = "left_and_joined",
InviteReject = "invite_reject",
InviteWithdrawal = "invite_withdrawal",
Invited = "invited",
Banned = "banned",
Unbanned = "unbanned",
Kicked = "kicked",
ChangedName = "changed_name",
ChangedAvatar = "changed_avatar",
NoChange = "no_change",
}
const SEP = ",";
export default class MemberEventListSummary extends React.Component<IProps> {
static defaultProps = {
summaryLength: 1,
threshold: 3,
@ -62,30 +90,28 @@ export default class MemberEventListSummary extends React.Component {
/**
* Generate the text for users aggregated by their transition sequences (`eventAggregates`) where
* the sequences are ordered by `orderedTransitionSequences`.
* @param {object[]} eventAggregates a map of transition sequence to array of user display names
* @param {object} eventAggregates a map of transition sequence to array of user display names
* or user IDs.
* @param {string[]} orderedTransitionSequences an array which is some ordering of
* `Object.keys(eventAggregates)`.
* @returns {string} the textual summary of the aggregated events that occurred.
*/
_generateSummary(eventAggregates, orderedTransitionSequences) {
private generateSummary(eventAggregates: Record<string, string[]>, orderedTransitionSequences: string[]) {
const summaries = orderedTransitionSequences.map((transitions) => {
const userNames = eventAggregates[transitions];
const nameList = this._renderNameList(userNames);
const nameList = this.renderNameList(userNames);
const splitTransitions = transitions.split(',');
const splitTransitions = transitions.split(SEP) as TransitionType[];
// Some neighbouring transitions are common, so canonicalise some into "pair"
// transitions
const canonicalTransitions = this._getCanonicalTransitions(splitTransitions);
const canonicalTransitions = MemberEventListSummary.getCanonicalTransitions(splitTransitions);
// Transform into consecutive repetitions of the same transition (like 5
// consecutive 'joined_and_left's)
const coalescedTransitions = this._coalesceRepeatedTransitions(
canonicalTransitions,
);
const coalescedTransitions = MemberEventListSummary.coalesceRepeatedTransitions(canonicalTransitions);
const descs = coalescedTransitions.map((t) => {
return this._getDescriptionForTransition(
return MemberEventListSummary.getDescriptionForTransition(
t.transitionType, userNames.length, t.repeats,
);
});
@ -108,7 +134,7 @@ export default class MemberEventListSummary extends React.Component {
* more items in `users` than `this.props.summaryLength`, which is the number of names
* included before "and [n] others".
*/
_renderNameList(users) {
private renderNameList(users: string[]) {
return formatCommaSeparatedList(users, this.props.summaryLength);
}
@ -119,22 +145,22 @@ export default class MemberEventListSummary extends React.Component {
* @param {string[]} transitions an array of transitions.
* @returns {string[]} an array of transitions.
*/
_getCanonicalTransitions(transitions) {
private static getCanonicalTransitions(transitions: TransitionType[]): TransitionType[] {
const modMap = {
'joined': {
'after': 'left',
'newTransition': 'joined_and_left',
[TransitionType.Joined]: {
after: TransitionType.Left,
newTransition: TransitionType.JoinedAndLeft,
},
'left': {
'after': 'joined',
'newTransition': 'left_and_joined',
[TransitionType.Left]: {
after: TransitionType.Joined,
newTransition: TransitionType.LeftAndJoined,
},
// $currentTransition : {
// 'after' : $nextTransition,
// 'newTransition' : 'new_transition_type',
// },
};
const res = [];
const res: TransitionType[] = [];
for (let i = 0; i < transitions.length; i++) {
const t = transitions[i];
@ -166,8 +192,12 @@ export default class MemberEventListSummary extends React.Component {
* @param {string[]} transitions the array of transitions to transform.
* @returns {object[]} an array of coalesced transitions.
*/
_coalesceRepeatedTransitions(transitions) {
const res = [];
private static coalesceRepeatedTransitions(transitions: TransitionType[]) {
const res: {
transitionType: TransitionType;
repeats: number;
}[] = [];
for (let i = 0; i < transitions.length; i++) {
if (res.length > 0 && res[res.length - 1].transitionType === transitions[i]) {
res[res.length - 1].repeats += 1;
@ -189,7 +219,7 @@ export default class MemberEventListSummary extends React.Component {
* @param {number} repeats the number of times the transition was repeated in a row.
* @returns {string} the written Human Readable equivalent of the transition.
*/
_getDescriptionForTransition(t, userCount, repeats) {
private static getDescriptionForTransition(t: TransitionType, userCount: number, repeats: number) {
// The empty interpolations 'severalUsers' and 'oneUser'
// are there only to show translators to non-English languages
// that the verb is conjugated to plural or singular Subject.
@ -217,12 +247,18 @@ export default class MemberEventListSummary extends React.Component {
break;
case "invite_reject":
res = (userCount > 1)
? _t("%(severalUsers)srejected their invitations %(count)s times", { severalUsers: "", count: repeats })
? _t("%(severalUsers)srejected their invitations %(count)s times", {
severalUsers: "",
count: repeats,
})
: _t("%(oneUser)srejected their invitation %(count)s times", { oneUser: "", count: repeats });
break;
case "invite_withdrawal":
res = (userCount > 1)
? _t("%(severalUsers)shad their invitations withdrawn %(count)s times", { severalUsers: "", count: repeats })
? _t("%(severalUsers)shad their invitations withdrawn %(count)s times", {
severalUsers: "",
count: repeats,
})
: _t("%(oneUser)shad their invitation withdrawn %(count)s times", { oneUser: "", count: repeats });
break;
case "invited":
@ -265,8 +301,8 @@ export default class MemberEventListSummary extends React.Component {
return res;
}
_getTransitionSequence(events) {
return events.map(this._getTransition);
private static getTransitionSequence(events: MatrixEvent[]) {
return events.map(MemberEventListSummary.getTransition);
}
/**
@ -277,60 +313,60 @@ export default class MemberEventListSummary extends React.Component {
* @returns {string?} the transition type given to this event. This defaults to `null`
* if a transition is not recognised.
*/
_getTransition(e) {
private static getTransition(e: MatrixEvent): TransitionType {
if (e.mxEvent.getType() === 'm.room.third_party_invite') {
// Handle 3pid invites the same as invites so they get bundled together
if (!isValid3pidInvite(e.mxEvent)) {
return 'invite_withdrawal';
return TransitionType.InviteWithdrawal;
}
return 'invited';
return TransitionType.Invited;
}
switch (e.mxEvent.getContent().membership) {
case 'invite': return 'invited';
case 'ban': return 'banned';
case 'invite': return TransitionType.Invited;
case 'ban': return TransitionType.Banned;
case 'join':
if (e.mxEvent.getPrevContent().membership === 'join') {
if (e.mxEvent.getContent().displayname !==
e.mxEvent.getPrevContent().displayname) {
return 'changed_name';
return TransitionType.ChangedName;
} else if (e.mxEvent.getContent().avatar_url !==
e.mxEvent.getPrevContent().avatar_url) {
return 'changed_avatar';
return TransitionType.ChangedAvatar;
}
// console.log("MELS ignoring duplicate membership join event");
return 'no_change';
return TransitionType.NoChange;
} else {
return 'joined';
return TransitionType.Joined;
}
case 'leave':
if (e.mxEvent.getSender() === e.mxEvent.getStateKey()) {
switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_reject';
default: return 'left';
case 'invite': return TransitionType.InviteReject;
default: return TransitionType.Left;
}
}
switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_withdrawal';
case 'ban': return 'unbanned';
case 'invite': return TransitionType.InviteWithdrawal;
case 'ban': return TransitionType.Unbanned;
// sender is not target and made the target leave, if not from invite/ban then this is a kick
default: return 'kicked';
default: return TransitionType.Kicked;
}
default: return null;
}
}
_getAggregate(userEvents) {
getAggregate(userEvents: Record<string, IUserEvents[]>) {
// A map of aggregate type to arrays of display names. Each aggregate type
// is a comma-delimited string of transitions, e.g. "joined,left,kicked".
// The array of display names is the array of users who went through that
// sequence during eventsToRender.
const aggregate = {
const aggregate: Record<string, string[]> = {
// $aggregateType : []:string
};
// A map of aggregate types to the indices that order them (the index of
// the first event for a given transition sequence)
const aggregateIndices = {
const aggregateIndices: Record<string, number> = {
// $aggregateType : int
};
@ -340,7 +376,7 @@ export default class MemberEventListSummary extends React.Component {
const firstEvent = userEvents[userId][0];
const displayName = firstEvent.displayName;
const seq = this._getTransitionSequence(userEvents[userId]);
const seq = MemberEventListSummary.getTransitionSequence(userEvents[userId]).join(SEP);
if (!aggregate[seq]) {
aggregate[seq] = [];
aggregateIndices[seq] = -1;
@ -349,8 +385,9 @@ export default class MemberEventListSummary extends React.Component {
aggregate[seq].push(displayName);
if (aggregateIndices[seq] === -1 ||
firstEvent.index < aggregateIndices[seq]) {
aggregateIndices[seq] = firstEvent.index;
firstEvent.index < aggregateIndices[seq]
) {
aggregateIndices[seq] = firstEvent.index;
}
},
);
@ -364,25 +401,21 @@ export default class MemberEventListSummary extends React.Component {
render() {
const eventsToRender = this.props.events;
// Map user IDs to an array of objects:
const userEvents = {
// $userId : [{
// // The original event
// mxEvent: e,
// // The display name of the user (if not, then user ID)
// displayName: e.target.name || userId,
// // The original index of the event in this.props.events
// index: index,
// }]
};
// Map user IDs to latest Avatar Member. ES6 Maps are ordered by when the key was created,
// so this works perfectly for us to match event order whilst storing the latest Avatar Member
const latestUserAvatarMember = new Map<string, RoomMember>();
const avatarMembers = [];
// Object mapping user IDs to an array of IUserEvents
const userEvents: Record<string, IUserEvents[]> = {};
eventsToRender.forEach((e, index) => {
const userId = e.getStateKey();
// Initialise a user's events
if (!userEvents[userId]) {
userEvents[userId] = [];
if (e.target) avatarMembers.push(e.target);
}
if (e.target) {
latestUserAvatarMember.set(userId, e.target);
}
let displayName = userId;
@ -399,21 +432,20 @@ export default class MemberEventListSummary extends React.Component {
});
});
const aggregate = this._getAggregate(userEvents);
const aggregate = this.getAggregate(userEvents);
// Sort types by order of lowest event index within sequence
const orderedTransitionSequences = Object.keys(aggregate.names).sort(
(seq1, seq2) => aggregate.indices[seq1] > aggregate.indices[seq2],
(seq1, seq2) => aggregate.indices[seq1] - aggregate.indices[seq2],
);
const EventListSummary = sdk.getComponent("views.elements.EventListSummary");
return <EventListSummary
events={this.props.events}
threshold={this.props.threshold}
onToggle={this.props.onToggle}
startExpanded={this.props.startExpanded}
children={this.props.children}
summaryMembers={avatarMembers}
summaryText={this._generateSummary(aggregate.names, orderedTransitionSequences)} />;
summaryMembers={[...latestUserAvatarMember.values()]}
summaryText={this.generateSummary(aggregate.names, orderedTransitionSequences)} />;
}
}

View file

@ -58,6 +58,11 @@ export default class PersistentApp extends React.Component {
const persistentWidgetInRoomId = ActiveWidgetStore.getRoomId(this.state.persistentWidgetId);
if (this.state.roomId !== persistentWidgetInRoomId) {
const persistentWidgetInRoom = MatrixClientPeg.get().getRoom(persistentWidgetInRoomId);
// Sanity check the room - the widget may have been destroyed between render cycles, and
// thus no room is associated anymore.
if (!persistentWidgetInRoom) return null;
// get the widget data
const appEvent = WidgetUtils.getRoomWidgets(persistentWidgetInRoom).find((ev) => {
return ev.getStateKey() === ActiveWidgetStore.getPersistentWidgetId();
@ -82,6 +87,7 @@ export default class PersistentApp extends React.Component {
showDelete={false}
showMinimise={false}
miniMode={true}
showMenubar={false}
/>;
}
}

View file

@ -29,6 +29,7 @@ import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {Action} from "../../../dispatcher/actions";
import sanitizeHtml from "sanitize-html";
import {UIFeature} from "../../../settings/UIFeature";
import {PERMITTED_URL_SCHEMES} from "../../../HtmlUtils";
// This component does no cycle detection, simply because the only way to make such a cycle would be to
// craft event_id's, using a homeserver that generates predictable event IDs; even then the impact would
@ -62,6 +63,12 @@ export default class ReplyThread extends React.Component {
err: false,
};
this.unmounted = false;
this.context.on("Event.replaced", this.onEventReplaced);
this.room = this.context.getRoom(this.props.parentEv.getRoomId());
this.room.on("Room.redaction", this.onRoomRedaction);
this.room.on("Room.redactionCancelled", this.onRoomRedaction);
this.onQuoteClick = this.onQuoteClick.bind(this);
this.canCollapse = this.canCollapse.bind(this);
this.collapse = this.collapse.bind(this);
@ -106,6 +113,9 @@ export default class ReplyThread extends React.Component {
{
allowedTags: false, // false means allow everything
allowedAttributes: false,
// we somehow can't allow all schemes, so we allow all that we
// know of and mxc (for img tags)
allowedSchemes: [...PERMITTED_URL_SCHEMES, 'mxc'],
exclusiveFilter: (frame) => frame.tag === "mx-reply",
},
);
@ -213,11 +223,6 @@ export default class ReplyThread extends React.Component {
}
componentDidMount() {
this.unmounted = false;
this.room = this.context.getRoom(this.props.parentEv.getRoomId());
this.room.on("Room.redaction", this.onRoomRedaction);
// same event handler as Room.redaction as for both we just do forceUpdate
this.room.on("Room.redactionCancelled", this.onRoomRedaction);
this.initialize();
}
@ -227,21 +232,36 @@ export default class ReplyThread extends React.Component {
componentWillUnmount() {
this.unmounted = true;
this.context.removeListener("Event.replaced", this.onEventReplaced);
if (this.room) {
this.room.removeListener("Room.redaction", this.onRoomRedaction);
this.room.removeListener("Room.redactionCancelled", this.onRoomRedaction);
}
}
onRoomRedaction = (ev, room) => {
if (this.unmounted) return;
// If one of the events we are rendering gets redacted, force a re-render
if (this.state.events.some(event => event.getId() === ev.getId())) {
updateForEventId = (eventId) => {
if (this.state.events.some(event => event.getId() === eventId)) {
this.forceUpdate();
}
};
onEventReplaced = (ev) => {
if (this.unmounted) return;
// If one of the events we are rendering gets replaced, force a re-render
this.updateForEventId(ev.getId());
};
onRoomRedaction = (ev) => {
if (this.unmounted) return;
const eventId = ev.getAssociatedId();
if (!eventId) return;
// If one of the events we are rendering gets redacted, force a re-render
this.updateForEventId(eventId);
};
async initialize() {
const {parentEv} = this.props;
// at time of making this component we checked that props.parentEv has a parentEventId
@ -368,6 +388,7 @@ export default class ReplyThread extends React.Component {
isTwelveHour={SettingsStore.getValue("showTwelveHourTimestamps")}
useIRCLayout={this.props.useIRCLayout}
enableFlair={SettingsStore.getValue(UIFeature.Flair)}
replacingEventId={ev.replacingEventId()}
/>
</blockquote>;
});

View file

@ -26,12 +26,12 @@ import * as FormattingUtils from '../../../utils/FormattingUtils';
import FlairStore from '../../../stores/FlairStore';
import GroupStore from '../../../stores/GroupStore';
import TagOrderStore from '../../../stores/TagOrderStore';
import GroupFilterOrderStore from '../../../stores/GroupFilterOrderStore';
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import AccessibleButton from "./AccessibleButton";
import SettingsStore from "../../../settings/SettingsStore";
// A class for a child of TagPanel (possibly wrapped in a DNDTagTile) that represents
// A class for a child of GroupFilterPanel (possibly wrapped in a DNDTagTile) that represents
// a thing to click on for the user to filter the visible rooms in the RoomList to:
// - Rooms that are part of the group
// - Direct messages with members of the group
@ -142,7 +142,7 @@ export default class TagTile extends React.Component {
mx_TagTile_selected_prototype: this.props.selected && isPrototype,
});
const badge = TagOrderStore.getGroupBadge(this.props.tag);
const badge = GroupFilterOrderStore.getGroupBadge(this.props.tag);
let badgeElement;
if (badge && !this.state.hover && !this.props.menuDisplayed) {
const badgeClasses = classNames({

View file

@ -17,7 +17,7 @@ limitations under the License.
import React from "react";
import defaultDispatcher from "../../../dispatcher/dispatcher";
import * as fbEmitter from "fbemitter";
import TagOrderStore from "../../../stores/TagOrderStore";
import GroupFilterOrderStore from "../../../stores/GroupFilterOrderStore";
import AccessibleTooltipButton from "./AccessibleTooltipButton";
import classNames from "classnames";
import { _t } from "../../../languageHandler";
@ -36,12 +36,12 @@ export default class UserTagTile extends React.PureComponent<IProps, IState> {
super(props);
this.state = {
selected: TagOrderStore.getSelectedTags().length === 0,
selected: GroupFilterOrderStore.getSelectedTags().length === 0,
};
}
public componentDidMount() {
this.tagStoreRef = TagOrderStore.addListener(this.onTagStoreUpdate);
this.tagStoreRef = GroupFilterOrderStore.addListener(this.onTagStoreUpdate);
}
public componentWillUnmount() {
@ -49,7 +49,7 @@ export default class UserTagTile extends React.PureComponent<IProps, IState> {
}
private onTagStoreUpdate = () => {
const selected = TagOrderStore.getSelectedTags().length === 0;
const selected = GroupFilterOrderStore.getSelectedTags().length === 0;
this.setState({selected});
};

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,32 +15,53 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import React, {RefObject} from 'react';
import { CATEGORY_HEADER_HEIGHT, EMOJI_HEIGHT, EMOJIS_PER_ROW } from "./EmojiPicker";
import * as sdk from '../../../index';
import LazyRenderList from "../elements/LazyRenderList";
import {DATA_BY_CATEGORY, IEmoji} from "../../../emoji";
import Emoji from './Emoji';
const OVERFLOW_ROWS = 3;
class Category extends React.PureComponent {
static propTypes = {
emojis: PropTypes.arrayOf(PropTypes.object).isRequired,
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
onMouseEnter: PropTypes.func.isRequired,
onMouseLeave: PropTypes.func.isRequired,
onClick: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
export type CategoryKey = (keyof typeof DATA_BY_CATEGORY) | "recent";
_renderEmojiRow = (rowIndex) => {
export interface ICategory {
id: CategoryKey;
name: string;
enabled: boolean;
visible: boolean;
ref: RefObject<HTMLButtonElement>;
}
interface IProps {
id: string;
name: string;
emojis: IEmoji[];
selectedEmojis: Set<string>;
heightBefore: number;
viewportHeight: number;
scrollTop: number;
onClick(emoji: IEmoji): void;
onMouseEnter(emoji: IEmoji): void;
onMouseLeave(emoji: IEmoji): void;
}
class Category extends React.PureComponent<IProps> {
private renderEmojiRow = (rowIndex: number) => {
const { onClick, onMouseEnter, onMouseLeave, selectedEmojis, emojis } = this.props;
const emojisForRow = emojis.slice(rowIndex * 8, (rowIndex + 1) * 8);
const Emoji = sdk.getComponent("emojipicker.Emoji");
return (<div key={rowIndex}>{
emojisForRow.map(emoji =>
<Emoji key={emoji.hexcode} emoji={emoji} selectedEmojis={selectedEmojis}
onClick={onClick} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />)
emojisForRow.map(emoji => ((
<Emoji
key={emoji.hexcode}
emoji={emoji}
selectedEmojis={selectedEmojis}
onClick={onClick}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
/>
)))
}</div>);
};
@ -52,7 +74,6 @@ class Category extends React.PureComponent {
for (let counter = 0; counter < rows.length; ++counter) {
rows[counter] = counter;
}
const LazyRenderList = sdk.getComponent('elements.LazyRenderList');
const viewportTop = scrollTop;
const viewportBottom = viewportTop + viewportHeight;
@ -84,7 +105,7 @@ class Category extends React.PureComponent {
height={localHeight}
overflowItems={OVERFLOW_ROWS}
overflowMargin={0}
renderItem={this._renderEmojiRow}>
renderItem={this.renderEmojiRow}>
</LazyRenderList>
</section>
);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,18 +16,19 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import {MenuItem} from "../../structures/ContextMenu";
import {IEmoji} from "../../../emoji";
class Emoji extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
emoji: PropTypes.object.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
interface IProps {
emoji: IEmoji;
selectedEmojis?: Set<string>;
onClick(emoji: IEmoji): void;
onMouseEnter(emoji: IEmoji): void;
onMouseLeave(emoji: IEmoji): void;
}
class Emoji extends React.PureComponent<IProps> {
render() {
const { onClick, onMouseEnter, onMouseLeave, emoji, selectedEmojis } = this.props;
const isSelected = selectedEmojis && selectedEmojis.has(emoji.unicode);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,25 +16,43 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import * as recent from '../../../emojipicker/recent';
import {DATA_BY_CATEGORY, getEmojiFromUnicode} from "../../../emoji";
import {DATA_BY_CATEGORY, getEmojiFromUnicode, IEmoji} from "../../../emoji";
import AutoHideScrollbar from "../../structures/AutoHideScrollbar";
import Header from "./Header";
import Search from "./Search";
import Preview from "./Preview";
import QuickReactions from "./QuickReactions";
import Category, {ICategory, CategoryKey} from "./Category";
export const CATEGORY_HEADER_HEIGHT = 22;
export const EMOJI_HEIGHT = 37;
export const EMOJIS_PER_ROW = 8;
class EmojiPicker extends React.Component {
static propTypes = {
onChoose: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
showQuickReactions: PropTypes.bool,
};
interface IProps {
selectedEmojis: Set<string>;
showQuickReactions?: boolean;
onChoose(unicode: string): boolean;
}
interface IState {
filter: string;
previewEmoji?: IEmoji;
scrollTop: number;
// initial estimation of height, dialog is hardcoded to 450px height.
// should be enough to never have blank rows of emojis as
// 3 rows of overflow are also rendered. The actual value is updated on scroll.
viewportHeight: number;
}
class EmojiPicker extends React.Component<IProps, IState> {
private readonly recentlyUsed: IEmoji[];
private readonly memoizedDataByCategory: Record<CategoryKey, IEmoji[]>;
private readonly categories: ICategory[];
private bodyRef = React.createRef<HTMLDivElement>();
constructor(props) {
super(props);
@ -42,9 +61,6 @@ class EmojiPicker extends React.Component {
filter: "",
previewEmoji: null,
scrollTop: 0,
// initial estimation of height, dialog is hardcoded to 450px height.
// should be enough to never have blank rows of emojis as
// 3 rows of overflow are also rendered. The actual value is updated on scroll.
viewportHeight: 280,
};
@ -110,18 +126,9 @@ class EmojiPicker extends React.Component {
visible: false,
ref: React.createRef(),
}];
this.bodyRef = React.createRef();
this.onChangeFilter = this.onChangeFilter.bind(this);
this.onHoverEmoji = this.onHoverEmoji.bind(this);
this.onHoverEmojiEnd = this.onHoverEmojiEnd.bind(this);
this.onClickEmoji = this.onClickEmoji.bind(this);
this.scrollToCategory = this.scrollToCategory.bind(this);
this.updateVisibility = this.updateVisibility.bind(this);
}
onScroll = () => {
private onScroll = () => {
const body = this.bodyRef.current;
this.setState({
scrollTop: body.scrollTop,
@ -130,7 +137,7 @@ class EmojiPicker extends React.Component {
this.updateVisibility();
};
updateVisibility() {
private updateVisibility = () => {
const body = this.bodyRef.current;
const rect = body.getBoundingClientRect();
for (const cat of this.categories) {
@ -147,21 +154,21 @@ class EmojiPicker extends React.Component {
// We update this here instead of through React to avoid re-render on scroll.
if (cat.visible) {
cat.ref.current.classList.add("mx_EmojiPicker_anchor_visible");
cat.ref.current.setAttribute("aria-selected", true);
cat.ref.current.setAttribute("tabindex", 0);
cat.ref.current.setAttribute("aria-selected", "true");
cat.ref.current.setAttribute("tabindex", "0");
} else {
cat.ref.current.classList.remove("mx_EmojiPicker_anchor_visible");
cat.ref.current.setAttribute("aria-selected", false);
cat.ref.current.setAttribute("tabindex", -1);
cat.ref.current.setAttribute("aria-selected", "false");
cat.ref.current.setAttribute("tabindex", "-1");
}
}
}
};
scrollToCategory(category) {
private scrollToCategory = (category: string) => {
this.bodyRef.current.querySelector(`[data-category-id="${category}"]`).scrollIntoView();
}
};
onChangeFilter(filter) {
private onChangeFilter = (filter: string) => {
filter = filter.toLowerCase(); // filter is case insensitive stored lower-case
for (const cat of this.categories) {
let emojis;
@ -181,27 +188,34 @@ class EmojiPicker extends React.Component {
// Header underlines need to be updated, but updating requires knowing
// where the categories are, so we wait for a tick.
setTimeout(this.updateVisibility, 0);
}
};
onHoverEmoji(emoji) {
private onEnterFilter = () => {
const btn = this.bodyRef.current.querySelector<HTMLButtonElement>(".mx_EmojiPicker_item");
if (btn) {
btn.click();
}
};
private onHoverEmoji = (emoji: IEmoji) => {
this.setState({
previewEmoji: emoji,
});
}
};
onHoverEmojiEnd(emoji) {
private onHoverEmojiEnd = (emoji: IEmoji) => {
this.setState({
previewEmoji: null,
});
}
};
onClickEmoji(emoji) {
private onClickEmoji = (emoji: IEmoji) => {
if (this.props.onChoose(emoji.unicode) !== false) {
recent.add(emoji.unicode);
}
}
};
_categoryHeightForEmojiCount(count) {
private static categoryHeightForEmojiCount(count: number) {
if (count === 0) {
return 0;
}
@ -209,25 +223,37 @@ class EmojiPicker extends React.Component {
}
render() {
const Header = sdk.getComponent("emojipicker.Header");
const Search = sdk.getComponent("emojipicker.Search");
const Category = sdk.getComponent("emojipicker.Category");
const Preview = sdk.getComponent("emojipicker.Preview");
const QuickReactions = sdk.getComponent("emojipicker.QuickReactions");
let heightBefore = 0;
return (
<div className="mx_EmojiPicker">
<Header categories={this.categories} defaultCategory="recent" onAnchorClick={this.scrollToCategory} />
<Search query={this.state.filter} onChange={this.onChangeFilter} />
<AutoHideScrollbar className="mx_EmojiPicker_body" wrappedRef={e => this.bodyRef.current = e} onScroll={this.onScroll}>
<Header categories={this.categories} onAnchorClick={this.scrollToCategory} />
<Search query={this.state.filter} onChange={this.onChangeFilter} onEnter={this.onEnterFilter} />
<AutoHideScrollbar
className="mx_EmojiPicker_body"
wrappedRef={ref => {
// @ts-ignore - AutoHideScrollbar should accept a RefObject or fall back to its own instead
this.bodyRef.current = ref
}}
onScroll={this.onScroll}
>
{this.categories.map(category => {
const emojis = this.memoizedDataByCategory[category.id];
const categoryElement = (<Category key={category.id} id={category.id} name={category.name}
heightBefore={heightBefore} viewportHeight={this.state.viewportHeight}
scrollTop={this.state.scrollTop} emojis={emojis} onClick={this.onClickEmoji}
onMouseEnter={this.onHoverEmoji} onMouseLeave={this.onHoverEmojiEnd}
selectedEmojis={this.props.selectedEmojis} />);
const height = this._categoryHeightForEmojiCount(emojis.length);
const categoryElement = ((
<Category
key={category.id}
id={category.id}
name={category.name}
heightBefore={heightBefore}
viewportHeight={this.state.viewportHeight}
scrollTop={this.state.scrollTop}
emojis={emojis}
onClick={this.onClickEmoji}
onMouseEnter={this.onHoverEmoji}
onMouseLeave={this.onHoverEmojiEnd}
selectedEmojis={this.props.selectedEmojis}
/>
));
const height = EmojiPicker.categoryHeightForEmojiCount(emojis.length);
heightBefore += height;
return categoryElement;
})}

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,19 +16,19 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from "classnames";
import {_t} from "../../../languageHandler";
import {Key} from "../../../Keyboard";
import {CategoryKey, ICategory} from "./Category";
class Header extends React.PureComponent {
static propTypes = {
categories: PropTypes.arrayOf(PropTypes.object).isRequired,
onAnchorClick: PropTypes.func.isRequired,
};
interface IProps {
categories: ICategory[];
onAnchorClick(id: CategoryKey): void
}
findNearestEnabled(index, delta) {
class Header extends React.PureComponent<IProps> {
private findNearestEnabled(index: number, delta: number) {
index += this.props.categories.length;
const cats = [...this.props.categories, ...this.props.categories, ...this.props.categories];
@ -37,12 +38,12 @@ class Header extends React.PureComponent {
}
}
changeCategoryRelative(delta) {
private changeCategoryRelative(delta: number) {
const current = this.props.categories.findIndex(c => c.visible);
this.changeCategoryAbsolute(current + delta, delta);
}
changeCategoryAbsolute(index, delta=1) {
private changeCategoryAbsolute(index: number, delta=1) {
const category = this.props.categories[this.findNearestEnabled(index, delta)];
if (category) {
this.props.onAnchorClick(category.id);
@ -52,7 +53,7 @@ class Header extends React.PureComponent {
// Implements ARIA Tabs with Automatic Activation pattern
// https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-1/tabs.html
onKeyDown = (ev) => {
private onKeyDown = (ev: React.KeyboardEvent) => {
let handled = true;
switch (ev.key) {
case Key.ARROW_LEFT:
@ -80,7 +81,12 @@ class Header extends React.PureComponent {
render() {
return (
<nav className="mx_EmojiPicker_header" role="tablist" aria-label={_t("Categories")} onKeyDown={this.onKeyDown}>
<nav
className="mx_EmojiPicker_header"
role="tablist"
aria-label={_t("Categories")}
onKeyDown={this.onKeyDown}
>
{this.props.categories.map(category => {
const classes = classNames(`mx_EmojiPicker_anchor mx_EmojiPicker_anchor_${category.id}`, {
mx_EmojiPicker_anchor_visible: category.visible,

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,19 +16,21 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
class Preview extends React.PureComponent {
static propTypes = {
emoji: PropTypes.object,
};
import {IEmoji} from "../../../emoji";
interface IProps {
emoji: IEmoji;
}
class Preview extends React.PureComponent<IProps> {
render() {
const {
unicode = "",
annotation = "",
shortcodes: [shortcode = ""],
} = this.props.emoji || {};
return (
<div className="mx_EmojiPicker_footer mx_EmojiPicker_preview">
<div className="mx_EmojiPicker_preview_emoji">

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,11 +16,10 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import {getEmojiFromUnicode} from "../../../emoji";
import {getEmojiFromUnicode, IEmoji} from "../../../emoji";
import Emoji from "./Emoji";
// We use the variation-selector Heart in Quick Reactions for some reason
const QUICK_REACTIONS = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀", "👀"].map(emoji => {
@ -30,36 +30,36 @@ const QUICK_REACTIONS = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀
return data;
});
class QuickReactions extends React.Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
interface IProps {
selectedEmojis?: Set<string>;
onClick(emoji: IEmoji): void;
}
interface IState {
hover?: IEmoji;
}
class QuickReactions extends React.Component<IProps, IState> {
constructor(props) {
super(props);
this.state = {
hover: null,
};
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
}
onMouseEnter(emoji) {
private onMouseEnter = (emoji: IEmoji) => {
this.setState({
hover: emoji,
});
}
};
onMouseLeave() {
private onMouseLeave = () => {
this.setState({
hover: null,
});
}
};
render() {
const Emoji = sdk.getComponent("emojipicker.Emoji");
return (
<section className="mx_EmojiPicker_footer mx_EmojiPicker_quick mx_EmojiPicker_category">
<h2 className="mx_EmojiPicker_quick_header mx_EmojiPicker_category_label">
@ -72,10 +72,16 @@ class QuickReactions extends React.Component {
}
</h2>
<ul className="mx_EmojiPicker_list" aria-label={_t("Quick Reactions")}>
{QUICK_REACTIONS.map(emoji => <Emoji
key={emoji.hexcode} emoji={emoji} onClick={this.props.onClick}
onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}
selectedEmojis={this.props.selectedEmojis} />)}
{QUICK_REACTIONS.map(emoji => ((
<Emoji
key={emoji.hexcode}
emoji={emoji}
onClick={this.props.onClick}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
selectedEmojis={this.props.selectedEmojis}
/>
)))}
</ul>
</section>
);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,26 +16,29 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from "prop-types";
import {MatrixEvent} from "matrix-js-sdk/src/models/event";
import EmojiPicker from "./EmojiPicker";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import dis from "../../../dispatcher/dispatcher";
class ReactionPicker extends React.Component {
static propTypes = {
mxEvent: PropTypes.object.isRequired,
onFinished: PropTypes.func.isRequired,
reactions: PropTypes.object,
};
interface IProps {
mxEvent: MatrixEvent;
reactions: any; // TODO type this once js-sdk is more typescripted
onFinished(): void;
}
interface IState {
selectedEmojis: Set<string>;
}
class ReactionPicker extends React.Component<IProps, IState> {
constructor(props) {
super(props);
this.state = {
selectedEmojis: new Set(Object.keys(this.getReactions())),
};
this.onChoose = this.onChoose.bind(this);
this.onReactionsChange = this.onReactionsChange.bind(this);
this.addListeners();
}
@ -45,7 +49,7 @@ class ReactionPicker extends React.Component {
}
}
addListeners() {
private addListeners() {
if (this.props.reactions) {
this.props.reactions.on("Relations.add", this.onReactionsChange);
this.props.reactions.on("Relations.remove", this.onReactionsChange);
@ -55,22 +59,13 @@ class ReactionPicker extends React.Component {
componentWillUnmount() {
if (this.props.reactions) {
this.props.reactions.removeListener(
"Relations.add",
this.onReactionsChange,
);
this.props.reactions.removeListener(
"Relations.remove",
this.onReactionsChange,
);
this.props.reactions.removeListener(
"Relations.redaction",
this.onReactionsChange,
);
this.props.reactions.removeListener("Relations.add", this.onReactionsChange);
this.props.reactions.removeListener("Relations.remove", this.onReactionsChange);
this.props.reactions.removeListener("Relations.redaction", this.onReactionsChange);
}
}
getReactions() {
private getReactions() {
if (!this.props.reactions) {
return {};
}
@ -81,13 +76,13 @@ class ReactionPicker extends React.Component {
.map(event => [event.getRelation().key, event.getId()]));
}
onReactionsChange() {
private onReactionsChange = () => {
this.setState({
selectedEmojis: new Set(Object.keys(this.getReactions())),
});
}
};
onChoose(reaction) {
onChoose = (reaction: string) => {
this.componentWillUnmount();
this.props.onFinished();
const myReactions = this.getReactions();
@ -109,7 +104,7 @@ class ReactionPicker extends React.Component {
dis.dispatch({action: "message_sent"});
return true;
}
}
};
render() {
return <EmojiPicker

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,32 +16,41 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import {Key} from "../../../Keyboard";
class Search extends React.PureComponent {
static propTypes = {
query: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
interface IProps {
query: string;
onChange(value: string): void;
onEnter(): void;
}
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
class Search extends React.PureComponent<IProps> {
private inputRef = React.createRef<HTMLInputElement>();
componentDidMount() {
// For some reason, neither the autoFocus nor just calling focus() here worked, so here's a setTimeout
setTimeout(() => this.inputRef.current.focus(), 0);
}
private onKeyDown = (ev: React.KeyboardEvent) => {
if (ev.key === Key.ENTER) {
this.props.onEnter();
ev.stopPropagation();
ev.preventDefault();
}
};
render() {
let rightButton;
if (this.props.query) {
rightButton = (
<button onClick={() => this.props.onChange("")}
className="mx_EmojiPicker_search_icon mx_EmojiPicker_search_clear"
title={_t("Cancel search")} />
<button
onClick={() => this.props.onChange("")}
className="mx_EmojiPicker_search_icon mx_EmojiPicker_search_clear"
title={_t("Cancel search")}
/>
);
} else {
rightButton = <span className="mx_EmojiPicker_search_icon" />;
@ -48,8 +58,15 @@ class Search extends React.PureComponent {
return (
<div className="mx_EmojiPicker_search">
<input autoFocus type="text" placeholder="Search" value={this.props.query}
onChange={ev => this.props.onChange(ev.target.value)} ref={this.inputRef} />
<input
autoFocus
type="text"
placeholder="Search"
value={this.props.query}
onChange={ev => this.props.onChange(ev.target.value)}
onKeyDown={this.onKeyDown}
ref={this.inputRef}
/>
{rightButton}
</div>
);

View file

@ -25,10 +25,8 @@ export default class EncryptionEvent extends React.Component {
let body;
let classes = "mx_EventTile_bubble mx_cryptoEvent mx_cryptoEvent_icon";
if (
mxEvent.getContent().algorithm === 'm.megolm.v1.aes-sha2' &&
MatrixClientPeg.get().isRoomEncrypted(mxEvent.getRoomId())
) {
const isRoomEncrypted = MatrixClientPeg.get().isRoomEncrypted(mxEvent.getRoomId());
if (mxEvent.getContent().algorithm === 'm.megolm.v1.aes-sha2' && isRoomEncrypted) {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption enabled")}</div>
<div className="mx_cryptoEvent_subtitle">
@ -38,6 +36,13 @@ export default class EncryptionEvent extends React.Component {
)}
</div>
</div>;
} else if (isRoomEncrypted) {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption enabled")}</div>
<div className="mx_cryptoEvent_subtitle">
{_t("Ignored attempt to disable encryption")}
</div>
</div>;
} else {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption not enabled")}</div>

View file

@ -0,0 +1,76 @@
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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 { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { _t } from "../../../languageHandler";
import WidgetStore from "../../../stores/WidgetStore";
interface IProps {
mxEvent: MatrixEvent;
}
export default class MJitsiWidgetEvent extends React.PureComponent<IProps> {
constructor(props) {
super(props);
}
render() {
const url = this.props.mxEvent.getContent()['url'];
const prevUrl = this.props.mxEvent.getPrevContent()['url'];
const senderName = this.props.mxEvent.sender?.name || this.props.mxEvent.getSender();
let joinCopy = _t('Join the conference at the top of this room');
if (!WidgetStore.instance.isPinned(this.props.mxEvent.getStateKey())) {
joinCopy = _t('Join the conference from the room information card on the right');
}
if (!url) {
// removed
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t('Video conference ended by %(senderName)s', {senderName})}
</div>
</div>
);
} else if (prevUrl) {
// modified
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t('Video conference updated by %(senderName)s', {senderName})}
</div>
<div className='mx_MJitsiWidgetEvent_subtitle'>
{joinCopy}
</div>
</div>
);
} else {
// assume added
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t("Video conference started by %(senderName)s", {senderName})}
</div>
<div className='mx_MJitsiWidgetEvent_subtitle'>
{joinCopy}
</div>
</div>
);
}
}
}

View file

@ -45,7 +45,7 @@ export default class RoomCreate extends React.Component {
render() {
const predecessor = this.props.mxEvent.getContent()['predecessor'];
if (predecessor === undefined) {
return <div />; // We should never have been instaniated in this case
return <div />; // We should never have been instantiated in this case
}
const prevRoom = MatrixClientPeg.get().getRoom(predecessor['room_id']);
const permalinkCreator = new RoomPermalinkCreator(prevRoom, predecessor['room_id']);

View file

@ -401,7 +401,8 @@ export default class TextualBody extends React.Component {
const mxEvent = this.props.mxEvent;
const content = mxEvent.getContent();
const stripReply = ReplyThread.getParentEventId(mxEvent);
// only strip reply if this is the original replying event, edits thereafter do not have the fallback
const stripReply = !mxEvent.replacingEvent() && ReplyThread.getParentEventId(mxEvent);
let body = HtmlUtils.bodyToHtml(content, this.props.highlights, {
disableBigEmoji: content.msgtype === "m.emote" || !SettingsStore.getValue('TextualBody.enableBigEmoji'),
// Part of Replies fallback support

View file

@ -31,6 +31,7 @@ interface IProps {
className?: string;
withoutScrollContainer?: boolean;
previousPhase?: RightPanelPhases;
closeLabel?: string;
onClose?(): void;
}
@ -47,6 +48,7 @@ export const Group: React.FC<IGroupProps> = ({ className, title, children }) =>
};
const BaseCard: React.FC<IProps> = ({
closeLabel,
onClose,
className,
header,
@ -68,7 +70,11 @@ const BaseCard: React.FC<IProps> = ({
let closeButton;
if (onClose) {
closeButton = <AccessibleButton className="mx_BaseCard_close" onClick={onClose} title={_t("Close")} />;
closeButton = <AccessibleButton
className="mx_BaseCard_close"
onClick={onClose}
title={closeLabel || _t("Close")}
/>;
}
if (!withoutScrollContainer) {

View file

@ -27,6 +27,9 @@ import * as sdk from "../../../index";
import {_t} from "../../../languageHandler";
import {VerificationRequest} from "matrix-js-sdk/src/crypto/verification/request/VerificationRequest";
import {RoomMember} from "matrix-js-sdk/src/models/room-member";
import dis from "../../../dispatcher/dispatcher";
import {Action} from "../../../dispatcher/actions";
import {RightPanelPhases} from "../../../stores/RightPanelStorePhases";
// cancellation codes which constitute a key mismatch
const MISMATCHES = ["m.key_mismatch", "m.user_error", "m.mismatched_sas"];
@ -42,7 +45,14 @@ interface IProps {
}
const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
const {verificationRequest, verificationRequestPromise, member, onClose, layout, isRoomEncrypted} = props;
const {
verificationRequest,
verificationRequestPromise,
member,
onClose,
layout,
isRoomEncrypted,
} = props;
const [request, setRequest] = useState(verificationRequest);
// state to show a spinner immediately after clicking "start verification",
// before we have a request
@ -95,22 +105,6 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
}, [onClose, request]);
useEventEmitter(request, "change", changeHandler);
const onCancel = useCallback(function() {
if (request) {
request.cancel();
}
}, [request]);
let cancelButton: JSX.Element;
if (layout !== "dialog" && request && request.pending) {
const AccessibleButton = sdk.getComponent("elements.AccessibleButton");
cancelButton = (<AccessibleButton
className="mx_EncryptionPanel_cancel"
onClick={onCancel}
title={_t('Cancel')}
></AccessibleButton>);
}
const onStartVerification = useCallback(async () => {
setRequesting(true);
const cli = MatrixClientPeg.get();
@ -118,7 +112,13 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
const verificationRequest_ = await cli.requestVerificationDM(member.userId, roomId);
setRequest(verificationRequest_);
setPhase(verificationRequest_.phase);
}, [member.userId]);
// Notify the RightPanelStore about this
dis.dispatch({
action: Action.SetRightPanelPhase,
phase: RightPanelPhases.EncryptionPanel,
refireParams: { member, verificationRequest: verificationRequest_ },
});
}, [member]);
const requested =
(!request && isRequesting) ||
@ -128,8 +128,7 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
member.userId === MatrixClientPeg.get().getUserId();
if (!request || requested) {
const initiatedByMe = (!request && isRequesting) || (request && request.initiatedByMe);
return (<React.Fragment>
{cancelButton}
return (
<EncryptionInfo
isRoomEncrypted={isRoomEncrypted}
onStartVerification={onStartVerification}
@ -138,10 +137,9 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
waitingForOtherParty={requested && initiatedByMe}
waitingForNetwork={requested && !initiatedByMe}
inDialog={layout === "dialog"} />
</React.Fragment>);
);
} else {
return (<React.Fragment>
{cancelButton}
return (
<VerificationPanel
isRoomEncrypted={isRoomEncrypted}
layout={layout}
@ -152,7 +150,7 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
inDialog={layout === "dialog"}
phase={phase}
/>
</React.Fragment>);
);
}
};

View file

@ -31,7 +31,7 @@ interface IProps {
// The badge to display above the icon
badge?: React.ReactNode;
// The parameters to track the click event
analytics: string[];
analytics: Parameters<typeof Analytics.trackEvent>;
// Button name
name: string;

View file

@ -17,20 +17,22 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {useCallback, useMemo, useState, useEffect, useContext} from 'react';
import PropTypes from 'prop-types';
import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react';
import classNames from 'classnames';
import {Group, RoomMember, User, Room} from 'matrix-js-sdk';
import {MatrixClient} from 'matrix-js-sdk/src/client';
import {RoomMember} from 'matrix-js-sdk/src/models/room-member';
import {User} from 'matrix-js-sdk/src/models/user';
import {Room} from 'matrix-js-sdk/src/models/room';
import {EventTimeline} from 'matrix-js-sdk/src/models/event-timeline';
import dis from '../../../dispatcher/dispatcher';
import Modal from '../../../Modal';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import {_t} from '../../../languageHandler';
import createRoom, {privateShouldBeEncrypted} from '../../../createRoom';
import DMRoomMap from '../../../utils/DMRoomMap';
import AccessibleButton from '../elements/AccessibleButton';
import SdkConfig from '../../../SdkConfig';
import SettingsStore from "../../../settings/SettingsStore";
import {EventTimeline} from "matrix-js-sdk";
import RoomViewStore from "../../../stores/RoomViewStore";
import MultiInviter from "../../../utils/MultiInviter";
import GroupStore from "../../../stores/GroupStore";
@ -41,13 +43,31 @@ import {textualPowerLevel} from '../../../Roles';
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {RightPanelPhases} from "../../../stores/RightPanelStorePhases";
import EncryptionPanel from "./EncryptionPanel";
import { useAsyncMemo } from '../../../hooks/useAsyncMemo';
import { verifyUser, legacyVerifyUser, verifyDevice } from '../../../verification';
import {useAsyncMemo} from '../../../hooks/useAsyncMemo';
import {legacyVerifyUser, verifyDevice, verifyUser} from '../../../verification';
import {Action} from "../../../dispatcher/actions";
import {useIsEncrypted} from "../../../hooks/useIsEncrypted";
import BaseCard from "./BaseCard";
import {E2EStatus} from "../../../utils/ShieldUtils";
import ImageView from "../elements/ImageView";
import Spinner from "../elements/Spinner";
import IconButton from "../elements/IconButton";
import PowerSelector from "../elements/PowerSelector";
import MemberAvatar from "../avatars/MemberAvatar";
import PresenceLabel from "../rooms/PresenceLabel";
import ShareDialog from "../dialogs/ShareDialog";
import ErrorDialog from "../dialogs/ErrorDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
import ConfirmUserActionDialog from "../dialogs/ConfirmUserActionDialog";
import InfoDialog from "../dialogs/InfoDialog";
const _disambiguateDevices = (devices) => {
interface IDevice {
deviceId: string;
ambiguous?: boolean;
getDisplayName(): string;
}
const disambiguateDevices = (devices: IDevice[]) => {
const names = Object.create(null);
for (let i = 0; i < devices.length; i++) {
const name = devices[i].getDisplayName();
@ -64,11 +84,11 @@ const _disambiguateDevices = (devices) => {
}
};
export const getE2EStatus = (cli, userId, devices) => {
export const getE2EStatus = (cli: MatrixClient, userId: string, devices: IDevice[]): E2EStatus => {
const isMe = userId === cli.getUserId();
const userTrust = cli.checkUserTrust(userId);
if (!userTrust.isCrossSigningVerified()) {
return userTrust.wasCrossSigningVerified() ? "warning" : "normal";
return userTrust.wasCrossSigningVerified() ? E2EStatus.Warning : E2EStatus.Normal;
}
const anyDeviceUnverified = devices.some(device => {
@ -81,10 +101,10 @@ export const getE2EStatus = (cli, userId, devices) => {
const deviceTrust = cli.checkDeviceTrust(userId, deviceId);
return isMe ? !deviceTrust.isCrossSigningVerified() : !deviceTrust.isVerified();
});
return anyDeviceUnverified ? "warning" : "verified";
return anyDeviceUnverified ? E2EStatus.Warning : E2EStatus.Verified;
};
async function openDMForUser(matrixClient, userId) {
async function openDMForUser(matrixClient: MatrixClient, userId: string) {
const dmRooms = DMRoomMap.shared().getDMRoomsForUserId(userId);
const lastActiveRoom = dmRooms.reduce((lastActiveRoom, roomId) => {
const room = matrixClient.getRoom(roomId);
@ -107,6 +127,7 @@ async function openDMForUser(matrixClient, userId) {
const createRoomOptions = {
dmUserId: userId,
encryption: undefined,
};
if (privateShouldBeEncrypted()) {
@ -122,10 +143,12 @@ async function openDMForUser(matrixClient, userId) {
}
}
createRoom(createRoomOptions);
return createRoom(createRoomOptions);
}
function useHasCrossSigningKeys(cli, member, canVerify, setUpdating) {
type SetUpdating = (updating: boolean) => void;
function useHasCrossSigningKeys(cli: MatrixClient, member: RoomMember, canVerify: boolean, setUpdating: SetUpdating) {
return useAsyncMemo(async () => {
if (!canVerify) {
return undefined;
@ -142,7 +165,7 @@ function useHasCrossSigningKeys(cli, member, canVerify, setUpdating) {
}, [cli, member, canVerify], undefined);
}
function DeviceItem({userId, device}) {
function DeviceItem({userId, device}: {userId: string, device: IDevice}) {
const cli = useContext(MatrixClientContext);
const isMe = userId === cli.getUserId();
const deviceTrust = cli.checkDeviceTrust(userId, device.deviceId);
@ -169,8 +192,8 @@ function DeviceItem({userId, device}) {
};
const deviceName = device.ambiguous ?
(device.getDisplayName() ? device.getDisplayName() : "") + " (" + device.deviceId + ")" :
device.getDisplayName();
(device.getDisplayName() ? device.getDisplayName() : "") + " (" + device.deviceId + ")" :
device.getDisplayName();
let trustedLabel = null;
if (userTrust.isVerified()) trustedLabel = isVerified ? _t("Trusted") : _t("Not trusted");
@ -198,8 +221,7 @@ function DeviceItem({userId, device}) {
}
}
function DevicesSection({devices, userId, loading}) {
const Spinner = sdk.getComponent("elements.Spinner");
function DevicesSection({devices, userId, loading}: {devices: IDevice[], userId: string, loading: boolean}) {
const cli = useContext(MatrixClientContext);
const userTrust = cli.checkUserTrust(userId);
@ -210,7 +232,7 @@ function DevicesSection({devices, userId, loading}) {
return <Spinner />;
}
if (devices === null) {
return _t("Unable to load session list");
return <>{_t("Unable to load session list")}</>;
}
const isMe = userId === cli.getUserId();
const deviceTrusts = devices.map(d => cli.checkDeviceTrust(userId, d.deviceId));
@ -285,7 +307,11 @@ function DevicesSection({devices, userId, loading}) {
);
}
const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
const UserOptionsSection: React.FC<{
member: RoomMember;
isIgnored: boolean;
canInvite: boolean;
}> = ({member, isIgnored, canInvite}) => {
const cli = useContext(MatrixClientContext);
let ignoreButton = null;
@ -296,7 +322,6 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
const isMe = member.userId === cli.getUserId();
const onShareUserClick = () => {
const ShareDialog = sdk.getComponent("dialogs.ShareDialog");
Modal.createTrackedDialog('share room member dialog', '', ShareDialog, {
target: member,
});
@ -318,7 +343,10 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
};
ignoreButton = (
<AccessibleButton onClick={onIgnoreToggle} className={classNames("mx_UserInfo_field", {mx_UserInfo_destructive: !isIgnored})}>
<AccessibleButton
onClick={onIgnoreToggle}
className={classNames("mx_UserInfo_field", {mx_UserInfo_destructive: !isIgnored})}
>
{ isIgnored ? _t("Unignore") : _t("Ignore") }
</AccessibleButton>
);
@ -341,11 +369,14 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
});
};
readReceiptButton = (
<AccessibleButton onClick={onReadReceiptButton} className="mx_UserInfo_field">
{ _t('Jump to read receipt') }
</AccessibleButton>
);
const room = cli.getRoom(member.roomId);
if (room?.getEventReadUpTo(member.userId)) {
readReceiptButton = (
<AccessibleButton onClick={onReadReceiptButton} className="mx_UserInfo_field">
{ _t('Jump to read receipt') }
</AccessibleButton>
);
}
insertPillButton = (
<AccessibleButton onClick={onInsertPillButton} className={"mx_UserInfo_field"}>
@ -367,7 +398,6 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
}
});
} catch (err) {
const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
Modal.createTrackedDialog('Failed to invite', '', ErrorDialog, {
title: _t('Failed to invite'),
description: ((err && err.message) ? err.message : _t("Operation failed")),
@ -413,8 +443,7 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
);
};
const _warnSelfDemote = async () => {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const warnSelfDemote = async () => {
const {finished} = Modal.createTrackedDialog('Demoting Self', '', QuestionDialog, {
title: _t("Demote yourself?"),
description:
@ -430,7 +459,7 @@ const _warnSelfDemote = async () => {
return confirmed;
};
const GenericAdminToolsContainer = ({children}) => {
const GenericAdminToolsContainer: React.FC<{}> = ({children}) => {
return (
<div className="mx_UserInfo_container">
<h3>{ _t("Admin Tools") }</h3>
@ -441,7 +470,20 @@ const GenericAdminToolsContainer = ({children}) => {
);
};
const _isMuted = (member, powerLevelContent) => {
interface IPowerLevelsContent {
events?: Record<string, number>;
// eslint-disable-next-line camelcase
users_default?: number;
// eslint-disable-next-line camelcase
events_default?: number;
// eslint-disable-next-line camelcase
state_default?: number;
ban?: number;
kick?: number;
redact?: number;
}
const isMuted = (member: RoomMember, powerLevelContent: IPowerLevelsContent) => {
if (!powerLevelContent || !member) return false;
const levelToSend = (
@ -451,8 +493,8 @@ const _isMuted = (member, powerLevelContent) => {
return member.powerLevel < levelToSend;
};
export const useRoomPowerLevels = (cli, room) => {
const [powerLevels, setPowerLevels] = useState({});
export const useRoomPowerLevels = (cli: MatrixClient, room: Room) => {
const [powerLevels, setPowerLevels] = useState<IPowerLevelsContent>({});
const update = useCallback(() => {
if (!room) {
@ -479,14 +521,19 @@ export const useRoomPowerLevels = (cli, room) => {
return powerLevels;
};
const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
interface IBaseProps {
member: RoomMember;
startUpdating(): void;
stopUpdating(): void;
}
const RoomKickButton: React.FC<IBaseProps> = ({member, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
// check if user can be kicked/disinvited
if (member.membership !== "invite" && member.membership !== "join") return null;
const onKick = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const {finished} = Modal.createTrackedDialog(
'Confirm User Action Dialog',
'onKick',
@ -509,7 +556,6 @@ const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
// get out of sync if we force setState here!
console.log("Kick success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Kick error: " + err);
Modal.createTrackedDialog('Failed to kick', '', ErrorDialog, {
title: _t("Failed to kick"),
@ -526,7 +572,7 @@ const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
</AccessibleButton>;
};
const RedactMessagesButton = ({member}) => {
const RedactMessagesButton: React.FC<IBaseProps> = ({member}) => {
const cli = useContext(MatrixClientContext);
const onRedactAllMessages = async () => {
@ -554,7 +600,6 @@ const RedactMessagesButton = ({member}) => {
const user = member.name;
if (count === 0) {
const InfoDialog = sdk.getComponent("dialogs.InfoDialog");
Modal.createTrackedDialog('No user messages found to remove', '', InfoDialog, {
title: _t("No recent messages by %(user)s found", {user}),
description:
@ -563,14 +608,14 @@ const RedactMessagesButton = ({member}) => {
</div>,
});
} else {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const {finished} = Modal.createTrackedDialog('Remove recent messages by user', '', QuestionDialog, {
title: _t("Remove recent messages by %(user)s", {user}),
description:
<div>
<p>{ _t("You are about to remove %(count)s messages by %(user)s. This cannot be undone. Do you wish to continue?", {count, user}) }</p>
<p>{ _t("For a large amount of messages, this might take some time. Please don't refresh your client in the meantime.") }</p>
<p>{ _t("You are about to remove %(count)s messages by %(user)s. " +
"This cannot be undone. Do you wish to continue?", {count, user}) }</p>
<p>{ _t("For a large amount of messages, this might take some time. " +
"Please don't refresh your client in the meantime.") }</p>
</div>,
button: _t("Remove %(count)s messages", {count}),
});
@ -603,11 +648,10 @@ const RedactMessagesButton = ({member}) => {
</AccessibleButton>;
};
const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
const BanToggleButton: React.FC<IBaseProps> = ({member, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
const onBanOrUnban = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const {finished} = Modal.createTrackedDialog(
'Confirm User Action Dialog',
'onBanOrUnban',
@ -636,7 +680,6 @@ const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
// get out of sync if we force setState here!
console.log("Ban success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Ban error: " + err);
Modal.createTrackedDialog('Failed to ban user', '', ErrorDialog, {
title: _t("Error"),
@ -661,22 +704,26 @@ const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
</AccessibleButton>;
};
const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdating}) => {
interface IBaseRoomProps extends IBaseProps {
room: Room;
powerLevels: IPowerLevelsContent;
}
const MuteToggleButton: React.FC<IBaseRoomProps> = ({member, room, powerLevels, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
// Don't show the mute/unmute option if the user is not in the room
if (member.membership !== "join") return null;
const isMuted = _isMuted(member, powerLevels);
const muted = isMuted(member, powerLevels);
const onMuteToggle = async () => {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const roomId = member.roomId;
const target = member.userId;
// if muting self, warn as it may be irreversible
if (target === cli.getUserId()) {
try {
if (!(await _warnSelfDemote())) return;
if (!(await warnSelfDemote())) return;
} catch (e) {
console.error("Failed to warn about self demotion: ", e);
return;
@ -692,7 +739,7 @@ const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdatin
powerLevels.events_default
);
let level;
if (isMuted) { // unmute
if (muted) { // unmute
level = levelToSend;
} else { // mute
level = levelToSend - 1;
@ -718,16 +765,23 @@ const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdatin
};
const classes = classNames("mx_UserInfo_field", {
mx_UserInfo_destructive: !isMuted,
mx_UserInfo_destructive: !muted,
});
const muteLabel = isMuted ? _t("Unmute") : _t("Mute");
const muteLabel = muted ? _t("Unmute") : _t("Mute");
return <AccessibleButton className={classes} onClick={onMuteToggle}>
{ muteLabel }
</AccessibleButton>;
};
const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpdating, powerLevels}) => {
const RoomAdminToolsContainer: React.FC<IBaseRoomProps> = ({
room,
children,
member,
startUpdating,
stopUpdating,
powerLevels,
}) => {
const cli = useContext(MatrixClientContext);
let kickButton;
let banButton;
@ -747,6 +801,11 @@ const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpd
} = powerLevels;
const me = room.getMember(cli.getUserId());
if (!me) {
// we aren't in the room, so return no admin tooling
return <div />;
}
const isMe = me.userId === member.userId;
const canAffectUser = member.powerLevel < me.powerLevel || isMe;
@ -786,7 +845,18 @@ const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpd
return <div />;
};
const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating, stopUpdating}) => {
interface GroupMember {
userId: string;
displayname?: string; // XXX: GroupMember objects are inconsistent :((
avatarUrl?: string;
}
const GroupAdminToolsSection: React.FC<{
groupId: string;
groupMember: GroupMember;
startUpdating(): void;
stopUpdating(): void;
}> = ({children, groupId, groupMember, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
const [isPrivileged, setIsPrivileged] = useState(false);
@ -814,8 +884,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
}, [groupId, groupMember.userId]);
if (isPrivileged) {
const _onKick = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const onKick = async () => {
const {finished} = Modal.createDialog(ConfirmUserActionDialog, {
matrixClient: cli,
groupMember,
@ -836,7 +905,6 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
member: null,
});
}).catch((e) => {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, {
title: _t('Error'),
description: isInvited ?
@ -850,7 +918,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
};
const kickButton = (
<AccessibleButton className="mx_UserInfo_field mx_UserInfo_destructive" onClick={_onKick}>
<AccessibleButton className="mx_UserInfo_field mx_UserInfo_destructive" onClick={onKick}>
{ isInvited ? _t('Disinvite') : _t('Remove from community') }
</AccessibleButton>
);
@ -870,13 +938,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
return <div />;
};
const GroupMember = PropTypes.shape({
userId: PropTypes.string.isRequired,
displayname: PropTypes.string, // XXX: GroupMember objects are inconsistent :((
avatarUrl: PropTypes.string,
});
const useIsSynapseAdmin = (cli) => {
const useIsSynapseAdmin = (cli: MatrixClient) => {
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
cli.isSynapseAdministrator().then((isAdmin) => {
@ -888,14 +950,20 @@ const useIsSynapseAdmin = (cli) => {
return isAdmin;
};
const useHomeserverSupportsCrossSigning = (cli) => {
return useAsyncMemo(async () => {
const useHomeserverSupportsCrossSigning = (cli: MatrixClient) => {
return useAsyncMemo<boolean>(async () => {
return cli.doesServerSupportUnstableFeature("org.matrix.e2e_cross_signing");
}, [cli], false);
};
function useRoomPermissions(cli, room, user) {
const [roomPermissions, setRoomPermissions] = useState({
interface IRoomPermissions {
modifyLevelMax: number;
canEdit: boolean;
canInvite: boolean;
}
function useRoomPermissions(cli: MatrixClient, room: Room, user: User): IRoomPermissions {
const [roomPermissions, setRoomPermissions] = useState<IRoomPermissions>({
// modifyLevelMax is the max PL we can set this user to, typically min(their PL, our PL) && canSetPL
modifyLevelMax: -1,
canEdit: false,
@ -940,7 +1008,7 @@ function useRoomPermissions(cli, room, user) {
updateRoomPermissions();
return () => {
setRoomPermissions({
maximalPowerLevel: -1,
modifyLevelMax: -1,
canEdit: false,
canInvite: false,
});
@ -950,14 +1018,18 @@ function useRoomPermissions(cli, room, user) {
return roomPermissions;
}
const PowerLevelSection = ({user, room, roomPermissions, powerLevels}) => {
const PowerLevelSection: React.FC<{
user: User;
room: Room;
roomPermissions: IRoomPermissions;
powerLevels: IPowerLevelsContent;
}> = ({user, room, roomPermissions, powerLevels}) => {
const [isEditing, setEditing] = useState(false);
if (isEditing) {
return (<PowerLevelEditor
user={user} room={room} roomPermissions={roomPermissions}
onFinished={() => setEditing(false)} />);
} else {
const IconButton = sdk.getComponent('elements.IconButton');
const powerLevelUsersDefault = powerLevels.users_default || 0;
const powerLevel = parseInt(user.powerLevel, 10);
const modifyButton = roomPermissions.canEdit ?
@ -975,7 +1047,12 @@ const PowerLevelSection = ({user, room, roomPermissions, powerLevels}) => {
}
};
const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
const PowerLevelEditor: React.FC<{
user: User;
room: Room;
roomPermissions: IRoomPermissions;
onFinished(): void;
}> = ({user, room, roomPermissions, onFinished}) => {
const cli = useContext(MatrixClientContext);
const [isUpdating, setIsUpdating] = useState(false);
@ -994,7 +1071,6 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
// get out of sync if we force setState here!
console.log("Power change success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to change power level " + err);
Modal.createTrackedDialog('Failed to change power level', '', ErrorDialog, {
title: _t("Error"),
@ -1025,12 +1101,10 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
}
const myUserId = cli.getUserId();
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
// If we are changing our own PL it can only ever be decreasing, which we cannot reverse.
if (myUserId === target) {
try {
if (!(await _warnSelfDemote())) return;
if (!(await warnSelfDemote())) return;
} catch (e) {
console.error("Failed to warn about self demotion: ", e);
}
@ -1039,7 +1113,7 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
}
const myPower = powerLevelEvent.getContent().users[myUserId];
if (parseInt(myPower) === parseInt(powerLevel)) {
if (parseInt(myPower) === powerLevel) {
const {finished} = Modal.createTrackedDialog('Promote to PL100 Warning', '', QuestionDialog, {
title: _t("Warning!"),
description:
@ -1062,12 +1136,9 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", "");
const powerLevelUsersDefault = powerLevelEvent ? powerLevelEvent.getContent().users_default : 0;
const IconButton = sdk.getComponent('elements.IconButton');
const Spinner = sdk.getComponent("elements.Spinner");
const buttonOrSpinner = isUpdating ? <Spinner w={16} h={16} /> :
<IconButton icon="check" onClick={changePowerLevel} />;
const PowerSelector = sdk.getComponent('elements.PowerSelector');
return (
<div className="mx_UserInfo_profileField">
<PowerSelector
@ -1083,7 +1154,7 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
);
};
export const useDevices = (userId) => {
export const useDevices = (userId: string) => {
const cli = useContext(MatrixClientContext);
// undefined means yet to be loaded, null means failed to load, otherwise list of devices
@ -1094,7 +1165,7 @@ export const useDevices = (userId) => {
let cancelled = false;
async function _downloadDeviceList() {
async function downloadDeviceList() {
try {
await cli.downloadKeys([userId], true);
const devices = cli.getStoredDevicesForUser(userId);
@ -1104,13 +1175,13 @@ export const useDevices = (userId) => {
return;
}
_disambiguateDevices(devices);
disambiguateDevices(devices);
setDevices(devices);
} catch (err) {
setDevices(null);
}
}
_downloadDeviceList();
downloadDeviceList();
// Handle being unmounted
return () => {
@ -1153,7 +1224,13 @@ export const useDevices = (userId) => {
return devices;
};
const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
const BasicUserInfo: React.FC<{
room: Room;
member: User | RoomMember;
groupId: string;
devices: IDevice[];
isRoomEncrypted: boolean;
}> = ({room, member, groupId, devices, isRoomEncrypted}) => {
const cli = useContext(MatrixClientContext);
const powerLevels = useRoomPowerLevels(cli, room);
@ -1186,7 +1263,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
const roomPermissions = useRoomPermissions(cli, room, member);
const onSynapseDeactivate = useCallback(async () => {
const QuestionDialog = sdk.getComponent('views.dialogs.QuestionDialog');
const {finished} = Modal.createTrackedDialog('Synapse User Deactivation', '', QuestionDialog, {
title: _t("Deactivate user?"),
description:
@ -1207,7 +1283,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
console.error("Failed to deactivate user");
console.error(err);
const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
Modal.createTrackedDialog('Failed to deactivate Synapse user', '', ErrorDialog, {
title: _t('Failed to deactivate user'),
description: ((err && err.message) ? err.message : _t("Operation failed")),
@ -1260,8 +1335,7 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
}
if (pendingUpdateCount > 0) {
const Loader = sdk.getComponent("elements.Spinner");
spinner = <Loader imgClassName="mx_ContextualMenu_spinner" />;
spinner = <Spinner imgClassName="mx_ContextualMenu_spinner" />;
}
let memberDetails;
@ -1324,7 +1398,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
// HACK: only show a spinner if the device section spinner is not shown,
// to avoid showing a double spinner
// We should ask for a design that includes all the different loading states here
const Spinner = sdk.getComponent('elements.Spinner');
verifyButton = <Spinner />;
}
}
@ -1351,7 +1424,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
{ securitySection }
<UserOptionsSection
devices={devices}
canInvite={roomPermissions.canInvite}
isIgnored={isIgnored}
member={member} />
@ -1362,7 +1434,12 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
</React.Fragment>;
};
const UserInfoHeader = ({member, e2eStatus}) => {
type Member = User | RoomMember | GroupMember;
const UserInfoHeader: React.FC<{
member: Member;
e2eStatus: E2EStatus;
}> = ({member, e2eStatus}) => {
const cli = useContext(MatrixClientContext);
const onMemberAvatarClick = useCallback(() => {
@ -1370,7 +1447,6 @@ const UserInfoHeader = ({member, e2eStatus}) => {
if (!avatarUrl) return;
const httpUrl = cli.mxcUrlToHttp(avatarUrl);
const ImageView = sdk.getComponent("elements.ImageView");
const params = {
src: httpUrl,
name: member.name,
@ -1379,7 +1455,6 @@ const UserInfoHeader = ({member, e2eStatus}) => {
Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
}, [cli, member]);
const MemberAvatar = sdk.getComponent('avatars.MemberAvatar');
const avatarElement = (
<div className="mx_UserInfo_avatar">
<div>
@ -1421,10 +1496,13 @@ const UserInfoHeader = ({member, e2eStatus}) => {
let presenceLabel = null;
if (showPresence) {
const PresenceLabel = sdk.getComponent('rooms.PresenceLabel');
presenceLabel = <PresenceLabel activeAgo={presenceLastActiveAgo}
currentlyActive={presenceCurrentlyActive}
presenceState={presenceState} />;
presenceLabel = (
<PresenceLabel
activeAgo={presenceLastActiveAgo}
currentlyActive={presenceCurrentlyActive}
presenceState={presenceState}
/>
);
}
let statusLabel = null;
@ -1461,7 +1539,32 @@ const UserInfoHeader = ({member, e2eStatus}) => {
</React.Fragment>;
};
const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemberInfo, ...props}) => {
interface IProps {
user: Member;
groupId?: string;
room?: Room;
phase: RightPanelPhases.RoomMemberInfo | RightPanelPhases.GroupMemberInfo;
onClose(): void;
}
interface IPropsWithEncryptionPanel extends React.ComponentProps<typeof EncryptionPanel> {
user: Member;
groupId: void;
room: Room;
phase: RightPanelPhases.EncryptionPanel;
onClose(): void;
}
type Props = IProps | IPropsWithEncryptionPanel;
const UserInfo: React.FC<Props> = ({
user,
groupId,
room,
onClose,
phase = RightPanelPhases.RoomMemberInfo,
...props
}) => {
const cli = useContext(MatrixClientContext);
// fetch latest room member if we have a room, so we don't show historical information, falling back to user
@ -1485,7 +1588,7 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
<BasicUserInfo
room={room}
member={member}
groupId={groupId}
groupId={groupId as string}
devices={devices}
isRoomEncrypted={isRoomEncrypted} />
);
@ -1493,7 +1596,12 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
case RightPanelPhases.EncryptionPanel:
classes.push("mx_UserInfo_smallAvatar");
content = (
<EncryptionPanel {...props} member={member} onClose={onClose} isRoomEncrypted={isRoomEncrypted} />
<EncryptionPanel
{...props as React.ComponentProps<typeof EncryptionPanel>}
member={member}
onClose={onClose}
isRoomEncrypted={isRoomEncrypted}
/>
);
break;
}
@ -1504,23 +1612,24 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
previousPhase = RightPanelPhases.RoomMemberList;
}
const header = <UserInfoHeader member={member} e2eStatus={e2eStatus} onClose={onClose} />;
return <BaseCard className={classes.join(" ")} header={header} onClose={onClose} previousPhase={previousPhase}>
let closeLabel = undefined;
if (phase === RightPanelPhases.EncryptionPanel) {
const verificationRequest = (props as React.ComponentProps<typeof EncryptionPanel>).verificationRequest;
if (verificationRequest && verificationRequest.pending) {
closeLabel = _t("Cancel");
}
}
const header = <UserInfoHeader member={member} e2eStatus={e2eStatus} />;
return <BaseCard
className={classes.join(" ")}
header={header}
onClose={onClose}
closeLabel={closeLabel}
previousPhase={previousPhase}
>
{ content }
</BaseCard>;
};
UserInfo.propTypes = {
user: PropTypes.oneOfType([
PropTypes.instanceOf(User),
PropTypes.instanceOf(RoomMember),
GroupMember,
]).isRequired,
group: PropTypes.instanceOf(Group),
groupId: PropTypes.string,
room: PropTypes.instanceOf(Room),
onClose: PropTypes.func,
};
export default UserInfo;

View file

@ -29,16 +29,17 @@ import defaultDispatcher from "../../../dispatcher/dispatcher";
import {SetRightPanelPhasePayload} from "../../../dispatcher/payloads/SetRightPanelPhasePayload";
import {Action} from "../../../dispatcher/actions";
import WidgetStore from "../../../stores/WidgetStore";
import ActiveWidgetStore from "../../../stores/ActiveWidgetStore";
import {ChevronFace, ContextMenuButton, useContextMenu} from "../../structures/ContextMenu";
import IconizedContextMenu, {
IconizedContextMenuOption,
IconizedContextMenuOptionList,
} from "../context_menus/IconizedContextMenu";
import {AppTileActionPayload} from "../../../dispatcher/payloads/AppTileActionPayload";
import {Capability} from "../../../widgets/WidgetApi";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import classNames from "classnames";
import dis from "../../../dispatcher/dispatcher";
import { WidgetMessagingStore } from "../../../stores/widgets/WidgetMessagingStore";
import { MatrixCapabilities } from "matrix-widget-api";
interface IProps {
room: Room;
@ -77,9 +78,17 @@ const WidgetCard: React.FC<IProps> = ({ room, widgetId, onClose }) => {
let contextMenu;
if (menuDisplayed) {
let snapshotButton;
if (ActiveWidgetStore.widgetHasCapability(app.id, Capability.Screenshot)) {
const widgetMessaging = WidgetMessagingStore.instance.getMessagingForId(app.id);
if (widgetMessaging?.hasCapability(MatrixCapabilities.Screenshots)) {
const onSnapshotClick = () => {
WidgetUtils.snapshotWidget(app);
widgetMessaging.takeScreenshot().then(data => {
dis.dispatch({
action: 'picture_snapshot',
file: data.screenshot,
});
}).catch(err => {
console.error("Failed to take screenshot: ", err);
});
closeMenu();
};

View file

@ -40,12 +40,10 @@ export default class AppsDrawer extends React.Component {
room: PropTypes.object.isRequired,
resizeNotifier: PropTypes.instanceOf(ResizeNotifier).isRequired,
showApps: PropTypes.bool, // Should apps be rendered
hide: PropTypes.bool, // If rendered, should apps drawer be visible
};
static defaultProps = {
showApps: true,
hide: false,
};
constructor(props) {
@ -173,7 +171,6 @@ export default class AppsDrawer extends React.Component {
const classes = classNames({
"mx_AppsDrawer": true,
"mx_AppsDrawer_hidden": this.props.hide,
"mx_AppsDrawer_fullWidth": apps.length < 2,
"mx_AppsDrawer_minimised": !this.props.showApps,
});

View file

@ -37,7 +37,6 @@ export default class AuxPanel extends React.Component {
room: PropTypes.object.isRequired,
userId: PropTypes.string.isRequired,
showApps: PropTypes.bool, // Render apps
hideAppsDrawer: PropTypes.bool, // Do not display apps drawer and content (may still be rendered)
// set to true to show the file drop target
draggingFile: PropTypes.bool,
@ -54,7 +53,6 @@ export default class AuxPanel extends React.Component {
static defaultProps = {
showApps: true,
hideAppsDrawer: false,
};
constructor(props) {
@ -170,7 +168,6 @@ export default class AuxPanel extends React.Component {
userId={this.props.userId}
maxHeight={this.props.maxHeight}
showApps={this.props.showApps}
hide={this.props.hideAppsDrawer}
resizeNotifier={this.props.resizeNotifier}
/>;
}

View file

@ -92,7 +92,7 @@ interface IProps {
label?: string;
initialCaret?: DocumentOffset;
onChange();
onChange?();
onPaste?(event: ClipboardEvent<HTMLDivElement>, model: EditorModel): boolean;
}
@ -619,13 +619,14 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
private onFormatAction = (action: Formatting) => {
const range = getRangeForSelection(
this.editorRef.current,
this.props.model,
document.getSelection());
const range = getRangeForSelection(this.editorRef.current, this.props.model, document.getSelection());
// trim the range as we want it to exclude leading/trailing spaces
range.trim();
if (range.length === 0) {
return;
}
this.historyManager.ensureLastChangesPushed(this.props.model);
this.modifiedFlag = true;
switch (action) {

View file

@ -34,6 +34,7 @@ import * as ObjectUtils from "../../../ObjectUtils";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {E2E_STATE} from "./E2EIcon";
import {toRem} from "../../../utils/units";
import {WidgetType} from "../../../widgets/WidgetType";
import RoomAvatar from "../avatars/RoomAvatar";
const eventTileTypes = {
@ -45,6 +46,7 @@ const eventTileTypes = {
'm.call.invite': 'messages.TextualEvent',
'm.call.answer': 'messages.TextualEvent',
'm.call.hangup': 'messages.TextualEvent',
'm.call.reject': 'messages.TextualEvent',
};
const stateEventTileTypes = {
@ -111,6 +113,19 @@ export function getHandlerTile(ev) {
}
}
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
if (type === "im.vector.modular.widgets") {
let type = ev.getContent()['type'];
if (!type) {
// deleted/invalid widget - try the past widget type
type = ev.getPrevContent()['type'];
}
if (WidgetType.JITSI.matches(type)) {
return "messages.MJitsiWidgetEvent";
}
}
return ev.isState() ? stateEventTileTypes[type] : eventTileTypes[type];
}
@ -627,22 +642,23 @@ export default class EventTile extends React.Component {
const msgtype = content.msgtype;
const eventType = this.props.mxEvent.getType();
let tileHandler = getHandlerTile(this.props.mxEvent);
// Info messages are basically information about commands processed on a room
const isBubbleMessage = eventType.startsWith("m.key.verification") ||
(eventType === "m.room.message" && msgtype && msgtype.startsWith("m.key.verification")) ||
(eventType === "m.room.encryption");
(eventType === "m.room.encryption") ||
(tileHandler === "messages.MJitsiWidgetEvent");
let isInfoMessage = (
!isBubbleMessage && eventType !== 'm.room.message' &&
eventType !== 'm.sticker' && eventType !== 'm.room.create'
);
let tileHandler = getHandlerTile(this.props.mxEvent);
// If we're showing hidden events in the timeline, we should use the
// source tile when there's no regular tile for an event and also for
// replace relations (which otherwise would display as a confusing
// duplicate of the thing they are replacing).
const useSource = !tileHandler || this.props.mxEvent.isRelation("m.replace");
if (useSource && SettingsStore.getValue("showHiddenEventsInTimeline")) {
if (SettingsStore.getValue("showHiddenEventsInTimeline") && !haveTileForEvent(this.props.mxEvent)) {
tileHandler = "messages.ViewSourceEvent";
// Reuse info message avatar and sender profile styling
isInfoMessage = true;
@ -902,6 +918,7 @@ export default class EventTile extends React.Component {
highlights={this.props.highlights}
highlightLink={this.props.highlightLink}
onHeightChanged={this.props.onHeightChanged}
replacingEventId={this.props.replacingEventId}
showUrlPreview={false} />
</div>
</div>

View file

@ -18,7 +18,6 @@
import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import dis from '../../../dispatcher/dispatcher';
import {Key} from '../../../Keyboard';
@ -28,19 +27,10 @@ export default class ForwardMessage extends React.Component {
};
componentDidMount() {
dis.dispatch({
action: 'panel_disable',
middleDisabled: true,
});
document.addEventListener('keydown', this._onKeyDown);
}
componentWillUnmount() {
dis.dispatch({
action: 'panel_disable',
middleDisabled: false,
});
document.removeEventListener('keydown', this._onKeyDown);
}

View file

@ -121,8 +121,8 @@ export default class MemberList extends React.Component {
this.setState(this._getMembersState(this.roomMembers()));
this._listenForMembersChanges();
}
} else if (membership === "invite") {
// show the members we've got when invited
} else {
// show the members we already have loaded
this.setState(this._getMembersState(this.roomMembers()));
}
}

View file

@ -1,6 +1,7 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -32,6 +33,12 @@ import {aboveLeftOf, ContextMenu, ContextMenuTooltipButton, useContextMenu} from
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import ReplyPreview from "./ReplyPreview";
import {UIFeature} from "../../../settings/UIFeature";
import WidgetStore from "../../../stores/WidgetStore";
import WidgetUtils from "../../../utils/WidgetUtils";
import {UPDATE_EVENT} from "../../../stores/AsyncStore";
import ActiveWidgetStore from "../../../stores/ActiveWidgetStore";
import { PlaceCallType } from "../../../CallHandler";
import { CallState } from 'matrix-js-sdk/src/webrtc/call';
function ComposerAvatar(props) {
const MemberStatusMessageAvatar = sdk.getComponent('avatars.MemberStatusMessageAvatar');
@ -48,7 +55,7 @@ function CallButton(props) {
const onVoiceCallClick = (ev) => {
dis.dispatch({
action: 'place_call',
type: "voice",
type: PlaceCallType.Voice,
room_id: props.roomId,
});
};
@ -68,7 +75,7 @@ function VideoCallButton(props) {
const onCallClick = (ev) => {
dis.dispatch({
action: 'place_call',
type: ev.shiftKey ? "screensharing" : "video",
type: ev.shiftKey ? PlaceCallType.ScreenSharing : PlaceCallType.Video,
room_id: props.roomId,
});
};
@ -85,27 +92,51 @@ VideoCallButton.propTypes = {
};
function HangupButton(props) {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const onHangupClick = () => {
if (props.isConference) {
dis.dispatch({
action: props.canEndConference ? 'end_conference' : 'hangup_conference',
room_id: props.roomId,
});
return;
}
const call = CallHandler.sharedInstance().getCallForRoom(props.roomId);
if (!call) {
return;
}
const action = call.state === CallState.Ringing ? 'reject' : 'hangup';
dis.dispatch({
action: 'hangup',
action,
// hangup the call for this room, which may not be the room in props
// (e.g. conferences which will hangup the 1:1 room instead)
room_id: call.roomId,
});
};
return (<AccessibleButton className="mx_MessageComposer_button mx_MessageComposer_hangup"
let tooltip = _t("Hangup");
if (props.isConference && props.canEndConference) {
tooltip = _t("End conference");
}
const canLeaveConference = !props.isConference ? true : props.isInConference;
return (
<AccessibleTooltipButton
className="mx_MessageComposer_button mx_MessageComposer_hangup"
onClick={onHangupClick}
title={_t('Hangup')}
/>);
title={tooltip}
disabled={!canLeaveConference}
/>
);
}
HangupButton.propTypes = {
roomId: PropTypes.string.isRequired,
isConference: PropTypes.bool.isRequired,
canEndConference: PropTypes.bool,
isInConference: PropTypes.bool,
};
const EmojiButton = ({addEmoji}) => {
@ -226,12 +257,17 @@ export default class MessageComposer extends React.Component {
this._onRoomViewStoreUpdate = this._onRoomViewStoreUpdate.bind(this);
this._onTombstoneClick = this._onTombstoneClick.bind(this);
this.renderPlaceholderText = this.renderPlaceholderText.bind(this);
WidgetStore.instance.on(UPDATE_EVENT, this._onWidgetUpdate);
ActiveWidgetStore.on('update', this._onActiveWidgetUpdate);
this._dispatcherRef = null;
this.state = {
isQuoting: Boolean(RoomViewStore.getQuotingEvent()),
replyToEvent: RoomViewStore.getQuotingEvent(),
tombstone: this._getRoomTombstone(),
canSendMessages: this.props.room.maySendMessage(),
showCallButtons: SettingsStore.getValue("showCallButtonsInComposer"),
hasConference: WidgetStore.instance.doesRoomHaveConference(this.props.room),
joinedConference: WidgetStore.instance.isJoinedToConferenceIn(this.props.room),
};
}
@ -247,6 +283,14 @@ export default class MessageComposer extends React.Component {
}
};
_onWidgetUpdate = () => {
this.setState({hasConference: WidgetStore.instance.doesRoomHaveConference(this.props.room)});
};
_onActiveWidgetUpdate = () => {
this.setState({joinedConference: WidgetStore.instance.isJoinedToConferenceIn(this.props.room)});
};
componentDidMount() {
this.dispatcherRef = dis.register(this.onAction);
MatrixClientPeg.get().on("RoomState.events", this._onRoomStateEvents);
@ -277,6 +321,8 @@ export default class MessageComposer extends React.Component {
if (this._roomStoreToken) {
this._roomStoreToken.remove();
}
WidgetStore.instance.removeListener(UPDATE_EVENT, this._onWidgetUpdate);
ActiveWidgetStore.removeListener('update', this._onActiveWidgetUpdate);
dis.unregister(this.dispatcherRef);
}
@ -296,9 +342,9 @@ export default class MessageComposer extends React.Component {
}
_onRoomViewStoreUpdate() {
const isQuoting = Boolean(RoomViewStore.getQuotingEvent());
if (this.state.isQuoting === isQuoting) return;
this.setState({ isQuoting });
const replyToEvent = RoomViewStore.getQuotingEvent();
if (this.state.replyToEvent === replyToEvent) return;
this.setState({ replyToEvent });
}
onInputStateChanged(inputState) {
@ -337,7 +383,7 @@ export default class MessageComposer extends React.Component {
}
renderPlaceholderText() {
if (this.state.isQuoting) {
if (this.state.replyToEvent) {
if (this.props.e2eStatus) {
return _t('Send an encrypted reply…');
} else {
@ -382,7 +428,9 @@ export default class MessageComposer extends React.Component {
room={this.props.room}
placeholder={this.renderPlaceholderText()}
resizeNotifier={this.props.resizeNotifier}
permalinkCreator={this.props.permalinkCreator} />,
permalinkCreator={this.props.permalinkCreator}
replyToEvent={this.state.replyToEvent}
/>,
<UploadButton key="controls_upload" roomId={this.props.room.roomId} />,
<EmojiButton key="emoji_button" addEmoji={this.addEmoji} />,
);
@ -392,9 +440,20 @@ export default class MessageComposer extends React.Component {
}
if (this.state.showCallButtons) {
if (callInProgress) {
if (this.state.hasConference) {
const canEndConf = WidgetUtils.canUserModifyWidgets(this.props.room.roomId);
controls.push(
<HangupButton key="controls_hangup" roomId={this.props.room.roomId} />,
<HangupButton
key="controls_hangup"
roomId={this.props.room.roomId}
isConference={true}
canEndConference={canEndConf}
isInConference={this.state.joinedConference}
/>,
);
} else if (callInProgress) {
controls.push(
<HangupButton key="controls_hangup" roomId={this.props.room.roomId} isConference={false} />,
);
} else {
controls.push(

View file

@ -76,7 +76,7 @@ export default class RoomBreadcrumbs extends React.PureComponent<IProps, IState>
};
private viewRoom = (room: Room, index: number) => {
Analytics.trackEvent("Breadcrumbs", "click_node", index);
Analytics.trackEvent("Breadcrumbs", "click_node", String(index));
defaultDispatcher.dispatch({action: "view_room", room_id: room.roomId});
};

View file

@ -399,6 +399,7 @@ export default class RoomSublist extends React.Component<IProps, IState> {
const isUnreadFirst = RoomListStore.instance.getListOrder(this.props.tagId) === ListAlgorithm.Importance;
const newAlgorithm = isUnreadFirst ? ListAlgorithm.Natural : ListAlgorithm.Importance;
await RoomListStore.instance.setListOrder(this.props.tagId, newAlgorithm);
this.forceUpdate(); // because if the sublist doesn't have any changes then we will miss the list order change
};
private onTagSortChanged = async (sort: SortAlgorithm) => {

View file

@ -29,7 +29,6 @@ import {
} from '../../../editor/serialize';
import {CommandPartCreator} from '../../../editor/parts';
import BasicMessageComposer from "./BasicMessageComposer";
import RoomViewStore from '../../../stores/RoomViewStore';
import ReplyThread from "../elements/ReplyThread";
import {parseEvent} from '../../../editor/deserialize';
import {findEditableEvent} from '../../../utils/EventUtils';
@ -41,7 +40,6 @@ import {_t, _td} from '../../../languageHandler';
import ContentMessages from '../../../ContentMessages';
import {Key} from "../../../Keyboard";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import RateLimitedFunc from '../../../ratelimitedfunc';
import {Action} from "../../../dispatcher/actions";
@ -61,7 +59,7 @@ function addReplyToMessageContent(content, repliedToEvent, permalinkCreator) {
}
// exported for tests
export function createMessageContent(model, permalinkCreator) {
export function createMessageContent(model, permalinkCreator, replyToEvent) {
const isEmote = containsEmote(model);
if (isEmote) {
model = stripEmoteCommand(model);
@ -70,21 +68,20 @@ export function createMessageContent(model, permalinkCreator) {
model = stripPrefix(model, "/");
}
model = unescapeMessage(model);
const repliedToEvent = RoomViewStore.getQuotingEvent();
const body = textSerialize(model);
const content = {
msgtype: isEmote ? "m.emote" : "m.text",
body: body,
};
const formattedBody = htmlSerializeIfNeeded(model, {forceHTML: !!repliedToEvent});
const formattedBody = htmlSerializeIfNeeded(model, {forceHTML: !!replyToEvent});
if (formattedBody) {
content.format = "org.matrix.custom.html";
content.formatted_body = formattedBody;
}
if (repliedToEvent) {
addReplyToMessageContent(content, repliedToEvent, permalinkCreator);
if (replyToEvent) {
addReplyToMessageContent(content, replyToEvent, permalinkCreator);
}
return content;
@ -95,6 +92,7 @@ export default class SendMessageComposer extends React.Component {
room: PropTypes.object.isRequired,
placeholder: PropTypes.string,
permalinkCreator: PropTypes.object.isRequired,
replyToEvent: PropTypes.object,
};
static contextType = MatrixClientContext;
@ -104,12 +102,13 @@ export default class SendMessageComposer extends React.Component {
this.model = null;
this._editorRef = null;
this.currentlyComposedEditorState = null;
const cli = MatrixClientPeg.get();
if (cli.isCryptoEnabled() && cli.isRoomEncrypted(this.props.room.roomId)) {
if (this.context.isCryptoEnabled() && this.context.isRoomEncrypted(this.props.room.roomId)) {
this._prepareToEncrypt = new RateLimitedFunc(() => {
cli.prepareToEncrypt(this.props.room);
this.context.prepareToEncrypt(this.props.room);
}, 60000);
}
window.addEventListener("beforeunload", this._saveStoredEditorState);
}
_setEditorRef = ref => {
@ -145,7 +144,7 @@ export default class SendMessageComposer extends React.Component {
if (e.shiftKey || e.metaKey) return;
const shouldSelectHistory = e.altKey && e.ctrlKey;
const shouldEditLastMessage = !e.altKey && !e.ctrlKey && up && !RoomViewStore.getQuotingEvent();
const shouldEditLastMessage = !e.altKey && !e.ctrlKey && up && !this.props.replyToEvent;
if (shouldSelectHistory) {
// Try select composer history
@ -187,9 +186,13 @@ export default class SendMessageComposer extends React.Component {
this.sendHistoryManager.currentIndex = this.sendHistoryManager.history.length;
return;
}
const serializedParts = this.sendHistoryManager.getItem(delta);
if (serializedParts) {
this.model.reset(serializedParts);
const {parts, replyEventId} = this.sendHistoryManager.getItem(delta);
dis.dispatch({
action: 'reply_to_event',
event: replyEventId ? this.props.room.findEventById(replyEventId) : null,
});
if (parts) {
this.model.reset(parts);
this._editorRef.focus();
}
}
@ -299,12 +302,12 @@ export default class SendMessageComposer extends React.Component {
}
}
const replyToEvent = this.props.replyToEvent;
if (shouldSend) {
const isReply = !!RoomViewStore.getQuotingEvent();
const {roomId} = this.props.room;
const content = createMessageContent(this.model, this.props.permalinkCreator);
const content = createMessageContent(this.model, this.props.permalinkCreator, replyToEvent);
this.context.sendMessage(roomId, content);
if (isReply) {
if (replyToEvent) {
// Clear reply_to_event as we put the message into the queue
// if the send fails, retry will handle resending.
dis.dispatch({
@ -315,7 +318,7 @@ export default class SendMessageComposer extends React.Component {
dis.dispatch({action: "message_sent"});
}
this.sendHistoryManager.save(this.model);
this.sendHistoryManager.save(this.model, replyToEvent);
// clear composer
this.model.reset([]);
this._editorRef.clearUndoHistory();
@ -325,6 +328,8 @@ export default class SendMessageComposer extends React.Component {
componentWillUnmount() {
dis.unregister(this.dispatcherRef);
window.removeEventListener("beforeunload", this._saveStoredEditorState);
this._saveStoredEditorState();
}
// TODO: [REACT-WARNING] Move this to constructor
@ -333,11 +338,11 @@ export default class SendMessageComposer extends React.Component {
const parts = this._restoreStoredEditorState(partCreator) || [];
this.model = new EditorModel(parts, partCreator);
this.dispatcherRef = dis.register(this.onAction);
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, 'mx_cider_composer_history_');
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, 'mx_cider_history_');
}
get _editorStateKey() {
return `cider_editor_state_${this.props.room.roomId}`;
return `mx_cider_state_${this.props.room.roomId}`;
}
_clearStoredEditorState() {
@ -347,9 +352,19 @@ export default class SendMessageComposer extends React.Component {
_restoreStoredEditorState(partCreator) {
const json = localStorage.getItem(this._editorStateKey);
if (json) {
const serializedParts = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
return parts;
try {
const {parts: serializedParts, replyEventId} = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
if (replyEventId) {
dis.dispatch({
action: 'reply_to_event',
event: this.props.room.findEventById(replyEventId),
});
}
return parts;
} catch (e) {
console.error(e);
}
}
}
@ -357,7 +372,8 @@ export default class SendMessageComposer extends React.Component {
if (this.model.isEmpty) {
this._clearStoredEditorState();
} else {
localStorage.setItem(this._editorStateKey, JSON.stringify(this.model.serializeParts()));
const item = SendHistoryManager.createItem(this.model, this.props.replyToEvent);
localStorage.setItem(this._editorStateKey, JSON.stringify(item));
}
}
@ -449,7 +465,6 @@ export default class SendMessageComposer extends React.Component {
room={this.props.room}
label={this.props.placeholder}
placeholder={this.props.placeholder}
onChange={this._saveStoredEditorState}
onPaste={this._onPaste}
/>
</div>

View file

@ -22,7 +22,6 @@ import * as sdk from '../../../index';
import dis from '../../../dispatcher/dispatcher';
import AccessibleButton from '../elements/AccessibleButton';
import WidgetUtils from '../../../utils/WidgetUtils';
import ActiveWidgetStore from '../../../stores/ActiveWidgetStore';
import PersistedElement from "../elements/PersistedElement";
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
@ -30,6 +29,7 @@ import {ContextMenu} from "../../structures/ContextMenu";
import {WidgetType} from "../../../widgets/WidgetType";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import {Action} from "../../../dispatcher/actions";
import {WidgetMessagingStore} from "../../../stores/widgets/WidgetMessagingStore";
// This should be below the dialog level (4000), but above the rest of the UI (1000-2000).
// We sit in a context menu, so this should be given to the context menu.
@ -212,9 +212,11 @@ export default class Stickerpicker extends React.Component {
_sendVisibilityToWidget(visible) {
if (!this.state.stickerpickerWidget) return;
const widgetMessaging = ActiveWidgetStore.getWidgetMessaging(this.state.stickerpickerWidget.id);
if (widgetMessaging && visible !== this._prevSentVisibility) {
widgetMessaging.sendVisibility(visible);
const messaging = WidgetMessagingStore.instance.getMessagingForId(this.state.stickerpickerWidget.id);
if (messaging && visible !== this._prevSentVisibility) {
messaging.updateVisibility(visible).catch(err => {
console.error("Error updating widget visibility: ", err);
});
this._prevSentVisibility = visible;
}
}

View file

@ -19,14 +19,12 @@ import Field from "../elements/Field";
import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import dis from "../../../dispatcher/dispatcher";
import AccessibleButton from '../elements/AccessibleButton';
import Spinner from '../elements/Spinner';
import { _t } from '../../../languageHandler';
import * as sdk from "../../../index";
import Modal from "../../../Modal";
import sessionStore from '../../../stores/SessionStore';
export default class ChangePassword extends React.Component {
static propTypes = {
onFinished: PropTypes.func,
@ -35,6 +33,7 @@ export default class ChangePassword extends React.Component {
rowClassName: PropTypes.string,
buttonClassName: PropTypes.string,
buttonKind: PropTypes.string,
buttonLabel: PropTypes.string,
confirm: PropTypes.bool,
// Whether to autoFocus the new password input
autoFocusNewPasswordInput: PropTypes.bool,
@ -65,33 +64,11 @@ export default class ChangePassword extends React.Component {
state = {
phase: ChangePassword.Phases.Edit,
cachedPassword: null,
oldPassword: "",
newPassword: "",
newPasswordConfirm: "",
};
componentDidMount() {
this._sessionStore = sessionStore;
this._sessionStoreToken = this._sessionStore.addListener(
this._setStateFromSessionStore,
);
this._setStateFromSessionStore();
}
componentWillUnmount() {
if (this._sessionStoreToken) {
this._sessionStoreToken.remove();
}
}
_setStateFromSessionStore = () => {
this.setState({
cachedPassword: this._sessionStore.getCachedPassword(),
});
};
changePassword(oldPassword, newPassword) {
const cli = MatrixClientPeg.get();
@ -118,8 +95,11 @@ export default class ChangePassword extends React.Component {
</div>,
button: _t("Continue"),
extraButtons: [
<button className="mx_Dialog_primary"
onClick={this._onExportE2eKeysClicked}>
<button
key="exportRoomKeys"
className="mx_Dialog_primary"
onClick={this._onExportE2eKeysClicked}
>
{ _t('Export E2E room keys') }
</button>,
],
@ -149,9 +129,6 @@ export default class ChangePassword extends React.Component {
});
cli.setPassword(authDict, newPassword).then(() => {
// Notify SessionStore that the user's password was changed
dis.dispatch({action: 'password_changed'});
if (this.props.shouldAskForEmail) {
return this._optionallySetEmail().then((confirmed) => {
this.props.onFinished({
@ -211,7 +188,7 @@ export default class ChangePassword extends React.Component {
onClickChange = (ev) => {
ev.preventDefault();
const oldPassword = this.state.cachedPassword || this.state.oldPassword;
const oldPassword = this.state.oldPassword;
const newPassword = this.state.newPassword;
const confirmPassword = this.state.newPasswordConfirm;
const err = this.props.onCheckPassword(
@ -230,31 +207,22 @@ export default class ChangePassword extends React.Component {
const rowClassName = this.props.rowClassName;
const buttonClassName = this.props.buttonClassName;
let currentPassword = null;
if (!this.state.cachedPassword) {
currentPassword = (
<div className={rowClassName}>
<Field
type="password"
label={_t('Current password')}
value={this.state.oldPassword}
onChange={this.onChangeOldPassword}
/>
</div>
);
}
switch (this.state.phase) {
case ChangePassword.Phases.Edit:
const passwordLabel = this.state.cachedPassword ?
_t('Password') : _t('New Password');
return (
<form className={this.props.className} onSubmit={this.onClickChange}>
{ currentPassword }
<div className={rowClassName}>
<Field
type="password"
label={passwordLabel}
label={_t('Current password')}
value={this.state.oldPassword}
onChange={this.onChangeOldPassword}
/>
</div>
<div className={rowClassName}>
<Field
type="password"
label={_t('New Password')}
value={this.state.newPassword}
autoFocus={this.props.autoFocusNewPasswordInput}
onChange={this.onChangeNewPassword}
@ -271,15 +239,14 @@ export default class ChangePassword extends React.Component {
/>
</div>
<AccessibleButton className={buttonClassName} kind={this.props.buttonKind} onClick={this.onClickChange}>
{ _t('Change Password') }
{ this.props.buttonLabel || _t('Change Password') }
</AccessibleButton>
</form>
);
case ChangePassword.Phases.Uploading:
var Loader = sdk.getComponent("elements.Spinner");
return (
<div className="mx_Dialog_content">
<Loader />
<Spinner />
</div>
);
}

View file

@ -42,6 +42,14 @@ export default class IntegrationManager extends React.Component {
loading: false,
};
constructor(props) {
super(props);
this.state = {
errored: false,
};
}
componentDidMount() {
this.dispatcherRef = dis.register(this.onAction);
document.addEventListener("keydown", this.onKeyDown);
@ -66,6 +74,10 @@ export default class IntegrationManager extends React.Component {
}
};
onError = () => {
this.setState({ errored: true });
};
render() {
if (this.props.loading) {
const Spinner = sdk.getComponent("elements.Spinner");
@ -77,7 +89,7 @@ export default class IntegrationManager extends React.Component {
);
}
if (!this.props.connected) {
if (!this.props.connected || this.state.errored) {
return (
<div className='mx_IntegrationManager_error'>
<h3>{_t("Cannot connect to integration manager")}</h3>
@ -86,6 +98,6 @@ export default class IntegrationManager extends React.Component {
);
}
return <iframe src={this.props.url}></iframe>;
return <iframe src={this.props.url} onError={this.onError} />;
}
}

View file

@ -18,30 +18,23 @@ import React, {createRef} from 'react';
import {_t} from "../../../languageHandler";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import Field from "../elements/Field";
import {User} from "matrix-js-sdk";
import { getHostingLink } from '../../../utils/HostingLink';
import * as sdk from "../../../index";
import {OwnProfileStore} from "../../../stores/OwnProfileStore";
import Modal from "../../../Modal";
import ErrorDialog from "../dialogs/ErrorDialog";
export default class ProfileSettings extends React.Component {
constructor() {
super();
const client = MatrixClientPeg.get();
let user = client.getUser(client.getUserId());
if (!user) {
// XXX: We shouldn't have to do this.
// There seems to be a condition where the User object won't exist until a room
// exists on the account. To work around this, we'll just create a temporary User
// and use that.
console.warn("User object not found - creating one for ProfileSettings");
user = new User(client.getUserId());
}
let avatarUrl = user.avatarUrl;
let avatarUrl = OwnProfileStore.instance.avatarMxc;
if (avatarUrl) avatarUrl = client.mxcUrlToHttp(avatarUrl, 96, 96, 'crop', false);
this.state = {
userId: user.userId,
originalDisplayName: user.rawDisplayName,
displayName: user.rawDisplayName,
userId: client.getUserId(),
originalDisplayName: OwnProfileStore.instance.displayName,
displayName: OwnProfileStore.instance.displayName,
originalAvatarUrl: avatarUrl,
avatarUrl: avatarUrl,
avatarFile: null,
@ -84,21 +77,26 @@ export default class ProfileSettings extends React.Component {
const client = MatrixClientPeg.get();
const newState = {};
// TODO: What do we do about errors?
try {
if (this.state.originalDisplayName !== this.state.displayName) {
await client.setDisplayName(this.state.displayName);
newState.originalDisplayName = this.state.displayName;
}
if (this.state.originalDisplayName !== this.state.displayName) {
await client.setDisplayName(this.state.displayName);
newState.originalDisplayName = this.state.displayName;
}
if (this.state.avatarFile) {
const uri = await client.uploadContent(this.state.avatarFile);
await client.setAvatarUrl(uri);
newState.avatarUrl = client.mxcUrlToHttp(uri, 96, 96, 'crop', false);
newState.originalAvatarUrl = newState.avatarUrl;
newState.avatarFile = null;
} else if (this.state.originalAvatarUrl !== this.state.avatarUrl) {
await client.setAvatarUrl(""); // use empty string as Synapse 500s on undefined
if (this.state.avatarFile) {
const uri = await client.uploadContent(this.state.avatarFile);
await client.setAvatarUrl(uri);
newState.avatarUrl = client.mxcUrlToHttp(uri, 96, 96, 'crop', false);
newState.originalAvatarUrl = newState.avatarUrl;
newState.avatarFile = null;
} else if (this.state.originalAvatarUrl !== this.state.avatarUrl) {
await client.setAvatarUrl(""); // use empty string as Synapse 500s on undefined
}
} catch (err) {
Modal.createTrackedDialog('Failed to save profile', '', ErrorDialog, {
title: _t("Failed to save your profile"),
description: ((err && err.message) ? err.message : _t("The operation could not be completed")),
});
}
this.setState(newState);

View file

@ -239,7 +239,7 @@ export default class RolesRoomSettingsTab extends React.Component {
defaultValue: 50,
},
"redact": {
desc: _t('Remove messages'),
desc: _t('Remove messages sent by others'),
defaultValue: 50,
},
"notifications.room": {

View file

@ -24,13 +24,14 @@ import dis from '../../../dispatcher/dispatcher';
import { ActionPayload } from '../../../dispatcher/payloads';
import PersistentApp from "../elements/PersistentApp";
import SettingsStore from "../../../settings/SettingsStore";
import { CallState, MatrixCall } from 'matrix-js-sdk/lib/webrtc/call';
interface IProps {
}
interface IState {
roomId: string;
activeCall: any;
activeCall: MatrixCall;
}
export default class CallPreview extends React.Component<IProps, IState> {
@ -84,7 +85,7 @@ export default class CallPreview extends React.Component<IProps, IState> {
if (call) {
dis.dispatch({
action: 'view_room',
room_id: call.groupRoomId || call.roomId,
room_id: call.roomId,
});
}
};
@ -93,7 +94,7 @@ export default class CallPreview extends React.Component<IProps, IState> {
const callForRoom = CallHandler.sharedInstance().getCallForRoom(this.state.roomId);
const showCall = (
this.state.activeCall &&
this.state.activeCall.call_state === 'connected' &&
this.state.activeCall.state === CallState.Connected &&
!callForRoom
);

View file

@ -25,6 +25,7 @@ import AccessibleButton from '../elements/AccessibleButton';
import VideoView from "./VideoView";
import RoomAvatar from "../avatars/RoomAvatar";
import PulsedAvatar from '../avatars/PulsedAvatar';
import { CallState, MatrixCall } from 'matrix-js-sdk/lib/webrtc/call';
interface IProps {
// js-sdk room object. If set, we will only show calls for the given
@ -87,7 +88,7 @@ export default class CallView extends React.Component<IProps, IState> {
};
private showCall() {
let call;
let call: MatrixCall;
if (this.props.room) {
const roomId = this.props.room.roomId;
@ -120,7 +121,7 @@ export default class CallView extends React.Component<IProps, IState> {
call.setRemoteAudioElement(this.getVideoView().getRemoteAudioElement());
}
}
if (call && call.type === "video" && call.call_state !== "ended" && call.call_state !== "ringing") {
if (call && call.type === "video" && call.state !== CallState.Ended && call.state !== CallState.Ringing) {
this.getVideoView().getLocalVideoElement().style.display = "block";
this.getVideoView().getRemoteVideoElement().style.display = "block";
} else {

View file

@ -25,6 +25,7 @@ import CallHandler from '../../../CallHandler';
import PulsedAvatar from '../avatars/PulsedAvatar';
import RoomAvatar from '../avatars/RoomAvatar';
import FormButton from '../elements/FormButton';
import { CallState } from 'matrix-js-sdk/lib/webrtc/call';
interface IProps {
}
@ -53,7 +54,7 @@ export default class IncomingCallBox extends React.Component<IProps, IState> {
switch (payload.action) {
case 'call_state': {
const call = CallHandler.sharedInstance().getCallForRoom(payload.room_id);
if (call && call.call_state === 'ringing') {
if (call && call.state === CallState.Ringing) {
this.setState({
incomingCall: call,
});
@ -77,7 +78,7 @@ export default class IncomingCallBox extends React.Component<IProps, IState> {
private onRejectClick: React.MouseEventHandler = (e) => {
e.stopPropagation();
dis.dispatch({
action: 'hangup',
action: 'reject',
room_id: this.state.incomingCall.roomId,
});
};