aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/GroupManager.tsx
blob: 0765d89e4db9c2b7795f236fb66b925786307670 (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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { action, computed, observable, runInAction } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import Select from 'react-select';
import * as RequestPromise from "request-promise";
import { Doc, DocListCast, DocListCastAsync, Opt } from "../../fields/Doc";
import { Cast, StrCast } from "../../fields/Types";
import { setGroups } from "../../fields/util";
import { Utils } from "../../Utils";
import { DocServer } from "../DocServer";
import { MainViewModal } from "../views/MainViewModal";
import { TaskCompletionBox } from "../views/nodes/TaskCompletedBox";
import "./GroupManager.scss";
import { GroupMemberView } from "./GroupMemberView";
import { SharingManager, User } from "./SharingManager";

/**
 * Interface for options for the react-select component
 */
export interface UserOptions {
    label: string;
    value: string;
}

@observer
export class GroupManager extends React.Component<{}> {

    static Instance: GroupManager;
    @observable isOpen: boolean = false; // whether the GroupManager is to be displayed or not.
    @observable private users: string[] = []; // list of users populated from the database.
    @observable private selectedUsers: UserOptions[] | null = null; // list of users selected in the "Select users" dropdown.
    @observable currentGroup: Opt<Doc>; // the currently selected group.
    @observable private createGroupModalOpen: boolean = false;
    private inputRef: React.RefObject<HTMLInputElement> = React.createRef(); // the ref for the input box.
    private createGroupButtonRef: React.RefObject<HTMLButtonElement> = React.createRef(); // the ref for the group creation button
    private currentUserGroups: string[] = []; // the list of groups the current user is a member of
    @observable private buttonColour: "#979797" | "black" = "#979797";
    @observable private groupSort: "ascending" | "descending" | "none" = "none";
    private populating: boolean = false;



    constructor(props: Readonly<{}>) {
        super(props);
        GroupManager.Instance = this;
    }

    /**
     * Populates the list of users and groups.
     */
    componentDidMount() {
        this.populateUsers();
        this.populateGroups();
    }

    /**
     * Fetches the list of users stored on the database.
     */
    populateUsers = async () => {
        if (!this.populating) {
            this.populating = true;
            runInAction(() => this.users = []);
            const userList = await RequestPromise.get(Utils.prepend("/getUsers"));
            const raw = JSON.parse(userList) as User[];
            const evaluating = raw.map(async user => {
                const userDocument = await DocServer.GetRefField(user.userDocumentId);
                if (userDocument instanceof Doc) {
                    const notificationDoc = await Cast(userDocument.mySharedDocs, Doc);
                    runInAction(() => {
                        if (notificationDoc instanceof Doc) {
                            this.users.push(user.email);
                        }
                    });
                }
            });
            return Promise.all(evaluating).then(() => this.populating = false);
        }
    }

    /**
     * Populates the list of groups the current user is a member of and sets this list to be used in the GetEffectiveAcl in util.ts
     */
    populateGroups = () => {
        DocListCastAsync(this.GroupManagerDoc?.data).then(groups => {
            groups?.forEach(group => {
                const members: string[] = JSON.parse(StrCast(group.members));
                if (members.includes(Doc.CurrentUserEmail)) this.currentUserGroups.push(StrCast(group.groupName));
            });
            this.currentUserGroups.push("Public");
            setGroups(this.currentUserGroups);
        });
    }

    /**
     * @returns the options to be rendered in the dropdown menu to add users and create a group.
     */
    @computed get options() {
        return this.users.map(user => ({ label: user, value: user }));
    }

    /**
     * Makes the GroupManager visible.
     */
    @action
    open = () => {
        // SelectionManager.DeselectAll();
        this.isOpen = true;
        this.populateUsers();
        this.populateGroups();
    }

    /**
     * Hides the GroupManager.
    */
    @action
    close = () => {
        this.isOpen = false;
        this.currentGroup = undefined;
        this.selectedUsers = null;
        // this.users = [];
        this.createGroupModalOpen = false;
        TaskCompletionBox.taskCompleted = false;
    }

    /**
     * @returns the database of groups.
     */
    get GroupManagerDoc(): Doc | undefined {
        return Doc.UserDoc().globalGroupDatabase as Doc;
    }

    /**
     * @returns a list of all group documents.
     */
    getAllGroups(): Doc[] {
        const groupDoc = this.GroupManagerDoc;
        return groupDoc ? DocListCast(groupDoc.data) : [];
    }

    /**
     * @returns a group document based on the group name.
     * @param groupName 
     */
    getGroup(groupName: string): Doc | undefined {
        const groupDoc = this.getAllGroups().find(group => group.groupName === groupName);
        return groupDoc;
    }

    /**
     * Returns an array of the list of members of a given group.
     */
    getGroupMembers(group: string | Doc): string[] {
        if (group instanceof Doc) return JSON.parse(StrCast(group.members)) as string[];
        else return JSON.parse(StrCast(this.getGroup(group)!.members)) as string[];
    }

    /**
     * @returns the members of the admin group.
     */
    get adminGroupMembers(): string[] {
        return this.getGroup("Admin") ? JSON.parse(StrCast(this.getGroup("Admin")!.members)) : "";
    }

    /**
     * @returns a boolean indicating whether the current user has access to edit group documents.
     * @param groupDoc 
     */
    hasEditAccess(groupDoc: Doc): boolean {
        if (!groupDoc) return false;
        const accessList: string[] = JSON.parse(StrCast(groupDoc.owners));
        return accessList.includes(Doc.CurrentUserEmail) || this.adminGroupMembers?.includes(Doc.CurrentUserEmail);
    }

    /**
     * Helper method that sets up the group document.
     * @param groupName 
     * @param memberEmails 
     */
    createGroupDoc(groupName: string, memberEmails: string[] = []) {
        const groupDoc = new Doc;
        groupDoc.groupName = groupName.toLowerCase() === "admin" ? "Admin" : groupName;
        groupDoc.owners = JSON.stringify([Doc.CurrentUserEmail]);
        groupDoc.members = JSON.stringify(memberEmails);
        if (memberEmails.includes(Doc.CurrentUserEmail)) {
            this.currentUserGroups.push(groupName);
            setGroups(this.currentUserGroups);
        }
        this.addGroup(groupDoc);
    }

    /**
     * Helper method that adds a group document to the database of group documents and @returns whether it was successfully added or not.
     * @param groupDoc 
     */
    addGroup(groupDoc: Doc): boolean {
        if (this.GroupManagerDoc) {
            Doc.AddDocToList(this.GroupManagerDoc, "data", groupDoc);
            return true;
        }
        return false;
    }

    /**
     * Deletes a group from the database of group documents and @returns whether the group was deleted or not.
     * @param group 
     */
    deleteGroup(group: Doc): boolean {
        if (group) {
            if (this.GroupManagerDoc && this.hasEditAccess(group)) {
                Doc.RemoveDocFromList(this.GroupManagerDoc, "data", group);
                SharingManager.Instance.removeGroup(group);
                const members: string[] = JSON.parse(StrCast(group.members));
                if (members.includes(Doc.CurrentUserEmail)) {
                    const index = this.currentUserGroups.findIndex(groupName => groupName === group.groupName);
                    index !== -1 && this.currentUserGroups.splice(index, 1);
                    setGroups(this.currentUserGroups);
                }
                if (group === this.currentGroup) {
                    runInAction(() => this.currentGroup = undefined);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Adds a member to a group.
     * @param groupDoc 
     * @param email 
     */
    addMemberToGroup(groupDoc: Doc, email: string) {
        if (this.hasEditAccess(groupDoc)) {
            const memberList: string[] = JSON.parse(StrCast(groupDoc.members));
            !memberList.includes(email) && memberList.push(email);
            groupDoc.members = JSON.stringify(memberList);
            SharingManager.Instance.shareWithAddedMember(groupDoc, email);
        }
    }

    /**
     * Removes a member from the group.
     * @param groupDoc 
     * @param email 
     */
    removeMemberFromGroup(groupDoc: Doc, email: string) {
        if (this.hasEditAccess(groupDoc)) {
            const memberList: string[] = JSON.parse(StrCast(groupDoc.members));
            const index = memberList.indexOf(email);
            if (index !== -1) {
                const user = memberList.splice(index, 1)[0];
                groupDoc.members = JSON.stringify(memberList);
                SharingManager.Instance.removeMember(groupDoc, email);
            }
        }
    }

    /**
     * Handles changes in the users selected in the "Select users" dropdown.
     * @param selectedOptions 
     */
    @action
    handleChange = (selectedOptions: any) => {
        this.selectedUsers = selectedOptions as UserOptions[];
    }

    /**
     * Creates the group when the enter key has been pressed (when in the input).
     * @param e 
     */
    handleKeyDown = (e: React.KeyboardEvent) => {
        e.key === "Enter" && this.createGroup();
    }

    /**
     * Handles the input of required fields in the setup of a group and resets the relevant variables.
     */
    @action
    createGroup = () => {
        if (!this.inputRef.current?.value) {
            alert("Please enter a group name");
            return;
        }
        if (this.getAllGroups().find(group => group.groupName === this.inputRef.current!.value)) { // why do I need a null check here?
            alert("Please select a unique group name");
            return;
        }
        this.createGroupDoc(this.inputRef.current.value, this.selectedUsers?.map(user => user.value));
        this.selectedUsers = null;
        this.inputRef.current.value = "";
        this.buttonColour = "#979797";

        const { left, width, top } = this.createGroupButtonRef.current!.getBoundingClientRect();
        TaskCompletionBox.popupX = left - 2 * width;
        TaskCompletionBox.popupY = top;
        TaskCompletionBox.textDisplayed = "Group created!";
        TaskCompletionBox.taskCompleted = true;
        setTimeout(action(() => TaskCompletionBox.taskCompleted = false), 2000);

    }

    /**
     * @returns the MainViewModal which allows the user to create groups.
     */
    private get groupCreationModal() {
        const contents = (
            <div className="group-create">
                <div className="group-heading" style={{ marginBottom: 0 }}>
                    <p><b>New Group</b></p>
                    <div className={"close-button"} onClick={action(() => {
                        this.createGroupModalOpen = false; TaskCompletionBox.taskCompleted = false;
                    })}>
                        <FontAwesomeIcon icon={"times"} color={"black"} size={"lg"} />
                    </div>
                </div>
                <input
                    className="group-input"
                    ref={this.inputRef}
                    onKeyDown={this.handleKeyDown}
                    autoFocus
                    type="text"
                    placeholder="Group name"
                    onChange={action(() => this.buttonColour = this.inputRef.current?.value ? "black" : "#979797")} />
                <Select
                    isMulti={true}
                    isSearchable={true}
                    options={this.options}
                    onChange={this.handleChange}
                    placeholder={"Select users"}
                    value={this.selectedUsers}
                    closeMenuOnSelect={false}
                    styles={{
                        dropdownIndicator: (base, state) => ({
                            ...base,
                            transition: '0.5s all ease',
                            transform: state.selectProps.menuIsOpen ? 'rotate(180deg)' : undefined
                        }),
                        multiValue: (base) => ({
                            ...base,
                            maxWidth: "50%",

                            '&:hover': {
                                maxWidth: "unset"
                            }
                        })
                    }}
                />
                <button
                    ref={this.createGroupButtonRef}
                    onClick={this.createGroup}
                    style={{ background: this.buttonColour }}
                    disabled={this.buttonColour === "#979797"}
                >
                    Create
                </button>
            </div>
        );

        return (
            <MainViewModal
                isDisplayed={this.createGroupModalOpen}
                interactive={true}
                contents={contents}
                dialogueBoxStyle={{ width: "90%", height: "70%" }}
                closeOnExternalClick={action(() => { this.createGroupModalOpen = false; this.selectedUsers = null; TaskCompletionBox.taskCompleted = false; })}
            />
        );
    }

    /**
     * A getter that @returns the main interface for the GroupManager.
     */
    private get groupInterface() {

        const sortGroups = (d1: Doc, d2: Doc) => {
            const g1 = StrCast(d1.groupName);
            const g2 = StrCast(d2.groupName);

            return g1 < g2 ? -1 : g1 === g2 ? 0 : 1;
        };

        let groups = this.getAllGroups();
        groups = this.groupSort === "ascending" ? groups.sort(sortGroups) : this.groupSort === "descending" ? groups.sort(sortGroups).reverse() : groups;

        return (
            <div className="group-interface">
                {this.groupCreationModal}
                {this.currentGroup ?
                    <GroupMemberView
                        group={this.currentGroup}
                        onCloseButtonClick={action(() => this.currentGroup = undefined)}
                    />
                    : null}
                <div className="group-heading">
                    <p><b>Manage Groups</b></p>
                    <button onClick={action(() => this.createGroupModalOpen = true)}>
                        <FontAwesomeIcon icon={"plus-hexagon"} size={"sm"} /> Create Group
                    </button>
                    <div className={"close-button"} onClick={this.close}>
                        <FontAwesomeIcon icon={"times"} color={"black"} size={"lg"} />
                    </div>
                </div>
                <div className="main-container">
                    <div
                        className="sort-groups"
                        onClick={action(() => this.groupSort = this.groupSort === "ascending" ? "descending" : this.groupSort === "descending" ? "none" : "ascending")}>
                        Name {this.groupSort === "ascending" ? <FontAwesomeIcon icon={"caret-up"} size={"xs"} />
                            : this.groupSort === "descending" ? <FontAwesomeIcon icon={"caret-down"} size={"xs"} />
                                : <FontAwesomeIcon icon={"caret-right"} size={"xs"} />
                        }
                    </div>
                    <div className="group-body">
                        {groups.map(group =>
                            <div
                                className="group-row"
                                key={StrCast(group.groupName)}
                            >
                                <div className="group-name" >{group.groupName}</div>
                                <div className="group-info" onClick={action(() => this.currentGroup = group)}>
                                    <FontAwesomeIcon icon={"info-circle"} color={"#e8e8e8"} size={"sm"} style={{ backgroundColor: "#1e89d7", borderRadius: "100%", border: "1px solid #1e89d7" }} />
                                </div>
                            </div>
                        )}
                    </div>
                </div>

            </div>
        );
    }

    render() {
        return (
            <MainViewModal
                contents={this.groupInterface}
                isDisplayed={this.isOpen}
                interactive={true}
                dialogueBoxStyle={{ zIndex: 1002 }}
                overlayStyle={{ zIndex: 1001 }}
                closeOnExternalClick={this.close}
            />
        );
    }

}