forked from TryGhost/Ghost
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinvite-user-modal.tsx
More file actions
263 lines (235 loc) · 9.39 KB
/
Copy pathinvite-user-modal.tsx
File metadata and controls
263 lines (235 loc) · 9.39 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
import NiceModal from '@ebay/nice-modal-react';
import validator from 'validator';
import {APIError, ValidationError} from '@tryghost/admin-x-framework/errors';
import {HostLimitError, useLimiter} from '../../../hooks/use-limiter';
import {Modal, Radio, TextField, showToast} from '@tryghost/admin-x-design-system';
import {useAddInvite, useBrowseInvites} from '@tryghost/admin-x-framework/api/invites';
import {useBrowseRoles} from '@tryghost/admin-x-framework/api/roles';
import {useBrowseUsers} from '@tryghost/admin-x-framework/api/users';
import {useEffect, useRef, useState} from 'react';
import {useGlobalData} from '../../providers/global-data-provider';
import {useHandleError} from '@tryghost/admin-x-framework/hooks';
import {useRouting} from '@tryghost/admin-x-framework/routing';
type RoleType = 'administrator' | 'editor' | 'author' | 'contributor' | 'super editor';
const USER_ALREADY_REGISTERED_VALIDATION = 'User is already registered.';
const USER_ALREADY_EXISTS_ERROR = 'A user with that email address already exists.';
const InviteUserModal = NiceModal.create(() => {
const modal = NiceModal.useModal();
const rolesQuery = useBrowseRoles();
const assignableRolesQuery = useBrowseRoles({
searchParams: {limit: '100', permissions: 'assign'}
});
const limiter = useLimiter();
const {updateRoute} = useRouting();
const {config} = useGlobalData();
const editorBeta = config.labs.superEditors;
const focusRef = useRef<HTMLInputElement>(null);
const [email, setEmail] = useState<string>('');
const [saveState, setSaveState] = useState<'saving' | 'saved' | 'error' | ''>('');
const [role, setRole] = useState<RoleType>('contributor');
const [errors, setErrors] = useState<{
email?: string;
role?: string;
}>({});
const {data: {users} = {}} = useBrowseUsers();
const {data: {invites} = {}} = useBrowseInvites();
const {mutateAsync: addInvite} = useAddInvite();
const handleError = useHandleError();
useEffect(() => {
if (focusRef.current) {
focusRef.current.focus();
}
}, []);
useEffect(() => {
if (saveState === 'saved') {
setTimeout(() => {
setSaveState('');
}, 2000);
}
}, [saveState]);
useEffect(() => {
if (role !== 'contributor' && limiter?.isLimited('staff')) {
limiter.errorIfWouldGoOverLimit('staff').then(() => {
setErrors(e => ({...e, role: undefined}));
}).catch((error) => {
if (error instanceof HostLimitError) {
setErrors(e => ({...e, role: error.message}));
return;
} else {
throw error;
}
});
} else {
setErrors(e => ({...e, role: undefined}));
}
}, [limiter, role]);
if (!rolesQuery.data?.roles || !assignableRolesQuery.data?.roles) {
return null;
}
const roles = rolesQuery.data.roles;
const assignableRoles = assignableRolesQuery.data.roles;
let okLabel = 'Send invitation';
if (saveState === 'saving') {
okLabel = 'Sending...';
} else if (saveState === 'saved') {
okLabel = 'Invite sent!';
} else if (saveState === 'error') {
okLabel = 'Retry';
}
const handleSendInvitation = async () => {
if (saveState === 'saving') {
return;
}
if (!validator.isEmail(email)) {
setErrors({
email: 'Please enter a valid email address.'
});
return;
}
if (users?.some(({email: userEmail}) => userEmail === email)) {
setErrors({
email: USER_ALREADY_EXISTS_ERROR
});
return;
}
if (invites?.some(({email: inviteEmail}) => inviteEmail === email)) {
setErrors({
email: 'A user with that email address was already invited.'
});
return;
}
if (errors.role) {
return;
}
setSaveState('saving');
try {
await addInvite({
email,
roleId: roles.find(({name}) => name.toLowerCase() === role.toLowerCase())!.id
});
setSaveState('saved');
showToast({
title: `Invitation sent`,
message: `${email}`,
type: 'success'
});
modal.remove();
updateRoute('staff?tab=invited');
} catch (e) {
const validationError = e instanceof ValidationError ? e.data?.errors[0] : undefined;
if (validationError && (validationError.context || validationError.message) === USER_ALREADY_REGISTERED_VALIDATION) {
setSaveState('');
setErrors({
email: USER_ALREADY_EXISTS_ERROR
});
return;
}
setSaveState('error');
let title = 'Failed to send invitation';
let message = (<span>If the problem persists, <a href="https://ghost.org/contact"><u>contact support</u>.</a>.</span>);
if (e instanceof APIError) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let data = e.data as any; // we have unknown data types in the APIError/error classes
if (data?.errors?.[0]?.type === 'EmailError') {
message = (<span>Check your Mailgun configuration.</span>);
}
}
showToast({
title,
message,
type: 'error'
});
handleError(e, {withToast: false});
return;
}
};
const roleOptions = [
{
hint: 'Can create and edit their own posts, but cannot publish. An Editor needs to approve and publish for them.',
label: 'Contributor',
value: 'contributor'
},
{
hint: 'A trusted user who can create, edit and publish their own posts, but can’t modify others.',
label: 'Author',
value: 'author'
},
{
hint: 'Can invite and manage other Authors and Contributors, as well as edit and publish any posts on the site.',
label: 'Editor',
value: 'editor'
},
{
hint: 'Trusted staff user who should be able to manage all content and users, as well as site settings and options.',
label: 'Administrator',
value: 'administrator'
}
];
// If the editor beta is enabled, replace the editor role option with super editor options.
// This gets a little weird, because we aren't changing what is actually assigned based on the toggle.
// So, a site could have the editor beta enabled, but that doesn't automatically convert their editors.
// (Editors can be up/downgraded by reassigning them in this modal. For 6.0, we should decide whether
// the old editors are going away or whether both roles are staying, and tidy this up then.)
if (editorBeta) {
roleOptions[2] = {
hint: 'Can invite and manage other Authors and Contributors, as well as edit and publish any posts on the site. Can manage members and moderate comments.',
label: 'Editor (beta mode)',
value: 'super editor'
};
};
const allowedRoleOptions = roleOptions.filter((option) => {
return assignableRoles.some((r) => {
return r.name === option.label || (r.name === 'Super Editor' && option.label === 'Editor (beta mode)');
});
});
if (!!errors.email) {
okLabel = 'Retry';
}
return (
<Modal
afterClose={() => {
updateRoute('staff');
}}
cancelLabel=''
okColor={saveState === 'error' || !!errors.email ? 'red' : 'black'}
okLabel={okLabel}
testId='invite-user-modal'
title='Invite a new staff user'
width={540}
onOk={handleSendInvitation}
>
<div className='flex flex-col gap-6 py-4'>
<p>
Send an invitation for a new person to create a staff account on your site, and select a role that matches what you’d like them to be able to do.
</p>
<TextField
error={!!errors.email}
hint={errors.email}
inputRef={focusRef}
placeholder='jamie@example.com'
title='Email address'
value={email}
onChange={(event) => {
setEmail(event.target.value);
}}
onKeyDown={() => setErrors(e => ({...e, email: undefined}))}
/>
<div>
<Radio
error={!!errors.role}
hint={errors.role}
id='role'
options={allowedRoleOptions}
selectedOption={role}
separator={true}
title="Role"
onSelect={(value) => {
setRole(value as RoleType);
}}
/>
</div>
</div>
</Modal>
);
});
export default InviteUserModal;