Skip to content

Commit

Permalink
chore: expose details to validate method
Browse files Browse the repository at this point in the history
  • Loading branch information
anubra266 committed Nov 21, 2024
1 parent fb6fa8d commit a55b68e
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/few-spiders-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zag-js/file-upload": patch
---

Expose `details` to `validate` method
19 changes: 16 additions & 3 deletions examples/next-ts/pages/file-upload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,22 @@ import { useControls } from "../hooks/use-controls"
export default function Page() {
const controls = useControls(fileUploadControls)

const [state, send] = useMachine(fileUpload.machine({ id: useId() }), {
context: controls.context,
})
const [state, send] = useMachine(
fileUpload.machine({
id: useId(),
validate(file, { acceptedFiles, rejectedFiles }) {
// Check for duplicate files by comparing names in acceptedFiles
const duplicate = [...acceptedFiles, ...rejectedFiles].some((uploadedFile) => uploadedFile.name === file.name)
if (duplicate) {
return [`The file "${file.name}" has already been uploaded.`]
}
return null // No errors
},
}),
{
context: controls.context,
},
)

const api = fileUpload.connect(state, send, normalizeProps)

Expand Down
2 changes: 1 addition & 1 deletion packages/machines/file-upload/src/file-upload.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ interface PublicContext extends LocaleProperties, CommonProperties {
/**
* Function to validate a file
*/
validate?: ((file: File) => FileError[] | null) | undefined
validate?: ((file: File, details: FileChangeDetails) => FileError[] | null) | undefined
/**
* Function called when the value changes, whether accepted or rejected
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/machines/file-upload/src/file-upload.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function getFilesFromEvent(ctx: MachineContext, files: File[]) {
const [accepted, acceptError] = isValidFileType(file, ctx.acceptAttr)
const [sizeMatch, sizeError] = isValidFileSize(file, ctx.minFileSize, ctx.maxFileSize)

const validateErrors = ctx.validate?.(file)
const validateErrors = ctx.validate?.(file, { acceptedFiles: ctx.acceptedFiles, rejectedFiles: ctx.rejectedFiles })
const valid = validateErrors ? validateErrors.length === 0 : true

if (accepted && sizeMatch && valid) {
Expand Down

0 comments on commit a55b68e

Please sign in to comment.