-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmy-widgets-collaborate-dialog.jsx
More file actions
383 lines (346 loc) · 11.1 KB
/
Copy pathmy-widgets-collaborate-dialog.jsx
File metadata and controls
383 lines (346 loc) · 11.1 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
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
import React, { useEffect, useState, useRef, useMemo } from 'react'
import { useQuery, useQueryClient } from 'react-query'
import { apiGetUsers } from '../util/api'
import setUserInstancePerms from './hooks/useSetUserInstancePerms'
import Modal from './modal'
import useDebounce from './hooks/useDebounce'
import LoadingIcon from './loading-icon'
import NoContentIcon from './no-content-icon'
import CollaborateUserRow from './my-widgets-collaborate-user-row'
import './my-widgets-collaborate-dialog.scss'
import { access } from './materia-constants'
import useUserList from './hooks/useUserList'
const initDialogState = (state) => {
return ({
searchText: '',
shareNotAllowed: false,
updatedAllUserPerms: new Map()
})
}
const MyWidgetsCollaborateDialog = ({onClose, inst, myPerms, otherUserPerms, setOtherUserPerms, currentUser, setInvalidLogin}) => {
const [state, setState] = useState(initDialogState())
const debouncedSearchTerm = useDebounce(state.searchText, 250)
const queryClient = useQueryClient()
const setUserPerms = setUserInstancePerms()
const [error, setError] = useState('')
const mounted = useRef(false)
const popperRef = useRef(null)
const userList = useUserList(debouncedSearchTerm)
const [collabUsers, setCollabUsers] = useState({})
const { data, remove: clearUsers, isFetching} = useQuery({
queryKey: ['collab-users', inst.id, (otherUserPerms != null ? Array.from(otherUserPerms.keys()) : otherUserPerms)], // check for changes in otherUserPerms
enabled: !!otherUserPerms && Array.from(otherUserPerms.keys()).length > 0,
queryFn: () => apiGetUsers(Array.from(otherUserPerms.keys())),
staleTime: Infinity,
placeholderData: {},
retry: false,
onSuccess: (data) => {
setCollabUsers({...collabUsers, ...data})
},
onError: (err) => {
if (err.message == "Invalid Login")
{
setInvalidLogin(true)
customClose()
} else {
setError("Failed to load users")
}
}
})
useEffect(() => {
if (userList.error) {
setError(`User search failed with error: ${data.msg}`);
if (userList.error.title == "Invalid Login")
{
setInvalidLogin(true)
}
}
}, [userList.error])
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
// updatedAllUserPerms is assigned the value of otherUserPerms (a read-only prop) when the component loads
useEffect(() => {
if (otherUserPerms != null)
{
const map = new Map([...state.updatedAllUserPerms, ...otherUserPerms])
map.forEach((key, pair) => {
key.remove = false
})
setState({...state, updatedAllUserPerms: map})
}
}, [otherUserPerms])
// Handles clicking a search result
const onClickMatch = match => {
const tempPerms = new Map(state.updatedAllUserPerms)
let shareNotAllowed = false
if(!inst.guest_access && match.is_student && !match.is_support_user){
shareNotAllowed = true
setState({...state, searchText: '', updatedAllUserPerms: tempPerms, shareNotAllowed: shareNotAllowed})
return
}
if(!state.updatedAllUserPerms.get(match.id) || state.updatedAllUserPerms.get(match.id).remove === true)
{
// Adds user to query data
let tmpMatch = {}
tmpMatch[match.id] = match
queryClient.setQueryData(['collab-users', inst.id], old => ({...old, ...tmpMatch}))
if (!collabUsers[match.id])
{
setCollabUsers({...collabUsers, [match.id]: match})
}
// Updateds the perms
tempPerms.set(
match.id,
{
accessLevel: access.VISIBLE,
expireTime: null,
editable: false,
contexts: null,
can: {
view: true,
copy: false,
edit: false,
delete: false,
share: false
},
remove: false
}
)
}
setState({...state,
searchText: '',
updatedAllUserPerms: tempPerms,
shareNotAllowed: shareNotAllowed
})
}
// does the perms set contain the current user?
// supportUsers always have implicit access. Otherwise, verify the user is in the perms set and isn't pending removal.
const containsUser = () => {
if (myPerms?.isSupportUser) return true
for (const [id, val] of Array.from(state.updatedAllUserPerms)) {
if (id == currentUser.id) return !val.remove
}
return false
}
const onSave = () => {
let delCurrUser = false
if (state.updatedAllUserPerms.get(currentUser.id)?.remove) {
delCurrUser = true
}
let permsObj = [];
if (delCurrUser && myPerms.accessLevel != access.FULL)
{
// Only send a request to update current user perms so that it doesn't get no-perm'd by the server
let currentUserPerms = state.updatedAllUserPerms.get(currentUser.id);
permsObj.push({
user: currentUser.id,
expiration: currentUserPerms.expireTime,
perm_level: currentUserPerms.remove ? null : currentUserPerms.accessLevel,
has_contexts: currentUserPerms.contexts != null
})
}
else
{
// else send a request to update all perms
permsObj = Array.from(state.updatedAllUserPerms).map(([userId, userPerms]) => {
return {
user: userId,
expiration: userPerms.expireTime,
perm_level: userPerms.remove ? null : userPerms.accessLevel,
has_contexts: userPerms.contexts != null
}
})
}
setUserPerms.mutate({
instId: inst.id,
permsObj: permsObj,
successFunc: (data) => {
if (mounted.current) {
if (delCurrUser) {
queryClient.invalidateQueries(['instances', currentUser])
}
queryClient.invalidateQueries('search-widgets')
queryClient.invalidateQueries(['user-perms', inst.id])
queryClient.invalidateQueries(['user-search', inst.id])
queryClient.removeQueries(['collab-users', inst.id])
setOtherUserPerms(state.updatedAllUserPerms)
customClose()
}
},
errorFunc: (err) => {
if (err.message == "Share Not Allowed")
{
setState({...state, shareNotAllowed: true})
} else if (err.message == "Invalid Login")
{
setInvalidLogin(true)
} else {
setError((err.message || "Error") + ": Failed to save permissions.")
}
}
})
let tmpPerms = new Map(state.updatedAllUserPerms)
tmpPerms.forEach((value, key) => {
if(value.remove === true) {
tmpPerms.delete(key)
}
})
setState({...state, updatedAllUserPerms: tmpPerms})
}
const customClose = () => {
clearUsers()
onClose()
}
const updatePerms = (userId, perms) => {
let newPerms = new Map(state.updatedAllUserPerms)
newPerms.set(parseInt(userId), perms)
setState({...state, updatedAllUserPerms: newPerms})
}
// Can't search unless you have full access.
let searchContainerRender = null
if (myPerms?.can?.share || myPerms?.isSupportUser) {
let searchResultsRender = null
if (debouncedSearchTerm !== '' && state.searchText !== '' && userList.users?.length && userList.users?.length !== 0) {
const searchResultElements = userList.users?.map(match =>
<div key={match.id}
className='collab-search-match clickable'
onClick={() => onClickMatch(match)}>
<img className='collab-match-avatar' src={match.avatar} alt="user avatar" />
<p className={`collab-match-name ${match.is_student ? 'collab-match-student' : ''}`}>
{match.first_name} {match.last_name}
</p>
</div>
)
searchResultsRender = (
<div className='collab-search-list'>
{ searchResultElements }
</div>
)
}
searchContainerRender = (
<div className='search-container'>
<span className='collab-input-label'>
Add people:
</span>
<input
tabIndex='0'
value={state.searchText}
onChange={(e) => setState({...state, searchText: e.target.value})}
className='user-add'
type='text'
placeholder="Enter a user's name or e-mail"/>
<span className="collab-input-disclaimer">Only individuals who have previously used Materia will show up in search.</span>
{ searchResultsRender }
</div>
)
}
const fullPermHolders = Array.from(state.updatedAllUserPerms.values())
.filter(u => u.accessLevel === access.FULL && !u.remove)
.length;
const onlyOneFullPermHolder = fullPermHolders === 1
const removedCurrentUser = state.updatedAllUserPerms.get(currentUser.id)?.remove === true
let mainContentRender = <LoadingIcon />
if (!isFetching) {
mainContentRender = <NoContentIcon />
if (containsUser) {
const mainContentElements = []
let userContentElement = null
Array.from(state.updatedAllUserPerms).forEach(([userId, userPerms]) => {
if (userPerms.remove === true) return
let user = collabUsers[userId]
if (!user) return
user.is_owner = user.id === inst.user_id
const rowElement = (
<CollaborateUserRow
key={user.id}
user={user}
perms={userPerms}
myPerms={myPerms}
isCurrentUser={currentUser.id === user.id}
onlyOneFullPermHolder={onlyOneFullPermHolder}
removedCurrentUser={removedCurrentUser}
onChange={(userId, perms) => updatePerms(userId, perms)}
readOnly={myPerms?.can?.share === false}
/>
)
if (currentUser.id === user.id) userContentElement = rowElement
else mainContentElements.push(rowElement)
})
mainContentRender = (
<>
<header className='access-list-header'>You</header>
{ userContentElement }
<header className='access-list-header'>Users With Access</header>
{ mainContentElements.length > 0 ? mainContentElements : <span className='not-shared'>No other users have access to your widget.</span> }
</>
)
}
}
const disableShareNotAllowed = () => setState({...state, shareNotAllowed: false})
let noShareWarningRender = null
if (state.shareNotAllowed === true) {
noShareWarningRender = (
<Modal onClose={disableShareNotAllowed} smaller={true} alert={true}>
<div>
<span className='alert-title'>Share Not Allowed</span>
<p className='alert-description'>Access must be set to "Guest Mode" to collaborate with students.</p>
<button className='action_button' onClick={disableShareNotAllowed}>Okay</button>
</div>
</Modal>
)
}
let errorRender = null
if (error) {
errorRender = (
<div className='error'>
<p>{error}</p>
</div>
)
}
return (
<Modal onClose={customClose}
ignoreClose={state.shareNotAllowed}>
<div className='collaborate-modal' ref={popperRef}>
<span className='title'>Collaborate</span>
{ errorRender }
<div id='access' className='collab-container'>
{ searchContainerRender }
<div className={`access-list ${containsUser ? '' : 'no-content'}`}>
{ mainContentRender }
</div>
{/* Calendar portal used to bring calendar popup out of access-list to avoid cutting off the overflow */}
<div id='calendar-portal' />
<p className='disclaimer'>
Users with full access can edit this widget and can
add or remove people in this list.
{onlyOneFullPermHolder && myPerms.accessLevel == access.FULL && (
<span>
<em>
{ '\u00A0'}Note: There must be at least one user with full access.
</em>
</span>
)}
</p>
<div className='btn-box'>
<a tabIndex='0'
className='cancel_button'
onClick={customClose}>
Cancel
</a>
<a tabIndex='0'
className='action_button green save_button'
onClick={onSave}>
Save
</a>
</div>
</div>
</div>
{ noShareWarningRender }
</Modal>
)
}
export default MyWidgetsCollaborateDialog