Skip to content

⭐️⭐️⭐️ 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.

feat(web): paste and drop images into issue text (#17)

Crofff80be446a719
diff --git a/apps/api/src/attachments/routes.ts b/apps/api/src/attachments/routes.ts
index 8a42dd17..660915f1 100644
--- a/apps/api/src/attachments/routes.ts
+++ b/apps/api/src/attachments/routes.ts
@@ -15,6 +15,7 @@ import {
listAttachments,
getAttachmentByPublicId,
deleteAttachmentByPublicId,
+ removeAttachmentEmbeds,
getProjectAttachmentBytes,
type AttachmentRow,
} from './store';
@@ -274,6 +275,9 @@ export const attachmentRoutes = new Elysia({
async ({ params }) => {
const row = await deleteAttachmentByPublicId(params.publicId);
if (!row) throw new HttpError(404, 'Attachment not found');
+ // Strip any embed of this attachment from the issue description and its
+ // markdown field values, so no broken image is left behind.
+ await removeAttachmentEmbeds(row.issueId, row.publicId);
// Row is already gone; a failed object delete only orphans bytes, so don't
// fail the request over it.
await deleteObject(row.s3Key).catch((err) => {
diff --git a/apps/api/src/attachments/store.ts b/apps/api/src/attachments/store.ts
index ca131d77..e3db3a9d 100644
--- a/apps/api/src/attachments/store.ts
+++ b/apps/api/src/attachments/store.ts
@@ -1,4 +1,4 @@
-import { db, issue, issueAttachment } from '@repo/db';
+import { db, issue, issueAttachment, issueFieldValue } from '@repo/db';
import { eq, sql } from 'drizzle-orm';
import { iso, num } from '../shared/lib';
@@ -87,3 +87,59 @@ export async function deleteAttachmentByPublicId(publicId: string): Promise<Atta
.returning();
return rows[0] ? mapAttachment(rows[0]) : null;
}
+
+// An embed of a deleted attachment left in markdown would 404 once the object is
+// gone (or, worse, keep showing from the year-long immutable cache on the raw
+// route). Strip any construct whose URL carries this attachment's publicId: a
+// markdown image/link, or an inline <img>/<video>. The publicId is a uuid, so a
+// URL substring match is specific to this one attachment.
+function stripEmbeds(text: string, publicId: string): string {
+ const id = publicId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return text
+ .replace(new RegExp(`!?\\[[^\\]]*\\]\\([^)]*${id}[^)]*\\)`, 'g'), '')
+ .replace(new RegExp(`<img\\b[^>]*${id}[^>]*>`, 'g'), '')
+ .replace(new RegExp(`<video\\b[^>]*${id}[^>]*>(?:\\s*</video>)?`, 'g'), '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+// Remove embeds of one attachment from the issue description and its markdown
+// custom field values. Called on delete so a removed attachment leaves no broken
+// image behind.
+export async function removeAttachmentEmbeds(issueId: number, publicId: string): Promise<void> {
+ let changed = false;
+
+ const [row] = await db
+ .select({ description: issue.description })
+ .from(issue)
+ .where(eq(issue.id, issueId));
+ if (row) {
+ const next = stripEmbeds(row.description, publicId);
+ if (next !== row.description) {
+ await db.update(issue).set({ description: next }).where(eq(issue.id, issueId));
+ changed = true;
+ }
+ }
+
+ const values = await db
+ .select({ id: issueFieldValue.id, valueText: issueFieldValue.valueText })
+ .from(issueFieldValue)
+ .where(eq(issueFieldValue.issueId, issueId));
+ for (const v of values) {
+ if (v.valueText == null) continue;
+ const next = stripEmbeds(v.valueText, publicId);
+ if (next !== v.valueText) {
+ await db.update(issueFieldValue).set({ valueText: next }).where(eq(issueFieldValue.id, v.id));
+ changed = true;
+ }
+ }
+
+ // issueRev is derived from issue.updatedAt; bump it so an open detail view
+ // refetches the cleaned description and field values.
+ if (changed) {
+ await db
+ .update(issue)
+ .set({ updatedAt: sql`now()` })
+ .where(eq(issue.id, issueId));
+ }
+}
diff --git a/apps/web/src/features/issue/components/create/NewIssueModal.tsx b/apps/web/src/features/issue/components/create/NewIssueModal.tsx
index 8712e234..e4078746 100644
--- a/apps/web/src/features/issue/components/create/NewIssueModal.tsx
+++ b/apps/web/src/features/issue/components/create/NewIssueModal.tsx
@@ -1,10 +1,13 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState, type DragEvent } from 'react';
+import { type Editor } from '@tiptap/react';
import { MoreHorizontal } from 'lucide-react';
import { type IssueFieldValueInput, type ProjectDetail } from '@/lib/api';
import { type NewIssueDefaults } from '@/utils/project';
import { useSession } from '@/lib/auth-client';
-import { useCreateIssue, useSetFieldValue } from '@/services/issues.service';
+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 IssueCustomFieldPill from '../fields/IssueCustomFieldPill';
import Modal from '@/components/common/overlay/Modal';
import IssueMarkdownEditor from '../editor/IssueMarkdownEditor';
@@ -79,7 +82,60 @@ export default function NewIssueModal({
const [justAddedId, setJustAddedId] = useState<number | null>(null);
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);
+ };
+ }, []);
+
+ // 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.
+ const [descEditor, setDescEditor] = useState<Editor | null>(null);
+
+ const dropFilesIntoDescription = (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;
+ 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 [addFieldOpen, setAddFieldOpen] = useState(false);
@@ -124,6 +180,25 @@ 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() } });
+ }
+ }
+
// Set custom field values on the freshly created issue. Body fields are
// always applicable; property fields only if the user added them.
for (const def of fieldDefs) {
@@ -144,7 +219,7 @@ export default function NewIssueModal({
return (
<Modal title="New issue" projectKey={project.project.key} onClose={onClose} wide>
- <div>
+ <div onDragOver={onModalDragOver} onDrop={onModalDrop}>
<input
className="w-full bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground"
placeholder="Issue title"
@@ -156,6 +231,8 @@ export default function NewIssueModal({
className={`mt-3 ${bodyDefs.length > 0 ? 'min-h-14' : 'min-h-24'}`}
defaultValue={description}
onChange={setDescription}
+ onReady={setDescEditor}
+ uploadFile={uploadFile}
/>
{bodyDefs.length > 0 && (
diff --git a/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx b/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
index 22546835..f4b6cc51 100644
--- a/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
+++ b/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
@@ -78,6 +78,21 @@ export default function IssueMarkdownEditor({
uploadFile?: (file: File) => Promise<{ url: string; contentType: string; filename: string }>;
}) {
const editorRef = useRef<Editor | null>(null);
+
+ // Upload each file and insert it (image/video inline, other files as a link)
+ // starting at `pos`, advancing past each insertion. Shared by drop and paste.
+ const insertFiles = (files: FileList, pos: number) => {
+ void (async () => {
+ for (const file of Array.from(files)) {
+ const a = await uploadFile?.(file).catch(() => null);
+ const ed = editorRef.current;
+ if (!a || !ed) continue;
+ ed.chain().insertContentAt(pos, attachmentHtml(a)).focus().run();
+ pos = ed.state.selection.to;
+ }
+ })();
+ };
+
const editor = useEditor({
editable,
extensions: [
@@ -117,16 +132,18 @@ export default function IssueMarkdownEditor({
if (!files || files.length === 0) return false;
event.preventDefault();
const coords = view.posAtCoords({ left: event.clientX, top: event.clientY });
- let pos = coords?.pos ?? view.state.selection.to;
- void (async () => {
- for (const file of Array.from(files)) {
- const a = await uploadFile(file).catch(() => null);
- const ed = editorRef.current;
- if (!a || !ed) continue;
- ed.chain().insertContentAt(pos, attachmentHtml(a)).focus().run();
- pos = ed.state.selection.to;
- }
- })();
+ insertFiles(files, coords?.pos ?? view.state.selection.to);
+ return true;
+ },
+ // A pasted screenshot or copied file arrives as clipboard files: upload
+ // each and insert at the cursor, same as a drop. Plain text/html pastes
+ // carry no files and fall through to tiptap's default handling.
+ handlePaste(view, event) {
+ if (!uploadFile) return false;
+ const files = event.clipboardData?.files;
+ if (!files || files.length === 0) return false;
+ event.preventDefault();
+ insertFiles(files, view.state.selection.to);
return true;
},
},
diff --git a/apps/web/src/features/issue/services/attachments.service.ts b/apps/web/src/features/issue/services/attachments.service.ts
index d78ff42a..2549cf75 100644
--- a/apps/web/src/features/issue/services/attachments.service.ts
+++ b/apps/web/src/features/issue/services/attachments.service.ts
@@ -23,6 +23,11 @@ export function useDeleteAttachment(issueId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (publicId: string) => api.deleteAttachment(publicId),
- onSuccess: () => void qc.invalidateQueries({ queryKey: qk.attachments(issueId) }),
+ // Deleting also strips the attachment's embeds from the description and
+ // markdown field values, so refetch the issue alongside the panel list.
+ onSuccess: () => {
+ void qc.invalidateQueries({ queryKey: qk.attachments(issueId) });
+ void qc.invalidateQueries({ queryKey: qk.issue(issueId) });
+ },
});
}