{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "uploads",
  "title": "Uploads",
  "description": "Each file's upload, for a list of files held elsewhere: a few at a time, with progress, cancel and retry, ending with what the server gave back. A saved file stands in the list as uploaded and never uploads. The File input's.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/settle.json"
  ],
  "files": [
    {
      "path": "registry/lib/uploads.ts",
      "content": "'use client'\n\nimport { settle } from '@/registry/lib/settle'\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'\n\n/*\n * Each file's upload, for a list of files someone else holds, such as a\n * File input's, followed from the list itself, whoever changes it: a file added waits its turn, uploads with its progress, and\n * ends uploaded, with what the server gave back for it, or failed. A few\n * upload at once; a file taken out has its upload cancelled, and a failed\n * one can be tried again. A saved file, such as one an edit form opens\n * with, stands in the list as uploaded and never uploads.\n */\n\n/** Where a file's upload is. */\ntype UploadStatus = 'queued' | 'uploading' | 'done' | 'failed'\n\ninterface Upload {\n  status: UploadStatus\n  /** How many of its bytes have gone up. */\n  loaded: number\n  /** What a form sends for it once it is up: what `upload` resolved with. */\n  value?: string\n  /** Why it failed, when it did. */\n  error?: string\n}\n\ninterface UploadOptions {\n  /** Aborts when the person cancels the upload: stop sending, and the promise's answer is ignored. */\n  signal: AbortSignal\n  /** Call with how many bytes have gone up so far. */\n  onProgress: (loaded: number) => void\n}\n\n/**\n * Sends one file. Resolves, once it is stored, with what a form sends for\n * it, such as its id; throws an `Error` whose message says why not.\n */\ntype UploadFile = (file: File, options: UploadOptions) => Promise<string>\n\n/** A file already saved, such as one an edit form opens with. */\ninterface SavedFile {\n  /** What a form sends for it, such as its id. */\n  value: string\n  name: string\n  /** In bytes. */\n  size: number\n  /** Its MIME type, for its picture. */\n  type?: string\n}\n\nconst savedValues = new WeakMap<File, string>()\n\n/** A `File` that stands for a saved one in a list: it holds no bytes and never uploads. */\nfunction savedFileOf(saved: SavedFile) {\n  const file = new File([], saved.name, { type: saved.type ?? '', lastModified: 0 })\n  Object.defineProperty(file, 'size', { value: saved.size })\n  savedValues.set(file, saved.value)\n  return file\n}\n\n/** What a form sends for a saved file's stand-in; nothing for any other file. */\nfunction savedValueOf(file: File) {\n  return savedValues.get(file)\n}\n\n/** A file's upload: its record, or, with none, uploaded if it stands for a saved file and waiting if files upload. */\nfunction uploadOf(\n  file: File,\n  record: Upload | undefined,\n  uploading: boolean,\n): Upload | undefined {\n  if (record) return record\n  const value = savedValueOf(file)\n  if (value !== undefined) return { status: 'done', loaded: file.size, value }\n  return uploading ? { status: 'queued', loaded: 0 } : undefined\n}\n\n/** The files that start uploading now: the first that wait, up to `concurrency` uploading at once. */\nfunction startable(\n  files: readonly File[],\n  uploads: ReadonlyMap<File, Upload>,\n  concurrency: number,\n): File[] {\n  const running = files.filter((file) => uploads.get(file)?.status === 'uploading').length\n  const room = Math.max(0, concurrency - running)\n  return files.filter((file) => uploads.get(file)?.status === 'queued').slice(0, room)\n}\n\ninterface UploadSummary {\n  /** Files in the list. */\n  count: number\n  done: number\n  failed: number\n  /** Waiting or uploading. */\n  active: number\n  /** Bytes gone up, a failed file's counted as finished with, so a bar never goes back. */\n  loaded: number\n  /** Bytes of every file. */\n  total: number\n  /** How far the whole batch has got, from 0 to 100. */\n  percent: number\n}\n\n/** Where the files' uploads are, taken together. */\nfunction summarize(\n  files: readonly File[],\n  uploads: ReadonlyMap<File, Upload>,\n): UploadSummary {\n  let done = 0\n  let failed = 0\n  let active = 0\n  let loaded = 0\n  let total = 0\n  for (const file of files) {\n    const upload = uploads.get(file)\n    total += file.size\n    if (upload?.status === 'done') done += 1\n    else if (upload?.status === 'failed') failed += 1\n    else if (upload) active += 1\n    const finished = upload?.status === 'done' || upload?.status === 'failed'\n    loaded += finished ? file.size : Math.min(upload?.loaded ?? 0, file.size)\n  }\n  const percent = total > 0 ? (loaded / total) * 100 : active === 0 ? 100 : 0\n  return { count: files.length, done, failed, active, loaded, total, percent }\n}\n\n/** A row's progress: 100 once it's up, 0 while it waits, and none when it doesn't upload. */\nfunction rowProgress(upload: Upload | undefined, size: number): number | undefined {\n  if (!upload) return undefined\n  if (upload.status === 'done') return 100\n  if (size === 0) return 0\n  // Held under 100 until the server says it's stored: the last byte isn't the end.\n  return Math.min(99, (upload.loaded / size) * 100)\n}\n\n/** Why an upload failed, in the person's words. */\nfunction failureText(reason: unknown) {\n  if (reason instanceof Error && reason.message) return reason.message\n  if (typeof reason === 'string' && reason) return reason\n  return 'Couldn’t be uploaded. Try again.'\n}\n\n/** What a screen reader hears once nothing is left uploading. */\nfunction settledAnnouncement(summary: UploadSummary) {\n  if (summary.count === 0 || summary.active > 0) return ''\n  if (summary.failed === 0)\n    return summary.done === 1 ? 'Upload complete' : `All ${summary.done} files uploaded`\n  return `${summary.done} uploaded, ${summary.failed} failed`\n}\n\n/**\n * The uploads of `files`: a file added waits its turn, and one taken out has\n * its upload cancelled. Without `upload`, nothing uploads, and only saved\n * files count as uploaded.\n */\nfunction useUploads({\n  files,\n  upload,\n  concurrency = 3,\n}: {\n  files: readonly File[]\n  upload?: UploadFile\n  /** How many files upload at once. */\n  concurrency?: number\n}) {\n  // The uploads that have started, ended or been retried; a file with none\n  // waits its turn, or is uploaded if it stands for a saved one.\n  const [records, setRecords] = useState<ReadonlyMap<File, Upload>>(() => new Map())\n  const controllers = useRef(new Map<File, AbortController>())\n  const latest = useRef(upload)\n  useLayoutEffect(() => {\n    latest.current = upload\n  })\n\n  // Progress arrives far more often than a screen can show it: one render a frame.\n  const pending = useRef(new Map<File, number>())\n  const frame = useRef(0)\n  const flush = useCallback(() => {\n    frame.current = 0\n    const loaded = new Map(pending.current)\n    pending.current.clear()\n    setRecords((last) => {\n      const next = new Map(last)\n      for (const [file, bytes] of loaded) {\n        const now = next.get(file)\n        if (now?.status === 'uploading') next.set(file, { ...now, loaded: bytes })\n      }\n      return next\n    })\n  }, [])\n\n  const set = useCallback((file: File, entry: Upload | null) => {\n    pending.current.delete(file)\n    setRecords((last) => {\n      const next = new Map(last)\n      if (entry) next.set(file, entry)\n      else next.delete(file)\n      return next\n    })\n  }, [])\n\n  const begin = useCallback(\n    (file: File) => {\n      const send = latest.current\n      if (controllers.current.has(file) || !send) return\n      const controller = new AbortController()\n      controllers.current.set(file, controller)\n      set(file, { status: 'uploading', loaded: 0 })\n      const onProgress = (loaded: number) => {\n        if (controller.signal.aborted) return\n        pending.current.set(file, loaded)\n        if (!frame.current) frame.current = requestAnimationFrame(flush)\n      }\n      settle(\n        () => send(file, { signal: controller.signal, onProgress }),\n        (ok, _waited, reason, value) => {\n          if (controller.signal.aborted) return\n          controllers.current.delete(file)\n          set(\n            file,\n            ok\n              ? { status: 'done', loaded: file.size, value: String(value ?? '') }\n              : { status: 'failed', loaded: 0, error: failureText(reason) },\n          )\n        },\n      )\n    },\n    [flush, set],\n  )\n\n  // Each file's upload, from the list itself: whoever changed it, a file\n  // added waits its turn, and one taken out is cancelled below.\n  const uploads = new Map<File, Upload>()\n  for (const file of files) {\n    const entry = uploadOf(file, records.get(file), upload !== undefined)\n    if (entry) uploads.set(file, entry)\n  }\n\n  useEffect(() => {\n    for (const file of startable(files, uploads, concurrency)) begin(file)\n    // A file taken out of the list stops going up, and its record goes.\n    for (const [file, controller] of controllers.current) {\n      if (files.includes(file)) continue\n      controller.abort()\n      controllers.current.delete(file)\n    }\n    const gone = [...records.keys()].filter((file) => !files.includes(file))\n    // Once this commit is done, so a file added back starts afresh.\n    if (gone.length > 0) queueMicrotask(() => gone.forEach((file) => set(file, null)))\n  })\n\n  // Leaving the page cancels what is still going up.\n  useEffect(() => {\n    const running = controllers.current\n    return () => {\n      cancelAnimationFrame(frame.current)\n      frame.current = 0\n      for (const controller of running.values()) controller.abort()\n      running.clear()\n    }\n  }, [])\n\n  /** Tries a failed file again, where it is in the list. */\n  const retry = (file: File) => {\n    if (uploads.get(file)?.status === 'failed') set(file, null)\n  }\n\n  /** The files still waiting or going up. */\n  const active = files.filter((file) => {\n    const status = uploads.get(file)?.status\n    return status === 'queued' || status === 'uploading'\n  })\n\n  /** What a form sends: each uploaded or saved file's value, in the list's order. */\n  const values = files.flatMap((file) => {\n    const value = uploads.get(file)?.value\n    return value === undefined ? [] : [value]\n  })\n\n  return {\n    uploads,\n    summary: summarize(files, uploads),\n    values,\n    active,\n    retry,\n    /** Tries every failed file again. */\n    retryFailed: () => {\n      for (const file of files) retry(file)\n    },\n  }\n}\n\nexport { savedFileOf, savedValueOf, useUploads }\n\nexport type { SavedFile, Upload, UploadFile, UploadOptions, UploadStatus, UploadSummary }\n\nexport { failureText, rowProgress, settledAnnouncement, startable, summarize, uploadOf }\n",
      "type": "registry:lib",
      "target": "@lib/uploads.ts"
    }
  ],
  "type": "registry:lib"
}