النماذج
file-upload
منطقة سحب وإفلات فوق حقل ملفات أصلي، مع قائمة بالملفات ومعاينة للصور وفحص النوع والحجم في المتصفح.
<form class="w-full max-w-md" onsubmit="event.preventDefault()">
<x-ui.file-upload name="attachments[]" multiple accept=".png,.jpg,.jpeg,.pdf" max-size="10MB"
prompt="اسحب الملفات إلى هنا أو انقر للاستعراض"
up-to="حتى :size"
remove-label="إزالة :name"
type-error="نوع الملف غير مسموح به."
size-error="حجم الملف أكبر من :size." />
</form>
التثبيت
php artisan ui:add file-upload
1. ثبّت الاعتماديات
- composer:
gehrisandro/tailwind-merge-laravel
2.
انسخ الكود إلى
resources/views/components/ui/
resources/views/components/ui/file-upload.blade.php
@props([
'multiple' => false,
'accept' => null,
'maxSize' => null,
'disabled' => false,
'invalid' => false,
'prompt' => 'Drag files here or click to browse',
'hint' => null,
'upTo' => 'up to :size',
'removeLabel' => 'Remove :name',
'typeError' => 'This file type is not allowed.',
'sizeError' => 'File is larger than :size.',
])
@php
// max-size takes bytes or a string like "500KB" / "10MB" (1024-based).
$maxBytes = null;
if ($maxSize !== null && preg_match('/^\s*([\d.]+)\s*(B|KB|MB|GB)?\s*$/i', (string) $maxSize, $m)) {
$power = ['B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3][strtoupper($m[2] ?? '') ?: 'B'];
$maxBytes = (int) round((float) $m[1] * 1024 ** $power);
}
// Default hint: "PNG, JPG, PDF up to 10MB", built from accept and max-size.
if ($hint === null) {
$types = $accept
? implode(', ', array_map(fn ($t) => strtoupper(ltrim(trim($t), '.')), explode(',', $accept)))
: '';
$limit = $maxSize !== null ? str_replace(':size', $maxSize, $upTo) : '';
$hint = trim($types . ' ' . $limit);
}
$classes = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'group/file-upload grid w-full gap-3',
$attributes->get('class'),
);
$zone = $invalid
? 'border-destructive group-data-[state=dragging]/file-upload:border-destructive'
: 'border-input group-data-[state=dragging]/file-upload:border-primary';
@endphp
<div class="{{ $classes }}" data-ui-file-upload data-state="idle" data-accept="{{ $accept }}"
data-max-size="{{ $maxBytes }}" data-max-label="{{ $maxSize }}" data-type-error="{{ $typeError }}"
data-size-error="{{ $sizeError }}" data-remove-label="{{ $removeLabel }}">
<label data-ui-file-upload-zone
class="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-dashed px-6 py-10 text-center transition-[color,background-color,border-color,box-shadow] hover:bg-accent/50 group-data-[state=dragging]/file-upload:bg-accent has-focus-visible:border-ring has-focus-visible:ring-[3px] has-focus-visible:ring-ring/50 has-disabled:cursor-not-allowed has-disabled:opacity-50 has-disabled:hover:bg-transparent {{ $zone }}">
<input type="file" data-ui-file-upload-input class="sr-only" @if ($accept) accept="{{ $accept }}" @endif
@if ($multiple) multiple @endif @disabled($disabled) @if ($invalid) aria-invalid="true" @endif
{{ $attributes->except('class') }} />
<span class="flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground">
<svg class="size-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
aria-hidden="true">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" x2="12" y1="3" y2="15" />
</svg>
</span>
<span class="text-sm font-medium">{{ $prompt }}</span>
@if ($hint !== '')
<span class="text-xs text-muted-foreground">{{ $hint }}</span>
@endif
</label>
<ul data-ui-file-upload-list class="grid gap-2 empty:hidden" aria-live="polite"></ul>
<template data-ui-file-upload-template>
<li data-state="valid"
class="flex items-center gap-3 rounded-md border px-3 py-2 text-sm data-[state=error]:border-destructive/50">
<span
class="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md bg-muted text-muted-foreground">
<img data-ui-file-upload-thumb class="hidden size-full object-cover" alt="" />
<svg data-ui-file-upload-icon="image" class="hidden size-5" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</svg>
<svg data-ui-file-upload-icon="file" class="hidden size-5" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
<path d="M14 2v4a2 2 0 0 0 2 2h4" />
</svg>
</span>
<div class="min-w-0 flex-1">
<p data-ui-file-upload-name class="truncate font-medium"></p>
<p data-ui-file-upload-size class="text-xs text-muted-foreground"></p>
<p data-ui-file-upload-error class="text-xs text-destructive" hidden></p>
</div>
<button type="button" data-ui-file-upload-remove
class="inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50 focus-visible:ring-ring/50 focus-visible:ring-[3px]">
<svg class="size-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
aria-hidden="true">
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
</button>
</li>
</template>
</div>
@once
<script>
(function() {
if (window.__laralcnFileUpload) return;
window.__laralcnFileUpload = true;
// Each root keeps its list as root.__items: { file, error, url }.
// Accepted files (no error) are mirrored into the native input.
function items(root) {
return root.__items || (root.__items = []);
}
function input(root) {
return root.querySelector('[data-ui-file-upload-input]');
}
function humanSize(bytes) {
var units = ['B', 'KB', 'MB', 'GB'];
var i = 0;
while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++; }
return (i === 0 ? bytes : bytes.toFixed(1).replace(/\.0$/, '')) + ' ' + units[i];
}
function accepts(accept, file) {
if (!accept) return true;
var name = file.name.toLowerCase();
var type = (file.type || '').toLowerCase();
return accept.split(',').some(function(token) {
token = token.trim().toLowerCase();
if (!token) return false;
if (token.charAt(0) === '.') return name.slice(-token.length) === token;
if (token.slice(-2) === '/*') return type.indexOf(token.slice(0, -1)) === 0;
return type === token;
});
}
function validate(root, file) {
if (!accepts(root.dataset.accept, file)) return root.dataset.typeError;
var max = parseInt(root.dataset.maxSize, 10);
if (max && file.size > max) return root.dataset.sizeError.replace(':size', root.dataset.maxLabel);
return null;
}
function drop(item) {
if (item.url) URL.revokeObjectURL(item.url);
}
function sameFile(a, b) {
return a.name === b.name && a.size === b.size && a.lastModified === b.lastModified;
}
// Merge new files into the list (single mode replaces it), then sync
// the native input so the form submits only the accepted files.
function add(root, files) {
var field = input(root);
var list = items(root);
files = Array.prototype.slice.call(files);
if (!field.multiple) {
list.forEach(drop);
list.length = 0;
files = files.slice(0, 1);
}
files.forEach(function(file) {
if (list.some(function(item) { return sameFile(item.file, file); })) return;
var error = validate(root, file);
var url = !error && /^image\//.test(file.type) ? URL.createObjectURL(file) : null;
list.push({ file: file, error: error, url: url });
});
sync(root);
}
function sync(root) {
var transfer = new DataTransfer();
items(root).forEach(function(item) {
if (!item.error) transfer.items.add(item.file);
});
input(root).files = transfer.files;
paint(root);
}
function paint(root) {
var list = root.querySelector('[data-ui-file-upload-list]');
var template = root.querySelector('[data-ui-file-upload-template]');
list.textContent = '';
items(root).forEach(function(item, index) {
var li = template.content.firstElementChild.cloneNode(true);
var isImage = /^image\//.test(item.file.type);
li.dataset.index = index;
li.dataset.state = item.error ? 'error' : 'valid';
li.querySelector('[data-ui-file-upload-name]').textContent = item.file.name;
li.querySelector('[data-ui-file-upload-size]').textContent = humanSize(item.file.size);
li.querySelector('[data-ui-file-upload-remove]').setAttribute('aria-label',
root.dataset.removeLabel.replace(':name', item.file.name));
if (item.error) {
var error = li.querySelector('[data-ui-file-upload-error]');
error.textContent = item.error;
error.hidden = false;
}
if (item.url) {
var thumb = li.querySelector('[data-ui-file-upload-thumb]');
thumb.src = item.url;
thumb.classList.remove('hidden');
} else {
li.querySelector('[data-ui-file-upload-icon="' + (isImage ? 'image' : 'file') + '"]')
.classList.remove('hidden');
}
list.appendChild(li);
});
}
function changed(root) {
input(root).dispatchEvent(new Event('change', { bubbles: true }));
}
function zoneRoot(event) {
var zone = event.target.closest && event.target.closest('[data-ui-file-upload-zone]');
if (!zone) return null;
var root = zone.closest('[data-ui-file-upload]');
return input(root).disabled ? null : root;
}
['dragenter', 'dragover'].forEach(function(type) {
document.addEventListener(type, function(event) {
var root = zoneRoot(event);
if (!root) return;
event.preventDefault();
root.dataset.state = 'dragging';
});
});
document.addEventListener('dragleave', function(event) {
var root = zoneRoot(event);
if (!root) return;
var zone = root.querySelector('[data-ui-file-upload-zone]');
if (!zone.contains(event.relatedTarget)) root.dataset.state = 'idle';
});
document.addEventListener('drop', function(event) {
var root = zoneRoot(event);
if (!root) return;
event.preventDefault();
root.dataset.state = 'idle';
if (!event.dataTransfer || !event.dataTransfer.files.length) return;
add(root, event.dataTransfer.files);
changed(root);
});
// Capture phase: runs before any listener on the input or its form,
// so by the time a consumer sees the picker's change event the input
// already holds the merged, validated file list.
document.addEventListener('change', function(event) {
if (!event.isTrusted || !event.target.matches('[data-ui-file-upload-input]')) return;
add(event.target.closest('[data-ui-file-upload]'), event.target.files);
}, true);
document.addEventListener('click', function(event) {
var button = event.target.closest('[data-ui-file-upload-remove]');
if (!button) return;
var root = button.closest('[data-ui-file-upload]');
var li = button.closest('li');
var index = parseInt(li.dataset.index, 10);
var list = items(root);
var removed = list.splice(index, 1)[0];
drop(removed);
sync(root);
if (!removed.error) changed(root);
var next = root.querySelectorAll('[data-ui-file-upload-remove]');
(next[Math.min(index, next.length - 1)] || input(root)).focus();
});
})();
</script>
@endonce
الاستخدام
{{-- Several files, checked against accept and max-size in the browser --}}
<x-ui.file-upload name="attachments[]" multiple accept=".png,.jpg,.pdf" max-size="10MB" />
{{-- One image; a new pick replaces the old one --}}
<x-ui.file-upload name="avatar" accept="image/*" max-size="2MB" />
{{-- Error state from server validation, custom copy --}}
<x-ui.file-upload name="contract" accept=".pdf" :invalid="$errors->has('contract')"
prompt="Drop the signed contract here" hint="PDF only" />
{{-- Livewire (WithFileUploads): wire:model lands on the native input --}}
<x-ui.file-upload wire:model="photos" multiple accept="image/*" />
<script>
// The input fires a normal change event after every drop or removal.
const field = document.querySelector('input[name="attachments[]"]');
field.addEventListener('change', () => console.log(field.files.length));
// Uploading is up to you, for example:
// fetch('/upload', { method: 'POST', body: new FormData(field.form) });
</script>
يبقى حقل الملفات الأصلي هو الحقل المُرسَل: تُمرَّر إليه name وwire:model وid وrequired، ويُطلق الحدث change بعد كل إفلات أو إزالة. تُفحص accept وmax-size (بالبايت أو 10MB) في المتصفح؛ وتظهر الملفات المرفوضة في القائمة مع رسالة خطأ ولا تُضاف أبدًا. لا يرفع المكوّن الملفات بنفسه: أرسل new FormData(form) عبر fetch، أو استخدم WithFileUploads في Livewire.
الخصائص
كل خاصية مع قيمتها الافتراضية. مرّر أيًّا منها كسمة، واستخدم : لربط قيمة PHP.
@props([
'multiple' => false,
'accept' => null,
'maxSize' => null,
'disabled' => false,
'invalid' => false,
'prompt' => 'Drag files here or click to browse',
'hint' => null,
'upTo' => 'up to :size',
'removeLabel' => 'Remove :name',
'typeError' => 'This file type is not allowed.',
'sizeError' => 'File is larger than :size.',
])