@alepha/ui 0.32.0 → 0.33.0

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.
Files changed (186) hide show
  1. package/dist/account/AccountConnections.js +1 -1
  2. package/dist/account/AccountConnections.js.map +1 -1
  3. package/dist/account/AccountDeleteDialog.d.ts.map +1 -1
  4. package/dist/account/AccountDeleteDialog.js +17 -17
  5. package/dist/account/AccountDeleteDialog.js.map +1 -1
  6. package/dist/account/AccountKeys.js +2 -2
  7. package/dist/account/AccountKeys.js.map +1 -1
  8. package/dist/account/AccountMfaDialog.d.ts.map +1 -1
  9. package/dist/account/AccountMfaDialog.js +19 -25
  10. package/dist/account/AccountMfaDialog.js.map +1 -1
  11. package/dist/account/AccountPasswordDialog.d.ts.map +1 -1
  12. package/dist/account/AccountPasswordDialog.js +25 -24
  13. package/dist/account/AccountPasswordDialog.js.map +1 -1
  14. package/dist/account/AccountProfile.d.ts.map +1 -1
  15. package/dist/account/AccountProfile.js +17 -24
  16. package/dist/account/AccountProfile.js.map +1 -1
  17. package/dist/account/AccountSecurity.d.ts.map +1 -1
  18. package/dist/account/AccountSecurity.js +21 -19
  19. package/dist/account/AccountSecurity.js.map +1 -1
  20. package/dist/account/AccountSessions.js +1 -1
  21. package/dist/account/AccountSessions.js.map +1 -1
  22. package/dist/account/ApiKeyCreateDialog.d.ts.map +1 -1
  23. package/dist/account/ApiKeyCreateDialog.js +8 -12
  24. package/dist/account/ApiKeyCreateDialog.js.map +1 -1
  25. package/dist/admin/AdminFiles.js +1 -1
  26. package/dist/admin/AdminFiles.js.map +1 -1
  27. package/dist/admin/AdminJobs.js +1 -1
  28. package/dist/admin/AdminJobs.js.map +1 -1
  29. package/dist/admin/AdminKeys.js +1 -1
  30. package/dist/admin/AdminKeys.js.map +1 -1
  31. package/dist/admin/AdminParameters.d.ts.map +1 -1
  32. package/dist/admin/AdminParameters.js +7 -5
  33. package/dist/admin/AdminParameters.js.map +1 -1
  34. package/dist/admin/AdminParametersTreeFooterActions.d.ts +2 -2
  35. package/dist/admin/AdminParametersTreeFooterActions.d.ts.map +1 -1
  36. package/dist/admin/AdminParametersTreeFooterActions.js.map +1 -1
  37. package/dist/admin/AdminParametersTreePane.d.ts +2 -2
  38. package/dist/admin/AdminParametersTreePane.d.ts.map +1 -1
  39. package/dist/admin/AdminParametersTreePane.js.map +1 -1
  40. package/dist/admin/AdminRouter.d.ts +1 -3
  41. package/dist/admin/AdminRouter.d.ts.map +1 -1
  42. package/dist/admin/AdminRouter.js +2 -4
  43. package/dist/admin/AdminRouter.js.map +1 -1
  44. package/dist/admin/AdminSessions.js +1 -1
  45. package/dist/admin/AdminSessions.js.map +1 -1
  46. package/dist/admin/AdminUserAvatarControl.d.ts.map +1 -1
  47. package/dist/admin/AdminUserAvatarControl.js +9 -16
  48. package/dist/admin/AdminUserAvatarControl.js.map +1 -1
  49. package/dist/admin/AdminUserDetail.js +4 -4
  50. package/dist/admin/AdminUserDetail.js.map +1 -1
  51. package/dist/admin/AdminUsers.d.ts.map +1 -1
  52. package/dist/admin/AdminUsers.js +10 -12
  53. package/dist/admin/AdminUsers.js.map +1 -1
  54. package/dist/admin/AdminUsersRolesPicker.d.ts +5 -1
  55. package/dist/admin/AdminUsersRolesPicker.d.ts.map +1 -1
  56. package/dist/admin/AdminUsersRolesPicker.js +2 -3
  57. package/dist/admin/AdminUsersRolesPicker.js.map +1 -1
  58. package/dist/admin/analytics/QueryPanel.js +1 -1
  59. package/dist/admin/analytics/QueryPanel.js.map +1 -1
  60. package/dist/admin/useConfirmedAction.d.ts +8 -2
  61. package/dist/admin/useConfirmedAction.d.ts.map +1 -1
  62. package/dist/admin/useConfirmedAction.js +15 -4
  63. package/dist/admin/useConfirmedAction.js.map +1 -1
  64. package/dist/auth/AuthLogin.d.ts.map +1 -1
  65. package/dist/auth/AuthLogin.js +4 -4
  66. package/dist/auth/AuthLogin.js.map +1 -1
  67. package/dist/auth/AuthRegister.js.map +1 -1
  68. package/dist/core/index.js +1 -1
  69. package/dist/form/AutoForm.js +1 -1
  70. package/dist/form/AutoForm.js.map +1 -1
  71. package/dist/form/Control.js +1 -1
  72. package/dist/form/Control.js.map +1 -1
  73. package/dist/form/ControlArray.js +5 -5
  74. package/dist/form/ControlArray.js.map +1 -1
  75. package/dist/form/ControlSelect.js +2 -2
  76. package/dist/form/ControlSelect.js.map +1 -1
  77. package/dist/form/ControlUpload.d.ts +1 -1
  78. package/dist/form/ControlUpload.js.map +1 -1
  79. package/dist/i18n/fr/uiFr.d.ts.map +1 -1
  80. package/dist/i18n/fr/uiFr.js +0 -9
  81. package/dist/i18n/fr/uiFr.js.map +1 -1
  82. package/dist/organizations/MyOrganizationInvitations.js +2 -2
  83. package/dist/organizations/MyOrganizationInvitations.js.map +1 -1
  84. package/dist/organizations/OrganizationInviteDialog.js +1 -1
  85. package/dist/organizations/OrganizationInviteDialog.js.map +1 -1
  86. package/dist/organizations/OrganizationMembers.js +1 -1
  87. package/dist/organizations/OrganizationMembers.js.map +1 -1
  88. package/dist/organizations/OrganizationPendingInvitations.js +1 -1
  89. package/dist/organizations/OrganizationPendingInvitations.js.map +1 -1
  90. package/dist/organizations/OrganizationRanks.js +3 -3
  91. package/dist/organizations/OrganizationRanks.js.map +1 -1
  92. package/dist/organizations/useInviteOrganizationMember.d.ts +6 -1
  93. package/dist/organizations/useInviteOrganizationMember.d.ts.map +1 -1
  94. package/dist/organizations/useInviteOrganizationMember.js +13 -13
  95. package/dist/organizations/useInviteOrganizationMember.js.map +1 -1
  96. package/dist/organizations/useRevokeOrganizationInvitation.d.ts +7 -1
  97. package/dist/organizations/useRevokeOrganizationInvitation.d.ts.map +1 -1
  98. package/dist/organizations/useRevokeOrganizationInvitation.js +13 -2
  99. package/dist/organizations/useRevokeOrganizationInvitation.js.map +1 -1
  100. package/dist/shell/ButtonUser.d.ts +1 -2
  101. package/dist/shell/ButtonUser.d.ts.map +1 -1
  102. package/dist/shell/ButtonUser.js +14 -42
  103. package/dist/shell/ButtonUser.js.map +1 -1
  104. package/dist/shell/ButtonUserContent.d.ts +13 -0
  105. package/dist/shell/ButtonUserContent.d.ts.map +1 -0
  106. package/dist/shell/ButtonUserContent.js +52 -0
  107. package/dist/shell/ButtonUserContent.js.map +1 -0
  108. package/dist/shell/ButtonUserPlaceholder.d.ts +14 -0
  109. package/dist/shell/ButtonUserPlaceholder.d.ts.map +1 -0
  110. package/dist/shell/ButtonUserPlaceholder.js +17 -0
  111. package/dist/shell/ButtonUserPlaceholder.js.map +1 -0
  112. package/dist/styles.css +31 -0
  113. package/dist/table/DataTable.js +1 -1
  114. package/dist/table/DataTable.js.map +1 -1
  115. package/dist/table/DataTableFilterBar.js +2 -2
  116. package/dist/table/DataTableFilterBar.js.map +1 -1
  117. package/dist/table/dataTableBaseProps.d.ts +1 -1
  118. package/dist/table/dataTableTypes.d.ts +3 -3
  119. package/dist/table/dataTableTypes.d.ts.map +1 -1
  120. package/dist/table/useDataTableData.d.ts.map +1 -1
  121. package/dist/table/useDataTableData.js +3 -1
  122. package/dist/table/useDataTableData.js.map +1 -1
  123. package/dist/table/useDataTableRefresh.js +2 -2
  124. package/dist/table/useDataTableRefresh.js.map +1 -1
  125. package/dist/table/useDataTableSummary.d.ts.map +1 -1
  126. package/dist/table/useDataTableSummary.js +2 -1
  127. package/dist/table/useDataTableSummary.js.map +1 -1
  128. package/package.json +6 -6
  129. package/src/account/AccountConnections.tsx +1 -1
  130. package/src/account/AccountDeleteDialog.tsx +25 -31
  131. package/src/account/AccountKeys.tsx +2 -2
  132. package/src/account/AccountMfaDialog.tsx +33 -27
  133. package/src/account/AccountPasswordDialog.tsx +36 -39
  134. package/src/account/AccountProfile.tsx +29 -43
  135. package/src/account/AccountSecurity.tsx +57 -64
  136. package/src/account/AccountSessions.tsx +1 -1
  137. package/src/account/ApiKeyCreateDialog.tsx +12 -20
  138. package/src/account/__tests__/AccountRouter.spec.ts +2 -1
  139. package/src/admin/AdminFiles.tsx +1 -1
  140. package/src/admin/AdminJobs.tsx +1 -1
  141. package/src/admin/AdminKeys.tsx +1 -1
  142. package/src/admin/AdminParameters.tsx +7 -5
  143. package/src/admin/AdminParametersTreeFooterActions.tsx +2 -2
  144. package/src/admin/AdminParametersTreePane.tsx +2 -2
  145. package/src/admin/AdminRouter.tsx +2 -4
  146. package/src/admin/AdminSessions.tsx +1 -1
  147. package/src/admin/AdminUserAvatarControl.tsx +17 -22
  148. package/src/admin/AdminUserDetail.tsx +4 -4
  149. package/src/admin/AdminUsers.tsx +10 -12
  150. package/src/admin/AdminUsersRolesPicker.tsx +11 -4
  151. package/src/admin/__tests__/AdminRouter.spec.ts +3 -2
  152. package/src/admin/analytics/QueryPanel.tsx +1 -1
  153. package/src/admin/useConfirmedAction.tsx +24 -10
  154. package/src/auth/AuthLogin.tsx +10 -9
  155. package/src/auth/AuthRegister.tsx +2 -2
  156. package/src/form/AutoForm.tsx +1 -1
  157. package/src/form/Control.tsx +1 -1
  158. package/src/form/ControlArray.tsx +5 -5
  159. package/src/form/ControlSelect.tsx +2 -2
  160. package/src/form/ControlUpload.tsx +1 -1
  161. package/src/form/__tests__/ControlArrayChildChange.browser.spec.tsx +1 -1
  162. package/src/i18n/fr/uiFr.ts +0 -9
  163. package/src/organizations/MyOrganizationInvitations.tsx +2 -2
  164. package/src/organizations/OrganizationInviteDialog.tsx +1 -1
  165. package/src/organizations/OrganizationMembers.tsx +1 -1
  166. package/src/organizations/OrganizationPendingInvitations.tsx +1 -1
  167. package/src/organizations/OrganizationRanks.tsx +3 -3
  168. package/src/organizations/useInviteOrganizationMember.ts +22 -15
  169. package/src/organizations/useRevokeOrganizationInvitation.ts +23 -4
  170. package/src/shell/ButtonUser.tsx +14 -79
  171. package/src/shell/ButtonUserContent.tsx +92 -0
  172. package/src/shell/ButtonUserPlaceholder.tsx +25 -0
  173. package/src/shell/__tests__/ActionErrorToaster.browser.spec.tsx +1 -1
  174. package/src/shell/__tests__/ActionErrorToasterHandled.browser.spec.tsx +1 -2
  175. package/src/shell/__tests__/AppShell.pageCache.spec.tsx +67 -0
  176. package/src/styles.css +31 -0
  177. package/src/table/DataTable.tsx +1 -1
  178. package/src/table/DataTableFilterBar.tsx +2 -2
  179. package/src/table/__tests__/DataTableFilterDateRange.browser.spec.tsx +1 -1
  180. package/src/table/__tests__/DataTableQuerySeed.browser.spec.tsx +1 -1
  181. package/src/table/__tests__/DataTableShareFilters.browser.spec.tsx +1 -1
  182. package/src/table/dataTableBaseProps.ts +1 -1
  183. package/src/table/dataTableTypes.ts +3 -3
  184. package/src/table/useDataTableData.ts +2 -0
  185. package/src/table/useDataTableRefresh.ts +3 -3
  186. package/src/table/useDataTableSummary.ts +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"AuthRegister.js","names":[],"sources":["../../src/auth/AuthRegister.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { SchemaValidationError, z } from \"alepha\";\nimport type {\n RealmConfig,\n RegistrationIntentResponse,\n UserController,\n} from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle } from \"lucide-react\";\nimport {\n type ReactNode,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSeparator,\n InputOTPSlot,\n} from \"../otp/InputOTP.tsx\";\nimport { AuthRegisterCentered } from \"./AuthRegisterCentered.tsx\";\nimport { AuthRegisterFormPhase } from \"./AuthRegisterFormPhase.tsx\";\nimport { AuthRegisterRealmLogo } from \"./AuthRegisterRealmLogo.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport type { TurnstileWidgetHandle } from \"./TurnstileWidget.tsx\";\n\nexport interface AuthRegisterProps {\n /**\n * Realm configuration (drives required fields, verification step, OAuth buttons).\n */\n realmConfig: RealmConfig;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Route to the login page. When set, a \"Sign in\" link is shown.\n */\n loginPath?: string;\n /**\n * Optional banner rendered above the registration form (form phase only).\n * Used to contextualize the flow when the user arrives via a CTA, e.g.\n * \"Before creating a campaign, create an account.\"\n */\n message?: ReactNode;\n /**\n * Where the \"Cancel\" button abandons to. Defaults to \"/\". This is\n * intentionally decoupled from the post-auth `?redirect=` target: cancelling\n * an unauthenticated registration must land somewhere public (home), not the\n * protected destination the user was *heading* to — which would only bounce\n * them back to this page.\n */\n cancelPath?: string;\n /**\n * Render the form even though `settings.registrationAllowed` is `false`.\n *\n * For a visitor the application has already vouched for out of band - an\n * invitation link, a signup code - who would otherwise meet the closed\n * alert and stop. Presentation only: the server decides, through the\n * realm's `isPreAuthorized` seam, and refuses this submit like any other if\n * {@link preAuthToken} does not hold up.\n */\n preAuthorized?: boolean;\n /**\n * Pre-fill the email field and stop it being edited.\n *\n * Set it alongside {@link preAuthToken}, which is bound to one address:\n * letting the field be typed over only produces a server-side refusal the\n * visitor cannot act on.\n */\n lockedEmail?: string;\n /**\n * The application's opaque proof that this address may register into a\n * closed realm. Passed through to the register request untouched.\n */\n preAuthToken?: string;\n /**\n * Where a successful registration lands, overriding `?redirect=`.\n *\n * A prop rather than a URL param because the submit handler is built ONCE,\n * at mount, and closes over whatever `redirect` was then: a page that\n * decides the destination and seeds the query afterwards has already\n * missed it, and the user lands on the default with nothing to explain\n * why. A prop is read on the render that builds the handler.\n *\n * Sanitised like the query value, since the two are the same kind of thing.\n */\n redirect?: string;\n}\n\nexport const AuthRegister = (props: AuthRegisterProps) => {\n const auth = useAuth();\n const userCtrl = useClient<UserController>();\n const router = useRouter();\n const { tr } = useI18n();\n const redirect = safeRedirect(props.redirect ?? router.query.redirect);\n // Surface upstream auth errors (e.g. failed OAuth callback redirects with\n // `?error=...`) — same pattern as AuthLogin. Without this the user lands on\n // a fresh-looking registration page with no clue why.\n const queryError =\n typeof router.query.error === \"string\" ? router.query.error : undefined;\n\n const [state, setState] = useState<State>({ phase: \"form\" });\n const [emailCode, setEmailCode] = useState(\"\");\n const [phoneCode, setPhoneCode] = useState(\"\");\n const [verifyError, setVerifyError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n // The handler reads the token the widget issued last through a ref, so a\n // submit never posts a token captured by an earlier render.\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n // The realm decides, unless the application has already vouched for this\n // particular visitor. Both halves are presentation: the gate is\n // `RegistrationService`, which refuses a submit that the seam does not\n // recognise however the form got rendered.\n const allowed =\n props.preAuthorized === true || settings.registrationAllowed !== false;\n\n const schema = useMemo(() => {\n // Optionality is decided as each field is built, because that is the only\n // thing the form reads: `FormModel` derives both the required marker and\n // the pre-submit check from `z.schema.requiredKeys(schema)`, which asks\n // whether the field is optional or defaulted.\n //\n // This used to declare every field optional and then push the configured\n // names onto the array returned by `z.schema.requiredKeys(s)` — a TypeBox\n // habit, where a JSON Schema's `required` was a live array hanging off the\n // schema. The zod implementation computes a fresh array from the shape, so\n // the pushes mutated a detached value and vanished: a realm with\n // `email: \"required\"` still rendered Email with no asterisk and let an\n // empty one through to the server.\n const names = settings.firstNameLastName === \"required\";\n const shape = {\n firstName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n username:\n settings.username === \"required\"\n ? z.text({ trim: true, pattern: settings.usernameRegExp })\n : z.text({ trim: true, pattern: settings.usernameRegExp }).optional(),\n email: settings.email === \"required\" ? z.email() : z.email().optional(),\n phoneNumber:\n settings.phoneNumber === \"required\" ? z.e164() : z.e164().optional(),\n password: z.string().min(settings.passwordPolicy?.minLength ?? 8),\n };\n\n // The runtime shape varies with the realm, but the *type* must not: every\n // consumer below reads `data.email`, `data.username` and the rest as\n // possibly-absent. Widening to the all-optional shape keeps one stable\n // type instead of a union of eight.\n return z.object(shape) as unknown as ReturnType<typeof registerFormSchema>;\n }, [settings]);\n\n const form = useForm({\n schema,\n // A locked address is the form's starting value, not a field the visitor\n // fills. It arrives before mount (the page resolves the token in its\n // loader), which is what lets `useForm` anchor it here.\n initialValues: props.lockedEmail\n ? ({ email: props.lockedEmail } as never)\n : undefined,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n try {\n const intent = await userCtrl.createRegistrationIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n firstName: data.firstName,\n lastName: data.lastName,\n username: data.username,\n // The locked address wins over whatever the field holds: it is\n // the one the token is bound to, and a disabled input is a\n // presentation fact rather than a guarantee.\n email: props.lockedEmail ?? data.email,\n phoneNumber: data.phoneNumber,\n password: data.password,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n preAuthToken: props.preAuthToken,\n },\n });\n const identifier =\n data.username ?? props.lockedEmail ?? data.email ?? data.phoneNumber;\n if (\n intent.expectEmailVerification ||\n intent.expectPhoneVerification ||\n intent.expectCaptcha\n ) {\n setState({\n phase: \"verification\",\n intent,\n credentials: identifier\n ? { identifier, password: data.password }\n : undefined,\n });\n return;\n }\n await userCtrl.createUserFromIntent({\n body: { intentId: intent.intentId },\n });\n if (identifier && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n // Turnstile tokens are single-use — force a fresh challenge so the\n // user can retry after a server-side failure.\n captchaRef.current?.reset();\n throw err;\n }\n },\n });\n\n const formState = useFormState(form, [\"error\", \"values\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const passwordValue = String(formState.values?.password ?? \"\");\n\n const firstFieldId =\n (settings.firstNameLastName !== \"none\" && form.input.firstName?.props.id) ||\n (settings.username !== \"none\" &&\n settings.username !== \"email\" &&\n form.input.username?.props.id) ||\n (settings.email !== \"none\" && form.input.email?.props.id) ||\n (settings.phoneNumber !== \"none\" && form.input.phoneNumber?.props.id) ||\n form.input.password.props.id;\n\n useEffect(() => {\n if (state.phase !== \"form\" || !firstFieldId) return;\n const el = document.getElementById(\n String(firstFieldId),\n ) as HTMLInputElement | null;\n el?.focus();\n }, [state.phase, firstFieldId]);\n\n const handleVerify = async () => {\n if (!state.intent) return;\n setSubmitting(true);\n setVerifyError(null);\n try {\n await userCtrl.createUserFromIntent({\n body: {\n intentId: state.intent.intentId,\n emailCode: state.intent.expectEmailVerification\n ? emailCode\n : undefined,\n phoneCode: state.intent.expectPhoneVerification\n ? phoneCode\n : undefined,\n },\n });\n if (state.credentials && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: state.credentials.identifier,\n password: state.credentials.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n setVerifyError(\n err instanceof Error\n ? err.message\n : tr(\"auth.register.verifyFailed\", {\n default: \"Verification failed\",\n }),\n );\n } finally {\n setSubmitting(false);\n }\n };\n\n // Query appended to the \"already have an account? sign in\" link: the realm,\n // plus the post-auth redirect (`?redirect=`) so signing in returns the user\n // to wherever registering would have sent them (it's dropped otherwise).\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const loginQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = loginQ ? `?${loginQ}` : \"\";\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n const showDivider = credentialsProvider && externalMethods.length > 0;\n const isVerifying = state.phase === \"verification\" && state.intent;\n const canSubmitVerify =\n !isVerifying ||\n ((!state.intent!.expectEmailVerification || emailCode.length === 6) &&\n (!state.intent!.expectPhoneVerification || phoneCode.length === 6));\n\n const contentRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n const el = contentRef.current;\n if (!el) return;\n setContentHeight(el.scrollHeight);\n const ro = new ResizeObserver(() => {\n setContentHeight(el.scrollHeight);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n return (\n <AuthRegisterCentered>\n {props.logo ?? (\n <AuthRegisterRealmLogo\n settings={settings}\n realmName={props.realmConfig.realmName}\n />\n )}\n <Card className=\"w-full\">\n <CardContent\n className=\"overflow-hidden p-0 transition-[height] duration-300 ease-out\"\n style={\n contentHeight !== undefined ? { height: contentHeight } : undefined\n }\n >\n <div ref={contentRef}>\n <div\n key={state.phase}\n className=\"animate-in fade-in flex flex-col gap-4 px-6 duration-300\"\n >\n {isVerifying ? (\n <>\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.register.verifyTitle\", {\n default: \"Verify your account\",\n })}\n </h2>\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.register.verifyHint\", {\n default:\n \"Please enter the verification code(s) sent to you.\",\n })}\n </p>\n {verifyError && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{verifyError}</AlertDescription>\n </Alert>\n )}\n {state.intent!.expectEmailVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"emailCode\">\n {tr(\"auth.register.emailCode\", {\n default: \"Email verification code\",\n })}\n </Label>\n <InputOTP\n id=\"emailCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={emailCode}\n onChange={setEmailCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n {state.intent!.expectPhoneVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"phoneCode\">\n {tr(\"auth.register.phoneCode\", {\n default: \"Phone verification code\",\n })}\n </Label>\n <InputOTP\n id=\"phoneCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={phoneCode}\n onChange={setPhoneCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n <Button\n onClick={handleVerify}\n loading={submitting}\n disabled={!canSubmitVerify}\n >\n {tr(\"auth.register.verifySubmit\", {\n default: \"Complete registration\",\n })}\n </Button>\n <Button\n variant=\"minimal\"\n onClick={() => setState({ phase: \"form\" })}\n >\n {tr(\"auth.register.verifyBack\", {\n default: \"Back to registration\",\n })}\n </Button>\n </>\n ) : (\n <AuthRegisterFormPhase\n allowed={allowed}\n form={form}\n formError={formError ?? queryError}\n loading={formState.loading}\n passwordValue={passwordValue}\n settings={settings}\n realmName={props.realmConfig.realmName}\n credentialsProvider={credentialsProvider}\n externalMethods={externalMethods}\n showDivider={showDivider}\n redirect={redirect}\n loginPath={props.loginPath}\n realmQuery={realmQuery}\n auth={auth}\n captchaSiteKey={captchaSiteKey}\n captchaToken={captchaToken}\n captchaRef={captchaRef}\n onCaptchaToken={setCaptchaToken}\n message={props.message}\n lockedEmail={props.lockedEmail}\n />\n )}\n </div>\n </div>\n </CardContent>\n </Card>\n {!isVerifying && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? \"/\"} />}\n >\n {tr(\"auth.register.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </AuthRegisterCentered>\n );\n};\n\ntype Phase = \"form\" | \"verification\";\n\ninterface State {\n phase: Phase;\n intent?: RegistrationIntentResponse;\n credentials?: { identifier: string; password: string };\n}\n\n/**\n * The reference shape of the registration form, with every configurable field\n * optional.\n *\n * `AuthRegister` builds its real schema from the realm settings, so which\n * fields are optional changes per realm. This exists purely to give that\n * schema one stable TypeScript type: the handler reads `data.email`,\n * `data.username` and `data.phoneNumber` as possibly-absent regardless of what\n * a given realm requires, which is the correct type for code that has to\n * compile against all of them.\n */\nconst registerFormSchema = () =>\n z.object({\n firstName: z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: z.text({ trim: true, maxLength: 100 }).optional(),\n username: z.text({ trim: true }).optional(),\n email: z.email().optional(),\n phoneNumber: z.e164().optional(),\n password: z.string(),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2GA,MAAa,gBAAgB,UAA6B;CACxD,MAAM,OAAO,QAAQ;CACrB,MAAM,WAAW,UAA0B;CAC3C,MAAM,SAAS,UAAU;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,a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AAC,eAAD,EAAA,UAAA;WACE,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;WACzB,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;WACzB,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;UACZ,EAAA,CAAA;UACf,oBAAC,mBAAD,CAAoB,CAAA;UACpB,qBAAC,eAAD,EAAA,UAAA;WACE,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;WACzB,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;WACzB,oBAAC,cAAD,EAAc,OAAO,EAAI,CAAA;UACZ,EAAA,CAAA;SACP;QACP,CAAA,CAAA;;OAEP,oBAAC,QAAD;QACE,SAAS;QACT,SAAS;QACT,UAAU,CAAC;QAEV,UAAA,GAAG,8BAA8B,EAChC,SAAS,wBACX,CAAC;OACK,CAAA;OACR,oBAAC,QAAD;QACE,SAAQ;QACR,eAAe,SAAS,EAAE,OAAO,OAAO,CAAC;QAExC,UAAA,GAAG,4BAA4B,EAC9B,SAAS,uBACX,CAAC;OACK,CAAA;MACR,EAAA,CAAA,IAEF,oBAAC,uBAAD;OACW;OACH;OACN,WAAW,aAAa;OACxB,SAAS,UAAU;OACJ;OACL;OACV,WAAW,MAAM,YAAY;OACR;OACJ;OACJ;OACH;OACV,WAAW,MAAM;OACL;OACN;OACU;OACF;OACF;OACZ,gBAAgB;OAChB,SAAS,MAAM;OACf,aAAa,MAAM;MACpB,CAAA;KAEA,GA1HE,MAAM,KA0HR;IACF,CAAA;GACM,CAAA;EACT,CAAA;EACL,CAAC,eACA,oBAAC,QAAD;GACE,SAAQ;GACR,cAAc;GACd,QAAQ,oBAAC,KAAD,EAAG,MAAM,MAAM,cAAc,IAAM,CAAA;GAE1C,UAAA,GAAG,wBAAwB,EAAE,SAAS,SAAS,CAAC;EAC3C,CAAA;CAEU,EAAA,CAAA;AAE1B"}
