This repository was archived by the owner on Sep 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 808
Expand file tree
/
Copy pathEvent.tsx
More file actions
217 lines (185 loc) · 7.24 KB
/
Event.tsx
File metadata and controls
217 lines (185 loc) · 7.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
Copyright 2022 Michael Telatynski <[email protected]>
Copyright 2023 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, { ChangeEvent, ReactNode, useContext, useMemo, useRef, useState } from "react";
import { IContent, MatrixEvent } from "matrix-js-sdk/src/matrix";
import { _t, _td, TranslationKey } from "../../../../languageHandler";
import Field from "../../elements/Field";
import BaseTool, { DevtoolsContext, IDevtoolsProps } from "./BaseTool";
import MatrixClientContext from "../../../../contexts/MatrixClientContext";
import withValidation from "../../elements/Validation";
import SyntaxHighlight from "../../elements/SyntaxHighlight";
export const stringify = (object: object): string => {
return JSON.stringify(object, null, 2);
};
interface IEventEditorProps extends Pick<IDevtoolsProps, "onBack"> {
fieldDefs: IFieldDef[]; // immutable
defaultContent?: string;
onSend(fields: string[], content?: IContent): Promise<unknown>;
}
interface IFieldDef {
id: string;
label: TranslationKey;
default?: string;
}
export const eventTypeField = (defaultValue?: string): IFieldDef => ({
id: "eventType",
label: _td("Event Type"),
default: defaultValue,
});
export const stateKeyField = (defaultValue?: string): IFieldDef => ({
id: "stateKey",
label: _td("State Key"),
default: defaultValue,
});
const validateEventContent = withValidation<any, Error | undefined>({
async deriveData({ value }) {
try {
JSON.parse(value!);
} catch (e) {
return e as Error;
}
return undefined;
},
rules: [
{
key: "validJson",
test: ({ value }, error) => {
if (!value) return true;
return !error;
},
invalid: (error) => _t("Doesn't look like valid JSON.") + " " + error,
},
],
});
export const EventEditor: React.FC<IEventEditorProps> = ({ fieldDefs, defaultContent = "{\n\n}", onSend, onBack }) => {
const [fieldData, setFieldData] = useState<string[]>(fieldDefs.map((def) => def.default ?? ""));
const [content, setContent] = useState<string>(defaultContent);
const contentField = useRef<Field>(null);
const fields = fieldDefs.map((def, i) => (
<Field
key={def.id}
id={def.id}
label={_t(def.label)}
size={42}
autoFocus={defaultContent === undefined && i === 0}
type="text"
autoComplete="on"
value={fieldData[i]}
onChange={(ev: ChangeEvent<HTMLInputElement>) =>
setFieldData((data) => {
data[i] = ev.target.value;
return [...data];
})
}
/>
));
const onAction = async (): Promise<string | undefined> => {
const valid = contentField.current ? await contentField.current.validate({}) : false;
if (!valid) {
contentField.current?.focus();
contentField.current?.validate({ focused: true });
return;
}
try {
const json = JSON.parse(content);
await onSend(fieldData, json);
} catch (e) {
return _t("Failed to send event!") + (e instanceof Error ? ` (${e.message})` : "");
}
return _t("Event sent!");
};
return (
<BaseTool actionLabel={_t("Send")} onAction={onAction} onBack={onBack}>
<div className="mx_DevTools_eventTypeStateKeyGroup">{fields}</div>
<Field
id="evContent"
label={_t("Event Content")}
type="text"
className="mx_DevTools_textarea"
autoComplete="off"
value={content}
onChange={(ev) => setContent(ev.target.value)}
element="textarea"
onValidate={validateEventContent}
ref={contentField}
autoFocus={!!defaultContent}
/>
</BaseTool>
);
};
export interface IEditorProps extends Pick<IDevtoolsProps, "onBack"> {
mxEvent?: MatrixEvent;
}
interface IViewerProps extends Required<IEditorProps> {
Editor: React.FC<IEditorProps>;
extraButton?: ReactNode;
}
export const EventViewer: React.FC<IViewerProps> = ({ mxEvent, onBack, Editor, extraButton }) => {
const [editing, setEditing] = useState(false);
if (editing) {
const onBack = (): void => {
setEditing(false);
};
return <Editor mxEvent={mxEvent} onBack={onBack} />;
}
const onAction = async (): Promise<void> => {
setEditing(true);
};
return (
<BaseTool onBack={onBack} actionLabel={_t("Edit")} onAction={onAction} extraButton={extraButton}>
<SyntaxHighlight language="json">{stringify(mxEvent.event)}</SyntaxHighlight>
</BaseTool>
);
};
// returns the id of the initial message, not the id of the previous edit
const getBaseEventId = (baseEvent: MatrixEvent): string => {
// show the replacing event, not the original, if it is an edit
const mxEvent = baseEvent.replacingEvent() ?? baseEvent;
return mxEvent.getWireContent()["m.relates_to"]?.event_id ?? baseEvent.getId()!;
};
export const TimelineEventEditor: React.FC<IEditorProps> = ({ mxEvent, onBack }) => {
const context = useContext(DevtoolsContext);
const cli = useContext(MatrixClientContext);
const fields = useMemo(() => [eventTypeField(mxEvent?.getType())], [mxEvent]);
const onSend = ([eventType]: string[], content?: IContent): Promise<unknown> => {
return cli.sendEvent(context.room.roomId, eventType, content || {});
};
let defaultContent: string | undefined;
if (mxEvent) {
const originalContent = mxEvent.getContent();
// prefill an edit-message event, keep only the `body` and `msgtype` fields of originalContent
const bodyToStartFrom = originalContent["m.new_content"]?.body ?? originalContent.body; // prefill the last edit body, to start editing from there
const newContent = {
"body": ` * ${bodyToStartFrom}`,
"msgtype": originalContent.msgtype,
"m.new_content": {
body: bodyToStartFrom,
msgtype: originalContent.msgtype,
},
"m.relates_to": {
rel_type: "m.replace",
event_id: getBaseEventId(mxEvent),
},
};
defaultContent = stringify(newContent);
} else if (context.threadRootId) {
defaultContent = stringify({
"m.relates_to": {
rel_type: "m.thread",
event_id: context.threadRootId,
},
});
}
return <EventEditor fieldDefs={fields} defaultContent={defaultContent} onSend={onSend} onBack={onBack} />;
};