Merge pull request #6292 from matrix-org/t3chguy/ts/9

This commit is contained in:
Michael Telatynski 2021-07-01 14:11:17 +01:00 committed by GitHub
commit 04902fa2e4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 498 additions and 447 deletions

View file

@ -41,7 +41,7 @@ import { Key } from "../../../Keyboard";
import { EMOTICON_TO_EMOJI } from "../../../emoji";
import { CommandCategories, CommandMap, parseCommandString } from "../../../SlashCommands";
import Range from "../../../editor/range";
import MessageComposerFormatBar from "./MessageComposerFormatBar";
import MessageComposerFormatBar, { Formatting } from "./MessageComposerFormatBar";
import DocumentOffset from "../../../editor/offset";
import { IDiff } from "../../../editor/diff";
import AutocompleteWrapperModel from "../../../editor/autocomplete";
@ -55,7 +55,7 @@ const REGEX_EMOTICON_WHITESPACE = new RegExp('(?:^|\\s)(' + EMOTICON_REGEX.sourc
const IS_MAC = navigator.platform.indexOf("Mac") !== -1;
function ctrlShortcutLabel(key) {
function ctrlShortcutLabel(key: string): string {
return (IS_MAC ? "⌘" : "Ctrl") + "+" + key;
}
@ -81,14 +81,6 @@ function selectionEquals(a: Partial<Selection>, b: Selection): boolean {
a.type === b.type;
}
enum Formatting {
Bold = "bold",
Italics = "italics",
Strikethrough = "strikethrough",
Code = "code",
Quote = "quote",
}
interface IProps {
model: EditorModel;
room: Room;
@ -111,9 +103,9 @@ interface IState {
@replaceableComponent("views.rooms.BasicMessageEditor")
export default class BasicMessageEditor extends React.Component<IProps, IState> {
private editorRef = createRef<HTMLDivElement>();
public readonly editorRef = createRef<HTMLDivElement>();
private autocompleteRef = createRef<Autocomplete>();
private formatBarRef = createRef<typeof MessageComposerFormatBar>();
private formatBarRef = createRef<MessageComposerFormatBar>();
private modifiedFlag = false;
private isIMEComposing = false;
@ -156,7 +148,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
}
private replaceEmoticon = (caretPosition: DocumentPosition) => {
private replaceEmoticon = (caretPosition: DocumentPosition): number => {
const { model } = this.props;
const range = model.startRange(caretPosition);
// expand range max 8 characters backwards from caretPosition,
@ -188,7 +180,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
private updateEditorState = (selection: Caret, inputType?: string, diff?: IDiff) => {
private updateEditorState = (selection: Caret, inputType?: string, diff?: IDiff): void => {
renderModel(this.editorRef.current, this.props.model);
if (selection) { // set the caret/selection
try {
@ -230,25 +222,25 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
private showPlaceholder() {
private showPlaceholder(): void {
// escape single quotes
const placeholder = this.props.placeholder.replace(/'/g, '\\\'');
this.editorRef.current.style.setProperty("--placeholder", `'${placeholder}'`);
this.editorRef.current.classList.add("mx_BasicMessageComposer_inputEmpty");
}
private hidePlaceholder() {
private hidePlaceholder(): void {
this.editorRef.current.classList.remove("mx_BasicMessageComposer_inputEmpty");
this.editorRef.current.style.removeProperty("--placeholder");
}
private onCompositionStart = () => {
private onCompositionStart = (): void => {
this.isIMEComposing = true;
// even if the model is empty, the composition text shouldn't be mixed with the placeholder
this.hidePlaceholder();
};
private onCompositionEnd = () => {
private onCompositionEnd = (): void => {
this.isIMEComposing = false;
// some browsers (Chrome) don't fire an input event after ending a composition,
// so trigger a model update after the composition is done by calling the input handler.
@ -271,14 +263,14 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
isComposing(event: React.KeyboardEvent) {
public isComposing(event: React.KeyboardEvent): boolean {
// checking the event.isComposing flag just in case any browser out there
// emits events related to the composition after compositionend
// has been fired
return !!(this.isIMEComposing || (event.nativeEvent && event.nativeEvent.isComposing));
}
private onCutCopy = (event: ClipboardEvent, type: string) => {
private onCutCopy = (event: ClipboardEvent, type: string): void => {
const selection = document.getSelection();
const text = selection.toString();
if (text) {
@ -296,15 +288,15 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
private onCopy = (event: ClipboardEvent) => {
private onCopy = (event: ClipboardEvent): void => {
this.onCutCopy(event, "copy");
};
private onCut = (event: ClipboardEvent) => {
private onCut = (event: ClipboardEvent): void => {
this.onCutCopy(event, "cut");
};
private onPaste = (event: ClipboardEvent<HTMLDivElement>) => {
private onPaste = (event: ClipboardEvent<HTMLDivElement>): boolean => {
event.preventDefault(); // we always handle the paste ourselves
if (this.props.onPaste && this.props.onPaste(event, this.props.model)) {
// to prevent double handling, allow props.onPaste to skip internal onPaste
@ -328,7 +320,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
replaceRangeAndMoveCaret(range, parts);
};
private onInput = (event: Partial<InputEvent>) => {
private onInput = (event: Partial<InputEvent>): void => {
// ignore any input while doing IME compositions
if (this.isIMEComposing) {
return;
@ -339,7 +331,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
this.props.model.update(text, event.inputType, caret);
};
private insertText(textToInsert: string, inputType = "insertText") {
private insertText(textToInsert: string, inputType = "insertText"): void {
const sel = document.getSelection();
const { caret, text } = getCaretOffsetAndText(this.editorRef.current, sel);
const newText = text.substr(0, caret.offset) + textToInsert + text.substr(caret.offset);
@ -353,14 +345,14 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
// we don't need to. But if the user is navigating the caret without input
// we need to recalculate it, to be able to know where to insert content after
// losing focus
private setLastCaretFromPosition(position: DocumentPosition) {
private setLastCaretFromPosition(position: DocumentPosition): void {
const { model } = this.props;
this._isCaretAtEnd = position.isAtEnd(model);
this.lastCaret = position.asOffset(model);
this.lastSelection = cloneSelection(document.getSelection());
}
private refreshLastCaretIfNeeded() {
private refreshLastCaretIfNeeded(): DocumentOffset {
// XXX: needed when going up and down in editing messages ... not sure why yet
// because the editors should stop doing this when when blurred ...
// maybe it's on focus and the _editorRef isn't available yet or something.
@ -377,38 +369,38 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
return this.lastCaret;
}
clearUndoHistory() {
public clearUndoHistory(): void {
this.historyManager.clear();
}
getCaret() {
public getCaret(): DocumentOffset {
return this.lastCaret;
}
isSelectionCollapsed() {
public isSelectionCollapsed(): boolean {
return !this.lastSelection || this.lastSelection.isCollapsed;
}
isCaretAtStart() {
public isCaretAtStart(): boolean {
return this.getCaret().offset === 0;
}
isCaretAtEnd() {
public isCaretAtEnd(): boolean {
return this._isCaretAtEnd;
}
private onBlur = () => {
private onBlur = (): void => {
document.removeEventListener("selectionchange", this.onSelectionChange);
};
private onFocus = () => {
private onFocus = (): void => {
document.addEventListener("selectionchange", this.onSelectionChange);
// force to recalculate
this.lastSelection = null;
this.refreshLastCaretIfNeeded();
};
private onSelectionChange = () => {
private onSelectionChange = (): void => {
const { isEmpty } = this.props.model;
this.refreshLastCaretIfNeeded();
@ -427,7 +419,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
private onKeyDown = (event: React.KeyboardEvent) => {
private onKeyDown = (event: React.KeyboardEvent): void => {
const model = this.props.model;
let handled = false;
const action = getKeyBindingsManager().getMessageComposerAction(event);
@ -523,7 +515,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
};
private async tabCompleteName() {
private async tabCompleteName(): Promise<void> {
try {
await new Promise<void>(resolve => this.setState({ showVisualBell: false }, resolve));
const { model } = this.props;
@ -557,27 +549,27 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
}
isModified() {
public isModified(): boolean {
return this.modifiedFlag;
}
private onAutoCompleteConfirm = (completion: ICompletion) => {
private onAutoCompleteConfirm = (completion: ICompletion): void => {
this.modifiedFlag = true;
this.props.model.autoComplete.onComponentConfirm(completion);
};
private onAutoCompleteSelectionChange = (completion: ICompletion, completionIndex: number) => {
private onAutoCompleteSelectionChange = (completion: ICompletion, completionIndex: number): void => {
this.modifiedFlag = true;
this.props.model.autoComplete.onComponentSelectionChange(completion);
this.setState({ completionIndex });
};
private configureEmoticonAutoReplace = () => {
private configureEmoticonAutoReplace = (): void => {
const shouldReplace = SettingsStore.getValue('MessageComposerInput.autoReplaceEmoji');
this.props.model.setTransformCallback(shouldReplace ? this.replaceEmoticon : null);
};
private configureShouldShowPillAvatar = () => {
private configureShouldShowPillAvatar = (): void => {
const showPillAvatar = SettingsStore.getValue("Pill.shouldShowPillAvatar");
this.setState({ showPillAvatar });
};
@ -611,8 +603,8 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
this.editorRef.current.focus();
}
private getInitialCaretPosition() {
let caretPosition;
private getInitialCaretPosition(): DocumentPosition {
let caretPosition: DocumentPosition;
if (this.props.initialCaret) {
// if restoring state from a previous editor,
// restore caret position from the state
@ -625,7 +617,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
return caretPosition;
}
private onFormatAction = (action: Formatting) => {
private onFormatAction = (action: Formatting): void => {
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();
@ -680,9 +672,9 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
});
const shortcuts = {
bold: ctrlShortcutLabel("B"),
italics: ctrlShortcutLabel("I"),
quote: ctrlShortcutLabel(">"),
[Formatting.Bold]: ctrlShortcutLabel("B"),
[Formatting.Italics]: ctrlShortcutLabel("I"),
[Formatting.Quote]: ctrlShortcutLabel(">"),
};
const { completionIndex } = this.state;
@ -714,11 +706,11 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
</div>);
}
focus() {
public focus(): void {
this.editorRef.current.focus();
}
public insertMention(userId: string) {
public insertMention(userId: string): void {
const { model } = this.props;
const { partCreator } = model;
const member = this.props.room.getMember(userId);
@ -736,7 +728,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
this.focus();
}
public insertQuotedMessage(event: MatrixEvent) {
public insertQuotedMessage(event: MatrixEvent): void {
const { model } = this.props;
const { partCreator } = model;
const quoteParts = parseEvent(event, partCreator, { isQuotedMessage: true });
@ -751,7 +743,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
this.focus();
}
public insertPlaintext(text: string) {
public insertPlaintext(text: string): void {
const { model } = this.props;
const { partCreator } = model;
const caret = this.getCaret();

View file

@ -1,6 +1,5 @@
/*
Copyright 2019 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,37 +13,42 @@ 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 * as sdk from '../../../index';
import React, { createRef, KeyboardEvent } from 'react';
import classNames from 'classnames';
import { EventStatus, IContent, MatrixEvent } from 'matrix-js-sdk/src/models/event';
import { _t, _td } from '../../../languageHandler';
import PropTypes from 'prop-types';
import dis from '../../../dispatcher/dispatcher';
import EditorModel from '../../../editor/model';
import { getCaretOffsetAndText } from '../../../editor/dom';
import { htmlSerializeIfNeeded, textSerialize, containsEmote, stripEmoteCommand } from '../../../editor/serialize';
import { findEditableEvent } from '../../../utils/EventUtils';
import { parseEvent } from '../../../editor/deserialize';
import { CommandPartCreator } from '../../../editor/parts';
import { CommandPartCreator, Part, PartCreator } from '../../../editor/parts';
import EditorStateTransfer from '../../../utils/EditorStateTransfer';
import classNames from 'classnames';
import { EventStatus } from 'matrix-js-sdk/src/models/event';
import BasicMessageComposer from "./BasicMessageComposer";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import { CommandCategories, getCommand } from '../../../SlashCommands';
import { Command, CommandCategories, getCommand } from '../../../SlashCommands';
import { Action } from "../../../dispatcher/actions";
import CountlyAnalytics from "../../../CountlyAnalytics";
import { getKeyBindingsManager, MessageComposerAction } from '../../../KeyBindingsManager';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import SendHistoryManager from '../../../SendHistoryManager';
import Modal from '../../../Modal';
import { MsgType } from 'matrix-js-sdk/src/@types/event';
import { Room } from 'matrix-js-sdk/src/models/room';
import ErrorDialog from "../dialogs/ErrorDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
import { ActionPayload } from "../../../dispatcher/payloads";
import AccessibleButton from '../elements/AccessibleButton';
function _isReply(mxEvent) {
function eventIsReply(mxEvent: MatrixEvent): boolean {
const relatesTo = mxEvent.getContent()["m.relates_to"];
const isReply = !!(relatesTo && relatesTo["m.in_reply_to"]);
return isReply;
return !!(relatesTo && relatesTo["m.in_reply_to"]);
}
function getHtmlReplyFallback(mxEvent) {
function getHtmlReplyFallback(mxEvent: MatrixEvent): string {
const html = mxEvent.getContent().formatted_body;
if (!html) {
return "";
@ -54,7 +58,7 @@ function getHtmlReplyFallback(mxEvent) {
return (mxReply && mxReply.outerHTML) || "";
}
function getTextReplyFallback(mxEvent) {
function getTextReplyFallback(mxEvent: MatrixEvent): string {
const body = mxEvent.getContent().body;
const lines = body.split("\n").map(l => l.trim());
if (lines.length > 2 && lines[0].startsWith("> ") && lines[1].length === 0) {
@ -63,12 +67,12 @@ function getTextReplyFallback(mxEvent) {
return "";
}
function createEditContent(model, editedEvent) {
function createEditContent(model: EditorModel, editedEvent: MatrixEvent): IContent {
const isEmote = containsEmote(model);
if (isEmote) {
model = stripEmoteCommand(model);
}
const isReply = _isReply(editedEvent);
const isReply = eventIsReply(editedEvent);
let plainPrefix = "";
let htmlPrefix = "";
@ -79,11 +83,11 @@ function createEditContent(model, editedEvent) {
const body = textSerialize(model);
const newContent = {
"msgtype": isEmote ? "m.emote" : "m.text",
const newContent: IContent = {
"msgtype": isEmote ? MsgType.Emote : MsgType.Text,
"body": body,
};
const contentBody = {
const contentBody: IContent = {
msgtype: newContent.msgtype,
body: `${plainPrefix} * ${body}`,
};
@ -105,55 +109,60 @@ function createEditContent(model, editedEvent) {
}, contentBody);
}
interface IProps {
editState: EditorStateTransfer;
className?: string;
}
interface IState {
saveDisabled: boolean;
}
@replaceableComponent("views.rooms.EditMessageComposer")
export default class EditMessageComposer extends React.Component {
static propTypes = {
// the message event being edited
editState: PropTypes.instanceOf(EditorStateTransfer).isRequired,
};
export default class EditMessageComposer extends React.Component<IProps, IState> {
static contextType = MatrixClientContext;
context!: React.ContextType<typeof MatrixClientContext>;
constructor(props, context) {
super(props, context);
this.model = null;
this._editorRef = null;
private readonly editorRef = createRef<BasicMessageComposer>();
private readonly dispatcherRef: string;
private model: EditorModel = null;
constructor(props: IProps, context: React.ContextType<typeof MatrixClientContext>) {
super(props);
this.context = context; // otherwise React will only set it prior to render due to type def above
this.state = {
saveDisabled: true,
};
this._createEditorModel();
window.addEventListener("beforeunload", this._saveStoredEditorState);
this.createEditorModel();
window.addEventListener("beforeunload", this.saveStoredEditorState);
this.dispatcherRef = dis.register(this.onAction);
}
_setEditorRef = ref => {
this._editorRef = ref;
};
_getRoom() {
private getRoom(): Room {
return this.context.getRoom(this.props.editState.getEvent().getRoomId());
}
_onKeyDown = (event) => {
private onKeyDown = (event: KeyboardEvent): void => {
// ignore any keypress while doing IME compositions
if (this._editorRef.isComposing(event)) {
if (this.editorRef.current?.isComposing(event)) {
return;
}
const action = getKeyBindingsManager().getMessageComposerAction(event);
switch (action) {
case MessageComposerAction.Send:
this._sendEdit();
this.sendEdit();
event.preventDefault();
break;
case MessageComposerAction.CancelEditing:
this._cancelEdit();
this.cancelEdit();
break;
case MessageComposerAction.EditPrevMessage: {
if (this._editorRef.isModified() || !this._editorRef.isCaretAtStart()) {
if (this.editorRef.current?.isModified() || !this.editorRef.current?.isCaretAtStart()) {
return;
}
const previousEvent = findEditableEvent(this._getRoom(), false,
const previousEvent = findEditableEvent(this.getRoom(), false,
this.props.editState.getEvent().getId());
if (previousEvent) {
dis.dispatch({ action: 'edit_event', event: previousEvent });
@ -162,14 +171,14 @@ export default class EditMessageComposer extends React.Component {
break;
}
case MessageComposerAction.EditNextMessage: {
if (this._editorRef.isModified() || !this._editorRef.isCaretAtEnd()) {
if (this.editorRef.current?.isModified() || !this.editorRef.current?.isCaretAtEnd()) {
return;
}
const nextEvent = findEditableEvent(this._getRoom(), true, this.props.editState.getEvent().getId());
const nextEvent = findEditableEvent(this.getRoom(), true, this.props.editState.getEvent().getId());
if (nextEvent) {
dis.dispatch({ action: 'edit_event', event: nextEvent });
} else {
this._clearStoredEditorState();
this.clearStoredEditorState();
dis.dispatch({ action: 'edit_event', event: null });
dis.fire(Action.FocusComposer);
}
@ -177,32 +186,32 @@ export default class EditMessageComposer extends React.Component {
break;
}
}
};
private get editorRoomKey(): string {
return `mx_edit_room_${this.getRoom().roomId}`;
}
get _editorRoomKey() {
return `mx_edit_room_${this._getRoom().roomId}`;
}
get _editorStateKey() {
private get editorStateKey(): string {
return `mx_edit_state_${this.props.editState.getEvent().getId()}`;
}
_cancelEdit = () => {
this._clearStoredEditorState();
private cancelEdit = (): void => {
this.clearStoredEditorState();
dis.dispatch({ action: "edit_event", event: null });
dis.fire(Action.FocusComposer);
};
private get shouldSaveStoredEditorState(): boolean {
return localStorage.getItem(this.editorRoomKey) !== null;
}
get _shouldSaveStoredEditorState() {
return localStorage.getItem(this._editorRoomKey) !== null;
}
_restoreStoredEditorState(partCreator) {
const json = localStorage.getItem(this._editorStateKey);
private restoreStoredEditorState(partCreator: PartCreator): Part[] {
const json = localStorage.getItem(this.editorStateKey);
if (json) {
try {
const { parts: serializedParts } = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
const parts: Part[] = serializedParts.map(p => partCreator.deserializePart(p));
return parts;
} catch (e) {
console.error("Error parsing editing state: ", e);
@ -210,25 +219,25 @@ export default class EditMessageComposer extends React.Component {
}
}
_clearStoredEditorState() {
localStorage.removeItem(this._editorRoomKey);
localStorage.removeItem(this._editorStateKey);
private clearStoredEditorState(): void {
localStorage.removeItem(this.editorRoomKey);
localStorage.removeItem(this.editorStateKey);
}
_clearPreviousEdit() {
if (localStorage.getItem(this._editorRoomKey)) {
localStorage.removeItem(`mx_edit_state_${localStorage.getItem(this._editorRoomKey)}`);
private clearPreviousEdit(): void {
if (localStorage.getItem(this.editorRoomKey)) {
localStorage.removeItem(`mx_edit_state_${localStorage.getItem(this.editorRoomKey)}`);
}
}
_saveStoredEditorState() {
private saveStoredEditorState(): void {
const item = SendHistoryManager.createItem(this.model);
this._clearPreviousEdit();
localStorage.setItem(this._editorRoomKey, this.props.editState.getEvent().getId());
localStorage.setItem(this._editorStateKey, JSON.stringify(item));
this.clearPreviousEdit();
localStorage.setItem(this.editorRoomKey, this.props.editState.getEvent().getId());
localStorage.setItem(this.editorStateKey, JSON.stringify(item));
}
_isSlashCommand() {
private isSlashCommand(): boolean {
const parts = this.model.parts;
const firstPart = parts[0];
if (firstPart) {
@ -244,10 +253,10 @@ export default class EditMessageComposer extends React.Component {
return false;
}
_isContentModified(newContent) {
private isContentModified(newContent: IContent): boolean {
// if nothing has changed then bail
const oldContent = this.props.editState.getEvent().getContent();
if (!this._editorRef.isModified() ||
if (!this.editorRef.current?.isModified() ||
(oldContent["msgtype"] === newContent["msgtype"] && oldContent["body"] === newContent["body"] &&
oldContent["format"] === newContent["format"] &&
oldContent["formatted_body"] === newContent["formatted_body"])) {
@ -256,7 +265,7 @@ export default class EditMessageComposer extends React.Component {
return true;
}
_getSlashCommand() {
private getSlashCommand(): [Command, string, string] {
const commandText = this.model.parts.reduce((text, part) => {
// use mxid to textify user pills in a command
if (part.type === "user-pill") {
@ -268,7 +277,7 @@ export default class EditMessageComposer extends React.Component {
return [cmd, args, commandText];
}
async _runSlashCommand(cmd, args, roomId) {
private async runSlashCommand(cmd: Command, args: string, roomId: string): Promise<void> {
const result = cmd.run(roomId, args);
let messageContent;
let error = result.error;
@ -285,7 +294,6 @@ export default class EditMessageComposer extends React.Component {
}
if (error) {
console.error("Command failure: %s", error);
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
// assume the error is a server error when the command is async
const isServerError = !!result.promise;
const title = isServerError ? _td("Server error") : _td("Command error");
@ -309,7 +317,7 @@ export default class EditMessageComposer extends React.Component {
}
}
_sendEdit = async () => {
private sendEdit = async (): Promise<void> => {
const startTime = CountlyAnalytics.getTimestamp();
const editedEvent = this.props.editState.getEvent();
const editContent = createEditContent(this.model, editedEvent);
@ -318,20 +326,19 @@ export default class EditMessageComposer extends React.Component {
let shouldSend = true;
// If content is modified then send an updated event into the room
if (this._isContentModified(newContent)) {
if (this.isContentModified(newContent)) {
const roomId = editedEvent.getRoomId();
if (!containsEmote(this.model) && this._isSlashCommand()) {
const [cmd, args, commandText] = this._getSlashCommand();
if (!containsEmote(this.model) && this.isSlashCommand()) {
const [cmd, args, commandText] = this.getSlashCommand();
if (cmd) {
if (cmd.category === CommandCategories.messages) {
editContent["m.new_content"] = await this._runSlashCommand(cmd, args, roomId);
editContent["m.new_content"] = await this.runSlashCommand(cmd, args, roomId);
} else {
this._runSlashCommand(cmd, args, roomId);
this.runSlashCommand(cmd, args, roomId);
shouldSend = false;
}
} else {
// ask the user if their unknown command should be sent as a message
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const { finished } = Modal.createTrackedDialog("Unknown command", "", QuestionDialog, {
title: _t("Unknown Command"),
description: <div>
@ -358,9 +365,9 @@ export default class EditMessageComposer extends React.Component {
}
}
if (shouldSend) {
this._cancelPreviousPendingEdit();
this.cancelPreviousPendingEdit();
const prom = this.context.sendMessage(roomId, editContent);
this._clearStoredEditorState();
this.clearStoredEditorState();
dis.dispatch({ action: "message_sent" });
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, true, false, editContent);
}
@ -371,7 +378,7 @@ export default class EditMessageComposer extends React.Component {
dis.fire(Action.FocusComposer);
};
_cancelPreviousPendingEdit() {
private cancelPreviousPendingEdit(): void {
const originalEvent = this.props.editState.getEvent();
const previousEdit = originalEvent.replacingEvent();
if (previousEdit && (
@ -389,23 +396,23 @@ export default class EditMessageComposer extends React.Component {
const sel = document.getSelection();
let caret;
if (sel.focusNode) {
caret = getCaretOffsetAndText(this._editorRef, sel).caret;
caret = getCaretOffsetAndText(this.editorRef.current?.editorRef.current, sel).caret;
}
const parts = this.model.serializeParts();
// if caret is undefined because for some reason there isn't a valid selection,
// then when mounting the editor again with the same editor state,
// it will set the cursor at the end.
this.props.editState.setEditorState(caret, parts);
window.removeEventListener("beforeunload", this._saveStoredEditorState);
if (this._shouldSaveStoredEditorState) {
this._saveStoredEditorState();
window.removeEventListener("beforeunload", this.saveStoredEditorState);
if (this.shouldSaveStoredEditorState) {
this.saveStoredEditorState();
}
dis.unregister(this.dispatcherRef);
}
_createEditorModel() {
private createEditorModel(): void {
const { editState } = this.props;
const room = this._getRoom();
const room = this.getRoom();
const partCreator = new CommandPartCreator(room, this.context);
let parts;
if (editState.hasEditorState()) {
@ -414,13 +421,13 @@ export default class EditMessageComposer extends React.Component {
parts = editState.getSerializedParts().map(p => partCreator.deserializePart(p));
} else {
//otherwise, either restore serialized parts from localStorage or parse the body of the event
parts = this._restoreStoredEditorState(partCreator) || parseEvent(editState.getEvent(), partCreator);
parts = this.restoreStoredEditorState(partCreator) || parseEvent(editState.getEvent(), partCreator);
}
this.model = new EditorModel(parts, partCreator);
this._saveStoredEditorState();
this.saveStoredEditorState();
}
_getInitialCaretPosition() {
private getInitialCaretPosition(): CaretPosition {
const { editState } = this.props;
let caretPosition;
if (editState.hasEditorState() && editState.getCaret()) {
@ -435,8 +442,8 @@ export default class EditMessageComposer extends React.Component {
return caretPosition;
}
_onChange = () => {
if (!this.state.saveDisabled || !this._editorRef || !this._editorRef.isModified()) {
private onChange = (): void => {
if (!this.state.saveDisabled || !this.editorRef.current?.isModified()) {
return;
}
@ -445,33 +452,34 @@ export default class EditMessageComposer extends React.Component {
});
};
onAction = payload => {
if (payload.action === "edit_composer_insert" && this._editorRef) {
private onAction = (payload: ActionPayload) => {
if (payload.action === "edit_composer_insert" && this.editorRef.current) {
if (payload.userId) {
this._editorRef.insertMention(payload.userId);
this.editorRef.current?.insertMention(payload.userId);
} else if (payload.event) {
this._editorRef.insertQuotedMessage(payload.event);
this.editorRef.current?.insertQuotedMessage(payload.event);
} else if (payload.text) {
this._editorRef.insertPlaintext(payload.text);
this.editorRef.current?.insertPlaintext(payload.text);
}
}
};
render() {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
return (<div className={classNames("mx_EditMessageComposer", this.props.className)} onKeyDown={this._onKeyDown}>
return (<div className={classNames("mx_EditMessageComposer", this.props.className)} onKeyDown={this.onKeyDown}>
<BasicMessageComposer
ref={this._setEditorRef}
ref={this.editorRef}
model={this.model}
room={this._getRoom()}
room={this.getRoom()}
initialCaret={this.props.editState.getCaret()}
label={_t("Edit message")}
onChange={this._onChange}
onChange={this.onChange}
/>
<div className="mx_EditMessageComposer_buttons">
<AccessibleButton kind="secondary" onClick={this._cancelEdit}>{_t("Cancel")}</AccessibleButton>
<AccessibleButton kind="primary" onClick={this._sendEdit} disabled={this.state.saveDisabled}>
{_t("Save")}
<AccessibleButton kind="secondary" onClick={this.cancelEdit}>
{ _t("Cancel") }
</AccessibleButton>
<AccessibleButton kind="primary" onClick={this.sendEdit} disabled={this.state.saveDisabled}>
{ _t("Save") }
</AccessibleButton>
</div>
</div>);

View file

@ -43,6 +43,7 @@ import { E2EStatus } from '../../../utils/ShieldUtils';
import SendMessageComposer from "./SendMessageComposer";
import { ComposerInsertPayload } from "../../../dispatcher/payloads/ComposerInsertPayload";
import { Action } from "../../../dispatcher/actions";
import EditorModel from "../../../editor/model";
interface IComposerAvatarProps {
me: object;
@ -318,14 +319,14 @@ export default class MessageComposer extends React.Component<IProps, IState> {
}
};
addEmoji(emoji: string) {
private addEmoji(emoji: string) {
dis.dispatch<ComposerInsertPayload>({
action: Action.ComposerInsert,
text: emoji,
});
}
sendMessage = async () => {
private sendMessage = async () => {
if (this.state.haveRecording && this.voiceRecordingButton) {
// There shouldn't be any text message to send when a voice recording is active, so
// just send out the voice recording.
@ -333,11 +334,10 @@ export default class MessageComposer extends React.Component<IProps, IState> {
return;
}
// XXX: Private function access
this.messageComposerInput._sendMessage();
this.messageComposerInput.sendMessage();
};
onChange = (model) => {
private onChange = (model: EditorModel) => {
this.setState({
isComposerEmpty: model.isEmpty,
});

View file

@ -1,5 +1,5 @@
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,21 +14,35 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import React, { createRef } from 'react';
import classNames from 'classnames';
import { _t } from '../../../languageHandler';
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import { replaceableComponent } from "../../../utils/replaceableComponent";
@replaceableComponent("views.rooms.MessageComposerFormatBar")
export default class MessageComposerFormatBar extends React.PureComponent {
static propTypes = {
onAction: PropTypes.func.isRequired,
shortcuts: PropTypes.object.isRequired,
};
export enum Formatting {
Bold = "bold",
Italics = "italics",
Strikethrough = "strikethrough",
Code = "code",
Quote = "quote",
}
constructor(props) {
interface IProps {
shortcuts: Partial<Record<Formatting, string>>;
onAction(action: Formatting): void;
}
interface IState {
visible: boolean;
}
@replaceableComponent("views.rooms.MessageComposerFormatBar")
export default class MessageComposerFormatBar extends React.PureComponent<IProps, IState> {
private readonly formatBarRef = createRef<HTMLDivElement>();
constructor(props: IProps) {
super(props);
this.state = { visible: false };
}
@ -37,49 +51,53 @@ export default class MessageComposerFormatBar extends React.PureComponent {
const classes = classNames("mx_MessageComposerFormatBar", {
"mx_MessageComposerFormatBar_shown": this.state.visible,
});
return (<div className={classes} ref={ref => this._formatBarRef = ref}>
<FormatButton label={_t("Bold")} onClick={() => this.props.onAction("bold")} icon="Bold" shortcut={this.props.shortcuts.bold} visible={this.state.visible} />
<FormatButton label={_t("Italics")} onClick={() => this.props.onAction("italics")} icon="Italic" shortcut={this.props.shortcuts.italics} visible={this.state.visible} />
<FormatButton label={_t("Strikethrough")} onClick={() => this.props.onAction("strikethrough")} icon="Strikethrough" visible={this.state.visible} />
<FormatButton label={_t("Code block")} onClick={() => this.props.onAction("code")} icon="Code" visible={this.state.visible} />
<FormatButton label={_t("Quote")} onClick={() => this.props.onAction("quote")} icon="Quote" shortcut={this.props.shortcuts.quote} visible={this.state.visible} />
return (<div className={classes} ref={this.formatBarRef}>
<FormatButton label={_t("Bold")} onClick={() => this.props.onAction(Formatting.Bold)} icon="Bold" shortcut={this.props.shortcuts.bold} visible={this.state.visible} />
<FormatButton label={_t("Italics")} onClick={() => this.props.onAction(Formatting.Italics)} icon="Italic" shortcut={this.props.shortcuts.italics} visible={this.state.visible} />
<FormatButton label={_t("Strikethrough")} onClick={() => this.props.onAction(Formatting.Strikethrough)} icon="Strikethrough" visible={this.state.visible} />
<FormatButton label={_t("Code block")} onClick={() => this.props.onAction(Formatting.Code)} icon="Code" visible={this.state.visible} />
<FormatButton label={_t("Quote")} onClick={() => this.props.onAction(Formatting.Quote)} icon="Quote" shortcut={this.props.shortcuts.quote} visible={this.state.visible} />
</div>);
}
showAt(selectionRect) {
public showAt(selectionRect: DOMRect): void {
if (!this.formatBarRef.current) return;
this.setState({ visible: true });
const parentRect = this._formatBarRef.parentElement.getBoundingClientRect();
this._formatBarRef.style.left = `${selectionRect.left - parentRect.left}px`;
const parentRect = this.formatBarRef.current.parentElement.getBoundingClientRect();
this.formatBarRef.current.style.left = `${selectionRect.left - parentRect.left}px`;
// 12 is half the height of the bar (e.g. to center it) and 16 is an offset that felt ok.
this._formatBarRef.style.top = `${selectionRect.top - parentRect.top - 16 - 12}px`;
this.formatBarRef.current.style.top = `${selectionRect.top - parentRect.top - 16 - 12}px`;
}
hide() {
public hide(): void {
this.setState({ visible: false });
}
}
class FormatButton extends React.PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
icon: PropTypes.string.isRequired,
shortcut: PropTypes.string,
visible: PropTypes.bool,
};
interface IFormatButtonProps {
label: string;
icon: string;
shortcut?: string;
visible?: boolean;
onClick(): void;
}
class FormatButton extends React.PureComponent<IFormatButtonProps> {
render() {
const className = `mx_MessageComposerFormatBar_button mx_MessageComposerFormatBar_buttonIcon${this.props.icon}`;
let shortcut;
if (this.props.shortcut) {
shortcut = <div className="mx_MessageComposerFormatBar_tooltipShortcut">{this.props.shortcut}</div>;
shortcut = <div className="mx_MessageComposerFormatBar_tooltipShortcut">
{ this.props.shortcut }
</div>;
}
const tooltip = <div>
<div className="mx_Tooltip_title">
{this.props.label}
{ this.props.label }
</div>
<div className="mx_Tooltip_sub">
{shortcut}
{ shortcut }
</div>
</div>;

View file

@ -1,6 +1,5 @@
/*
Copyright 2019 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2019 - 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,8 +13,11 @@ 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 React, { ClipboardEvent, createRef, KeyboardEvent } from 'react';
import EMOJI_REGEX from 'emojibase-regex';
import { IContent, MatrixEvent } from 'matrix-js-sdk/src/models/event';
import dis from '../../../dispatcher/dispatcher';
import EditorModel from '../../../editor/model';
import {
@ -27,13 +29,12 @@ import {
startsWith,
stripPrefix,
} from '../../../editor/serialize';
import { CommandPartCreator } from '../../../editor/parts';
import { CommandPartCreator, Part, PartCreator, SerializedPart } from '../../../editor/parts';
import BasicMessageComposer from "./BasicMessageComposer";
import ReplyThread from "../elements/ReplyThread";
import { findEditableEvent } from '../../../utils/EventUtils';
import SendHistoryManager from "../../../SendHistoryManager";
import { CommandCategories, getCommand } from '../../../SlashCommands';
import * as sdk from '../../../index';
import { Command, CommandCategories, getCommand } from '../../../SlashCommands';
import Modal from '../../../Modal';
import { _t, _td } from '../../../languageHandler';
import ContentMessages from '../../../ContentMessages';
@ -44,12 +45,20 @@ import { containsEmoji } from "../../../effects/utils";
import { CHAT_EFFECTS } from '../../../effects';
import CountlyAnalytics from "../../../CountlyAnalytics";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import EMOJI_REGEX from 'emojibase-regex';
import { getKeyBindingsManager, MessageComposerAction } from '../../../KeyBindingsManager';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import SettingsStore from '../../../settings/SettingsStore';
import { RoomPermalinkCreator } from "../../../utils/permalinks/Permalinks";
import { Room } from 'matrix-js-sdk/src/models/room';
import ErrorDialog from "../dialogs/ErrorDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
import { ActionPayload } from "../../../dispatcher/payloads";
function addReplyToMessageContent(content, repliedToEvent, permalinkCreator) {
function addReplyToMessageContent(
content: IContent,
repliedToEvent: MatrixEvent,
permalinkCreator: RoomPermalinkCreator,
): void {
const replyContent = ReplyThread.makeReplyMixIn(repliedToEvent);
Object.assign(content, replyContent);
@ -65,7 +74,11 @@ function addReplyToMessageContent(content, repliedToEvent, permalinkCreator) {
}
// exported for tests
export function createMessageContent(model, permalinkCreator, replyToEvent) {
export function createMessageContent(
model: EditorModel,
permalinkCreator: RoomPermalinkCreator,
replyToEvent: MatrixEvent,
): IContent {
const isEmote = containsEmote(model);
if (isEmote) {
model = stripEmoteCommand(model);
@ -76,7 +89,7 @@ export function createMessageContent(model, permalinkCreator, replyToEvent) {
model = unescapeMessage(model);
const body = textSerialize(model);
const content = {
const content: IContent = {
msgtype: isEmote ? "m.emote" : "m.text",
body: body,
};
@ -94,7 +107,7 @@ export function createMessageContent(model, permalinkCreator, replyToEvent) {
}
// exported for tests
export function isQuickReaction(model) {
export function isQuickReaction(model: EditorModel): boolean {
const parts = model.parts;
if (parts.length == 0) return false;
const text = textSerialize(model);
@ -111,46 +124,48 @@ export function isQuickReaction(model) {
return false;
}
interface IProps {
room: Room;
placeholder?: string;
permalinkCreator: RoomPermalinkCreator;
replyToEvent?: MatrixEvent;
disabled?: boolean;
onChange?(model: EditorModel): void;
}
@replaceableComponent("views.rooms.SendMessageComposer")
export default class SendMessageComposer extends React.Component {
static propTypes = {
room: PropTypes.object.isRequired,
placeholder: PropTypes.string,
permalinkCreator: PropTypes.object.isRequired,
replyToEvent: PropTypes.object,
onChange: PropTypes.func,
disabled: PropTypes.bool,
};
export default class SendMessageComposer extends React.Component<IProps> {
static contextType = MatrixClientContext;
context!: React.ContextType<typeof MatrixClientContext>;
constructor(props, context) {
super(props, context);
this.model = null;
this._editorRef = null;
this.currentlyComposedEditorState = null;
private readonly prepareToEncrypt?: RateLimitedFunc;
private readonly editorRef = createRef<BasicMessageComposer>();
private model: EditorModel = null;
private currentlyComposedEditorState: SerializedPart[] = null;
private dispatcherRef: string;
private sendHistoryManager: SendHistoryManager;
constructor(props: IProps, context: React.ContextType<typeof MatrixClientContext>) {
super(props);
this.context = context; // otherwise React will only set it prior to render due to type def above
if (this.context.isCryptoEnabled() && this.context.isRoomEncrypted(this.props.room.roomId)) {
this._prepareToEncrypt = new RateLimitedFunc(() => {
this.prepareToEncrypt = new RateLimitedFunc(() => {
this.context.prepareToEncrypt(this.props.room);
}, 60000);
}
window.addEventListener("beforeunload", this._saveStoredEditorState);
window.addEventListener("beforeunload", this.saveStoredEditorState);
}
_setEditorRef = ref => {
this._editorRef = ref;
};
_onKeyDown = (event) => {
private onKeyDown = (event: KeyboardEvent): void => {
// ignore any keypress while doing IME compositions
if (this._editorRef.isComposing(event)) {
if (this.editorRef.current?.isComposing(event)) {
return;
}
const action = getKeyBindingsManager().getMessageComposerAction(event);
switch (action) {
case MessageComposerAction.Send:
this._sendMessage();
this.sendMessage();
event.preventDefault();
break;
case MessageComposerAction.SelectPrevSendHistory:
@ -165,7 +180,7 @@ export default class SendMessageComposer extends React.Component {
}
case MessageComposerAction.EditPrevMessage:
// selection must be collapsed and caret at start
if (this._editorRef.isSelectionCollapsed() && this._editorRef.isCaretAtStart()) {
if (this.editorRef.current?.isSelectionCollapsed() && this.editorRef.current?.isCaretAtStart()) {
const editEvent = findEditableEvent(this.props.room, false);
if (editEvent) {
// We're selecting history, so prevent the key event from doing anything else
@ -184,29 +199,29 @@ export default class SendMessageComposer extends React.Component {
});
break;
default:
if (this._prepareToEncrypt) {
if (this.prepareToEncrypt) {
// This needs to be last!
this._prepareToEncrypt();
this.prepareToEncrypt();
}
}
};
// we keep sent messages/commands in a separate history (separate from undo history)
// so you can alt+up/down in them
selectSendHistory(up) {
private selectSendHistory(up: boolean): boolean {
const delta = up ? -1 : 1;
// True if we are not currently selecting history, but composing a message
if (this.sendHistoryManager.currentIndex === this.sendHistoryManager.history.length) {
// We can't go any further - there isn't any more history, so nop.
if (!up) {
return;
return false;
}
this.currentlyComposedEditorState = this.model.serializeParts();
} else if (this.sendHistoryManager.currentIndex + delta === this.sendHistoryManager.history.length) {
// True when we return to the message being composed currently
this.model.reset(this.currentlyComposedEditorState);
this.sendHistoryManager.currentIndex = this.sendHistoryManager.history.length;
return;
return true;
}
const { parts, replyEventId } = this.sendHistoryManager.getItem(delta);
dis.dispatch({
@ -215,11 +230,12 @@ export default class SendMessageComposer extends React.Component {
});
if (parts) {
this.model.reset(parts);
this._editorRef.focus();
this.editorRef.current?.focus();
}
return true;
}
_isSlashCommand() {
private isSlashCommand(): boolean {
const parts = this.model.parts;
const firstPart = parts[0];
if (firstPart) {
@ -237,7 +253,7 @@ export default class SendMessageComposer extends React.Component {
return false;
}
_sendQuickReaction() {
private sendQuickReaction(): void {
const timeline = this.props.room.getLiveTimeline();
const events = timeline.getEvents();
const reaction = this.model.parts[1].text;
@ -272,7 +288,7 @@ export default class SendMessageComposer extends React.Component {
}
}
_getSlashCommand() {
private getSlashCommand(): [Command, string, string] {
const commandText = this.model.parts.reduce((text, part) => {
// use mxid to textify user pills in a command
if (part.type === "user-pill") {
@ -284,7 +300,7 @@ export default class SendMessageComposer extends React.Component {
return [cmd, args, commandText];
}
async _runSlashCommand(cmd, args) {
private async runSlashCommand(cmd: Command, args: string): Promise<void> {
const result = cmd.run(this.props.room.roomId, args);
let messageContent;
let error = result.error;
@ -302,7 +318,6 @@ export default class SendMessageComposer extends React.Component {
}
if (error) {
console.error("Command failure: %s", error);
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
// assume the error is a server error when the command is async
const isServerError = !!result.promise;
const title = isServerError ? _td("Server error") : _td("Command error");
@ -326,7 +341,7 @@ export default class SendMessageComposer extends React.Component {
}
}
async _sendMessage() {
public async sendMessage(): Promise<void> {
if (this.model.isEmpty) {
return;
}
@ -335,21 +350,20 @@ export default class SendMessageComposer extends React.Component {
let shouldSend = true;
let content;
if (!containsEmote(this.model) && this._isSlashCommand()) {
const [cmd, args, commandText] = this._getSlashCommand();
if (!containsEmote(this.model) && this.isSlashCommand()) {
const [cmd, args, commandText] = this.getSlashCommand();
if (cmd) {
if (cmd.category === CommandCategories.messages) {
content = await this._runSlashCommand(cmd, args);
content = await this.runSlashCommand(cmd, args);
if (replyToEvent) {
addReplyToMessageContent(content, replyToEvent, this.props.permalinkCreator);
}
} else {
this._runSlashCommand(cmd, args);
this.runSlashCommand(cmd, args);
shouldSend = false;
}
} else {
// ask the user if their unknown command should be sent as a message
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const { finished } = Modal.createTrackedDialog("Unknown command", "", QuestionDialog, {
title: _t("Unknown Command"),
description: <div>
@ -378,7 +392,7 @@ export default class SendMessageComposer extends React.Component {
if (isQuickReaction(this.model)) {
shouldSend = false;
this._sendQuickReaction();
this.sendQuickReaction();
}
if (shouldSend) {
@ -411,9 +425,9 @@ export default class SendMessageComposer extends React.Component {
this.sendHistoryManager.save(this.model, replyToEvent);
// clear composer
this.model.reset([]);
this._editorRef.clearUndoHistory();
this._editorRef.focus();
this._clearStoredEditorState();
this.editorRef.current?.clearUndoHistory();
this.editorRef.current?.focus();
this.clearStoredEditorState();
if (SettingsStore.getValue("scrollToBottomOnMessageSent")) {
dis.dispatch({ action: "scroll_to_bottom" });
}
@ -421,33 +435,33 @@ export default class SendMessageComposer extends React.Component {
componentWillUnmount() {
dis.unregister(this.dispatcherRef);
window.removeEventListener("beforeunload", this._saveStoredEditorState);
this._saveStoredEditorState();
window.removeEventListener("beforeunload", this.saveStoredEditorState);
this.saveStoredEditorState();
}
// TODO: [REACT-WARNING] Move this to constructor
UNSAFE_componentWillMount() { // eslint-disable-line camelcase
const partCreator = new CommandPartCreator(this.props.room, this.context);
const parts = this._restoreStoredEditorState(partCreator) || [];
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_history_');
}
get _editorStateKey() {
private get editorStateKey() {
return `mx_cider_state_${this.props.room.roomId}`;
}
_clearStoredEditorState() {
localStorage.removeItem(this._editorStateKey);
private clearStoredEditorState(): void {
localStorage.removeItem(this.editorStateKey);
}
_restoreStoredEditorState(partCreator) {
const json = localStorage.getItem(this._editorStateKey);
private restoreStoredEditorState(partCreator: PartCreator): Part[] {
const json = localStorage.getItem(this.editorStateKey);
if (json) {
try {
const { parts: serializedParts, replyEventId } = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
const parts: Part[] = serializedParts.map(p => partCreator.deserializePart(p));
if (replyEventId) {
dis.dispatch({
action: 'reply_to_event',
@ -462,20 +476,20 @@ export default class SendMessageComposer extends React.Component {
}
// should save state when editor has contents or reply is open
_shouldSaveStoredEditorState = () => {
return !this.model.isEmpty || this.props.replyToEvent;
}
private shouldSaveStoredEditorState = (): boolean => {
return !this.model.isEmpty || !!this.props.replyToEvent;
};
_saveStoredEditorState = () => {
if (this._shouldSaveStoredEditorState()) {
private saveStoredEditorState = (): void => {
if (this.shouldSaveStoredEditorState()) {
const item = SendHistoryManager.createItem(this.model, this.props.replyToEvent);
localStorage.setItem(this._editorStateKey, JSON.stringify(item));
localStorage.setItem(this.editorStateKey, JSON.stringify(item));
} else {
this._clearStoredEditorState();
this.clearStoredEditorState();
}
}
};
onAction = (payload) => {
private onAction = (payload: ActionPayload): void => {
// don't let the user into the composer if it is disabled - all of these branches lead
// to the cursor being in the composer
if (this.props.disabled) return;
@ -483,21 +497,21 @@ export default class SendMessageComposer extends React.Component {
switch (payload.action) {
case 'reply_to_event':
case Action.FocusComposer:
this._editorRef && this._editorRef.focus();
this.editorRef.current?.focus();
break;
case "send_composer_insert":
if (payload.userId) {
this._editorRef && this._editorRef.insertMention(payload.userId);
this.editorRef.current?.insertMention(payload.userId);
} else if (payload.event) {
this._editorRef && this._editorRef.insertQuotedMessage(payload.event);
this.editorRef.current?.insertQuotedMessage(payload.event);
} else if (payload.text) {
this._editorRef && this._editorRef.insertPlaintext(payload.text);
this.editorRef.current?.insertPlaintext(payload.text);
}
break;
}
};
_onPaste = (event) => {
private onPaste = (event: ClipboardEvent<HTMLDivElement>): boolean => {
const { clipboardData } = event;
// Prioritize text on the clipboard over files as Office on macOS puts a bitmap
// in the clipboard as well as the content being copied.
@ -511,23 +525,27 @@ export default class SendMessageComposer extends React.Component {
);
return true; // to skip internal onPaste handler
}
}
};
onChange = () => {
private onChange = (): void => {
if (this.props.onChange) this.props.onChange(this.model);
}
};
private focusComposer = (): void => {
this.editorRef.current?.focus();
};
render() {
return (
<div className="mx_SendMessageComposer" onClick={this.focusComposer} onKeyDown={this._onKeyDown}>
<div className="mx_SendMessageComposer" onClick={this.focusComposer} onKeyDown={this.onKeyDown}>
<BasicMessageComposer
onChange={this.onChange}
ref={this._setEditorRef}
ref={this.editorRef}
model={this.model}
room={this.props.room}
label={this.props.placeholder}
placeholder={this.props.placeholder}
onPaste={this._onPaste}
onPaste={this.onPaste}
disabled={this.props.disabled}
/>
</div>