File Dropzone
Drag and drop upload area on a native file input. Checks type, size, and count per file, lists files with icons, sizes, progress, and remove.
- brand-guidelines.pdf2.3 MB
- hero-photo.jpg1.1 MB
- launch-video.mov46 MB
Larger than 5 MB
- brand-guidelines.pdf2.3 MB
- hero-photo.jpg1.1 MB
- launch-video.mov46 MB
Larger than 5 MB
- brand-guidelines.pdf 2.3 MB
- hero-photo.jpg 1.1 MB
- launch-video.mov 46 MB
Larger than 5 MB
- brand-guidelines.pdf2.3 MB
- hero-photo.jpg1.1 MB
- launch-video.mov46 MB
Larger than 5 MB
@php
$files = [
['name' => 'brand-guidelines.pdf', 'size' => 2457600, 'type' => 'application/pdf', 'progress' => 100],
['name' => 'hero-photo.jpg', 'size' => 1153434, 'type' => 'image/jpeg', 'progress' => 64],
['name' => 'launch-video.mov', 'size' => 48234496, 'type' => 'video/quicktime', 'error' => 'Larger than 5 MB'],
];
@endphp
<x-markas.file-dropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
:max-size="5242880"
:max-files="4"
hint="Images or PDF, up to 5 MB each"
:files="$files"
/>import { FileDropzone } from "@/components/markas/FileDropzone";
const files = [
{
name: "brand-guidelines.pdf",
size: 2457600,
type: "application/pdf",
progress: 100,
},
{ name: "hero-photo.jpg", size: 1153434, type: "image/jpeg", progress: 64 },
{
name: "launch-video.mov",
size: 48234496,
type: "video/quicktime",
error: "Larger than 5 MB",
},
];
export default function FileDropzoneExample() {
return (
<FileDropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
maxSize={5242880}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
files={files}
/>
);
}<script setup lang="ts">
import FileDropzone from "@/components/markas/FileDropzone.vue";
const files = [
{
name: "brand-guidelines.pdf",
size: 2457600,
type: "application/pdf",
progress: 100,
},
{ name: "hero-photo.jpg", size: 1153434, type: "image/jpeg", progress: 64 },
{
name: "launch-video.mov",
size: 48234496,
type: "video/quicktime",
error: "Larger than 5 MB",
},
];
</script>
<template>
<FileDropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
:max-size="5242880"
:max-files="4"
hint="Images or PDF, up to 5 MB each"
:files="files"
/>
</template><script lang="ts">
import FileDropzone from "$lib/components/markas/FileDropzone.svelte";
const files = [
{
name: "brand-guidelines.pdf",
size: 2457600,
type: "application/pdf",
progress: 100,
},
{
name: "hero-photo.jpg",
size: 1153434,
type: "image/jpeg",
progress: 64,
},
{
name: "launch-video.mov",
size: 48234496,
type: "video/quicktime",
error: "Larger than 5 MB",
},
];
</script>
<FileDropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
maxSize={5242880}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
{files}
/>---
import FileDropzone from "@/components/markas/FileDropzone.astro";
const files = [
{
name: "brand-guidelines.pdf",
size: 2457600,
type: "application/pdf",
progress: 100,
},
{
name: "hero-photo.jpg",
size: 1153434,
type: "image/jpeg",
progress: 64,
},
{
name: "launch-video.mov",
size: 48234496,
type: "video/quicktime",
error: "Larger than 5 MB",
},
];
---
<FileDropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
maxSize={5242880}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
files={files}
/>import { Component } from "@angular/core";
import { FileDropzone } from "./markas/file-dropzone.component";
@Component({
selector: "markas-example",
imports: [FileDropzone],
template: `
<markas-file-dropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
[maxSize]="5242880"
[maxFiles]="4"
hint="Images or PDF, up to 5 MB each"
[files]="files"
/>
`,
})
export default class FileDropzoneExample {
protected readonly files = [
{
name: "brand-guidelines.pdf",
size: 2457600,
type: "application/pdf",
progress: 100,
},
{ name: "hero-photo.jpg", size: 1153434, type: "image/jpeg", progress: 64 },
{
name: "launch-video.mov",
size: 48234496,
type: "video/quicktime",
error: "Larger than 5 MB",
},
];
}Examples
Single photo with custom labels
Profile photo
Shown on your profile and next to your comments.
Profile photo
Shown on your profile and next to your comments.
- rania-portrait.png471 KB
Profile photo
Shown on your profile and next to your comments.
- rania-portrait.png471 KB
Profile photo
Shown on your profile and next to your comments.
- rania-portrait.png 471 KB
Profile photo
Shown on your profile and next to your comments.
- rania-portrait.png471 KB
@php
$section = 'grid gap-3';
$title = 'text-sm font-medium text-ink';
$text = 'text-sm text-muted';
$current = [
['name' => 'rania-portrait.png', 'size' => 482304, 'type' => 'image/png', 'progress' => 100],
];
@endphp
<div class="{{ $section }}">
<div>
<p class="{{ $title }}">Profile photo</p>
<p class="{{ $text }}">Shown on your profile and next to your comments.</p>
</div>
<x-markas.file-dropzone
name="avatar"
accept="image/png,image/jpeg"
:max-size="2097152"
hint="Square PNG or JPG, up to 2 MB"
drop-label="Drop a photo here or"
browse-label="choose one"
:files="$current"
/>
</div>import { FileDropzone } from "@/components/markas/FileDropzone";
const section = "grid gap-3";
const title = "text-sm font-medium text-ink";
const text = "text-sm text-muted";
const current = [
{
name: "rania-portrait.png",
size: 482304,
type: "image/png",
progress: 100,
},
];
export default function Example() {
return (
<div className={section}>
<div>
<p className={title}>Profile photo</p>
<p className={text}>Shown on your profile and next to your comments.</p>
</div>
<FileDropzone
name="avatar"
accept="image/png,image/jpeg"
maxSize={2097152}
hint="Square PNG or JPG, up to 2 MB"
dropLabel="Drop a photo here or"
browseLabel="choose one"
files={current}
/>
</div>
);
}<script setup lang="ts">
import FileDropzone from "@/components/markas/FileDropzone.vue";
const section = "grid gap-3";
const title = "text-sm font-medium text-ink";
const text = "text-sm text-muted";
const current = [
{
name: "rania-portrait.png",
size: 482304,
type: "image/png",
progress: 100,
},
];
</script>
<template>
<div :class="section">
<div>
<p :class="title">Profile photo</p>
<p :class="text">Shown on your profile and next to your comments.</p>
</div>
<FileDropzone
name="avatar"
accept="image/png,image/jpeg"
:max-size="2097152"
hint="Square PNG or JPG, up to 2 MB"
drop-label="Drop a photo here or"
browse-label="choose one"
:files="current"
/>
</div>
</template><script lang="ts">
import FileDropzone from "$lib/components/markas/FileDropzone.svelte";
const section = "grid gap-3";
const title = "text-sm font-medium text-ink";
const text = "text-sm text-muted";
const current = [
{
name: "rania-portrait.png",
size: 482304,
type: "image/png",
progress: 100,
},
];
</script>
<div class={section}>
<div>
<p class={title}>Profile photo</p>
<p class={text}>Shown on your profile and next to your comments.</p>
</div>
<FileDropzone
name="avatar"
accept="image/png,image/jpeg"
maxSize={2097152}
hint="Square PNG or JPG, up to 2 MB"
dropLabel="Drop a photo here or"
browseLabel="choose one"
files={current}
/>
</div>---
import FileDropzone from "@/components/markas/FileDropzone.astro";
const section = "grid gap-3";
const title = "text-sm font-medium text-ink";
const text = "text-sm text-muted";
const current = [
{
name: "rania-portrait.png",
size: 482304,
type: "image/png",
progress: 100,
},
];
---
<div class={section}>
<div>
<p class={title}>Profile photo</p>
<p class={text}>Shown on your profile and next to your comments.</p>
</div>
<FileDropzone
name="avatar"
accept="image/png,image/jpeg"
maxSize={2097152}
hint="Square PNG or JPG, up to 2 MB"
dropLabel="Drop a photo here or"
browseLabel="choose one"
files={current}
/>
</div>import { Component } from "@angular/core";
import { FileDropzone } from "./markas/file-dropzone.component";
@Component({
selector: "markas-example",
imports: [FileDropzone],
template: `
<div [class]="section">
<div>
<p [class]="title">Profile photo</p>
<p [class]="text">Shown on your profile and next to your comments.</p>
</div>
<markas-file-dropzone
name="avatar"
accept="image/png,image/jpeg"
[maxSize]="2097152"
hint="Square PNG or JPG, up to 2 MB"
dropLabel="Drop a photo here or"
browseLabel="choose one"
[files]="current"
/>
</div>
`,
})
export default class FileDropzoneAvatarExample {
protected readonly section = "grid gap-3";
protected readonly title = "text-sm font-medium text-ink";
protected readonly text = "text-sm text-muted";
protected readonly current = [
{
name: "rania-portrait.png",
size: 482304,
type: "image/png",
progress: 100,
},
];
}Inside a form
@php
$form = 'grid gap-4';
$field = 'grid gap-1.5';
$label = 'text-sm font-medium text-ink';
$footer = 'flex justify-end';
$attached = [
['name' => 'campaign-brief.docx', 'size' => 88064, 'type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
];
@endphp
<form action="#" class="{{ $form }}">
<x-markas.input name="project" label="Project name" placeholder="Spring launch" />
<div class="{{ $field }}">
<p class="{{ $label }}">Attachments</p>
<x-markas.file-dropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
:max-files="5"
:max-size="10485760"
hint="PDF, DOCX, or ZIP, up to 10 MB each"
:files="$attached"
/>
</div>
<div class="{{ $footer }}">
<x-markas.button type="submit">Send request</x-markas.button>
</div>
</form>import { Button } from "@/components/markas/Button";
import { FileDropzone } from "@/components/markas/FileDropzone";
import { Input } from "@/components/markas/Input";
const form = "grid gap-4";
const field = "grid gap-1.5";
const label = "text-sm font-medium text-ink";
const footer = "flex justify-end";
const attached = [
{
name: "campaign-brief.docx",
size: 88064,
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
];
export default function Example() {
return (
<form action="#" className={form}>
<Input name="project" label="Project name" placeholder="Spring launch" />
<div className={field}>
<p className={label}>Attachments</p>
<FileDropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
maxFiles={5}
maxSize={10485760}
hint="PDF, DOCX, or ZIP, up to 10 MB each"
files={attached}
/>
</div>
<div className={footer}>
<Button type="submit">Send request</Button>
</div>
</form>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import FileDropzone from "@/components/markas/FileDropzone.vue";
import Input from "@/components/markas/Input.vue";
const form = "grid gap-4";
const field = "grid gap-1.5";
const label = "text-sm font-medium text-ink";
const footer = "flex justify-end";
const attached = [
{
name: "campaign-brief.docx",
size: 88064,
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
];
</script>
<template>
<form action="#" :class="form">
<Input name="project" label="Project name" placeholder="Spring launch" />
<div :class="field">
<p :class="label">Attachments</p>
<FileDropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
:max-files="5"
:max-size="10485760"
hint="PDF, DOCX, or ZIP, up to 10 MB each"
:files="attached"
/>
</div>
<div :class="footer">
<Button type="submit">Send request</Button>
</div>
</form>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import FileDropzone from "$lib/components/markas/FileDropzone.svelte";
import Input from "$lib/components/markas/Input.svelte";
const form = "grid gap-4";
const field = "grid gap-1.5";
const label = "text-sm font-medium text-ink";
const footer = "flex justify-end";
const attached = [
{
name: "campaign-brief.docx",
size: 88064,
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
];
</script>
<form action="#" class={form}>
<Input name="project" label="Project name" placeholder="Spring launch" />
<div class={field}>
<p class={label}>Attachments</p>
<FileDropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
maxFiles={5}
maxSize={10485760}
hint="PDF, DOCX, or ZIP, up to 10 MB each"
files={attached}
/>
</div>
<div class={footer}>
<Button type="submit">Send request</Button>
</div>
</form>---
import Button from "@/components/markas/Button.astro";
import FileDropzone from "@/components/markas/FileDropzone.astro";
import Input from "@/components/markas/Input.astro";
const form = "grid gap-4";
const field = "grid gap-1.5";
const label = "text-sm font-medium text-ink";
const footer = "flex justify-end";
const attached = [
{
name: "campaign-brief.docx",
size: 88064,
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
];
---
<form action="#" class={form}>
<Input name="project" label="Project name" placeholder="Spring launch" />
<div class={field}>
<p class={label}>Attachments</p>
<FileDropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
maxFiles={5}
maxSize={10485760}
hint="PDF, DOCX, or ZIP, up to 10 MB each"
files={attached}
/>
</div>
<div class={footer}>
<Button type="submit">Send request</Button>
</div>
</form>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { FileDropzone } from "./markas/file-dropzone.component";
import { Input } from "./markas/input.component";
@Component({
selector: "markas-example",
imports: [Button, FileDropzone, Input],
template: `
<form action="#" [class]="form">
<markas-input
name="project"
label="Project name"
placeholder="Spring launch"
/>
<div [class]="field">
<p [class]="label">Attachments</p>
<markas-file-dropzone
name="attachments[]"
accept=".pdf,.docx,.zip"
multiple
[maxFiles]="5"
[maxSize]="10485760"
hint="PDF, DOCX, or ZIP, up to 10 MB each"
[files]="attached"
/>
</div>
<div [class]="footer">
<button markas-button type="submit">Send request</button>
</div>
</form>
`,
})
export default class FileDropzoneFormExample {
protected readonly form = "grid gap-4";
protected readonly field = "grid gap-1.5";
protected readonly label = "text-sm font-medium text-ink";
protected readonly footer = "flex justify-end";
protected readonly attached = [
{
name: "campaign-brief.docx",
size: 88064,
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
];
}Upload progress
- keynote-deck.pdf5.6 MB
- product-demo.mp440 MB
- voiceover.wav9 MB
- keynote-deck.pdf5.6 MB
- product-demo.mp440 MB
- voiceover.wav9 MB
- keynote-deck.pdf 5.6 MB
- product-demo.mp4 40 MB
- voiceover.wav 9 MB
- keynote-deck.pdf5.6 MB
- product-demo.mp440 MB
- voiceover.wav9 MB
@php
$uploads = [
['name' => 'keynote-deck.pdf', 'size' => 5872025, 'type' => 'application/pdf', 'progress' => 100],
['name' => 'product-demo.mp4', 'size' => 41943040, 'type' => 'video/mp4', 'progress' => 72],
['name' => 'voiceover.wav', 'size' => 9437184, 'type' => 'audio/wav', 'progress' => 35],
];
@endphp
{{-- Simulated upload: +9% every 150ms, sent back to the dropzone as file-progress events. A real app reports progress from its upload request. --}}
<div
x-data="{
started: new Set(),
simulate(event) {
const zone = event.target.closest('[x-data]');
for (const { name } of event.detail) {
if (this.started.has(name)) continue;
this.started.add(name);
let value = 0;
const send = () => zone.dispatchEvent(new CustomEvent('file-progress', { detail: { name, progress: value } }));
send();
const timer = setInterval(() => {
value = Math.min(100, value + 9);
send();
if (value === 100) clearInterval(timer);
}, 150);
}
},
}"
x-on:files-change="simulate($event)"
>
<x-markas.file-dropzone multiple hint="Add a file to watch it upload" :files="$uploads" />
</div>import { useEffect, useRef, useState } from "react";
import { FileDropzone } from "@/components/markas/FileDropzone";
/** Simulated upload: +9% every 150ms. A real app reports progress from its upload request. */
const STEP = 9;
const TICK_MS = 150;
const uploads = [
{
name: "keynote-deck.pdf",
size: 5872025,
type: "application/pdf",
progress: 100,
},
{ name: "product-demo.mp4", size: 41943040, type: "video/mp4", progress: 72 },
{ name: "voiceover.wav", size: 9437184, type: "audio/wav", progress: 35 },
];
export default function Example() {
const [progress, setProgress] = useState<Record<string, number>>({});
const started = useRef(new Set<string>());
const timers = useRef<number[]>([]);
useEffect(() => () => timers.current.forEach(clearInterval), []);
const simulate = (files: File[]) => {
for (const { name } of files) {
if (started.current.has(name)) continue;
started.current.add(name);
let value = 0;
setProgress((current) => ({ ...current, [name]: value }));
const timer = window.setInterval(() => {
value = Math.min(100, value + STEP);
setProgress((current) => ({ ...current, [name]: value }));
if (value === 100) clearInterval(timer);
}, TICK_MS);
timers.current.push(timer);
}
};
return (
<FileDropzone
multiple
hint="Add a file to watch it upload"
files={uploads}
progress={progress}
onFilesChange={simulate}
/>
);
}<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue";
import FileDropzone from "@/components/markas/FileDropzone.vue";
/** Simulated upload: +9% every 150ms. A real app reports progress from its upload request. */
const STEP = 9;
const TICK_MS = 150;
const uploads = [
{
name: "keynote-deck.pdf",
size: 5872025,
type: "application/pdf",
progress: 100,
},
{ name: "product-demo.mp4", size: 41943040, type: "video/mp4", progress: 72 },
{ name: "voiceover.wav", size: 9437184, type: "audio/wav", progress: 35 },
];
const progress = ref<Record<string, number>>({});
const started = new Set<string>();
const timers: number[] = [];
onBeforeUnmount(() => timers.forEach(clearInterval));
function simulate(files: File[]) {
for (const { name } of files) {
if (started.has(name)) continue;
started.add(name);
let value = 0;
progress.value = { ...progress.value, [name]: value };
const timer = window.setInterval(() => {
value = Math.min(100, value + STEP);
progress.value = { ...progress.value, [name]: value };
if (value === 100) clearInterval(timer);
}, TICK_MS);
timers.push(timer);
}
}
</script>
<template>
<FileDropzone
multiple
hint="Add a file to watch it upload"
:files="uploads"
:progress="progress"
@change="simulate"
/>
</template><script lang="ts">
import { onDestroy } from "svelte";
import FileDropzone from "$lib/components/markas/FileDropzone.svelte";
/** Simulated upload: +9% every 150ms. A real app reports progress from its upload request. */
const STEP = 9;
const TICK_MS = 150;
const uploads = [
{
name: "keynote-deck.pdf",
size: 5872025,
type: "application/pdf",
progress: 100,
},
{
name: "product-demo.mp4",
size: 41943040,
type: "video/mp4",
progress: 72,
},
{ name: "voiceover.wav", size: 9437184, type: "audio/wav", progress: 35 },
];
let progress = $state<Record<string, number>>({});
const started = new Set<string>();
const timers: number[] = [];
onDestroy(() => timers.forEach(clearInterval));
function simulate(files: File[]) {
for (const { name } of files) {
if (started.has(name)) continue;
started.add(name);
let value = 0;
progress = { ...progress, [name]: value };
const timer = window.setInterval(() => {
value = Math.min(100, value + STEP);
progress = { ...progress, [name]: value };
if (value === 100) clearInterval(timer);
}, TICK_MS);
timers.push(timer);
}
}
</script>
<FileDropzone
multiple
hint="Add a file to watch it upload"
files={uploads}
{progress}
onFilesChange={simulate}
/>---
import FileDropzone from "@/components/markas/FileDropzone.astro";
const uploads = [
{
name: "keynote-deck.pdf",
size: 5872025,
type: "application/pdf",
progress: 100,
},
{ name: "product-demo.mp4", size: 41943040, type: "video/mp4", progress: 72 },
{ name: "voiceover.wav", size: 9437184, type: "audio/wav", progress: 35 },
];
---
<FileDropzone multiple hint="Add a file to watch it upload" files={uploads} />
<script>
/** Simulated upload: +9% every 150ms. A real app reports progress from its upload request. */
const STEP = 9;
const TICK_MS = 150;
const started = new Set<string>();
type Dropzone = HTMLElement & { setProgress(name: string, percent: number): void };
document.addEventListener("markas-change", (event) => {
const dropzone = event.target as Dropzone;
if (dropzone.localName !== "markas-file-dropzone") return;
for (const { name } of (event as CustomEvent<File[]>).detail) {
if (started.has(name)) continue;
started.add(name);
let value = 0;
dropzone.setProgress(name, value);
const timer = window.setInterval(() => {
value = Math.min(100, value + STEP);
dropzone.setProgress(name, value);
if (value === 100) clearInterval(timer);
}, TICK_MS);
}
});
</script>import { Component, DestroyRef, inject, signal } from "@angular/core";
import { FileDropzone } from "./markas/file-dropzone.component";
/** Simulated upload: +9% every 150ms. A real app reports progress from its upload request. */
const STEP = 9;
const TICK_MS = 150;
@Component({
selector: "markas-example",
imports: [FileDropzone],
template: `
<markas-file-dropzone
multiple
hint="Add a file to watch it upload"
[files]="uploads"
[progress]="progress()"
(filesChange)="simulate($event)"
/>
`,
})
export default class FileDropzoneUploadingExample {
protected readonly uploads = [
{
name: "keynote-deck.pdf",
size: 5872025,
type: "application/pdf",
progress: 100,
},
{
name: "product-demo.mp4",
size: 41943040,
type: "video/mp4",
progress: 72,
},
{ name: "voiceover.wav", size: 9437184, type: "audio/wav", progress: 35 },
];
protected readonly progress = signal<Record<string, number>>({});
private readonly started = new Set<string>();
private readonly timers: number[] = [];
constructor() {
inject(DestroyRef).onDestroy(() => this.timers.forEach(clearInterval));
}
protected simulate(files: File[]) {
for (const { name } of files) {
if (this.started.has(name)) continue;
this.started.add(name);
let value = 0;
this.progress.update((current) => ({ ...current, [name]: value }));
const timer = window.setInterval(() => {
value = Math.min(100, value + STEP);
this.progress.update((current) => ({ ...current, [name]: value }));
if (value === 100) clearInterval(timer);
}, TICK_MS);
this.timers.push(timer);
}
}
}Installation
npx markasui@latest add file-dropzonepnpm dlx markasui@latest add file-dropzoneyarn dlx markasui@latest add file-dropzonebunx --bun markasui@latest add file-dropzone- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/file-dropzone.blade.php.
@props([
'name' => null,
'accept' => null,
'multiple' => false,
'maxSize' => null,
'maxFiles' => null,
'disabled' => false,
'required' => false,
'files' => [],
'hint' => null,
'dropLabel' => 'Drop files here or',
'browseLabel' => 'browse',
'removeLabel' => 'Remove {name}',
'tooLargeLabel' => 'Larger than {size}',
'typeLabel' => 'File type not allowed',
'tooManyLabel' => 'Only {max} files allowed',
])
@php
$root = 'grid gap-3';
$zone = 'group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none';
$badge = 'size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none';
$titleClass = 'text-sm text-ink';
$browseClass = 'font-medium underline underline-offset-4';
$hintClass = 'text-xs text-muted';
$srOnly = 'sr-only';
$list = 'grid gap-2';
$item = 'group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5';
$fileIcon = 'size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger';
$body = 'grid min-w-0 flex-1 gap-1.5';
$row = 'flex items-baseline justify-between gap-3 text-sm';
$nameClass = 'truncate font-medium text-ink';
$sizeClass = 'shrink-0 text-xs text-muted tabular-nums';
$errorClass = 'text-xs text-danger';
$track = 'h-1.5 overflow-hidden rounded-full bg-subtle';
$bar = 'h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none';
$bars = ['busy' => 'bg-primary', 'done' => 'bg-success'];
$remove = 'size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
$smallIcon = 'size-4';
// 24px stroked icons per file kind.
$icons = [
'upload' => 'M12 16V4M7 9l5-5 5 5M4 16v4h16v-4',
'image' => 'M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01',
'video' => 'M3 6h13v12H3zM16 10l5-3v10l-5-3',
'audio' => 'M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z',
'file' => 'M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4',
'remove' => 'M6 6l12 12M18 6 6 18',
];
// Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
$idKey = 'markas-file-dropzone|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $name).'|';
for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
$__env->markAsRenderedOnce($idKey.$idIndex);
$id = $attributes->get('id') ?? 'markas-file-dropzone-'.hash('xxh32', $idKey.$idIndex);
// wire:model goes on a hidden file input that only receives the accepted files.
$model = $attributes->whereStartsWith('wire:model');
$initial = array_map(fn (array $file, int $key) => [
'key' => $key,
'name' => (string) $file['name'],
'size' => (int) $file['size'],
'type' => (string) ($file['type'] ?? ''),
'progress' => isset($file['progress']) ? (float) $file['progress'] : null,
'error' => $file['error'] ?? null,
], array_values($files), array_keys(array_values($files)));
$config = [
'accept' => (string) $accept,
'multiple' => (bool) $multiple,
'maxSize' => $maxSize === null ? null : (int) $maxSize,
'maxFiles' => $maxFiles === null ? null : (int) $maxFiles,
'disabled' => (bool) $disabled,
'labels' => ['remove' => $removeLabel, 'tooLarge' => $tooLargeLabel, 'type' => $typeLabel, 'tooMany' => $tooManyLabel],
'icons' => $icons,
'bars' => $bars,
];
@endphp
{{-- Picked and dropped files are checked against accept, maxSize, and maxFiles; the valid ones stay in the native input so the form posts them. Dispatch file-progress with { name, progress } on the component to move a bar. --}}
<div
x-data="{
...@js($config),
items: @js($initial),
seq: {{ count($initial) }},
over: false,
fill(template, value) {
return template.replace(/\{\w+\}/, () => String(value));
},
size(bytes) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${['B', 'KB', 'MB', 'GB'][unit]}`;
},
accepts(file) {
const type = (file.type || '').toLowerCase();
return ! this.accept || this.accept.split(',').some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith('.')) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1));
return type === rule;
});
},
kind(file) {
const group = (file.type || '').split('/')[0];
return ['image', 'video', 'audio'].includes(group) ? group : 'file';
},
update(next) {
this.items = next;
const picked = next.filter((i) => i.file && ! i.error).map((i) => i.file);
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
this.$refs.input.files = transfer.files;
this.$dispatch('files-change', picked);
this.sync(picked);
},
{{-- Livewire: upload the accepted files through the hidden wire:model input, or clear the property when none are left. --}}
sync(picked) {
const target = this.$refs.wire;
if (! target) return;
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
target.files = transfer.files;
if (picked.length > 0) return target.dispatchEvent(new Event('change'));
const property = [...target.attributes].find((attr) => attr.name.startsWith('wire:model'))?.value;
if (property) this.$wire.$set(property, this.multiple ? [] : null);
},
uploading(progress) {
this.items = this.items.map((i) => (i.file && ! i.error ? { ...i, progress } : i));
},
add(incoming) {
const limit = this.multiple ? (this.maxFiles ?? Infinity) : 1;
const kept = this.multiple ? this.items : [];
let count = kept.filter((i) => ! i.error).length;
const added = incoming.map((file) => {
const error = ! this.accepts(file) ? this.labels.type
: this.maxSize !== null && file.size > this.maxSize ? this.fill(this.labels.tooLarge, this.size(this.maxSize))
: count >= limit ? this.fill(this.labels.tooMany, limit)
: null;
if (! error) count++;
return { key: this.seq++, name: file.name, size: file.size, type: file.type, progress: null, error, file };
});
this.update([...kept, ...added]);
},
drag(event, entering) {
event.preventDefault();
if (entering) return (this.over = ! this.disabled);
if (! event.currentTarget.contains(event.relatedTarget)) this.over = false;
},
drop(event) {
event.preventDefault();
this.over = false;
if (! this.disabled) this.add([...event.dataTransfer.files]);
},
progressed({ name, progress }) {
this.items = this.items.map((i) => (i.name === name ? { ...i, progress } : i));
},
}"
x-on:file-progress="progressed($event.detail)"
x-on:livewire-upload-progress="uploading($event.detail.progress)"
x-on:livewire-upload-finish="uploading(100)"
x-on:livewire-upload-error="uploading(null)"
{{ $attributes->except('id')->whereDoesntStartWith('wire:model')->class([$root]) }}
>
<label
data-state="idle"
x-bind:data-state="over ? 'over' : 'idle'"
x-on:dragenter="drag($event, true)"
x-on:dragover="drag($event, true)"
x-on:dragleave="drag($event, false)"
x-on:drop="drop($event)"
class="{{ $zone }}"
>
<input
x-ref="input"
id="{{ $id }}"
type="file"
@if ($name) name="{{ $name }}" @endif
@if ($accept) accept="{{ $accept }}" @endif
@if ($multiple) multiple @endif
@if ($disabled) disabled @endif
@if ($required) required @endif
x-on:change="add([...$event.target.files])"
class="{{ $srOnly }}"
/>
<svg class="{{ $badge }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ $icons['upload'] }}" /></svg>
<span class="{{ $titleClass }}">{{ $dropLabel }} <span class="{{ $browseClass }}">{{ $browseLabel }}</span></span>
@if ($hint)
<span class="{{ $hintClass }}">{{ $hint }}</span>
@endif
</label>
@if ($model->isNotEmpty())
<input x-ref="wire" type="file" hidden tabindex="-1" aria-hidden="true" @if ($multiple) multiple @endif {{ $model }} />
@endif
<ul x-show="items.length > 0" @if (count($initial) === 0) style="display: none" @endif class="{{ $list }}">
<template x-for="file in items" x-bind:key="file.key">
<li x-bind:data-state="file.error ? 'error' : 'ok'" class="{{ $item }}">
<svg class="{{ $fileIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path x-bind:d="icons[kind(file)]" /></svg>
<div class="{{ $body }}">
<div class="{{ $row }}">
<span class="{{ $nameClass }}" x-text="file.name"></span>
<span class="{{ $sizeClass }}" x-text="size(file.size)"></span>
</div>
<template x-if="file.error">
<p role="alert" class="{{ $errorClass }}" x-text="file.error"></p>
</template>
<template x-if="! file.error && file.progress !== null">
<div role="progressbar" x-bind:aria-valuenow="file.progress" x-bind:aria-label="file.name" class="{{ $track }}"><div x-bind:class="@js($bar) + ' ' + bars[file.progress < 100 ? 'busy' : 'done']" x-bind:style="{ width: file.progress + '%' }"></div></div>
</template>
</div>
<button
type="button"
x-bind:aria-label="fill(labels.remove, file.name)"
x-on:click="update(items.filter((i) => i.key !== file.key))"
class="{{ $remove }}"
>
<svg class="{{ $smallIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ $icons['remove'] }}" /></svg>
</button>
</li>
</template>
</ul>
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/FileDropzone.tsx.
"use client";
import {
useId,
useRef,
useState,
type ComponentProps,
type DragEvent,
type ReactNode,
} from "react";
const root = "grid gap-3";
const zone =
"group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none";
const badge =
"size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none";
const titleClass = "text-sm text-ink";
const browseClass = "font-medium underline underline-offset-4";
const hintClass = "text-xs text-muted";
const srOnly = "sr-only";
const list = "grid gap-2";
const item =
"group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5";
const fileIcon =
"size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger";
const body = "grid min-w-0 flex-1 gap-1.5";
const row = "flex items-baseline justify-between gap-3 text-sm";
const nameClass = "truncate font-medium text-ink";
const sizeClass = "shrink-0 text-xs text-muted tabular-nums";
const errorClass = "text-xs text-danger";
const track = "h-1.5 overflow-hidden rounded-full bg-subtle";
const bar =
"h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none";
const bars = { busy: "bg-primary", done: "bg-success" };
const remove =
"size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const smallIcon = "size-4";
const svg = {
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round",
"aria-hidden": true,
} as const;
/** 24px stroked icons: the drop prompt, remove, and one per file kind. */
const UPLOAD = "M12 16V4M7 9l5-5 5 5M4 16v4h16v-4";
const REMOVE = "M6 6l12 12M18 6 6 18";
const FILE = "M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4";
const KINDS: Record<string, string> = {
image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
video: "M3 6h13v12H3zM16 10l5-3v10l-5-3",
audio:
"M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
};
export type DropzoneFile = {
name: string;
/** Size in bytes. */
size: number;
type?: string;
/** Upload progress 0 to 100. Leave out to hide the bar. */
progress?: number;
error?: string;
};
type Item = DropzoneFile & { key: number; file?: File };
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
export function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
export function accepts(file: { name: string; type?: string }, accept = "") {
const type = (file.type ?? "").toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
const iconOf = ({ type = "" }: DropzoneFile) =>
KINDS[type.split("/")[0]!] ?? FILE;
export type FileDropzoneProps = Omit<ComponentProps<"div">, "onChange"> & {
name?: string;
accept?: string;
multiple?: boolean;
/** Largest file in bytes. */
maxSize?: number;
/** Most files kept when multiple is on. */
maxFiles?: number;
disabled?: boolean;
required?: boolean;
/** Files already in the list, such as earlier uploads. They are shown, not submitted. */
files?: DropzoneFile[];
/** Live upload progress by file name, 0 to 100. */
progress?: Record<string, number>;
hint?: ReactNode;
onFilesChange?: (files: File[]) => void;
dropLabel?: string;
browseLabel?: string;
removeLabel?: string;
tooLargeLabel?: string;
typeLabel?: string;
tooManyLabel?: string;
};
export function FileDropzone({
name,
accept,
multiple = false,
maxSize,
maxFiles,
disabled,
required,
files = [],
progress = {},
hint,
onFilesChange,
dropLabel = "Drop files here or",
browseLabel = "browse",
removeLabel = "Remove {name}",
tooLargeLabel = "Larger than {size}",
typeLabel = "File type not allowed",
tooManyLabel = "Only {max} files allowed",
id,
className,
...props
}: FileDropzoneProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const input = useRef<HTMLInputElement>(null);
const seq = useRef(files.length);
const [items, setItems] = useState<Item[]>(() =>
files.map((file, key) => ({ ...file, key })),
);
const [over, setOver] = useState(false);
const limit = multiple ? (maxFiles ?? Infinity) : 1;
/** Keep the native input's files equal to the valid picked files, so a form posts them. */
const update = (next: Item[]) => {
setItems(next);
const picked = next.flatMap((i) => (i.file && !i.error ? [i.file] : []));
if (input.current) {
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
input.current.files = transfer.files;
}
onFilesChange?.(picked);
};
const add = (incoming: File[]) => {
const kept = multiple ? items : [];
let count = kept.filter((i) => !i.error).length;
const added = incoming.map((file) => {
const error = !accepts(file, accept)
? typeLabel
: maxSize !== undefined && file.size > maxSize
? fill(tooLargeLabel, formatSize(maxSize))
: count >= limit
? fill(tooManyLabel, limit)
: undefined;
if (!error) count++;
const { name, size, type } = file;
return { key: seq.current++, name, size, type, file, error };
});
update([...kept, ...added]);
};
const drag = (event: DragEvent<HTMLLabelElement>, entering: boolean) => {
event.preventDefault();
if (entering) return setOver(!disabled);
if (!event.currentTarget.contains(event.relatedTarget as Node | null))
setOver(false);
};
return (
<div {...props} className={cx(root, className)}>
<label
data-state={over ? "over" : "idle"}
className={zone}
onDragEnter={(event) => drag(event, true)}
onDragOver={(event) => drag(event, true)}
onDragLeave={(event) => drag(event, false)}
onDrop={(event) => {
event.preventDefault();
setOver(false);
if (!disabled) add([...event.dataTransfer.files]);
}}
>
<input
ref={input}
id={inputId}
type="file"
name={name}
accept={accept}
multiple={multiple}
disabled={disabled}
required={required}
className={srOnly}
onChange={(event) => add([...(event.currentTarget.files ?? [])])}
/>
<svg className={badge} {...svg}>
<path d={UPLOAD} />
</svg>
<span className={titleClass}>
{dropLabel} <span className={browseClass}>{browseLabel}</span>
</span>
{hint && <span className={hintClass}>{hint}</span>}
</label>
{items.length > 0 && (
<ul className={list}>
{items.map((file) => {
const percent = progress[file.name] ?? file.progress;
return (
<li
key={file.key}
data-state={file.error ? "error" : "ok"}
className={item}
>
<svg className={fileIcon} {...svg}>
<path d={iconOf(file)} />
</svg>
<div className={body}>
<div className={row}>
<span className={nameClass}>{file.name}</span>
<span className={sizeClass}>{formatSize(file.size)}</span>
</div>
{file.error ? (
<p role="alert" className={errorClass}>
{file.error}
</p>
) : percent !== undefined ? (
<div
role="progressbar"
aria-valuenow={percent}
aria-label={file.name}
className={track}
>
<div
className={cx(
bar,
bars[percent < 100 ? "busy" : "done"],
)}
style={{ width: `${percent}%` }}
></div>
</div>
) : null}
</div>
<button
type="button"
aria-label={fill(removeLabel, file.name)}
className={remove}
onClick={() => update(items.filter((i) => i !== file))}
>
<svg className={smallIcon} {...svg}>
<path d={REMOVE} />
</svg>
</button>
</li>
);
})}
</ul>
)}
</div>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/FileDropzone.vue.
<script setup lang="ts">
import { ref, useId } from "vue";
export type DropzoneFile = {
name: string;
/** Size in bytes. */
size: number;
type?: string;
/** Upload progress 0 to 100. Leave out to hide the bar. */
progress?: number;
error?: string;
};
type Item = DropzoneFile & { key: number; file?: File };
const props = withDefaults(
defineProps<{
name?: string;
accept?: string;
multiple?: boolean;
/** Largest file in bytes. */
maxSize?: number;
/** Most files kept when multiple is on. */
maxFiles?: number;
disabled?: boolean;
required?: boolean;
id?: string;
/** Files already in the list, such as earlier uploads. They are shown, not submitted. */
files?: DropzoneFile[];
/** Live upload progress by file name, 0 to 100. */
progress?: Record<string, number>;
hint?: string;
dropLabel?: string;
browseLabel?: string;
removeLabel?: string;
tooLargeLabel?: string;
typeLabel?: string;
tooManyLabel?: string;
}>(),
{
files: () => [],
progress: () => ({}),
dropLabel: "Drop files here or",
browseLabel: "browse",
removeLabel: "Remove {name}",
tooLargeLabel: "Larger than {size}",
typeLabel: "File type not allowed",
tooManyLabel: "Only {max} files allowed",
},
);
const emit = defineEmits<{ change: [files: File[]] }>();
const root = "grid gap-3";
const zone =
"group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none";
const badge =
"size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none";
const titleClass = "text-sm text-ink";
const browseClass = "font-medium underline underline-offset-4";
const hintClass = "text-xs text-muted";
const srOnly = "sr-only";
const list = "grid gap-2";
const item =
"group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5";
const fileIcon =
"size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger";
const body = "grid min-w-0 flex-1 gap-1.5";
const row = "flex items-baseline justify-between gap-3 text-sm";
const nameClass = "truncate font-medium text-ink";
const sizeClass = "shrink-0 text-xs text-muted tabular-nums";
const errorClass = "text-xs text-danger";
const track = "h-1.5 overflow-hidden rounded-full bg-subtle";
const bar =
"h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none";
const bars = { busy: "bg-primary", done: "bg-success" };
const remove =
"size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const smallIcon = "size-4";
const svg = {
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round",
"aria-hidden": "true",
} as const;
/** 24px stroked icons: the drop prompt, remove, and one per file kind. */
const UPLOAD = "M12 16V4M7 9l5-5 5 5M4 16v4h16v-4";
const REMOVE = "M6 6l12 12M18 6 6 18";
const FILE = "M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4";
const KINDS: Record<string, string> = {
image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
video: "M3 6h13v12H3zM16 10l5-3v10l-5-3",
audio:
"M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
};
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
function accepts(file: { name: string; type?: string }, accept = "") {
const type = (file.type ?? "").toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
const iconOf = ({ type = "" }: DropzoneFile) =>
KINDS[type.split("/")[0]!] ?? FILE;
const generatedId = useId();
const input = ref<HTMLInputElement>();
let seq = props.files.length;
const items = ref<Item[]>(props.files.map((file, key) => ({ ...file, key })));
const over = ref(false);
const percentOf = (file: Item) => props.progress[file.name] ?? file.progress;
/** Keep the native input's files equal to the valid picked files, so a form posts them. */
function update(next: Item[]) {
items.value = next;
const picked = next.flatMap((i) => (i.file && !i.error ? [i.file] : []));
if (input.value) {
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
input.value.files = transfer.files;
}
emit("change", picked);
}
function add(incoming: File[]) {
const limit = props.multiple ? (props.maxFiles ?? Infinity) : 1;
const kept = props.multiple ? items.value : [];
let count = kept.filter((i) => !i.error).length;
const added = incoming.map((file) => {
const error = !accepts(file, props.accept)
? props.typeLabel
: props.maxSize !== undefined && file.size > props.maxSize
? fill(props.tooLargeLabel, formatSize(props.maxSize))
: count >= limit
? fill(props.tooManyLabel, limit)
: undefined;
if (!error) count++;
const { name, size, type } = file;
return { key: seq++, name, size, type, file, error };
});
update([...kept, ...added]);
}
function leave(event: DragEvent) {
const zoneEl = event.currentTarget as HTMLElement;
if (!zoneEl.contains(event.relatedTarget as Node | null)) over.value = false;
}
function drop(event: DragEvent) {
over.value = false;
if (!props.disabled) add([...(event.dataTransfer?.files ?? [])]);
}
</script>
<template>
<div :class="root">
<label
:data-state="over ? 'over' : 'idle'"
:class="zone"
@dragenter.prevent="over = !props.disabled"
@dragover.prevent="over = !props.disabled"
@dragleave="leave"
@drop.prevent="drop"
>
<input
:id="props.id ?? generatedId"
ref="input"
type="file"
:name="props.name"
:accept="props.accept"
:multiple="props.multiple"
:disabled="props.disabled"
:required="props.required"
:class="srOnly"
@change="add([...(($event.target as HTMLInputElement).files ?? [])])"
/>
<svg :class="badge" v-bind="svg">
<path :d="UPLOAD" />
</svg>
<span :class="titleClass"
>{{ props.dropLabel }}
<span :class="browseClass">{{ props.browseLabel }}</span></span
>
<span v-if="props.hint" :class="hintClass">{{ props.hint }}</span>
</label>
<ul v-if="items.length > 0" :class="list">
<li
v-for="file in items"
:key="file.key"
:data-state="file.error ? 'error' : 'ok'"
:class="item"
>
<svg :class="fileIcon" v-bind="svg">
<path :d="iconOf(file)" />
</svg>
<div :class="body">
<div :class="row">
<span :class="nameClass">{{ file.name }}</span>
<span :class="sizeClass">{{ formatSize(file.size) }}</span>
</div>
<p v-if="file.error" role="alert" :class="errorClass">
{{ file.error }}
</p>
<div
v-else-if="percentOf(file) !== undefined"
role="progressbar"
:aria-valuenow="percentOf(file)"
:aria-label="file.name"
:class="track"
>
<div
:class="[bar, bars[percentOf(file)! < 100 ? 'busy' : 'done']]"
:style="{ width: `${percentOf(file)}%` }"
></div>
</div>
</div>
<button
type="button"
:aria-label="fill(props.removeLabel, file.name)"
:class="remove"
@click="update(items.filter((i) => i !== file))"
>
<svg :class="smallIcon" v-bind="svg">
<path :d="REMOVE" />
</svg>
</button>
</li>
</ul>
</div>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/FileDropzone.svelte.
<script lang="ts" module>
export type DropzoneFile = {
name: string;
/** Size in bytes. */
size: number;
type?: string;
/** Upload progress 0 to 100. Leave out to hide the bar. */
progress?: number;
error?: string;
};
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
export function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
export function accepts(file: { name: string; type?: string }, accept = "") {
const type = (file.type ?? "").toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
</script>
<script lang="ts">
import { untrack } from "svelte";
import type { HTMLAttributes } from "svelte/elements";
const root = "grid gap-3";
const zone =
"group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none";
const badge =
"size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none";
const titleClass = "text-sm text-ink";
const browseClass = "font-medium underline underline-offset-4";
const hintClass = "text-xs text-muted";
const srOnly = "sr-only";
const list = "grid gap-2";
const item =
"group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5";
const fileIcon =
"size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger";
const body = "grid min-w-0 flex-1 gap-1.5";
const row = "flex items-baseline justify-between gap-3 text-sm";
const nameClass = "truncate font-medium text-ink";
const sizeClass = "shrink-0 text-xs text-muted tabular-nums";
const errorClass = "text-xs text-danger";
const track = "h-1.5 overflow-hidden rounded-full bg-subtle";
const bar =
"h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none";
const bars = { busy: "bg-primary", done: "bg-success" };
const remove =
"size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const smallIcon = "size-4";
/** 24px stroked icons: the drop prompt, remove, and one per file kind. */
const UPLOAD = "M12 16V4M7 9l5-5 5 5M4 16v4h16v-4";
const REMOVE = "M6 6l12 12M18 6 6 18";
const FILE = "M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4";
const KINDS: Record<string, string> = {
image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
video: "M3 6h13v12H3zM16 10l5-3v10l-5-3",
audio:
"M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
};
type Item = DropzoneFile & { key: number; file?: File };
const iconOf = ({ type = "" }: DropzoneFile) =>
KINDS[type.split("/")[0]!] ?? FILE;
type Props = HTMLAttributes<HTMLDivElement> & {
name?: string;
accept?: string;
multiple?: boolean;
/** Largest file in bytes. */
maxSize?: number;
/** Most files kept when multiple is on. */
maxFiles?: number;
disabled?: boolean;
required?: boolean;
/** Files already in the list, such as earlier uploads. They are shown, not submitted. */
files?: DropzoneFile[];
/** Live upload progress by file name, 0 to 100. */
progress?: Record<string, number>;
hint?: string;
onFilesChange?: (files: File[]) => void;
dropLabel?: string;
browseLabel?: string;
removeLabel?: string;
tooLargeLabel?: string;
typeLabel?: string;
tooManyLabel?: string;
};
let {
name,
accept,
multiple = false,
maxSize,
maxFiles,
disabled,
required,
files = [],
progress = {},
hint,
onFilesChange,
dropLabel = "Drop files here or",
browseLabel = "browse",
removeLabel = "Remove {name}",
tooLargeLabel = "Larger than {size}",
typeLabel = "File type not allowed",
tooManyLabel = "Only {max} files allowed",
id,
class: className,
...rest
}: Props = $props();
const generatedId = $props.id();
const inputId = $derived(id ?? generatedId);
let inputEl = $state<HTMLInputElement>();
let seq = untrack(() => files.length);
let items = $state<Item[]>(
untrack(() => files.map((file, key) => ({ ...file, key }))),
);
let over = $state(false);
const limit = $derived(multiple ? (maxFiles ?? Infinity) : 1);
/** Keep the native input's files equal to the valid picked files, so a form posts them. */
function update(next: Item[]) {
items = next;
const picked = next.flatMap((i) => (i.file && !i.error ? [i.file] : []));
if (inputEl) {
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
inputEl.files = transfer.files;
}
onFilesChange?.(picked);
}
function add(incoming: File[]) {
const kept = multiple ? items : [];
let count = kept.filter((i) => !i.error).length;
const added = incoming.map((file) => {
const error = !accepts(file, accept)
? typeLabel
: maxSize !== undefined && file.size > maxSize
? fill(tooLargeLabel, formatSize(maxSize))
: count >= limit
? fill(tooManyLabel, limit)
: undefined;
if (!error) count++;
const { name, size, type } = file;
return { key: seq++, name, size, type, file, error };
});
update([...kept, ...added]);
}
function drag(
event: DragEvent & { currentTarget: HTMLLabelElement },
entering: boolean,
) {
event.preventDefault();
if (entering) {
over = !disabled;
return;
}
if (!event.currentTarget.contains(event.relatedTarget as Node | null))
over = false;
}
function drop(event: DragEvent) {
event.preventDefault();
over = false;
if (!disabled) add([...(event.dataTransfer?.files ?? [])]);
}
</script>
{#snippet icon(d: string, iconClass: string)}
<svg
class={iconClass}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path {d} />
</svg>
{/snippet}
<div {...rest} class={[root, className]}>
<label
data-state={over ? "over" : "idle"}
class={zone}
ondragenter={(event) => drag(event, true)}
ondragover={(event) => drag(event, true)}
ondragleave={(event) => drag(event, false)}
ondrop={drop}
>
<input
bind:this={inputEl}
id={inputId}
type="file"
{name}
{accept}
{multiple}
{disabled}
{required}
class={srOnly}
onchange={(event) => add([...(event.currentTarget.files ?? [])])}
/>
{@render icon(UPLOAD, badge)}
<span class={titleClass}
>{dropLabel} <span class={browseClass}>{browseLabel}</span></span
>
{#if hint}
<span class={hintClass}>{hint}</span>
{/if}
</label>
{#if items.length > 0}
<ul class={list}>
{#each items as file (file.key)}
{@const percent = progress[file.name] ?? file.progress}
<li data-state={file.error ? "error" : "ok"} class={item}>
{@render icon(iconOf(file), fileIcon)}
<div class={body}>
<div class={row}>
<span class={nameClass}>{file.name}</span>
<span class={sizeClass}>{formatSize(file.size)}</span>
</div>
{#if file.error}
<p role="alert" class={errorClass}>{file.error}</p>
{:else if percent !== undefined}
<div
role="progressbar"
aria-valuenow={percent}
aria-label={file.name}
class={track}
>
<div
class={[bar, bars[percent < 100 ? "busy" : "done"]]}
style:width={`${percent}%`}
></div>
</div>
{/if}
</div>
<button
type="button"
aria-label={fill(removeLabel, file.name)}
class={remove}
onclick={() => update(items.filter((i) => i !== file))}
>
{@render icon(REMOVE, smallIcon)}
</button>
</li>
{/each}
</ul>
{/if}
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/FileDropzone.astro.
---
import type { HTMLAttributes } from "astro/types";
const root = "grid gap-3";
const zone =
"group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none";
const badge =
"size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none";
const titleClass = "text-sm text-ink";
const browseClass = "font-medium underline underline-offset-4";
const hintClass = "text-xs text-muted";
const srOnly = "sr-only";
const list = "grid gap-2";
const item =
"group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5";
const fileIcon =
"size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger";
const body = "grid min-w-0 flex-1 gap-1.5";
const row = "flex items-baseline justify-between gap-3 text-sm";
const nameClass = "truncate font-medium text-ink";
const sizeClass = "shrink-0 text-xs text-muted tabular-nums";
const errorClass = "text-xs text-danger";
const track = "h-1.5 overflow-hidden rounded-full bg-subtle";
const bar =
"h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none";
const bars = { busy: "bg-primary", done: "bg-success" };
const remove =
"size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const smallIcon = "size-4";
/** 24px stroked icons: the drop prompt, remove, and one per file kind. */
const UPLOAD = "M12 16V4M7 9l5-5 5 5M4 16v4h16v-4";
const REMOVE = "M6 6l12 12M18 6 6 18";
const FILE = "M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4";
const KINDS: Record<string, string> = {
image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
video: "M3 6h13v12H3zM16 10l5-3v10l-5-3",
audio:
"M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
};
export type DropzoneFile = {
name: string;
/** Size in bytes. */
size: number;
type?: string;
/** Upload progress 0 to 100. Leave out to hide the bar. */
progress?: number;
error?: string;
};
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
function accepts(file: { name: string; type?: string }, accept = "") {
const type = (file.type ?? "").toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
const iconOf = ({ type = "" }: DropzoneFile) =>
KINDS[type.split("/")[0]!] ?? FILE;
type Props = HTMLAttributes<"div"> & {
name?: string;
accept?: string;
multiple?: boolean;
/** Largest file in bytes. */
maxSize?: number;
/** Most files kept when multiple is on. */
maxFiles?: number;
disabled?: boolean;
required?: boolean;
/** Files already in the list, such as earlier uploads. They are shown, not submitted. */
files?: DropzoneFile[];
hint?: string;
dropLabel?: string;
browseLabel?: string;
removeLabel?: string;
tooLargeLabel?: string;
typeLabel?: string;
tooManyLabel?: string;
};
const {
name,
accept,
multiple = false,
maxSize,
maxFiles,
disabled,
required,
files = [],
hint,
dropLabel = "Drop files here or",
browseLabel = "browse",
removeLabel = "Remove {name}",
tooLargeLabel = "Larger than {size}",
typeLabel = "File type not allowed",
tooManyLabel = "Only {max} files allowed",
id,
class: className,
...rest
} = Astro.props;
const inputId = id ?? `markas-file-dropzone-${crypto.randomUUID().slice(0, 8)}`;
const limit = multiple ? (maxFiles ?? Infinity) : 1;
// Messages the browser fills in for picked files, worked out here so the script stays small.
const labels = {
remove: removeLabel,
type: typeLabel,
tooLarge: maxSize === undefined ? "" : fill(tooLargeLabel, formatSize(maxSize)),
tooMany: fill(tooManyLabel, limit),
};
const svg = {
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round",
"aria-hidden": "true",
} as const;
---
<markas-file-dropzone
class="contents"
data-accept={accept}
data-max-size={maxSize}
data-limit={limit}
data-multiple={multiple ? "" : undefined}
data-disabled={disabled ? "" : undefined}
data-labels={JSON.stringify(labels)}
data-kinds={JSON.stringify({ ...KINDS, file: FILE })}
>
<div {...rest} class:list={[root, className]}>
<label data-state="idle" class={zone}>
<input
id={inputId}
type="file"
name={name}
accept={accept}
multiple={multiple}
disabled={disabled}
required={required}
class={srOnly}
/>
<svg class={badge} {...svg}><path d={UPLOAD}></path></svg>
<span class={titleClass}>{dropLabel} <span class={browseClass}>{browseLabel}</span></span>
{hint && <span class={hintClass}>{hint}</span>}
</label>
<ul class={list} hidden={files.length === 0}>
{
files.map((file) => (
<li data-state={file.error ? "error" : "ok"} class={item}>
<svg class={fileIcon} {...svg}><path d={iconOf(file)}></path></svg>
<div class={body}>
<div class={row}>
<span class={nameClass}>{file.name}</span>
<span class={sizeClass}>{formatSize(file.size)}</span>
</div>
{file.error ? (
<p role="alert" class={errorClass}>{file.error}</p>
) : file.progress !== undefined ? (
<div role="progressbar" aria-valuenow={file.progress} aria-label={file.name} class={track}>
<div class:list={[bar, bars[file.progress < 100 ? "busy" : "done"]]} style={`width: ${file.progress}%`}></div>
</div>
) : null}
</div>
<button type="button" aria-label={fill(removeLabel, file.name)} class={remove} data-remove>
<svg class={smallIcon} {...svg}><path d={REMOVE}></path></svg>
</button>
</li>
))
}
</ul>
<template data-item>
<li data-state="ok" class={item}>
<svg class={fileIcon} {...svg}><path></path></svg>
<div class={body}>
<div class={row}>
<span class={nameClass}></span>
<span class={sizeClass}></span>
</div>
<p role="alert" class={errorClass}></p>
<div role="progressbar" class={track}>
<div class={bar} data-busy={bars.busy} data-done={bars.done}></div>
</div>
</div>
<button type="button" class={remove} data-remove>
<svg class={smallIcon} {...svg}><path d={REMOVE}></path></svg>
</button>
</li>
</template>
</div>
</markas-file-dropzone>
<script>
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
function accepts(file: File, accept = "") {
const type = file.type.toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
// Each dropzone keeps its own list, so it is a custom element: it also works for markup
// added later and for pages reached through view transitions. Picked files are drawn from
// the template next to the list.
class MarkasFileDropzone extends HTMLElement {
private picked = new Map<HTMLElement, File>();
private ready = false;
connectedCallback() {
const zone = this.querySelector("label");
const input = this.querySelector<HTMLInputElement>("input[type=file]");
if (this.ready || !zone || !input) return;
this.ready = true;
const drag = (event: DragEvent, entering: boolean) => {
event.preventDefault();
if (entering) zone.dataset.state = this.disabled ? "idle" : "over";
else if (!zone.contains(event.relatedTarget as Node | null))
zone.dataset.state = "idle";
};
zone.addEventListener("dragenter", (event) => drag(event, true));
zone.addEventListener("dragover", (event) => drag(event, true));
zone.addEventListener("dragleave", (event) => drag(event, false));
zone.addEventListener("drop", (event) => {
event.preventDefault();
zone.dataset.state = "idle";
if (!this.disabled) this.add(input, [...(event.dataTransfer?.files ?? [])]);
});
input.addEventListener("change", () => this.add(input, [...(input.files ?? [])]));
this.addEventListener("click", (event) => {
const row = (event.target as Element).closest("[data-remove]")?.closest("li");
if (!row) return;
row.remove();
this.picked.delete(row);
this.sync(input);
});
}
private get disabled() {
return this.dataset.disabled !== undefined;
}
private add(input: HTMLInputElement, incoming: File[]) {
const list = this.querySelector("ul");
const template = this.querySelector<HTMLTemplateElement>("template[data-item]");
if (!list || !template) return;
const labels = JSON.parse(this.dataset.labels ?? "{}");
const kinds = JSON.parse(this.dataset.kinds ?? "{}");
const maxSize = this.dataset.maxSize ? Number(this.dataset.maxSize) : Infinity;
const limit = Number(this.dataset.limit);
if (this.dataset.multiple === undefined) {
list.replaceChildren();
this.picked.clear();
}
let count = list.querySelectorAll("li[data-state=ok]").length;
for (const file of incoming) {
const error = !accepts(file, this.dataset.accept)
? labels.type
: file.size > maxSize
? labels.tooLarge
: count >= limit
? labels.tooMany
: "";
if (!error) count++;
const row = (template.content.firstElementChild as HTMLElement).cloneNode(true) as HTMLElement;
row.dataset.state = error ? "error" : "ok";
row.querySelector("path")?.setAttribute("d", kinds[file.type.split("/")[0] ?? ""] ?? kinds.file);
const [name, size] = row.querySelectorAll("span");
if (name) name.textContent = file.name;
if (size) size.textContent = formatSize(file.size);
const alert = row.querySelector("[role=alert]");
if (error && alert) alert.textContent = error;
else alert?.remove();
row.querySelector("[role=progressbar]")?.remove();
row.querySelector("[data-remove]")?.setAttribute("aria-label", fill(labels.remove, file.name));
list.append(row);
if (!error) this.picked.set(row, file);
}
this.sync(input);
}
/** Show upload progress (0 to 100) for a listed file: dropzone.setProgress("a.pdf", 40). */
setProgress(name: string, percent: number) {
const template = this.querySelector<HTMLTemplateElement>("template[data-item]");
const proto = template?.content.querySelector("[role=progressbar]");
for (const row of this.querySelectorAll<HTMLElement>("ul > li[data-state=ok]")) {
if (row.querySelector("span")?.textContent !== name) continue;
let track = row.querySelector("[role=progressbar]");
if (!track && proto) {
track = proto.cloneNode(true) as Element;
track.setAttribute("aria-label", name);
row.querySelector("span")?.closest("div")?.parentElement?.append(track);
}
const fill = track?.firstElementChild as HTMLElement | null | undefined;
if (!track || !fill) continue;
track.setAttribute("aria-valuenow", String(percent));
fill.style.width = `${percent}%`;
const model = proto?.firstElementChild as HTMLElement | null | undefined;
const tone = percent < 100 ? model?.dataset.busy : model?.dataset.done;
fill.className = `${model?.getAttribute("class") ?? ""} ${tone ?? ""}`;
}
}
/** Keep the native input's files equal to the valid picked files, so a form posts them. */
private sync(input: HTMLInputElement) {
const list = this.querySelector("ul");
if (list) list.hidden = list.children.length === 0;
const transfer = new DataTransfer();
const files = [...this.picked.values()];
files.forEach((file) => transfer.items.add(file));
input.files = transfer.files;
this.dispatchEvent(new CustomEvent("markas-change", { detail: files, bubbles: true }));
}
}
if (!customElements.get("markas-file-dropzone"))
customElements.define("markas-file-dropzone", MarkasFileDropzone);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/file-dropzone.component.ts.
import { NgTemplateOutlet } from "@angular/common";
import {
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
type ElementRef,
input,
linkedSignal,
numberAttribute,
output,
signal,
viewChild,
} from "@angular/core";
const root = "grid gap-3";
const zone =
"group/zone grid cursor-pointer justify-items-center gap-2 rounded-xl border-2 border-dashed border-line bg-surface px-6 py-8 text-center transition duration-200 ease-out hover:border-primary-line hover:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[:disabled]:opacity-50 data-[state=over]:border-primary data-[state=over]:bg-primary-soft data-[state=over]:ring-4 data-[state=over]:ring-primary/10 motion-reduce:transition-none";
const badge =
"size-11 rounded-full bg-subtle p-3 text-ink transition duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] group-data-[state=over]/zone:-translate-y-1.5 group-data-[state=over]/zone:scale-110 group-data-[state=over]/zone:bg-surface motion-reduce:transition-none";
const titleClass = "text-sm text-ink";
const browseClass = "font-medium underline underline-offset-4";
const hintClass = "text-xs text-muted";
const srOnly = "sr-only";
const list = "grid gap-2";
const item =
"group/item flex items-center gap-3 rounded-lg border border-line bg-surface p-3 data-[state=error]:border-danger/40 data-[state=error]:bg-danger/5";
const fileIcon =
"size-9 shrink-0 rounded-md bg-subtle p-2 text-ink group-data-[state=error]/item:bg-danger/10 group-data-[state=error]/item:text-danger";
const body = "grid min-w-0 flex-1 gap-1.5";
const row = "flex items-baseline justify-between gap-3 text-sm";
const nameClass = "truncate font-medium text-ink";
const sizeClass = "shrink-0 text-xs text-muted tabular-nums";
const errorClass = "text-xs text-danger";
const track = "h-1.5 overflow-hidden rounded-full bg-subtle";
const bar =
"h-full rounded-full transition-[width] duration-300 ease-out motion-reduce:transition-none";
const bars = { busy: "bg-primary", done: "bg-success" };
const remove =
"size-8 shrink-0 rounded-md p-2 text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const smallIcon = "size-4";
/** 24px stroked icons: the drop prompt, remove, and one per file kind. */
const UPLOAD = "M12 16V4M7 9l5-5 5 5M4 16v4h16v-4";
const REMOVE = "M6 6l12 12M18 6 6 18";
const FILE = "M14 3H5v18h14V8zM14 3v5h5M9 13h6M9 17h4";
const KINDS: Record<string, string> = {
image: "M4 4h16v16H4zM4 16l5-5 4 4 3-3 4 4M15 8h.01",
video: "M3 6h13v12H3zM16 10l5-3v10l-5-3",
audio:
"M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",
};
export type DropzoneFile = {
name: string;
/** Size in bytes. */
size: number;
type?: string;
/** Upload progress 0 to 100. Leave out to hide the bar. */
progress?: number;
error?: string;
};
type Item = DropzoneFile & { key: number; file?: File };
const fill = (template: string, value: string | number) =>
template.replace(/\{\w+\}/, () => String(value));
/** 1536 -> "2 KB", 2400000 -> "2.3 MB". */
export function formatSize(bytes: number) {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < 3) {
value /= 1024;
unit++;
}
return `${unit < 2 ? Math.round(value) : Number(value.toFixed(1))} ${["B", "KB", "MB", "GB"][unit]}`;
}
/** Same rules as the accept attribute: .ext, type/*, or an exact MIME type. */
export function accepts(file: { name: string; type?: string }, accept = "") {
const type = (file.type ?? "").toLowerCase();
return (
!accept ||
accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (rule.startsWith(".")) return file.name.toLowerCase().endsWith(rule);
if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
return type === rule;
})
);
}
const iconOf = ({ type = "" }: DropzoneFile) =>
KINDS[type.split("/")[0]!] ?? FILE;
let nextId = 0;
/** Host stays out of layout; id moves to the file input and class to the root. */
@Component({
selector: "markas-file-dropzone",
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgTemplateOutlet],
host: { class: "contents", "[attr.id]": "null", "[attr.name]": "null" },
template: `
<ng-template #icon let-d let-iconClass="iconClass">
<svg
[class]="iconClass"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path [attr.d]="d" />
</svg>
</ng-template>
<div [class]="rootClasses()">
<label
[attr.data-state]="over() ? 'over' : 'idle'"
[class]="zone"
(dragenter)="drag($event, true)"
(dragover)="drag($event, true)"
(dragleave)="drag($event, false)"
(drop)="drop($event)"
>
<input
#inputEl
[id]="inputId()"
type="file"
[attr.name]="name() ?? null"
[attr.accept]="accept() ?? null"
[multiple]="multiple()"
[disabled]="disabled()"
[required]="required()"
[class]="srOnly"
(change)="pick($event)"
/>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{ $implicit: UPLOAD, iconClass: badge }"
/>
<span [class]="titleClass"
>{{ dropLabel() }}
<span [class]="browseClass">{{ browseLabel() }}</span></span
>
@if (hint()) {
<span [class]="hintClass">{{ hint() }}</span>
}
</label>
@if (items().length > 0) {
<ul [class]="list">
@for (file of items(); track file.key) {
<li [attr.data-state]="file.error ? 'error' : 'ok'" [class]="item">
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: iconOf(file),
iconClass: fileIcon,
}"
/>
<div [class]="body">
<div [class]="row">
<span [class]="nameClass">{{ file.name }}</span>
<span [class]="sizeClass">{{ formatSize(file.size) }}</span>
</div>
@if (file.error) {
<p role="alert" [class]="errorClass">{{ file.error }}</p>
} @else if (percentOf(file) !== undefined) {
<div
role="progressbar"
[attr.aria-valuenow]="percentOf(file)"
[attr.aria-label]="file.name"
[class]="track"
>
<div
[class]="barClass(percentOf(file))"
[style.width.%]="percentOf(file)"
></div>
</div>
}
</div>
<button
type="button"
[attr.aria-label]="fill(removeLabel(), file.name)"
[class]="remove"
(click)="removeItem(file)"
>
<ng-container
[ngTemplateOutlet]="icon"
[ngTemplateOutletContext]="{
$implicit: REMOVE,
iconClass: smallIcon,
}"
/>
</button>
</li>
}
</ul>
}
</div>
`,
})
export class FileDropzone {
readonly name = input<string>();
readonly accept = input<string>();
readonly multiple = input(false, { transform: booleanAttribute });
/** Largest file in bytes. */
readonly maxSize = input<number | undefined, unknown>(undefined, {
transform: (value: unknown) =>
value === undefined ? undefined : numberAttribute(value),
});
/** Most files kept when multiple is on. */
readonly maxFiles = input<number | undefined, unknown>(undefined, {
transform: (value: unknown) =>
value === undefined ? undefined : numberAttribute(value),
});
readonly disabled = input(false, { transform: booleanAttribute });
readonly required = input(false, { transform: booleanAttribute });
/** Files already in the list, such as earlier uploads. They are shown, not submitted. */
readonly files = input<DropzoneFile[]>([]);
/** Live upload progress by file name, 0 to 100. */
readonly progress = input<Record<string, number>>({});
readonly hint = input<string>();
readonly dropLabel = input("Drop files here or");
readonly browseLabel = input("browse");
readonly removeLabel = input("Remove {name}");
readonly tooLargeLabel = input("Larger than {size}");
readonly typeLabel = input("File type not allowed");
readonly tooManyLabel = input("Only {max} files allowed");
readonly id = input<string>();
readonly userClass = input("", { alias: "class" });
/** The valid picked files, every time the list changes. */
readonly filesChange = output<File[]>();
protected readonly UPLOAD = UPLOAD;
protected readonly REMOVE = REMOVE;
protected readonly zone = zone;
protected readonly badge = badge;
protected readonly titleClass = titleClass;
protected readonly browseClass = browseClass;
protected readonly hintClass = hintClass;
protected readonly srOnly = srOnly;
protected readonly list = list;
protected readonly item = item;
protected readonly fileIcon = fileIcon;
protected readonly body = body;
protected readonly row = row;
protected readonly nameClass = nameClass;
protected readonly sizeClass = sizeClass;
protected readonly errorClass = errorClass;
protected readonly track = track;
protected readonly remove = remove;
protected readonly smallIcon = smallIcon;
protected readonly fill = fill;
protected readonly formatSize = formatSize;
protected readonly iconOf = iconOf;
private readonly generatedId = `markas-file-dropzone-${nextId++}`;
protected readonly inputId = computed(() => this.id() ?? this.generatedId);
protected readonly rootClasses = computed(() =>
[root, this.userClass()].filter(Boolean).join(" "),
);
protected readonly over = signal(false);
private seq = 0;
/** Starts from the files passed in; picks and removals are kept here. */
protected readonly items = linkedSignal<Item[]>(() => {
const files = this.files();
this.seq = files.length;
return files.map((file, key) => ({ ...file, key }));
});
private readonly inputEl =
viewChild.required<ElementRef<HTMLInputElement>>("inputEl");
protected percentOf(file: Item) {
return this.progress()[file.name] ?? file.progress;
}
protected barClass(percent: number | undefined) {
return `${bar} ${bars[(percent ?? 0) < 100 ? "busy" : "done"]}`;
}
/** Keep the native input's files equal to the valid picked files, so a form posts them. */
private update(next: Item[]) {
this.items.set(next);
const picked = next.flatMap((i) => (i.file && !i.error ? [i.file] : []));
const transfer = new DataTransfer();
picked.forEach((file) => transfer.items.add(file));
this.inputEl().nativeElement.files = transfer.files;
this.filesChange.emit(picked);
}
private add(incoming: File[]) {
const multiple = this.multiple();
const limit = multiple ? (this.maxFiles() ?? Infinity) : 1;
const maxSize = this.maxSize();
const kept = multiple ? this.items() : [];
let count = kept.filter((i) => !i.error).length;
const added = incoming.map((file) => {
const error = !accepts(file, this.accept())
? this.typeLabel()
: maxSize !== undefined && file.size > maxSize
? fill(this.tooLargeLabel(), formatSize(maxSize))
: count >= limit
? fill(this.tooManyLabel(), limit)
: undefined;
if (!error) count++;
const { name, size, type } = file;
return { key: this.seq++, name, size, type, file, error };
});
this.update([...kept, ...added]);
}
protected pick(event: Event) {
this.add([...((event.target as HTMLInputElement).files ?? [])]);
}
protected removeItem(file: Item) {
this.update(this.items().filter((i) => i !== file));
}
protected drag(event: DragEvent, entering: boolean) {
event.preventDefault();
if (entering) {
this.over.set(!this.disabled());
return;
}
const zone = event.currentTarget as HTMLElement;
if (!zone.contains(event.relatedTarget as Node | null))
this.over.set(false);
}
protected drop(event: DragEvent) {
event.preventDefault();
this.over.set(false);
if (!this.disabled()) this.add([...(event.dataTransfer?.files ?? [])]);
}
}Usage
<x-markas.file-dropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
:max-size="5 * 1024 * 1024"
:max-files="4"
hint="Images or PDF, up to 5 MB each"
/>Needs Alpine.js. Inside a form with enctype="multipart/ the valid files post as attachments[].
Livewire
<x-markas.file-dropzone multiple accept="image/*" :max-size="5242880" wire:model="photos" />Add use WithFileUploads; to the component. Only files that pass accept, maxSize, and maxFiles are uploaded, through a hidden file input that carries wire:model. Upload progress fills the bars, and removing every file sets the property back to null (or [] with multiple). Validate again on the server.
import { FileDropzone } from "@/components/markas/FileDropzone";
<FileDropzone
accept="image/*,.pdf"
multiple
maxSize={5 * 1024 * 1024}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
progress={progress}
onFilesChange={upload}
/>;<template>
<FileDropzone
accept="image/*,.pdf"
multiple
:max-size="5 * 1024 * 1024"
:max-files="4"
hint="Images or PDF, up to 5 MB each"
:progress="progress"
@change="upload"
/>
</template><script lang="ts">
import FileDropzone from "$lib/components/markas/FileDropzone.svelte";
</script>
<FileDropzone
accept="image/*,.pdf"
multiple
maxSize={5 * 1024 * 1024}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
{progress}
onFilesChange={upload}
/>---
import FileDropzone from "@/components/markas/FileDropzone.astro";
---
<FileDropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
maxSize={5 * 1024 * 1024}
maxFiles={4}
hint="Images or PDF, up to 5 MB each"
/>A small custom element validates picks, keeps them on the native input, and dispatches a bubbling markas-change event with the valid files as detail. Show upload progress with dropzone.
import { Component, signal } from "@angular/core";
import { FileDropzone } from "./markas/file-dropzone.component";
@Component({
selector: "app-attachments",
imports: [FileDropzone],
template: `
<markas-file-dropzone
name="attachments[]"
accept="image/*,.pdf"
multiple
[maxSize]="5242880"
[maxFiles]="4"
hint="Images or PDF, up to 5 MB each"
[progress]="progress()"
(filesChange)="upload($event)"
/>
`,
})
export class Attachments {
progress = signal<Record<string, number>>({});
upload(files: File[]) {}
}- The drop area is a label around a native file input, so a click, Enter, or Space opens the picker. Only valid files stay on the input, so a regular form post sends them.
- Files that fail
accept,maxSize, ormaxFilesstay in the list with an error until removed. filesshows earlier uploads (name, size, type, progress, error). They are shown, not posted.- Progress: React and Vue take
progressby file name. In Blade dispatchfile-progresswith{ name, progress }on the component. - Attributes and
classgo to the outer element;name,accept,disabled,required, andidgo to the input.
Props
| Name | Type | Default | Description |
|---|---|---|---|
name | string | - | Name of the native file input. The valid picked and dropped files post with the form, so use attachments[] with multiple. |
accept | string | - | Allowed types, as in the accept attribute: .pdf, image/*, or application/zip, comma separated. Other files get the type error. |
multiple | boolean | false | Keeps adding files to the list. Without it a new pick replaces the file. |
maxSize | number | - | Largest file in bytes, for example 5242880 for 5 MB. Larger files stay in the list with an error and are not posted. |
maxFiles | number | - | Most valid files kept when multiple is on. Extra files get the too many error. |
files | { name, size, type?, progress?, error? }[] | [] | Files already in the list, such as earlier uploads. They are shown but not posted. |
progress | Record<string, number> | {} | React and Vue: live upload progress by file name, 0 to 100. Blade: dispatch file-progress with { name, progress } on the component. |
hint | string | - | Small text under the prompt, such as PNG or JPG, up to 5 MB. |
disabled / required / id | boolean / boolean / string | false / false / auto | Passed to the native file input. Other attributes and class go to the outer element. |
onFilesChange / @change / files-change | (files: File[]) => void | - | Called with the valid files after every add or remove. Blade dispatches a files-change event. |
dropLabel | string | Drop files here or | Prompt in the drop area, followed by browseLabel. |
browseLabel | string | browse | Underlined word after the prompt. |
removeLabel | string | Remove {name} | Accessible name of each remove button. {name} is the file name. |
tooLargeLabel | string | Larger than {size} | Error for a file over maxSize. {size} is maxSize formatted, such as 5 MB. |
typeLabel | string | File type not allowed | Error for a file that does not match accept. |
tooManyLabel | string | Only {max} files allowed | Error for files past maxFiles. {max} is the limit. |
(filesChange) | output<File[]> | - | Angular only. Emits the valid picked files every time the list changes. Svelte uses onFilesChange like React. |
markas-change / setProgress() | CustomEvent<File[]> / method | - | Astro only. Bubbling event with the valid files as detail, and a method on markas-file-dropzone that shows upload progress for a file name. |
Accessibility
- The drop area is a label around a visually hidden native file input, so a click, Enter, or Space opens the file picker and the prompt is its name.
- Keyboard focus on the input outlines the whole drop area.
- Each file error is a role alert, each progress bar is a role progressbar named after the file with aria-valuenow, and each remove button names the file.
- With reduced motion the drop highlight and the icon lift appear without animation.
Related components
More markasui components with the same classes in every framework.
- Bottom NavigationMobile app style bottom bar. A pill glides to the selected item, its label rises in, and the bar can shrink to icons while content scrolls.
- Card StackLayered stack of cards. Swipe, arrow keys, or buttons throw the top card away and the next one rises. Loops, with a position indicator.
- Chat MessageMessage in an AI conversation. User bubbles on the right, assistant replies with an avatar, hover actions, a typing indicator, and optional token streaming.
- Currency InputMoney field that formats as you type (Rp 12.500.000), keeps the caret in place, and posts the plain number. Optional quick amount chips.
- DockmacOS style dock. Icons grow smoothly toward the pointer or focus, show a label above, mark open items with a dot, and bounce on launch.
- Drag ElementsArea of cards or stickers you can drag around with light momentum, kept inside its bounds. Arrow keys move a focused item, Escape puts it back.