file-upload

Progress file upload

Progress file upload

Загрузка превью…

src/file-upload/c-file-upload-5.vue

<!--
  Иконки/тип файла — путь lucide, идентичны react.tsx.
  `https://picsum.photos/...` заменён локальным 1x1 data-URI (PIXEL).
-->
<script setup lang="ts">
import { ref } from "vue"
import { AlertAction, Alert as ReuiAlert, AlertTitle as ReuiAlertTitle } from "@/components/reui/alert"
import { Badge } from "@/components/reui/badge"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { formatBytes, useFileUpload, type FileMetadata, type FileWithPreview } from "@/composables/use-file-upload"
import ErrorAlert from "./_shared/ErrorAlert.vue"

const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAUwAOw=="

interface FileUploadItem extends FileWithPreview {
  progress: number
  status: "uploading" | "completed" | "error"
  error?: string
}

const maxFiles = 5
const maxSize = 10 * 1024 * 1024

const defaultImages: FileMetadata[] = [
  { id: "default-3", name: "image-1.png", size: 42048, type: "image/png", url: PIXEL },
  { id: "default-4", name: "image-2.png", size: 62807, type: "image/png", url: PIXEL },
]
const defaultUploadFiles: FileUploadItem[] = defaultImages.map((image) => ({
  id: image.id,
  file: { name: image.name, size: image.size, type: image.type } as File,
  preview: image.url,
  progress: 100,
  status: "completed",
}))

const uploadFiles = ref<FileUploadItem[]>(defaultUploadFiles)

const [state, { removeFile, clearFiles, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, openFileDialog, handleFileChange }] =
  useFileUpload({
    maxFiles,
    maxSize,
    accept: "*",
    multiple: true,
    initialFiles: defaultImages,
    onFilesChange: (newFiles) => {
      uploadFiles.value = newFiles.map((file) => {
        const existing = uploadFiles.value.find((f) => f.id === file.id)
        if (existing) return { ...existing, ...file }
        return { ...file, progress: 0, status: "uploading" as const }
      })
    },
  })

function removeUploadFile(fileId: string) {
  uploadFiles.value = uploadFiles.value.filter((f) => f.id !== fileId)
  removeFile(fileId)
}

function getFileIcon(file: File | FileMetadata) {
  const type = file.type
  if (type.startsWith("image/")) return "image"
  if (type.startsWith("video/")) return "video"
  if (type.startsWith("audio/")) return "headphones"
  return "file-text"
}
</script>

