All components
File Upload
Dashed dropzone with a file item list showing names, sizes, and delete triggers.
Attachments
- brand-guidelines.pdf1.3 MB
- logo.svg18 kB
1234567891011121314151617181920212223242526272829import { FileUpload } from "#components/ui/ui-sdk/file-upload.tsx";
export function Example() { return ( // UI SDK's FileInput validates and holds the files (accept, maxFiles, // maxSize, ...) and submits them with a form via `name`. ItemGroup // renders its Item once per file — no mapping — and is one Tab stop: // arrows move between files, Delete or Backspace removes one <FileUpload.Root maxFiles={5} name="attachments"> <FileUpload.Label>Attachments</FileUpload.Label> <FileUpload.Dropzone> <FileUpload.DropzoneContent> Drag files here or click to browse </FileUpload.DropzoneContent> </FileUpload.Dropzone> <FileUpload.ItemGroup aria-label="Attachments"> <FileUpload.Item> <FileUpload.ItemContent> <FileUpload.ItemName /> <FileUpload.ItemSizeText /> </FileUpload.ItemContent> <FileUpload.ItemDeleteTrigger /> </FileUpload.Item> </FileUpload.ItemGroup> </FileUpload.Root> );}
// file list in code: <FileUpload.Context>{(api) => api.files.length}</FileUpload.Context>Install
1npx stylexblocks add file-uploadSource
components/ui/ui-sdk/file-upload.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437import * as stylex from "@stylexjs/stylex";import { createContext, useContext, useState } from "react";import { createFileInputController, FileInput as UiSdkFileInput, FileInputDropzone, FileInputItem, FileInputItemRemove, FileInputList, FileInputTrigger, formatFileSize, type FileInputController, type FileInputState,} from "@ui-sdk/react/file-input";import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";import { defineSlotRecipe, resolveSlotStyles, type StyleOverrideProps,} from "#lib/recipe-props.ts";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const fileUploadRoot = stylex.create({ base: { display: 'flex', flexDirection: 'column', gap: spacing._4, width: '100%', alignItems: 'flex-start', },})
const fileUploadLabel = stylex.create({ base: { fontWeight: fontWeights.medium, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, },})
const fileUploadDropzone = stylex.create({ base: { backgroundColor: semanticColors.bg, borderRadius: semanticRadii.panel, borderWidth: '1px', borderStyle: 'dashed', display: 'flex', alignItems: 'center', flexDirection: 'column', gap: spacing._4, justifyContent: 'center', padding: spacing._4, transition: 'backgrounds', outlineWidth: { default: null, ':focus-visible': '1px', }, outlineOffset: { default: null, ':focus-visible': '2px', }, outlineStyle: { default: null, ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
const fileUploadDropzoneContent = stylex.create({ base: { display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: spacing._4, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, },})
const fileUploadItem = stylex.create({ base: { fontSize: fontSizes.sm, lineHeight: lineHeights.sm, animationName: 'fade-in', animationDuration: durations.moderate, backgroundColor: semanticColors.bg, borderRadius: semanticRadii.panel, borderWidth: '1px', width: '100%', display: 'flex', alignItems: 'center', gap: spacing._3, paddingInline: spacing._4, paddingBlock: spacing._2, },})
const fileUploadItemGroup = stylex.create({ base: { width: '100%', display: 'flex', flexDirection: 'column', gap: spacing._3, },})
const fileUploadItemName = stylex.create({ base: { color: semanticColors.fg, fontWeight: fontWeights.medium, lineClamp: 1, },})
const fileUploadItemContent = stylex.create({ base: { display: 'flex', flexDirection: 'column', gap: spacing._0_5, flex: 1, },})
const fileUploadItemSizeText = stylex.create({ base: { color: semanticColors.fgMuted, fontSize: fontSizes.xs, lineHeight: lineHeights.xs, },})
const fileUploadItemDeleteTrigger = stylex.create({ base: { alignSelf: 'flex-start', },})
const fileUploadItemPreviewImage = stylex.create({ base: { width: sizes._10, height: sizes._10, objectFit: 'scale-down', },})
const fileUploadRecipe = defineSlotRecipe({ slots: { root: { styles: fileUploadRoot }, label: { styles: fileUploadLabel }, dropzone: { styles: fileUploadDropzone }, dropzoneContent: { styles: fileUploadDropzoneContent }, item: { styles: fileUploadItem }, itemGroup: { styles: fileUploadItemGroup }, itemName: { styles: fileUploadItemName }, itemContent: { styles: fileUploadItemContent }, itemSizeText: { styles: fileUploadItemSizeText }, itemDeleteTrigger: { styles: fileUploadItemDeleteTrigger }, itemPreviewImage: { styles: fileUploadItemPreviewImage }, }, defaultVariants: {},});
// What the recipe leaves to the composition layer: button/list resets, and a// focus ring for the items — UI SDK makes the file list one Tab stop with// arrow-key navigation, so items take focus (Ark's don't).const chrome = stylex.create({ btnReset: { appearance: "none", backgroundColor: "transparent", borderWidth: 0, borderStyle: "none", padding: 0, margin: 0, fontFamily: "inherit", fontSize: "inherit", color: "inherit", cursor: "pointer", textAlign: "inherit", }, listReset: { listStyle: "none", margin: 0, padding: 0 }, itemFocus: { outlineWidth: { default: null, ":focus-visible": "2px" }, outlineStyle: { default: null, ":focus-visible": "solid" }, outlineOffset: { default: null, ":focus-visible": "1px" }, outlineColor: { default: null, ":focus-visible": colorPalette.focusRing }, },});
function CloseIcon(props: React.ComponentProps<"svg">) { return ( <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}> <path d="m4 4 8 8m0-8-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> </svg> );}
const ControllerContext = createContext<FileInputController | null>(null);const StateContext = createContext<FileInputState>({ value: [], disabled: false, required: false, dragging: false,});const ItemContext = createContext<File | null>(null);
const { withProvider, withContext } = createSlotRecipeContext(fileUploadRecipe);
const StyledRoot = withProvider(UiSdkFileInput, "root", "FileUploadRoot");
type UiSdkFileInputProps = React.ComponentProps<typeof UiSdkFileInput>;
export interface FileUploadRootProps extends Omit<UiSdkFileInputProps, "style" | "className" | "defaultValue" | "children">, StyleOverrideProps { /** Prefilled files (maps to UI SDK's `defaultValue`). */ defaultFiles?: File[]; /** Runs with the new file list after files are added or removed. */ onFilesChange?: (files: File[]) => void; children?: React.ReactNode;}
/** * FileUpload — dashed dropzone with a file item list, on UI SDK's FileInput: * it validates and holds the files (`accept`, `maxFiles`, `maxSize`, ...), * renders the hidden input a form submits, announces changes, and makes the * list one Tab stop (arrows move, Delete/Backspace removes). Defaults to * `multiple`, like the Ark and Base UI versions. */function Root(props: FileUploadRootProps) { const { defaultFiles, onFilesChange, onValueChange, multiple = true, controller: own, children, ...rest } = props; const [fallback] = useState(createFileInputController); const controller = own ?? fallback; return ( <ControllerContext.Provider value={controller}> <StyledRoot {...rest} multiple={multiple} controller={controller} defaultValue={defaultFiles} onValueChange={(value, details) => { onValueChange?.(value, details); onFilesChange?.(value); }} > {(state: FileInputState) => ( <StateContext.Provider value={state}>{children}</StateContext.Provider> )} </StyledRoot> </ControllerContext.Provider> );}Root.displayName = "FileUploadRoot";
const StyledDropzone = withContext( FileInputDropzone, (v) => [chrome.btnReset, ...resolveSlotStyles(fileUploadRecipe.slots.dropzone, v)], "FileUploadDropzone",);
/** * Takes dropped and pasted files. UI SDK's drop zone is no control, so this * one renders a button that opens the picker through the root's controller * — one Tab stop, like the Ark and Base UI dropzones. */function Dropzone( props: Omit<React.ComponentProps<typeof FileInputDropzone>, "style" | "className"> & StyleOverrideProps,) { const controller = useContext(ControllerContext); const { onClick, ...rest } = props; return ( <StyledDropzone render={<button type="button" />} onClick={(event: React.MouseEvent<HTMLDivElement>) => { onClick?.(event); if (!event.defaultPrevented) controller?.open(); }} {...rest} /> );}Dropzone.displayName = "FileUploadDropzone";
const StyledItemGroup = withContext( FileInputList, (v) => [...resolveSlotStyles(fileUploadRecipe.slots.itemGroup, v), chrome.listReset], "FileUploadItemGroup",);
/** * The file list. Its children render once per file, so put a single * `FileUpload.Item` template in it — no mapping over the files. */function ItemGroup( props: Omit<React.ComponentProps<typeof FileInputList>, "style" | "className"> & StyleOverrideProps,) { return <StyledItemGroup render={<ul />} {...props} />;}ItemGroup.displayName = "FileUploadItemGroup";
const StyledItem = withContext( FileInputItem, (v) => [...resolveSlotStyles(fileUploadRecipe.slots.item, v), chrome.itemFocus], "FileUploadItem",);
export interface FileUploadItemProps extends Omit<React.ComponentProps<typeof FileInputItem>, "style" | "className" | "children">, StyleOverrideProps { children?: React.ReactNode;}
/** One file: the list fills `file` in; pass it to use an item on its own. */function Item(props: FileUploadItemProps) { const { children, ...rest } = props; return ( <StyledItem render={<li />} {...rest}> {({ file }: { file: File }) => ( <ItemContext.Provider value={file}>{children}</ItemContext.Provider> )} </StyledItem> );}Item.displayName = "FileUploadItem";
const StyledItemName = withContext("span", "itemName", "FileUploadItemName");
function ItemName( props: Omit<React.ComponentProps<typeof StyledItemName>, "children"> & { children?: React.ReactNode; },) { const file = useContext(ItemContext); const { children, ...rest } = props; return <StyledItemName {...rest}>{children ?? file?.name}</StyledItemName>;}ItemName.displayName = "FileUploadItemName";
const StyledItemSizeText = withContext("span", "itemSizeText", "FileUploadItemSizeText");
function ItemSizeText( props: Omit<React.ComponentProps<typeof StyledItemSizeText>, "children"> & { children?: React.ReactNode; },) { const file = useContext(ItemContext); const { children, ...rest } = props; return ( <StyledItemSizeText {...rest}> {children ?? (file ? formatFileSize(file.size) : null)} </StyledItemSizeText> );}ItemSizeText.displayName = "FileUploadItemSizeText";
const StyledItemDeleteTrigger = withContext( FileInputItemRemove, (v) => [chrome.btnReset, ...resolveSlotStyles(fileUploadRecipe.slots.itemDeleteTrigger, v)], "FileUploadItemDeleteTrigger",);
/** Removes its item's file; named "Remove <file name>", out of the Tab order. */function ItemDeleteTrigger( props: Omit<React.ComponentProps<typeof FileInputItemRemove>, "style" | "className"> & StyleOverrideProps,) { const { children, ...rest } = props; return <StyledItemDeleteTrigger {...rest}>{children ?? <CloseIcon />}</StyledItemDeleteTrigger>;}ItemDeleteTrigger.displayName = "FileUploadItemDeleteTrigger";
export interface FileUploadContextValue { files: readonly File[]; disabled: boolean; dragging: boolean; addFiles: (files: readonly File[] | FileList) => boolean; removeFile: (file: File) => boolean; clear: () => boolean; open: () => boolean;}
/** Read the file list the way Ark exposes its machine context. */function Context({ children,}: { children: (ctx: FileUploadContextValue) => React.ReactNode;}) { const state = useContext(StateContext); const controller = useContext(ControllerContext); return children({ files: state.value, disabled: state.disabled, dragging: state.dragging, addFiles: (files) => controller?.addFiles(files) ?? false, removeFile: (file) => controller?.removeFile(file) ?? false, clear: () => controller?.clear() ?? false, open: () => controller?.open() ?? false, });}
export const FileUpload = { Root, Label: withContext("span", "label", "FileUploadLabel"), Dropzone, DropzoneContent: withContext("span", "dropzoneContent", "FileUploadDropzoneContent"), Trigger: withContext(FileInputTrigger, () => [chrome.btnReset], "FileUploadTrigger"), ItemGroup, Item, ItemContent: withContext("div", "itemContent", "FileUploadItemContent"), ItemName, ItemSizeText, ItemDeleteTrigger, Context,};