aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/whoReacted.tsx
blob: a14ca3a2a06ad3701e5fffd556226677adb281cf (plain)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
 * Vencord, a modification for Discord's desktop app
 * Copyright (c) 2022 Vendicated and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants";
import { LazyComponent, sleep, useForceUpdater } from "@utils/misc";
import { Queue } from "@utils/Queue";
import definePlugin from "@utils/types";
import { findByCode, findByPropsLazy } from "@webpack";
import { ChannelStore, FluxDispatcher, React, RestAPI, Tooltip } from "@webpack/common";
import { ReactionEmoji, User } from "discord-types/general";

const UserSummaryItem = LazyComponent(() => findByCode("defaultRenderUser", "showDefaultAvatarsForNullUsers"));
const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar");

const ReactionStore = findByPropsLazy("getReactions");

const queue = new Queue();

function fetchReactions(msg: Message, emoji: ReactionEmoji) {
    const key = emoji.name + (emoji.id ? `:${emoji.id}` : "");
    return RestAPI.get({
        url: `/channels/${msg.channel_id}/messages/${msg.id}/reactions/${key}`,
        query: {
            limit: 100
        },
        oldFormErrors: true
    })
        .then(res => FluxDispatcher.dispatch({
            type: "MESSAGE_REACTION_ADD_USERS",
            channelId: msg.channel_id,
            messageId: msg.id,
            users: res.body,
            emoji
        }))
        .catch(console.error)
        .finally(() => sleep(250));
}

function getReactionsWithQueue(msg: Message, e: ReactionEmoji) {
    const key = `${msg.id}:${e.name}:${e.id ?? ""}`;
    const cache = ReactionStore.__getLocalVars().reactions[key] ??= { fetched: false, users: {} };
    if (!cache.fetched) {
        queue.unshift(() =>
            fetchReactions(msg, e)
        );
        cache.fetched = true;
    }

    return cache.users;
}

function makeRenderMoreUsers(users: User[]) {
    return function renderMoreUsers(_label: string, _count: number) {
        return (
            <Tooltip text={users.slice(5).map(u => u.username).join(", ")} >
                {({ onMouseEnter, onMouseLeave }) => (
                    <div
                        className={AvatarStyles.moreUsers}
                        onMouseEnter={onMouseEnter}
                        onMouseLeave={onMouseLeave}
                    >
                        +{users.length - 5}
                    </div>
                )}
            </Tooltip >
        );
    };
}

export default definePlugin({
    name: "WhoReacted",
    description: "Renders the Avatars of reactors",
    authors: [Devs.Ven],

    patches: [{
        find: ",reactionRef:",
        replacement: {
            match: /((.)=(.{1,3})\.hideCount)(,.+?reactionCount.+?\}\))/,
            replace: "$1,whoReactedProps=$3$4,$2?null:$self.renderUsers(whoReactedProps)"
        }
    }],

    renderUsers(props: RootObject) {
        return props.message.reactions.length > 10 ? null : (
            <ErrorBoundary noop>
                <this._renderUsers {...props} />
            </ErrorBoundary>
        );
    },

    _renderUsers({ message, emoji }: RootObject) {
        const forceUpdate = useForceUpdater();
        React.useEffect(() => {
            const cb = (e: any) => {
                if (e.messageId === message.id)
                    forceUpdate();
            };
            FluxDispatcher.subscribe("MESSAGE_REACTION_ADD_USERS", cb);

            return () => FluxDispatcher.unsubscribe("MESSAGE_REACTION_ADD_USERS", cb);
        }, [message.id]);

        const reactions = getReactionsWithQueue(message, emoji);
        const users = Object.values(reactions).filter(Boolean) as User[];

        return (
            <div
                style={{ marginLeft: "0.5em", transform: "scale(0.9)" }}
            >
                <UserSummaryItem
                    users={users}
                    guildId={ChannelStore.getChannel(message.channel_id)?.guild_id}
                    renderIcon={false}
                    max={5}
                    showDefaultAvatarsForNullUsers
                    showUserPopout
                    renderMoreUsers={makeRenderMoreUsers(users)}
                />
            </div>
        );
    }
});


export interface GuildMemberAvatar { }

export interface Author {
    id: string;
    username: string;
    discriminator: string;
    avatar: string;
    avatarDecoration?: any;
    email: string;
    verified: boolean;
    bot: boolean;
    system: boolean;
    mfaEnabled: boolean;
    mobile: boolean;
    desktop: boolean;
    premiumType: number;
    flags: number;
    publicFlags: number;
    purchasedFlags: number;
    premiumUsageFlags: number;
    phone: string;
    nsfwAllowed: boolean;
    guildMemberAvatars: GuildMemberAvatar;
}

export interface Emoji {
    id: string;
    name: string;
}

export interface Reaction {
    emoji: Emoji;
    count: number;
    burst_user_ids: any[];
    burst_count: number;
    burst_colors: any[];
    burst_me: boolean;
    me: boolean;
}

export interface Message {
    id: string;
    type: number;
    channel_id: string;
    author: Author;
    content: string;
    deleted: boolean;
    editHistory: any[];
    attachments: any[];
    embeds: any[];
    mentions: any[];
    mentionRoles: any[];
    mentionChannels: any[];
    mentioned: boolean;
    pinned: boolean;
    mentionEveryone: boolean;
    tts: boolean;
    codedLinks: any[];
    giftCodes: any[];
    timestamp: string;
    editedTimestamp?: any;
    state: string;
    nonce?: any;
    blocked: boolean;
    call?: any;
    bot: boolean;
    webhookId?: any;
    reactions: Reaction[];
    applicationId?: any;
    application?: any;
    activity?: any;
    messageReference?: any;
    flags: number;
    isSearchHit: boolean;
    stickers: any[];
    stickerItems: any[];
    components: any[];
    loggingName?: any;
    interaction?: any;
    interactionData?: any;
    interactionError?: any;
}

export interface Emoji {
    id: string;
    name: string;
    animated: boolean;
}

export interface RootObject {
    message: Message;
    readOnly: boolean;
    isLurking: boolean;
    isPendingMember: boolean;
    useChatFontScaling: boolean;
    emoji: Emoji;
    count: number;
    burst_user_ids: any[];
    burst_count: number;
    burst_colors: any[];
    burst_me: boolean;
    me: boolean;
    type: number;
    hideEmoji: boolean;
    remainingBurstCurrency: number;
}