@recursica/mantine-adapter 0.40.0 → 0.41.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.
@@ -1,7 +1,410 @@
1
- import React from "react";
1
+ import React, { forwardRef, useEffect, useRef, useState } from "react";
2
+ import { type InputWrapperProps } from "@mantine/core";
3
+ import {
4
+ filterStylingProps,
5
+ type RecursicaOverStyled,
6
+ } from "../../utils/filterStylingProps";
7
+ import { Button } from "../Button/Button";
8
+ import { Chip } from "../Chip/Chip";
9
+ import {
10
+ FormControlWrapper,
11
+ type RecursicaFormControlWrapperProps,
12
+ } from "../FormControlWrapper/FormControlWrapper";
13
+ import styles from "./FileInput.module.css";
2
14
 
3
- export type FileInputProps = React.HTMLAttributes<HTMLDivElement>;
15
+ import {
16
+ fileMatchesAccept,
17
+ type RecursicaFileUploadItem,
18
+ type RecursicaFileInputProps as BaseRecursicaFileInputProps,
19
+ } from "@recursica/adapter-common";
20
+ export type { RecursicaFileUploadItem };
4
21
 
5
- export const FileInput: React.FC<FileInputProps> = (props) => {
6
- return <div {...props}>FileInput</div>;
7
- };
22
+ export interface RecursicaFileInputProps
23
+ extends Omit<
24
+ React.HTMLAttributes<HTMLDivElement>,
25
+ "children" | "onDrop" | "onChange"
26
+ >,
27
+ Pick<
28
+ InputWrapperProps,
29
+ "label" | "error" | "required" | "withAsterisk" | "id"
30
+ >,
31
+ Omit<
32
+ RecursicaFormControlWrapperProps,
33
+ "controlMaxWidth" | "controlMinWidth"
34
+ >,
35
+ BaseRecursicaFileInputProps {}
36
+
37
+ export type FileInputProps = RecursicaOverStyled<RecursicaFileInputProps>;
38
+
39
+ function UploadIcon() {
40
+ return (
41
+ <svg
42
+ xmlns="http://www.w3.org/2000/svg"
43
+ viewBox="0 0 24 24"
44
+ fill="none"
45
+ stroke="currentColor"
46
+ strokeWidth="2"
47
+ strokeLinecap="round"
48
+ strokeLinejoin="round"
49
+ aria-hidden
50
+ >
51
+ <path d="M12 3v12" />
52
+ <path d="M7 8l5-5 5 5" />
53
+ <path d="M4 21h16" />
54
+ </svg>
55
+ );
56
+ }
57
+
58
+ function ClearIcon() {
59
+ return (
60
+ <svg
61
+ xmlns="http://www.w3.org/2000/svg"
62
+ viewBox="0 0 24 24"
63
+ fill="none"
64
+ stroke="currentColor"
65
+ strokeWidth="2"
66
+ strokeLinecap="round"
67
+ strokeLinejoin="round"
68
+ aria-hidden
69
+ >
70
+ <line x1="18" y1="6" x2="6" y2="18" />
71
+ <line x1="6" y1="6" x2="18" y2="18" />
72
+ </svg>
73
+ );
74
+ }
75
+
76
+ /**
77
+ * A single-line, `TextField`-shaped control for choosing one or more files, sharing
78
+ * `FileUpload`'s selection/validation interface (`accept`/`maxSize`/`maxFiles`, `readOnly`)
79
+ * behind a different presentation.
80
+ *
81
+ * @example
82
+ * <FileInput
83
+ * label="Resume"
84
+ * files={files}
85
+ * onFilesAdded={(added) => setFiles(added.map((file) => ({ file })))}
86
+ * onFileRemove={() => setFiles([])}
87
+ * />
88
+ */
89
+ export const FileInput = forwardRef<HTMLDivElement, FileInputProps>(
90
+ function FileInput(props, ref) {
91
+ const {
92
+ overStyled = false,
93
+ formLayout = "stacked",
94
+
95
+ // Label & Wrapper Maps
96
+ labelSize,
97
+ labelAlignment,
98
+ labelOptionalText,
99
+ labelWithEditIcon,
100
+ labelActionArea,
101
+ onLabelEditClick,
102
+
103
+ label,
104
+ assistiveText,
105
+ assistiveWithIcon,
106
+ error,
107
+ required,
108
+ withAsterisk,
109
+ id,
110
+ className,
111
+ style,
112
+ disabled,
113
+ readOnly,
114
+
115
+ files,
116
+ onFilesAdded,
117
+ onFileRemove,
118
+ accept,
119
+ multiple = false,
120
+ maxSize,
121
+ maxFiles,
122
+ onFilesRejected,
123
+ invalidFileTypeMessage = "File type not accepted",
124
+ maxFilesMessage = multiple
125
+ ? `Maximum of ${maxFiles} files allowed`
126
+ : "Only one file is allowed",
127
+ icon,
128
+ placeholder = "Select a file...",
129
+ browseLabel = "Choose file",
130
+ removeFileLabel = "Remove",
131
+ clearLabel = "Clear",
132
+ ...rest
133
+ } = props;
134
+
135
+ const sanitizedProps = filterStylingProps(rest, overStyled);
136
+ const restRecord = sanitizedProps as Record<string, unknown>;
137
+
138
+ const interactive = !disabled && !readOnly;
139
+ const hasFiles = !!files && files.length > 0;
140
+
141
+ const inputRef = useRef<HTMLInputElement>(null);
142
+
143
+ // Whether the most recent drop/pick attempt included a file that failed the `accept` check —
144
+ // surfaced as the control's error state (see `effectiveError` below), same as FileUpload.
145
+ const [invalidTypeRejected, setInvalidTypeRejected] = useState(false);
146
+ // Whether the most recent drop/pick attempt included a file past the effective cap — 1 in
147
+ // single-file mode, `maxFiles` in multiple-file mode.
148
+ const [tooManyFilesRejected, setTooManyFilesRejected] = useState(false);
149
+
150
+ const handleFiles = (incoming: FileList | File[]) => {
151
+ if (!interactive) return;
152
+ const list = Array.from(incoming);
153
+ if (list.length === 0) return;
154
+
155
+ // Single-file mode always replaces the current selection rather than adding to it, so it
156
+ // never counts the existing file against the cap — the effective cap is just 1.
157
+ const effectiveMaxFiles = multiple ? maxFiles : 1;
158
+ const currentCount = multiple ? (files?.length ?? 0) : 0;
159
+
160
+ const accepted: File[] = [];
161
+ const rejected: File[] = [];
162
+ let hasInvalidType = false;
163
+ let hasTooMany = false;
164
+ for (const file of list) {
165
+ const isInvalidType = !fileMatchesAccept(file, accept);
166
+ if (isInvalidType) hasInvalidType = true;
167
+ const isTooLarge = maxSize !== undefined && file.size > maxSize;
168
+ const wouldExceedMax =
169
+ effectiveMaxFiles !== undefined &&
170
+ currentCount + accepted.length >= effectiveMaxFiles;
171
+ if (wouldExceedMax) hasTooMany = true;
172
+ const isRejected = isInvalidType || isTooLarge || wouldExceedMax;
173
+ (isRejected ? rejected : accepted).push(file);
174
+ }
175
+ setInvalidTypeRejected(hasInvalidType);
176
+ setTooManyFilesRejected(hasTooMany);
177
+ if (accepted.length > 0) onFilesAdded?.(accepted);
178
+ if (rejected.length > 0) onFilesRejected?.(rejected);
179
+ };
180
+
181
+ // Counts nested dragenter/dragleave pairs (they fire for every child element the pointer
182
+ // crosses, not just the root itself) so the drag-over visual state only clears once the
183
+ // pointer has actually left the control, not just moved between its children. Mirrors
184
+ // FileUpload's dropzone.
185
+ const dragCounterRef = useRef(0);
186
+ const [isDragging, setIsDragging] = useState(false);
187
+
188
+ const handleDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
189
+ event.preventDefault();
190
+ dragCounterRef.current += 1;
191
+ setIsDragging(true);
192
+ };
193
+
194
+ const handleDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
195
+ event.preventDefault();
196
+ dragCounterRef.current -= 1;
197
+ if (dragCounterRef.current <= 0) {
198
+ dragCounterRef.current = 0;
199
+ setIsDragging(false);
200
+ }
201
+ };
202
+
203
+ const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
204
+ // Required so the browser treats this element as a valid drop target.
205
+ event.preventDefault();
206
+ };
207
+
208
+ const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
209
+ event.preventDefault();
210
+ dragCounterRef.current = 0;
211
+ setIsDragging(false);
212
+ handleFiles(event.dataTransfer.files);
213
+ };
214
+
215
+ const openFilePicker = () => {
216
+ if (!interactive) return;
217
+ inputRef.current?.click();
218
+ };
219
+
220
+ const handleRootKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
221
+ if (event.key !== "Enter" && event.key !== " ") return;
222
+ event.preventDefault();
223
+ openFilePicker();
224
+ };
225
+
226
+ const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
227
+ if (event.target.files) handleFiles(event.target.files);
228
+ // Reset so picking the same file again still fires a change event.
229
+ event.target.value = "";
230
+ };
231
+
232
+ const handleClearAll = () => {
233
+ if (!interactive || !files || files.length === 0) return;
234
+ files.forEach((item) => onFileRemove?.(item.id ?? item.file.name));
235
+ };
236
+
237
+ // Roving tabindex across the file chip list (single- or multiple-file mode): only the
238
+ // "active" chip's remove icon is a tab stop, and Left/Right/Up/Down move it — same pattern
239
+ // as FileUpload, see FILEINPUT_IMPLEMENTATION_NOTES.md.
240
+ const [activeChipIndex, setActiveChipIndex] = useState(0);
241
+ const removeIconRefs = useRef<Array<HTMLSpanElement | null>>([]);
242
+ const prevFileCountRef = useRef(files?.length ?? 0);
243
+
244
+ useEffect(() => {
245
+ const count = files?.length ?? 0;
246
+ if (count > 0 && count < prevFileCountRef.current) {
247
+ const nextIndex = Math.min(activeChipIndex, count - 1);
248
+ setActiveChipIndex(nextIndex);
249
+ removeIconRefs.current[nextIndex]?.focus();
250
+ }
251
+ prevFileCountRef.current = count;
252
+ // Only react to the file list itself shrinking/growing, not to activeChipIndex changes.
253
+ // eslint-disable-next-line react-hooks/exhaustive-deps
254
+ }, [files]);
255
+
256
+ const handleChipRowKeyDown = (
257
+ event: React.KeyboardEvent<HTMLDivElement>,
258
+ ) => {
259
+ const count = files?.length ?? 0;
260
+ if (count === 0) return;
261
+ let nextIndex: number | undefined;
262
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") {
263
+ nextIndex = (activeChipIndex + 1) % count;
264
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
265
+ nextIndex = (activeChipIndex - 1 + count) % count;
266
+ }
267
+ if (nextIndex === undefined) return;
268
+ event.preventDefault();
269
+ event.stopPropagation();
270
+ setActiveChipIndex(nextIndex);
271
+ removeIconRefs.current[nextIndex]?.focus();
272
+ };
273
+
274
+ // The built-in `accept`/cap-mismatch message is only shown when the integrator hasn't
275
+ // supplied their own `error` — an explicit error always wins.
276
+ const effectiveError =
277
+ error ??
278
+ (invalidTypeRejected
279
+ ? invalidFileTypeMessage
280
+ : tooManyFilesRejected
281
+ ? maxFilesMessage
282
+ : undefined);
283
+
284
+ const wrapperClass = className
285
+ ? `${styles.layoutOverride} ${className}`
286
+ : styles.layoutOverride;
287
+
288
+ return (
289
+ <FormControlWrapper
290
+ overStyled={overStyled as true}
291
+ className={wrapperClass}
292
+ style={style}
293
+ formLayout={formLayout}
294
+ labelSize={labelSize}
295
+ labelAlignment={labelAlignment}
296
+ labelOptionalText={labelOptionalText}
297
+ labelWithEditIcon={labelWithEditIcon}
298
+ labelActionArea={labelActionArea}
299
+ onLabelEditClick={onLabelEditClick}
300
+ label={label}
301
+ assistiveText={assistiveText}
302
+ assistiveWithIcon={assistiveWithIcon}
303
+ error={effectiveError}
304
+ required={required}
305
+ withAsterisk={withAsterisk}
306
+ id={id}
307
+ controlMaxWidth="var(--file-input-control-max-width)"
308
+ controlMinWidth="var(--file-input-control-min-width)"
309
+ >
310
+ <div
311
+ ref={ref}
312
+ className={styles.root}
313
+ role="button"
314
+ aria-label={browseLabel}
315
+ aria-disabled={disabled ? "true" : undefined}
316
+ tabIndex={interactive ? 0 : -1}
317
+ data-disabled={disabled ? "true" : undefined}
318
+ data-readonly={readOnly ? "true" : undefined}
319
+ data-error={effectiveError ? "true" : undefined}
320
+ data-dragging={isDragging ? "true" : undefined}
321
+ onClick={interactive ? openFilePicker : undefined}
322
+ onKeyDown={interactive ? handleRootKeyDown : undefined}
323
+ onDragEnter={interactive ? handleDragEnter : undefined}
324
+ onDragLeave={interactive ? handleDragLeave : undefined}
325
+ onDragOver={interactive ? handleDragOver : undefined}
326
+ onDrop={interactive ? handleDrop : undefined}
327
+ {...restRecord}
328
+ >
329
+ <span className={styles.leadingIcon} aria-hidden>
330
+ {icon ?? <UploadIcon />}
331
+ </span>
332
+
333
+ <div className={styles.content}>
334
+ {!hasFiles && (
335
+ <span className={styles.value} data-placeholder="true">
336
+ {placeholder}
337
+ </span>
338
+ )}
339
+
340
+ {hasFiles && (
341
+ <div
342
+ className={styles.chipRow}
343
+ onKeyDown={readOnly ? undefined : handleChipRowKeyDown}
344
+ >
345
+ {files!.map((item: RecursicaFileUploadItem, index) => {
346
+ const itemId = item.id ?? item.file.name;
347
+ return (
348
+ <span
349
+ key={itemId}
350
+ className={styles.chipWrapper}
351
+ onClick={(e) => e.stopPropagation()}
352
+ >
353
+ <Chip
354
+ checked={false}
355
+ tabIndex={-1}
356
+ removeLabel={readOnly ? undefined : removeFileLabel}
357
+ removeTabIndex={
358
+ !readOnly && index === activeChipIndex ? 0 : -1
359
+ }
360
+ removeIconRef={(el) => {
361
+ removeIconRefs.current[index] = el;
362
+ }}
363
+ onRemove={
364
+ readOnly || disabled
365
+ ? undefined
366
+ : () => onFileRemove?.(itemId)
367
+ }
368
+ >
369
+ {item.file.name}
370
+ </Chip>
371
+ </span>
372
+ );
373
+ })}
374
+ </div>
375
+ )}
376
+ </div>
377
+
378
+ {hasFiles && !readOnly && (
379
+ <Button
380
+ overStyled
381
+ variant="text"
382
+ size="small"
383
+ icon={<ClearIcon />}
384
+ aria-label={clearLabel}
385
+ className={styles.trailingIcon}
386
+ disabled={disabled}
387
+ onClick={(e) => {
388
+ e.preventDefault();
389
+ e.stopPropagation();
390
+ handleClearAll();
391
+ }}
392
+ />
393
+ )}
394
+
395
+ <input
396
+ ref={inputRef}
397
+ type="file"
398
+ hidden
399
+ accept={accept}
400
+ multiple={multiple}
401
+ disabled={!interactive}
402
+ onChange={handleInputChange}
403
+ />
404
+ </div>
405
+ </FormControlWrapper>
406
+ );
407
+ },
408
+ );
409
+
410
+ FileInput.displayName = "FileInput";
@@ -14,23 +14,131 @@ import { FileInput } from "@recursica/mantine-adapter";
14
14
 