<template>
  <div class="w-full max-w-2xl">
    <div
      class="rounded-lg relative border border-dashed p-8 text-center transition-colors"
      :class="state.isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25 hover:border-muted-foreground/50'"
      @dragenter="handleDragEnter"
      @dragleave="handleDragLeave"
      @dragover="handleDragOver"
      @drop="handleDrop"
    >
      <input type="file" multiple class="sr-only" @change="handleFileChange" />

      <div class="flex flex-col items-center gap-4">
        <div class="flex h-16 w-16 items-center justify-center rounded-full" :class="state.isDragging ? 'bg-primary/10' : 'bg-muted'">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="h-6"
            :class="state.isDragging ? 'text-primary' : 'text-muted-foreground'"
          ><path d="M12 3v12" /><path d="m17 8-5-5-5 5" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /></svg>
        </div>

        <div class="space-y-2">
          <h3 class="text-lg font-semibold">Upload your files</h3>
          <p class="text-muted-foreground text-sm">Drag and drop files here or click to browse</p>
          <p class="text-muted-foreground text-xs">{{ `Support for multiple file types up to ${formatBytes(maxSize)} each` }}</p>
        </div>

        <Button @click="openFileDialog">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="h-4 w-4"
          ><path d="M12 3v12" /><path d="m17 8-5-5-5 5" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /></svg>
          Select files
        </Button>
      </div>
    </div>

    <div v-if="uploadFiles.length > 0" class="mt-6 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <h4 class="text-sm font-medium">Upload Progress</h4>
        <div class="flex items-center gap-2">
          <Badge size="sm" variant="success-light">{{ `Completed: ${uploadFiles.filter((f) => f.status === 'completed').length}` }}</Badge>
        </div>
      </div>
      <Button variant="outline" size="sm" @click="clearFiles">Clear all</Button>
    </div>

    <div v-if="uploadFiles.length > 0" class="mt-4 space-y-3">
      <div v-for="fileItem in uploadFiles" :key="fileItem.id" class="border-border bg-card rounded-lg border p-2.5">
        <div class="flex items-start gap-2.5">
          <div class="shrink-0">
            <img
              v-if="fileItem.preview && fileItem.file.type.startsWith('image/')"
              :src="fileItem.preview"
              :alt="fileItem.file.name"
              class="rounded-lg h-12 w-12 border object-cover"
            />
            <div v-else class="border-border text-muted-foreground rounded-lg flex h-12 w-12 items-center justify-center border">
              <svg
                v-if="getFileIcon(fileItem.file) === 'image'"
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4"
              ><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
                v-else-if="getFileIcon(fileItem.file) === 'video'"
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4"
              ><path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5" /><rect x="2" y="6" width="14" height="12" rx="2" /></svg>
              <svg
                v-else-if="getFileIcon(fileItem.file) === 'headphones'"
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4"
              ><path d="M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3" /></svg>
              <svg
                v-else
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4"
              ><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" /><path d="M10 9H8" /><path d="M16 13H8" /><path d="M16 17H8" /></svg>
            </div>
          </div>

          <div class="min-w-0 flex-1">
            <div class="mt-0.75 flex items-center justify-between">
              <p class="inline-flex flex-col justify-center gap-1 truncate font-medium">
                <span class="text-sm">{{ fileItem.file.name }}</span>
                <span class="text-muted-foreground text-xs">{{ formatBytes(fileItem.file.size) }}</span>
              </p>
              <div class="flex items-center gap-2">
                <Button
                  variant="ghost"
                  size="icon"
                  class="text-muted-foreground size-6 hover:bg-transparent hover:opacity-100"
                  @click="removeUploadFile(fileItem.id)"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    class="size-4"
                  ><path d="M18 6 6 18" /><path d="m6 6 12 12" /></svg>
                </Button>
              </div>
            </div>

            <div v-if="fileItem.status === 'uploading'" class="mt-2">
              <Progress :model-value="fileItem.progress" class="h-1" />
            </div>

            <ReuiAlert v-if="fileItem.status === 'error' && fileItem.error" variant="destructive" class="mt-2 px-2 py-1">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4"
              ><circle cx="12" cy="12" r="10" /><line x1="12" x2="12" y1="8" y2="12" /><line x1="12" x2="12.01" y1="16" y2="16" /></svg>
              <ReuiAlertTitle class="text-xs">{{ fileItem.error }}</ReuiAlertTitle>
              <AlertAction>
                <Button variant="ghost" size="icon" class="text-muted-foreground size-6 hover:bg-transparent hover:opacity-100">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    class="size-3.5"
                  ><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" /><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" /><path d="M8 16H3v5" /></svg>
                </Button>
              </AlertAction>
            </ReuiAlert>
          </div>
        </div>
      </div>
    </div>

    <ErrorAlert :errors="state.errors" />
  </div>
</template>

src/file-upload/_shared/ErrorAlert.vue

<!--
  Общий блок "File upload error(s)" (`registry-reui/bases/radix/hooks/
  use-file-upload.ts` пробрасывает `errors: string[]`), повторяется во всех
  паттернах категории с одинаковой разметкой. Деталь реализации — не
  экспортируется из index.ts (тот же приём, что `calendar/_shared/
  CCalendar.vue`). В проверяемом (пустом/дефолтном) состоянии `errors`
  всегда пуст, поэтому этот компонент никогда не монтируется на диф.
-->
<script setup lang="ts">
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"

defineProps<{ errors: string[] }>()
</script>

<template>
  <Alert v-if="errors.length > 0" variant="destructive" class="mt-5">
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
    ><circle cx="12" cy="12" r="10" /><line x1="12" x2="12" y1="8" y2="12" /><line x1="12" x2="12.01" y1="16" y2="16" /></svg>
    <AlertTitle>File upload error(s)</AlertTitle>
    <AlertDescription>
      <p v-for="(error, index) in errors" :key="index" class="last:mb-0">{{ error }}</p>
    </AlertDescription>
  </Alert>
</template>

Установка

npx shadcn-vue@latest add https://revueui.rootapi.dev/r/c-file-upload-5.json

Зависимости реестра

Источник: порт из ReUI (Keenthemes, MIT)