@krak-stack/auth 0.1.52 → 0.1.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
3
- import { useStore } from "@tanstack/react-form";
3
+ import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
4
  import {} from "@tanstack/react-table";
5
- import { Effect, Schema } from "effect";
5
+ import { Effect, Option, Schema } from "effect";
6
6
  import { AsyncResult, Atom } from "effect/unstable/reactivity";
7
7
  import { Building2, Check, ChevronsUpDown, Copy, KeyRound, LogOut, Mail, PencilIcon, Plus, Trash2, UserIcon, UserPlus, Users, X, } from "lucide-react";
8
8
  import { createContext, useContext, useEffect, useEffectEvent, useRef, useState, } from "react";
9
9
  import { DataTable, DataTableRelationshipCell, } from "@/components/ui/data-table";
10
+ import { ImageField, SelectField, SubmitButton, SubmitError, TextField, } from "@/components/ui/effect-form";
10
11
  import { EditingLocaleSwitcher } from "@/components/ui/editing-locale-switcher";
11
12
  import { AppBrand } from "@/components/ui/app-brand";
12
13
  import { FieldSet } from "@/components/ui/field";
13
- import { useAppForm } from "@/components/ui/form";
14
14
  import { Badge } from "@/components/ui/badge";
15
15
  import { Button } from "@/components/ui/button";
16
16
  import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
@@ -63,6 +63,9 @@ const messages = {
63
63
  organization_invite_member_title: "Invite a member",
64
64
  organization_loading: "Loading...",
65
65
  organization_location: "Location",
66
+ organization_parent: "Parent organization",
67
+ organization_parent_description: "Optionally group this organization under another organization.",
68
+ organization_parent_none: "No parent organization",
66
69
  organization_icon: "Icon",
67
70
  organization_logo: "Logo",
68
71
  organization_logo_upload_error: "Could not upload the organization logo.",
@@ -151,6 +154,9 @@ const messages = {
151
154
  organization_invite_member_title: "Inviter un membre",
152
155
  organization_loading: "Chargement...",
153
156
  organization_location: "Emplacement",
157
+ organization_parent: "Organisation parente",
158
+ organization_parent_description: "Regroupez facultativement cette organisation sous une autre organisation.",
159
+ organization_parent_none: "Aucune organisation parente",
154
160
  organization_icon: "Icône",
155
161
  organization_logo: "Logo",
156
162
  organization_logo_upload_error: "Impossible de téléverser le logo de l'organisation.",
@@ -284,11 +290,35 @@ const organizationApiKeysAtom = Atom.family((authClient) => Atom.family((organiz
284
290
  catch: (error) => error,
285
291
  })))));
286
292
  const emptyOrganizationApiKeysAtom = Atom.make(Effect.succeed([]));
293
+ const organizationImageSchema = Schema.Union([
294
+ Schema.String,
295
+ Schema.instanceOf(File),
296
+ Schema.Null,
297
+ Schema.Undefined,
298
+ ]);
299
+ const organizationFormBuilder = FormBuilder.empty
300
+ .addField("parentId", Schema.String)
301
+ .addField("slug", Schema.String)
302
+ .addField("enName", Schema.String)
303
+ .addField("enLogo", organizationImageSchema)
304
+ .addField("enIcon", organizationImageSchema)
305
+ .addField("enContactEmail", Schema.String)
306
+ .addField("enLocation", Schema.String)
307
+ .addField("frName", Schema.String)
308
+ .addField("frLogo", organizationImageSchema)
309
+ .addField("frIcon", organizationImageSchema)
310
+ .addField("frContactEmail", Schema.String)
311
+ .addField("frLocation", Schema.String);
312
+ const inviteMemberFormBuilder = FormBuilder.empty
313
+ .addField("email", Schema.NonEmptyString)
314
+ .addField("role", Schema.String);
315
+ const apiKeyFormBuilder = FormBuilder.empty.addField("name", Schema.NonEmptyString);
287
316
  const slugify = (value) => value
288
317
  .trim()
289
318
  .toLowerCase()
290
319
  .replace(/[^a-z0-9]+/g, "-")
291
320
  .replace(/^-+|-+$/g, "");