15
15
  ## 2. Basic Example
16
16
 
17
+ `FileInput` is a **controlled** component: it never stores the selected file(s) itself. `onFilesAdded` reports newly picked/dropped files, `onFileRemove` reports which file was removed (or cleared), and you own the `files` array in between.
18
+
19
+ It shares `FileUpload`'s selection/validation interface, but is presented as a single-line, `TextField`-shaped control instead of a dropzone — every selected file renders as a removable chip in a horizontally scrollable row, whether `multiple` is set or not.
20
+
17
21
  ```tsx
18
- import React from "react";
22
+ import React, { useState } from "react";
19
23
  import { FileInput } from "@recursica/mantine-adapter";
24
+ import { type RecursicaFileUploadItem } from "@recursica/adapter-common";
20
25
 
21
26
  export default function Demo() {
22
- return <FileInput label="Upload Resume" placeholder="Choose a file..." />;
27
+ const [files, setFiles] = useState<RecursicaFileUploadItem[]>([]);
28
+
29
+ return (
30
+ <FileInput
31
+ label="Resume"
32
+ files={files}
33
+ onFilesAdded={(added) => setFiles(added.map((file) => ({ file })))}
34
+ onFileRemove={() => setFiles([])}
35
+ />
36
+ );
23
37
  }
24
38
  ```
