File size: 11,061 Bytes
e82b8d9 | 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 | import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useMe } from "../api.ts";
import { authClient } from "../auth-client.ts";
import { Btn, Chip, Input, Tile } from "../design/ui.tsx";
type Role = "owner" | "admin" | "member";
const ROLES: Role[] = ["owner", "admin", "member"];
type Member = {
id: string;
role: string;
createdAt: Date | string;
userId: string;
user: { id: string; email: string; name?: string | null; image?: string | null };
};
type Invitation = {
id: string;
email: string;
role: string | null;
status: string;
expiresAt: Date | string;
};
function memberQueryKey(orgId: string) {
return ["org-members", orgId] as const;
}
function inviteQueryKey(orgId: string) {
return ["org-invitations", orgId] as const;
}
export function OrgMembersCard() {
const me = useMe();
const orgId = me.data?.org?.id;
const myUserId = me.data?.user.id;
const membersQ = useQuery({
queryKey: orgId ? memberQueryKey(orgId) : ["org-members", "none"],
enabled: !!orgId,
queryFn: async () => {
const res = await authClient.organization.listMembers({ query: { organizationId: orgId } });
if (res.error) throw new Error(res.error.message ?? "Failed to load members");
return (res.data?.members ?? []) as Member[];
},
});
const invitesQ = useQuery({
queryKey: orgId ? inviteQueryKey(orgId) : ["org-invitations", "none"],
enabled: !!orgId,
queryFn: async () => {
const res = await authClient.organization.listInvitations({
query: { organizationId: orgId },
});
if (res.error) throw new Error(res.error.message ?? "Failed to load invitations");
return (res.data ?? []) as Invitation[];
},
});
if (!orgId) return null;
const myRole = membersQ.data?.find((m) => m.userId === myUserId)?.role ?? "member";
const canManage = myRole === "owner" || myRole === "admin";
return (
<div className="flex flex-col gap-4">
<InviteForm orgId={orgId} canManage={canManage} />
<Tile padded={false}>
<div className="border-b border-border px-5 py-3">
<span className="text-[12px] text-muted">Members</span>
</div>
{membersQ.isLoading ? (
<div className="px-5 py-6 text-[12px] text-muted">Loading…</div>
) : membersQ.error ? (
<div className="px-5 py-6 text-[12px] text-danger">{String(membersQ.error)}</div>
) : (
<ul className="divide-y divide-border">
{(membersQ.data ?? []).map((m) => (
<MemberRow
key={m.id}
member={m}
orgId={orgId}
isSelf={m.userId === myUserId}
canManage={canManage}
/>
))}
</ul>
)}
</Tile>
{(invitesQ.data?.filter((i) => i.status === "pending").length ?? 0) > 0 && (
<Tile padded={false}>
<div className="border-b border-border px-5 py-3">
<span className="text-[12px] text-muted">Pending invitations</span>
</div>
<ul className="divide-y divide-border">
{(invitesQ.data ?? [])
.filter((i) => i.status === "pending")
.map((inv) => (
<InvitationRow key={inv.id} invitation={inv} orgId={orgId} canManage={canManage} />
))}
</ul>
</Tile>
)}
</div>
);
}
function InviteForm({ orgId, canManage }: { orgId: string; canManage: boolean }) {
const [email, setEmail] = useState("");
const [role, setRole] = useState<Role>("member");
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const qc = useQueryClient();
const invite = useMutation({
mutationFn: async (input: { email: string; role: Role }) => {
const res = await authClient.organization.inviteMember({
email: input.email,
role: input.role,
organizationId: orgId,
});
if (res.error) throw new Error(res.error.message ?? "Failed to invite");
return res.data;
},
onSuccess: (_data, vars) => {
setEmail("");
setSuccess(`Invitation sent to ${vars.email}`);
setTimeout(() => setSuccess(null), 3000);
void qc.invalidateQueries({ queryKey: inviteQueryKey(orgId) });
},
});
if (!canManage) {
return (
<Tile>
<p className="text-[12px] text-muted">
Only owners and admins can invite new members. Ask one of them for access.
</p>
</Tile>
);
}
const submit = (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
const trimmed = email.trim();
if (!trimmed) return;
invite.mutate(
{ email: trimmed, role },
{ onError: (e) => setError(e instanceof Error ? e.message : String(e)) },
);
};
return (
<Tile>
<form onSubmit={submit} className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex-1">
<label className="mb-1.5 block text-[12px] text-muted">Invite by email</label>
<Input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="teammate@example.com"
required
/>
</div>
<div className="w-full sm:w-40">
<label className="mb-1.5 block text-[12px] text-muted">Role</label>
<RoleSelect value={role} onChange={(v) => setRole(v)} />
</div>
<Btn type="submit" loading={invite.isPending} disabled={!email.trim()}>
Send invite
</Btn>
</form>
{error && <p className="mt-2 text-[12px] text-danger">{error}</p>}
{success && <p className="mt-2 text-[12px] text-success">{success}</p>}
</Tile>
);
}
function MemberRow({
member,
orgId,
isSelf,
canManage,
}: {
member: Member;
orgId: string;
isSelf: boolean;
canManage: boolean;
}) {
const qc = useQueryClient();
const [error, setError] = useState<string | null>(null);
const updateRole = useMutation({
mutationFn: async (newRole: Role) => {
const res = await authClient.organization.updateMemberRole({
memberId: member.id,
role: newRole,
organizationId: orgId,
});
if (res.error) throw new Error(res.error.message ?? "Failed to update role");
return res.data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: memberQueryKey(orgId) }),
onError: (e) => setError(e instanceof Error ? e.message : String(e)),
});
const remove = useMutation({
mutationFn: async () => {
const res = await authClient.organization.removeMember({
memberIdOrEmail: member.id,
organizationId: orgId,
});
if (res.error) throw new Error(res.error.message ?? "Failed to remove member");
return res.data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: memberQueryKey(orgId) }),
onError: (e) => setError(e instanceof Error ? e.message : String(e)),
});
const role = member.role as Role;
const canEditRole = canManage && !isSelf;
return (
<li className="flex items-center justify-between gap-3 px-5 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] text-fg">
{member.user.name?.trim() || member.user.email}
</span>
{isSelf && <Chip tone="muted">you</Chip>}
</div>
{member.user.name?.trim() && (
<div className="truncate text-[11px] text-subtle">{member.user.email}</div>
)}
{error && <div className="mt-1 text-[11px] text-danger">{error}</div>}
</div>
<div className="flex items-center gap-2">
{canEditRole ? (
<RoleSelect
value={role}
disabled={updateRole.isPending}
onChange={(v) => {
if (v === role) return;
setError(null);
updateRole.mutate(v);
}}
/>
) : (
<Chip tone={role === "owner" ? "accent" : "neutral"}>{role}</Chip>
)}
{canManage && !isSelf && (
<Btn
variant="danger"
size="sm"
loading={remove.isPending}
onClick={() => {
if (!window.confirm(`Remove ${member.user.email} from this org?`)) return;
setError(null);
remove.mutate();
}}
>
Remove
</Btn>
)}
</div>
</li>
);
}
function InvitationRow({
invitation,
orgId,
canManage,
}: {
invitation: Invitation;
orgId: string;
canManage: boolean;
}) {
const qc = useQueryClient();
const [cancelError, setCancelError] = useState<string | null>(null);
const cancel = useMutation({
mutationFn: async () => {
const res = await authClient.organization.cancelInvitation({
invitationId: invitation.id,
});
if (res.error) throw new Error(res.error.message ?? "Failed to cancel");
return res.data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: inviteQueryKey(orgId) }),
onError: (e) => setCancelError(e instanceof Error ? e.message : String(e)),
});
return (
<li className="flex items-center justify-between gap-3 px-5 py-3">
<div className="min-w-0 flex-1">
<div className="truncate text-[13px] text-fg">{invitation.email}</div>
<div className="text-[11px] text-subtle">
Invited as {invitation.role ?? "member"} · expires{" "}
{new Date(invitation.expiresAt).toLocaleDateString()}
</div>
{cancelError && <div className="mt-1 text-[11px] text-danger">{cancelError}</div>}
</div>
{canManage && (
<Btn
variant="ghost"
size="sm"
loading={cancel.isPending}
onClick={() => {
setCancelError(null);
cancel.mutate();
}}
>
Cancel
</Btn>
)}
</li>
);
}
function RoleSelect({
value,
onChange,
disabled,
}: {
value: Role;
onChange: (next: Role) => void;
disabled?: boolean;
}) {
return (
<div className="relative">
<select
value={value}
disabled={disabled}
onChange={(e) => onChange(e.target.value as Role)}
className="h-8 appearance-none rounded-sm border border-border bg-surface-2 pl-3 pr-7 text-[12.5px] text-fg focus:border-border-strong focus:outline-none disabled:opacity-50"
>
{ROLES.map((r) => (
<option key={r} value={r}>
{r}
</option>
))}
</select>
<svg
aria-hidden
className="pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-subtle"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="m6 9 6 6 6-6" />
</svg>
</div>
);
}
|