⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(web): attach files in the new issue modal (#52)
Crofffc3769ec3e4b
diff --git a/apps/web/src/components/common/overlay/Modal.tsx b/apps/web/src/components/common/overlay/Modal.tsxindex fa3f2190..d9adec2f 100644--- a/apps/web/src/components/common/overlay/Modal.tsx+++ b/apps/web/src/components/common/overlay/Modal.tsx@@ -59,7 +59,7 @@ export default function Modal({'transition-none',fullscreen? 'top-0 left-0 flex h-screen w-screen max-w-none translate-x-0 translate-y-0 flex-col overflow-hidden rounded-none border-0 sm:max-w-none'- : cn('max-h-[85vh] overflow-y-auto', MAX_WIDTH[`${wide}`]),+ : cn('max-h-[85vh] overflow-hidden', MAX_WIDTH[`${wide}`]),)}><DialogHeader>@@ -76,7 +76,16 @@ export default function Modal({</DialogTitle>{description && <DialogDescription>{description}</DialogDescription>}</DialogHeader>- {children}+ {/* The body scrolls, not the dialog: the dialog stays the positioned+ ancestor a body-wide overlay can cover without scrolling away. */}+ <div+ className={cn(+ 'min-h-0',+ fullscreen ? 'flex flex-1 flex-col overflow-hidden' : 'overflow-y-auto',+ )}+ >+ {children}+ </div>{/* After the body: Radix focuses the first tabbable node on open, whichshould be a field of the body, not a control. */}<div className="absolute top-3 right-3 flex items-center gap-1">diff --git a/apps/web/src/features/issue/components/IssueAttachmentThumb.tsx b/apps/web/src/features/issue/components/IssueAttachmentThumb.tsxnew file mode 100644index 00000000..43f27fab--- /dev/null+++ b/apps/web/src/features/issue/components/IssueAttachmentThumb.tsx@@ -0,0 +1,28 @@+import Image from 'next/image';+import { FileIcon } from 'lucide-react';+import { isImage, isVideo, type Embeddable } from '../utils/attachmentEmbed';++// An attachment card's leading thumbnail: images and videos preview themselves,+// every other type falls back to a generic file glyph.+export default function IssueAttachmentThumb({ attachment }: { attachment: Embeddable }) {+ if (isImage(attachment))+ return (+ <Image+ src={attachment.url}+ alt={attachment.filename}+ fill+ // The thumbnail is w-10 (40px) in every card size used here.+ sizes="40px"+ // A file picked in the new issue modal is previewed from a local blob:+ // URL, which the image optimizer cannot fetch.+ unoptimized={attachment.url.startsWith('blob:')}+ draggable={false}+ className="object-cover"+ />+ );+ if (isVideo(attachment))+ return (+ <video src={attachment.url} className="size-full object-cover" muted draggable={false} />+ );+ return <FileIcon className="text-muted-foreground" />;+}diff --git a/apps/web/src/features/issue/components/create/NewIssueAttachButton.tsx b/apps/web/src/features/issue/components/create/NewIssueAttachButton.tsxnew file mode 100644index 00000000..fd61f5be--- /dev/null+++ b/apps/web/src/features/issue/components/create/NewIssueAttachButton.tsx@@ -0,0 +1,49 @@+import { useRef } from 'react';+import { Paperclip } from 'lucide-react';+import { useStorageSettingsQuery } from '@/services/storage.service';+import { attachmentAccept, attachmentLimitHint } from '@/utils/uploadLimits';+import { Button } from '@/components/ui/button';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';++// Attaches files to an issue being created; the picked files are listed by+// NewIssueAttachmentList and uploaded once the issue exists.+export default function NewIssueAttachButton({+ onPick,+}: {+ onPick: (files: FileList | null) => void;+}) {+ const limits = useStorageSettingsQuery().data;+ const fileInput = useRef<HTMLInputElement>(null);++ return (+ <>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="text-muted-foreground hover:text-foreground"+ aria-label="Attach files"+ onClick={() => fileInput.current?.click()}+ >+ <Paperclip />+ </Button>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Attach files{limits && `. ${attachmentLimitHint(limits)}`}+ </TooltipContent>+ </Tooltip>+ <input+ ref={fileInput}+ type="file"+ multiple+ accept={attachmentAccept(limits)}+ className="hidden"+ onChange={(e) => {+ onPick(e.target.files);+ e.target.value = '';+ }}+ />+ </>+ );+}diff --git a/apps/web/src/features/issue/components/create/NewIssueAttachmentList.tsx b/apps/web/src/features/issue/components/create/NewIssueAttachmentList.tsxnew file mode 100644index 00000000..61070e5a--- /dev/null+++ b/apps/web/src/features/issue/components/create/NewIssueAttachmentList.tsx@@ -0,0 +1,64 @@+import { X } from 'lucide-react';+import { type PendingAttachment } from '../../hooks/useNewIssueAttachments';+import { isImage, isVideo, type Embeddable } from '../../utils/attachmentEmbed';+import { formatSize } from '../../utils/fileSize';+import IssueAttachmentThumb from '../IssueAttachmentThumb';+import {+ Attachment as AttachmentCard,+ AttachmentAction,+ AttachmentActions,+ AttachmentContent,+ AttachmentDescription,+ AttachmentMedia,+ AttachmentTitle,+} from '@/components/ui/attachment';++// Files waiting to be uploaded once the issue is created. They preview from+// their local blob: URL, and Insert embeds that URL into the description; the+// modal rewrites it to the stored URL after the upload.+export default function NewIssueAttachmentList({+ items,+ onInsert,+ onRemove,+}: {+ items: PendingAttachment[];+ onInsert: (attachment: Embeddable) => void;+ onRemove: (id: number) => void;+}) {+ if (items.length === 0) return null;++ return (+ <div className="mt-3 flex flex-col gap-2">+ {items.map((item) => (+ <AttachmentCard key={item.id} className="w-full">+ <AttachmentMedia variant={isImage(item) || isVideo(item) ? 'image' : 'icon'}>+ <IssueAttachmentThumb attachment={item} />+ </AttachmentMedia>++ <AttachmentContent>+ <AttachmentTitle>{item.filename}</AttachmentTitle>+ <AttachmentDescription>{formatSize(item.file.size)}</AttachmentDescription>+ </AttachmentContent>++ <AttachmentActions>+ <AttachmentAction+ size="sm"+ onClick={() => onInsert(item)}+ title="Insert into description"+ >+ Insert+ </AttachmentAction>+ <AttachmentAction+ className="hover:text-destructive"+ onClick={() => onRemove(item.id)}+ aria-label={`Remove ${item.filename}`}+ title="Remove"+ >+ <X />+ </AttachmentAction>+ </AttachmentActions>+ </AttachmentCard>+ ))}+ </div>+ );+}diff --git a/apps/web/src/features/issue/components/create/NewIssueDropOverlay.tsx b/apps/web/src/features/issue/components/create/NewIssueDropOverlay.tsxnew file mode 100644index 00000000..fd782b0e--- /dev/null+++ b/apps/web/src/features/issue/components/create/NewIssueDropOverlay.tsx@@ -0,0 +1,21 @@+import { Paperclip } from 'lucide-react';++// Covers the whole modal while files are dragged over it, stating where they+// land. pointer-events-none so the drag events keep reaching the modal below.+export default function NewIssueDropOverlay({ count }: { count: number }) {+ let label: string;+ if (count === 1) label = 'Drop the file';+ else if (count > 1) label = `Drop ${count} files`;+ // A drag does not always expose its items, leaving the count at 0.+ else label = 'Drop files';++ return (+ <div className="pointer-events-none absolute inset-0 z-50 flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-primary bg-background/80 text-primary backdrop-blur-sm">+ <Paperclip className="size-6" />+ <span className="text-sm font-medium">{label}</span>+ <span className="text-xs text-muted-foreground">+ Added to the description and attached to the issue+ </span>+ </div>+ );+}diff --git a/apps/web/src/features/issue/components/create/NewIssueModal.tsx b/apps/web/src/features/issue/components/create/NewIssueModal.tsxindex 19d267b0..014c751b 100644--- a/apps/web/src/features/issue/components/create/NewIssueModal.tsx+++ b/apps/web/src/features/issue/components/create/NewIssueModal.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState, type DragEvent } from 'react';+import { useEffect, useRef, useState } from 'react';import { type Editor } from '@tiptap/react';import { MoreHorizontal } from 'lucide-react';import { type IssueFieldValueInput, type ProjectDetail } from '@/lib/api';@@ -7,9 +7,18 @@ import { cn } from '@/lib/utils';import { useSession } from '@/lib/auth-client';import { useCreateIssue, useSetFieldValue, useUpdateIssue } from '@/services/issues.service';import { useCustomFieldsQuery } from '@/services/customFields.service';-import { useUploadAttachment } from '../../services/attachments.service';-import { attachmentHtml } from '../../utils/attachmentEmbed';+import { useFileDragZone } from '../../hooks/useFileDragZone';+import { useNewIssueAttachments } from '../../hooks/useNewIssueAttachments';+import {+ attachmentHtml,+ removeEmbed,+ stripEmbed,+ type Embeddable,+} from '../../utils/attachmentEmbed';import IssueCustomFieldPill from '../fields/IssueCustomFieldPill';+import NewIssueAttachButton from './NewIssueAttachButton';+import NewIssueAttachmentList from './NewIssueAttachmentList';+import NewIssueDropOverlay from './NewIssueDropOverlay';import Modal from '@/components/common/overlay/Modal';import IssueMarkdownEditor from '../editor/IssueMarkdownEditor';import AssigneeSelect from '@/components/common/fields/AssigneeSelect';@@ -86,58 +95,64 @@ export default function NewIssueModal({const createIssue = useCreateIssue();const updateIssue = useUpdateIssue(project.project.key);const setFieldValueMutation = useSetFieldValue(project.project.key);- const uploadAttachment = useUploadAttachment();-- // Files pasted or dropped into the description before the issue exists.- // Attachments upload against an issue id, which we only have after creation,- // so each file is shown inline via a local blob: URL and held here; on submit- // they are uploaded for real and their blob: URLs rewritten to the stored URL.- const pendingFilesRef = useRef(new Map<string, File>());- const uploadFile = async (file: File) => {- const url = URL.createObjectURL(file);- pendingFilesRef.current.set(url, file);- return { url, contentType: file.type, filename: file.name };- };-- // Revoke any object URLs still pending when the modal unmounts (closed without- // submitting); the submit path revokes the ones it consumes.- useEffect(() => {- const pending = pendingFilesRef.current;- return () => {- for (const url of pending.keys()) URL.revokeObjectURL(url);- };- }, []);+ const attachments = useNewIssueAttachments();- // The description editor instance, so a file dropped anywhere on the modal- // (not just onto the small editor box) can be inserted at the cursor.+ // The description editor instance, so a file dropped or pasted anywhere on the+ // modal (not just onto the small editor box) can be inserted at the cursor.const [descEditor, setDescEditor] = useState<Editor | null>(null);- const dropFilesIntoDescription = (files: FileList) => {+ // The markdown editors of the body custom fields, so an attachment removed+ // from the list takes its embeds with it wherever they were inserted.+ const fieldEditors = useRef(new Map<number, Editor>());++ function insertIntoDescription(a: Embeddable) {+ descEditor?.chain().focus().insertContent(attachmentHtml(a)).run();+ }++ function removeAttachment(id: number) {+ const item = attachments.remove(id);+ if (!item) return;+ if (descEditor) removeEmbed(descEditor, item.url);+ for (const editor of fieldEditors.current.values()) removeEmbed(editor, item.url);+ }++ function insertFilesIntoDescription(files: FileList) {if (!descEditor) return;let pos = descEditor.state.selection.to;void (async () => {for (const file of Array.from(files)) {- const a = await uploadFile(file).catch(() => null);- if (!a || !descEditor) continue;+ const a = await attachments.uploadFile(file).catch(() => null);+ if (!a) continue;descEditor.chain().insertContentAt(pos, attachmentHtml(a)).focus().run();pos = descEditor.state.selection.to;}})();- };-- function onModalDragOver(e: DragEvent<HTMLDivElement>) {- if (e.dataTransfer.types.includes('Files')) e.preventDefault();}- function onModalDrop(e: DragEvent<HTMLDivElement>) {- // A drop landing on the editor box is already handled by tiptap, which- // calls preventDefault; only handle drops elsewhere on the modal here.- if (e.defaultPrevented) return;- const files = e.dataTransfer.files;- if (!files || files.length === 0) return;- e.preventDefault();- dropFilesIntoDescription(files);- }+ const { draggedFiles, dragHandlers } = useFileDragZone(insertFilesIntoDescription);++ // Read through a ref: the paste listener below is registered once, while the+ // insert closes over the editor and the upload limits, which both arrive after+ // the first render.+ const insertFilesRef = useRef(insertFilesIntoDescription);+ insertFilesRef.current = insertFilesIntoDescription;++ // A paste carrying files lands in the description unless a markdown editor has+ // the focus, in which case tiptap has already inserted it there. The listener+ // is on the document because the focus may sit on the dialog itself, above the+ // modal body.+ useEffect(() => {+ function onPaste(e: ClipboardEvent) {+ const files = e.clipboardData?.files;+ if (!files || files.length === 0) return;+ const target = e.target;+ if (target instanceof Element && target.closest('.ProseMirror')) return;+ e.preventDefault();+ insertFilesRef.current(files);+ }+ document.addEventListener('paste', onPaste);+ return () => document.removeEventListener('paste', onPaste);+ }, []);const [addFieldOpen, setAddFieldOpen] = useState(false);@@ -149,6 +164,7 @@ export default function NewIssueModal({// eslint-disable-next-line react-hooks/exhaustive-deps}, [fieldsQuery.data]);+ const errorMessage = error ?? attachments.error;const bodyDefs = fieldDefs.filter((d) => d.showInBody);const propertyDefs = fieldDefs.filter((d) => !d.showInBody);const activeDefs = propertyDefs.filter((d) => activeFieldIds.includes(d.id));@@ -186,23 +202,20 @@ export default function NewIssueModal({labelIds,},});- // Upload files pasted/dropped into the description, then rewrite their- // blob: URLs to the stored attachment URLs. A failed upload drops its- // placeholder rather than leaving a dead blob: link.- const pending = pendingFilesRef.current;- if (pending.size > 0) {- let body = description;- for (const [blobUrl, file] of pending) {- const a = await uploadAttachment- .mutateAsync({ issueId: created.id, file })- .catch(() => null);- body = body.replaceAll(blobUrl, a ? a.url : '');- URL.revokeObjectURL(blobUrl);- }- pending.clear();- if (body !== description) {- await updateIssue.mutateAsync({ id: created.id, patch: { description: body.trim() } });+ // Upload the pending files, then point every embed at its stored URL+ // instead of the local blob: one.+ const storedUrls = await attachments.uploadAll(created.id);+ const rewrite = (markdown: string) => {+ let out = markdown;+ for (const [blobUrl, url] of storedUrls) {+ out = url ? out.replaceAll(blobUrl, url) : stripEmbed(out, blobUrl);}+ return out;+ };++ const body = rewrite(description);+ if (body !== description) {+ await updateIssue.mutateAsync({ id: created.id, patch: { description: body.trim() } });}// Set custom field values on the freshly created issue. Body fields are@@ -213,7 +226,8 @@ export default function NewIssueModal({if (!v) continue;const hasValue = (v.optionIds?.length ?? 0) > 0 || (v.value != null && v.value !== '');if (!hasValue) continue;- await setFieldValueMutation.mutateAsync({ issueId: created.id, fieldId: def.id, value: v });+ const value = typeof v.value === 'string' ? { ...v, value: rewrite(v.value) } : v;+ await setFieldValueMutation.mutateAsync({ issueId: created.id, fieldId: def.id, value });}onCreated();} catch (err) {@@ -234,9 +248,11 @@ export default function NewIssueModal({><divclassName={cn(fullscreen && 'flex min-h-0 flex-1 flex-col overflow-y-auto')}- onDragOver={onModalDragOver}- onDrop={onModalDrop}+ {...dragHandlers}>+ {/* Not inside a relative box on purpose: the dialog itself is the+ positioned ancestor, so the overlay covers the whole modal. */}+ {draggedFiles !== null && <NewIssueDropOverlay count={draggedFiles} />}<inputclassName="w-full bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground"placeholder="Issue title"@@ -249,7 +265,7 @@ export default function NewIssueModal({defaultValue={description}onChange={setDescription}onReady={setDescEditor}- uploadFile={uploadFile}+ uploadFile={attachments.uploadFile}/>{bodyDefs.length > 0 && (@@ -264,6 +280,11 @@ export default function NewIssueModal({defaultValue={(fieldValues[def.id]?.value as string) ?? ''}placeholder="Empty"onChange={(md) => setFieldValue(def.id, { value: md })}+ onReady={(editor) => {+ if (editor) fieldEditors.current.set(def.id, editor);+ else fieldEditors.current.delete(def.id);+ }}+ uploadFile={attachments.uploadFile}/>) : (<IssueCustomFieldPill@@ -382,9 +403,16 @@ export default function NewIssueModal({)}</div>- {error && <p className="mt-3 text-xs text-destructive">{error}</p>}+ <NewIssueAttachmentList+ items={attachments.pending}+ onInsert={insertIntoDescription}+ onRemove={removeAttachment}+ />++ {errorMessage && <p className="mt-3 text-xs text-destructive">{errorMessage}</p>}- <div className="mt-4 flex items-center justify-end border-t pt-3">+ <div className="mt-4 flex items-center justify-between border-t pt-3">+ <NewIssueAttachButton onPick={attachments.attach} /><Button disabled={saving || !title.trim()} onClick={submit}>Create issue</Button>diff --git a/apps/web/src/features/issue/components/detail/IssueAttachmentsPanel.tsx b/apps/web/src/features/issue/components/detail/IssueAttachmentsPanel.tsxindex cb455ece..f46b63c4 100644--- a/apps/web/src/features/issue/components/detail/IssueAttachmentsPanel.tsx+++ b/apps/web/src/features/issue/components/detail/IssueAttachmentsPanel.tsx@@ -1,21 +1,15 @@import { useRef, useState, type DragEvent } from 'react';-import Image from 'next/image';-import {- Download,- FileIcon,- GripVertical,- HelpCircle,- Paperclip,- Plus,- Trash2,-} from 'lucide-react';+import { Download, GripVertical, HelpCircle, Paperclip, Plus, Trash2 } from 'lucide-react';import { type Attachment } from '@/lib/api';+import { useFileDragZone } from '../../hooks/useFileDragZone';import {useAttachmentsQuery,useDeleteAttachment,useUploadAttachment,} from '../../services/attachments.service';import { attachmentHtml, isImage, isVideo } from '../../utils/attachmentEmbed';+import { formatSize } from '../../utils/fileSize';+import IssueAttachmentThumb from '../IssueAttachmentThumb';import { useStorageSettingsQuery } from '@/services/storage.service';import { attachmentAccept, attachmentError, attachmentLimitHint } from '@/utils/uploadLimits';import { Button } from '@/components/ui/button';@@ -30,32 +24,6 @@ import {} from '@/components/ui/attachment';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';-function formatSize(bytes: number): string {- if (bytes < 1024) return `${bytes} B`;- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;-}--// The card's leading thumbnail: images and videos preview themselves, every-// other type falls back to a generic file glyph.-function AttachmentThumb({ a }: { a: Attachment }) {- if (isImage(a))- return (- <Image- src={a.url}- alt={a.filename}- fill- // The thumbnail is w-10 (40px) in every card size used here.- sizes="40px"- draggable={false}- className="object-cover"- />- );- if (isVideo(a))- return <video src={a.url} className="size-full object-cover" muted draggable={false} />;- return <FileIcon className="text-muted-foreground" />;-}-function onDragStart(e: DragEvent<HTMLElement>, a: Attachment) {e.dataTransfer.setData('text/html', attachmentHtml(a));e.dataTransfer.setData('text/plain', a.url);@@ -81,11 +49,7 @@ export default function IssueAttachmentsPanel({const deleteAttachment = useDeleteAttachment(issueId);const limits = useStorageSettingsQuery().data;const [error, setError] = useState<string | null>(null);- const [dropActive, setDropActive] = useState(false);const fileInput = useRef<HTMLInputElement>(null);- // dragenter/dragleave fire for every child; count them so the overlay only- // clears when the pointer actually leaves the panel.- const dragDepth = useRef(0);const uploading = uploadAttachment.isPending;@@ -110,47 +74,10 @@ export default function IssueAttachmentsPanel({}}- // Only external files trigger the upload drop zone; dragging an attachment- // card (which carries text/html, not Files) must not.- const isFileDrag = (e: DragEvent) => e.dataTransfer.types.includes('Files');-- function onDragEnter(e: DragEvent) {- if (!isFileDrag(e)) return;- dragDepth.current += 1;- setDropActive(true);- }-- function onDragOver(e: DragEvent) {- if (!isFileDrag(e)) return;- e.preventDefault();- e.dataTransfer.dropEffect = 'copy';- }-- function onDragLeave(e: DragEvent) {- if (!isFileDrag(e)) return;- dragDepth.current -= 1;- if (dragDepth.current <= 0) {- dragDepth.current = 0;- setDropActive(false);- }- }-- function onDrop(e: DragEvent) {- if (!isFileDrag(e)) return;- e.preventDefault();- dragDepth.current = 0;- setDropActive(false);- void onFilesPicked(e.dataTransfer.files);- }+ const { draggedFiles, dragHandlers } = useFileDragZone((files) => void onFilesPicked(files));return (- <div- className="relative mt-6 border-t pt-5"- onDragEnter={onDragEnter}- onDragOver={onDragOver}- onDragLeave={onDragLeave}- onDrop={onDrop}- >+ <div className="relative mt-6 border-t pt-5" {...dragHandlers}><div className="mb-3 flex items-center justify-between"><h3 className="flex items-center gap-1.5 text-xs font-medium tracking-wide text-muted-foreground uppercase"><Paperclip className="size-3.5" />@@ -210,7 +137,7 @@ export default function IssueAttachmentsPanel({</span><AttachmentMedia variant={isImage(a) || isVideo(a) ? 'image' : 'icon'}>- <AttachmentThumb a={a} />+ <IssueAttachmentThumb attachment={a} /></AttachmentMedia><AttachmentContent>@@ -250,7 +177,7 @@ export default function IssueAttachmentsPanel({</div>)}- {dropActive && (+ {draggedFiles !== null && (<div className="pointer-events-none absolute inset-0 top-5 z-30 flex flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed border-primary bg-background/80 text-primary backdrop-blur-sm"><Download className="size-6" /><span className="text-sm font-medium">Drop files to upload</span>diff --git a/apps/web/src/features/issue/hooks/useFileDragZone.ts b/apps/web/src/features/issue/hooks/useFileDragZone.tsnew file mode 100644index 00000000..864b568a--- /dev/null+++ b/apps/web/src/features/issue/hooks/useFileDragZone.ts@@ -0,0 +1,48 @@+import { useRef, useState, type DragEvent } from 'react';++// Drag-and-drop of external files onto an element. `draggedFiles` is the number+// of files currently dragged over it, or null when nothing is; spread+// `dragHandlers` onto the element. dragenter/dragleave fire for every child, so+// they are counted and the state only clears when the pointer leaves the zone.+export function useFileDragZone(onFiles: (files: FileList) => void) {+ const [draggedFiles, setDraggedFiles] = useState<number | null>(null);+ const depth = useRef(0);++ // Only external files count; dragging a card inside the zone (which carries+ // text/html, not Files) must not open the drop zone.+ const isFileDrag = (e: DragEvent) => e.dataTransfer.types.includes('Files');++ const dragHandlers = {+ onDragEnter(e: DragEvent) {+ if (!isFileDrag(e)) return;+ depth.current += 1;+ setDraggedFiles(Array.from(e.dataTransfer.items).filter((i) => i.kind === 'file').length);+ },+ onDragOver(e: DragEvent) {+ if (!isFileDrag(e)) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = 'copy';+ },+ onDragLeave(e: DragEvent) {+ if (!isFileDrag(e)) return;+ depth.current -= 1;+ if (depth.current <= 0) {+ depth.current = 0;+ setDraggedFiles(null);+ }+ },+ onDrop(e: DragEvent) {+ depth.current = 0;+ setDraggedFiles(null);+ // A drop onto a markdown editor inside the zone is already handled by+ // tiptap, which calls preventDefault.+ if (e.defaultPrevented || !isFileDrag(e)) return;+ const files = e.dataTransfer.files;+ if (files.length === 0) return;+ e.preventDefault();+ onFiles(files);+ },+ };++ return { draggedFiles, dragHandlers };+}diff --git a/apps/web/src/features/issue/hooks/useNewIssueAttachments.ts b/apps/web/src/features/issue/hooks/useNewIssueAttachments.tsnew file mode 100644index 00000000..f458dd5c--- /dev/null+++ b/apps/web/src/features/issue/hooks/useNewIssueAttachments.ts@@ -0,0 +1,84 @@+import { useEffect, useRef, useState } from 'react';+import { useStorageSettingsQuery } from '@/services/storage.service';+import { attachmentError } from '@/utils/uploadLimits';+import { useUploadAttachment } from '../services/attachments.service';+import { type Embeddable } from '../utils/attachmentEmbed';++export type PendingAttachment = Embeddable & { id: number; file: File };++// Files attached to an issue that does not exist yet. An upload needs an issue+// id, so every file waits here until the issue is created and is uploaded then.+// Until that happens a file is served from a local blob: URL, which is what the+// list previews and what an embed in the description points at; uploadAll+// returns the stored URL to rewrite each embed to.+export function useNewIssueAttachments() {+ const limits = useStorageSettingsQuery().data;+ const uploadAttachment = useUploadAttachment();+ const [pending, setPending] = useState<PendingAttachment[]>([]);+ const [error, setError] = useState<string | null>(null);+ const nextId = useRef(0);+ const blobUrls = useRef<string[]>([]);+ const removedUrls = useRef<string[]>([]);++ useEffect(() => {+ const urls = blobUrls.current;+ return () => {+ for (const url of urls) URL.revokeObjectURL(url);+ };+ }, []);++ // Null when the file is refused; the reason is then in `error`.+ function add(file: File): PendingAttachment | null {+ // The api enforces the same limits; checking here avoids holding a file+ // that is going to be refused on submit.+ const reason = attachmentError(file, limits);+ if (reason) {+ setError(reason);+ return null;+ }+ setError(null);+ const url = URL.createObjectURL(file);+ blobUrls.current.push(url);+ const item = { id: nextId.current++, file, url, contentType: file.type, filename: file.name };+ setPending((prev) => [...prev, item]);+ return item;+ }++ function attach(files: FileList | null) {+ if (!files) return;+ for (const file of Array.from(files)) add(file);+ }++ // Handed to the markdown editors as their uploadFile: the file is attached and+ // the editor embeds the returned blob: URL at the cursor.+ async function uploadFile(file: File): Promise<Embeddable> {+ const item = add(file);+ if (!item) throw new Error('File refused');+ return item;+ }++ // Returns the removed attachment, so the caller can drop its embeds too.+ function remove(id: number): PendingAttachment | null {+ const item = pending.find((p) => p.id === id);+ if (!item) return null;+ removedUrls.current.push(item.url);+ setPending((prev) => prev.filter((p) => p.id !== id));+ return item;+ }++ // Uploads every pending file to the freshly created issue and returns each+ // blob: URL mapped to its stored URL. A removed file, and one whose upload+ // failed, maps to an empty string: its embed is stripped instead of rewritten.+ async function uploadAll(issueId: number): Promise<Map<string, string>> {+ const urls = new Map<string, string>(removedUrls.current.map((url) => [url, '']));+ for (const item of pending) {+ const uploaded = await uploadAttachment+ .mutateAsync({ issueId, file: item.file })+ .catch(() => null);+ urls.set(item.url, uploaded ? uploaded.url : '');+ }+ return urls;+ }++ return { pending, error, attach, uploadFile, remove, uploadAll };+}diff --git a/apps/web/src/features/issue/utils/attachmentEmbed.ts b/apps/web/src/features/issue/utils/attachmentEmbed.tsindex cdc3e0d8..2dea5cdf 100644--- a/apps/web/src/features/issue/utils/attachmentEmbed.ts+++ b/apps/web/src/features/issue/utils/attachmentEmbed.ts@@ -1,3 +1,5 @@+import { type Editor } from '@tiptap/react';+// Embedding an attachment into a description. Both a stored Attachment and a// fresh upload response satisfy this shape.export type Embeddable = { url: string; contentType: string; filename: string };@@ -23,3 +25,27 @@ export function attachmentMarkdown(a: Embeddable): string {if (isVideo(a)) return `<video src="${a.url}" controls></video>`;return `[${a.filename}](${a.url})`;}++// Drops the embeds of `url` from markdown text: a markdown image or link, plus+// the raw <img>/<video> tags a sized image and a video serialize to. Used on a+// URL that never became an attachment, so no dead link is stored.+export function stripEmbed(markdown: string, url: string): string {+ const quoted = url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return markdown+ .replace(new RegExp(`!?\\[[^\\]]*\\]\\(${quoted}\\)`, 'g'), '')+ .replace(new RegExp(`<img\\b[^>]*src="${quoted}"[^>]*>`, 'g'), '')+ .replace(new RegExp(`<video[^>]*src="${quoted}"[^>]*>\\s*</video>`, 'g'), '');+}++// The same removal on a live editor: the image or video node carrying `url` as+// src, and a link pointing at it.+export function removeEmbed(editor: Editor, url: string) {+ if (editor.isDestroyed) return;+ const { tr, doc } = editor.state;+ doc.descendants((node, pos) => {+ if (node.attrs.src !== url && !node.marks.some((m) => m.attrs.href === url)) return;+ tr.delete(tr.mapping.map(pos), tr.mapping.map(pos + node.nodeSize));+ return false;+ });+ if (tr.docChanged) editor.view.dispatch(tr);+}diff --git a/apps/web/src/features/issue/utils/fileSize.ts b/apps/web/src/features/issue/utils/fileSize.tsnew file mode 100644index 00000000..d6372d0d--- /dev/null+++ b/apps/web/src/features/issue/utils/fileSize.ts@@ -0,0 +1,5 @@+export function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+}