25
39
 
40
+ Note that a single-file `onFilesAdded` handler typically **replaces** `files` wholesale (as above)
41
+ rather than appending — picking a new file in single-file mode always replaces the current one.
42
+
43
+ ---
44
+
45
+ ## 3. Props Reference
46
+
47
+ | Prop | Type | Description |
48
+ | ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
49
+ | `files` | `RecursicaFileUploadItem[]` | Files currently selected. Each item is `{ file: File; id?: string }`. |
50
+ | `onFilesAdded` | `(files: File[]) => void` | Called with newly picked/dropped files. Only the new files — merge them into `files` yourself. |
51
+ | `onFileRemove` | `(id: string) => void` | Called with a file's `id` (or `file.name` if no `id` was given) when it's removed via a chip's remove icon or the trailing clear button. |
52
+ | `accept` | `string` | Native `accept` attribute (e.g. `".pdf,.png"` or `"image/*"`) — constrains the picker dialog, and is also enforced against dropped files (via `onFilesRejected`), since the browser never applies `accept` to a `drop` event itself. |
53
+ | `multiple` | `boolean` | Whether more than one file can be selected/dropped at once. Defaults to `false`, unlike `FileUpload` (defaults to `true`). |
54
+ | `maxSize` | `number` | Maximum size per file, in bytes. Oversized files go to `onFilesRejected` instead of `onFilesAdded`. |
55
+ | `maxFiles` | `number` | Maximum total number of files allowed. Only meaningful when `multiple` is `true` — single-file mode always caps at 1 regardless of this prop. |
56
+ | `onFilesRejected` | `(files: File[]) => void` | Called with files rejected for exceeding `maxSize`/`maxFiles` (or the single-file cap) or not matching `accept`. |
57
+ | `invalidFileTypeMessage` | `React.ReactNode` | Error message shown when a file is rejected for not matching `accept`. Defaults to `"File type not accepted"`. An explicit `error` prop always takes priority over this. |
58
+ | `maxFilesMessage` | `React.ReactNode` | Error message shown when a file is rejected for exceeding the cap. Defaults to `"Maximum of {maxFiles} files allowed"` when `multiple`, or `"Only one file is allowed"` otherwise. An explicit `error` prop always wins. |
59
+ | `icon` | `React.ReactNode` | Leading icon shown inside the control. Defaults to the built-in upload icon. |
60
+ | `placeholder` | `React.ReactNode` | Text shown when no file is selected. Defaults to `"Select a file..."`. |
61
+ | `browseLabel` | `string` | Screen-reader label for the control itself (it's the sole interactive/focusable surface, there being no separate "Browse" button). Defaults to `"Choose file"`. |
62
+ | `removeFileLabel` | `string` | Screen-reader label for a file chip's remove button. Defaults to `"Remove"`. |
63
+ | `clearLabel` | `string` | Screen-reader label (`aria-label`) for the trailing clear-all `Button`. Defaults to `"Clear"`. |
64
+ | `disabled` | `boolean` | Disables the control and its clear/remove icons. |
65
+ | `readOnly` | `boolean` | Renders `files` as a static, non-interactive display with no clear/remove icons, and disables picking or dropping new files. |
66
+
67
+ `FileInput` also accepts the standard Recursica form-control props (`label`, `assistiveText`, `error`, `required`, `withAsterisk`, `formLayout`, `labelSize`, `labelAlignment`, `labelOptionalText`, `labelWithEditIcon`, `onLabelEditClick`) — see [FormControlWrapper's USAGE.md](../FormControlWrapper/USAGE.md) for how these behave.
68
+
69
+ ---
70
+
71
+ ## 4. Multiple Files
72
+
73
+ ```tsx
74
+ <FileInput
75
+ label="Attachments"
76
+ assistiveText="Up to 5 files"
77
+ multiple
78
+ files={files}
79
+ onFilesAdded={(added) =>
80
+ setFiles((prev) => [...prev, ...added.map((file) => ({ file }))])
81
+ }
82
+ onFileRemove={(id) =>
83
+ setFiles((prev) =>
84
+ prev.filter((item) => (item.id ?? item.file.name) !== id),
85
+ )
86
+ }
87
+ />
88
+ ```
89
+
90
+ With `multiple`, the same horizontally scrollable row of removable chips (the same `Chip`
91
+ component `FileUpload` uses) can hold more than one file, and the trailing `Button` clears the
92
+ entire selection at once rather than removing a single file.
93
+
94
+ ---
95
+
96
+ ## 5. Rejecting Oversized or Wrong-Type Files
97
+
98
+ Works exactly like `FileUpload`:
99
+
100
+ ```tsx
101
+ <FileInput
102
+ label="Resume"
103
+ assistiveText="PDF only, max 5MB"
104
+ accept=".pdf"
105
+ maxSize={5 * 1024 * 1024}
106
+ files={files}
107
+ onFilesAdded={(added) => setFiles(added.map((file) => ({ file })))}
108
+ onFileRemove={() => setFiles([])}
109
+ />
110
+ ```
111
+
112
+ A mismatched or oversized file puts the control into its error state automatically — no need to
113
+ wire `onFilesRejected` into your own `error` prop just to show something. Override the message
114
+ with `invalidFileTypeMessage`/`maxFilesMessage`, or pass your own `error` prop to take over the
115
+ error state entirely.
116
+
117
+ ---
118
+
119
+ ## 6. Read-Only Display
120
+
121
+ ```tsx
122
+ <FileInput
123
+ label="Submitted Files"
124
+ assistiveText="Submitted files cannot be changed"
125
+ multiple
126
+ readOnly
127
+ files={files}
128
+ />
129
+ ```
130
+
131
+ Renders `files` as a static display with no clear/remove icons, and the control is no longer
132
+ focusable or clickable.
133
+
26
134
  ---
27
135
 
28
- ## 3. Design System Integration
136
+ ## 7. Design System Integration
29
137
 
30
138
  All Recursica components in the `@recursica/mantine-adapter` package adhere strictly to design system spacing, scaling, and behavior patterns.
31
139
 
32
140
  > [!IMPORTANT]
33
141
  >
34
- > - **Anti-override protection**: Rogues style injections (like inline `style` or arbitrary `className`) are automatically blocked by our prop layer unless `overStyled={true}` is explicitly provided.
142
+ > - **Anti-override protection**: Rogue style injections (like inline `style` or arbitrary `className`) are automatically blocked by our prop layer unless `overStyled={true}` is explicitly provided.
35
143
  > - **No Direct Layers**: Do not pass a `layer` prop to this component. To place it on a specific visual layer, wrap it in a `<Layer layer={0|1|2|3}>` component natively.
36
144
  > - **Variables and Theming**: Styling is entirely determined by local CSS variables defined in `recursica_variables_scoped.css` and mapped in the component's CSS module.