1
+ {"version":3,"file":"AuthRegister.js","names":[],"sources":["../../src/auth/AuthRegister.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { SchemaValidationError, z } from \"alepha\";\nimport type {\n RealmConfig,\n RegistrationIntentResponse,\n UserController,\n} from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle } from \"lucide-react\";\nimport {\n type ReactNode,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSeparator,\n InputOTPSlot,\n} from \"../otp/InputOTP.tsx\";\nimport { AuthRegisterCentered } from \"./AuthRegisterCentered.tsx\";\nimport { AuthRegisterFormPhase } from \"./AuthRegisterFormPhase.tsx\";\nimport { AuthRegisterRealmLogo } from \"./AuthRegisterRealmLogo.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport type { TurnstileWidgetHandle } from \"./TurnstileWidget.tsx\";\n\nexport interface AuthRegisterProps {\n /**\n * Realm configuration (drives required fields, verification step, OAuth buttons).\n */\n realmConfig: RealmConfig;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Route to the login page. When set, a \"Sign in\" link is shown.\n */\n loginPath?: string;\n /**\n * Optional banner rendered above the registration form (form phase only).\n * Used to contextualize the flow when the user arrives via a CTA, e.g.\n * \"Before creating a campaign, create an account.\"\n */\n message?: ReactNode;\n /**\n * Where the \"Cancel\" button abandons to. Defaults to \"/\". This is\n * intentionally decoupled from the post-auth `?redirect=` target: cancelling\n * an unauthenticated registration must land somewhere public (home), not the\n * protected destination the user was *heading* to — which would only bounce\n * them back to this page.\n */\n cancelPath?: string;\n /**\n * Render the form even though `settings.registrationAllowed` is `false`.\n *\n * For a visitor the application has already vouched for out of band - an\n * invitation link, a signup code - who would otherwise meet the closed\n * alert and stop. Presentation only: the server decides, through the\n * realm's `isPreAuthorized` seam, and refuses this submit like any other if\n * {@link preAuthToken} does not hold up.\n */\n preAuthorized?: boolean;\n /**\n * Pre-fill the email field and stop it being edited.\n *\n * Set it alongside {@link preAuthToken}, which is bound to one address:\n * letting the field be typed over only produces a server-side refusal the\n * visitor cannot act on.\n */\n lockedEmail?: string;\n /**\n * The application's opaque proof that this address may register into a\n * closed realm. Passed through to the register request untouched.\n */\n preAuthToken?: string;\n /**\n * Where a successful registration lands, overriding `?redirect=`.\n *\n * A prop rather than a URL param because the submit handler is built ONCE,\n * at mount, and closes over whatever `redirect` was then: a page that\n * decides the destination and seeds the query afterwards has already\n * missed it, and the user lands on the default with nothing to explain\n * why. A prop is read on the render that builds the handler.\n *\n * Sanitised like the query value, since the two are the same kind of thing.\n */\n redirect?: string;\n}\n\nexport const AuthRegister = (props: AuthRegisterProps) => {\n const auth = useAuth();\n const userCtrl = useClient<UserController>();\n const router = useRouter();\n const { tr } = useI18n();\n const redirect = safeRedirect(props.redirect ?? router.query.redirect);\n // Surface upstream auth errors (e.g. failed OAuth callback redirects with\n // `?error=...`) — same pattern as AuthLogin. Without this the user lands on\n // a fresh-looking registration page with no clue why.\n const queryError =\n typeof router.query.error === \"string\" ? router.query.error : undefined;\n\n const [state, setState] = useState<State>({ phase: \"form\" });\n const [emailCode, setEmailCode] = useState(\"\");\n const [phoneCode, setPhoneCode] = useState(\"\");\n const [verifyError, setVerifyError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n // The handler reads the token the widget issued last through a ref, so a\n // submit never posts a token captured by an earlier render.\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n // The realm decides, unless the application has already vouched for this\n // particular visitor. Both halves are presentation: the gate is\n // `RegistrationService`, which refuses a submit that the seam does not\n // recognise however the form got rendered.\n const allowed =\n props.preAuthorized === true || settings.registrationAllowed !== false;\n\n const schema = useMemo(() => {\n // Optionality is decided as each field is built, because that is the only\n // thing the form reads: `FormModel` derives both the required marker and\n // the pre-submit check from `z.schema.requiredInputKeys(schema)`, which asks\n // whether the field is optional or defaulted.\n //\n // This used to declare every field optional and then push the configured\n // names onto the array returned by `z.schema.requiredInputKeys(s)` , a TypeBox\n // habit, where a JSON Schema's `required` was a live array hanging off the\n // schema. The zod implementation computes a fresh array from the shape, so\n // the pushes mutated a detached value and vanished: a realm with\n // `email: \"required\"` still rendered Email with no asterisk and let an\n // empty one through to the server.\n const names = settings.firstNameLastName === \"required\";\n const shape = {\n firstName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n username:\n settings.username === \"required\"\n ? z.text({ trim: true, pattern: settings.usernameRegExp })\n : z.text({ trim: true, pattern: settings.usernameRegExp }).optional(),\n email: settings.email === \"required\" ? z.email() : z.email().optional(),\n phoneNumber:\n settings.phoneNumber === \"required\" ? z.e164() : z.e164().optional(),\n password: z.string().min(settings.passwordPolicy?.minLength ?? 8),\n };\n\n // The runtime shape varies with the realm, but the *type* must not: every\n // consumer below reads `data.email`, `data.username` and the rest as\n // possibly-absent. Widening to the all-optional shape keeps one stable\n // type instead of a union of eight.\n return z.object(shape) as unknown as ReturnType<typeof registerFormSchema>;\n }, [settings]);\n\n const form = useForm({\n schema,\n // A locked address is the form's starting value, not a field the visitor\n // fills. It arrives before mount (the page resolves the token in its\n // loader), which is what lets `useForm` anchor it here.\n initialValues: props.lockedEmail\n ? ({ email: props.lockedEmail } as never)\n : undefined,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n try {\n const intent = await userCtrl.createRegistrationIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n firstName: data.firstName,\n lastName: data.lastName,\n username: data.username,\n // The locked address wins over whatever the field holds: it is\n // the one the token is bound to, and a disabled input is a\n // presentation fact rather than a guarantee.\n email: props.lockedEmail ?? data.email,\n phoneNumber: data.phoneNumber,\n password: data.password,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n preAuthToken: props.preAuthToken,\n },\n });\n const identifier =\n data.username ?? props.lockedEmail ?? data.email ?? data.phoneNumber;\n if (\n intent.expectEmailVerification ||\n intent.expectPhoneVerification ||\n intent.expectCaptcha\n ) {\n setState({\n phase: \"verification\",\n intent,\n credentials: identifier\n ? { identifier, password: data.password }\n : undefined,\n });\n return;\n }\n await userCtrl.createUserFromIntent({\n body: { intentId: intent.intentId },\n });\n if (identifier && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n // Turnstile tokens are single-use — force a fresh challenge so the\n // user can retry after a server-side failure.\n captchaRef.current?.reset();\n throw err;\n }\n },\n });\n\n const formState = useFormState(form, [\"error\", \"values\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const passwordValue = String(formState.values?.password ?? \"\");\n\n const firstFieldId =\n (settings.firstNameLastName !== \"none\" && form.input.firstName?.props.id) ||\n (settings.username !== \"none\" &&\n settings.username !== \"email\" &&\n form.input.username?.props.id) ||\n (settings.email !== \"none\" && form.input.email?.props.id) ||\n (settings.phoneNumber !== \"none\" && form.input.phoneNumber?.props.id) ||\n form.input.password.props.id;\n\n useEffect(() => {\n if (state.phase !== \"form\" || !firstFieldId) return;\n const el = document.getElementById(\n String(firstFieldId),\n ) as HTMLInputElement | null;\n el?.focus();\n }, [state.phase, firstFieldId]);\n\n const handleVerify = async () => {\n if (!state.intent) return;\n setSubmitting(true);\n setVerifyError(null);\n try {\n await userCtrl.createUserFromIntent({\n body: {\n intentId: state.intent.intentId,\n emailCode: state.intent.expectEmailVerification\n ? emailCode\n : undefined,\n phoneCode: state.intent.expectPhoneVerification\n ? phoneCode\n : undefined,\n },\n });\n if (state.credentials && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: state.credentials.identifier,\n password: state.credentials.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n setVerifyError(\n err instanceof Error\n ? err.message\n : tr(\"auth.register.verifyFailed\", {\n default: \"Verification failed\",\n }),\n );\n } finally {\n setSubmitting(false);\n }\n };\n\n // Query appended to the \"already have an account? sign in\" link: the realm,\n // plus the post-auth redirect (`?redirect=`) so signing in returns the user\n // to wherever registering would have sent them (it's dropped otherwise).\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const loginQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = loginQ ? `?${loginQ}` : \"\";\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n const showDivider = credentialsProvider && externalMethods.length > 0;\n const isVerifying = state.phase === \"verification\" && state.intent;\n const canSubmitVerify =\n !isVerifying ||\n ((!state.intent!.expectEmailVerification || emailCode.length === 6) &&\n (!state.intent!.expectPhoneVerification || phoneCode.length === 6));\n\n const contentRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n const el = contentRef.current;\n if (!el) return;\n setContentHeight(el.scrollHeight);\n const ro = new ResizeObserver(() => {\n setContentHeight(el.scrollHeight);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n return (\n <AuthRegisterCentered>\n {props.logo ?? (\n <AuthRegisterRealmLogo\n settings={settings}\n realmName={props.realmConfig.realmName}\n />\n )}\n <Card className=\"w-full\">\n <CardContent\n className=\"overflow-hidden p-0 transition-[height] duration-300 ease-out\"\n style={\n contentHeight !== undefined ? { height: contentHeight } : undefined\n }\n >\n <div ref={contentRef}>\n <div\n key={state.phase}\n className=\"animate-in fade-in flex flex-col gap-4 px-6 duration-300\"\n >\n {isVerifying ? (\n <>\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.register.verifyTitle\", {\n default: \"Verify your account\",\n })}\n </h2>\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.register.verifyHint\", {\n default:\n \"Please enter the verification code(s) sent to you.\",\n })}\n </p>\n {verifyError && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{verifyError}</AlertDescription>\n </Alert>\n )}\n {state.intent!.expectEmailVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"emailCode\">\n {tr(\"auth.register.emailCode\", {\n default: \"Email verification code\",\n })}\n </Label>\n <InputOTP\n id=\"emailCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={emailCode}\n onChange={setEmailCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n {state.intent!.expectPhoneVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"phoneCode\">\n {tr(\"auth.register.phoneCode\", {\n default: \"Phone verification code\",\n })}\n </Label>\n <InputOTP\n id=\"phoneCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={phoneCode}\n onChange={setPhoneCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n <Button\n onClick={handleVerify}\n loading={submitting}\n disabled={!canSubmitVerify}\n >\n {tr(\"auth.register.verifySubmit\", {\n default: \"Complete registration\",\n })}\n </Button>\n <Button\n variant=\"minimal\"\n onClick={() => setState({ phase: \"form\" })}\n >\n {tr(\"auth.register.verifyBack\", {\n default: \"Back to registration\",\n })}\n </Button>\n </>\n ) : (\n <AuthRegisterFormPhase\n allowed={allowed}\n form={form}\n formError={formError ?? queryError}\n loading={formState.loading}\n passwordValue={passwordValue}\n settings={settings}\n realmName={props.realmConfig.realmName}\n credentialsProvider={credentialsProvider}\n externalMethods={externalMethods}\n showDivider={showDivider}\n redirect={redirect}\n loginPath={props.loginPath}\n realmQuery={realmQuery}\n auth={auth}\n captchaSiteKey={captchaSiteKey}\n captchaToken={captchaToken}\n captchaRef={captchaRef}\n onCaptchaToken={setCaptchaToken}\n message={props.message}\n lockedEmail={props.lockedEmail}\n />\n )}\n </div>\n </div>\n </CardContent>\n </Card>\n {!isVerifying && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? \"/\"} />}\n >\n {tr(\"auth.register.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </AuthRegisterCentered>\n );\n};\n\ntype Phase = \"form\" | \"verification\";\n\ninterface State {\n phase: Phase;\n intent?: RegistrationIntentResponse;\n credentials?: { identifier: string; password: string };\n}\n\n/**\n * The reference shape of the registration form, with every configurable field\n * optional.\n *\n * `AuthRegister` builds its real schema from the realm settings, so which\n * fields are optional changes per realm. This exists purely to give that\n * schema one stable TypeScript type: the handler reads `data.email`,\n * `data.username` and `data.phoneNumber` as possibly-absent regardless of what\n * a given realm requires, which is the correct type for code that has to\n * compile against all of them.\n */\nconst registerFormSchema = () =>\n z.object({\n firstName: z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: z.text({ trim: true, maxLength: 100 }).optional(),\n username: z.text({ trim: true }).optional(),\n email: z.email().optional(),\n phoneNumber: z.e164().optional(),\n password: z.string(),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2GA,MAAa,gBAAgB,UAA6B;CACxD,MAAM,OAAO,QAAQ;CACrB,MAAM,WAAW,UAA0B;CAC3C,MAAM,SAAS,UAAU;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,aAAa,MAAM,YAAY,OAAO,MAAM,QAAQ;CAIrE,MAAM,aACJ,OAAO,OAAO,MAAM,UAAU,WAAW,OAAO,MAAM,QAAQ,KAAA;CAEhE,MAAM,CAAC,OAAO,YAAY,SAAgB,EAAE,OAAO,OAAO,CAAC;CAC3D,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,aAAa,kBAAkB,SAAwB,IAAI;CAClE,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAElD,MAAM,iBAAiB,MAAM,YAAY;CACzC,MAAM,CAAC,cAAc,mBAAmB,SAA6B;CACrE,MAAM,aAAa,OAAqC,IAAI;CAG5D,MAAM,kBAAkB,OAA2B,KAAA,CAAS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wBACX,CAAC;OACK,CAAA;OACR,oBAAC,QAAD;QACE,SAAQ;QACR,eAAe,SAAS,EAAE,OAAO,OAAO,CAAC;QAExC,UAAA,GAAG,4BAA4B,EAC9B,SAAS,uBACX,CAAC;OACK,CAAA;MACR,EAAA,CAAA,IAEF,oBAAC,uBAAD;OACW;OACH;OACN,WAAW,aAAa;OACxB,SAAS,UAAU;OACJ;OACL;OACV,WAAW,MAAM,YAAY;OACR;OACJ;OACJ;OACH;OACV,WAAW,MAAM;OACL;OACN;OACU;OACF;OACF;OACZ,gBAAgB;OAChB,SAAS,MAAM;OACf,aAAa,MAAM;MACpB,CAAA;KAEA,GA1HE,MAAM,KA0HR;IACF,CAAA;GACM,CAAA;EACT,CAAA;EACL,CAAC,eACA,oBAAC,QAAD;GACE,SAAQ;GACR,cAAc;GACd,QAAQ,oBAAC,KAAD,EAAG,MAAM,MAAM,cAAc,IAAM,CAAA;GAE1C,UAAA,GAAG,wBAAwB,EAAE,SAAS,SAAS,CAAC;EAC3C,CAAA;CAEU,EAAA,CAAA;AAE1B"}
@@ -34,12 +34,12 @@ import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupActio
34
34
  import { Toaster } from "./Toaster.js";
35
35
  import { Alert, AlertAction, AlertDescription, AlertTitle } from "./Alert.js";
36
36
  import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "./Card.js";
37
- import { BrandIcon } from "./BrandIcon.js";
38
37
  import { Spinner } from "./Spinner.js";
39
38
  import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "./Empty.js";
40
39
  import { Avatar, AvatarBadge, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarImage } from "./Avatar.js";
41
40
  import { Tabs, TabsContent, TabsList, TabsTrigger, tabsListVariants } from "./Tabs.js";
42
41
  import { PaneRail } from "./PaneRail.js";
42
+ import { BrandIcon } from "./BrandIcon.js";
43
43
  import { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants } from "./ButtonGroup.js";
44
44
  import { Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerOverlay, DrawerPortal, DrawerSwipeHandle, DrawerTitle, DrawerTrigger } from "./Drawer.js";
45
45
  import { highlightRanges } from "./highlightRanges.js";
@@ -31,7 +31,7 @@ const AutoForm = (props) => {
31
31
  useEffect(() => {
32
32
  if (!autoSaveEnabled) return;
33
33
  let handle;
34
- const off = alepha.events.on("form:change", (ev) => {
34
+ const off = alepha.events.on("form:changed", (ev) => {
35
35
  if (ev.id !== props.form.id) return;
36
36
  if (ev.initial) return;
37
37
  const top = ev.path.replace(/^\//, "").split("/")[0];
@@ -1 +1 @@
1
- {"version":3,"file":"AutoForm.js","names":[],"sources":["../../src/form/AutoForm.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { type ZObject, type ZType, z } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { type FormModel, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { type ReactNode, useEffect, useMemo } from \"react\";\n\nimport type { ButtonIntent, ButtonVariant } from \"../core/Button.tsx\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardFooter,\n CardTitle,\n} from \"../core/Card.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport { AutoFormBottomBar } from \"./AutoFormBottomBar.tsx\";\nimport { AutoFormGroupBlock } from \"./AutoFormGroupBlock.tsx\";\nimport { autoGroupSchema } from \"./autoFormGroups.ts\";\nimport type { ControlProps } from \"./Control.tsx\";\nimport { FormFieldAutoSaveProvider } from \"./FormFieldAutoSaveProvider.tsx\";\nimport { FormFieldLayoutProvider } from \"./FormFieldLayoutProvider.tsx\";\nimport { FormFieldRequiredMarkerProvider } from \"./FormFieldRequiredMarkerProvider.tsx\";\nimport { iconFor } from \"./iconHint.tsx\";\n\nexport interface AutoFormProps<T extends ZObject> {\n /**\n * Form model returned by `useForm()`. The schema drives every field.\n */\n form: FormModel<T>;\n\n /**\n * Header icon (lucide name).\n */\n icon?: string;\n /**\n * Header title.\n */\n title?: string;\n /**\n * Header description / subtitle.\n */\n description?: string;\n /**\n * Extra content rendered on the right of the header (e.g. a status badge).\n * In `card` mode it renders as the `CardAction`; otherwise it is pushed to\n * the right edge of the header box.\n */\n headerAction?: ReactNode;\n\n /**\n * Manual layout: list of groups, each with its own fields.\n * If neither `groups` nor `autoGroup` is set, every top-level schema\n * field is rendered in a single ungrouped column.\n */\n groups?: AutoFormGroup[];\n\n /**\n * Auto-group: scan the schema, primitive fields land in a \"General\"\n * group, each object/array-of-objects becomes its own group.\n */\n autoGroup?: boolean | { defaultTitle?: string; defaultIcon?: string };\n\n /**\n * Per-field control overrides keyed by field name (also works without groups).\n */\n fields?: Partial<\n Record<keyof T[\"shape\"] & string, Partial<Omit<ControlProps, \"input\">>>\n >;\n\n /**\n * Localize field labels the schema doesn't carry. When set, each field's\n * label is resolved from the app dictionary via\n * `tr(\\`${i18nPrefix}.${fieldName}\\`)` and its description via\n * `tr(\\`${i18nPrefix}.${fieldName}.desc\\`)`, falling back to the\n * schema-derived label/description when the key is absent. Lets a generic\n * AutoForm (e.g. the parameters admin, whose schemas rarely set `title`)\n * render translated labels without per-schema annotations. Explicit\n * `fields[name].label` overrides still win.\n */\n i18nPrefix?: string;\n\n /**\n * Submit button label.\n */\n submitLabel?: string;\n /**\n * Hide built-in submit button.\n */\n noSubmit?: boolean;\n /**\n * Disable submit when form is pristine (not dirty).\n */\n disabledIfPristine?: boolean;\n /**\n * Disable the entire form (cascades to controls).\n */\n disabled?: boolean;\n\n /**\n * Show the red `*` next to the label of every required field.\n *\n * Set `false` on a form where the marker is not news — one whose fields are\n * nearly all required, or where the one required field is self-evidently so\n * (a project's Name). A page of asterisks tells the reader nothing about\n * which field to be careful with, which is the only thing the marker is for.\n *\n * Purely visual. `aria-required` still comes from the schema, so a screen\n * reader announces the field as required either way — the marker itself is\n * `aria-hidden` and never carried that.\n *\n * @default true\n */\n requiredMarker?: boolean;\n\n /**\n * Cancel button — hidden when omitted.\n */\n onCancel?: () => void;\n /**\n * Skip the reset button in the bottom bar.\n */\n skipReset?: boolean;\n /**\n * Skip the entire bottom bar.\n */\n skipBottomBar?: boolean;\n\n /**\n * Extra action buttons in the bottom bar (left side).\n */\n actions?: AutoFormAction[];\n\n /**\n * Extra content rendered above the bottom bar.\n */\n footer?: ReactNode;\n\n /**\n * Extra classes applied to the form wrapper.\n */\n className?: string;\n\n /**\n * Override the column classes of each field group's grid. By default fields\n * lay out on a fixed 12-column grid and each field's span is derived from\n * width heuristics (`$control.width`, type, …).\n *\n * Pass responsive column classes — e.g.\n * `\"grid-cols-1 md:grid-cols-2 xl:grid-cols-3\"` — to get N equal columns per\n * breakpoint instead; when set, every field occupies a single cell and the\n * per-field width heuristics are ignored.\n */\n gridClassName?: string;\n\n /**\n * Wrap the form in a `<Card>`:\n * - the header (icon + title/description) renders as the `CardHeader`,\n * - the field groups render as the `CardContent`,\n * - the action bar (cancel / reset / actions / submit) renders as the\n * `CardFooter`.\n *\n * When omitted, the form uses its default chrome (a muted header box and a\n * standalone bottom bar). The footer is hidden in `autoSave` mode just like\n * the default bottom bar.\n *\n * Pass a string to override the `<Card>` className (e.g. `\"rounded-none\"` to\n * make the card sit flush against neighbouring panes).\n */\n card?: boolean | string;\n\n /**\n * Fill the available height: the card stretches to `100%` of its container\n * and the body (field groups) scrolls while the header and footer stay\n * pinned. Only meaningful in `card` mode.\n */\n fill?: boolean;\n\n /**\n * Visual layout for every nested Control.\n * - `\"stack\"` (default): label on top, control below — the classic form look.\n * - `\"row\"`: settings-style — each control sits on its own line with the\n * label/description on the left and the control on the right. Each\n * group renders as a bordered card with horizontal dividers.\n *\n * `\"row\"` **is** the settings-card shape, not an approximation of it: the\n * rows render the same markup as {@link SettingsRow}, the card the same as\n * {@link SettingsSection}, the heading through the same\n * {@link SettingsHeading}, and the action bar as the card's own last\n * divided row. So a settings card whose rows are form fields should be an\n * `AutoForm`, and reach for `SettingsSection` only for the rows that are\n * *not* fields — an avatar picker, a read-only value, a lone button.\n */\n layout?: \"stack\" | \"row\";\n\n /**\n * Auto-commit edits instead of showing a Save button.\n *\n * When enabled, every field change schedules a debounced `form.submit()`\n * and the bottom bar is hidden by default. Pass an options object to\n * customize the debounce delay (default 600ms).\n *\n * The `handler` you pass to `useForm` is the auto-commit target — it\n * runs once per quiescent edit, and any thrown error stops the loop\n * until the user edits again.\n */\n autoSave?: boolean | { delay?: number };\n}\n\n/**\n * Schema-driven form with optional grouping, header chrome, and bottom\n * bar. Every input field is resolved through `<Control>`, so schemas\n * carrying `$control` metadata configure themselves.\n */\nexport const AutoForm = <T extends ZObject>(props: AutoFormProps<T>) => {\n const { tr } = useI18n();\n const { dirty, loading } = useFormState(props.form, [\"dirty\", \"loading\"]);\n const inputs = props.form.input as Record<string, never>;\n\n // `z.object({})` rather than a hand-made `{ properties: {} }`: the latter\n // only ever worked because a prototype alias made `.properties` readable on\n // a schema, so a fake object with that key passed for one.\n const schema = (props.form.options.schema as ZObject) ?? z.object({});\n\n // ── Auto-save ─────────────────────────────────────────────────────\n // Text fields (string) are intentionally excluded: typing should not commit\n // on every keystroke. They commit via Enter (native submit) or the inline\n // tick button. Booleans / selects / uploads / etc. auto-commit on change.\n const autoSave = props.autoSave;\n const autoSaveDelay =\n typeof autoSave === \"object\" ? (autoSave?.delay ?? 600) : 600;\n const autoSaveEnabled = !!autoSave;\n const alepha = useAlepha();\n useEffect(() => {\n if (!autoSaveEnabled) return;\n let handle: ReturnType<typeof setTimeout> | undefined;\n const off = alepha.events.on(\"form:change\", (ev) => {\n if (ev.id !== props.form.id) return;\n if (ev.initial) return;\n // FormModel paths look like \"/title\" or \"/contacts/0/email\". The\n // top-level key is the first segment after the leading slash.\n const top = ev.path.replace(/^\\//, \"\").split(\"/\")[0];\n const fieldSchema = z.schema.shape(schema)[top];\n const fieldConfig = resolveControlConfig(\n top,\n props.fields as Record<string, unknown> | undefined,\n props.groups,\n );\n // Text fields (incl. optional/nullable wrappers) should NOT auto-commit\n // on keystroke; they commit via Enter or the inline tick button.\n // Uploads commit a uuid string when the upload finishes, and selects /\n // comboboxes / segmented controls commit a discrete value on change —\n // all of those MUST auto-save even though the field schema is a string.\n const rendersAsSelect =\n !!fieldConfig.select ||\n !!fieldConfig.combobox ||\n !!fieldConfig.segmented ||\n fieldConfig.items != null ||\n isEnumSchema(fieldSchema);\n if (\n !fieldConfig.upload &&\n !rendersAsSelect &&\n isStringSchema(fieldSchema)\n )\n return;\n if (handle) clearTimeout(handle);\n handle = setTimeout(() => props.form.submit(), autoSaveDelay);\n });\n return () => {\n off();\n if (handle) clearTimeout(handle);\n };\n }, [\n alepha,\n autoSaveEnabled,\n autoSaveDelay,\n props.form,\n props.fields,\n props.groups,\n schema,\n ]);\n const skipBottomBar = props.skipBottomBar ?? autoSaveEnabled;\n\n const resolvedGroups: AutoFormGroup[] = useMemo(() => {\n if (props.groups) return props.groups.filter((g) => g.can?.() !== false);\n if (props.autoGroup) {\n const opts = typeof props.autoGroup === \"object\" ? props.autoGroup : {};\n return autoGroupSchema(schema, { tr, ...opts });\n }\n return [\n {\n fields: Object.keys(z.schema.shape(schema)),\n },\n ];\n }, [props.groups, props.autoGroup, schema]);\n\n const HeaderIcon = props.icon ? iconFor(props.icon) : undefined;\n const hasHeader = !!(\n props.title ||\n props.description ||\n HeaderIcon ||\n props.headerAction\n );\n\n const layout = props.layout ?? \"stack\";\n\n const bottomBarProps = {\n form: props.form,\n dirty,\n loading,\n disabled: props.disabled,\n disabledIfPristine: props.disabledIfPristine,\n submitLabel: props.submitLabel,\n noSubmit: props.noSubmit,\n onCancel: props.onCancel,\n skipReset: props.skipReset,\n actions: props.actions,\n };\n\n // In row layout the action bar is the card's own last row, not a second\n // bordered box floating under it — see the `layout` prop's note. `card`\n // mode already owns its footer (`CardFooter`), and a form that resolved to\n // no groups at all has nothing to put the bar inside, so both fall back to\n // the standalone bar below.\n const inCardBottomBar =\n layout === \"row\" &&\n !props.card &&\n !skipBottomBar &&\n resolvedGroups.length ? (\n <AutoFormBottomBar {...bottomBarProps} bare />\n ) : undefined;\n\n const fieldGroups = (\n <FormFieldLayoutProvider value={layout}>\n <FormFieldRequiredMarkerProvider value={props.requiredMarker ?? true}>\n <FormFieldAutoSaveProvider value={autoSaveEnabled}>\n {resolvedGroups.map((group, gi) => (\n <AutoFormGroupBlock\n key={gi}\n group={group}\n inputs={inputs}\n disabled={props.disabled}\n fields={props.fields}\n i18nPrefix={props.i18nPrefix}\n multiGroup={resolvedGroups.length > 1}\n layout={layout}\n gridClassName={props.gridClassName}\n bottomBar={\n gi === resolvedGroups.length - 1 ? inCardBottomBar : undefined\n }\n />\n ))}\n </FormFieldAutoSaveProvider>\n </FormFieldRequiredMarkerProvider>\n </FormFieldLayoutProvider>\n );\n\n if (props.card) {\n const cardClassName =\n typeof props.card === \"string\" ? props.card : undefined;\n return (\n <form\n {...props.form.props}\n className={cn(\n props.fill && \"flex h-full min-h-0 flex-col\",\n props.className,\n )}\n >\n <Card\n className={cn(\n props.fill && \"min-h-0 flex-1\",\n // Header owns its bottom padding (pb-3); trim the card's top\n // padding to match so header top/bottom are an even 12px.\n hasHeader && \"pt-3\",\n cardClassName,\n )}\n >\n {hasHeader && (\n // Explicit flex header (not shadcn CardHeader): CardHeader's grid\n // adds a phantom second row + row-gap below the title whenever a\n // CardDescription is nested, making the bottom padding larger than\n // the top. A plain flex row keeps top/bottom padding symmetric.\n <div\n data-slot=\"card-header\"\n className=\"flex items-start justify-between gap-3 border-b px-4 pb-3\"\n >\n <div className=\"flex items-center gap-3\">\n {HeaderIcon && (\n <div className=\"bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full\">\n <HeaderIcon className=\"size-5\" />\n </div>\n )}\n <div className=\"flex flex-col gap-0\">\n {props.title && <CardTitle>{props.title}</CardTitle>}\n {props.description && (\n <CardDescription>{props.description}</CardDescription>\n )}\n </div>\n </div>\n {props.headerAction && (\n <div className=\"shrink-0\">{props.headerAction}</div>\n )}\n </div>\n )}\n <CardContent\n className={cn(\n \"flex flex-col gap-4\",\n // `relative` alongside the scroller, not decoration: Base UI\n // gives every named control a 1×1 hidden `<input>` positioned\n // `absolute` with no offsets, and a scroller that is not itself\n // a containing block neither clips those inputs nor scrolls\n // them with the field they belong to — so a native validation\n // bubble would point at where the field used to be. #1849.\n props.fill && \"relative min-h-0 flex-1 overflow-y-auto\",\n )}\n >\n {fieldGroups}\n {props.footer}\n </CardContent>\n {!skipBottomBar && (\n <CardFooter>\n <AutoFormBottomBar {...bottomBarProps} bare />\n </CardFooter>\n )}\n </Card>\n </form>\n );\n }\n\n return (\n <form {...props.form.props} className={props.className}>\n <div className=\"flex flex-col gap-4\">\n {hasHeader && (\n <div className=\"bg-muted/40 flex items-start gap-3 rounded-md border p-4\">\n {HeaderIcon && (\n <div className=\"bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full\">\n <HeaderIcon className=\"size-5\" />\n </div>\n )}\n <div className=\"flex flex-col gap-1\">\n {props.title && (\n <h2 className=\"text-base font-semibold\">{props.title}</h2>\n )}\n {props.description && (\n <p className=\"text-muted-foreground text-sm\">\n {props.description}\n </p>\n )}\n </div>\n {props.headerAction && (\n <div className=\"ml-auto\">{props.headerAction}</div>\n )}\n </div>\n )}\n\n {fieldGroups}\n\n {props.footer}\n\n {!skipBottomBar && !inCardBottomBar && (\n <AutoFormBottomBar {...bottomBarProps} />\n )}\n </div>\n </form>\n );\n};\n\nexport interface AutoFormGroup {\n /**\n * Group title shown in the header.\n */\n title?: string;\n /**\n * One line under the title, for context the fields should not each repeat.\n *\n * Only rendered in `layout=\"row\"`, where the heading sits above the card\n * and there is room for it — the boxed group bar the grid layout uses is a\n * single line by construction.\n */\n description?: string;\n /**\n * Icon name (lucide) for the group header.\n */\n icon?: string;\n /**\n * Visibility predicate. Group is omitted when this returns false.\n */\n can?: () => boolean;\n /**\n * Field names from the form schema. Each renders as a `<Control>`.\n * Use the object form `{ name, ...controlProps }` for per-field overrides\n * (width, icon, custom, etc.).\n */\n fields: Array<\n string | (Partial<Omit<ControlProps, \"input\">> & { name: string })\n >;\n}\n\nexport interface AutoFormAction {\n label: string;\n icon?: string;\n variant?: ButtonVariant;\n intent?: ButtonIntent;\n onClick: () => void | Promise<void>;\n disabled?: boolean;\n}\n\n/**\n * Detect a `z.string()` schema (incl. optional/nullable wrappers) so the\n * auto-save effect can skip keystroke commits on text fields.\n */\nfunction isStringSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n // Zod, not JSON Schema: `z.string().optional()` has no `type: \"string\"`,\n // so the optional text fields of a form used to auto-save every keystroke.\n const inner = z.schema.unwrap(schema as ZType);\n if (z.schema.isString(inner)) return true;\n if (z.schema.isUnion(inner)) {\n return z.schema.options(inner).some(isStringSchema);\n }\n return false;\n}\n\n/**\n * Detect an enum schema (incl. optional/nullable wrappers). Enum fields\n * render as a `<Select>`, so they must auto-commit on change like any\n * other select — never get lumped in with free-text string fields.\n */\nfunction isEnumSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n const inner = z.schema.unwrap(schema as ZType);\n if (z.schema.isEnum(inner)) return true;\n if (z.schema.isUnion(inner)) {\n return z.schema.options(inner).some(isEnumSchema);\n }\n return false;\n}\n\n/**\n * Resolve the effective `<Control>` config for a field, merging the\n * `fields` map with any per-field override carried on a `groups` entry —\n * the same precedence `AutoFormGroupBlock` applies when rendering.\n */\nfunction resolveControlConfig(\n name: string,\n fields: Record<string, unknown> | undefined,\n groups: AutoFormGroup[] | undefined,\n): Record<string, unknown> {\n const fromMap = (fields?.[name] as Record<string, unknown>) ?? {};\n let fromGroup: Record<string, unknown> = {};\n for (const group of groups ?? []) {\n for (const field of group.fields) {\n if (typeof field === \"object\" && field.name === name) {\n fromGroup = field as Record<string, unknown>;\n }\n }\n }\n return { ...fromMap, ...fromGroup };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyNA,MA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ACpC"}
1
+ {"version":3,"file":"AutoForm.js","names":[],"sources":["../../src/form/AutoForm.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { type ZObject, type ZType, z } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { type FormModel, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { type ReactNode, useEffect, useMemo } from \"react\";\n\nimport type { ButtonIntent, ButtonVariant } from \"../core/Button.tsx\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardFooter,\n CardTitle,\n} from \"../core/Card.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport { AutoFormBottomBar } from \"./AutoFormBottomBar.tsx\";\nimport { AutoFormGroupBlock } from \"./AutoFormGroupBlock.tsx\";\nimport { autoGroupSchema } from \"./autoFormGroups.ts\";\nimport type { ControlProps } from \"./Control.tsx\";\nimport { FormFieldAutoSaveProvider } from \"./FormFieldAutoSaveProvider.tsx\";\nimport { FormFieldLayoutProvider } from \"./FormFieldLayoutProvider.tsx\";\nimport { FormFieldRequiredMarkerProvider } from \"./FormFieldRequiredMarkerProvider.tsx\";\nimport { iconFor } from \"./iconHint.tsx\";\n\nexport interface AutoFormProps<T extends ZObject> {\n /**\n * Form model returned by `useForm()`. The schema drives every field.\n */\n form: FormModel<T>;\n\n /**\n * Header icon (lucide name).\n */\n icon?: string;\n /**\n * Header title.\n */\n title?: string;\n /**\n * Header description / subtitle.\n */\n description?: string;\n /**\n * Extra content rendered on the right of the header (e.g. a status badge).\n * In `card` mode it renders as the `CardAction`; otherwise it is pushed to\n * the right edge of the header box.\n */\n headerAction?: ReactNode;\n\n /**\n * Manual layout: list of groups, each with its own fields.\n * If neither `groups` nor `autoGroup` is set, every top-level schema\n * field is rendered in a single ungrouped column.\n */\n groups?: AutoFormGroup[];\n\n /**\n * Auto-group: scan the schema, primitive fields land in a \"General\"\n * group, each object/array-of-objects becomes its own group.\n */\n autoGroup?: boolean | { defaultTitle?: string; defaultIcon?: string };\n\n /**\n * Per-field control overrides keyed by field name (also works without groups).\n */\n fields?: Partial<\n Record<keyof T[\"shape\"] & string, Partial<Omit<ControlProps, \"input\">>>\n >;\n\n /**\n * Localize field labels the schema doesn't carry. When set, each field's\n * label is resolved from the app dictionary via\n * `tr(\\`${i18nPrefix}.${fieldName}\\`)` and its description via\n * `tr(\\`${i18nPrefix}.${fieldName}.desc\\`)`, falling back to the\n * schema-derived label/description when the key is absent. Lets a generic\n * AutoForm (e.g. the parameters admin, whose schemas rarely set `title`)\n * render translated labels without per-schema annotations. Explicit\n * `fields[name].label` overrides still win.\n */\n i18nPrefix?: string;\n\n /**\n * Submit button label.\n */\n submitLabel?: string;\n /**\n * Hide built-in submit button.\n */\n noSubmit?: boolean;\n /**\n * Disable submit when form is pristine (not dirty).\n */\n disabledIfPristine?: boolean;\n /**\n * Disable the entire form (cascades to controls).\n */\n disabled?: boolean;\n\n /**\n * Show the red `*` next to the label of every required field.\n *\n * Set `false` on a form where the marker is not news — one whose fields are\n * nearly all required, or where the one required field is self-evidently so\n * (a project's Name). A page of asterisks tells the reader nothing about\n * which field to be careful with, which is the only thing the marker is for.\n *\n * Purely visual. `aria-required` still comes from the schema, so a screen\n * reader announces the field as required either way — the marker itself is\n * `aria-hidden` and never carried that.\n *\n * @default true\n */\n requiredMarker?: boolean;\n\n /**\n * Cancel button — hidden when omitted.\n */\n onCancel?: () => void;\n /**\n * Skip the reset button in the bottom bar.\n */\n skipReset?: boolean;\n /**\n * Skip the entire bottom bar.\n */\n skipBottomBar?: boolean;\n\n /**\n * Extra action buttons in the bottom bar (left side).\n */\n actions?: AutoFormAction[];\n\n /**\n * Extra content rendered above the bottom bar.\n */\n footer?: ReactNode;\n\n /**\n * Extra classes applied to the form wrapper.\n */\n className?: string;\n\n /**\n * Override the column classes of each field group's grid. By default fields\n * lay out on a fixed 12-column grid and each field's span is derived from\n * width heuristics (`$control.width`, type, …).\n *\n * Pass responsive column classes — e.g.\n * `\"grid-cols-1 md:grid-cols-2 xl:grid-cols-3\"` — to get N equal columns per\n * breakpoint instead; when set, every field occupies a single cell and the\n * per-field width heuristics are ignored.\n */\n gridClassName?: string;\n\n /**\n * Wrap the form in a `<Card>`:\n * - the header (icon + title/description) renders as the `CardHeader`,\n * - the field groups render as the `CardContent`,\n * - the action bar (cancel / reset / actions / submit) renders as the\n * `CardFooter`.\n *\n * When omitted, the form uses its default chrome (a muted header box and a\n * standalone bottom bar). The footer is hidden in `autoSave` mode just like\n * the default bottom bar.\n *\n * Pass a string to override the `<Card>` className (e.g. `\"rounded-none\"` to\n * make the card sit flush against neighbouring panes).\n */\n card?: boolean | string;\n\n /**\n * Fill the available height: the card stretches to `100%` of its container\n * and the body (field groups) scrolls while the header and footer stay\n * pinned. Only meaningful in `card` mode.\n */\n fill?: boolean;\n\n /**\n * Visual layout for every nested Control.\n * - `\"stack\"` (default): label on top, control below — the classic form look.\n * - `\"row\"`: settings-style — each control sits on its own line with the\n * label/description on the left and the control on the right. Each\n * group renders as a bordered card with horizontal dividers.\n *\n * `\"row\"` **is** the settings-card shape, not an approximation of it: the\n * rows render the same markup as {@link SettingsRow}, the card the same as\n * {@link SettingsSection}, the heading through the same\n * {@link SettingsHeading}, and the action bar as the card's own last\n * divided row. So a settings card whose rows are form fields should be an\n * `AutoForm`, and reach for `SettingsSection` only for the rows that are\n * *not* fields — an avatar picker, a read-only value, a lone button.\n */\n layout?: \"stack\" | \"row\";\n\n /**\n * Auto-commit edits instead of showing a Save button.\n *\n * When enabled, every field change schedules a debounced `form.submit()`\n * and the bottom bar is hidden by default. Pass an options object to\n * customize the debounce delay (default 600ms).\n *\n * The `handler` you pass to `useForm` is the auto-commit target — it\n * runs once per quiescent edit, and any thrown error stops the loop\n * until the user edits again.\n */\n autoSave?: boolean | { delay?: number };\n}\n\n/**\n * Schema-driven form with optional grouping, header chrome, and bottom\n * bar. Every input field is resolved through `<Control>`, so schemas\n * carrying `$control` metadata configure themselves.\n */\nexport const AutoForm = <T extends ZObject>(props: AutoFormProps<T>) => {\n const { tr } = useI18n();\n const { dirty, loading } = useFormState(props.form, [\"dirty\", \"loading\"]);\n const inputs = props.form.input as Record<string, never>;\n\n // `z.object({})` rather than a hand-made `{ properties: {} }`: the latter\n // only ever worked because a prototype alias made `.properties` readable on\n // a schema, so a fake object with that key passed for one.\n const schema = (props.form.options.schema as ZObject) ?? z.object({});\n\n // ── Auto-save ─────────────────────────────────────────────────────\n // Text fields (string) are intentionally excluded: typing should not commit\n // on every keystroke. They commit via Enter (native submit) or the inline\n // tick button. Booleans / selects / uploads / etc. auto-commit on change.\n const autoSave = props.autoSave;\n const autoSaveDelay =\n typeof autoSave === \"object\" ? (autoSave?.delay ?? 600) : 600;\n const autoSaveEnabled = !!autoSave;\n const alepha = useAlepha();\n useEffect(() => {\n if (!autoSaveEnabled) return;\n let handle: ReturnType<typeof setTimeout> | undefined;\n const off = alepha.events.on(\"form:changed\", (ev) => {\n if (ev.id !== props.form.id) return;\n if (ev.initial) return;\n // FormModel paths look like \"/title\" or \"/contacts/0/email\". The\n // top-level key is the first segment after the leading slash.\n const top = ev.path.replace(/^\\//, \"\").split(\"/\")[0];\n const fieldSchema = z.schema.shape(schema)[top];\n const fieldConfig = resolveControlConfig(\n top,\n props.fields as Record<string, unknown> | undefined,\n props.groups,\n );\n // Text fields (incl. optional/nullable wrappers) should NOT auto-commit\n // on keystroke; they commit via Enter or the inline tick button.\n // Uploads commit a uuid string when the upload finishes, and selects /\n // comboboxes / segmented controls commit a discrete value on change —\n // all of those MUST auto-save even though the field schema is a string.\n const rendersAsSelect =\n !!fieldConfig.select ||\n !!fieldConfig.combobox ||\n !!fieldConfig.segmented ||\n fieldConfig.items != null ||\n isEnumSchema(fieldSchema);\n if (\n !fieldConfig.upload &&\n !rendersAsSelect &&\n isStringSchema(fieldSchema)\n )\n return;\n if (handle) clearTimeout(handle);\n handle = setTimeout(() => props.form.submit(), autoSaveDelay);\n });\n return () => {\n off();\n if (handle) clearTimeout(handle);\n };\n }, [\n alepha,\n autoSaveEnabled,\n autoSaveDelay,\n props.form,\n props.fields,\n props.groups,\n schema,\n ]);\n const skipBottomBar = props.skipBottomBar ?? autoSaveEnabled;\n\n const resolvedGroups: AutoFormGroup[] = useMemo(() => {\n if (props.groups) return props.groups.filter((g) => g.can?.() !== false);\n if (props.autoGroup) {\n const opts = typeof props.autoGroup === \"object\" ? props.autoGroup : {};\n return autoGroupSchema(schema, { tr, ...opts });\n }\n return [\n {\n fields: Object.keys(z.schema.shape(schema)),\n },\n ];\n }, [props.groups, props.autoGroup, schema]);\n\n const HeaderIcon = props.icon ? iconFor(props.icon) : undefined;\n const hasHeader = !!(\n props.title ||\n props.description ||\n HeaderIcon ||\n props.headerAction\n );\n\n const layout = props.layout ?? \"stack\";\n\n const bottomBarProps = {\n form: props.form,\n dirty,\n loading,\n disabled: props.disabled,\n disabledIfPristine: props.disabledIfPristine,\n submitLabel: props.submitLabel,\n noSubmit: props.noSubmit,\n onCancel: props.onCancel,\n skipReset: props.skipReset,\n actions: props.actions,\n };\n\n // In row layout the action bar is the card's own last row, not a second\n // bordered box floating under it — see the `layout` prop's note. `card`\n // mode already owns its footer (`CardFooter`), and a form that resolved to\n // no groups at all has nothing to put the bar inside, so both fall back to\n // the standalone bar below.\n const inCardBottomBar =\n layout === \"row\" &&\n !props.card &&\n !skipBottomBar &&\n resolvedGroups.length ? (\n <AutoFormBottomBar {...bottomBarProps} bare />\n ) : undefined;\n\n const fieldGroups = (\n <FormFieldLayoutProvider value={layout}>\n <FormFieldRequiredMarkerProvider value={props.requiredMarker ?? true}>\n <FormFieldAutoSaveProvider value={autoSaveEnabled}>\n {resolvedGroups.map((group, gi) => (\n <AutoFormGroupBlock\n key={gi}\n group={group}\n inputs={inputs}\n disabled={props.disabled}\n fields={props.fields}\n i18nPrefix={props.i18nPrefix}\n multiGroup={resolvedGroups.length > 1}\n layout={layout}\n gridClassName={props.gridClassName}\n bottomBar={\n gi === resolvedGroups.length - 1 ? inCardBottomBar : undefined\n }\n />\n ))}\n </FormFieldAutoSaveProvider>\n </FormFieldRequiredMarkerProvider>\n </FormFieldLayoutProvider>\n );\n\n if (props.card) {\n const cardClassName =\n typeof props.card === \"string\" ? props.card : undefined;\n return (\n <form\n {...props.form.props}\n className={cn(\n props.fill && \"flex h-full min-h-0 flex-col\",\n props.className,\n )}\n >\n <Card\n className={cn(\n props.fill && \"min-h-0 flex-1\",\n // Header owns its bottom padding (pb-3); trim the card's top\n // padding to match so header top/bottom are an even 12px.\n hasHeader && \"pt-3\",\n cardClassName,\n )}\n >\n {hasHeader && (\n // Explicit flex header (not shadcn CardHeader): CardHeader's grid\n // adds a phantom second row + row-gap below the title whenever a\n // CardDescription is nested, making the bottom padding larger than\n // the top. A plain flex row keeps top/bottom padding symmetric.\n <div\n data-slot=\"card-header\"\n className=\"flex items-start justify-between gap-3 border-b px-4 pb-3\"\n >\n <div className=\"flex items-center gap-3\">\n {HeaderIcon && (\n <div className=\"bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full\">\n <HeaderIcon className=\"size-5\" />\n </div>\n )}\n <div className=\"flex flex-col gap-0\">\n {props.title && <CardTitle>{props.title}</CardTitle>}\n {props.description && (\n <CardDescription>{props.description}</CardDescription>\n )}\n </div>\n </div>\n {props.headerAction && (\n <div className=\"shrink-0\">{props.headerAction}</div>\n )}\n </div>\n )}\n <CardContent\n className={cn(\n \"flex flex-col gap-4\",\n // `relative` alongside the scroller, not decoration: Base UI\n // gives every named control a 1×1 hidden `<input>` positioned\n // `absolute` with no offsets, and a scroller that is not itself\n // a containing block neither clips those inputs nor scrolls\n // them with the field they belong to — so a native validation\n // bubble would point at where the field used to be. #1849.\n props.fill && \"relative min-h-0 flex-1 overflow-y-auto\",\n )}\n >\n {fieldGroups}\n {props.footer}\n </CardContent>\n {!skipBottomBar && (\n <CardFooter>\n <AutoFormBottomBar {...bottomBarProps} bare />\n </CardFooter>\n )}\n </Card>\n </form>\n );\n }\n\n return (\n <form {...props.form.props} className={props.className}>\n <div className=\"flex flex-col gap-4\">\n {hasHeader && (\n <div className=\"bg-muted/40 flex items-start gap-3 rounded-md border p-4\">\n {HeaderIcon && (\n <div className=\"bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-full\">\n <HeaderIcon className=\"size-5\" />\n </div>\n )}\n <div className=\"flex flex-col gap-1\">\n {props.title && (\n <h2 className=\"text-base font-semibold\">{props.title}</h2>\n )}\n {props.description && (\n <p className=\"text-muted-foreground text-sm\">\n {props.description}\n </p>\n )}\n </div>\n {props.headerAction && (\n <div className=\"ml-auto\">{props.headerAction}</div>\n )}\n </div>\n )}\n\n {fieldGroups}\n\n {props.footer}\n\n {!skipBottomBar && !inCardBottomBar && (\n <AutoFormBottomBar {...bottomBarProps} />\n )}\n </div>\n </form>\n );\n};\n\nexport interface AutoFormGroup {\n /**\n * Group title shown in the header.\n */\n title?: string;\n /**\n * One line under the title, for context the fields should not each repeat.\n *\n * Only rendered in `layout=\"row\"`, where the heading sits above the card\n * and there is room for it — the boxed group bar the grid layout uses is a\n * single line by construction.\n */\n description?: string;\n /**\n * Icon name (lucide) for the group header.\n */\n icon?: string;\n /**\n * Visibility predicate. Group is omitted when this returns false.\n */\n can?: () => boolean;\n /**\n * Field names from the form schema. Each renders as a `<Control>`.\n * Use the object form `{ name, ...controlProps }` for per-field overrides\n * (width, icon, custom, etc.).\n */\n fields: Array<\n string | (Partial<Omit<ControlProps, \"input\">> & { name: string })\n >;\n}\n\nexport interface AutoFormAction {\n label: string;\n icon?: string;\n variant?: ButtonVariant;\n intent?: ButtonIntent;\n onClick: () => void | Promise<void>;\n disabled?: boolean;\n}\n\n/**\n * Detect a `z.string()` schema (incl. optional/nullable wrappers) so the\n * auto-save effect can skip keystroke commits on text fields.\n */\nfunction isStringSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n // Zod, not JSON Schema: `z.string().optional()` has no `type: \"string\"`,\n // so the optional text fields of a form used to auto-save every keystroke.\n const inner = z.schema.unwrap(schema as ZType);\n if (z.schema.isString(inner)) return true;\n if (z.schema.isUnion(inner)) {\n return z.schema.options(inner).some(isStringSchema);\n }\n return false;\n}\n\n/**\n * Detect an enum schema (incl. optional/nullable wrappers). Enum fields\n * render as a `<Select>`, so they must auto-commit on change like any\n * other select — never get lumped in with free-text string fields.\n */\nfunction isEnumSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n const inner = z.schema.unwrap(schema as ZType);\n if (z.schema.isEnum(inner)) return true;\n if (z.schema.isUnion(inner)) {\n return z.schema.options(inner).some(isEnumSchema);\n }\n return false;\n}\n\n/**\n * Resolve the effective `<Control>` config for a field, merging the\n * `fields` map with any per-field override carried on a `groups` entry —\n * the same precedence `AutoFormGroupBlock` applies when rendering.\n */\nfunction resolveControlConfig(\n name: string,\n fields: Record<string, unknown> | undefined,\n groups: AutoFormGroup[] | undefined,\n): Record<string, unknown> {\n const fromMap = (fields?.[name] as Record<string, unknown>) ?? {};\n let fromGroup: Record<string, unknown> = {};\n for (const group of groups ?? []) {\n for (const field of group.fields) {\n if (typeof field === \"object\" && field.name === name) {\n fromGroup = field as Record<string, unknown>;\n }\n }\n }\n return { ...fromMap, ...fromGroup };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyNA,MAAa,YAA+B,UAA4B;CACtE,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,EAAE,OAAO,YAAY,aAAa,MAAM,MAAM,CAAC,SAAS,SAAS,CAAC;CACxE,MAAM,SAAS,MAAM,KAAK;CAK1B,MAAM,SAAU,MAAM,KAAK,QAAQ,UAAsB,EAAE,OAAO,CAAC,CAAC;CAMpE,MAAM,WAAW,MAAM;CACvB,MAAM,gBACJ,OAAO,aAAa,WAAY,UAAU,SAAS,MAAO;CAC5D,MAAM,kBAAkB,CAAC,CAAC;CAC1B,MAAM,SAAS,UAAU;CACzB,gBAAgB;EACd,IAAI,CAAC,iBAAiB;EACtB,IAAI;EACJ,MAAM,MAAM,OAAO,OA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AAO,WAAW,UAAU,OAAO;CAGlD,MAAM,QAAQ,EAAE,OAAO,OAAO,MAAe;CAC7C,IAAI,EAAE,OAAO,SAAS,KAAK,GAAG,OAAO;CACrC,IAAI,EAAE,OAAO,QAAQ,KAAK,GACxB,OAAO,EAAE,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,cAAc;CAEpD,OAAO;AACT;;;;;;AAOA,SAAS,aAAa,QAA0B;CAC9C,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,MAAM,QAAQ,EAAE,OAAO,OAAO,MAAe;CAC7C,IAAI,EAAE,OAAO,OAAO,KAAK,GAAG,OAAO;CACnC,IAAI,EAAE,OAAO,QAAQ,KAAK,GACxB,OAAO,EAAE,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,YAAY;CAElD,OAAO;AACT;;;;;;AAOA,SAAS,qBACP,MACA,QACA,QACyB;CACzB,MAAM,UAAW,SAAS,SAAqC,CAAC;CAChE,IAAI,YAAqC,CAAC;CAC1C,KAAK,MAAM,SAAS,UAAU,CAAC,GAC7B,KAAK,MAAM,SAAS,MAAM,QACxB,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,MAC9C,YAAY;CAIlB,OAAO;EAAE,GAAG;EAAS,GAAG;CAAU;AACpC"}
@@ -345,7 +345,7 @@ const useDynamicControlRefresh = (input) => {
345
345
  useEffect(() => {
346
346
  if (!isDynamic || !input?.form) return;
347
347
  const formId = input.form.id;
348
- return alepha.events.on("form:change", (e) => {
348
+ return alepha.events.on("form:changed", (e) => {
349
349
  if (e.id === formId && e.path !== input.path) bump((n) => n + 1);
350
350
  });
351
351
  }, [
@@ -1 +1 @@
1
- {"version":3,"file":"Control.js","names":[],"sources":["../../src/form/Control.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { z } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { resolveSchemaControl, type SchemaControl } from \"alepha/react/ui\";\nimport { Check, X } from \"lucide-react\";\nimport {\n type ComponentType,\n type HTMLAttributes,\n type ReactNode,\n useEffect,\n useState,\n} from \"react\";\n\nimport { Input } from \"../core/Input.tsx\";\nimport { Switch } from \"../core/Switch.tsx\";\nimport { Textarea } from \"../core/Textarea.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport { ControlArray, type ControlArrayProps } from \"./ControlArray.tsx\";\nimport { ControlDate, type ControlDateProps } from \"./ControlDate.tsx\";\nimport { ControlDateRange } from \"./ControlDateRange.tsx\";\nimport { ControlNumber } from \"./ControlNumber.tsx\";\nimport { ControlObject } from \"./ControlObject.tsx\";\nimport { ControlPassword } from \"./ControlPassword.tsx\";\nimport {\n ControlSelect,\n type ControlSelectSize,\n type SelectOption,\n} from \"./ControlSelect.tsx\";\nimport { ControlUpload, type ControlUploadProps } from \"./ControlUpload.tsx\";\nimport { FormField, formFieldAriaProps } from \"./FormField.tsx\";\nimport { useFormFieldAutoSave } from \"./FormFieldAutoSaveProvider.tsx\";\nimport { useFormFieldLayout } from \"./FormFieldLayoutProvider.tsx\";\nimport { type IconComponent, iconFor } from \"./iconHint.tsx\";\n\nexport interface ControlProps {\n /**\n * Bound `InputField` from `useForm`. Carries value, schema, and error state.\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title` or the field name.\n */\n label?: string;\n /**\n * Helper text shown below the control. Falls back to schema `description`.\n */\n description?: string;\n /**\n * Force a specific input variant — renders a single-line text input.\n */\n text?: boolean;\n /**\n * Force a textarea.\n */\n area?: boolean;\n /**\n * Force a masked password input.\n */\n password?: boolean;\n /**\n * Force a `<Switch>` (boolean toggle).\n */\n switch?: boolean;\n /**\n * Force a numeric input.\n */\n number?: boolean;\n /**\n * Force the file-upload control (alias for `upload`).\n */\n file?: boolean;\n /**\n * Force a date picker.\n */\n date?: boolean;\n /**\n * Force a date-time picker.\n */\n datetime?: boolean;\n /**\n * Force a date-range picker, regardless of the schema's format.\n *\n * Rarely needed: `z.dateRange()` tags the array itself, so the control\n * selects itself. Here for the same reason `date` and `datetime` are - a\n * field whose schema is a plain pair of strings can still ask for it.\n */\n dateRange?: boolean;\n /**\n * Force a time picker.\n */\n time?: boolean;\n /**\n * Date picker caption style — `\"dropdown\"` swaps the month arrows for\n * month/year selects. See {@link ControlDateProps.captionLayout}.\n */\n captionLayout?: ControlDateProps[\"captionLayout\"];\n /** First selectable month of a date picker. */\n startMonth?: Date;\n /** Last selectable month of a date picker. */\n endMonth?: Date;\n /**\n * Date-of-birth shorthand: a year dropdown covering the last 120 years.\n * See {@link ControlDateProps.birthdate}.\n */\n birthdate?: boolean;\n /**\n * Force a `<Select>`.\n */\n select?: boolean;\n /**\n * Force a combobox (searchable select). Alias for `searchable: true`.\n */\n combobox?: boolean;\n /**\n * Force the select's search input on or off. Defaults to \"auto\" — on for an\n * async list, when `createNewEntry` is set, or above ~50 options.\n */\n searchable?: boolean;\n /**\n * Force a `<Segmented>` control (one option visible at a time).\n */\n segmented?: boolean;\n /**\n * Force a slider (numeric only).\n */\n slider?: boolean;\n /**\n * Force a nested `<ControlObject>` for object-typed schemas.\n */\n object?: boolean;\n /**\n * Force a nested `<ControlArray>` for array-typed schemas.\n */\n array?: boolean;\n /**\n * Props forwarded to the nested `<ControlObject>`, keyed by child field name.\n * This is the only way to reach INSIDE an object field — without it a caller\n * can style/override the object as a whole but never one of its children\n * (e.g. attaching a `custom` widget to `payg.zoneFareCents`).\n */\n /**\n * Dictionary prefix for schema-generated labels/help: this field reads\n * `<prefix>.<name>` and `<prefix>.<name>.desc`, and passes the extended\n * prefix down into nested objects and array items.\n */\n i18nPrefix?: string;\n objectProps?: {\n controlProps?: Record<string, Partial<Omit<ControlProps, \"input\">>>;\n variant?: \"fieldset\" | \"plain\";\n defaultExpanded?: boolean;\n };\n /**\n * Custom render component receiving `{value, onChange}`.\n */\n custom?: ComponentType<{ value: unknown; onChange: (v: unknown) => void }>;\n /**\n * Override icon — pass `null` to remove the schema-inferred icon.\n */\n icon?: IconComponent | string | null;\n /**\n * Disable the control.\n */\n disabled?: boolean;\n /**\n * Render slot before the control.\n */\n top?: ReactNode;\n /**\n * Render slot after the control.\n */\n bottom?: ReactNode;\n /**\n * A status drawn inside the right end of a text input, such as a tick or a\n * cross saying whether the value is accepted. Decoration only: it takes no\n * pointer events, so put anything the reader must act on in `bottom`.\n *\n * The auto-save tick and the clear button own that corner when they show,\n * and hide it meanwhile. The input reserves its gutter while it is drawn.\n */\n trailing?: ReactNode;\n /**\n * An error to show now, drawn exactly like a validation error. Wins over\n * the form's own, which only exists once the form has been submitted: a\n * multi-step wizard whose Next is not a submit uses this to refuse a value\n * the moment it is typed.\n */\n error?: string;\n /**\n * Width slot inside an `<AutoForm>` group (mapped to a CSS grid column\n * span). Read by the parent group; ignored when rendering standalone.\n */\n width?: 100 | 75 | 66 | 50 | 33 | 25;\n /**\n * HTML `autocomplete` hint passed to the underlying input.\n */\n autoComplete?: string;\n /**\n * Placeholder text. On a text-shaped control this is the HTML\n * `placeholder`; on a select it is the trigger text shown while nothing is\n * picked.\n */\n placeholder?: string;\n /**\n * Autofocus the control on mount. Forwarded to the text, number, password\n * or textarea input the control renders. Ignored by the variants that are\n * not a single focusable field (select, date, upload, array, object).\n *\n * Every forward site carries an `oxlint-disable-next-line\n * jsx-a11y/no-autofocus`. That rule is right about a page that grabs focus\n * unbidden and wrong here: nothing focuses unless a caller passed this prop,\n * and it is the caller the rule should be asking. Left to fire, it did real\n * damage once - a lint pass deleted the forwarding and left the prop\n * declared, so login and dialog forms silently stopped focusing their first\n * field and two components grew `getElementById(...).focus()` workarounds.\n */\n autoFocus?: boolean;\n /**\n * Visible row count for the textarea variant. Overrides the value\n * auto-derived from the schema's `maxLength`. Ignored by other variants.\n */\n rows?: number;\n /**\n * Escape hatch — extra native attributes (event handlers, `className`,\n * `aria-*`, `data-*`, `style`, …) forwarded to whichever element the\n * control actually renders (text input / textarea / password input). The\n * form bindings (`value`, `onChange`, `id`, `name`) always win and cannot\n * be overridden here.\n *\n * `data-*` is spelled out because `HTMLAttributes` does not carry it:\n * TypeScript special-cases dashed attributes in JSX only, so an object\n * literal `{ \"data-testid\": … }` is an excess property and fails to\n * compile. Without this a control cannot carry a test hook, which meant a\n * surface with an e2e had to keep a raw `<input>` rather than adopt the\n * shared control.\n *\n * ⚠️ **`autoComplete` does not go here.** `Control` takes it as a\n * first-class prop, and `ControlPassword` writes its own after spreading\n * this object - so a value passed through `inputProps` is silently\n * replaced by `\"current-password\"`, which on a field holding a deploy\n * token is the password-manager prompt the masking exists to avoid.\n */\n inputProps?: HTMLAttributes<HTMLElement> & {\n [attribute: `data-${string}`]: string | number | boolean | undefined;\n };\n /**\n * Allow user to create new entries in select / multi-select.\n */\n createNewEntry?: boolean | ((query: string) => unknown);\n /**\n * Inline option list for select / combobox controls. Infer array or\n * async loader. Overrides schema-derived `enum` when present.\n */\n items?:\n | SelectOption[]\n | ((query: string) => SelectOption[] | Promise<SelectOption[]>);\n /**\n * Whether the field offers a way back to empty.\n *\n * On a `ControlSelect`, `true` adds a synthetic \"none\" row that resets the\n * field to `undefined` — use it for optional filter chips.\n *\n * On a text field the affordance is the opposite way round: an optional\n * field already shows a clear (×) button whenever it holds a value, and\n * `false` takes it away. Pass `false` when emptying the field is not\n * something the API can honour — a username has no \"unset\" on the server,\n * so offering the button would promise an edit that silently does nothing.\n */\n clearable?: boolean;\n /**\n * Forwarded to `ControlSelect` — label of the `clearable` row, also\n * used as the empty-state trigger placeholder. Defaults to \"None\".\n */\n clearLabel?: string;\n /**\n * Trigger text for a multi-select whose selection is too long to name, e.g.\n * `(n) => \\`${n} status\\``. One selection always shows the value itself, so\n * this is only ever asked for two or more past `maxTriggerLength`. Defaults\n * to `\"{n} values\"`.\n */\n countLabel?: (count: number) => string;\n /**\n * Forwarded to `ControlSelect`: the longest joined text a multi-select\n * trigger names its selection with before it collapses to `countLabel`.\n * Defaults to 20.\n */\n maxTriggerLength?: number;\n /**\n * Forwarded to `ControlSelect` — extra className on the trigger.\n * Useful for sizing filter chips inline.\n */\n triggerClassName?: string;\n /**\n * Trigger height and type scale, for the select-shaped controls. Defaults\n * to `default`; `xs` is for a control that sits ON a row of text rather\n * than in a form.\n */\n size?: ControlSelectSize;\n /**\n * Render the select trigger borderless and transparent, so it reads as the\n * row it sits on rather than as a form field. Pairs with `size=\"xs\"`.\n */\n minimal?: boolean;\n /**\n * Forwarded to `ControlSelect`: drawn at the top of a select's popup, for\n * a setting that changes what the choice means (a filter's \"is / is not\").\n */\n popupHeader?: ReactNode;\n /**\n * Forwarded to `ControlSelect`: a short qualifier drawn before the\n * selected label on the trigger (\"not Active\").\n */\n triggerPrefix?: ReactNode;\n /**\n * Forwarded to `ControlSelect`: extra className on a select's popup, e.g.\n * `w-max min-w-48` to size it from its content rather than its trigger.\n */\n popupClassName?: string;\n /**\n * Render a managed upload control (image preview, multi, drag-drop)\n * that calls `FileController.uploadFile` and stores the file ID(s) in\n * the form value. Pass `true` for defaults or an options object.\n */\n upload?:\n | boolean\n | Pick<\n ControlUploadProps,\n \"multi\" | \"accept\" | \"maxSize\" | \"bucket\" | \"image\"\n >;\n}\n\n/**\n * Schema-driven form field renderer. Inspects the bound `InputField` from\n * `useForm`, evaluates `schema.$control` (object or function), merges the\n * result with explicit props, and dispatches to the right sub-control.\n */\nexport const Control = (props: ControlProps) => {\n const form = useFormState(props.input, [\"error\", \"dirty\"]);\n const autoSaveEnabled = useFormFieldAutoSave();\n const rowLayout = useFormFieldLayout() === \"row\";\n const [value, setValue] = useFieldValue(props.input);\n\n // Function-form `$control` reads other fields → re-render on any\n // change. Infer `$control` (object) does not need this subscription.\n useDynamicControlRefresh(props.input);\n\n if (!props.input?.props) return null;\n\n const parsed = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n const meta = props.error ? { ...parsed, error: props.error } : parsed;\n\n // ── Resolve $control (object | function | false) ─────────────────\n const resolved = resolveSchemaControl(meta.control, {\n form: props.input.form,\n value,\n });\n // `null` is gone, `hidden` is present-but-invisible. A control renders\n // nothing for either; only the LAYOUT tells them apart.\n if (resolved === null || resolved.hidden) return null;\n\n const merged = {\n ...props,\n ...(resolved as Partial<ControlProps>),\n } as ControlProps & Partial<SchemaControl>;\n\n // ── Custom escape hatch ──────────────────────────────────────────\n if (merged.custom) {\n const Custom = merged.custom;\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Custom value={value} onChange={(v) => setValue(v)} />\n </FormField>,\n );\n }\n\n // ── Recursive: object / array of objects ─────────────────────────\n if (merged.object || meta.isObject) {\n return wrapWithSlots(\n merged,\n <ControlObject\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n i18nPrefix={merged.i18nPrefix}\n controlProps={merged.objectProps?.controlProps}\n variant={merged.objectProps?.variant}\n defaultExpanded={merged.objectProps?.defaultExpanded}\n clearable={merged.clearable}\n />,\n );\n }\n if (merged.array || meta.isArrayOfObjects) {\n const arrayProps = (merged as { arrayProps?: Record<string, unknown> })\n .arrayProps;\n return wrapWithSlots(\n merged,\n <ControlArray\n input={props.input}\n i18nPrefix={merged.i18nPrefix}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n confirmDelete={\n arrayProps?.confirmDelete as ControlArrayProps[\"confirmDelete\"]\n }\n renderTabName={\n arrayProps?.renderTabName as ControlArrayProps[\"renderTabName\"]\n }\n forceTabs={arrayProps?.forceTabs as boolean | undefined}\n />,\n );\n }\n\n // ── File: managed upload (image preview, multi, drag-drop) ──────\n // Checked early so it wins over the array→combobox branch below\n // when the schema is `z.array(z.string())` with $control.upload.\n if (merged.upload) {\n const uploadOpts =\n typeof merged.upload === \"object\"\n ? (merged.upload as Partial<ControlUploadProps>)\n : {};\n return wrapWithSlots(\n merged,\n <ControlUpload\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n {...uploadOpts}\n />,\n );\n }\n\n // ── Items provided → select / multi / combobox ───────────────────\n // Read before the numeric branch, because that branch owns every numeric\n // schema by default and `ControlNumber` has nowhere to put an option list:\n // a `z.number()` field handed `items` used to render a bare spinner and drop\n // the rows on the floor, silently. An explicit list is an explicit request\n // for a select, so it wins - `slider` / `number` still override it below.\n const items = (merged as Record<string, unknown>).items as\n | undefined\n | unknown[]\n | ((q: string) => unknown);\n\n // ── Number / slider ──────────────────────────────────────────────\n if (\n merged.slider ||\n merged.number ||\n (!merged.select &&\n !merged.segmented &&\n !merged.combobox &&\n items == null &&\n (meta.type === \"number\" || meta.type === \"integer\"))\n ) {\n return wrapWithSlots(\n merged,\n <ControlNumber\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n slider={merged.slider}\n disabled={merged.disabled}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n />,\n );\n }\n\n // ── Date range ───────────────────────────────────────────────────\n //\n // ⚠️ ABOVE the array branch below, and that placement is the whole of it.\n // `z.dateRange()` IS an array, so the `meta.isArray` test twenty lines down\n // matches it first and renders a range as a multi-select combobox - which\n // looks like a deliberate control and is silently the wrong one. Sitting\n // this beside the date branch further down, where it reads as though it\n // belongs, is exactly the mistake.\n //\n // Keyed on the format LITERAL, never on \"array whose items are dates\": that\n // second test cannot tell a range from an ordinary list of two days, and it\n // is what would make a later `date-time-range` a rewrite rather than one\n // more literal plus a `withTime` prop.\n if (merged.dateRange || meta.format === \"date-range\") {\n return wrapWithSlots(\n merged,\n <ControlDateRange\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n clearable={merged.clearable}\n placeholder={merged.placeholder}\n triggerClassName={merged.triggerClassName}\n // From `props`, like the select's below: a node has no place in a\n // schema's `$control`.\n triggerPrefix={props.triggerPrefix}\n />,\n );\n }\n\n if (\n merged.select ||\n merged.combobox ||\n merged.segmented ||\n meta.isEnum ||\n (meta.isArray && !meta.isArrayOfObjects) ||\n items != null\n ) {\n return wrapWithSlots(\n merged,\n <ControlSelect\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n segmented={merged.segmented}\n combobox={merged.combobox}\n searchable={merged.searchable}\n items={items as never}\n // Every field carries a leading icon, a select included: the list\n // glyph unless the caller names one or passes `null`. Not on a\n // `minimal` trigger, the toolbar filter chip, which names itself with\n // a `triggerPrefix` and would only get noisier.\n icon={\n merged.minimal\n ? resolveIcon(merged.icon)\n : resolveIcon(merged.icon, \"list\")\n }\n disabled={merged.disabled}\n createNewEntry={\n merged.createNewEntry as boolean | ((q: string) => never) | undefined\n }\n clearable={merged.clearable}\n clearLabel={merged.clearLabel}\n countLabel={merged.countLabel}\n maxTriggerLength={merged.maxTriggerLength}\n // Dropped here until now, so a picker that needed to name its own\n // empty state (\"Pick an epic…\") could not be a `Control` at all.\n placeholder={merged.placeholder}\n triggerClassName={merged.triggerClassName}\n size={merged.size}\n minimal={merged.minimal}\n // Used to be dropped here, silently: every `inputProps={{ \"aria-label\"\n // }}` on a select-shaped Control (the epics and quests status filters\n // among them) named nothing at all, because the trigger is a button\n // with no visible label to borrow a name from.\n triggerProps={merged.inputProps}\n // From `props`, not `merged`: a node has no business in a schema's\n // `$control`, so there is nothing for the merge to contribute.\n popupHeader={props.popupHeader}\n triggerPrefix={props.triggerPrefix}\n popupClassName={merged.popupClassName}\n />,\n );\n }\n\n // ── Boolean → switch ─────────────────────────────────────────────\n if (meta.type === \"boolean\" && merged.switch !== false) {\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <div className=\"flex h-9 items-center\">\n <Switch\n id={meta.id}\n // Same omission as the numeric control had: without a name the\n // toggle is invisible to `[name=\"…\"]` lookups, including\n // `AutoForm`'s scroll-to-first-error.\n name={props.input.props.name}\n disabled={merged.disabled}\n checked={Boolean(value)}\n onCheckedChange={(v) => setValue(v)}\n />\n </div>\n </FormField>,\n );\n }\n\n // ── Date / time ──────────────────────────────────────────────────\n if (\n merged.date ||\n merged.datetime ||\n merged.time ||\n meta.format === \"date\" ||\n meta.format === \"date-time\" ||\n meta.format === \"time\"\n ) {\n return wrapWithSlots(\n merged,\n <ControlDate\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n date={merged.date}\n datetime={merged.datetime}\n time={merged.time}\n disabled={merged.disabled}\n clearable={merged.clearable}\n captionLayout={merged.captionLayout}\n startMonth={merged.startMonth}\n endMonth={merged.endMonth}\n birthdate={merged.birthdate}\n />,\n );\n }\n\n // ── File (raw) ───────────────────────────────────────────────────\n if (merged.file) {\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Input\n id={meta.id}\n name={props.input.props.name}\n type=\"file\"\n disabled={merged.disabled}\n onChange={(e) => setValue(e.target.files?.[0])}\n />\n </FormField>,\n );\n }\n\n // ── Auto-textarea: explicit `area` or maxLength > 256 ────────────\n const maxLength = meta.constraints.maxLength ?? 0;\n if (merged.area || maxLength > 256) {\n const rows =\n merged.rows ?? (maxLength > 1024 ? 6 : maxLength > 512 ? 4 : 2);\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Textarea\n {...merged.inputProps}\n {...formFieldAriaProps({\n id: meta.id,\n error: meta.error,\n description: merged.description ?? meta.description,\n required: meta.required,\n })}\n id={meta.id}\n name={props.input.props.name}\n rows={rows}\n disabled={merged.disabled}\n maxLength={maxLength || undefined}\n autoComplete={merged.autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n placeholder={merged.placeholder}\n value={String(value ?? \"\")}\n onChange={(e) => setValue(e.target.value)}\n />\n </FormField>,\n );\n }\n\n // ── Password ─────────────────────────────────────────────────────\n const isPassword =\n merged.password ||\n meta.iconHint === \"password\" ||\n meta.format === \"password\";\n if (isPassword) {\n return wrapWithSlots(\n merged,\n <ControlPassword\n id={meta.id}\n name={props.input.props.name}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n disabled={merged.disabled}\n autoComplete={merged.autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n inputProps={merged.inputProps}\n icon={resolveIcon(merged.icon, \"password\")}\n value={String(value ?? \"\")}\n onChange={(v) => setValue(v)}\n />,\n );\n }\n\n // ── Default text input with format-driven HTML5 type + icon ──────\n const Icon = resolveIcon(merged.icon, meta.iconHint);\n const htmlType =\n meta.format === \"email\"\n ? \"email\"\n : meta.format === \"url\" || meta.format === \"uri\"\n ? \"url\"\n : meta.format === \"tel\" || meta.format === \"phone\"\n ? \"tel\"\n : \"text\";\n\n // Derive a sensible HTML `autocomplete` hint from the schema format so\n // password managers and browser autofill behave correctly out of the box.\n // Explicit `autoComplete` prop always wins.\n const autoCompleteFromFormat =\n meta.format === \"email\"\n ? \"email\"\n : meta.format === \"tel\" || meta.format === \"phone\"\n ? \"tel\"\n : meta.format === \"url\" || meta.format === \"uri\"\n ? \"url\"\n : undefined;\n const autoComplete = merged.autoComplete ?? autoCompleteFromFormat;\n\n // A value typed verbatim (an account identifier, an address, a code) must\n // not be rewritten by the keyboard: iOS capitalises the first letter of a\n // username by default, and a sign-in then fails on \"Test@mobile.test\".\n const verbatim =\n htmlType === \"email\" ||\n htmlType === \"url\" ||\n [\"username\", \"email\", \"tel\", \"url\", \"one-time-code\"].includes(\n autoComplete ?? \"\",\n );\n\n // ── Right-side affordance: tick (when dirty) or clear (when nullable) ─\n // Tick only renders inside an `<AutoForm autoSave>` tree (or any caller\n // that explicitly wraps with `<FormFieldAutoSaveProvider value>`).\n const showSave = autoSaveEnabled && !!form.dirty && !merged.disabled;\n const isNullable =\n !meta.required && value != null && value !== \"\" && !merged.disabled;\n // `clearable !== false`, not `clearable === true`: an optional text field\n // offers the button by default and a caller opts *out* of it. See the prop.\n const showClear = !showSave && isNullable && merged.clearable !== false;\n // The right gutter is reserved only while the tick is drawn, or while the\n // cross is drawn AND the field has focus. Kept on every editable field, it\n // took 36px from the text of each one and cut placeholders short for a\n // button that was not there (\"Rechercher client, terr…\"). At rest the cross\n // floats over the end of the value on a fade instead, so a settings row\n // shows \"Delete project\" rather than \"Delete proj\"; once focused the gutter\n // comes back, since the caret must never sit under the button. The input\n // is border-box, so the padding never changes its width.\n const showTrailing = !showSave && !showClear && merged.trailing != null;\n const reserveGutter = showSave || showTrailing;\n\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <div className=\"relative\">\n {Icon && (\n <Icon className=\"text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2\" />\n )}\n <Input\n autoCapitalize={verbatim ? \"none\" : undefined}\n autoCorrect={verbatim ? \"off\" : undefined}\n spellCheck={verbatim ? false : undefined}\n {...merged.inputProps}\n {...formFieldAriaProps({\n id: meta.id,\n error: meta.error,\n description: merged.description ?? meta.description,\n required: meta.required,\n })}\n id={meta.id}\n name={props.input.props.name}\n type={htmlType}\n disabled={merged.disabled}\n autoComplete={autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n placeholder={merged.placeholder}\n value={String(value ?? \"\")}\n minLength={meta.constraints.minLength}\n maxLength={meta.constraints.maxLength}\n pattern={meta.constraints.pattern}\n // `cn`, not a plain join: the settings width below has to be\n // overridable by the caller, and only `cn`'s merge can decide\n // that `sm:w-96` beats `sm:w-64` rather than both landing on the\n // element. Order is precedence — later wins.\n className={cn(\n // Row layout is the settings-card shape, whose right-hand cell is\n // an `auto` grid column: `w-full` there resolves against the\n // input's own intrinsic size (~172px), so every card would get a\n // slightly different control column. 256px is the width every\n // hand-written `SettingsRow` already passes; encoded once here.\n // Below `sm` the row stacks, and `w-full` from `<Input>` is right.\n rowLayout && \"sm:w-64\",\n merged.inputProps?.className,\n Icon && \"pl-9\",\n reserveGutter && \"pr-9\",\n showClear && \"focus:pr-9\",\n )}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n merged.inputProps?.onKeyDown?.(e);\n if (e.defaultPrevented || e.key !== \"Enter\") return;\n // The commit the auto-save effect deliberately withholds from a\n // text field on every keystroke. Its comment offers \"Enter or the\n // inline tick button\" as the two ways to commit - and only the\n // tick ever existed. `AutoForm` in auto-save mode renders no\n // submit button, so the browser's implicit submission never fires\n // and Enter did nothing at all, on every text field in every\n // auto-saving form.\n //\n // Guarded on `showSave` so it is inert outside auto-save mode and\n // on a pristine field, where a normal form's own Enter handling\n // must keep working.\n if (!showSave) return;\n e.preventDefault();\n // `props.input.form`, the same handle the tick button submits\n // through. The local `form` is only the `dirty` / `error` slice.\n void props.input.form.submit();\n }}\n />\n {showSave && (\n <button\n type=\"button\"\n onClick={() => props.input.form.submit()}\n aria-label=\"Save\"\n className=\"text-primary hover:text-primary/80 absolute top-1/2 right-2 -translate-y-1/2 p-1\"\n >\n <Check className=\"size-3.5\" />\n </button>\n )}\n {showClear && (\n <button\n type=\"button\"\n onClick={() => setValue(undefined)}\n aria-label=\"Clear\"\n // `data-slot` like every other clear in the kit\n // (`combobox-clear`, and `control-clear` on the field trigger).\n // It was the only one without a hook, so the only way to address\n // it was its `aria-label` - which is translated, so a French UI\n // would have matched nothing. Purely an identification hook: no\n // style and no behaviour rides on it here.\n data-slot=\"control-clear\"\n // Over the value, inside the border (`inset-y-px right-px`), on a\n // fade into the surface behind the field (`--surface`, which any\n // element painting a surface token declares, see `styles.css`).\n // In dark the input carries its own\n // `bg-input/30` tint, so the fade stacks that tint over the\n // surface to match it exactly.\n className=\"text-muted-foreground hover:text-foreground absolute inset-y-px right-px flex items-center rounded-r-[calc(var(--radius-lg)-1px)] bg-[linear-gradient(to_right,transparent,var(--surface)_1.25rem)] pr-2.5 pl-6 dark:bg-[linear-gradient(to_right,transparent,color-mix(in_oklab,var(--input)_30%,transparent)_1.25rem),linear-gradient(to_right,transparent,var(--surface)_1.25rem)]\"\n >\n <X className=\"size-3.5\" />\n </button>\n )}\n {showTrailing && (\n <span\n data-slot=\"control-trailing\"\n className=\"pointer-events-none absolute top-1/2 right-3 flex -translate-y-1/2 items-center\"\n >\n {merged.trailing}\n </span>\n )}\n </div>\n </FormField>,\n );\n};\n\n/**\n * The raw `$control` a field declares, object form or function form.\n *\n * It rides on zod's `.meta()` registry rather than being a plain schema\n * property, and the field may be wrapped (optional / nullable / default), so\n * the wrapper has to be peeled before the meta is readable.\n *\n * Exported because the LAYOUT needs it too: `AutoForm` sizes a grid cell from\n * the width `$control` asks for, and a function-form `$control` has no `.width`\n * to read off the function itself. Pair it with {@link resolveSchemaControl}.\n */\nexport const readSchemaControl = (\n input: BaseInputField | undefined,\n): unknown => {\n const base = input?.schema ? z.schema.unwrap(input.schema) : undefined;\n return (base as { meta?: () => { $control?: unknown } } | undefined)?.meta?.()\n ?.$control;\n};\n\n/**\n * Re-render when a function-form `$control` may have changed its mind, which\n * is on any change to a field OTHER than this one. An object-form `$control`\n * is static and needs no subscription.\n *\n * Exported alongside {@link readSchemaControl}, and for the same reason: a\n * consumer that resolves `$control` itself has to re-resolve on the same\n * events, or it renders a stale answer.\n */\nexport const useDynamicControlRefresh = (input: BaseInputField | undefined) => {\n const alepha = useAlepha();\n const [, bump] = useState(0);\n const isDynamic = typeof readSchemaControl(input) === \"function\";\n useEffect(() => {\n if (!isDynamic || !input?.form) return;\n const formId = input.form.id;\n return alepha.events.on(\"form:change\", (e) => {\n if (e.id === formId && e.path !== input.path) bump((n) => n + 1);\n });\n }, [alepha, input?.form, input?.path, isDynamic]);\n};\n\nconst resolveIcon = (\n icon: ControlProps[\"icon\"],\n fallback?: string | null,\n): IconComponent | undefined => {\n if (icon === null) return undefined;\n if (typeof icon === \"string\") return iconFor(icon);\n if (icon) return icon;\n return iconFor(fallback);\n};\n\nconst wrapWithSlots = (\n props: ControlProps & Partial<SchemaControl>,\n body: ReactNode,\n): ReactNode => {\n const top = (props.top as ReactNode) ?? null;\n const bottom = (props.bottom as ReactNode) ?? null;\n if (!top && !bottom) return body;\n return (\n <div className=\"flex flex-col gap-1\">\n {top}\n {body}\n {bottom}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwVA,MAAa,WAAW,UAAwB;CAC9C,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,SAAS,OAAO,CAAC;CACzD,MAAM,kBAAkB,qBAAqB;CAC7C,MAAM,YAAY,mBAAmB,MAAM;CAC3C,MAAM,CAAC,OAAO,YAAY,cAAc,MAAM,KAAK;CAInD,yBAAyB,MAAM,KAAK;CAEpC,IAAI,CAAC,MAAM,OAAO,OAAO,OAAO;CAEhC,MAAM,SAAS,WAAW,MAAM,OAAO;EACrC,OAAO,MAAM;EACb,aAAa,MAAM;EACnB,OAAO,KAAK;CACd,CAAC;CACD,MAAM,OAAO,MAAM,QAAQ;EAAE,GAAG;EAAQ,OAAO,MAAM;CAAM,IAAI;CAG/D,MAAM,WAAW,qBAAqB,KAAK,SAAS;EAClD,MAAM,MAAM,MAAM;EAClB;CACF,CAAC;CAGD,IAAI,aAAa,QAAQ,SAAS,QAAQ,OAAO;CAEjD,MAAM,SAAS;EACb,GAAG;EACH,GAAI;CACN;CAGA,IAAI,OAAO,QAAQ;EACjB,MAAM,SAAS,OAAO;EACtB,OAAO,cACL,QACA,oBAAC,WAAD;GACE,IAAI,KAAK;GACT,OAAO,OAAO,SAAS,KAAK;GAC5B,aAAa,OAAO,eAAe,KAA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AAM,UAAwB;CAC9C,IAAI,CAAC,OAAO,CAAC,QAAQ,OAAO;CAC5B,OACE,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACG;GACA;GACA;EACE;;AAET"}
1
+ {"version":3,"file":"Control.js","names":[],"sources":["../../src/form/Control.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { z } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { resolveSchemaControl, type SchemaControl } from \"alepha/react/ui\";\nimport { Check, X } from \"lucide-react\";\nimport {\n type ComponentType,\n type HTMLAttributes,\n type ReactNode,\n useEffect,\n useState,\n} from \"react\";\n\nimport { Input } from \"../core/Input.tsx\";\nimport { Switch } from \"../core/Switch.tsx\";\nimport { Textarea } from \"../core/Textarea.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport { ControlArray, type ControlArrayProps } from \"./ControlArray.tsx\";\nimport { ControlDate, type ControlDateProps } from \"./ControlDate.tsx\";\nimport { ControlDateRange } from \"./ControlDateRange.tsx\";\nimport { ControlNumber } from \"./ControlNumber.tsx\";\nimport { ControlObject } from \"./ControlObject.tsx\";\nimport { ControlPassword } from \"./ControlPassword.tsx\";\nimport {\n ControlSelect,\n type ControlSelectSize,\n type SelectOption,\n} from \"./ControlSelect.tsx\";\nimport { ControlUpload, type ControlUploadProps } from \"./ControlUpload.tsx\";\nimport { FormField, formFieldAriaProps } from \"./FormField.tsx\";\nimport { useFormFieldAutoSave } from \"./FormFieldAutoSaveProvider.tsx\";\nimport { useFormFieldLayout } from \"./FormFieldLayoutProvider.tsx\";\nimport { type IconComponent, iconFor } from \"./iconHint.tsx\";\n\nexport interface ControlProps {\n /**\n * Bound `InputField` from `useForm`. Carries value, schema, and error state.\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title` or the field name.\n */\n label?: string;\n /**\n * Helper text shown below the control. Falls back to schema `description`.\n */\n description?: string;\n /**\n * Force a specific input variant — renders a single-line text input.\n */\n text?: boolean;\n /**\n * Force a textarea.\n */\n area?: boolean;\n /**\n * Force a masked password input.\n */\n password?: boolean;\n /**\n * Force a `<Switch>` (boolean toggle).\n */\n switch?: boolean;\n /**\n * Force a numeric input.\n */\n number?: boolean;\n /**\n * Force the file-upload control (alias for `upload`).\n */\n file?: boolean;\n /**\n * Force a date picker.\n */\n date?: boolean;\n /**\n * Force a date-time picker.\n */\n datetime?: boolean;\n /**\n * Force a date-range picker, regardless of the schema's format.\n *\n * Rarely needed: `z.dateRange()` tags the array itself, so the control\n * selects itself. Here for the same reason `date` and `datetime` are - a\n * field whose schema is a plain pair of strings can still ask for it.\n */\n dateRange?: boolean;\n /**\n * Force a time picker.\n */\n time?: boolean;\n /**\n * Date picker caption style — `\"dropdown\"` swaps the month arrows for\n * month/year selects. See {@link ControlDateProps.captionLayout}.\n */\n captionLayout?: ControlDateProps[\"captionLayout\"];\n /** First selectable month of a date picker. */\n startMonth?: Date;\n /** Last selectable month of a date picker. */\n endMonth?: Date;\n /**\n * Date-of-birth shorthand: a year dropdown covering the last 120 years.\n * See {@link ControlDateProps.birthdate}.\n */\n birthdate?: boolean;\n /**\n * Force a `<Select>`.\n */\n select?: boolean;\n /**\n * Force a combobox (searchable select). Alias for `searchable: true`.\n */\n combobox?: boolean;\n /**\n * Force the select's search input on or off. Defaults to \"auto\" — on for an\n * async list, when `createNewEntry` is set, or above ~50 options.\n */\n searchable?: boolean;\n /**\n * Force a `<Segmented>` control (one option visible at a time).\n */\n segmented?: boolean;\n /**\n * Force a slider (numeric only).\n */\n slider?: boolean;\n /**\n * Force a nested `<ControlObject>` for object-typed schemas.\n */\n object?: boolean;\n /**\n * Force a nested `<ControlArray>` for array-typed schemas.\n */\n array?: boolean;\n /**\n * Props forwarded to the nested `<ControlObject>`, keyed by child field name.\n * This is the only way to reach INSIDE an object field — without it a caller\n * can style/override the object as a whole but never one of its children\n * (e.g. attaching a `custom` widget to `payg.zoneFareCents`).\n */\n /**\n * Dictionary prefix for schema-generated labels/help: this field reads\n * `<prefix>.<name>` and `<prefix>.<name>.desc`, and passes the extended\n * prefix down into nested objects and array items.\n */\n i18nPrefix?: string;\n objectProps?: {\n controlProps?: Record<string, Partial<Omit<ControlProps, \"input\">>>;\n variant?: \"fieldset\" | \"plain\";\n defaultExpanded?: boolean;\n };\n /**\n * Custom render component receiving `{value, onChange}`.\n */\n custom?: ComponentType<{ value: unknown; onChange: (v: unknown) => void }>;\n /**\n * Override icon — pass `null` to remove the schema-inferred icon.\n */\n icon?: IconComponent | string | null;\n /**\n * Disable the control.\n */\n disabled?: boolean;\n /**\n * Render slot before the control.\n */\n top?: ReactNode;\n /**\n * Render slot after the control.\n */\n bottom?: ReactNode;\n /**\n * A status drawn inside the right end of a text input, such as a tick or a\n * cross saying whether the value is accepted. Decoration only: it takes no\n * pointer events, so put anything the reader must act on in `bottom`.\n *\n * The auto-save tick and the clear button own that corner when they show,\n * and hide it meanwhile. The input reserves its gutter while it is drawn.\n */\n trailing?: ReactNode;\n /**\n * An error to show now, drawn exactly like a validation error. Wins over\n * the form's own, which only exists once the form has been submitted: a\n * multi-step wizard whose Next is not a submit uses this to refuse a value\n * the moment it is typed.\n */\n error?: string;\n /**\n * Width slot inside an `<AutoForm>` group (mapped to a CSS grid column\n * span). Read by the parent group; ignored when rendering standalone.\n */\n width?: 100 | 75 | 66 | 50 | 33 | 25;\n /**\n * HTML `autocomplete` hint passed to the underlying input.\n */\n autoComplete?: string;\n /**\n * Placeholder text. On a text-shaped control this is the HTML\n * `placeholder`; on a select it is the trigger text shown while nothing is\n * picked.\n */\n placeholder?: string;\n /**\n * Autofocus the control on mount. Forwarded to the text, number, password\n * or textarea input the control renders. Ignored by the variants that are\n * not a single focusable field (select, date, upload, array, object).\n *\n * Every forward site carries an `oxlint-disable-next-line\n * jsx-a11y/no-autofocus`. That rule is right about a page that grabs focus\n * unbidden and wrong here: nothing focuses unless a caller passed this prop,\n * and it is the caller the rule should be asking. Left to fire, it did real\n * damage once - a lint pass deleted the forwarding and left the prop\n * declared, so login and dialog forms silently stopped focusing their first\n * field and two components grew `getElementById(...).focus()` workarounds.\n */\n autoFocus?: boolean;\n /**\n * Visible row count for the textarea variant. Overrides the value\n * auto-derived from the schema's `maxLength`. Ignored by other variants.\n */\n rows?: number;\n /**\n * Escape hatch — extra native attributes (event handlers, `className`,\n * `aria-*`, `data-*`, `style`, …) forwarded to whichever element the\n * control actually renders (text input / textarea / password input). The\n * form bindings (`value`, `onChange`, `id`, `name`) always win and cannot\n * be overridden here.\n *\n * `data-*` is spelled out because `HTMLAttributes` does not carry it:\n * TypeScript special-cases dashed attributes in JSX only, so an object\n * literal `{ \"data-testid\": … }` is an excess property and fails to\n * compile. Without this a control cannot carry a test hook, which meant a\n * surface with an e2e had to keep a raw `<input>` rather than adopt the\n * shared control.\n *\n * ⚠️ **`autoComplete` does not go here.** `Control` takes it as a\n * first-class prop, and `ControlPassword` writes its own after spreading\n * this object - so a value passed through `inputProps` is silently\n * replaced by `\"current-password\"`, which on a field holding a deploy\n * token is the password-manager prompt the masking exists to avoid.\n */\n inputProps?: HTMLAttributes<HTMLElement> & {\n [attribute: `data-${string}`]: string | number | boolean | undefined;\n };\n /**\n * Allow user to create new entries in select / multi-select.\n */\n createNewEntry?: boolean | ((query: string) => unknown);\n /**\n * Inline option list for select / combobox controls. Infer array or\n * async loader. Overrides schema-derived `enum` when present.\n */\n items?:\n | SelectOption[]\n | ((query: string) => SelectOption[] | Promise<SelectOption[]>);\n /**\n * Whether the field offers a way back to empty.\n *\n * On a `ControlSelect`, `true` adds a synthetic \"none\" row that resets the\n * field to `undefined` — use it for optional filter chips.\n *\n * On a text field the affordance is the opposite way round: an optional\n * field already shows a clear (×) button whenever it holds a value, and\n * `false` takes it away. Pass `false` when emptying the field is not\n * something the API can honour — a username has no \"unset\" on the server,\n * so offering the button would promise an edit that silently does nothing.\n */\n clearable?: boolean;\n /**\n * Forwarded to `ControlSelect` — label of the `clearable` row, also\n * used as the empty-state trigger placeholder. Defaults to \"None\".\n */\n clearLabel?: string;\n /**\n * Trigger text for a multi-select whose selection is too long to name, e.g.\n * `(n) => \\`${n} status\\``. One selection always shows the value itself, so\n * this is only ever asked for two or more past `maxTriggerLength`. Defaults\n * to `\"{n} values\"`.\n */\n countLabel?: (count: number) => string;\n /**\n * Forwarded to `ControlSelect`: the longest joined text a multi-select\n * trigger names its selection with before it collapses to `countLabel`.\n * Defaults to 20.\n */\n maxTriggerLength?: number;\n /**\n * Forwarded to `ControlSelect` — extra className on the trigger.\n * Useful for sizing filter chips inline.\n */\n triggerClassName?: string;\n /**\n * Trigger height and type scale, for the select-shaped controls. Defaults\n * to `default`; `xs` is for a control that sits ON a row of text rather\n * than in a form.\n */\n size?: ControlSelectSize;\n /**\n * Render the select trigger borderless and transparent, so it reads as the\n * row it sits on rather than as a form field. Pairs with `size=\"xs\"`.\n */\n minimal?: boolean;\n /**\n * Forwarded to `ControlSelect`: drawn at the top of a select's popup, for\n * a setting that changes what the choice means (a filter's \"is / is not\").\n */\n popupHeader?: ReactNode;\n /**\n * Forwarded to `ControlSelect`: a short qualifier drawn before the\n * selected label on the trigger (\"not Active\").\n */\n triggerPrefix?: ReactNode;\n /**\n * Forwarded to `ControlSelect`: extra className on a select's popup, e.g.\n * `w-max min-w-48` to size it from its content rather than its trigger.\n */\n popupClassName?: string;\n /**\n * Render a managed upload control (image preview, multi, drag-drop)\n * that calls `FileController.uploadFile` and stores the file ID(s) in\n * the form value. Pass `true` for defaults or an options object.\n */\n upload?:\n | boolean\n | Pick<\n ControlUploadProps,\n \"multi\" | \"accept\" | \"maxSize\" | \"bucket\" | \"image\"\n >;\n}\n\n/**\n * Schema-driven form field renderer. Inspects the bound `InputField` from\n * `useForm`, evaluates `schema.$control` (object or function), merges the\n * result with explicit props, and dispatches to the right sub-control.\n */\nexport const Control = (props: ControlProps) => {\n const form = useFormState(props.input, [\"error\", \"dirty\"]);\n const autoSaveEnabled = useFormFieldAutoSave();\n const rowLayout = useFormFieldLayout() === \"row\";\n const [value, setValue] = useFieldValue(props.input);\n\n // Function-form `$control` reads other fields → re-render on any\n // change. Infer `$control` (object) does not need this subscription.\n useDynamicControlRefresh(props.input);\n\n if (!props.input?.props) return null;\n\n const parsed = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n const meta = props.error ? { ...parsed, error: props.error } : parsed;\n\n // ── Resolve $control (object | function | false) ─────────────────\n const resolved = resolveSchemaControl(meta.control, {\n form: props.input.form,\n value,\n });\n // `null` is gone, `hidden` is present-but-invisible. A control renders\n // nothing for either; only the LAYOUT tells them apart.\n if (resolved === null || resolved.hidden) return null;\n\n const merged = {\n ...props,\n ...(resolved as Partial<ControlProps>),\n } as ControlProps & Partial<SchemaControl>;\n\n // ── Custom escape hatch ──────────────────────────────────────────\n if (merged.custom) {\n const Custom = merged.custom;\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Custom value={value} onChange={(v) => setValue(v)} />\n </FormField>,\n );\n }\n\n // ── Recursive: object / array of objects ─────────────────────────\n if (merged.object || meta.isObject) {\n return wrapWithSlots(\n merged,\n <ControlObject\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n i18nPrefix={merged.i18nPrefix}\n controlProps={merged.objectProps?.controlProps}\n variant={merged.objectProps?.variant}\n defaultExpanded={merged.objectProps?.defaultExpanded}\n clearable={merged.clearable}\n />,\n );\n }\n if (merged.array || meta.isArrayOfObjects) {\n const arrayProps = (merged as { arrayProps?: Record<string, unknown> })\n .arrayProps;\n return wrapWithSlots(\n merged,\n <ControlArray\n input={props.input}\n i18nPrefix={merged.i18nPrefix}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n confirmDelete={\n arrayProps?.confirmDelete as ControlArrayProps[\"confirmDelete\"]\n }\n renderTabName={\n arrayProps?.renderTabName as ControlArrayProps[\"renderTabName\"]\n }\n forceTabs={arrayProps?.forceTabs as boolean | undefined}\n />,\n );\n }\n\n // ── File: managed upload (image preview, multi, drag-drop) ──────\n // Checked early so it wins over the array→combobox branch below\n // when the schema is `z.array(z.string())` with $control.upload.\n if (merged.upload) {\n const uploadOpts =\n typeof merged.upload === \"object\"\n ? (merged.upload as Partial<ControlUploadProps>)\n : {};\n return wrapWithSlots(\n merged,\n <ControlUpload\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n {...uploadOpts}\n />,\n );\n }\n\n // ── Items provided → select / multi / combobox ───────────────────\n // Read before the numeric branch, because that branch owns every numeric\n // schema by default and `ControlNumber` has nowhere to put an option list:\n // a `z.number()` field handed `items` used to render a bare spinner and drop\n // the rows on the floor, silently. An explicit list is an explicit request\n // for a select, so it wins - `slider` / `number` still override it below.\n const items = (merged as Record<string, unknown>).items as\n | undefined\n | unknown[]\n | ((q: string) => unknown);\n\n // ── Number / slider ──────────────────────────────────────────────\n if (\n merged.slider ||\n merged.number ||\n (!merged.select &&\n !merged.segmented &&\n !merged.combobox &&\n items == null &&\n (meta.type === \"number\" || meta.type === \"integer\"))\n ) {\n return wrapWithSlots(\n merged,\n <ControlNumber\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n slider={merged.slider}\n disabled={merged.disabled}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n />,\n );\n }\n\n // ── Date range ───────────────────────────────────────────────────\n //\n // ⚠️ ABOVE the array branch below, and that placement is the whole of it.\n // `z.dateRange()` IS an array, so the `meta.isArray` test twenty lines down\n // matches it first and renders a range as a multi-select combobox - which\n // looks like a deliberate control and is silently the wrong one. Sitting\n // this beside the date branch further down, where it reads as though it\n // belongs, is exactly the mistake.\n //\n // Keyed on the format LITERAL, never on \"array whose items are dates\": that\n // second test cannot tell a range from an ordinary list of two days, and it\n // is what would make a later `date-time-range` a rewrite rather than one\n // more literal plus a `withTime` prop.\n if (merged.dateRange || meta.format === \"date-range\") {\n return wrapWithSlots(\n merged,\n <ControlDateRange\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n disabled={merged.disabled}\n clearable={merged.clearable}\n placeholder={merged.placeholder}\n triggerClassName={merged.triggerClassName}\n // From `props`, like the select's below: a node has no place in a\n // schema's `$control`.\n triggerPrefix={props.triggerPrefix}\n />,\n );\n }\n\n if (\n merged.select ||\n merged.combobox ||\n merged.segmented ||\n meta.isEnum ||\n (meta.isArray && !meta.isArrayOfObjects) ||\n items != null\n ) {\n return wrapWithSlots(\n merged,\n <ControlSelect\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n segmented={merged.segmented}\n combobox={merged.combobox}\n searchable={merged.searchable}\n items={items as never}\n // Every field carries a leading icon, a select included: the list\n // glyph unless the caller names one or passes `null`. Not on a\n // `minimal` trigger, the toolbar filter chip, which names itself with\n // a `triggerPrefix` and would only get noisier.\n icon={\n merged.minimal\n ? resolveIcon(merged.icon)\n : resolveIcon(merged.icon, \"list\")\n }\n disabled={merged.disabled}\n createNewEntry={\n merged.createNewEntry as boolean | ((q: string) => never) | undefined\n }\n clearable={merged.clearable}\n clearLabel={merged.clearLabel}\n countLabel={merged.countLabel}\n maxTriggerLength={merged.maxTriggerLength}\n // Dropped here until now, so a picker that needed to name its own\n // empty state (\"Pick an epic…\") could not be a `Control` at all.\n placeholder={merged.placeholder}\n triggerClassName={merged.triggerClassName}\n size={merged.size}\n minimal={merged.minimal}\n // Used to be dropped here, silently: every `inputProps={{ \"aria-label\"\n // }}` on a select-shaped Control (the epics and quests status filters\n // among them) named nothing at all, because the trigger is a button\n // with no visible label to borrow a name from.\n triggerProps={merged.inputProps}\n // From `props`, not `merged`: a node has no business in a schema's\n // `$control`, so there is nothing for the merge to contribute.\n popupHeader={props.popupHeader}\n triggerPrefix={props.triggerPrefix}\n popupClassName={merged.popupClassName}\n />,\n );\n }\n\n // ── Boolean → switch ─────────────────────────────────────────────\n if (meta.type === \"boolean\" && merged.switch !== false) {\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <div className=\"flex h-9 items-center\">\n <Switch\n id={meta.id}\n // Same omission as the numeric control had: without a name the\n // toggle is invisible to `[name=\"…\"]` lookups, including\n // `AutoForm`'s scroll-to-first-error.\n name={props.input.props.name}\n disabled={merged.disabled}\n checked={Boolean(value)}\n onCheckedChange={(v) => setValue(v)}\n />\n </div>\n </FormField>,\n );\n }\n\n // ── Date / time ──────────────────────────────────────────────────\n if (\n merged.date ||\n merged.datetime ||\n merged.time ||\n meta.format === \"date\" ||\n meta.format === \"date-time\" ||\n meta.format === \"time\"\n ) {\n return wrapWithSlots(\n merged,\n <ControlDate\n input={props.input}\n label={merged.label ?? props.label}\n description={merged.description ?? props.description}\n date={merged.date}\n datetime={merged.datetime}\n time={merged.time}\n disabled={merged.disabled}\n clearable={merged.clearable}\n captionLayout={merged.captionLayout}\n startMonth={merged.startMonth}\n endMonth={merged.endMonth}\n birthdate={merged.birthdate}\n />,\n );\n }\n\n // ── File (raw) ───────────────────────────────────────────────────\n if (merged.file) {\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Input\n id={meta.id}\n name={props.input.props.name}\n type=\"file\"\n disabled={merged.disabled}\n onChange={(e) => setValue(e.target.files?.[0])}\n />\n </FormField>,\n );\n }\n\n // ── Auto-textarea: explicit `area` or maxLength > 256 ────────────\n const maxLength = meta.constraints.maxLength ?? 0;\n if (merged.area || maxLength > 256) {\n const rows =\n merged.rows ?? (maxLength > 1024 ? 6 : maxLength > 512 ? 4 : 2);\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <Textarea\n {...merged.inputProps}\n {...formFieldAriaProps({\n id: meta.id,\n error: meta.error,\n description: merged.description ?? meta.description,\n required: meta.required,\n })}\n id={meta.id}\n name={props.input.props.name}\n rows={rows}\n disabled={merged.disabled}\n maxLength={maxLength || undefined}\n autoComplete={merged.autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n placeholder={merged.placeholder}\n value={String(value ?? \"\")}\n onChange={(e) => setValue(e.target.value)}\n />\n </FormField>,\n );\n }\n\n // ── Password ─────────────────────────────────────────────────────\n const isPassword =\n merged.password ||\n meta.iconHint === \"password\" ||\n meta.format === \"password\";\n if (isPassword) {\n return wrapWithSlots(\n merged,\n <ControlPassword\n id={meta.id}\n name={props.input.props.name}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n disabled={merged.disabled}\n autoComplete={merged.autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n inputProps={merged.inputProps}\n icon={resolveIcon(merged.icon, \"password\")}\n value={String(value ?? \"\")}\n onChange={(v) => setValue(v)}\n />,\n );\n }\n\n // ── Default text input with format-driven HTML5 type + icon ──────\n const Icon = resolveIcon(merged.icon, meta.iconHint);\n const htmlType =\n meta.format === \"email\"\n ? \"email\"\n : meta.format === \"url\" || meta.format === \"uri\"\n ? \"url\"\n : meta.format === \"tel\" || meta.format === \"phone\"\n ? \"tel\"\n : \"text\";\n\n // Derive a sensible HTML `autocomplete` hint from the schema format so\n // password managers and browser autofill behave correctly out of the box.\n // Explicit `autoComplete` prop always wins.\n const autoCompleteFromFormat =\n meta.format === \"email\"\n ? \"email\"\n : meta.format === \"tel\" || meta.format === \"phone\"\n ? \"tel\"\n : meta.format === \"url\" || meta.format === \"uri\"\n ? \"url\"\n : undefined;\n const autoComplete = merged.autoComplete ?? autoCompleteFromFormat;\n\n // A value typed verbatim (an account identifier, an address, a code) must\n // not be rewritten by the keyboard: iOS capitalises the first letter of a\n // username by default, and a sign-in then fails on \"Test@mobile.test\".\n const verbatim =\n htmlType === \"email\" ||\n htmlType === \"url\" ||\n [\"username\", \"email\", \"tel\", \"url\", \"one-time-code\"].includes(\n autoComplete ?? \"\",\n );\n\n // ── Right-side affordance: tick (when dirty) or clear (when nullable) ─\n // Tick only renders inside an `<AutoForm autoSave>` tree (or any caller\n // that explicitly wraps with `<FormFieldAutoSaveProvider value>`).\n const showSave = autoSaveEnabled && !!form.dirty && !merged.disabled;\n const isNullable =\n !meta.required && value != null && value !== \"\" && !merged.disabled;\n // `clearable !== false`, not `clearable === true`: an optional text field\n // offers the button by default and a caller opts *out* of it. See the prop.\n const showClear = !showSave && isNullable && merged.clearable !== false;\n // The right gutter is reserved only while the tick is drawn, or while the\n // cross is drawn AND the field has focus. Kept on every editable field, it\n // took 36px from the text of each one and cut placeholders short for a\n // button that was not there (\"Rechercher client, terr…\"). At rest the cross\n // floats over the end of the value on a fade instead, so a settings row\n // shows \"Delete project\" rather than \"Delete proj\"; once focused the gutter\n // comes back, since the caret must never sit under the button. The input\n // is border-box, so the padding never changes its width.\n const showTrailing = !showSave && !showClear && merged.trailing != null;\n const reserveGutter = showSave || showTrailing;\n\n return wrapWithSlots(\n merged,\n <FormField\n id={meta.id}\n label={merged.label ?? meta.label}\n description={merged.description ?? meta.description}\n error={meta.error}\n required={meta.required}\n >\n <div className=\"relative\">\n {Icon && (\n <Icon className=\"text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2\" />\n )}\n <Input\n autoCapitalize={verbatim ? \"none\" : undefined}\n autoCorrect={verbatim ? \"off\" : undefined}\n spellCheck={verbatim ? false : undefined}\n {...merged.inputProps}\n {...formFieldAriaProps({\n id: meta.id,\n error: meta.error,\n description: merged.description ?? meta.description,\n required: meta.required,\n })}\n id={meta.id}\n name={props.input.props.name}\n type={htmlType}\n disabled={merged.disabled}\n autoComplete={autoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- forwarded only when the caller asked, see `autoFocus` above\n autoFocus={merged.autoFocus}\n placeholder={merged.placeholder}\n value={String(value ?? \"\")}\n minLength={meta.constraints.minLength}\n maxLength={meta.constraints.maxLength}\n pattern={meta.constraints.pattern}\n // `cn`, not a plain join: the settings width below has to be\n // overridable by the caller, and only `cn`'s merge can decide\n // that `sm:w-96` beats `sm:w-64` rather than both landing on the\n // element. Order is precedence — later wins.\n className={cn(\n // Row layout is the settings-card shape, whose right-hand cell is\n // an `auto` grid column: `w-full` there resolves against the\n // input's own intrinsic size (~172px), so every card would get a\n // slightly different control column. 256px is the width every\n // hand-written `SettingsRow` already passes; encoded once here.\n // Below `sm` the row stacks, and `w-full` from `<Input>` is right.\n rowLayout && \"sm:w-64\",\n merged.inputProps?.className,\n Icon && \"pl-9\",\n reserveGutter && \"pr-9\",\n showClear && \"focus:pr-9\",\n )}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n merged.inputProps?.onKeyDown?.(e);\n if (e.defaultPrevented || e.key !== \"Enter\") return;\n // The commit the auto-save effect deliberately withholds from a\n // text field on every keystroke. Its comment offers \"Enter or the\n // inline tick button\" as the two ways to commit - and only the\n // tick ever existed. `AutoForm` in auto-save mode renders no\n // submit button, so the browser's implicit submission never fires\n // and Enter did nothing at all, on every text field in every\n // auto-saving form.\n //\n // Guarded on `showSave` so it is inert outside auto-save mode and\n // on a pristine field, where a normal form's own Enter handling\n // must keep working.\n if (!showSave) return;\n e.preventDefault();\n // `props.input.form`, the same handle the tick button submits\n // through. The local `form` is only the `dirty` / `error` slice.\n void props.input.form.submit();\n }}\n />\n {showSave && (\n <button\n type=\"button\"\n onClick={() => props.input.form.submit()}\n aria-label=\"Save\"\n className=\"text-primary hover:text-primary/80 absolute top-1/2 right-2 -translate-y-1/2 p-1\"\n >\n <Check className=\"size-3.5\" />\n </button>\n )}\n {showClear && (\n <button\n type=\"button\"\n onClick={() => setValue(undefined)}\n aria-label=\"Clear\"\n // `data-slot` like every other clear in the kit\n // (`combobox-clear`, and `control-clear` on the field trigger).\n // It was the only one without a hook, so the only way to address\n // it was its `aria-label` - which is translated, so a French UI\n // would have matched nothing. Purely an identification hook: no\n // style and no behaviour rides on it here.\n data-slot=\"control-clear\"\n // Over the value, inside the border (`inset-y-px right-px`), on a\n // fade into the surface behind the field (`--surface`, which any\n // element painting a surface token declares, see `styles.css`).\n // In dark the input carries its own\n // `bg-input/30` tint, so the fade stacks that tint over the\n // surface to match it exactly.\n className=\"text-muted-foreground hover:text-foreground absolute inset-y-px right-px flex items-center rounded-r-[calc(var(--radius-lg)-1px)] bg-[linear-gradient(to_right,transparent,var(--surface)_1.25rem)] pr-2.5 pl-6 dark:bg-[linear-gradient(to_right,transparent,color-mix(in_oklab,var(--input)_30%,transparent)_1.25rem),linear-gradient(to_right,transparent,var(--surface)_1.25rem)]\"\n >\n <X className=\"size-3.5\" />\n </button>\n )}\n {showTrailing && (\n <span\n data-slot=\"control-trailing\"\n className=\"pointer-events-none absolute top-1/2 right-3 flex -translate-y-1/2 items-center\"\n >\n {merged.trailing}\n </span>\n )}\n </div>\n </FormField>,\n );\n};\n\n/**\n * The raw `$control` a field declares, object form or function form.\n *\n * It rides on zod's `.meta()` registry rather than being a plain schema\n * property, and the field may be wrapped (optional / nullable / default), so\n * the wrapper has to be peeled before the meta is readable.\n *\n * Exported because the LAYOUT needs it too: `AutoForm` sizes a grid cell from\n * the width `$control` asks for, and a function-form `$control` has no `.width`\n * to read off the function itself. Pair it with {@link resolveSchemaControl}.\n */\nexport const readSchemaControl = (\n input: BaseInputField | undefined,\n): unknown => {\n const base = input?.schema ? z.schema.unwrap(input.schema) : undefined;\n return (base as { meta?: () => { $control?: unknown } } | undefined)?.meta?.()\n ?.$control;\n};\n\n/**\n * Re-render when a function-form `$control` may have changed its mind, which\n * is on any change to a field OTHER than this one. An object-form `$control`\n * is static and needs no subscription.\n *\n * Exported alongside {@link readSchemaControl}, and for the same reason: a\n * consumer that resolves `$control` itself has to re-resolve on the same\n * events, or it renders a stale answer.\n */\nexport const useDynamicControlRefresh = (input: BaseInputField | undefined) => {\n const alepha = useAlepha();\n const [, bump] = useState(0);\n const isDynamic = typeof readSchemaControl(input) === \"function\";\n useEffect(() => {\n if (!isDynamic || !input?.form) return;\n const formId = input.form.id;\n return alepha.events.on(\"form:changed\", (e) => {\n if (e.id === formId && e.path !== input.path) bump((n) => n + 1);\n });\n }, [alepha, input?.form, input?.path, isDynamic]);\n};\n\nconst resolveIcon = (\n icon: ControlProps[\"icon\"],\n fallback?: string | null,\n): IconComponent | undefined => {\n if (icon === null) return undefined;\n if (typeof icon === \"string\") return iconFor(icon);\n if (icon) return icon;\n return iconFor(fallback);\n};\n\nconst wrapWithSlots = (\n props: ControlProps & Partial<SchemaControl>,\n body: ReactNode,\n): ReactNode => {\n const top = (props.top as ReactNode) ?? null;\n const bottom = (props.bottom as ReactNode) ?? null;\n if (!top && !bottom) return body;\n return (\n <div className=\"flex flex-col gap-1\">\n {top}\n {body}\n {bottom}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwVA,MAAa,WAAW,UAAwB;CAC9C,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,SAAS,OAAO,CAAC;CACzD,MAAM,kBAAkB,qBAAqB;CAC7C,MAAM,YAAY,mBAAmB,MAAM;CAC3C,MAAM,CAAC,OAAO,YAAY,cAAc,MAAM,KAAK;CAInD,yBAAyB,MAAM,KAAK;CAEpC,IAAI,CAAC,MAAM,OAAO,OAAO,OAAO;CAEhC,MAAM,SAAS,WAAW,MAAM,OAAO;EACrC,OAAO,MAAM;EACb,aAAa,MAAM;EACnB,OAAO,KAAK;CACd,CAAC;CACD,MAAM,OAAO,MAAM,QAAQ;EAAE,GAAG;EAAQ,OAAO,MAAM;CAAM,IAAI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EACjE,CAAC;CACH,GAAG;EAAC;EAAQ,OAAO;EAAM,OAAO;EAAM;CAAS,CAAC;AAClD;AAEA,MAAM,eACJ,MACA,aAC8B;CAC9B,IAAI,SAAS,MAAM,OAAO,KAAA;CAC1B,IAAI,OAAO,SAAS,UAAU,OAAO,QAAQ,IAAI;CACjD,IAAI,MAAM,OAAO;CACjB,OAAO,QAAQ,QAAQ;AACzB;AAEA,MAAM,iBACJ,OACA,SACc;CACd,MAAM,MAAO,MAAM,OAAqB;CACxC,MAAM,SAAU,MAAM,UAAwB;CAC9C,IAAI,CAAC,OAAO,CAAC,QAAQ,OAAO;CAC5B,OACE,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACG;GACA;GACA;EACE;;AAET"}
@@ -38,7 +38,7 @@ const useArrayItems = (input) => {
38
38
  /**
39
39
  * Tell the CHILD paths what changed.
40
40
  *
41
- * `input.set()` writes the whole array and `FormModel` emits `form:change`
41
+ * `input.set()` writes the whole array and `FormModel` emits `form:changed`
42
42
  * for the array's own path only. The per-item and per-field inputs this
43
43
  * component builds carry paths of their own (`.../2/name`), so a child
44
44
  * subscribed through `useFieldValue` never heard about its own edit and
@@ -51,7 +51,7 @@ const useArrayItems = (input) => {
51
51
  const emitChanged = useCallback((prev, next) => {
52
52
  const form = input?.form;
53
53
  if (!form || !input) return;
54
- const emit = (path, value) => void alepha.events.emit("form:change", {
54
+ const emit = (path, value) => void alepha.events.emit("form:changed", {
55
55
  id: form.id,
56
56
  path,
57
57
  value
@@ -87,7 +87,7 @@ const useArrayItems = (input) => {
87
87
  if (!input?.form) return;
88
88
  const formId = input.form.id;
89
89
  const path = input.path;
90
- return alepha.events.on("form:change", (e) => {
90
+ return alepha.events.on("form:changed", (e) => {
91
91
  if (e.id === formId && e.path === path) sync(e.value);
92
92
  });
93
93
  }, [
@@ -168,7 +168,7 @@ const buildItemInput = (parent, schema, index, value, onChange) => ({
168
168
  const buildFieldInput = (parent, itemSchema, fieldName, index, itemValue, onFieldChange) => ({
169
169
  schema: z.schema.shape(itemSchema)[fieldName],
170
170
  path: `${parent.path}/${index}/${fieldName}`,
171
- required: z.schema.requiredKeys(itemSchema).includes(fieldName),
171
+ required: z.schema.requiredInputKeys(itemSchema).includes(fieldName),
172
172
  form: parent.form,
173
173
  initialValue: itemValue?.[fieldName],
174
174
  props: {
@@ -229,7 +229,7 @@ const ControlArray = (props) => {
229
229
  if (shape) {
230
230
  value = {};
231
231
  for (const [k, p] of Object.entries(z.schema.shape(shape))) {
232
- const def = z.schema.getDefault(p);
232
+ const def = z.schema.defaultValue(p);
233
233
  if (def !== void 0) value[k] = def;
234
234
  const literal = literalValueOf(p);
235
235
  if (literal !== void 0) value[k] = literal;