@alepha/ui 0.31.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.
- package/README.md +1 -1
- package/dist/account/AccountConnections.js +1 -1
- package/dist/account/AccountConnections.js.map +1 -1
- package/dist/account/AccountDeleteDialog.d.ts.map +1 -1
- package/dist/account/AccountDeleteDialog.js +17 -17
- package/dist/account/AccountDeleteDialog.js.map +1 -1
- package/dist/account/AccountKeys.js +2 -2
- package/dist/account/AccountKeys.js.map +1 -1
- package/dist/account/AccountMfaDialog.d.ts.map +1 -1
- package/dist/account/AccountMfaDialog.js +19 -25
- package/dist/account/AccountMfaDialog.js.map +1 -1
- package/dist/account/AccountPasswordDialog.d.ts.map +1 -1
- package/dist/account/AccountPasswordDialog.js +25 -24
- package/dist/account/AccountPasswordDialog.js.map +1 -1
- package/dist/account/AccountProfile.d.ts.map +1 -1
- package/dist/account/AccountProfile.js +17 -24
- package/dist/account/AccountProfile.js.map +1 -1
- package/dist/account/AccountSecurity.d.ts.map +1 -1
- package/dist/account/AccountSecurity.js +21 -19
- package/dist/account/AccountSecurity.js.map +1 -1
- package/dist/account/AccountSessions.js +1 -1
- package/dist/account/AccountSessions.js.map +1 -1
- package/dist/account/ApiKeyCreateDialog.d.ts.map +1 -1
- package/dist/account/ApiKeyCreateDialog.js +8 -12
- package/dist/account/ApiKeyCreateDialog.js.map +1 -1
- package/dist/admin/AdminFiles.js +1 -1
- package/dist/admin/AdminFiles.js.map +1 -1
- package/dist/admin/AdminJobs.js +1 -1
- package/dist/admin/AdminJobs.js.map +1 -1
- package/dist/admin/AdminKeys.js +1 -1
- package/dist/admin/AdminKeys.js.map +1 -1
- package/dist/admin/AdminParameters.d.ts.map +1 -1
- package/dist/admin/AdminParameters.js +7 -5
- package/dist/admin/AdminParameters.js.map +1 -1
- package/dist/admin/AdminParametersTreeFooterActions.d.ts +2 -2
- package/dist/admin/AdminParametersTreeFooterActions.d.ts.map +1 -1
- package/dist/admin/AdminParametersTreeFooterActions.js.map +1 -1
- package/dist/admin/AdminParametersTreePane.d.ts +2 -2
- package/dist/admin/AdminParametersTreePane.d.ts.map +1 -1
- package/dist/admin/AdminParametersTreePane.js.map +1 -1
- package/dist/admin/AdminRouter.d.ts +1 -3
- package/dist/admin/AdminRouter.d.ts.map +1 -1
- package/dist/admin/AdminRouter.js +2 -4
- package/dist/admin/AdminRouter.js.map +1 -1
- package/dist/admin/AdminSessions.js +1 -1
- package/dist/admin/AdminSessions.js.map +1 -1
- package/dist/admin/AdminUserAvatarControl.d.ts.map +1 -1
- package/dist/admin/AdminUserAvatarControl.js +9 -16
- package/dist/admin/AdminUserAvatarControl.js.map +1 -1
- package/dist/admin/AdminUserDetail.js +4 -4
- package/dist/admin/AdminUserDetail.js.map +1 -1
- package/dist/admin/AdminUsers.d.ts.map +1 -1
- package/dist/admin/AdminUsers.js +10 -12
- package/dist/admin/AdminUsers.js.map +1 -1
- package/dist/admin/AdminUsersRolesPicker.d.ts +5 -1
- package/dist/admin/AdminUsersRolesPicker.d.ts.map +1 -1
- package/dist/admin/AdminUsersRolesPicker.js +2 -3
- package/dist/admin/AdminUsersRolesPicker.js.map +1 -1
- package/dist/admin/analytics/QueryPanel.js +1 -1
- package/dist/admin/analytics/QueryPanel.js.map +1 -1
- package/dist/admin/useConfirmedAction.d.ts +8 -2
- package/dist/admin/useConfirmedAction.d.ts.map +1 -1
- package/dist/admin/useConfirmedAction.js +15 -4
- package/dist/admin/useConfirmedAction.js.map +1 -1
- package/dist/auth/AuthLogin.d.ts.map +1 -1
- package/dist/auth/AuthLogin.js +4 -4
- package/dist/auth/AuthLogin.js.map +1 -1
- package/dist/auth/AuthRegister.js.map +1 -1
- package/dist/form/AutoForm.js +1 -1
- package/dist/form/AutoForm.js.map +1 -1
- package/dist/form/Control.d.ts.map +1 -1
- package/dist/form/Control.js +11 -1
- package/dist/form/Control.js.map +1 -1
- package/dist/form/ControlArray.js +5 -5
- package/dist/form/ControlArray.js.map +1 -1
- package/dist/form/ControlSelect.js +2 -2
- package/dist/form/ControlSelect.js.map +1 -1
- package/dist/form/ControlUpload.d.ts +1 -1
- package/dist/form/ControlUpload.js.map +1 -1
- package/dist/i18n/fr/uiFr.d.ts.map +1 -1
- package/dist/i18n/fr/uiFr.js +0 -9
- package/dist/i18n/fr/uiFr.js.map +1 -1
- package/dist/organizations/MyOrganizationInvitations.js +2 -2
- package/dist/organizations/MyOrganizationInvitations.js.map +1 -1
- package/dist/organizations/OrganizationInviteDialog.js +1 -1
- package/dist/organizations/OrganizationInviteDialog.js.map +1 -1
- package/dist/organizations/OrganizationMembers.js +1 -1
- package/dist/organizations/OrganizationMembers.js.map +1 -1
- package/dist/organizations/OrganizationPendingInvitations.js +1 -1
- package/dist/organizations/OrganizationPendingInvitations.js.map +1 -1
- package/dist/organizations/OrganizationRanks.js +3 -3
- package/dist/organizations/OrganizationRanks.js.map +1 -1
- package/dist/organizations/useInviteOrganizationMember.d.ts +6 -1
- package/dist/organizations/useInviteOrganizationMember.d.ts.map +1 -1
- package/dist/organizations/useInviteOrganizationMember.js +13 -13
- package/dist/organizations/useInviteOrganizationMember.js.map +1 -1
- package/dist/organizations/useRevokeOrganizationInvitation.d.ts +7 -1
- package/dist/organizations/useRevokeOrganizationInvitation.d.ts.map +1 -1
- package/dist/organizations/useRevokeOrganizationInvitation.js +13 -2
- package/dist/organizations/useRevokeOrganizationInvitation.js.map +1 -1
- package/dist/shell/ButtonUser.d.ts +1 -2
- package/dist/shell/ButtonUser.d.ts.map +1 -1
- package/dist/shell/ButtonUser.js +14 -42
- package/dist/shell/ButtonUser.js.map +1 -1
- package/dist/shell/ButtonUserContent.d.ts +13 -0
- package/dist/shell/ButtonUserContent.d.ts.map +1 -0
- package/dist/shell/ButtonUserContent.js +52 -0
- package/dist/shell/ButtonUserContent.js.map +1 -0
- package/dist/shell/ButtonUserPlaceholder.d.ts +14 -0
- package/dist/shell/ButtonUserPlaceholder.d.ts.map +1 -0
- package/dist/shell/ButtonUserPlaceholder.js +17 -0
- package/dist/shell/ButtonUserPlaceholder.js.map +1 -0
- package/dist/styles.css +94 -0
- package/dist/table/DataTable.js +1 -1
- package/dist/table/DataTable.js.map +1 -1
- package/dist/table/DataTableFilterBar.js +2 -2
- package/dist/table/DataTableFilterBar.js.map +1 -1
- package/dist/table/dataTableBaseProps.d.ts +1 -1
- package/dist/table/dataTableTypes.d.ts +3 -3
- package/dist/table/dataTableTypes.d.ts.map +1 -1
- package/dist/table/useDataTableData.d.ts.map +1 -1
- package/dist/table/useDataTableData.js +3 -1
- package/dist/table/useDataTableData.js.map +1 -1
- package/dist/table/useDataTableRefresh.js +2 -2
- package/dist/table/useDataTableRefresh.js.map +1 -1
- package/dist/table/useDataTableSummary.d.ts.map +1 -1
- package/dist/table/useDataTableSummary.js +2 -1
- package/dist/table/useDataTableSummary.js.map +1 -1
- package/package.json +9 -9
- package/src/account/AccountConnections.tsx +1 -1
- package/src/account/AccountDeleteDialog.tsx +25 -31
- package/src/account/AccountKeys.tsx +2 -2
- package/src/account/AccountMfaDialog.tsx +33 -27
- package/src/account/AccountPasswordDialog.tsx +36 -39
- package/src/account/AccountProfile.tsx +29 -43
- package/src/account/AccountSecurity.tsx +57 -64
- package/src/account/AccountSessions.tsx +1 -1
- package/src/account/ApiKeyCreateDialog.tsx +12 -20
- package/src/account/__tests__/AccountRouter.spec.ts +2 -1
- package/src/admin/AdminFiles.tsx +1 -1
- package/src/admin/AdminJobs.tsx +1 -1
- package/src/admin/AdminKeys.tsx +1 -1
- package/src/admin/AdminParameters.tsx +7 -5
- package/src/admin/AdminParametersTreeFooterActions.tsx +2 -2
- package/src/admin/AdminParametersTreePane.tsx +2 -2
- package/src/admin/AdminRouter.tsx +2 -4
- package/src/admin/AdminSessions.tsx +1 -1
- package/src/admin/AdminUserAvatarControl.tsx +17 -22
- package/src/admin/AdminUserDetail.tsx +4 -4
- package/src/admin/AdminUsers.tsx +10 -12
- package/src/admin/AdminUsersRolesPicker.tsx +11 -4
- package/src/admin/__tests__/AdminRouter.spec.ts +3 -2
- package/src/admin/analytics/QueryPanel.tsx +1 -1
- package/src/admin/useConfirmedAction.tsx +24 -10
- package/src/auth/AuthLogin.tsx +10 -9
- package/src/auth/AuthRegister.tsx +2 -2
- package/src/form/AutoForm.tsx +1 -1
- package/src/form/Control.tsx +14 -1
- package/src/form/ControlArray.tsx +5 -5
- package/src/form/ControlSelect.tsx +2 -2
- package/src/form/ControlUpload.tsx +1 -1
- package/src/form/__tests__/ControlArrayChildChange.browser.spec.tsx +1 -1
- package/src/form/__tests__/ControlVerbatim.browser.spec.tsx +71 -0
- package/src/i18n/fr/uiFr.ts +0 -9
- package/src/organizations/MyOrganizationInvitations.tsx +2 -2
- package/src/organizations/OrganizationInviteDialog.tsx +1 -1
- package/src/organizations/OrganizationMembers.tsx +1 -1
- package/src/organizations/OrganizationPendingInvitations.tsx +1 -1
- package/src/organizations/OrganizationRanks.tsx +3 -3
- package/src/organizations/useInviteOrganizationMember.ts +22 -15
- package/src/organizations/useRevokeOrganizationInvitation.ts +23 -4
- package/src/shell/ButtonUser.tsx +14 -79
- package/src/shell/ButtonUserContent.tsx +92 -0
- package/src/shell/ButtonUserPlaceholder.tsx +25 -0
- package/src/shell/__tests__/ActionErrorToaster.browser.spec.tsx +1 -1
- package/src/shell/__tests__/ActionErrorToasterHandled.browser.spec.tsx +1 -2
- package/src/shell/__tests__/AppShell.pageCache.spec.tsx +67 -0
- package/src/styles.css +94 -0
- package/src/table/DataTable.tsx +1 -1
- package/src/table/DataTableFilterBar.tsx +2 -2
- package/src/table/__tests__/DataTableFilterDateRange.browser.spec.tsx +1 -1
- package/src/table/__tests__/DataTableQuerySeed.browser.spec.tsx +1 -1
- package/src/table/__tests__/DataTableShareFilters.browser.spec.tsx +1 -1
- package/src/table/dataTableBaseProps.ts +1 -1
- package/src/table/dataTableTypes.ts +3 -3
- package/src/table/useDataTableData.ts +2 -0
- package/src/table/useDataTableRefresh.ts +3 -3
- package/src/table/useDataTableSummary.ts +2 -1
|
@@ -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:
|
|
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:
|
|
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:
|
|
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.
|
|
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.
|
|
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;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlArray.js","names":[],"sources":["../../src/form/ControlArray.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 {\n type BaseInputField,\n parseField,\n unionVariants,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n ArrowDown,\n ArrowUp,\n ChevronDown,\n ChevronRight,\n Plus,\n Trash2,\n} from \"lucide-react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { Control, type ControlProps } from \"./Control.tsx\";\nimport { childI18nPrefix, resolveFieldI18n } from \"./fieldI18n.ts\";\n\ninterface ArrayItem {\n key: number;\n value: unknown;\n}\n\nexport interface ControlArrayProps {\n /**\n * Bound array `InputField` from `useForm`.\n */\n input: BaseInputField;\n /**\n * Dictionary prefix for the item fields: each reads `<prefix>.<field>` and\n * `<prefix>.<field>.desc` (the index is not part of the key — every row of\n * the list shares one label).\n */\n i18nPrefix?: string;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the array.\n */\n description?: string;\n /**\n * Minimum number of items (Add button disables when reached).\n */\n min?: number;\n /**\n * Maximum number of items (Add button disables when reached).\n */\n max?: number;\n /**\n * Override the \"Add item\" button label.\n */\n addLabel?: string;\n /**\n * Number of grid columns for each item's inner fields.\n */\n columns?: 1 | 2 | 3 | 4;\n /**\n * \"fieldset\" wraps in a bordered container with legend; \"plain\" renders items only.\n */\n variant?: \"fieldset\" | \"plain\";\n /**\n * Per-field `<Control>` overrides for items, keyed by inner field name.\n */\n controlProps?: Record<string, Partial<Omit<ControlProps, \"input\">>>;\n /**\n * Override props applied to every item (when items are primitive, not objects).\n */\n itemControlProps?: Partial<Omit<ControlProps, \"input\">>;\n /**\n * Disable add/remove and all inner controls.\n */\n disabled?: boolean;\n\n /**\n * Default expanded state. @default true\n */\n defaultExpanded?: boolean;\n\n /**\n * Confirm before deleting an item. Pass `true` for default copy or an\n * object to override title/message.\n */\n confirmDelete?: boolean | { title?: string; message?: string };\n\n /**\n * Compute the visible label for each item header (and tab name in tabs mode).\n */\n renderTabName?: (i: number, value: unknown) => string;\n\n /**\n * Force tabs mode even for short arrays. Default heuristic: items > 4 OR nested object/array fields.\n */\n forceTabs?: boolean;\n}\n\nconst colsClass: Record<number, string> = {\n 1: \"grid-cols-1\",\n 2: \"grid-cols-2\",\n 3: \"grid-cols-3\",\n 4: \"grid-cols-4\",\n};\n\n/**\n * The keys of a plain object, or nothing.\n *\n * An item that is not an object has no per-field inputs, so there is nothing\n * below it to notify.\n */\nconst objectKeys = (value: unknown): string[] =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? Object.keys(value as Record<string, unknown>)\n : [];\n\nconst useArrayItems = (input: BaseInputField | undefined) => {\n const alepha = useAlepha();\n const counter = useRef(0);\n const [items, setItemsState] = useState<ArrayItem[]>(() => {\n const initial = input?.initialValue;\n return Array.isArray(initial)\n ? initial.map((value) => ({ key: counter.current++, value }))\n : [];\n });\n\n // The list as last rendered, so a write can diff against it without\n // `setItems` depending on `items` (which would rebuild the callback, and\n // with it every row, on each keystroke).\n const itemsRef = useRef(items);\n itemsRef.current = items;\n\n /**\n * Tell the CHILD paths what changed.\n *\n * `input.set()` writes the whole array and `FormModel` emits `form:change`\n * for the array's own path only. The per-item and per-field inputs this\n * component builds carry paths of their own (`.../2/name`), so a child\n * subscribed through `useFieldValue` never heard about its own edit and\n * kept re-rendering the value it had at mount.\n *\n * Only what actually differs is emitted: this event is how a row avoids\n * re-rendering when a sibling changes, and announcing every path on every\n * keystroke would give that up.\n */\n const emitChanged = useCallback(\n (prev: ArrayItem[], next: ArrayItem[]) => {\n const form = input?.form;\n if (!form || !input) return;\n\n const emit = (path: string, value: unknown) =>\n void alepha.events.emit(\n \"form:change\",\n { id: form.id, path, value },\n { catch: true },\n );\n\n for (let i = 0; i < Math.max(prev.length, next.length); i++) {\n const before = prev[i]?.value;\n const after = next[i]?.value;\n if (before === after) continue;\n\n emit(`${input.path}/${i}`, after);\n\n for (const key of new Set([\n ...objectKeys(before),\n ...objectKeys(after),\n ])) {\n const beforeField = (before as Record<string, unknown>)?.[key];\n const afterField = (after as Record<string, unknown>)?.[key];\n if (beforeField !== afterField) {\n emit(`${input.path}/${i}/${key}`, afterField);\n }\n }\n }\n },\n [alepha, input],\n );\n\n const sync = useCallback(\n (next: unknown[] | undefined) => {\n if (!Array.isArray(next)) {\n emitChanged(itemsRef.current, []);\n setItemsState([]);\n return;\n }\n if (\n itemsRef.current.length === next.length &&\n itemsRef.current.every((it, i) => it.value === next[i])\n ) {\n return;\n }\n counter.current = 0;\n const rebuilt = next.map((value) => ({ key: counter.current++, value }));\n // A reset or a `setInitialValues` writes the array whole, so the child\n // paths need telling here too - same reason as an edit.\n emitChanged(itemsRef.current, rebuilt);\n setItemsState(rebuilt);\n },\n [emitChanged],\n );\n\n useEffect(() => {\n if (!input?.form) return;\n const formId = input.form.id;\n const path = input.path;\n return alepha.events.on(\"form:change\", (e) => {\n if (e.id === formId && e.path === path) sync(e.value as unknown[]);\n });\n }, [alepha, input, sync]);\n\n const setItems = useCallback(\n (next: ArrayItem[]) => {\n const prev = itemsRef.current;\n setItemsState(next);\n input?.set(next.map((it) => it.value));\n emitChanged(prev, next);\n },\n [input, emitChanged],\n );\n\n return { items, setItems, nextKey: () => counter.current++ };\n};\n\n/**\n * Discriminated-union support for item schemas.\n *\n * `z.array(z.union([...objects]))` is how a heterogeneous list is spelled. The\n * variants almost always differ by one literal property (`kind`, `type`, …),\n * which is enough to (a) tell which variant an existing item is and (b) label\n * the choice offered when adding one. Everything below degrades quietly: no\n * union, or no discriminant, and the array behaves exactly as before.\n */\nconst objectVariants = (itemSchema: ZType): ZObject[] | null => {\n const variants = unionVariants(itemSchema);\n if (!variants?.length) return null;\n const objects = variants\n .map((variant) => z.schema.unwrap(variant))\n .filter((variant) => z.schema.isObject(variant)) as ZObject[];\n return objects.length === variants.length ? objects : null;\n};\n\n/**\n * The property whose value identifies the variant (a literal in every variant).\n */\nconst discriminantOf = (variants: ZObject[]): string | null => {\n const [first] = variants;\n if (!first) return null;\n for (const name of Object.keys(z.schema.shape(first))) {\n const values = variants.map((variant) =>\n literalValueOf(z.schema.shape(variant)[name]),\n );\n if (values.every((value) => typeof value === \"string\")) {\n const unique = new Set(values as string[]);\n if (unique.size === variants.length) return name;\n }\n }\n return null;\n};\n\n/**\n * The single allowed value of a literal/const schema, if it is one.\n */\nconst literalValueOf = (schema: unknown): unknown => {\n if (!schema) return undefined;\n const inner = z.schema.unwrap(schema as ZType) as {\n const?: unknown;\n values?: unknown[] | Set<unknown>;\n _zod?: { def?: { values?: unknown[] } };\n };\n if (inner?.const !== undefined) return inner.const;\n // zod spells a literal's allowed values as `_zod.def.values` (an array);\n // the public `.values` is a Set, so normalise both.\n const raw = inner?._zod?.def?.values ?? inner?.values;\n const values =\n raw instanceof Set ? [...raw] : Array.isArray(raw) ? raw : undefined;\n return values?.length === 1 ? values[0] : undefined;\n};\n\n/**\n * Label for a variant: its discriminant value, else its index.\n */\nconst variantLabel = (\n variant: ZObject,\n discriminant: string | null,\n index: number,\n): string => {\n const value = discriminant\n ? literalValueOf(z.schema.shape(variant)[discriminant])\n : undefined;\n return typeof value === \"string\" ? value : `#${index + 1}`;\n};\n\nconst buildItemInput = (\n parent: BaseInputField,\n schema: ZType,\n index: number,\n value: unknown,\n onChange: (v: unknown) => void,\n): BaseInputField => ({\n schema,\n path: `${parent.path}/${index}`,\n required: false,\n form: parent.form,\n initialValue: value,\n props: {\n id: `${parent.props.id}-${index}`,\n name: `${parent.props.name}[${index}]`,\n },\n set: onChange,\n});\n\nconst buildFieldInput = (\n parent: BaseInputField,\n itemSchema: ZObject,\n fieldName: string,\n index: number,\n itemValue: Record<string, unknown> | undefined,\n onFieldChange: (field: string, value: unknown) => void,\n): BaseInputField => ({\n schema: z.schema.shape(itemSchema)[fieldName],\n path: `${parent.path}/${index}/${fieldName}`,\n required: z.schema.requiredKeys(itemSchema).includes(fieldName),\n form: parent.form,\n initialValue: itemValue?.[fieldName],\n props: {\n id: `${parent.props.id}-${index}-${fieldName}`,\n name: `${parent.props.name}[${index}].${fieldName}`,\n },\n set: (v: unknown) => onFieldChange(fieldName, v),\n});\n\nexport const ControlArray = (props: ControlArrayProps) => {\n const form = useFormState(props.input, [\"error\"]);\n const { tr } = useI18n();\n const { items, setItems, nextKey } = useArrayItems(props.input);\n const [expanded, setExpanded] = useState(props.defaultExpanded ?? true);\n const [activeTab, setActiveTab] = useState(0);\n const [pendingDelete, setPendingDelete] = useState<number | null>(null);\n\n if (!props.input?.props) return null;\n\n const meta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const schema = props.input.schema;\n // `isArray`, not `\"items\" in schema`: that spelling tested for a prototype\n // alias rather than for an array schema, so it answered false once the alias\n // went away — and the whole control rendered nothing, Add button included.\n if (!z.schema.isArray(schema)) return null;\n\n // `z.schema.element`, not `.items`: the latter only ever resolved through a\n // prototype alias on ZodArray, so it silently became `undefined` — and with\n // no item schema the control renders neither fields nor tabs.\n const itemSchema = z.schema.element(schema) as ZType;\n const variants = objectVariants(itemSchema);\n const discriminant = variants ? discriminantOf(variants) : null;\n\n /**\n * The object schema to edit an item with. For a union that is the variant the\n * item's discriminant points at (first variant as a fallback, e.g. a freshly\n * added item), so each row renders exactly its own fields.\n */\n const schemaForValue = (value: unknown): ZObject | null => {\n if (!variants) {\n // `isObject`, not `\"properties\" in itemSchema`: the latter tested for a\n // prototype alias, so it answered false as soon as the alias went away.\n return z.schema.isObject(itemSchema) ? (itemSchema as ZObject) : null;\n }\n if (discriminant && value && typeof value === \"object\") {\n const tag = (value as Record<string, unknown>)[discriminant];\n const match = variants.find(\n (variant) =>\n literalValueOf(z.schema.shape(variant)[discriminant]) === tag,\n );\n if (match) return match;\n }\n return variants[0] ?? null;\n };\n\n const objectItemSchema = schemaForValue(items[0]?.value);\n const fieldNames = objectItemSchema\n ? Object.keys(z.schema.shape(objectItemSchema))\n : [];\n\n // Schema-driven max/min if present: `z.array().max(3)` lands in zod's\n // constraint bag, the JSON-schema `maxItems` names never existed here.\n const bounds =\n (z.schema.unwrap(schema) as { _zod?: { bag?: Record<string, unknown> } })\n ._zod?.bag ?? {};\n const schemaMax =\n typeof bounds.maximum === \"number\" ? bounds.maximum : undefined;\n const schemaMin =\n typeof bounds.minimum === \"number\" ? bounds.minimum : undefined;\n const min = props.min ?? schemaMin ?? 0;\n const max = props.max ?? schemaMax ?? Number.POSITIVE_INFINITY;\n const columns = props.columns ?? 1;\n\n // Tabs heuristic: forced or nested complex item or many items\n const hasComplexFields = objectItemSchema\n ? fieldNames.some((n) => {\n const inner = z.schema.unwrap(z.schema.shape(objectItemSchema)[n]);\n return z.schema.isObject(inner) || z.schema.isArray(inner);\n })\n : false;\n const useTabs =\n props.forceTabs ||\n (objectItemSchema && (items.length > 4 || hasComplexFields));\n\n const handleAdd = (variantIndex = 0) => {\n if (items.length >= max) return;\n const shape = variants ? variants[variantIndex] : objectItemSchema;\n let value: unknown;\n if (shape) {\n value = {};\n for (const [k, p] of Object.entries(z.schema.shape(shape))) {\n const def = z.schema.getDefault(p);\n if (def !== undefined) (value as Record<string, unknown>)[k] = def;\n // Stamp the discriminant so the new item resolves to its variant.\n const literal = literalValueOf(p);\n if (literal !== undefined)\n (value as Record<string, unknown>)[k] = literal;\n }\n } else {\n value = \"\";\n }\n setItems([...items, { key: nextKey(), value }]);\n if (useTabs) setActiveTab(items.length);\n };\n\n const handleRemove = (index: number) => {\n if (items.length <= min) return;\n if (props.confirmDelete) {\n setPendingDelete(index);\n return;\n }\n doRemove(index);\n };\n\n const doRemove = (index: number) => {\n setItems(items.filter((_, i) => i !== index));\n if (useTabs)\n setActiveTab(Math.max(0, Math.min(activeTab, items.length - 2)));\n };\n\n const handleMove = (index: number, direction: -1 | 1) => {\n const target = index + direction;\n if (target < 0 || target >= items.length) return;\n const next = [...items];\n [next[index], next[target]] = [next[target], next[index]];\n setItems(next);\n if (useTabs) setActiveTab(target);\n };\n\n const updateItem = (index: number, value: unknown) => {\n const next = [...items];\n next[index] = { ...next[index], value };\n setItems(next);\n };\n\n const updateField = (index: number, field: string, value: unknown) => {\n const next = [...items];\n const current = (next[index].value as Record<string, unknown>) ?? {};\n next[index] = { ...next[index], value: { ...current, [field]: value } };\n setItems(next);\n };\n\n const tabName = (i: number): string => {\n if (props.renderTabName) {\n try {\n return props.renderTabName(i, items[i]?.value);\n } catch {\n // fall through\n }\n }\n const value = items[i]?.value as Record<string, unknown> | undefined;\n const tag = discriminant ? value?.[discriminant] : undefined;\n if (typeof tag === \"string\") return `${tag} #${i + 1}`;\n return `${meta.label} #${i + 1}`;\n };\n\n const renderItemBody = (item: ArrayItem, index: number) => {\n // Resolved per item: in a union each row may be a different variant.\n const itemObjectSchema = schemaForValue(item.value);\n const itemFieldNames = itemObjectSchema\n ? Object.keys(z.schema.shape(itemObjectSchema))\n : [];\n return itemObjectSchema ? (\n <div className={`grid gap-3 ${colsClass[columns]}`}>\n {itemFieldNames.map((name) => {\n const fieldProps = {\n ...props.controlProps?.[name],\n ...resolveFieldI18n(\n tr as never,\n props.i18nPrefix,\n name,\n props.controlProps?.[name] ?? {},\n ),\n i18nPrefix: childI18nPrefix(props.i18nPrefix, name),\n };\n // The discriminant decides the item's SHAPE — editing it would\n // invalidate every sibling field, so it is shown read-only.\n const isDiscriminant = !!variants && name === discriminant;\n const fieldInput = buildFieldInput(\n props.input,\n itemObjectSchema,\n name,\n index,\n item.value as Record<string, unknown>,\n (f, v) => updateField(index, f, v),\n );\n return (\n <Control\n key={name}\n input={fieldInput}\n disabled={props.disabled || isDiscriminant}\n {...fieldProps}\n />\n );\n })}\n </div>\n ) : (\n <Control\n input={buildItemInput(props.input, itemSchema, index, item.value, (v) =>\n updateItem(index, v),\n )}\n disabled={props.disabled}\n {...props.itemControlProps}\n />\n );\n };\n\n const itemActions = (index: number) => (\n <div className=\"flex shrink-0 flex-col gap-1\">\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={props.disabled || index === 0 || items.length < 2}\n onClick={() => handleMove(index, -1)}\n aria-label={tr(\"controlArray.moveUp\", { default: \"Move up\" })}\n >\n <ArrowUp className=\"size-3.5\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={props.disabled || items.length <= min}\n onClick={() => handleRemove(index)}\n aria-label={tr(\"controlArray.remove\", { default: \"Remove\" })}\n >\n <Trash2 className=\"size-3.5\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={\n props.disabled || index === items.length - 1 || items.length < 2\n }\n onClick={() => handleMove(index, 1)}\n aria-label={tr(\"controlArray.moveDown\", { default: \"Move down\" })}\n >\n <ArrowDown className=\"size-3.5\" />\n </Button>\n </div>\n );\n\n const flatList = (\n <div className=\"flex flex-col gap-2\">\n {items.map((item, index) => (\n <div\n key={item.key}\n className=\"bg-muted/30 flex items-start gap-2 rounded-md border p-3\"\n >\n <div className=\"min-w-0 flex-1\">{renderItemBody(item, index)}</div>\n {itemActions(index)}\n </div>\n ))}\n </div>\n );\n\n const tabs = useTabs && items.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex flex-wrap gap-1 border-b pb-1\">\n {items.map((item, i) => (\n <Button\n key={item.key}\n type=\"button\"\n variant={i === activeTab ? \"solid\" : \"minimal\"}\n size=\"sm\"\n onClick={() => setActiveTab(i)}\n >\n {tabName(i)}\n </Button>\n ))}\n </div>\n {items[activeTab] && (\n <div className=\"bg-muted/30 flex items-start gap-2 rounded-md border p-3\">\n <div className=\"min-w-0 flex-1\">\n {renderItemBody(items[activeTab], activeTab)}\n </div>\n {itemActions(activeTab)}\n </div>\n )}\n </div>\n );\n\n const list = (\n <div className=\"flex flex-col gap-2\">{useTabs ? tabs : flatList}</div>\n );\n\n const headerControls = (\n <div className=\"flex items-start gap-3\">\n {variants && variants.length > 1 ? (\n // A union offers a choice of shapes: one Add button per variant,\n // labelled by its discriminant (\"single\", \"period_pass\", …).\n <div className=\"flex shrink-0 flex-wrap gap-1\">\n {variants.map((variant, index) => (\n <Button\n key={variantLabel(variant, discriminant, index)}\n type=\"button\"\n variant=\"outlined\"\n size=\"sm\"\n className=\"h-8\"\n disabled={props.disabled || items.length >= max}\n onClick={() => handleAdd(index)}\n >\n <Plus className=\"size-3.5\" />\n {variantLabel(variant, discriminant, index)}\n </Button>\n ))}\n </div>\n ) : (\n <Button\n type=\"button\"\n variant=\"outlined\"\n size=\"icon\"\n className=\"size-8 shrink-0\"\n disabled={props.disabled || items.length >= max}\n onClick={() => handleAdd()}\n aria-label={\n props.addLabel ?? tr(\"controlArray.add\", { default: \"Add\" })\n }\n >\n <Plus className=\"size-4\" />\n </Button>\n )}\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <div className=\"text-sm leading-tight font-medium\">\n {meta.label}\n {meta.required && <span className=\"text-danger-text ml-0.5\">*</span>}\n <span className=\"text-muted-foreground ml-2 text-xs\">\n ({items.length})\n </span>\n </div>\n {meta.description && (\n <p className=\"text-muted-foreground text-xs leading-tight\">\n {meta.description}\n </p>\n )}\n {meta.error && (\n <p className=\"text-danger-text text-xs leading-tight\">{meta.error}</p>\n )}\n </div>\n {items.length > 0 && (\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-8 shrink-0\"\n aria-label={\n expanded\n ? tr(\"controlArray.collapse\", { default: \"Collapse\" })\n : tr(\"controlArray.expand\", { default: \"Expand\" })\n }\n onClick={() => setExpanded((e) => !e)}\n >\n {expanded ? (\n <ChevronDown className=\"size-4\" />\n ) : (\n <ChevronRight className=\"size-4\" />\n )}\n </Button>\n )}\n </div>\n );\n\n const confirmContent = (() => {\n if (pendingDelete == null) return null;\n const cd = props.confirmDelete;\n const title =\n typeof cd === \"object\"\n ? (cd.title ??\n tr(\"controlArray.deleteTitle\", { default: \"Delete item\" }))\n : tr(\"controlArray.deleteTitle\", { default: \"Delete item\" });\n const message =\n typeof cd === \"object\"\n ? (cd.message ??\n tr(\"controlArray.deleteConfirm\", {\n default: \"Are you sure you want to delete this item?\",\n }))\n : tr(\"controlArray.deleteConfirm\", {\n default: \"Are you sure you want to delete this item?\",\n });\n return (\n <Dialog\n open={pendingDelete != null}\n onOpenChange={(v) => !v && setPendingDelete(null)}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n <DialogDescription>{message}</DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button variant=\"minimal\" onClick={() => setPendingDelete(null)}>\n {tr(\"controlArray.cancel\", { default: \"Cancel\" })}\n </Button>\n <Button\n variant=\"outlined\"\n intent=\"danger\"\n onClick={() => {\n doRemove(pendingDelete);\n setPendingDelete(null);\n }}\n >\n {tr(\"controlArray.delete\", { default: \"Delete\" })}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n })();\n\n if (props.variant === \"plain\") {\n return (\n <div className=\"flex flex-col gap-2\">\n {headerControls}\n {expanded && items.length > 0 && list}\n {confirmContent}\n </div>\n );\n }\n\n return (\n <fieldset\n className={`rounded-md border p-3 ${\n meta.error ? \"border-danger\" : \"border-border\"\n }`}\n >\n {headerControls}\n {expanded && items.length > 0 && <div className=\"mt-3\">{list}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A,GAAG,uBAAuB,EAAE,SAAS,SAAS,CAAC;GAC1C,CAAA,CACI,EAAA,CAAA,CACD,EAAA,CAAA;EACT,CAAA;CAEZ,EAAA,CAAG;CAEH,IAAI,MAAM,YAAY,SACpB,OACE,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACG;GACA,YAAY,MAAM,SAAS,KAAK;GAChC;EACE;;CAIT,OACE,qBAAC,YAAD;EACE,WAAW,yBACT,KAAK,QAAQ,kBAAkB;EAFnC,UAAA;GAKG;GACA,YAAY,MAAM,SAAS,KAAK,oBAAC,OAAD;IAAK,WAAU;IAAQ,UAAA;GAAU,CAAA;GACjE;EACO;;AAEd"}
|
|
1
|
+
{"version":3,"file":"ControlArray.js","names":[],"sources":["../../src/form/ControlArray.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 {\n type BaseInputField,\n parseField,\n unionVariants,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n ArrowDown,\n ArrowUp,\n ChevronDown,\n ChevronRight,\n Plus,\n Trash2,\n} from \"lucide-react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { Control, type ControlProps } from \"./Control.tsx\";\nimport { childI18nPrefix, resolveFieldI18n } from \"./fieldI18n.ts\";\n\ninterface ArrayItem {\n key: number;\n value: unknown;\n}\n\nexport interface ControlArrayProps {\n /**\n * Bound array `InputField` from `useForm`.\n */\n input: BaseInputField;\n /**\n * Dictionary prefix for the item fields: each reads `<prefix>.<field>` and\n * `<prefix>.<field>.desc` (the index is not part of the key — every row of\n * the list shares one label).\n */\n i18nPrefix?: string;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the array.\n */\n description?: string;\n /**\n * Minimum number of items (Add button disables when reached).\n */\n min?: number;\n /**\n * Maximum number of items (Add button disables when reached).\n */\n max?: number;\n /**\n * Override the \"Add item\" button label.\n */\n addLabel?: string;\n /**\n * Number of grid columns for each item's inner fields.\n */\n columns?: 1 | 2 | 3 | 4;\n /**\n * \"fieldset\" wraps in a bordered container with legend; \"plain\" renders items only.\n */\n variant?: \"fieldset\" | \"plain\";\n /**\n * Per-field `<Control>` overrides for items, keyed by inner field name.\n */\n controlProps?: Record<string, Partial<Omit<ControlProps, \"input\">>>;\n /**\n * Override props applied to every item (when items are primitive, not objects).\n */\n itemControlProps?: Partial<Omit<ControlProps, \"input\">>;\n /**\n * Disable add/remove and all inner controls.\n */\n disabled?: boolean;\n\n /**\n * Default expanded state. @default true\n */\n defaultExpanded?: boolean;\n\n /**\n * Confirm before deleting an item. Pass `true` for default copy or an\n * object to override title/message.\n */\n confirmDelete?: boolean | { title?: string; message?: string };\n\n /**\n * Compute the visible label for each item header (and tab name in tabs mode).\n */\n renderTabName?: (i: number, value: unknown) => string;\n\n /**\n * Force tabs mode even for short arrays. Default heuristic: items > 4 OR nested object/array fields.\n */\n forceTabs?: boolean;\n}\n\nconst colsClass: Record<number, string> = {\n 1: \"grid-cols-1\",\n 2: \"grid-cols-2\",\n 3: \"grid-cols-3\",\n 4: \"grid-cols-4\",\n};\n\n/**\n * The keys of a plain object, or nothing.\n *\n * An item that is not an object has no per-field inputs, so there is nothing\n * below it to notify.\n */\nconst objectKeys = (value: unknown): string[] =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? Object.keys(value as Record<string, unknown>)\n : [];\n\nconst useArrayItems = (input: BaseInputField | undefined) => {\n const alepha = useAlepha();\n const counter = useRef(0);\n const [items, setItemsState] = useState<ArrayItem[]>(() => {\n const initial = input?.initialValue;\n return Array.isArray(initial)\n ? initial.map((value) => ({ key: counter.current++, value }))\n : [];\n });\n\n // The list as last rendered, so a write can diff against it without\n // `setItems` depending on `items` (which would rebuild the callback, and\n // with it every row, on each keystroke).\n const itemsRef = useRef(items);\n itemsRef.current = items;\n\n /**\n * Tell the CHILD paths what changed.\n *\n * `input.set()` writes the whole array and `FormModel` emits `form:changed`\n * for the array's own path only. The per-item and per-field inputs this\n * component builds carry paths of their own (`.../2/name`), so a child\n * subscribed through `useFieldValue` never heard about its own edit and\n * kept re-rendering the value it had at mount.\n *\n * Only what actually differs is emitted: this event is how a row avoids\n * re-rendering when a sibling changes, and announcing every path on every\n * keystroke would give that up.\n */\n const emitChanged = useCallback(\n (prev: ArrayItem[], next: ArrayItem[]) => {\n const form = input?.form;\n if (!form || !input) return;\n\n const emit = (path: string, value: unknown) =>\n void alepha.events.emit(\n \"form:changed\",\n { id: form.id, path, value },\n { catch: true },\n );\n\n for (let i = 0; i < Math.max(prev.length, next.length); i++) {\n const before = prev[i]?.value;\n const after = next[i]?.value;\n if (before === after) continue;\n\n emit(`${input.path}/${i}`, after);\n\n for (const key of new Set([\n ...objectKeys(before),\n ...objectKeys(after),\n ])) {\n const beforeField = (before as Record<string, unknown>)?.[key];\n const afterField = (after as Record<string, unknown>)?.[key];\n if (beforeField !== afterField) {\n emit(`${input.path}/${i}/${key}`, afterField);\n }\n }\n }\n },\n [alepha, input],\n );\n\n const sync = useCallback(\n (next: unknown[] | undefined) => {\n if (!Array.isArray(next)) {\n emitChanged(itemsRef.current, []);\n setItemsState([]);\n return;\n }\n if (\n itemsRef.current.length === next.length &&\n itemsRef.current.every((it, i) => it.value === next[i])\n ) {\n return;\n }\n counter.current = 0;\n const rebuilt = next.map((value) => ({ key: counter.current++, value }));\n // A reset or a `setInitialValues` writes the array whole, so the child\n // paths need telling here too - same reason as an edit.\n emitChanged(itemsRef.current, rebuilt);\n setItemsState(rebuilt);\n },\n [emitChanged],\n );\n\n useEffect(() => {\n if (!input?.form) return;\n const formId = input.form.id;\n const path = input.path;\n return alepha.events.on(\"form:changed\", (e) => {\n if (e.id === formId && e.path === path) sync(e.value as unknown[]);\n });\n }, [alepha, input, sync]);\n\n const setItems = useCallback(\n (next: ArrayItem[]) => {\n const prev = itemsRef.current;\n setItemsState(next);\n input?.set(next.map((it) => it.value));\n emitChanged(prev, next);\n },\n [input, emitChanged],\n );\n\n return { items, setItems, nextKey: () => counter.current++ };\n};\n\n/**\n * Discriminated-union support for item schemas.\n *\n * `z.array(z.union([...objects]))` is how a heterogeneous list is spelled. The\n * variants almost always differ by one literal property (`kind`, `type`, …),\n * which is enough to (a) tell which variant an existing item is and (b) label\n * the choice offered when adding one. Everything below degrades quietly: no\n * union, or no discriminant, and the array behaves exactly as before.\n */\nconst objectVariants = (itemSchema: ZType): ZObject[] | null => {\n const variants = unionVariants(itemSchema);\n if (!variants?.length) return null;\n const objects = variants\n .map((variant) => z.schema.unwrap(variant))\n .filter((variant) => z.schema.isObject(variant)) as ZObject[];\n return objects.length === variants.length ? objects : null;\n};\n\n/**\n * The property whose value identifies the variant (a literal in every variant).\n */\nconst discriminantOf = (variants: ZObject[]): string | null => {\n const [first] = variants;\n if (!first) return null;\n for (const name of Object.keys(z.schema.shape(first))) {\n const values = variants.map((variant) =>\n literalValueOf(z.schema.shape(variant)[name]),\n );\n if (values.every((value) => typeof value === \"string\")) {\n const unique = new Set(values as string[]);\n if (unique.size === variants.length) return name;\n }\n }\n return null;\n};\n\n/**\n * The single allowed value of a literal/const schema, if it is one.\n */\nconst literalValueOf = (schema: unknown): unknown => {\n if (!schema) return undefined;\n const inner = z.schema.unwrap(schema as ZType) as {\n const?: unknown;\n values?: unknown[] | Set<unknown>;\n _zod?: { def?: { values?: unknown[] } };\n };\n if (inner?.const !== undefined) return inner.const;\n // zod spells a literal's allowed values as `_zod.def.values` (an array);\n // the public `.values` is a Set, so normalise both.\n const raw = inner?._zod?.def?.values ?? inner?.values;\n const values =\n raw instanceof Set ? [...raw] : Array.isArray(raw) ? raw : undefined;\n return values?.length === 1 ? values[0] : undefined;\n};\n\n/**\n * Label for a variant: its discriminant value, else its index.\n */\nconst variantLabel = (\n variant: ZObject,\n discriminant: string | null,\n index: number,\n): string => {\n const value = discriminant\n ? literalValueOf(z.schema.shape(variant)[discriminant])\n : undefined;\n return typeof value === \"string\" ? value : `#${index + 1}`;\n};\n\nconst buildItemInput = (\n parent: BaseInputField,\n schema: ZType,\n index: number,\n value: unknown,\n onChange: (v: unknown) => void,\n): BaseInputField => ({\n schema,\n path: `${parent.path}/${index}`,\n required: false,\n form: parent.form,\n initialValue: value,\n props: {\n id: `${parent.props.id}-${index}`,\n name: `${parent.props.name}[${index}]`,\n },\n set: onChange,\n});\n\nconst buildFieldInput = (\n parent: BaseInputField,\n itemSchema: ZObject,\n fieldName: string,\n index: number,\n itemValue: Record<string, unknown> | undefined,\n onFieldChange: (field: string, value: unknown) => void,\n): BaseInputField => ({\n schema: z.schema.shape(itemSchema)[fieldName],\n path: `${parent.path}/${index}/${fieldName}`,\n required: z.schema.requiredInputKeys(itemSchema).includes(fieldName),\n form: parent.form,\n initialValue: itemValue?.[fieldName],\n props: {\n id: `${parent.props.id}-${index}-${fieldName}`,\n name: `${parent.props.name}[${index}].${fieldName}`,\n },\n set: (v: unknown) => onFieldChange(fieldName, v),\n});\n\nexport const ControlArray = (props: ControlArrayProps) => {\n const form = useFormState(props.input, [\"error\"]);\n const { tr } = useI18n();\n const { items, setItems, nextKey } = useArrayItems(props.input);\n const [expanded, setExpanded] = useState(props.defaultExpanded ?? true);\n const [activeTab, setActiveTab] = useState(0);\n const [pendingDelete, setPendingDelete] = useState<number | null>(null);\n\n if (!props.input?.props) return null;\n\n const meta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const schema = props.input.schema;\n // `isArray`, not `\"items\" in schema`: that spelling tested for a prototype\n // alias rather than for an array schema, so it answered false once the alias\n // went away — and the whole control rendered nothing, Add button included.\n if (!z.schema.isArray(schema)) return null;\n\n // `z.schema.element`, not `.items`: the latter only ever resolved through a\n // prototype alias on ZodArray, so it silently became `undefined` — and with\n // no item schema the control renders neither fields nor tabs.\n const itemSchema = z.schema.element(schema) as ZType;\n const variants = objectVariants(itemSchema);\n const discriminant = variants ? discriminantOf(variants) : null;\n\n /**\n * The object schema to edit an item with. For a union that is the variant the\n * item's discriminant points at (first variant as a fallback, e.g. a freshly\n * added item), so each row renders exactly its own fields.\n */\n const schemaForValue = (value: unknown): ZObject | null => {\n if (!variants) {\n // `isObject`, not `\"properties\" in itemSchema`: the latter tested for a\n // prototype alias, so it answered false as soon as the alias went away.\n return z.schema.isObject(itemSchema) ? (itemSchema as ZObject) : null;\n }\n if (discriminant && value && typeof value === \"object\") {\n const tag = (value as Record<string, unknown>)[discriminant];\n const match = variants.find(\n (variant) =>\n literalValueOf(z.schema.shape(variant)[discriminant]) === tag,\n );\n if (match) return match;\n }\n return variants[0] ?? null;\n };\n\n const objectItemSchema = schemaForValue(items[0]?.value);\n const fieldNames = objectItemSchema\n ? Object.keys(z.schema.shape(objectItemSchema))\n : [];\n\n // Schema-driven max/min if present: `z.array().max(3)` lands in zod's\n // constraint bag, the JSON-schema `maxItems` names never existed here.\n const bounds =\n (z.schema.unwrap(schema) as { _zod?: { bag?: Record<string, unknown> } })\n ._zod?.bag ?? {};\n const schemaMax =\n typeof bounds.maximum === \"number\" ? bounds.maximum : undefined;\n const schemaMin =\n typeof bounds.minimum === \"number\" ? bounds.minimum : undefined;\n const min = props.min ?? schemaMin ?? 0;\n const max = props.max ?? schemaMax ?? Number.POSITIVE_INFINITY;\n const columns = props.columns ?? 1;\n\n // Tabs heuristic: forced or nested complex item or many items\n const hasComplexFields = objectItemSchema\n ? fieldNames.some((n) => {\n const inner = z.schema.unwrap(z.schema.shape(objectItemSchema)[n]);\n return z.schema.isObject(inner) || z.schema.isArray(inner);\n })\n : false;\n const useTabs =\n props.forceTabs ||\n (objectItemSchema && (items.length > 4 || hasComplexFields));\n\n const handleAdd = (variantIndex = 0) => {\n if (items.length >= max) return;\n const shape = variants ? variants[variantIndex] : objectItemSchema;\n let value: unknown;\n if (shape) {\n value = {};\n for (const [k, p] of Object.entries(z.schema.shape(shape))) {\n const def = z.schema.defaultValue(p);\n if (def !== undefined) (value as Record<string, unknown>)[k] = def;\n // Stamp the discriminant so the new item resolves to its variant.\n const literal = literalValueOf(p);\n if (literal !== undefined)\n (value as Record<string, unknown>)[k] = literal;\n }\n } else {\n value = \"\";\n }\n setItems([...items, { key: nextKey(), value }]);\n if (useTabs) setActiveTab(items.length);\n };\n\n const handleRemove = (index: number) => {\n if (items.length <= min) return;\n if (props.confirmDelete) {\n setPendingDelete(index);\n return;\n }\n doRemove(index);\n };\n\n const doRemove = (index: number) => {\n setItems(items.filter((_, i) => i !== index));\n if (useTabs)\n setActiveTab(Math.max(0, Math.min(activeTab, items.length - 2)));\n };\n\n const handleMove = (index: number, direction: -1 | 1) => {\n const target = index + direction;\n if (target < 0 || target >= items.length) return;\n const next = [...items];\n [next[index], next[target]] = [next[target], next[index]];\n setItems(next);\n if (useTabs) setActiveTab(target);\n };\n\n const updateItem = (index: number, value: unknown) => {\n const next = [...items];\n next[index] = { ...next[index], value };\n setItems(next);\n };\n\n const updateField = (index: number, field: string, value: unknown) => {\n const next = [...items];\n const current = (next[index].value as Record<string, unknown>) ?? {};\n next[index] = { ...next[index], value: { ...current, [field]: value } };\n setItems(next);\n };\n\n const tabName = (i: number): string => {\n if (props.renderTabName) {\n try {\n return props.renderTabName(i, items[i]?.value);\n } catch {\n // fall through\n }\n }\n const value = items[i]?.value as Record<string, unknown> | undefined;\n const tag = discriminant ? value?.[discriminant] : undefined;\n if (typeof tag === \"string\") return `${tag} #${i + 1}`;\n return `${meta.label} #${i + 1}`;\n };\n\n const renderItemBody = (item: ArrayItem, index: number) => {\n // Resolved per item: in a union each row may be a different variant.\n const itemObjectSchema = schemaForValue(item.value);\n const itemFieldNames = itemObjectSchema\n ? Object.keys(z.schema.shape(itemObjectSchema))\n : [];\n return itemObjectSchema ? (\n <div className={`grid gap-3 ${colsClass[columns]}`}>\n {itemFieldNames.map((name) => {\n const fieldProps = {\n ...props.controlProps?.[name],\n ...resolveFieldI18n(\n tr as never,\n props.i18nPrefix,\n name,\n props.controlProps?.[name] ?? {},\n ),\n i18nPrefix: childI18nPrefix(props.i18nPrefix, name),\n };\n // The discriminant decides the item's SHAPE — editing it would\n // invalidate every sibling field, so it is shown read-only.\n const isDiscriminant = !!variants && name === discriminant;\n const fieldInput = buildFieldInput(\n props.input,\n itemObjectSchema,\n name,\n index,\n item.value as Record<string, unknown>,\n (f, v) => updateField(index, f, v),\n );\n return (\n <Control\n key={name}\n input={fieldInput}\n disabled={props.disabled || isDiscriminant}\n {...fieldProps}\n />\n );\n })}\n </div>\n ) : (\n <Control\n input={buildItemInput(props.input, itemSchema, index, item.value, (v) =>\n updateItem(index, v),\n )}\n disabled={props.disabled}\n {...props.itemControlProps}\n />\n );\n };\n\n const itemActions = (index: number) => (\n <div className=\"flex shrink-0 flex-col gap-1\">\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={props.disabled || index === 0 || items.length < 2}\n onClick={() => handleMove(index, -1)}\n aria-label={tr(\"controlArray.moveUp\", { default: \"Move up\" })}\n >\n <ArrowUp className=\"size-3.5\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={props.disabled || items.length <= min}\n onClick={() => handleRemove(index)}\n aria-label={tr(\"controlArray.remove\", { default: \"Remove\" })}\n >\n <Trash2 className=\"size-3.5\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-7\"\n disabled={\n props.disabled || index === items.length - 1 || items.length < 2\n }\n onClick={() => handleMove(index, 1)}\n aria-label={tr(\"controlArray.moveDown\", { default: \"Move down\" })}\n >\n <ArrowDown className=\"size-3.5\" />\n </Button>\n </div>\n );\n\n const flatList = (\n <div className=\"flex flex-col gap-2\">\n {items.map((item, index) => (\n <div\n key={item.key}\n className=\"bg-muted/30 flex items-start gap-2 rounded-md border p-3\"\n >\n <div className=\"min-w-0 flex-1\">{renderItemBody(item, index)}</div>\n {itemActions(index)}\n </div>\n ))}\n </div>\n );\n\n const tabs = useTabs && items.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex flex-wrap gap-1 border-b pb-1\">\n {items.map((item, i) => (\n <Button\n key={item.key}\n type=\"button\"\n variant={i === activeTab ? \"solid\" : \"minimal\"}\n size=\"sm\"\n onClick={() => setActiveTab(i)}\n >\n {tabName(i)}\n </Button>\n ))}\n </div>\n {items[activeTab] && (\n <div className=\"bg-muted/30 flex items-start gap-2 rounded-md border p-3\">\n <div className=\"min-w-0 flex-1\">\n {renderItemBody(items[activeTab], activeTab)}\n </div>\n {itemActions(activeTab)}\n </div>\n )}\n </div>\n );\n\n const list = (\n <div className=\"flex flex-col gap-2\">{useTabs ? tabs : flatList}</div>\n );\n\n const headerControls = (\n <div className=\"flex items-start gap-3\">\n {variants && variants.length > 1 ? (\n // A union offers a choice of shapes: one Add button per variant,\n // labelled by its discriminant (\"single\", \"period_pass\", …).\n <div className=\"flex shrink-0 flex-wrap gap-1\">\n {variants.map((variant, index) => (\n <Button\n key={variantLabel(variant, discriminant, index)}\n type=\"button\"\n variant=\"outlined\"\n size=\"sm\"\n className=\"h-8\"\n disabled={props.disabled || items.length >= max}\n onClick={() => handleAdd(index)}\n >\n <Plus className=\"size-3.5\" />\n {variantLabel(variant, discriminant, index)}\n </Button>\n ))}\n </div>\n ) : (\n <Button\n type=\"button\"\n variant=\"outlined\"\n size=\"icon\"\n className=\"size-8 shrink-0\"\n disabled={props.disabled || items.length >= max}\n onClick={() => handleAdd()}\n aria-label={\n props.addLabel ?? tr(\"controlArray.add\", { default: \"Add\" })\n }\n >\n <Plus className=\"size-4\" />\n </Button>\n )}\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <div className=\"text-sm leading-tight font-medium\">\n {meta.label}\n {meta.required && <span className=\"text-danger-text ml-0.5\">*</span>}\n <span className=\"text-muted-foreground ml-2 text-xs\">\n ({items.length})\n </span>\n </div>\n {meta.description && (\n <p className=\"text-muted-foreground text-xs leading-tight\">\n {meta.description}\n </p>\n )}\n {meta.error && (\n <p className=\"text-danger-text text-xs leading-tight\">{meta.error}</p>\n )}\n </div>\n {items.length > 0 && (\n <Button\n type=\"button\"\n variant=\"minimal\"\n size=\"icon\"\n className=\"size-8 shrink-0\"\n aria-label={\n expanded\n ? tr(\"controlArray.collapse\", { default: \"Collapse\" })\n : tr(\"controlArray.expand\", { default: \"Expand\" })\n }\n onClick={() => setExpanded((e) => !e)}\n >\n {expanded ? (\n <ChevronDown className=\"size-4\" />\n ) : (\n <ChevronRight className=\"size-4\" />\n )}\n </Button>\n )}\n </div>\n );\n\n const confirmContent = (() => {\n if (pendingDelete == null) return null;\n const cd = props.confirmDelete;\n const title =\n typeof cd === \"object\"\n ? (cd.title ??\n tr(\"controlArray.deleteTitle\", { default: \"Delete item\" }))\n : tr(\"controlArray.deleteTitle\", { default: \"Delete item\" });\n const message =\n typeof cd === \"object\"\n ? (cd.message ??\n tr(\"controlArray.deleteConfirm\", {\n default: \"Are you sure you want to delete this item?\",\n }))\n : tr(\"controlArray.deleteConfirm\", {\n default: \"Are you sure you want to delete this item?\",\n });\n return (\n <Dialog\n open={pendingDelete != null}\n onOpenChange={(v) => !v && setPendingDelete(null)}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n <DialogDescription>{message}</DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button variant=\"minimal\" onClick={() => setPendingDelete(null)}>\n {tr(\"controlArray.cancel\", { default: \"Cancel\" })}\n </Button>\n <Button\n variant=\"outlined\"\n intent=\"danger\"\n onClick={() => {\n doRemove(pendingDelete);\n setPendingDelete(null);\n }}\n >\n {tr(\"controlArray.delete\", { default: \"Delete\" })}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n })();\n\n if (props.variant === \"plain\") {\n return (\n <div className=\"flex flex-col gap-2\">\n {headerControls}\n {expanded && items.length > 0 && list}\n {confirmContent}\n </div>\n );\n }\n\n return (\n <fieldset\n className={`rounded-md border p-3 ${\n meta.error ? \"border-danger\" : \"border-border\"\n }`}\n >\n {headerControls}\n {expanded && items.length > 0 && <div className=\"mt-3\">{list}</div>}\n {confirmContent}\n </fieldset>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAkHA,MAAM,YAAoC;CACxC,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;AAQA,MAAM,cAAc,UAClB,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACtD,OAAO,KAAK,KAAgC,IAC5C,CAAC;AAEP,MAAM,iBAAiB,UAAsC;CAC3D,MAAM,SAAS,UAAU;CACzB,MAAM,UAAU,OAAO,CAAC;CACxB,MAAM,CAAC,OAAO,iBAAiB,eAA4B;EACzD,MAAM,UAAU,OAAO;EACvB,OAAO,MAAM,QAAQ,OAAO,IACxB,QAAQ,KAAK,WAAW;GAAE,KAAK,QAAQ;GAAW;EAAM,EAAE,IAC1D,CAAC;CACP,CAAC;CAKD,MAAM,WAAW,OAAO,KAAK;CAC7B,SAAS,UAAU;;;;;;;;;;;;;;CAenB,MAAM,cAAc,aACjB,MAAmB,SAAsB;EACxC,MAAM,OAAO,OAAO;EACpB,IAAI,CAAC,QAAQ,CAAC,OAAO;EAErB,MAAM,QAAQ,MAAc,UAC1B,KAAK,OAAO,OAAO,KACjB,gBACA;GAAE,IAAI,KAAK;GAAI;GAAM;EAAM,GAC3B,EAAE,OAAO,KAAK,CAChB;EAEF,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,KAAK,QAAQ,KAAK,MAAM,GAAG,KAAK;GAC3D,MAAM,SAAS,KAAK,EAAE,EAAE;GACxB,MAAM,QAAQ,KAAK,EAAE,EAAE;GACvB,IAAI,WAAW,OAAO;GAEtB,KAAK,GAAG,MAAM,KAAK,GAAG,KAAK,KAAK;GAEhC,KAAK,MAAM,uBAAO,IA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3D,UAAA,GAAG,uBAAuB,EAAE,SAAS,SAAS,CAAC;GAC1C,CAAA,GACR,oBAAC,QAAD;IACE,SAAQ;IACR,QAAO;IACP,eAAe;KACb,SAAS,aAAa;KACtB,iBAAiB,IAAI;IACvB;IAEC,UAAA,GAAG,uBAAuB,EAAE,SAAS,SAAS,CAAC;GAC1C,CAAA,CACI,EAAA,CAAA,CACD,EAAA,CAAA;EACT,CAAA;CAEZ,EAAA,CAAG;CAEH,IAAI,MAAM,YAAY,SACpB,OACE,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACG;GACA,YAAY,MAAM,SAAS,KAAK;GAChC;EACE;;CAIT,OACE,qBAAC,YAAD;EACE,WAAW,yBACT,KAAK,QAAQ,kBAAkB;EAFnC,UAAA;GAKG;GACA,YAAY,MAAM,SAAS,KAAK,oBAAC,OAAD;IAAK,WAAU;IAAQ,UAAA;GAAU,CAAA;GACjE;EACO;;AAEd"}
|
|
@@ -100,7 +100,7 @@ const ControlSelect = (props) => {
|
|
|
100
100
|
value,
|
|
101
101
|
onChange: (v) => setValue(v),
|
|
102
102
|
coerce,
|
|
103
|
-
onSearch: mode === "long" ? search.run : void 0,
|
|
103
|
+
onSearch: mode === "long" ? (text) => search.run(text) : void 0,
|
|
104
104
|
createNewEntry: props.createNewEntry,
|
|
105
105
|
icon: props.icon,
|
|
106
106
|
triggerClassName: props.triggerClassName,
|
|
@@ -187,7 +187,7 @@ const useAsyncLoader = (loader, threshold, debounceMs, defaultValue) => {
|
|
|
187
187
|
mode,
|
|
188
188
|
search: useAction({
|
|
189
189
|
debounce: debounceMs,
|
|
190
|
-
handler: async (text) => {
|
|
190
|
+
handler: async (_ctx, text) => {
|
|
191
191
|
if (!loader || mode !== "long") return;
|
|
192
192
|
if (cache.current.has(text)) {
|
|
193
193
|
setData(cache.current.get(text));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlSelect.js","names":[],"sources":["../../src/form/ControlSelect.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport type { Async } from \"alepha\";\nimport { useAction } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport type { HTMLAttributes } from \"react\";\nimport { type ReactNode, useMemo, useRef, useState } from \"react\";\n\nimport { Segmented } from \"../core/Segmented.tsx\";\nimport { ControlSelectCombobox } from \"./ControlSelectCombobox.tsx\";\nimport { optValue } from \"./controlSelectOptions.ts\";\nimport type { ControlTriggerSize } from \"./fieldTrigger.tsx\";\nimport { FormField } from \"./FormField.tsx\";\nimport type { IconComponent } from \"./iconHint.tsx\";\n\nexport interface ControlSelectProps {\n /**\n * Bound `InputField` from `useForm`. Single or multi value depending on schema.\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the input.\n */\n description?: string;\n /**\n * Render as a `<Segmented>` control (best for 2–4 options).\n */\n segmented?: boolean;\n /**\n * Force the search input on. Kept as the historical name for\n * `searchable: true` — every select is a combobox now, the flag only\n * decides whether it carries a search field.\n */\n combobox?: boolean;\n /**\n * Whether the dropdown carries a search input. Defaults to \"auto\": on for a\n * long-mode `loader` (the rows are not all here), when `createNewEntry` is\n * set (typing IS how an entry is made), and for lists longer than\n * `SEARCH_THRESHOLD`. Set explicitly to search a short list or to drop the\n * search field from a long one.\n *\n * Multi-select obeys the same rule as everything else; it used to force the\n * field on because its chips box doubled as the search input.\n */\n searchable?: boolean;\n /**\n * Async option loader. Triggers long-mode (server-side search) above `loaderThreshold` options.\n */\n loader?: (search: string, resolve?: string[]) => Async<SelectOption[]>;\n /**\n * Option count above which `loader` is invoked on every search instead of once. Defaults to 100.\n */\n loaderThreshold?: number;\n /**\n * Debounce in ms applied to search queries when calling `loader` in long mode.\n */\n loaderDebounce?: number;\n /**\n * Disable the control.\n */\n disabled?: boolean;\n /**\n * Inline option list (overrides schema `enum`). Accepts either a static\n * array or an async function `(query) => SelectOption[]`. The async form\n * is mapped to a long-mode loader.\n */\n items?:\n | SelectOption[]\n | ((query: string) => SelectOption[] | Promise<SelectOption[]>);\n /**\n * Allow the user to add a new option by typing. When `true`, the typed\n * query becomes the value (and label) of a freshly created entry. When a\n * function, the function builds the option from the query.\n *\n * - For multi-select fields: each entry is appended to the value array.\n * - For single fields: behaves like a regular text input with a dropdown\n * suggesting existing options.\n */\n createNewEntry?: boolean | ((query: string) => Exclude<SelectOption, string>);\n /**\n * When true, the dropdown gets a synthetic \"none\" row at the top that\n * resets the field to `undefined`. Useful for optional filter chips\n * (e.g. an admin-table status filter) where the user needs an explicit\n * \"no filter\" option — Base UI's `Select` reserves empty-string values\n * as its internal no-selection sentinel, so a regular `<SelectItem\n * value=\"\">` can't be picked. With `clearable`, ControlSelect uses an\n * internal sentinel and translates it to `undefined` in `onChange`.\n *\n * Currently honored by the static-short `Select` and the searchable\n * Combobox render paths. Ignored by `segmented` (use a real segment\n * for \"all\" there).\n */\n clearable?: boolean;\n /**\n * Label rendered for the \"clear\" row injected by `clearable`. Also\n * used as the trigger placeholder when the field is empty. Defaults to\n * `\"None\"`. Localize at the call site (e.g. `\"All types\"`,\n * `\"All status\"`).\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 * The longest joined text, in characters, a multi-select trigger names its\n * selection with (\"Draft, Ready\") before it collapses to `countLabel`.\n * Defaults to 20, which suits a filter chip; a full-width form field has\n * room for more.\n */\n maxTriggerLength?: number;\n /**\n * Trigger text when nothing is selected, e.g. \"Pick an epic…\". Defaults to\n * the `clearLabel` on a `clearable` or multi field (where empty IS a\n * meaningful state to name), and to \"Select…\" otherwise.\n *\n * Set it when the empty trigger has a job to do - a picker whose whole\n * purpose is the choice it prompts for reads as a dead \"Select…\" without\n * it, which is why the surfaces that needed one stayed on the raw `Select`.\n */\n placeholder?: string;\n /**\n * Extra className applied to the visible trigger: the combobox button or\n * the segmented control, whichever this field renders. Useful for sizing\n * filter chips (`\"w-40\"`, `\"w-72\"`, etc.) without wrapping the whole\n * `FormField` in an extra div.\n */\n triggerClassName?: string;\n /**\n * Trigger height and type scale. Defaults to `default`.\n */\n size?: ControlSelectSize;\n /**\n * Render the trigger borderless and transparent, so it reads as the row it\n * sits on rather than as a form field.\n */\n minimal?: boolean;\n /**\n * Extra attributes for whichever trigger this field renders, forwarded from\n * `Control`'s `inputProps`.\n *\n * The accessible name usually lives here, because a filter is routinely\n * rendered with `label=\"\"` next to its own heading: with no `<label>` to\n * borrow a name from, a `role=combobox` button or a radiogroup has no name\n * at all. That is both an a11y hole and unaddressable from a\n * test, and it was silent, since `Control` accepted `inputProps` and then\n * dropped it on every select-shaped branch.\n */\n triggerProps?: HTMLAttributes<HTMLElement>;\n /**\n * Leading icon rendered on the left of the trigger, matching the\n * text-input controls. Resolved by the parent `Control` from its `icon`\n * prop, falling back to the list glyph like a text input falls back to\n * its schema hint; `icon={null}` on the `Control` removes it, and a\n * `minimal` trigger gets none by default.\n */\n icon?: IconComponent;\n /**\n * Drawn at the top of the popup, above the options - for a setting that\n * changes what the choice MEANS rather than what is chosen, such as a\n * filter's \"is / is not\".\n *\n * ⚠️ Only the combobox shape has a popup, so a segmented or radio rendering\n * of the same field draws nothing for it.\n */\n popupHeader?: ReactNode;\n /**\n * Drawn on the trigger just before the selected label, after the icon: the\n * short word that keeps a qualified value from reading as a plain one\n * (\"not Active\"). Absent while nothing is selected, because a qualifier on\n * a placeholder has nothing to qualify.\n */\n triggerPrefix?: ReactNode;\n /**\n * Extra className on the popup, merged over its own.\n *\n * The popup is sized from its trigger by default (`--anchor-width`), and it\n * keeps following that width while open. A trigger whose text changes as\n * the reader picks - a `triggerPrefix` appearing, \"2 values\" replacing a\n * name - therefore resizes the popup under their cursor. `w-max` with a\n * floor (`w-max min-w-48`) sizes it from its own content instead.\n */\n popupClassName?: string;\n}\n\nexport const ControlSelect = (props: ControlSelectProps) => {\n const { tr } = useI18n();\n const form = useFormState(props.input, [\"error\"]);\n const [value, setValue] = useFieldValue(props.input);\n\n const meta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const isArray = meta.isArray;\n const isNumeric = meta.type === \"number\" || meta.type === \"integer\";\n const isBoolean = meta.type === \"boolean\";\n\n // Normalize items prop: array → static; function → loader\n const itemsArray = Array.isArray(props.items)\n ? (props.items as SelectOption[])\n : undefined;\n const itemsLoader =\n typeof props.items === \"function\"\n ? (props.items as (q: string) => Async<SelectOption[]>)\n : undefined;\n\n const enumValues =\n itemsArray ?? (meta.enum as SelectOption[] | undefined) ?? [];\n\n const effectiveLoader = props.loader ?? itemsLoader;\n\n const {\n data: asyncData,\n loading,\n mode,\n search,\n } = useAsyncLoader(\n effectiveLoader,\n props.loaderThreshold ?? 100,\n props.loaderDebounce ?? 300,\n props.input.initialValue,\n );\n\n // Labels and `disabled` flags are part of the identity: keying on the\n // joined values alone collided (`[\"ab\",\"c\"]` vs `[\"a\",\"bc\"]`) and kept a\n // stale list when only the labels changed.\n //\n // ⚠️ `icon` is EXCLUDED, and it has to be. It is a `ReactNode`, and a\n // rendered element holds a fiber that points back at its DOM node, so\n // `JSON.stringify` on the raw option threw \"Converting circular structure\n // to JSON\" - a documented prop that crashed the component the first time\n // anyone used it (#Q2049). Two lists that differ only by icon share a key,\n // which is right: the key exists to notice a changed VALUE or LABEL.\n const enumKey = JSON.stringify(\n enumValues.map((option) =>\n typeof option === \"string\"\n ? option\n : {\n value: option.value,\n label: option.label,\n description: option.description,\n tag: option.tag,\n disabled: option.disabled,\n },\n ),\n );\n const min = meta.constraints.minimum;\n const max = meta.constraints.maximum;\n // Derived, not stored: this is a pure function of the schema. As state\n // filled in by an effect, the first paint of every boolean or ranged select\n // was an EMPTY list, corrected one render later.\n const staticData = useMemo<SelectOption[]>(() => {\n if (effectiveLoader) return [];\n if (isBoolean && enumValues.length === 0) {\n return [\n { value: \"true\", label: tr(\"controlSelect.yes\", { default: \"Yes\" }) },\n { value: \"false\", label: tr(\"controlSelect.no\", { default: \"No\" }) },\n ];\n }\n if (\n isNumeric &&\n enumValues.length === 0 &&\n typeof min === \"number\" &&\n typeof max === \"number\" &&\n max - min <= 20\n ) {\n const range: SelectOption[] = [];\n for (let i = min; i <= max; i++) range.push(String(i));\n return range;\n }\n return enumValues;\n }, [effectiveLoader, enumKey, isBoolean, isNumeric, min, max, tr]);\n\n const data = effectiveLoader ? asyncData : staticData;\n\n if (!props.input?.props) return null;\n\n const coerce = (raw: string): unknown => {\n if (isNumeric) return Number(raw);\n if (isBoolean) return raw === \"true\";\n return raw;\n };\n\n if (props.segmented) {\n return (\n <FormField\n id={meta.id}\n label={meta.label}\n description={meta.description}\n error={meta.error}\n required={meta.required}\n >\n {/* `triggerProps` is deliberately NOT spread here. `Segmented`\n redeclares two attributes that `HTMLAttributes` also has, with\n narrower types (`defaultValue` is string-only, `onChange` takes a\n value rather than an event), so a blanket spread neither typechecks\n nor is safe. A segmented field also renders every option as visible\n text, so it is the one branch that is not nameless without a label.\n Name it with `label` if it needs one. */}\n <Segmented\n value={value != null ? String(value) : undefined}\n onChange={(v) => setValue(coerce(v))}\n disabled={props.disabled}\n options={data.slice(0, 10).map((o) => ({\n value: optValue(o),\n label: segmentedLabel(o),\n }))}\n fullWidth\n />\n </FormField>\n );\n }\n\n const clearLabel =\n props.clearLabel ?? tr(\"controlSelect.none\", { default: \"None\" });\n\n // One control for every list. The option count decides whether the popup\n // carries a search field — it no longer decides which primitive renders.\n // The native `Select` path this replaced silently dropped `description`,\n // `tag`, per-option `disabled` and `deselectable`, and styled its trigger\n // differently, purely because a list happened to be short.\n // A search field is offered only when scanning the list by eye stops being\n // realistic: a server-driven list (whose rows are not all here), one past\n // `SEARCH_THRESHOLD`, or one where typing is how a new entry is made.\n //\n // Multi-select used to force it on unconditionally, because the chips box\n // WAS the search input and there was no other way to open the popup. The\n // trigger is a button now, so multi obeys the same rule as everything else\n // and a four-row status filter no longer opens onto a search field.\n const searchable =\n props.searchable ??\n (props.combobox ||\n mode === \"long\" ||\n Boolean(props.createNewEntry) ||\n data.length > SEARCH_THRESHOLD);\n\n return (\n <FormField\n id={meta.id}\n label={meta.label}\n description={meta.description}\n error={meta.error}\n required={meta.required}\n >\n <ControlSelectCombobox\n id={meta.id}\n data={data}\n loading={loading}\n multi={isArray}\n searchable={searchable}\n disabled={props.disabled}\n value={value}\n onChange={(v) => setValue(v)}\n coerce={coerce}\n onSearch={mode === \"long\" ? search.run : undefined}\n createNewEntry={props.createNewEntry}\n icon={props.icon}\n // Used to be dropped on this path, so a filter chip sized `w-40` lost\n // its width as soon as its list crossed the threshold.\n triggerClassName={props.triggerClassName}\n triggerProps={props.triggerProps}\n size={props.size}\n minimal={props.minimal}\n // `clearable` used to reach this path as a placeholder and nothing\n // else, so a filter chip that had switched to the combobox (>20\n // options) could be set but never put back to \"All …\".\n clearable={props.clearable}\n clearLabel={clearLabel}\n countLabel={props.countLabel}\n maxTriggerLength={props.maxTriggerLength}\n popupHeader={props.popupHeader}\n triggerPrefix={props.triggerPrefix}\n popupClassName={props.popupClassName}\n // An optional field must also be able to go back to empty without a\n // dedicated row: Base UI never emits `null`, so re-pressing the\n // selected row deselects (see `handleSingle` in\n // `ControlSelectCombobox.tsx`). A required field keeps its value —\n // clearing it would only produce a validation error the user cannot\n // see yet.\n deselectable={props.clearable || !meta.required}\n // Multi shows this muted when nothing is picked, so it reaches the\n // trigger whether or not the field is `clearable` — a multi-select\n // has no clear ROW (it clears by deselecting), and without this its\n // empty trigger fell back to a bare \"Select…\".\n placeholder={\n props.placeholder ??\n (props.clearable || isArray ? clearLabel : undefined)\n }\n />\n </FormField>\n );\n};\n\nexport type SelectOption =\n | string\n | {\n value: string;\n label: string;\n /**\n * Optional secondary line shown under the label in the dropdown.\n */\n description?: string;\n /**\n * Optional small badge rendered next to the label.\n */\n tag?: string;\n /**\n * Optional icon/element rendered before the label, in both the\n * dropdown row and (for single-select) the trigger when selected.\n */\n icon?: ReactNode;\n /**\n * When true, the row is non-interactive — can't be selected if\n * not selected, can't be deselected if selected. Useful for\n * default/mandatory entries (e.g. the base \"user\" role).\n */\n disabled?: boolean;\n };\n\ntype LoaderMode = \"static\" | \"short\" | \"long\";\n\n/**\n * How tall and how loud a select trigger is.\n *\n * The kit's own scale, kept under this name because `Control` and a long tail\n * of callers already spell it `size=\"xs\"` on a select. The table behind it,\n * and the trigger box it sizes, are `control-base/field-trigger`'s - shared\n * with the two calendar controls, which used to draw a button instead.\n */\nexport type ControlSelectSize = ControlTriggerSize;\n\n/**\n * Static option count above which the dropdown grows a search input. Below it\n * the very same combobox renders without one — the threshold decides whether\n * you can type, never which control you get.\n */\n// Past this many rows, scanning by eye stops being realistic and the popup\n// grows a search field. Raised 20 -> 50 with the multi-select rework: the old\n// value put a search box on lists a reader takes in at a glance.\nconst SEARCH_THRESHOLD = 50;\n\n/**\n * Friendly label for plain string options: \"optional\" → \"Optional\",\n * \"in_progress\" → \"In Progress\". Custom `{ value, label }` items pass through\n * untouched.\n */\nconst titlecase = (s: string) =>\n s.replace(/[_-]+/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase());\n/**\n * What one segment shows.\n *\n * ⚠️ The option's `icon` is rendered HERE rather than dropped, which is what\n * this path did until #Q2049. `SegmentedOption.label` is a `ReactNode`, so\n * there was never a reason for it: an option list carrying icons for the\n * dropdown carried them for the segments too, and dropping them silently\n * made a caller choose between two shapes for one list.\n */\nconst segmentedLabel = (o: SelectOption): ReactNode => {\n if (typeof o === \"string\") {\n return titlecase(o);\n }\n if (!o.icon) {\n return o.label;\n }\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n {o.icon}\n {o.label}\n </span>\n );\n};\n\nconst useAsyncLoader = (\n loader: ControlSelectProps[\"loader\"],\n threshold: number,\n debounceMs: number,\n defaultValue: unknown,\n) => {\n const [data, setData] = useState<SelectOption[]>([]);\n const [loading, setLoading] = useState(false);\n const [mode, setMode] = useState<LoaderMode>(\"static\");\n const cache = useRef(new Map<string, SelectOption[]>());\n\n useAction(\n {\n // `id`, not `name`: `id` is what useAction threads into its\n // react:action:* events. `name` was accepted and never read, so this\n // identifier reached nothing.\n id: \"select:loader:init\",\n runOnInit: true,\n handler: async () => {\n if (!loader) {\n setMode(\"static\");\n return;\n }\n setLoading(true);\n try {\n const result = await loader(\"\");\n const isShort = result.length <= threshold;\n setMode(isShort ? \"short\" : \"long\");\n cache.current.set(\"\", result);\n setData(result);\n\n // Coercion at a boundary: the value is a form/route/chart primitive whose\n // declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n if (!isShort && defaultValue != null && String(defaultValue) !== \"\") {\n // Coercion at a boundary: the value is a form/route/chart primitive whose\n // declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n const resolved = await loader(\"\", [String(defaultValue)]);\n if (resolved.length > 0) {\n setData((prev) => {\n const existing = new Set(prev.map(optValue));\n const fresh = resolved.filter(\n (r) => !existing.has(optValue(r)),\n );\n return [...prev, ...fresh];\n });\n }\n }\n } finally {\n setLoading(false);\n }\n },\n },\n [loader, threshold],\n );\n\n const search = useAction<[string]>(\n {\n debounce: debounceMs,\n handler: async (text) => {\n if (!loader || mode !== \"long\") return;\n if (cache.current.has(text)) {\n setData(cache.current.get(text)!);\n return;\n }\n setLoading(true);\n try {\n const result = await loader(text);\n cache.current.set(text, result);\n setData(result);\n } finally {\n setLoading(false);\n }\n },\n },\n [loader, mode, debounceMs],\n );\n\n return { data, loading, mode, search };\n};\n"],"mappings":";;;;;;;;;;AAwMA,MAAa,iBAAiB,UAA8B;CAC1D,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,OAAO,CAAC;CAChD,MAAM,CAAC,OAAO,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C;KACxD,IAAI,SAAS,SAAS,GACpB,SAAS,SAAS;MAChB,MAAM,WAAW,IAAI,IAAI,KAAK,IAAI,QAAQ,CAAC;MAC3C,MAAM,QAAQ,SAAS,QACpB,MAAM,CAAC,SAAS,IAAI,SAAS,CAAC,CAAC,CAClC;MACA,OAAO,CAAC,GAAG,MAAM,GAAG,KAAK;KAC3B,CAAC;IAEL;GACF,UAAU;IACR,WAAW,KAAK;GAClB;EACF;CACF,GACA,CAAC,QAAQ,SAAS,CACpB;CAwBA,OAAO;EAAE;EAAM;EAAS;EAAM,QAtBf,UACb;GACE,UAAU;GACV,SAAS,OAAO,SAAS;IACvB,IAAI,CAAC,UAAU,SAAS,QAAQ;IAChC,IAAI,MAAM,QAAQ,IAAI,IAAI,GAAG;KAC3B,QAAQ,MAAM,QAAQ,IAAI,IAAI,CAAE;KAChC;IACF;IACA,WAAW,IAAI;IACf,IAAI;KACF,MAAM,SAAS,MAAM,OAAO,IAAI;KAChC,MAAM,QAAQ,IAAI,MAAM,MAAM;KAC9B,QAAQ,MAAM;IAChB,UAAU;KACR,WAAW,KAAK;IAClB;GACF;EACF,GACA;GAAC;GAAQ;GAAM;EAAU,CAGQ;CAAE;AACvC"}
|
|
1
|
+
{"version":3,"file":"ControlSelect.js","names":[],"sources":["../../src/form/ControlSelect.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport type { Async } from \"alepha\";\nimport { useAction } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport type { HTMLAttributes } from \"react\";\nimport { type ReactNode, useMemo, useRef, useState } from \"react\";\n\nimport { Segmented } from \"../core/Segmented.tsx\";\nimport { ControlSelectCombobox } from \"./ControlSelectCombobox.tsx\";\nimport { optValue } from \"./controlSelectOptions.ts\";\nimport type { ControlTriggerSize } from \"./fieldTrigger.tsx\";\nimport { FormField } from \"./FormField.tsx\";\nimport type { IconComponent } from \"./iconHint.tsx\";\n\nexport interface ControlSelectProps {\n /**\n * Bound `InputField` from `useForm`. Single or multi value depending on schema.\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the input.\n */\n description?: string;\n /**\n * Render as a `<Segmented>` control (best for 2–4 options).\n */\n segmented?: boolean;\n /**\n * Force the search input on. Kept as the historical name for\n * `searchable: true` — every select is a combobox now, the flag only\n * decides whether it carries a search field.\n */\n combobox?: boolean;\n /**\n * Whether the dropdown carries a search input. Defaults to \"auto\": on for a\n * long-mode `loader` (the rows are not all here), when `createNewEntry` is\n * set (typing IS how an entry is made), and for lists longer than\n * `SEARCH_THRESHOLD`. Set explicitly to search a short list or to drop the\n * search field from a long one.\n *\n * Multi-select obeys the same rule as everything else; it used to force the\n * field on because its chips box doubled as the search input.\n */\n searchable?: boolean;\n /**\n * Async option loader. Triggers long-mode (server-side search) above `loaderThreshold` options.\n */\n loader?: (search: string, resolve?: string[]) => Async<SelectOption[]>;\n /**\n * Option count above which `loader` is invoked on every search instead of once. Defaults to 100.\n */\n loaderThreshold?: number;\n /**\n * Debounce in ms applied to search queries when calling `loader` in long mode.\n */\n loaderDebounce?: number;\n /**\n * Disable the control.\n */\n disabled?: boolean;\n /**\n * Inline option list (overrides schema `enum`). Accepts either a static\n * array or an async function `(query) => SelectOption[]`. The async form\n * is mapped to a long-mode loader.\n */\n items?:\n | SelectOption[]\n | ((query: string) => SelectOption[] | Promise<SelectOption[]>);\n /**\n * Allow the user to add a new option by typing. When `true`, the typed\n * query becomes the value (and label) of a freshly created entry. When a\n * function, the function builds the option from the query.\n *\n * - For multi-select fields: each entry is appended to the value array.\n * - For single fields: behaves like a regular text input with a dropdown\n * suggesting existing options.\n */\n createNewEntry?: boolean | ((query: string) => Exclude<SelectOption, string>);\n /**\n * When true, the dropdown gets a synthetic \"none\" row at the top that\n * resets the field to `undefined`. Useful for optional filter chips\n * (e.g. an admin-table status filter) where the user needs an explicit\n * \"no filter\" option — Base UI's `Select` reserves empty-string values\n * as its internal no-selection sentinel, so a regular `<SelectItem\n * value=\"\">` can't be picked. With `clearable`, ControlSelect uses an\n * internal sentinel and translates it to `undefined` in `onChange`.\n *\n * Currently honored by the static-short `Select` and the searchable\n * Combobox render paths. Ignored by `segmented` (use a real segment\n * for \"all\" there).\n */\n clearable?: boolean;\n /**\n * Label rendered for the \"clear\" row injected by `clearable`. Also\n * used as the trigger placeholder when the field is empty. Defaults to\n * `\"None\"`. Localize at the call site (e.g. `\"All types\"`,\n * `\"All status\"`).\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 * The longest joined text, in characters, a multi-select trigger names its\n * selection with (\"Draft, Ready\") before it collapses to `countLabel`.\n * Defaults to 20, which suits a filter chip; a full-width form field has\n * room for more.\n */\n maxTriggerLength?: number;\n /**\n * Trigger text when nothing is selected, e.g. \"Pick an epic…\". Defaults to\n * the `clearLabel` on a `clearable` or multi field (where empty IS a\n * meaningful state to name), and to \"Select…\" otherwise.\n *\n * Set it when the empty trigger has a job to do - a picker whose whole\n * purpose is the choice it prompts for reads as a dead \"Select…\" without\n * it, which is why the surfaces that needed one stayed on the raw `Select`.\n */\n placeholder?: string;\n /**\n * Extra className applied to the visible trigger: the combobox button or\n * the segmented control, whichever this field renders. Useful for sizing\n * filter chips (`\"w-40\"`, `\"w-72\"`, etc.) without wrapping the whole\n * `FormField` in an extra div.\n */\n triggerClassName?: string;\n /**\n * Trigger height and type scale. Defaults to `default`.\n */\n size?: ControlSelectSize;\n /**\n * Render the trigger borderless and transparent, so it reads as the row it\n * sits on rather than as a form field.\n */\n minimal?: boolean;\n /**\n * Extra attributes for whichever trigger this field renders, forwarded from\n * `Control`'s `inputProps`.\n *\n * The accessible name usually lives here, because a filter is routinely\n * rendered with `label=\"\"` next to its own heading: with no `<label>` to\n * borrow a name from, a `role=combobox` button or a radiogroup has no name\n * at all. That is both an a11y hole and unaddressable from a\n * test, and it was silent, since `Control` accepted `inputProps` and then\n * dropped it on every select-shaped branch.\n */\n triggerProps?: HTMLAttributes<HTMLElement>;\n /**\n * Leading icon rendered on the left of the trigger, matching the\n * text-input controls. Resolved by the parent `Control` from its `icon`\n * prop, falling back to the list glyph like a text input falls back to\n * its schema hint; `icon={null}` on the `Control` removes it, and a\n * `minimal` trigger gets none by default.\n */\n icon?: IconComponent;\n /**\n * Drawn at the top of the popup, above the options - for a setting that\n * changes what the choice MEANS rather than what is chosen, such as a\n * filter's \"is / is not\".\n *\n * ⚠️ Only the combobox shape has a popup, so a segmented or radio rendering\n * of the same field draws nothing for it.\n */\n popupHeader?: ReactNode;\n /**\n * Drawn on the trigger just before the selected label, after the icon: the\n * short word that keeps a qualified value from reading as a plain one\n * (\"not Active\"). Absent while nothing is selected, because a qualifier on\n * a placeholder has nothing to qualify.\n */\n triggerPrefix?: ReactNode;\n /**\n * Extra className on the popup, merged over its own.\n *\n * The popup is sized from its trigger by default (`--anchor-width`), and it\n * keeps following that width while open. A trigger whose text changes as\n * the reader picks - a `triggerPrefix` appearing, \"2 values\" replacing a\n * name - therefore resizes the popup under their cursor. `w-max` with a\n * floor (`w-max min-w-48`) sizes it from its own content instead.\n */\n popupClassName?: string;\n}\n\nexport const ControlSelect = (props: ControlSelectProps) => {\n const { tr } = useI18n();\n const form = useFormState(props.input, [\"error\"]);\n const [value, setValue] = useFieldValue(props.input);\n\n const meta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const isArray = meta.isArray;\n const isNumeric = meta.type === \"number\" || meta.type === \"integer\";\n const isBoolean = meta.type === \"boolean\";\n\n // Normalize items prop: array → static; function → loader\n const itemsArray = Array.isArray(props.items)\n ? (props.items as SelectOption[])\n : undefined;\n const itemsLoader =\n typeof props.items === \"function\"\n ? (props.items as (q: string) => Async<SelectOption[]>)\n : undefined;\n\n const enumValues =\n itemsArray ?? (meta.enum as SelectOption[] | undefined) ?? [];\n\n const effectiveLoader = props.loader ?? itemsLoader;\n\n const {\n data: asyncData,\n loading,\n mode,\n search,\n } = useAsyncLoader(\n effectiveLoader,\n props.loaderThreshold ?? 100,\n props.loaderDebounce ?? 300,\n props.input.initialValue,\n );\n\n // Labels and `disabled` flags are part of the identity: keying on the\n // joined values alone collided (`[\"ab\",\"c\"]` vs `[\"a\",\"bc\"]`) and kept a\n // stale list when only the labels changed.\n //\n // ⚠️ `icon` is EXCLUDED, and it has to be. It is a `ReactNode`, and a\n // rendered element holds a fiber that points back at its DOM node, so\n // `JSON.stringify` on the raw option threw \"Converting circular structure\n // to JSON\" - a documented prop that crashed the component the first time\n // anyone used it (#Q2049). Two lists that differ only by icon share a key,\n // which is right: the key exists to notice a changed VALUE or LABEL.\n const enumKey = JSON.stringify(\n enumValues.map((option) =>\n typeof option === \"string\"\n ? option\n : {\n value: option.value,\n label: option.label,\n description: option.description,\n tag: option.tag,\n disabled: option.disabled,\n },\n ),\n );\n const min = meta.constraints.minimum;\n const max = meta.constraints.maximum;\n // Derived, not stored: this is a pure function of the schema. As state\n // filled in by an effect, the first paint of every boolean or ranged select\n // was an EMPTY list, corrected one render later.\n const staticData = useMemo<SelectOption[]>(() => {\n if (effectiveLoader) return [];\n if (isBoolean && enumValues.length === 0) {\n return [\n { value: \"true\", label: tr(\"controlSelect.yes\", { default: \"Yes\" }) },\n { value: \"false\", label: tr(\"controlSelect.no\", { default: \"No\" }) },\n ];\n }\n if (\n isNumeric &&\n enumValues.length === 0 &&\n typeof min === \"number\" &&\n typeof max === \"number\" &&\n max - min <= 20\n ) {\n const range: SelectOption[] = [];\n for (let i = min; i <= max; i++) range.push(String(i));\n return range;\n }\n return enumValues;\n }, [effectiveLoader, enumKey, isBoolean, isNumeric, min, max, tr]);\n\n const data = effectiveLoader ? asyncData : staticData;\n\n if (!props.input?.props) return null;\n\n const coerce = (raw: string): unknown => {\n if (isNumeric) return Number(raw);\n if (isBoolean) return raw === \"true\";\n return raw;\n };\n\n if (props.segmented) {\n return (\n <FormField\n id={meta.id}\n label={meta.label}\n description={meta.description}\n error={meta.error}\n required={meta.required}\n >\n {/* `triggerProps` is deliberately NOT spread here. `Segmented`\n redeclares two attributes that `HTMLAttributes` also has, with\n narrower types (`defaultValue` is string-only, `onChange` takes a\n value rather than an event), so a blanket spread neither typechecks\n nor is safe. A segmented field also renders every option as visible\n text, so it is the one branch that is not nameless without a label.\n Name it with `label` if it needs one. */}\n <Segmented\n value={value != null ? String(value) : undefined}\n onChange={(v) => setValue(coerce(v))}\n disabled={props.disabled}\n options={data.slice(0, 10).map((o) => ({\n value: optValue(o),\n label: segmentedLabel(o),\n }))}\n fullWidth\n />\n </FormField>\n );\n }\n\n const clearLabel =\n props.clearLabel ?? tr(\"controlSelect.none\", { default: \"None\" });\n\n // One control for every list. The option count decides whether the popup\n // carries a search field — it no longer decides which primitive renders.\n // The native `Select` path this replaced silently dropped `description`,\n // `tag`, per-option `disabled` and `deselectable`, and styled its trigger\n // differently, purely because a list happened to be short.\n // A search field is offered only when scanning the list by eye stops being\n // realistic: a server-driven list (whose rows are not all here), one past\n // `SEARCH_THRESHOLD`, or one where typing is how a new entry is made.\n //\n // Multi-select used to force it on unconditionally, because the chips box\n // WAS the search input and there was no other way to open the popup. The\n // trigger is a button now, so multi obeys the same rule as everything else\n // and a four-row status filter no longer opens onto a search field.\n const searchable =\n props.searchable ??\n (props.combobox ||\n mode === \"long\" ||\n Boolean(props.createNewEntry) ||\n data.length > SEARCH_THRESHOLD);\n\n return (\n <FormField\n id={meta.id}\n label={meta.label}\n description={meta.description}\n error={meta.error}\n required={meta.required}\n >\n <ControlSelectCombobox\n id={meta.id}\n data={data}\n loading={loading}\n multi={isArray}\n searchable={searchable}\n disabled={props.disabled}\n value={value}\n onChange={(v) => setValue(v)}\n coerce={coerce}\n onSearch={mode === \"long\" ? (text) => search.run(text) : undefined}\n createNewEntry={props.createNewEntry}\n icon={props.icon}\n // Used to be dropped on this path, so a filter chip sized `w-40` lost\n // its width as soon as its list crossed the threshold.\n triggerClassName={props.triggerClassName}\n triggerProps={props.triggerProps}\n size={props.size}\n minimal={props.minimal}\n // `clearable` used to reach this path as a placeholder and nothing\n // else, so a filter chip that had switched to the combobox (>20\n // options) could be set but never put back to \"All …\".\n clearable={props.clearable}\n clearLabel={clearLabel}\n countLabel={props.countLabel}\n maxTriggerLength={props.maxTriggerLength}\n popupHeader={props.popupHeader}\n triggerPrefix={props.triggerPrefix}\n popupClassName={props.popupClassName}\n // An optional field must also be able to go back to empty without a\n // dedicated row: Base UI never emits `null`, so re-pressing the\n // selected row deselects (see `handleSingle` in\n // `ControlSelectCombobox.tsx`). A required field keeps its value —\n // clearing it would only produce a validation error the user cannot\n // see yet.\n deselectable={props.clearable || !meta.required}\n // Multi shows this muted when nothing is picked, so it reaches the\n // trigger whether or not the field is `clearable` — a multi-select\n // has no clear ROW (it clears by deselecting), and without this its\n // empty trigger fell back to a bare \"Select…\".\n placeholder={\n props.placeholder ??\n (props.clearable || isArray ? clearLabel : undefined)\n }\n />\n </FormField>\n );\n};\n\nexport type SelectOption =\n | string\n | {\n value: string;\n label: string;\n /**\n * Optional secondary line shown under the label in the dropdown.\n */\n description?: string;\n /**\n * Optional small badge rendered next to the label.\n */\n tag?: string;\n /**\n * Optional icon/element rendered before the label, in both the\n * dropdown row and (for single-select) the trigger when selected.\n */\n icon?: ReactNode;\n /**\n * When true, the row is non-interactive — can't be selected if\n * not selected, can't be deselected if selected. Useful for\n * default/mandatory entries (e.g. the base \"user\" role).\n */\n disabled?: boolean;\n };\n\ntype LoaderMode = \"static\" | \"short\" | \"long\";\n\n/**\n * How tall and how loud a select trigger is.\n *\n * The kit's own scale, kept under this name because `Control` and a long tail\n * of callers already spell it `size=\"xs\"` on a select. The table behind it,\n * and the trigger box it sizes, are `control-base/field-trigger`'s - shared\n * with the two calendar controls, which used to draw a button instead.\n */\nexport type ControlSelectSize = ControlTriggerSize;\n\n/**\n * Static option count above which the dropdown grows a search input. Below it\n * the very same combobox renders without one — the threshold decides whether\n * you can type, never which control you get.\n */\n// Past this many rows, scanning by eye stops being realistic and the popup\n// grows a search field. Raised 20 -> 50 with the multi-select rework: the old\n// value put a search box on lists a reader takes in at a glance.\nconst SEARCH_THRESHOLD = 50;\n\n/**\n * Friendly label for plain string options: \"optional\" → \"Optional\",\n * \"in_progress\" → \"In Progress\". Custom `{ value, label }` items pass through\n * untouched.\n */\nconst titlecase = (s: string) =>\n s.replace(/[_-]+/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase());\n/**\n * What one segment shows.\n *\n * ⚠️ The option's `icon` is rendered HERE rather than dropped, which is what\n * this path did until #Q2049. `SegmentedOption.label` is a `ReactNode`, so\n * there was never a reason for it: an option list carrying icons for the\n * dropdown carried them for the segments too, and dropping them silently\n * made a caller choose between two shapes for one list.\n */\nconst segmentedLabel = (o: SelectOption): ReactNode => {\n if (typeof o === \"string\") {\n return titlecase(o);\n }\n if (!o.icon) {\n return o.label;\n }\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n {o.icon}\n {o.label}\n </span>\n );\n};\n\nconst useAsyncLoader = (\n loader: ControlSelectProps[\"loader\"],\n threshold: number,\n debounceMs: number,\n defaultValue: unknown,\n) => {\n const [data, setData] = useState<SelectOption[]>([]);\n const [loading, setLoading] = useState(false);\n const [mode, setMode] = useState<LoaderMode>(\"static\");\n const cache = useRef(new Map<string, SelectOption[]>());\n\n useAction(\n {\n // `id`, not `name`: `id` is what useAction threads into its\n // react:action:* events. `name` was accepted and never read, so this\n // identifier reached nothing.\n id: \"select:loader:init\",\n runOnInit: true,\n handler: async () => {\n if (!loader) {\n setMode(\"static\");\n return;\n }\n setLoading(true);\n try {\n const result = await loader(\"\");\n const isShort = result.length <= threshold;\n setMode(isShort ? \"short\" : \"long\");\n cache.current.set(\"\", result);\n setData(result);\n\n // Coercion at a boundary: the value is a form/route/chart primitive whose\n // declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n if (!isShort && defaultValue != null && String(defaultValue) !== \"\") {\n // Coercion at a boundary: the value is a form/route/chart primitive whose\n // declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n const resolved = await loader(\"\", [String(defaultValue)]);\n if (resolved.length > 0) {\n setData((prev) => {\n const existing = new Set(prev.map(optValue));\n const fresh = resolved.filter(\n (r) => !existing.has(optValue(r)),\n );\n return [...prev, ...fresh];\n });\n }\n }\n } finally {\n setLoading(false);\n }\n },\n },\n [loader, threshold],\n );\n\n const search = useAction<[string]>(\n {\n debounce: debounceMs,\n handler: async (_ctx, text) => {\n if (!loader || mode !== \"long\") return;\n if (cache.current.has(text)) {\n setData(cache.current.get(text)!);\n return;\n }\n setLoading(true);\n try {\n const result = await loader(text);\n cache.current.set(text, result);\n setData(result);\n } finally {\n setLoading(false);\n }\n },\n },\n [loader, mode, debounceMs],\n );\n\n return { data, loading, mode, search };\n};\n"],"mappings":";;;;;;;;;;AAwMA,MAAa,iBAAiB,UAA8B;CAC1D,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,OAAO,CAAC;CAChD,MAAM,CAAC,OAAO,YAAY,cAAc,MAAM,KAAK;CAEnD,MAAM,OAAO,WAAW,MAAM,OAAO;EACnC,OAAO,MAAM;EACb,aAAa,MAAM;EACnB,OAAO,KAAK;CACd,CAAC;CAED,MAAM,UAAU,KAAK;CACrB,MAAM,YAAY,KAAK,SAAS,YAAY,KAAK,SAAS;CAC1D,MAAM,YAAY,KAAK,SAAS;CAGhC,MAAM,aAAa,MAAM,QAAQ,MAAM,KAAK,IACvC,MAAM,QACP,KAAA;CACJ,MAAM,cACJ,OAAO,MAAM,UAAU,aAClB,MAAM,QACP,KAAA;CAEN,MAAM,aACJ,cAAe,KAAK,QAAuC,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;GACV,SAAS,OAAO,MAAM,SAAS;IAC7B,IAAI,CAAC,UAAU,SAAS,QAAQ;IAChC,IAAI,MAAM,QAAQ,IAAI,IAAI,GAAG;KAC3B,QAAQ,MAAM,QAAQ,IAAI,IAAI,CAAE;KAChC;IACF;IACA,WAAW,IAAI;IACf,IAAI;KACF,MAAM,SAAS,MAAM,OAAO,IAAI;KAChC,MAAM,QAAQ,IAAI,MAAM,MAAM;KAC9B,QAAQ,MAAM;IAChB,UAAU;KACR,WAAW,KAAK;IAClB;GACF;EACF,GACA;GAAC;GAAQ;GAAM;EAAU,CAGQ;CAAE;AACvC"}
|
|
@@ -40,7 +40,7 @@ export interface ControlUploadProps {
|
|
|
40
40
|
* image the decoder chokes on is uploaded as-is, and the storage's own
|
|
41
41
|
* `maxSize` remains what actually bounds it. That trade is deliberate — a
|
|
42
42
|
* server-side codec able to close the gap costs more bundle than the case is
|
|
43
|
-
* worth on an edge runtime, and encodes worse (see `files:
|
|
43
|
+
* worth on an edge runtime, and encodes worse (see `files:upload:before` in
|
|
44
44
|
* `alepha/api/files` for where it would attach if you want it anyway).
|
|
45
45
|
*
|
|
46
46
|
* @example { maxWidth: 256 }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlUpload.js","names":["FileIcon"],"sources":["../../src/form/ControlUpload.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport type { FileController } from \"alepha/api/files\";\nimport { useClient } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { File as FileIcon, Loader2, Upload, X } from \"lucide-react\";\nimport {\n type ChangeEvent,\n type DragEvent,\n useEffect,\n useId,\n useRef,\n useState,\n} from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"../core/Tooltip.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { formatBytes } from \"../core/utils.ts\";\nimport { ControlUploadItemThumb } from \"./ControlUploadItemThumb.tsx\";\nimport { FormField } from \"./FormField.tsx\";\nimport { type ResizeImageOptions, resizeImage } from \"./resizeImage.ts\";\n\nexport interface ControlUploadProps {\n /**\n * Bound `InputField` from `useForm`. Stores the uploaded file ID(s).\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the dropzone.\n */\n description?: string;\n /**\n * Multi-file mode. The form value becomes an `Array<string>` of file\n * IDs. Single mode (default) stores a bare UUID string.\n */\n multi?: boolean;\n /**\n * HTML `accept` filter on the file picker (e.g. `\"image/*\"`,\n * `\".pdf,.docx\"`).\n */\n accept?: string;\n /**\n * Max size per file (bytes). Files over the limit are rejected.\n */\n maxSize?: number;\n /**\n * Downscale images to these bounds before uploading.\n *\n * Set it wherever the result is rendered small — the bytes never leave the\n * machine, so it speeds up the upload as well as every later fetch. Applied\n * before {@link maxSize}, so a photo that would have been rejected for being\n * too large is resized and accepted instead.\n *\n * Best-effort by design: a browser without `OffscreenCanvas`, an SVG, or an\n * image the decoder chokes on is uploaded as-is, and the storage's own\n * `maxSize` remains what actually bounds it. That trade is deliberate — a\n * server-side codec able to close the gap costs more bundle than the case is\n * worth on an edge runtime, and encodes worse (see `files:beforeUpload` in\n * `alepha/api/files` for where it would attach if you want it anyway).\n *\n * @example { maxWidth: 256 }\n */\n image?: ResizeImageOptions;\n /**\n * Bucket name passed to the upload endpoint.\n */\n bucket?: string;\n /**\n * Disable the dropzone.\n */\n disabled?: boolean;\n}\n\n/**\n * File upload control. Wraps `FileController.uploadFile`, stores the\n * resulting file ID(s) in the form, and renders a thumbnail preview for\n * images and a chip-style summary for everything else.\n *\n * Single-file: form value is a uuid string.\n * Multi-file: form value is an array of uuid strings.\n */\nexport const ControlUpload = (props: ControlUploadProps) => {\n const form = useFormState(props.input, [\"error\"]);\n const [value, setValue] = useFieldValue(props.input);\n const client = useClient<FileController>();\n const { tr } = useI18n();\n const toast = useToast();\n const inputId = useId();\n const fileInputRef = useRef<HTMLInputElement>(null);\n const [uploading, setUploading] = useState(false);\n const [progress, setProgress] = useState(0);\n const [meta, setMeta] = useState<Map<string, UploadedFileMeta>>(new Map());\n const [dragOver, setDragOver] = useState(false);\n const [previewId, setPreviewId] = useState<string | null>(null);\n\n /**\n * Backfill `meta` for ids that arrived from form state (e.g. after a page\n * reload) so the renderer can show a thumbnail / chip instead of the raw\n * uuid. We can't infer the real mime type without an extra request, so we\n * fall back to a stub entry pointing at `/api/files/:id` and let the\n * `<img>` `onError` swap to the generic file chip.\n */\n useEffect(() => {\n const ids: string[] = props.multi\n ? Array.isArray(value)\n ? (value as string[])\n : []\n : value\n ? [value as string]\n : [];\n // Reconciles a cache of per-file metadata against the ids the field now\n // holds, and the entries it keeps were filled in by the upload requests this\n // same effect issues. It is the cache for an external system, not derived\n // state; the updater already no-ops when nothing changed.\n // oxlint-disable-next-line react/set-state-in-effect -- reconciles a cache for an external system, see the comment above\n setMeta((current) => {\n let changed = false;\n const next = new Map(current);\n for (const id of ids) {\n if (!next.has(id)) {\n next.set(id, {\n id,\n name: id,\n previewUrl: `/api/files/${id}`,\n });\n changed = true;\n }\n }\n return changed ? next : current;\n });\n }, [Array.isArray(value) ? value.join(\",\") : value, props.multi]);\n\n if (!props.input?.props) return null;\n\n const fieldMeta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const ids: string[] = props.multi\n ? Array.isArray(value)\n ? (value as string[])\n : []\n : value\n ? [value as string]\n : [];\n\n const handleFiles = async (files: FileList) => {\n if (!files.length) return;\n if (!props.multi && files.length > 1) {\n toast.error(\n tr(\"controlUpload.singleOnly\", { default: \"Only one file allowed\" }),\n );\n return;\n }\n\n setUploading(true);\n setProgress(0);\n const next = new Map(meta);\n const newIds: string[] = [];\n\n try {\n for (let i = 0; i < files.length; i++) {\n // Ahead of the size check on purpose: a 4 MB photo destined for a 32px\n // avatar should become a few kilobytes, not an error.\n const file = props.image\n ? await resizeImage(files[i], props.image)\n : files[i];\n\n if (props.maxSize && file.size > props.maxSize) {\n toast.error(\n tr(\"controlUpload.tooBig\", {\n default: `${file.name} exceeds ${formatBytes(props.maxSize)}`,\n args: [file.name, formatBytes(props.maxSize)],\n }),\n );\n continue;\n }\n\n const resource = await client.uploadFile({\n body: { file },\n query: props.bucket ? { bucket: props.bucket } : ({} as never),\n });\n\n const previewUrl = file.type.startsWith(\"image/\")\n ? URL.createObjectURL(file)\n : undefined;\n\n next.set(resource.id, {\n id: resource.id,\n name: resource.name ?? file.name,\n mimeType: resource.mimeType ?? file.type,\n size: resource.size ?? file.size,\n previewUrl,\n });\n newIds.push(resource.id);\n setProgress(Math.round(((i + 1) / files.length) * 100));\n }\n\n setMeta(next);\n if (props.multi) {\n setValue([...ids, ...newIds]);\n } else if (newIds[0]) {\n setValue(newIds[0]);\n }\n if (newIds.length) {\n toast.success(\n newIds.length === 1\n ? tr(\"controlUpload.uploadedOne\", { default: \"File uploaded\" })\n : tr(\"controlUpload.uploadedMany\", {\n default: `${newIds.length} files uploaded`,\n args: [String(newIds.length)],\n }),\n );\n }\n } catch (e) {\n const msg = (e as Error).message;\n toast.error(\n tr(\"controlUpload.failed\", {\n default: `Upload failed: ${msg}`,\n args: [msg],\n }),\n );\n } finally {\n setUploading(false);\n setProgress(0);\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }\n };\n\n const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {\n if (e.target.files) void handleFiles(e.target.files);\n };\n\n const handleDrop = (e: DragEvent) => {\n e.preventDefault();\n setDragOver(false);\n if (props.disabled) return;\n if (e.dataTransfer.files) void handleFiles(e.dataTransfer.files);\n };\n\n const removeOne = (id: string) => {\n const next = new Map(meta);\n const item = next.get(id);\n if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl);\n next.delete(id);\n setMeta(next);\n\n if (props.multi) {\n setValue(ids.filter((it) => it !== id));\n } else {\n setValue(undefined);\n }\n };\n\n const renderItem = (id: string) => {\n const item = meta.get(id);\n const acceptsImage = (props.accept ?? \"\").includes(\"image\");\n const mimeIsImage = item?.mimeType?.startsWith(\"image/\");\n const isImage =\n mimeIsImage || (acceptsImage && !!item?.previewUrl && !item?.mimeType);\n\n const canClear = !props.disabled && !fieldMeta.required;\n\n return (\n <div\n key={id}\n className={`border-border dark:bg-input/30 relative flex h-9 cursor-zoom-in items-center rounded-md border bg-transparent pl-1 ${canClear ? \"pr-9\" : \"pr-2\"}`}\n onClick={() => setPreviewId(id)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n setPreviewId(id);\n }\n }}\n role=\"button\"\n tabIndex={0}\n >\n {isImage && item?.previewUrl ? (\n <ControlUploadItemThumb url={item.previewUrl} alt={item.name ?? id} />\n ) : (\n <div className=\"bg-muted text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded\">\n <FileIcon className=\"size-4\" />\n </div>\n )}\n {canClear && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n removeOne(id);\n }}\n aria-label={tr(\"controlUpload.remove\", { default: \"Remove\" })}\n className=\"text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2 p-1\"\n >\n <X className=\"size-3.5\" />\n </button>\n )}\n </div>\n );\n };\n\n const previewItem = previewId ? meta.get(previewId) : undefined;\n const previewIsImage = previewItem\n ? previewItem.mimeType?.startsWith(\"image/\") ||\n ((props.accept ?? \"\").includes(\"image\") &&\n !!previewItem.previewUrl &&\n !previewItem.mimeType)\n : false;\n const previewHasName =\n !!previewItem?.name && previewItem.name !== previewItem.id;\n\n const dragDropHint =\n tr(\"controlUpload.dragDrop\", { default: \"Upload or drag and drop here\" }) +\n (props.maxSize\n ? ` · ${tr(\"controlUpload.max\", {\n default: `max ${formatBytes(props.maxSize)}`,\n args: [formatBytes(props.maxSize)],\n })}`\n : \"\");\n\n const dropZone = (\n <Tooltip>\n <TooltipTrigger\n render={\n <Button\n type=\"button\"\n variant=\"outlined\"\n size=\"sm\"\n disabled={props.disabled || uploading}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault();\n setDragOver(true);\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={handleDrop}\n className={dragOver ? \"border-primary bg-primary/5\" : \"\"}\n />\n }\n >\n {uploading ? (\n <>\n <Loader2 className=\"mr-1 size-4 animate-spin\" />\n {tr(\"controlUpload.uploading\", { default: \"Uploading…\" })}\n </>\n ) : (\n <>\n <Upload className=\"mr-1 size-4\" />\n {props.multi\n ? tr(\"controlUpload.chooseFiles\", { default: \"Choose files\" })\n : tr(\"controlUpload.chooseFile\", { default: \"Choose a file\" })}\n </>\n )}\n </TooltipTrigger>\n <TooltipContent>{dragDropHint}</TooltipContent>\n </Tooltip>\n );\n\n return (\n <FormField\n id={inputId}\n label={fieldMeta.label}\n description={fieldMeta.description}\n error={fieldMeta.error}\n required={fieldMeta.required}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n id={inputId}\n name={props.input.props.name}\n className=\"hidden\"\n accept={props.accept}\n multiple={props.multi}\n disabled={props.disabled}\n onChange={handleInputChange}\n />\n\n <div className=\"flex flex-col gap-2\">\n {ids.length > 0 && (\n <div className=\"flex flex-col gap-2\">{ids.map(renderItem)}</div>\n )}\n {(props.multi || ids.length === 0) && dropZone}\n {uploading && (\n <div className=\"bg-muted h-1 w-full overflow-hidden rounded\">\n <div\n className=\"bg-primary h-full transition-all\"\n style={{ width: `${progress}%` }}\n />\n </div>\n )}\n </div>\n\n <Dialog\n open={previewId !== null}\n onOpenChange={(o) => !o && setPreviewId(null)}\n >\n <DialogContent className=\"w-fit max-w-fit p-0\">\n <DialogHeader className=\"sr-only\">\n <DialogTitle>\n {previewHasName\n ? previewItem?.name\n : tr(\"controlUpload.savedFile\", { default: \"Saved file\" })}\n </DialogTitle>\n <DialogDescription>\n {previewItem?.mimeType ?? \"uploaded\"}\n </DialogDescription>\n </DialogHeader>\n <div className=\"p-4\">\n {previewIsImage && previewItem?.previewUrl ? (\n <img\n src={previewItem.previewUrl}\n alt={previewItem.name ?? \"\"}\n className=\"size-72 rounded object-contain\"\n />\n ) : (\n <div className=\"bg-muted text-muted-foreground flex size-72 items-center justify-center rounded\">\n <FileIcon className=\"size-16\" />\n </div>\n )}\n </div>\n {(previewHasName || previewItem?.mimeType) && (\n <div className=\"bg-muted/30 flex flex-col gap-0 border-t px-4 py-2\">\n {previewHasName && (\n <span className=\"truncate text-sm font-medium\">\n {previewItem?.name}\n </span>\n )}\n {previewItem?.mimeType && (\n <span className=\"text-muted-foreground truncate text-xs\">\n {previewItem.mimeType}\n </span>\n )}\n </div>\n )}\n </DialogContent>\n </Dialog>\n </FormField>\n );\n};\n\ninterface UploadedFileMeta {\n id: string;\n name: string;\n mimeType?: string;\n size?: number;\n /**\n * Object URL for image preview, when applicable.\n */\n previewUrl?: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqGA,MAAa,iBAAiB,UAA8B;CAC1D,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,OAAO,CAAC;CAChD,MAAM,CAAC,OAAO,YAAY,cAAc,MAAM,KAAK;CACnD,MAAM,SAAS,UAA0B;CACzC,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,QAAQ,SAAS;CACvB,MAAM,UAAU,MAAM;CACtB,MAAM,eAAe,OAAyB,IAAI;CAClD,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAChD,MAAM,CAAC,UAAU,eAAe,SAAS,CAAC;CAC1C,MAAM,CAAC,MAAM,WAAW,yBAAwC,IAAI,IAAI,CAAC;CACzE,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,WAAW,gBAAgB,SAAwB,IAAI;;;;;;;;CAS9D,gBAAgB;EACd,MAAM,MAAgB,MAAM,QACx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AA;MAEJ,CAAA;OACH,kBAAkB,aAAa,aAC/B,qBAAC,OAAD;OAAK,WAAU;OAAf,UAAA,CACG,kBACC,oBAAC,QAAD;QAAM,WAAU;QACb,UAAA,aAAa;OACV,CAAA,GAEP,aAAa,YACZ,oBAAC,QAAD;QAAM,WAAU;QACb,UAAA,YAAY;OACT,CAAA,CAEL;;KAEM;;GACT,CAAA;EACC;;AAEf"}
|
|
1
|
+
{"version":3,"file":"ControlUpload.js","names":["FileIcon"],"sources":["../../src/form/ControlUpload.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport type { FileController } from \"alepha/api/files\";\nimport { useClient } from \"alepha/react\";\nimport {\n type BaseInputField,\n parseField,\n useFieldValue,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { File as FileIcon, Loader2, Upload, X } from \"lucide-react\";\nimport {\n type ChangeEvent,\n type DragEvent,\n useEffect,\n useId,\n useRef,\n useState,\n} from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"../core/Tooltip.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { formatBytes } from \"../core/utils.ts\";\nimport { ControlUploadItemThumb } from \"./ControlUploadItemThumb.tsx\";\nimport { FormField } from \"./FormField.tsx\";\nimport { type ResizeImageOptions, resizeImage } from \"./resizeImage.ts\";\n\nexport interface ControlUploadProps {\n /**\n * Bound `InputField` from `useForm`. Stores the uploaded file ID(s).\n */\n input: BaseInputField;\n /**\n * Field label. Falls back to schema `title`.\n */\n label?: string;\n /**\n * Helper text shown below the dropzone.\n */\n description?: string;\n /**\n * Multi-file mode. The form value becomes an `Array<string>` of file\n * IDs. Single mode (default) stores a bare UUID string.\n */\n multi?: boolean;\n /**\n * HTML `accept` filter on the file picker (e.g. `\"image/*\"`,\n * `\".pdf,.docx\"`).\n */\n accept?: string;\n /**\n * Max size per file (bytes). Files over the limit are rejected.\n */\n maxSize?: number;\n /**\n * Downscale images to these bounds before uploading.\n *\n * Set it wherever the result is rendered small — the bytes never leave the\n * machine, so it speeds up the upload as well as every later fetch. Applied\n * before {@link maxSize}, so a photo that would have been rejected for being\n * too large is resized and accepted instead.\n *\n * Best-effort by design: a browser without `OffscreenCanvas`, an SVG, or an\n * image the decoder chokes on is uploaded as-is, and the storage's own\n * `maxSize` remains what actually bounds it. That trade is deliberate — a\n * server-side codec able to close the gap costs more bundle than the case is\n * worth on an edge runtime, and encodes worse (see `files:upload:before` in\n * `alepha/api/files` for where it would attach if you want it anyway).\n *\n * @example { maxWidth: 256 }\n */\n image?: ResizeImageOptions;\n /**\n * Bucket name passed to the upload endpoint.\n */\n bucket?: string;\n /**\n * Disable the dropzone.\n */\n disabled?: boolean;\n}\n\n/**\n * File upload control. Wraps `FileController.uploadFile`, stores the\n * resulting file ID(s) in the form, and renders a thumbnail preview for\n * images and a chip-style summary for everything else.\n *\n * Single-file: form value is a uuid string.\n * Multi-file: form value is an array of uuid strings.\n */\nexport const ControlUpload = (props: ControlUploadProps) => {\n const form = useFormState(props.input, [\"error\"]);\n const [value, setValue] = useFieldValue(props.input);\n const client = useClient<FileController>();\n const { tr } = useI18n();\n const toast = useToast();\n const inputId = useId();\n const fileInputRef = useRef<HTMLInputElement>(null);\n const [uploading, setUploading] = useState(false);\n const [progress, setProgress] = useState(0);\n const [meta, setMeta] = useState<Map<string, UploadedFileMeta>>(new Map());\n const [dragOver, setDragOver] = useState(false);\n const [previewId, setPreviewId] = useState<string | null>(null);\n\n /**\n * Backfill `meta` for ids that arrived from form state (e.g. after a page\n * reload) so the renderer can show a thumbnail / chip instead of the raw\n * uuid. We can't infer the real mime type without an extra request, so we\n * fall back to a stub entry pointing at `/api/files/:id` and let the\n * `<img>` `onError` swap to the generic file chip.\n */\n useEffect(() => {\n const ids: string[] = props.multi\n ? Array.isArray(value)\n ? (value as string[])\n : []\n : value\n ? [value as string]\n : [];\n // Reconciles a cache of per-file metadata against the ids the field now\n // holds, and the entries it keeps were filled in by the upload requests this\n // same effect issues. It is the cache for an external system, not derived\n // state; the updater already no-ops when nothing changed.\n // oxlint-disable-next-line react/set-state-in-effect -- reconciles a cache for an external system, see the comment above\n setMeta((current) => {\n let changed = false;\n const next = new Map(current);\n for (const id of ids) {\n if (!next.has(id)) {\n next.set(id, {\n id,\n name: id,\n previewUrl: `/api/files/${id}`,\n });\n changed = true;\n }\n }\n return changed ? next : current;\n });\n }, [Array.isArray(value) ? value.join(\",\") : value, props.multi]);\n\n if (!props.input?.props) return null;\n\n const fieldMeta = parseField(props.input, {\n label: props.label,\n description: props.description,\n error: form.error,\n });\n\n const ids: string[] = props.multi\n ? Array.isArray(value)\n ? (value as string[])\n : []\n : value\n ? [value as string]\n : [];\n\n const handleFiles = async (files: FileList) => {\n if (!files.length) return;\n if (!props.multi && files.length > 1) {\n toast.error(\n tr(\"controlUpload.singleOnly\", { default: \"Only one file allowed\" }),\n );\n return;\n }\n\n setUploading(true);\n setProgress(0);\n const next = new Map(meta);\n const newIds: string[] = [];\n\n try {\n for (let i = 0; i < files.length; i++) {\n // Ahead of the size check on purpose: a 4 MB photo destined for a 32px\n // avatar should become a few kilobytes, not an error.\n const file = props.image\n ? await resizeImage(files[i], props.image)\n : files[i];\n\n if (props.maxSize && file.size > props.maxSize) {\n toast.error(\n tr(\"controlUpload.tooBig\", {\n default: `${file.name} exceeds ${formatBytes(props.maxSize)}`,\n args: [file.name, formatBytes(props.maxSize)],\n }),\n );\n continue;\n }\n\n const resource = await client.uploadFile({\n body: { file },\n query: props.bucket ? { bucket: props.bucket } : ({} as never),\n });\n\n const previewUrl = file.type.startsWith(\"image/\")\n ? URL.createObjectURL(file)\n : undefined;\n\n next.set(resource.id, {\n id: resource.id,\n name: resource.name ?? file.name,\n mimeType: resource.mimeType ?? file.type,\n size: resource.size ?? file.size,\n previewUrl,\n });\n newIds.push(resource.id);\n setProgress(Math.round(((i + 1) / files.length) * 100));\n }\n\n setMeta(next);\n if (props.multi) {\n setValue([...ids, ...newIds]);\n } else if (newIds[0]) {\n setValue(newIds[0]);\n }\n if (newIds.length) {\n toast.success(\n newIds.length === 1\n ? tr(\"controlUpload.uploadedOne\", { default: \"File uploaded\" })\n : tr(\"controlUpload.uploadedMany\", {\n default: `${newIds.length} files uploaded`,\n args: [String(newIds.length)],\n }),\n );\n }\n } catch (e) {\n const msg = (e as Error).message;\n toast.error(\n tr(\"controlUpload.failed\", {\n default: `Upload failed: ${msg}`,\n args: [msg],\n }),\n );\n } finally {\n setUploading(false);\n setProgress(0);\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }\n };\n\n const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {\n if (e.target.files) void handleFiles(e.target.files);\n };\n\n const handleDrop = (e: DragEvent) => {\n e.preventDefault();\n setDragOver(false);\n if (props.disabled) return;\n if (e.dataTransfer.files) void handleFiles(e.dataTransfer.files);\n };\n\n const removeOne = (id: string) => {\n const next = new Map(meta);\n const item = next.get(id);\n if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl);\n next.delete(id);\n setMeta(next);\n\n if (props.multi) {\n setValue(ids.filter((it) => it !== id));\n } else {\n setValue(undefined);\n }\n };\n\n const renderItem = (id: string) => {\n const item = meta.get(id);\n const acceptsImage = (props.accept ?? \"\").includes(\"image\");\n const mimeIsImage = item?.mimeType?.startsWith(\"image/\");\n const isImage =\n mimeIsImage || (acceptsImage && !!item?.previewUrl && !item?.mimeType);\n\n const canClear = !props.disabled && !fieldMeta.required;\n\n return (\n <div\n key={id}\n className={`border-border dark:bg-input/30 relative flex h-9 cursor-zoom-in items-center rounded-md border bg-transparent pl-1 ${canClear ? \"pr-9\" : \"pr-2\"}`}\n onClick={() => setPreviewId(id)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n setPreviewId(id);\n }\n }}\n role=\"button\"\n tabIndex={0}\n >\n {isImage && item?.previewUrl ? (\n <ControlUploadItemThumb url={item.previewUrl} alt={item.name ?? id} />\n ) : (\n <div className=\"bg-muted text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded\">\n <FileIcon className=\"size-4\" />\n </div>\n )}\n {canClear && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n removeOne(id);\n }}\n aria-label={tr(\"controlUpload.remove\", { default: \"Remove\" })}\n className=\"text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2 p-1\"\n >\n <X className=\"size-3.5\" />\n </button>\n )}\n </div>\n );\n };\n\n const previewItem = previewId ? meta.get(previewId) : undefined;\n const previewIsImage = previewItem\n ? previewItem.mimeType?.startsWith(\"image/\") ||\n ((props.accept ?? \"\").includes(\"image\") &&\n !!previewItem.previewUrl &&\n !previewItem.mimeType)\n : false;\n const previewHasName =\n !!previewItem?.name && previewItem.name !== previewItem.id;\n\n const dragDropHint =\n tr(\"controlUpload.dragDrop\", { default: \"Upload or drag and drop here\" }) +\n (props.maxSize\n ? ` · ${tr(\"controlUpload.max\", {\n default: `max ${formatBytes(props.maxSize)}`,\n args: [formatBytes(props.maxSize)],\n })}`\n : \"\");\n\n const dropZone = (\n <Tooltip>\n <TooltipTrigger\n render={\n <Button\n type=\"button\"\n variant=\"outlined\"\n size=\"sm\"\n disabled={props.disabled || uploading}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault();\n setDragOver(true);\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={handleDrop}\n className={dragOver ? \"border-primary bg-primary/5\" : \"\"}\n />\n }\n >\n {uploading ? (\n <>\n <Loader2 className=\"mr-1 size-4 animate-spin\" />\n {tr(\"controlUpload.uploading\", { default: \"Uploading…\" })}\n </>\n ) : (\n <>\n <Upload className=\"mr-1 size-4\" />\n {props.multi\n ? tr(\"controlUpload.chooseFiles\", { default: \"Choose files\" })\n : tr(\"controlUpload.chooseFile\", { default: \"Choose a file\" })}\n </>\n )}\n </TooltipTrigger>\n <TooltipContent>{dragDropHint}</TooltipContent>\n </Tooltip>\n );\n\n return (\n <FormField\n id={inputId}\n label={fieldMeta.label}\n description={fieldMeta.description}\n error={fieldMeta.error}\n required={fieldMeta.required}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n id={inputId}\n name={props.input.props.name}\n className=\"hidden\"\n accept={props.accept}\n multiple={props.multi}\n disabled={props.disabled}\n onChange={handleInputChange}\n />\n\n <div className=\"flex flex-col gap-2\">\n {ids.length > 0 && (\n <div className=\"flex flex-col gap-2\">{ids.map(renderItem)}</div>\n )}\n {(props.multi || ids.length === 0) && dropZone}\n {uploading && (\n <div className=\"bg-muted h-1 w-full overflow-hidden rounded\">\n <div\n className=\"bg-primary h-full transition-all\"\n style={{ width: `${progress}%` }}\n />\n </div>\n )}\n </div>\n\n <Dialog\n open={previewId !== null}\n onOpenChange={(o) => !o && setPreviewId(null)}\n >\n <DialogContent className=\"w-fit max-w-fit p-0\">\n <DialogHeader className=\"sr-only\">\n <DialogTitle>\n {previewHasName\n ? previewItem?.name\n : tr(\"controlUpload.savedFile\", { default: \"Saved file\" })}\n </DialogTitle>\n <DialogDescription>\n {previewItem?.mimeType ?? \"uploaded\"}\n </DialogDescription>\n </DialogHeader>\n <div className=\"p-4\">\n {previewIsImage && previewItem?.previewUrl ? (\n <img\n src={previewItem.previewUrl}\n alt={previewItem.name ?? \"\"}\n className=\"size-72 rounded object-contain\"\n />\n ) : (\n <div className=\"bg-muted text-muted-foreground flex size-72 items-center justify-center rounded\">\n <FileIcon className=\"size-16\" />\n </div>\n )}\n </div>\n {(previewHasName || previewItem?.mimeType) && (\n <div className=\"bg-muted/30 flex flex-col gap-0 border-t px-4 py-2\">\n {previewHasName && (\n <span className=\"truncate text-sm font-medium\">\n {previewItem?.name}\n </span>\n )}\n {previewItem?.mimeType && (\n <span className=\"text-muted-foreground truncate text-xs\">\n {previewItem.mimeType}\n </span>\n )}\n </div>\n )}\n </DialogContent>\n </Dialog>\n </FormField>\n );\n};\n\ninterface UploadedFileMeta {\n id: string;\n name: string;\n mimeType?: string;\n size?: number;\n /**\n * Object URL for image preview, when applicable.\n */\n previewUrl?: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqGA,MAAa,iBAAiB,UAA8B;CAC1D,MAAM,OAAO,aAAa,MAAM,OAAO,CAAC,OAAO,CAAC;CAChD,MAAM,CAAC,OAAO,YAAY,cAAc,MAAM,KAAK;CACnD,MAAM,SAAS,UAA0B;CACzC,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,QAAQ,SAAS;CACvB,MAAM,UAAU,MAAM;CACtB,MAAM,eAAe,OAAyB,IAAI;CAClD,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAChD,MAAM,CAAC,UAAU,eAAe,SAAS,CAAC;CAC1C,MAAM,CAAC,MAAM,WAAW,yBAAwC,IAAI,IAAI,CAAC;CACzE,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,WAAW,gBAAgB,SAAwB,IAAI;;;;;;;;CAS9D,gBAAgB;EACd,MAAM,MAAgB,MAAM,QACxB,MAAM,QAAQ,KAAK,IAChB,QACD,CAAC,IACH,QACE,CAAC,KAAe,IAChB,CAAC;EAMP,SAAS,YAAY;GACnB,IAAI,UAAU;GACd,MAAM,OAAO,IAAI,IAAI,OAAO;GAC5B,KAAK,MAAM,MAAM,KACf,IAAI,CAAC,KAAK,IAAI,EAAE,GAAG;IACjB,KAAK,IAAI,IAAI;KACX;KACA,MAAM;KACN,YAAY,cAAc;IAC5B,CAAC;IACD,UAAU;GACZ;GAEF,OAAO,UAAU,OAAO;EAC1B,CAAC;CACH,GAAG,CAAC,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,GAAG,IAAI,OAAO,MAAM,KAAK,CAAC;CAEhE,IAAI,CAAC,MAAM,OAAO,OAAO,OAAO;CAEhC,MAAM,YAAY,WAAW,MAAM,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|
+
{"version":3,"file":"uiFr.d.ts","sourceRoot":"","sources":["../../../src/i18n/fr/uiFr.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAqrCvC,CAAC"}
|
package/dist/i18n/fr/uiFr.js
CHANGED
|
@@ -688,7 +688,6 @@ const uiFr = {
|
|
|
688
688
|
"admin.userDetail.avatar.replaced": "Avatar remplacé.",
|
|
689
689
|
"admin.userDetail.avatar.remove": "Retirer",
|
|
690
690
|
"admin.userDetail.avatar.removed": "Avatar retiré.",
|
|
691
|
-
"admin.userDetail.avatar.failed": "Impossible de changer l'avatar.",
|
|
692
691
|
"admin.userDetail.credentials": "Identifiants",
|
|
693
692
|
"admin.userDetail.credentialsHasPassword": "Un mot de passe est défini. Vous ne pouvez pas le retirer, mais vous pouvez en définir un nouveau.",
|
|
694
693
|
"admin.userDetail.credentialsNoPassword": "Aucun mot de passe n'est défini. Définissez-en un pour permettre la connexion par mot de passe.",
|
|
@@ -821,7 +820,6 @@ const uiFr = {
|
|
|
821
820
|
"account.delete.confirmBefore": "Saisissez",
|
|
822
821
|
"account.delete.currentPassword": "Mot de passe actuel",
|
|
823
822
|
"account.delete.description": "Cela supprime définitivement votre compte, ses méthodes de connexion et toutes vos sessions. C'est irréversible.",
|
|
824
|
-
"account.delete.error": "Impossible de supprimer votre compte",
|
|
825
823
|
"account.delete.submit": "Supprimer le compte",
|
|
826
824
|
"account.delete.title": "Supprimer votre compte",
|
|
827
825
|
"account.keys.access": "Accès",
|
|
@@ -843,7 +841,6 @@ const uiFr = {
|
|
|
843
841
|
"account.keys.statusAll": "Tous les statuts",
|
|
844
842
|
"account.keys.copied": "Copiée",
|
|
845
843
|
"account.keys.copy": "Copier",
|
|
846
|
-
"account.keys.createError": "Impossible de créer cette clé",
|
|
847
844
|
"account.keys.description": "Une clé agit en votre nom. Révoquez celles que vous ne reconnaissez plus.",
|
|
848
845
|
"account.keys.descriptionLabel": "Description",
|
|
849
846
|
"account.keys.descriptionPlaceholder": "Ce qui l'utilise, et où elle est enregistrée",
|
|
@@ -892,7 +889,6 @@ const uiFr = {
|
|
|
892
889
|
"account.mfa.cannotScan": "Impossible de scanner le code ?",
|
|
893
890
|
"account.mfa.copyCodes": "Copier les codes",
|
|
894
891
|
"account.mfa.enrollError": "Impossible de démarrer l'activation. Fermez cette fenêtre et réessayez.",
|
|
895
|
-
"account.mfa.invalidCode": "Ce code n'est pas valide",
|
|
896
892
|
"account.mfa.preparing": "Préparation…",
|
|
897
893
|
"account.mfa.recoveryCopied": "Codes de secours copiés",
|
|
898
894
|
"account.mfa.recoveryDescription": "Gardez-les en lieu sûr. Chacun ne fonctionne qu'une fois, et c'est la seule fois où ils peuvent être affichés.",
|
|
@@ -918,7 +914,6 @@ const uiFr = {
|
|
|
918
914
|
"account.password.changedWithSessions": "Mot de passe changé - $1 autre(s) session(s) déconnectée(s)",
|
|
919
915
|
"account.password.confirm": "Confirmer le nouveau mot de passe",
|
|
920
916
|
"account.password.current": "Mot de passe actuel",
|
|
921
|
-
"account.password.error": "Impossible d'enregistrer ce mot de passe",
|
|
922
917
|
"account.password.mismatch": "Les deux mots de passe ne correspondent pas",
|
|
923
918
|
"account.password.new": "Nouveau mot de passe",
|
|
924
919
|
"account.password.set": "Mot de passe défini",
|
|
@@ -930,9 +925,7 @@ const uiFr = {
|
|
|
930
925
|
"account.profile.avatarChange": "Changer l'avatar",
|
|
931
926
|
"account.profile.avatarDescription": "PNG, JPEG, GIF ou WebP, jusqu'à 5 Mo.",
|
|
932
927
|
"account.profile.avatarRemove": "Supprimer",
|
|
933
|
-
"account.profile.avatarRemoveError": "Impossible de supprimer votre avatar",
|
|
934
928
|
"account.profile.avatarUpdated": "Avatar mis à jour",
|
|
935
|
-
"account.profile.avatarUploadError": "Impossible d'envoyer cette image",
|
|
936
929
|
"account.profile.email": "E-mail",
|
|
937
930
|
"account.profile.emailDescription": "Changer d'e-mail demande une vérification, ce n'est donc pas une modification de profil.",
|
|
938
931
|
"account.profile.emailUnset": "Non renseigné",
|
|
@@ -952,7 +945,6 @@ const uiFr = {
|
|
|
952
945
|
"account.security.delete": "Supprimer ce compte",
|
|
953
946
|
"account.security.deleteButton": "Supprimer le compte",
|
|
954
947
|
"account.security.deleteDescription": "Supprime votre compte, ses méthodes de connexion et toutes vos sessions.",
|
|
955
|
-
"account.security.invalidCode": "Ce code n'est pas valide",
|
|
956
948
|
"account.security.methodsDescription": "Il doit en rester au moins une. Supprimer la dernière vous priverait définitivement d'accès.",
|
|
957
949
|
"account.security.methodsTitle": "Méthodes de connexion",
|
|
958
950
|
"account.security.mfa": "Double authentification",
|
|
@@ -976,7 +968,6 @@ const uiFr = {
|
|
|
976
968
|
"account.security.unlink": "Supprimer",
|
|
977
969
|
"account.security.unlinkAria": "Supprimer $1",
|
|
978
970
|
"account.security.unlinkDescription": "Vous ne pourrez plus vous connecter avec $1.",
|
|
979
|
-
"account.security.unlinkError": "Impossible de supprimer cette méthode",
|
|
980
971
|
"account.security.unlinkTitle": "Supprimer $1 ?",
|
|
981
972
|
"account.sessions.colDevice": "Appareil",
|
|
982
973
|
"account.sessions.colIp": "IP",
|