-
Notifications
You must be signed in to change notification settings - Fork 10k
/
MessageAction.ts
214 lines (184 loc) · 6.32 KB
/
MessageAction.ts
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
import type { ComponentProps, ContextType } from 'react';
import _ from 'underscore';
import mem from 'mem';
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker';
import type { Icon } from '@rocket.chat/fuselage';
import type { IMessage, IUser, ISubscription, IRoom, SettingValue, Serialized } from '@rocket.chat/core-typings';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import { Messages, Rooms, Subscriptions } from '../../../models/client';
import { roomCoordinator } from '../../../../client/lib/rooms/roomCoordinator';
import type { ToolboxContextValue } from '../../../../client/views/room/contexts/ToolboxContext';
import type { ChatContext } from '../../../../client/views/room/contexts/ChatContext';
import { APIClient } from '../../../utils/client';
const getMessage = async (msgId: string): Promise<Serialized<IMessage> | null> => {
try {
const { message } = await APIClient.get('/v1/chat.getMessage', { msgId });
return message;
} catch {
return null;
}
};
export const addMessageToList = (messagesList: IMessage[], message: IMessage): IMessage[] => {
// checks if the message is not already on the list
if (!messagesList.find(({ _id }) => _id === message._id)) {
messagesList.push(message);
}
return messagesList;
};
type MessageActionGroup = 'message' | 'menu';
export type MessageActionContext =
| 'message'
| 'threads'
| 'message-mobile'
| 'pinned'
| 'direct'
| 'starred'
| 'mentions'
| 'federated'
| 'videoconf';
type MessageActionConditionProps = {
message: IMessage;
user: IUser | undefined;
room: IRoom;
subscription?: ISubscription;
context?: MessageActionContext;
settings: { [key: string]: SettingValue };
chat: ContextType<typeof ChatContext>;
};
export type MessageActionConfig = {
id: string;
icon: ComponentProps<typeof Icon>['name'];
variant?: 'danger' | 'success' | 'warning';
label: TranslationKey;
order?: number;
/* @deprecated */
color?: string;
group?: MessageActionGroup | MessageActionGroup[];
context?: MessageActionContext[];
action: (
e: Pick<Event, 'preventDefault' | 'stopPropagation'>,
{
message,
tabbar,
room,
chat,
}: { message?: IMessage; tabbar: ToolboxContextValue; room?: IRoom; chat: ContextType<typeof ChatContext> },
) => any;
condition?: (props: MessageActionConditionProps) => Promise<boolean> | boolean;
};
type MessageActionConfigList = MessageActionConfig[];
export const MessageAction = new (class {
/*
config expects the following keys (only id is mandatory):
id (mandatory)
icon: string
label: string
action: function(event, instance)
condition: function(message)
order: integer
group: string (message or menu)
*/
buttons = new ReactiveVar<Record<string, MessageActionConfig>>({});
addButton(config: MessageActionConfig): void {
if (!config || !config.id) {
return;
}
if (!config.group) {
config.group = 'menu';
}
if (config.condition) {
config.condition = mem(config.condition, { maxAge: 1000, cacheKey: JSON.stringify });
}
return Tracker.nonreactive(() => {
const btns = this.buttons.get();
btns[config.id] = config;
mem.clear(this._getButtons);
mem.clear(this.getButtonsByGroup);
return this.buttons.set(btns);
});
}
removeButton(id: MessageActionConfig['id']): void {
return Tracker.nonreactive(() => {
const btns = this.buttons.get();
delete btns[id];
return this.buttons.set(btns);
});
}
updateButton(id: MessageActionConfig['id'], config: MessageActionConfig): void {
return Tracker.nonreactive(() => {
const btns = this.buttons.get();
if (btns[id]) {
btns[id] = _.extend(btns[id], config);
return this.buttons.set(btns);
}
});
}
getButtonById(id: MessageActionConfig['id']): MessageActionConfig | undefined {
const allButtons = this.buttons.get();
return allButtons[id];
}
_getButtons = mem((): MessageActionConfigList => _.sortBy(_.toArray(this.buttons.get()), 'order'), { maxAge: 1000 });
async getButtonsByCondition(
prop: MessageActionConditionProps,
arr: MessageActionConfigList = MessageAction._getButtons(),
): Promise<MessageActionConfigList> {
return (
await Promise.all(
arr.map(async (button) => {
return [button, !button.condition || (await button.condition(prop))] as const;
}),
)
)
.filter(([, condition]) => condition)
.map(([button]) => button);
}
getButtonsByGroup = mem(
function (group: MessageActionGroup, arr: MessageActionConfigList = MessageAction._getButtons()): MessageActionConfigList {
return arr.filter((button) => !button.group || (Array.isArray(button.group) ? button.group.includes(group) : button.group === group));
},
{ maxAge: 1000 },
);
getButtonsByContext(context: MessageActionContext, arr: MessageActionConfigList): MessageActionConfigList {
return !context ? arr : arr.filter((button) => !button.context || button.context.includes(context));
}
async getButtons(
props: MessageActionConditionProps,
context: MessageActionContext,
group: MessageActionGroup,
): Promise<MessageActionConfigList> {
const allButtons = group ? this.getButtonsByGroup(group) : MessageAction._getButtons();
const buttons = await this.getButtonsByCondition({ ...props, context }, this.getButtonsByContext(context, allButtons));
// Checks if the message is on thread context, so the "Reply in thread" button
// won't be rendered
const filteredButtons = context === 'threads' ? buttons.filter((button) => button.label !== 'Reply_in_thread') : buttons;
if (props.message) {
return this.getButtonsByCondition({ ...props, context }, this.getButtonsByContext(context, filteredButtons));
}
return allButtons;
}
resetButtons(): void {
mem.clear(this._getButtons);
mem.clear(this.getButtonsByGroup);
return this.buttons.set({});
}
async getPermaLink(msgId: string): Promise<string> {
if (!msgId) {
throw new Error('invalid-parameter');
}
const msg = Messages.findOne(msgId) || (await getMessage(msgId));
if (!msg) {
throw new Error('message-not-found');
}
const roomData = Rooms.findOne({
_id: msg.rid,
});
if (!roomData) {
throw new Error('room-not-found');
}
const subData = Subscriptions.findOne({ 'rid': roomData._id, 'u._id': Meteor.userId() });
const roomURL = roomCoordinator.getURL(roomData.t, subData || roomData);
return `${roomURL}?msg=${msgId}`;
}
})();