321
+ const noParentOrganization = "__none__";
292
322
  const isOrganizationSlugConflict = (error) => {
293
323
  if (typeof error !== "object" || error === null)
294
324
  return false;
@@ -345,11 +375,26 @@ const organizationDisplay = (organization, m, baseUrl) => {
345
375
  const organizationSwitcherSubtitle = (organization, subtitle, m) => organization?.userId
346
376
  ? `${m.organization_switcher_personal()} · ${subtitle}`
347
377
  : subtitle;
378
+ const organizationParentOptions = (organizations, m, excludedOrganizationId) => [
379
+ {
380
+ label: m.organization_parent_none(),
381
+ value: noParentOrganization,
382
+ },
383
+ ...organizations
384
+ .filter((organization) => organization.id !== excludedOrganizationId &&
385
+ !organization.userId &&
386
+ !organization.parentId)
387
+ .map((organization) => ({
388
+ label: organizationDisplay(organization, m).name,
389
+ value: organization.id,
390
+ })),
391
+ ];
348
392
  const organizationFormDefaults = (organization, baseUrl) => {
349
393
  const translations = parseOrganizationMetadata(organization?.metadata).translations;
350
394
  const en = translations.find((translation) => translation.locale === "en");
351
395
  const fr = translations.find((translation) => translation.locale === "fr");
352
396
  return {
397
+ parentId: organization?.parentId ?? noParentOrganization,
353
398
  slug: organization?.slug ?? "",
354
399
  enName: en?.name || organization?.name || "",
355
400
  enLogo: assetUrl(en?.logo, baseUrl) || null,
@@ -434,7 +479,7 @@ const organizationMetadataFromForm = async (value, m, uploadImage) => {
434
479
  }
435
480
  return { translations };
436
481
  };
437
- export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl, side = "bottom", className, defaultDialog = null, hideTrigger = false, menuActions, renderUnauthenticated, locked = false, messages, dialog: controlledDialog, onChange, onCreate, onDialogChange, }) {
482
+ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl, side = "bottom", className, defaultDialog = null, features, hideTrigger = false, menuActions, renderUnauthenticated, allowedOrganizationIds, messages, dialog: controlledDialog, onChange, onCreate, onDialogChange, }) {
438
483
  const auth = useKrakstackAuth();
439
484
  const authClient = providedAuthClient ?? auth?.authClient;
440
485
  if (!authClient) {
@@ -467,6 +512,9 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
467
512
  const activeMemberRole = normalizeOrganizationRole(activeOrganization.data?.members.find((member) => member.userId === session.data?.user.id)?.role);
468
513
  const canManageApiKeys = activeMemberRole === "owner" || activeMemberRole === "admin";
469
514
  const canUpdateOrganization = canManageApiKeys;
515
+ const canSwitchOrganizations = features?.organizationSwitching ?? true;
516
+ const canCreateOrganization = features?.organizationCreation ?? true;
517
+ const canViewOrganizationInvitations = features?.userInvitations ?? true;
470
518
  const setDialog = (next) => {
471
519
  const nextDialog = typeof next === "function" ? next(dialog) : next;
472
520
  if (nextDialog === dialog)
@@ -496,14 +544,18 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
496
544
  }
497
545
  const active = activeOrganization.data;
498
546
  const activeName = active?.name;
499
- const selectableOrganizations = !locked
500
- ? (organizations.data?.filter((organization) => organization.id !== active?.id) ?? [])
547
+ const visibleOrganizations = organizations.data?.filter((organization) => !allowedOrganizationIds ||
548
+ allowedOrganizationIds.includes(organization.id)) ?? [];
549
+ const selectableOrganizations = canSwitchOrganizations
550
+ ? visibleOrganizations.filter((organization) => organization.id !== active?.id)
501
551
  : [];
502
- const hasOrganizationListItems = organizations.isPending || Boolean(organizations.error) || !locked;
552
+ const hasOrganizationListItems = organizations.isPending ||
553
+ Boolean(organizations.error) ||
554
+ canSwitchOrganizations;
503
555
  const refreshAfterInvitationAction = async (previousActiveId) => {
504
556
  refreshUserInvitations();
505
557
  await refresh();
506
- if (locked && previousActiveId) {
558
+ if (!canSwitchOrganizations && previousActiveId) {
507
559
  const result = await authClient.organization.setActive({
508
560
  organizationId: previousActiveId,
509
561
  });
@@ -521,7 +573,7 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
521
573
  ? { imageSrc: activeDisplay.image }
522
574
  : {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.image
523
575
  ? { imageSrc: activeDisplay.image }
524
- : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizations.error ? (_jsx(DropdownMenuItem, { disabled: true, children: organizations.error.message })) : null, !locked && selectableOrganizations.length ? (selectableOrganizations.map((organization) => {
576
+ : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizations.error ? (_jsx(DropdownMenuItem, { disabled: true, children: organizations.error.message })) : null, canSwitchOrganizations && selectableOrganizations.length ? (selectableOrganizations.map((organization) => {
525
577
  const display = organizationDisplay(organization, m, baseUrl);
526
578
  return (_jsx(DropdownMenuItem, { onClick: async () => {
527
579
  const result = await authClient.organization.setActive({
@@ -532,18 +584,18 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
532
584
  onChange?.(organization);
533
585
  }
534
586
  }, children: _jsx(AppBrand, { to: null, label: display.name, subtitle: organizationSwitcherSubtitle(organization, display.subtitle, m), icon: Building2, className: "w-full text-left [&>div:first-child]:size-7", ...(display.image ? { imageSrc: display.image } : {}) }) }, organization.id));
535
- })) : !locked && !organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: active
587
+ })) : canSwitchOrganizations && !organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: active
536
588
  ? m.organization_switcher_no_other_organizations()
537
- : m.organization_switcher_empty() })) : null, !locked ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { onClick: openCreate, children: [_jsx(Plus, {}), m.organization_create_title()] }), _jsxs(DropdownMenuItem, { onClick: () => {
589
+ : m.organization_switcher_empty() })) : null, canCreateOrganization || canViewOrganizationInvitations ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), canCreateOrganization ? (_jsxs(DropdownMenuItem, { onClick: openCreate, children: [_jsx(Plus, {}), m.organization_create_title()] })) : null, canViewOrganizationInvitations ? (_jsxs(DropdownMenuItem, { onClick: () => {
538
590
  setDialog("invitations");
539
- }, children: [_jsx(Mail, {}), _jsxs("span", { className: "flex flex-1 items-center justify-between gap-3", children: [m.organization_user_invitations_title(), userInvitations.length ? (_jsx(Badge, { variant: "secondary", children: userInvitations.length })) : null] })] })] })) : null, activeOrganization.data ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), (() => {
591
+ }, children: [_jsx(Mail, {}), _jsxs("span", { className: "flex flex-1 items-center justify-between gap-3", children: [m.organization_user_invitations_title(), userInvitations.length ? (_jsx(Badge, { variant: "secondary", className: "bg-secondary! text-secondary-foreground!", children: userInvitations.length })) : null] })] })) : null] })) : null, activeOrganization.data ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), (() => {
540
592
  const organizationId = activeOrganization.data.id;
541
593
  return (_jsxs(DropdownMenuItem, { onClick: () => {
542
594
  void navigator.clipboard.writeText(organizationId);
543
595
  }, children: [_jsx(Copy, {}), m.organization_copy_id()] }));
544
- })(), canUpdateOrganization ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] })) : null, _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), canManageApiKeys ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })) : null] })) : null] }) })] })), _jsx(Dialog, { open: dialog === "create", onOpenChange: (open) => {
596
+ })(), canUpdateOrganization ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] })) : null, _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), canManageApiKeys ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })) : null] })) : null] }) })] })), _jsx(Dialog, { open: dialog === "create" && canCreateOrganization, onOpenChange: (open) => {
545
597
  setDialog((current) => open ? "create" : current === "create" ? null : current);
546
- }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() })] }), _jsx(Separator, {}), _jsx(CreateOrganizationSection, { authClient: authClient, baseUrl: baseUrl, onCreated: async (organization) => {
598
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() })] }), _jsx(Separator, {}), _jsx(CreateOrganizationSection, { authClient: authClient, baseUrl: baseUrl, organizations: visibleOrganizations, onCreated: async (organization) => {
547
599
  setDialog(null);
548
600
  const activeResult = await authClient.organization.setActive({
549
601
  organizationId: organization.id,
@@ -564,7 +616,7 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
564
616
  onChange?.(null);
565
617
  } })) : null] }) }), _jsx(Dialog, { open: dialog === "apiKeys" && canManageApiKeys, onOpenChange: (open) => {
566
618
  setDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
567
- }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_api_keys_title() }), _jsx(DialogDescription, { children: activeOrganization.data?.name })] }), _jsx(Separator, {}), activeOrganization.data ? (_jsx(OrganizationApiKeyManager, { authClient: authClient, organization: activeOrganization.data, active: dialog === "apiKeys" && canManageApiKeys })) : null] }) }), _jsx(Dialog, { open: dialog === "invitations" && !locked, onOpenChange: (open) => {
619
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_api_keys_title() }), _jsx(DialogDescription, { children: activeOrganization.data?.name })] }), _jsx(Separator, {}), activeOrganization.data ? (_jsx(OrganizationApiKeyManager, { authClient: authClient, organization: activeOrganization.data, active: dialog === "apiKeys" && canManageApiKeys })) : null] }) }), _jsx(Dialog, { open: dialog === "invitations" && canViewOrganizationInvitations, onOpenChange: (open) => {
568
620
  setDialog((current) => open ? "invitations" : current === "invitations" ? null : current);
569
621
  }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_user_invitations_title() }), _jsx(DialogDescription, { children: m.organization_user_invitations_description() })] }), _jsx(Separator, {}), _jsx(UserInvitationsManager, { authClient: authClient, baseUrl: baseUrl, invitations: userInvitations, loading: loadingUserInvitations, error: userInvitationsError, ...(activeOrganization.data
570
622
  ? { activeOrganizationId: activeOrganization.data.id }
@@ -685,21 +737,26 @@ function EditOrganizationSection({ authClient, baseUrl, organization, onUpdated,
685
737
  const [defaultLocale] = useState(currentOrganizationLocale);
686
738
  const [editingLocale, setEditingLocale] = useState(defaultLocale);
687
739
  const defaultValues = organizationFormDefaults(organization, baseUrl);
688
- const form = useAppForm({
689
- defaultValues,
690
- onSubmit: async ({ value, formApi }) => {
691
- formApi.setErrorMap({ onSubmit: undefined });
692
- try {
740
+ const [form] = useState(() => FormReact.make(organizationFormBuilder, {
741
+ fields: {
742
+ parentId: SelectField,
743
+ slug: TextField,
744
+ enName: TextField,
745
+ enLogo: ImageField,
746
+ enIcon: ImageField,
747
+ enContactEmail: TextField,
748
+ enLocation: TextField,
749
+ frName: TextField,
750
+ frLogo: ImageField,
751
+ frIcon: ImageField,
752
+ frContactEmail: TextField,
753
+ frLocation: TextField,
754
+ },
755
+ onSubmit: (_, { decoded: value }) => Effect.tryPromise({
756
+ try: async () => {
693
757
  const name = organizationNameFromForm(value, defaultLocale);
694
- if (!name) {
695
- formApi.setErrorMap({
696
- onSubmit: {
697
- form: m.organization_name_required(),
698
- fields: {},
699
- },
700
- });
701
- return;
702
- }
758
+ if (!name)
759
+ throw new Error(m.organization_name_required());
703
760
  const slug = value.slug.trim().toLowerCase();
704
761
  const metadata = await organizationMetadataFromForm(value, m, uploadImage);
705
762
  const result = await authClient.organization.update({
@@ -707,151 +764,137 @@ function EditOrganizationSection({ authClient, baseUrl, organization, onUpdated,
707
764
  data: { name, slug, metadata },
708
765
  });
709
766
  if (result.error) {
710
- formApi.setErrorMap({
711
- onSubmit: {
712
- form: result.error.message ?? m.organization_update_error(),
713
- fields: {},
714
- },
715
- });
716
- return;
767
+ throw new Error(result.error.message ?? m.organization_update_error());
717
768
  }
718
769
  await onUpdated();
719
- }
720
- catch (cause) {
721
- formApi.setErrorMap({
722
- onSubmit: {
723
- form: cause instanceof Error
724
- ? cause.message
725
- : m.organization_update_error(),
726
- fields: {},
727
- },
728
- });
729
- }
730
- },
731
- });
732
- return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
770
+ return result.data;
771
+ },
772
+ catch: (cause) => cause instanceof Error
773
+ ? cause
774
+ : new Error(m.organization_update_error()),
775
+ }),
776
+ }));
777
+ const submit = useAtomSet(form.submit);
778
+ const submitResult = useAtomValue(form.submit);
779
+ return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.Initialize, { defaultValues: defaultValues, children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
733
780
  event.preventDefault();
734
781
  event.stopPropagation();
735
- form.handleSubmit();
736
- }, children: [_jsx(form.AppField, { name: "slug", children: (field) => (_jsx(field.TextField, { label: m.organization_slug(), required: true })) }), _jsx(Separator, { className: "my-2" }), _jsx(OrganizationTranslationHeader, { locale: editingLocale, editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsxs(FieldSet, { disabled: editingLocale !== "en", className: editingLocale === "en" ? "contents" : "hidden", children: [_jsx(form.AppField, { name: "enName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "enLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), size: {
737
- width: 175,
738
- height: 50,
739
- suggestedWidth: 350,
740
- suggestedHeight: 100,
741
- } })) }), _jsx(form.AppField, { name: "enIcon", children: (field) => (_jsx(field.ImageField, { label: m.organization_icon(), size: {
742
- width: 96,
743
- height: 96,
744
- suggestedWidth: 512,
745
- suggestedHeight: 512,
746
- } })) }), _jsx(form.AppField, { name: "enContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "enLocation", children: (field) => _jsx(field.TextField, { label: m.organization_location() }) })] }), _jsxs(FieldSet, { disabled: editingLocale !== "fr", className: editingLocale === "fr" ? "contents" : "hidden", children: [_jsx(form.AppField, { name: "frName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "frLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), size: {
747
- width: 175,
748
- height: 50,
749
- suggestedWidth: 350,
750
- suggestedHeight: 100,
751
- } })) }), _jsx(form.AppField, { name: "frIcon", children: (field) => (_jsx(field.ImageField, { label: m.organization_icon(), size: {
752
- width: 96,
753
- height: 96,
754
- suggestedWidth: 512,
755
- suggestedHeight: 512,
756
- } })) }), _jsx(form.AppField, { name: "frContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "frLocation", children: (field) => _jsx(field.TextField, { label: m.organization_location() }) })] }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }) }));
782
+ submit();
783
+ }, children: [_jsx(form.slug, { label: m.organization_slug(), required: true }), _jsx(Separator, { className: "my-2" }), _jsx(OrganizationTranslationHeader, { locale: editingLocale, editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsxs(FieldSet, { disabled: editingLocale !== "en", className: editingLocale === "en" ? "contents" : "hidden", children: [_jsx(form.enName, { label: m.organization_translation_name() }), _jsx(form.enLogo, { label: m.organization_logo(), size: {
784
+ width: 175,
785
+ height: 50,
786
+ suggestedWidth: 350,
787
+ suggestedHeight: 100,
788
+ } }), _jsx(form.enIcon, { label: m.organization_icon(), size: {
789
+ width: 96,
790
+ height: 96,
791
+ suggestedWidth: 512,
792
+ suggestedHeight: 512,
793
+ } }), _jsx(form.enContactEmail, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" }), _jsx(form.enLocation, { label: m.organization_location() })] }), _jsxs(FieldSet, { disabled: editingLocale !== "fr", className: editingLocale === "fr" ? "contents" : "hidden", children: [_jsx(form.frName, { label: m.organization_translation_name() }), _jsx(form.frLogo, { label: m.organization_logo(), size: {
794
+ width: 175,
795
+ height: 50,
796
+ suggestedWidth: 350,
797
+ suggestedHeight: 100,
798
+ } }), _jsx(form.frIcon, { label: m.organization_icon(), size: {
799
+ width: 96,
800
+ height: 96,
801
+ suggestedWidth: 512,
802
+ suggestedHeight: 512,
803
+ } }), _jsx(form.frContactEmail, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" }), _jsx(form.frLocation, { label: m.organization_location() })] }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
757
804
  }
758
- function CreateOrganizationSection({ authClient, baseUrl, onCreated, }) {
805
+ function CreateOrganizationSection({ authClient, baseUrl, organizations, onCreated, }) {
759
806
  const m = useOrganizationMessages();
760
807
  const uploadImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
761
808
  const [defaultLocale] = useState(currentOrganizationLocale);
762
809
  const [editingLocale, setEditingLocale] = useState(defaultLocale);
763
810
  const defaultValues = organizationFormDefaults(undefined, baseUrl);
764
- const form = useAppForm({
765
- defaultValues,
766
- onSubmit: async ({ value, formApi }) => {
767
- formApi.setErrorMap({ onSubmit: undefined });
768
- try {
811
+ const [form] = useState(() => FormReact.make(organizationFormBuilder, {
812
+ fields: {
813
+ parentId: SelectField,
814
+ slug: TextField,
815
+ enName: TextField,
816
+ enLogo: ImageField,
817
+ enIcon: ImageField,
818
+ enContactEmail: TextField,
819
+ enLocation: TextField,
820
+ frName: TextField,
821
+ frLogo: ImageField,
822
+ frIcon: ImageField,
823
+ frContactEmail: TextField,
824
+ frLocation: TextField,
825
+ },
826
+ onSubmit: (_, { decoded: value }) => Effect.tryPromise({
827
+ try: async () => {
769
828
  const name = organizationNameFromForm(value, defaultLocale);
770
- if (!name) {
771
- formApi.setErrorMap({
772
- onSubmit: {
773
- form: m.organization_name_required(),
774
- fields: {},
775
- },
776
- });
777
- return;
778
- }
829
+ if (!name)
830
+ throw new Error(m.organization_name_required());
779
831
  const slug = (value.slug.trim() || slugify(name)).toLowerCase();
780
- const metadata = await organizationMetadataFromForm({
781
- ...value,
782
- slug,
783
- }, m, uploadImage);
832
+ const metadata = await organizationMetadataFromForm({ ...value, slug }, m, uploadImage);
784
833
  const result = await authClient.organization.create({
785
834
  name,
786
835
  slug,
787
836
  metadata,
837
+ ...(value.parentId === noParentOrganization
838
+ ? {}
839
+ : { parentId: value.parentId }),
788
840
  });
789
841
  if (result.error) {
790
- if (isOrganizationSlugConflict(result.error)) {
791
- formApi.setErrorMap({
792
- onSubmit: {
793
- fields: {
794
- slug: { message: m.organization_create_slug_conflict() },
795
- },
796
- },
797
- });
798
- return;
799
- }
800
- formApi.setErrorMap({
801
- onSubmit: {
802
- form: result.error.message ?? m.organization_create_error(),
803
- fields: {},
804
- },
805
- });
806
- return;
842
+ throw new Error(isOrganizationSlugConflict(result.error)
843
+ ? m.organization_create_slug_conflict()
844
+ : (result.error.message ?? m.organization_create_error()));
807
845
  }
808
- form.reset();
809
846
  await onCreated(result.data);
810
- }
811
- catch (cause) {
812
- formApi.setErrorMap({
813
- onSubmit: {
814
- form: cause instanceof Error
815
- ? cause.message
816
- : m.organization_create_error(),
817
- fields: {},
818
- },
819
- });
820
- }
821
- },
822
- });
823
- const name = useStore(form.store, (state) => organizationNameFromForm(state.values, defaultLocale));
824
- const slugIsDirty = useStore(form.store, (state) => state.fieldMeta.slug?.isDirty ?? false);
847
+ return result.data;
848
+ },
849
+ catch: (cause) => cause instanceof Error
850
+ ? cause
851
+ : new Error(m.organization_create_error()),
852
+ }),
853
+ }));
854
+ const submit = useAtomSet(form.submit);
855
+ const submitResult = useAtomValue(form.submit);
856
+ const values = useAtomValue(form.values);
857
+ const setSlug = useAtomSet(form.getFieldAtoms(form.fields.slug).setValue);
858
+ const lastGeneratedSlug = useRef("");
859
+ const slugWasEdited = useRef(false);
825
860
  useEffect(() => {
826
- if (!slugIsDirty) {
827
- form.setFieldValue("slug", slugify(name), { dontUpdateMeta: true });
861
+ if (Option.isNone(values) || slugWasEdited.current)
862
+ return;
863
+ if (values.value.slug !== lastGeneratedSlug.current) {
864
+ slugWasEdited.current = true;
865
+ return;
828
866
  }
829
- }, [form, name, slugIsDirty]);
830
- return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
867
+ const generatedSlug = slugify(organizationNameFromForm(values.value, defaultLocale));
868
+ if (generatedSlug === values.value.slug)
869
+ return;
870
+ lastGeneratedSlug.current = generatedSlug;
871
+ setSlug(generatedSlug);
872
+ }, [defaultLocale, setSlug, values]);
873
+ return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.Initialize, { defaultValues: defaultValues, children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
831
874
  event.preventDefault();
832
875
  event.stopPropagation();
833
- form.handleSubmit();
834
- }, children: [_jsx(form.AppField, { name: "slug", children: (field) => (_jsx(field.TextField, { label: m.organization_slug(), description: m.organization_slug_description() })) }), _jsx(Separator, { className: "my-2" }), _jsx(OrganizationTranslationHeader, { locale: editingLocale, editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsxs(FieldSet, { disabled: editingLocale !== "en", className: editingLocale === "en" ? "contents" : "hidden", children: [_jsx(form.AppField, { name: "enName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "enLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), size: {
835
- width: 175,
836
- height: 50,
837
- suggestedWidth: 350,
838
- suggestedHeight: 100,
839
- } })) }), _jsx(form.AppField, { name: "enIcon", children: (field) => (_jsx(field.ImageField, { label: m.organization_icon(), size: {
840
- width: 96,
841
- height: 96,
842
- suggestedWidth: 512,
843
- suggestedHeight: 512,
844
- } })) }), _jsx(form.AppField, { name: "enContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "enLocation", children: (field) => _jsx(field.TextField, { label: m.organization_location() }) })] }), _jsxs(FieldSet, { disabled: editingLocale !== "fr", className: editingLocale === "fr" ? "contents" : "hidden", children: [_jsx(form.AppField, { name: "frName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "frLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), size: {
845
- width: 175,
846
- height: 50,
847
- suggestedWidth: 350,
848
- suggestedHeight: 100,
849
- } })) }), _jsx(form.AppField, { name: "frIcon", children: (field) => (_jsx(field.ImageField, { label: m.organization_icon(), size: {
850
- width: 96,
851
- height: 96,
852
- suggestedWidth: 512,
853
- suggestedHeight: 512,
854
- } })) }), _jsx(form.AppField, { name: "frContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "frLocation", children: (field) => _jsx(field.TextField, { label: m.organization_location() }) })] }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }) }));
876
+ submit();
877
+ }, children: [_jsx(form.slug, { label: m.organization_slug(), description: m.organization_slug_description() }), _jsx(form.parentId, { label: m.organization_parent(), description: m.organization_parent_description(), options: organizationParentOptions(organizations, m) }), _jsx(Separator, { className: "my-2" }), _jsx(OrganizationTranslationHeader, { locale: editingLocale, editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsxs(FieldSet, { disabled: editingLocale !== "en", className: editingLocale === "en" ? "contents" : "hidden", children: [_jsx(form.enName, { label: m.organization_translation_name() }), _jsx(form.enLogo, { label: m.organization_logo(), size: {
878
+ width: 175,
879
+ height: 50,
880
+ suggestedWidth: 350,
881
+ suggestedHeight: 100,
882
+ } }), _jsx(form.enIcon, { label: m.organization_icon(), size: {
883
+ width: 96,
884
+ height: 96,
885
+ suggestedWidth: 512,
886
+ suggestedHeight: 512,
887
+ } }), _jsx(form.enContactEmail, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" }), _jsx(form.enLocation, { label: m.organization_location() })] }), _jsxs(FieldSet, { disabled: editingLocale !== "fr", className: editingLocale === "fr" ? "contents" : "hidden", children: [_jsx(form.frName, { label: m.organization_translation_name() }), _jsx(form.frLogo, { label: m.organization_logo(), size: {
888
+ width: 175,
889
+ height: 50,
890
+ suggestedWidth: 350,
891
+ suggestedHeight: 100,
892
+ } }), _jsx(form.frIcon, { label: m.organization_icon(), size: {
893
+ width: 96,
894
+ height: 96,
895
+ suggestedWidth: 512,
896
+ suggestedHeight: 512,
897
+ } }), _jsx(form.frContactEmail, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" }), _jsx(form.frLocation, { label: m.organization_location() })] }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
855
898
  }
856
899
  function OrganizationTranslationHeader({ locale, editingLocale, onEditingLocaleChange, }) {
857
900
  const m = useOrganizationMessages();
@@ -903,28 +946,36 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
903
946
  return;
904
947
  setLastMembersData(currentMembersData);
905
948
  }, [currentMembersData]);
906
- const inviteForm = useAppForm({
907
- defaultValues: { email: "", role: "member" },
908
- onSubmit: async ({ value, formApi }) => {
909
- formApi.setErrorMap({ onSubmit: undefined });
910
- const result = await authClient.organization.inviteMember({
911
- email: value.email.trim(),
912
- role: normalizeInvitationRole(value.role),
913
- organizationId: organization.id,
914
- });
915
- if (result.error) {
916
- formApi.setErrorMap({
917
- onSubmit: {
918
- form: result.error.message ?? m.organization_invite_error(),
919
- fields: {},
920
- },
921
- });
922
- return;
923
- }
924
- inviteForm.reset();
925
- refreshMembers();
949
+ const [inviteForm] = useState(() => FormReact.make(inviteMemberFormBuilder, {
950
+ fields: {
951
+ email: TextField,
952
+ role: SelectField,
926
953
  },
927
- });
954
+ onSubmit: (_, { decoded: value }) => Effect.tryPromise({
955
+ try: async () => {
956
+ const result = await authClient.organization.inviteMember({
957
+ email: value.email.trim(),
958
+ role: normalizeInvitationRole(value.role),
959
+ organizationId: organization.id,
960
+ });
961
+ if (result.error) {
962
+ throw new Error(result.error.message ?? m.organization_invite_error());
963
+ }
964
+ refreshMembers();
965
+ return result.data;
966
+ },
967
+ catch: (cause) => cause instanceof Error
968
+ ? cause
969
+ : new Error(m.organization_invite_error()),
970
+ }),
971
+ }));
972
+ const submitInvitation = useAtomSet(inviteForm.submit);
973
+ const resetInvitation = useAtomSet(inviteForm.reset);
974
+ const inviteResult = useAtomValue(inviteForm.submit);
975
+ useEffect(() => {
976
+ if (AsyncResult.isSuccess(inviteResult))
977
+ resetInvitation();
978
+ }, [inviteResult, resetInvitation]);
928
979
  const updateRole = async (member, role) => {
929
980
  setError(null);
930
981
  const nextRole = Array.isArray(role)
@@ -985,14 +1036,14 @@ function OrganizationMembersManager({ authClient, baseUrl, canManageMembers, org
985
1036
  }
986
1037
  refreshMembers();
987
1038
  };
988
- return (_jsxs("div", { className: "flex min-w-0 flex-col gap-5", children: [canInviteMembers ? (_jsx("div", { className: "min-h-40 rounded-lg border p-4", children: _jsx(inviteForm.AppForm, { children: _jsxs("form", { className: "grid gap-4 sm:grid-cols-[minmax(0,1fr)_12rem_auto] sm:items-end", onSubmit: (event) => {
1039
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-5", children: [canInviteMembers ? (_jsx("div", { className: "min-h-40 rounded-lg border p-4", children: _jsx(inviteForm.Initialize, { defaultValues: { email: "", role: "member" }, children: _jsxs("form", { className: "grid gap-4 sm:grid-cols-[minmax(0,1fr)_12rem_auto] sm:items-end", onSubmit: (event) => {
989
1040
  event.preventDefault();
990
1041
  event.stopPropagation();
991
- inviteForm.handleSubmit();
992
- }, children: [_jsxs("div", { className: "sm:col-span-3", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(UserPlus, { className: "size-4" }), m.organization_invite_member_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_invite_member_description() })] }), _jsx(inviteForm.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.organization_member_email(), placeholder: "teammate@example.com", type: "email", required: true })) }), _jsx(inviteForm.AppField, { name: "role", children: (field) => (_jsx(field.SelectField, { label: m.organization_member_role(), options: organizationRoles.map((role) => ({
993
- label: organizationRoleLabel(role, m),
994
- value: role,
995
- })) })) }), _jsx("div", { className: "self-end", children: _jsx(inviteForm.SubmitButton, {}) }), _jsx(inviteForm.FormError, {})] }) }) })) : null, membersError ? (_jsx("p", { className: "text-destructive text-sm", children: membersError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsxs("section", { className: "flex min-w-0 flex-col gap-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: m.organization_members_heading() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_members_description() })] }), _jsx("div", { className: "-m-1 min-w-0 overflow-x-auto p-1", children: _jsx(DataTable, { columns: memberColumns({
1042
+ submitInvitation();
1043
+ }, children: [_jsxs("div", { className: "sm:col-span-3", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(UserPlus, { className: "size-4" }), m.organization_invite_member_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_invite_member_description() })] }), _jsx(inviteForm.email, { label: m.organization_member_email(), placeholder: "teammate@example.com", type: "email", required: true }), _jsx(inviteForm.role, { label: m.organization_member_role(), options: organizationRoles.map((role) => ({
1044
+ label: organizationRoleLabel(role, m),
1045
+ value: role,
1046
+ })) }), _jsx("div", { className: "self-end", children: _jsx(SubmitButton, { form: inviteForm }) }), _jsx(SubmitError, { result: inviteResult })] }) }) })) : null, membersError ? (_jsx("p", { className: "text-destructive text-sm", children: membersError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsxs("section", { className: "flex min-w-0 flex-col gap-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: m.organization_members_heading() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_members_description() })] }), _jsx("div", { className: "-m-1 min-w-0 overflow-x-auto p-1", children: _jsx(DataTable, { columns: memberColumns({
996
1047
  m,
997
1048
  baseUrl,
998
1049
  canChangeRoles: canManageMembers,
@@ -1138,33 +1189,32 @@ function OrganizationApiKeyManager({ authClient, organization, active, }) {
1138
1189
  onSuccess: () => null,
1139
1190
  });
1140
1191
  const loading = keysResult._tag === "Initial";
1141
- const createForm = useAppForm({
1142
- defaultValues: { name: "" },
1143
- onSubmit: async ({ value, formApi }) => {
1144
- formApi.setErrorMap({ onSubmit: undefined });
1145
- setCreatedKey(null);
1146
- try {
1192
+ const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
1193
+ fields: { name: TextField },
1194
+ onSubmit: (_, { decoded: value }) => Effect.tryPromise({
1195
+ try: async () => {
1196
+ setCreatedKey(null);
1147
1197
  const created = await createApiKey({
1148
1198
  configId: "organization",
1149
1199
  organizationId: organization.id,
1150
1200
  name: value.name.trim(),
1151
1201
  }, m.user_api_key_create_error());
1152
1202
  setCreatedKey(created.key);
1153
- createForm.reset();
1154
1203
  refreshKeys();
1155
- }
1156
- catch (cause) {
1157
- formApi.setErrorMap({
1158
- onSubmit: {
1159
- form: cause instanceof Error
1160
- ? cause.message
1161
- : m.user_api_key_create_error(),
1162
- fields: {},
1163
- },
1164
- });
1165
- }
1166
- },
1167
- });
1204
+ return created;
1205
+ },
1206
+ catch: (cause) => cause instanceof Error
1207
+ ? cause
1208
+ : new Error(m.user_api_key_create_error()),
1209
+ }),
1210
+ }));
1211
+ const submitApiKey = useAtomSet(createForm.submit);
1212
+ const resetApiKey = useAtomSet(createForm.reset);
1213
+ const createResult = useAtomValue(createForm.submit);
1214
+ useEffect(() => {
1215
+ if (AsyncResult.isSuccess(createResult))
1216
+ resetApiKey();
1217
+ }, [createResult, resetApiKey]);
1168
1218
  const deleteKey = async (key) => {
1169
1219
  const result = await authClient.apiKey.delete({
1170
1220
  configId: "organization",
@@ -1176,11 +1226,11 @@ function OrganizationApiKeyManager({ authClient, organization, active, }) {
1176
1226
  }
1177
1227
  refreshKeys();
1178
1228
  };
1179
- return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
1229
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.Initialize, { defaultValues: { name: "" }, children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
1180
1230
  event.preventDefault();
1181
1231
  event.stopPropagation();
1182
- createForm.handleSubmit();
1183
- }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_api_key_name(), required: true })) }), _jsx(createForm.FormError, {}), _jsx(createForm.SubmitButton, {})] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsx("code", { className: "bg-muted overflow-x-auto rounded-md p-3 text-sm", children: createdKey })] })) : null, keysError ? (_jsx("p", { className: "text-destructive text-sm", children: keysError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ m }), data: keys, features: {
1232
+ submitApiKey();
1233
+ }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.name, { label: m.user_api_key_name(), required: true }), _jsx(SubmitError, { result: createResult }), _jsx(SubmitButton, { form: createForm })] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsx("code", { className: "bg-muted overflow-x-auto rounded-md p-3 text-sm", children: createdKey })] })) : null, keysError ? (_jsx("p", { className: "text-destructive text-sm", children: keysError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ m }), data: keys, features: {
1184
1234
  export: { baseName: `${organization.slug}-api-keys` },
1185
1235
  gallery: false,
1186
1236
  rowActions: {