Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat: add image upload functionality to task descriptions and comments

Andrej33f69409f00d
diff --git a/apps/api/package.json b/apps/api/package.json
index 3d33596a4..b13e38acb 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -22,6 +22,8 @@
"db:seed:user-data": "tsx scripts/seed-user-data.ts"
},
"dependencies": {
+ "@aws-sdk/client-s3": "^3.1006.0",
+ "@aws-sdk/s3-request-presigner": "^3.1006.0",
"@better-auth/api-key": "^1.5.4",
"@better-auth/drizzle-adapter": "^1.5.4",
"@hono/node-server": "^1.19.10",
diff --git a/apps/api/src/storage/s3.ts b/apps/api/src/storage/s3.ts
new file mode 100644
index 000000000..30f09eb00
--- /dev/null
+++ b/apps/api/src/storage/s3.ts
@@ -0,0 +1,268 @@
+import {
+ PutObjectCommand,
+ S3Client,
+ type S3ClientConfig,
+} from "@aws-sdk/client-s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+import { createId } from "@paralleldrive/cuid2";
+import { config } from "dotenv-mono";
+
+config();
+
+const DEFAULT_MAX_IMAGE_UPLOAD_BYTES = 10 * 1024 * 1024;
+const DEFAULT_PRESIGN_TTL_SECONDS = 300;
+
+const allowedImageMimeTypes = new Set([
+ "image/apng",
+ "image/avif",
+ "image/gif",
+ "image/heic",
+ "image/heif",
+ "image/jpeg",
+ "image/jpg",
+ "image/png",
+ "image/svg+xml",
+ "image/webp",
+]);
+
+type UploadSurface = "description" | "comment";
+
+type StorageConfig = {
+ endpoint: string;
+ region: string;
+ bucket: string;
+ accessKeyId: string;
+ secretAccessKey: string;
+ publicBaseUrl?: string;
+ forcePathStyle: boolean;
+ maxImageUploadBytes: number;
+ presignTtlSeconds: number;
+};
+
+type TaskImageUploadContext = {
+ workspaceId: string;
+ projectId: string;
+ taskId: string;
+ surface: UploadSurface;
+ filename: string;
+ contentType: string;
+};
+
+type TaskImageUploadUrl = {
+ key: string;
+ uploadUrl: string;
+ headers: Record<string, string>;
+ assetUrl: string;
+};
+
+let clientCache:
+ | {
+ cacheKey: string;
+ client: S3Client;
+ }
+ | undefined;
+
+function env(name: string) {
+ return process.env[name]?.trim() || "";
+}
+
+function parseBoolean(value: string | undefined, fallback: boolean) {
+ if (value === undefined || value.trim() === "") return fallback;
+ return value.trim().toLowerCase() === "true";
+}
+
+function parsePositiveInt(value: string | undefined, fallback: number) {
+ const parsed = Number.parseInt(value?.trim() || "", 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
+ return parsed;
+}
+
+function getStorageConfig(): StorageConfig {
+ const endpoint = env("S3_ENDPOINT");
+ const bucket = env("S3_BUCKET");
+ const accessKeyId = env("S3_ACCESS_KEY_ID");
+ const secretAccessKey = env("S3_SECRET_ACCESS_KEY");
+
+ if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {
+ throw new Error(
+ "S3 uploads are not configured. Set S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY.",
+ );
+ }
+
+ return {
+ endpoint,
+ region: env("S3_REGION") || "us-east-1",
+ bucket,
+ accessKeyId,
+ secretAccessKey,
+ publicBaseUrl: env("S3_PUBLIC_BASE_URL") || undefined,
+ forcePathStyle: parseBoolean(process.env.S3_FORCE_PATH_STYLE, true),
+ maxImageUploadBytes: parsePositiveInt(
+ process.env.S3_MAX_IMAGE_UPLOAD_BYTES,
+ DEFAULT_MAX_IMAGE_UPLOAD_BYTES,
+ ),
+ presignTtlSeconds: parsePositiveInt(
+ process.env.S3_PRESIGN_TTL_SECONDS,
+ DEFAULT_PRESIGN_TTL_SECONDS,
+ ),
+ };
+}
+
+function getMaxImageUploadBytes() {
+ return parsePositiveInt(
+ process.env.S3_MAX_IMAGE_UPLOAD_BYTES,
+ DEFAULT_MAX_IMAGE_UPLOAD_BYTES,
+ );
+}
+
+function getClient(config: StorageConfig) {
+ const cacheKey = JSON.stringify({
+ endpoint: config.endpoint,
+ region: config.region,
+ accessKeyId: config.accessKeyId,
+ bucket: config.bucket,
+ forcePathStyle: config.forcePathStyle,
+ });
+
+ if (clientCache?.cacheKey === cacheKey) {
+ return clientCache.client;
+ }
+
+ const clientConfig: S3ClientConfig = {
+ endpoint: config.endpoint,
+ region: config.region,
+ forcePathStyle: config.forcePathStyle,
+ credentials: {
+ accessKeyId: config.accessKeyId,
+ secretAccessKey: config.secretAccessKey,
+ },
+ };
+
+ const client = new S3Client(clientConfig);
+ clientCache = { cacheKey, client };
+ return client;
+}
+
+function sanitizePathSegment(value: string) {
+ return (
+ value
+ .toLowerCase()
+ .replace(/[^a-z0-9._-]+/g, "-")
+ .replace(/-{2,}/g, "-")
+ .replace(/^-+|-+$/g, "") || "file"
+ );
+}
+
+function getFileExtension(filename: string) {
+ const normalized = filename.trim();
+ const extension = normalized.includes(".")
+ ? normalized.split(".").pop() || ""
+ : "";
+
+ return sanitizePathSegment(extension).slice(0, 12);
+}
+
+function encodeKeyPath(key: string) {
+ return key
+ .split("/")
+ .map((segment) => encodeURIComponent(segment))
+ .join("/");
+}
+
+function buildAssetUrl(config: StorageConfig, key: string) {
+ const encodedKey = encodeKeyPath(key);
+
+ if (config.publicBaseUrl) {
+ return new URL(
+ encodedKey,
+ `${config.publicBaseUrl.replace(/\/+$/, "")}/`,
+ ).toString();
+ }
+
+ const endpoint = new URL(config.endpoint);
+
+ if (config.forcePathStyle) {
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/, "")}/${config.bucket}/${encodedKey}`;
+ return endpoint.toString();
+ }
+
+ endpoint.hostname = `${config.bucket}.${endpoint.hostname}`;
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/, "")}/${encodedKey}`;
+ return endpoint.toString();
+}
+
+function buildObjectKey(context: TaskImageUploadContext) {
+ const extension = getFileExtension(context.filename);
+ const surfaceFolder =
+ context.surface === "comment" ? "comments" : "descriptions";
+ const timestamp = Date.now();
+ const randomId = createId();
+
+ const baseName = sanitizePathSegment(
+ context.filename.replace(/\.[^/.]+$/, "") || "image",
+ ).slice(0, 64);
+
+ const fileName = extension
+ ? `${baseName}-${timestamp}-${randomId}.${extension}`
+ : `${baseName}-${timestamp}-${randomId}`;
+
+ return [
+ "workspace",
+ sanitizePathSegment(context.workspaceId),
+ "project",
+ sanitizePathSegment(context.projectId),
+ "task",
+ sanitizePathSegment(context.taskId),
+ surfaceFolder,
+ fileName,
+ ].join("/");
+}
+
+export function validateImageUploadInput(contentType: string, size: number) {
+ const maxImageUploadBytes = getMaxImageUploadBytes();
+
+ if (!allowedImageMimeTypes.has(contentType.toLowerCase())) {
+ throw new Error("Only image uploads are supported.");
+ }
+
+ if (size <= 0) {
+ throw new Error("Image upload size must be greater than zero.");
+ }
+
+ if (size > maxImageUploadBytes) {
+ throw new Error(
+ `Image exceeds the maximum upload size of ${Math.floor(maxImageUploadBytes / (1024 * 1024))}MB.`,
+ );
+ }
+}
+
+export async function createTaskImageUploadUrl(
+ context: TaskImageUploadContext,
+): Promise<TaskImageUploadUrl> {
+ const config = getStorageConfig();
+ const client = getClient(config);
+ const key = buildObjectKey(context);
+
+ const command = new PutObjectCommand({
+ Bucket: config.bucket,
+ Key: key,
+ ContentType: context.contentType,
+ });
+
+ const uploadUrl = await getSignedUrl(client, command, {
+ expiresIn: config.presignTtlSeconds,
+ });
+
+ return {
+ key,
+ uploadUrl,
+ headers: {
+ "Content-Type": context.contentType,
+ },
+ assetUrl: buildAssetUrl(config, key),
+ };
+}
+
+export function assertStorageConfigured() {
+ return getStorageConfig();
+}
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index 8f7825ed8..aa3d35844 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -4,9 +4,18 @@ import { HTTPException } from "hono/http-exception";
import { describeRoute, resolver, validator } from "hono-openapi";
import * as v from "valibot";
import db from "../database";
-import { taskTable, userTable } from "../database/schema";
+import {
+ projectTable,
+ taskTable,
+ userTable,
+ workspaceTable,
+} from "../database/schema";
import { publishEvent } from "../events";
import { taskSchema } from "../schemas";
+import {
+ createTaskImageUploadUrl,
+ validateImageUploadInput,
+} from "../storage/s3";
import { workspaceAccess } from "../utils/workspace-access-middleware";
import createTask from "./controllers/create-task";
import deleteTask from "./controllers/delete-task";
@@ -507,6 +516,88 @@ const task = new Hono<{
},
)
+ .put(
+ "/image-upload/:id",
+ describeRoute({
+ operationId: "createTaskImageUpload",
+ tags: ["Tasks"],
+ description:
+ "Create a presigned image upload URL for a task description or comment",
+ responses: {
+ 200: {
+ description: "Image upload URL created successfully",
+ content: {
+ "application/json": { schema: resolver(v.any()) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ validator(
+ "json",
+ v.object({
+ filename: v.string(),
+ contentType: v.string(),
+ size: v.number(),
+ surface: v.picklist(["description", "comment"] as const),
+ }),
+ ),
+ workspaceAccess.fromTask(),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const { filename, contentType, size, surface } = c.req.valid("json");
+
+ try {
+ validateImageUploadInput(contentType, size);
+ } catch (error) {
+ throw new HTTPException(400, {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Invalid image upload request",
+ });
+ }
+
+ const [taskContext] = await db
+ .select({
+ taskId: taskTable.id,
+ projectId: taskTable.projectId,
+ workspaceId: workspaceTable.id,
+ })
+ .from(taskTable)
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .innerJoin(
+ workspaceTable,
+ eq(projectTable.workspaceId, workspaceTable.id),
+ )
+ .where(eq(taskTable.id, id))
+ .limit(1);
+
+ if (!taskContext) {
+ throw new HTTPException(404, { message: "Task not found" });
+ }
+
+ try {
+ const upload = await createTaskImageUploadUrl({
+ workspaceId: taskContext.workspaceId,
+ projectId: taskContext.projectId,
+ taskId: taskContext.taskId,
+ surface,
+ filename,
+ contentType,
+ });
+
+ return c.json(upload);
+ } catch (error) {
+ throw new HTTPException(503, {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Image uploads are not configured",
+ });
+ }
+ },
+ )
.put(
"/description/:id",
describeRoute({
diff --git a/apps/docs/core/installation/docker-compose.mdx b/apps/docs/core/installation/docker-compose.mdx
index 2c3b2eafb..1df4b3991 100644
--- a/apps/docs/core/installation/docker-compose.mdx
+++ b/apps/docs/core/installation/docker-compose.mdx
@@ -61,4 +61,63 @@ Additionally, the following volumes are used:
- `postgres_data`: The PostgreSQL data.
-After creating the compose file, the next step is to set up the environment variables.
\ No newline at end of file
+## Notes on object storage
+
+Kaneo uses S3-compatible object storage for image uploads in task descriptions and comments.
+
+- Object storage is optional. Kaneo runs without it, but image uploads in task descriptions and comments will be unavailable.
+- For local/self-hosted setups, MinIO is the recommended option when you want uploads.
+- The Kaneo API creates presigned upload URLs and the browser uploads images directly to the configured storage backend.
+- If you do not configure object storage, leave the `S3_*` variables unset.
+
+### Optional MinIO service
+
+Add this service and volume to your `compose.yml` only if you want image uploads:
+
+```yml
+services:
+ minio:
+ image: minio/minio:latest
+ command: server /data --console-address ":9001"
+ env_file:
+ - .env
+ ports:
+ - "9000:9000"
+ - "9001:9001"
+ volumes:
+ - minio_data:/data
+ restart: unless-stopped
+
+volumes:
+ minio_data:
+```
+
+Set the matching `S3_*` environment variables in your `.env` file. See the [environment variables page](/core/installation/environment-variables).
+
+### Example `.env` values for MinIO
+
+```env
+MINIO_ROOT_USER=minioadmin
+MINIO_ROOT_PASSWORD=minioadmin
+
+S3_ENDPOINT=http://minio:9000
+S3_BUCKET=kaneo-uploads
+S3_ACCESS_KEY_ID=minioadmin
+S3_SECRET_ACCESS_KEY=minioadmin
+S3_REGION=us-east-1
+S3_FORCE_PATH_STYLE=true
+```
+
+Create the bucket before testing uploads. With MinIO, you can do that from the MinIO Console at `http://localhost:9001`.
+
+### Using `fs` instead of MinIO
+
+If you want to use [`fs`](https://github.com/ferdzo/fs), you can point the same `S3_*` variables at its endpoint instead of MinIO. Kaneo only needs an S3-compatible API endpoint, credentials, and a bucket.
+
+When using `fs`, keep these differences in mind:
+
+- Set `S3_FORCE_PATH_STYLE=true`.
+- Create buckets through the S3 API or CLI, not through a web console.
+- Browser uploads may require reverse-proxy CORS handling, because `fs` does not currently implement S3 CORS APIs.
+
+After creating the compose file, the next step is to set up the environment variables.
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index 9560097dd..4d8ce5737 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -13,6 +13,7 @@ The variables are split up into the following sections:
- [General URLs](#general-urls)
- [Database](#database)
- [Authentication](#authentication)
+- [Object Storage](#object-storage)
- [Access Control](#access-control)
- [GitHub SSO & Integration](#github-sso-&-integration)
- [Google SSO](#google-sso)
@@ -53,6 +54,24 @@ Name | Description |
## Optional variables
+### Object Storage
+
+Kaneo uses S3-compatible object storage for image uploads in task descriptions and task comments.
+
+MinIO is the easiest local option and the primary tested target. You can also use other S3-compatible storage backends such as AWS S3, Cloudflare R2, or [`fs`](https://github.com/ferdzo/fs).
+
+Name | Description | Default |
+--- | --- | --- |
+| `S3_ENDPOINT` | The S3-compatible API endpoint used by the Kaneo API for presigned uploads. Example: `http://minio:9000`. | |
+| `S3_BUCKET` | The bucket Kaneo will use for uploaded images. | |
+| `S3_ACCESS_KEY_ID` | Access key used by the Kaneo API to create presigned upload URLs. | |
+| `S3_SECRET_ACCESS_KEY` | Secret key used by the Kaneo API to create presigned upload URLs. | |
+| `S3_REGION` | The storage region used for request signing. | `us-east-1` |
+| `S3_PUBLIC_BASE_URL` | Optional public base URL for uploaded assets. Use this when objects should be served from a public hostname or reverse proxy instead of the raw API endpoint. | |
+| `S3_FORCE_PATH_STYLE` | Use path-style S3 URLs. This should usually be `true` for MinIO and `fs`. | `true` |
+| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed image upload size in bytes. | `10485760` |
+| `S3_PRESIGN_TTL_SECONDS` | How long presigned upload URLs remain valid. | `300` |
+
### Access Control
Name | Description | Default |
diff --git a/apps/docs/core/installation/object-storage-and-image-uploads.mdx b/apps/docs/core/installation/object-storage-and-image-uploads.mdx
new file mode 100644
index 000000000..6ad535578
--- /dev/null
+++ b/apps/docs/core/installation/object-storage-and-image-uploads.mdx
@@ -0,0 +1,111 @@
+---
+title: Object storage and image uploads
+description: Configure S3-compatible storage for task description and comment image uploads.
+---
+
+## Overview
+
+Kaneo supports image uploads in task descriptions and task comments.
+
+Uploads use an S3-compatible object storage backend:
+
+- the Kaneo API creates presigned upload URLs
+- the browser uploads images directly to the storage backend
+- Kaneo stores the final image URLs inside the task or comment content
+
+This means Kaneo can work with multiple backends as long as they expose a compatible S3-style API.
+
+## Recommended local setup: MinIO
+
+For local or self-hosted deployments, MinIO is the recommended storage backend.
+
+It gives you:
+
+- a stable S3-compatible API
+- a web console for bucket management
+- a simple Docker setup
+- better compatibility for direct browser uploads
+
+Example `.env` values:
+
+```env
+MINIO_ROOT_USER=minioadmin
+MINIO_ROOT_PASSWORD=minioadmin
+
+S3_ENDPOINT=http://minio:9000
+S3_BUCKET=kaneo-uploads
+S3_ACCESS_KEY_ID=minioadmin
+S3_SECRET_ACCESS_KEY=minioadmin
+S3_REGION=us-east-1
+S3_FORCE_PATH_STYLE=true
+```
+
+Create the bucket before using uploads.
+
+## Other S3-compatible backends
+
+Kaneo is not tied to MinIO. Any deployment can point Kaneo at another S3-compatible backend by changing the `S3_*` environment variables.
+
+Examples:
+
+- AWS S3
+- Cloudflare R2
+- MinIO
+- [`fs`](https://github.com/ferdzo/fs)
+
+## Using `fs`
+
+`fs` is another S3-compatible option if you want a lightweight local object store. It is built by friends of Kaneo.
+
+When using `fs`, configure Kaneo like this:
+
+```env
+S3_ENDPOINT=http://fs:2600
+S3_BUCKET=kaneo-uploads
+S3_ACCESS_KEY_ID=<your-access-key>
+S3_SECRET_ACCESS_KEY=<your-secret-key>
+S3_REGION=us-east-1
+S3_FORCE_PATH_STYLE=true
+```
+
+Important notes for `fs`:
+
+- buckets are created through the S3 API or CLI, not through a web dashboard
+- Kaneo still expects the bucket to exist before uploads start
+- direct browser uploads may need reverse-proxy CORS headers, because `fs` does not currently implement S3 CORS APIs
+
+## Required Kaneo storage variables
+
+Set these in your Kaneo deployment:
+
+| Name | Description |
+| --- | --- |
+| `S3_ENDPOINT` | S3-compatible API endpoint used by Kaneo |
+| `S3_BUCKET` | Bucket used for uploaded images |
+| `S3_ACCESS_KEY_ID` | Access key used to create presigned upload URLs |
+| `S3_SECRET_ACCESS_KEY` | Secret key used to create presigned upload URLs |
+| `S3_REGION` | Region used for signing |
+| `S3_FORCE_PATH_STYLE` | Usually `true` for MinIO and `fs` |
+
+Optional:
+
+| Name | Description |
+| --- | --- |
+| `S3_PUBLIC_BASE_URL` | Public URL used for serving uploaded assets |
+| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed image size |
+| `S3_PRESIGN_TTL_SECONDS` | Presigned upload URL lifetime |
+
+## Testing uploads
+
+Once storage is configured:
+
+1. Open a task.
+2. Paste, drag, or select an image inside the description or a comment.
+3. Confirm the image uploads and renders inline.
+
+If uploads fail:
+
+- confirm the bucket exists
+- confirm the credentials can write to the bucket
+- confirm the storage endpoint is reachable from the Kaneo API
+- if using direct browser uploads, confirm CORS is configured correctly for your storage endpoint
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index bd2cf6db3..9d66129d4 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -65,6 +65,7 @@
"core/installation/index",
"core/installation/drim",
"core/installation/docker-compose",
+ "core/installation/object-storage-and-image-uploads",
"core/installation/environment-variables",
"core/installation/start-services"
]
diff --git a/apps/web/package.json b/apps/web/package.json
index 4086834a3..7086512e2 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -44,6 +44,7 @@
"@tanstack/router-plugin": "^1.164.0",
"@tiptap/core": "^3.20.1",
"@tiptap/extension-code-block-lowlight": "^3.20.1",
+ "@tiptap/extension-image": "^3.20.1",
"@tiptap/extension-link": "^3.20.1",
"@tiptap/extension-list": "^3.20.1",
"@tiptap/extension-placeholder": "^3.20.1",
diff --git a/apps/web/src/components/activity/comment-card.tsx b/apps/web/src/components/activity/comment-card.tsx
index 93a254688..f9fe85c28 100644
--- a/apps/web/src/components/activity/comment-card.tsx
+++ b/apps/web/src/components/activity/comment-card.tsx
@@ -202,6 +202,8 @@ export default function CommentCard({
value={isEditing ? editedContent : content}
onChange={isEditing ? setEditedContent : undefined}
placeholder="Edit comment..."
+ taskId={taskId}
+ uploadSurface="comment"
className={
isEditing
? "[&_.kaneo-comment-editor-content_.ProseMirror]:min-h-[3rem] [&_.kaneo-comment-editor-content_.ProseMirror]:max-h-none [&_.kaneo-comment-editor-content_.ProseMirror]:overflow-visible [&_.kaneo-comment-editor-content_.ProseMirror]:px-3 [&_.kaneo-comment-editor-content_.ProseMirror]:pt-2.5 [&_.kaneo-comment-editor-content_.ProseMirror]:pb-2"
diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsx
index 8c53abf55..60ab463bb 100644
--- a/apps/web/src/components/activity/comment-editor.tsx
+++ b/apps/web/src/components/activity/comment-editor.tsx
@@ -1,4 +1,5 @@
import type { Editor } from "@tiptap/core";
+import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import { Table } from "@tiptap/extension-table";
import TableCell from "@tiptap/extension-table-cell";
@@ -16,6 +17,7 @@ import {
Check,
ChevronDown,
Copy,
+ ImagePlus,
Italic,
Link2,
List,
@@ -34,6 +36,7 @@ import {
} from "@/components/task/extensions/shiki-code-block";
import { TaskItemWithCheckbox } from "@/components/task/extensions/task-item-with-checkbox";
import { Button } from "@/components/ui/button";
+import { Dialog, DialogPopup } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
DropdownMenu,
@@ -52,12 +55,16 @@ import {
normalizeUrl,
} from "@/lib/editor-url-utils";
import { getSharedShikiHighlighter } from "@/lib/shiki-highlighter";
+import { toast } from "@/lib/toast";
+import { uploadTaskImage } from "@/lib/upload-task-image";
type CommentEditorProps = {
value: string;
onChange?: (value: string) => void;
placeholder?: string;
className?: string;
+ contentClassName?: string;
+ proseClassName?: string;
autoFocus?: boolean;
disabled?: boolean;
readOnly?: boolean;
@@ -65,6 +72,9 @@ type CommentEditorProps = {
slashMenuPosition?: "absolute" | "fixed";
onSubmitShortcut?: () => void;
onCancelShortcut?: () => void;
+ taskId?: string;
+ uploadSurface?: "description" | "comment";
+ ensureTaskId?: () => Promise<string | null>;
};
type SlashRange = { from: number; to: number };
@@ -141,6 +151,8 @@ export default function CommentEditor({
onChange,
placeholder = "Leave a comment...",
className,
+ contentClassName,
+ proseClassName,
autoFocus = false,
disabled = false,
readOnly = false,
@@ -148,12 +160,24 @@ export default function CommentEditor({
slashMenuPosition = "absolute",
onSubmitShortcut,
onCancelShortcut,
+ taskId,
+ uploadSurface = "comment",
+ ensureTaskId,
}: CommentEditorProps) {
const editorShellRef = useRef<HTMLDivElement | null>(null);
+ const imageInputRef = useRef<HTMLInputElement | null>(null);
+ const dragDepthRef = useRef(0);
const isSyncingRef = useRef(false);
const hasHydratedRef = useRef(false);
const latestValueRef = useRef(normalizeMarkdown(value || ""));
const lastEditorRef = useRef<Editor | null>(null);
+ const taskIdRef = useRef(taskId);
+ const ensureTaskIdRef = useRef(ensureTaskId);
+ const uploadSurfaceRef = useRef(uploadSurface);
+ const pendingImageInsertRef = useRef<{
+ editor: Editor;
+ range?: SlashRange;
+ } | null>(null);
const [slashMenu, setSlashMenu] = useState<SlashMenuState | null>(null);
const [shikiHighlighter, setShikiHighlighter] = useState<Highlighter | null>(
null,
@@ -170,6 +194,11 @@ export default function CommentEditor({
null,
);
const [embedComposerError, setEmbedComposerError] = useState("");
+ const [isDragActive, setIsDragActive] = useState(false);
+ const [previewImage, setPreviewImage] = useState<{
+ src: string;
+ alt: string;
+ } | null>(null);
const codeLanguages = useMemo(() => COMMENT_CODE_LANGUAGE_OPTIONS, []);
const availableShikiLanguages = useMemo(
() => new Set(Object.keys(bundledLanguages)),
@@ -202,6 +231,125 @@ export default function CommentEditor({
[slashMenuPosition],
);
+ useEffect(() => {
+ taskIdRef.current = taskId;
+ ensureTaskIdRef.current = ensureTaskId;
+ uploadSurfaceRef.current = uploadSurface;
+ }, [ensureTaskId, taskId, uploadSurface]);
+
+ const handleImageFileUpload = useCallback(
+ async (file: File, targetEditor?: Editor | null, range?: SlashRange) => {
+ const activeEditor = targetEditor || lastEditorRef.current;
+ const resolvedTaskId =
+ taskIdRef.current ?? (await ensureTaskIdRef.current?.());
+
+ if (!activeEditor || !resolvedTaskId) {
+ toast.error("Image uploads are only available on saved tasks.");
+ return;
+ }
+
+ const loadingToast = toast.loading("Uploading image...");
+
+ try {
+ const uploadedImage = await uploadTaskImage({
+ taskId: resolvedTaskId,
+ surface: uploadSurfaceRef.current,
+ file,
+ });
+
+ const chain = activeEditor.chain().focus();
+ if (range) {
+ chain.deleteRange(range);
+ }
+
+ chain
+ .setImage({
+ src: uploadedImage.url,
+ alt: uploadedImage.alt,
+ })
+ .run();
+
+ toast.dismiss(loadingToast);
+ toast.success("Image uploaded");
+ } catch (error) {
+ toast.dismiss(loadingToast);
+ toast.error(
+ error instanceof Error ? error.message : "Failed to upload image",
+ );
+ }
+ },
+ [],
+ );
+
+ const canUploadImages = Boolean(taskId || ensureTaskId);
+
+ const openImagePicker = useCallback(
+ (activeEditor?: Editor | null, range?: SlashRange) => {
+ pendingImageInsertRef.current = activeEditor
+ ? { editor: activeEditor, range }
+ : null;
+ imageInputRef.current?.click();
+ },
+ [],
+ );
+
+ const hasImageDrag = useCallback((event: React.DragEvent<HTMLElement>) => {
+ return Array.from(event.dataTransfer?.items || []).some((item) =>
+ item.type.toLowerCase().startsWith("image/"),
+ );
+ }, []);
+
+ const handleShellDragEnter = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {
+ return;
+ }
+ event.preventDefault();
+ dragDepthRef.current += 1;
+ setIsDragActive(true);
+ },
+ [canUploadImages, disabled, hasImageDrag, readOnly],
+ );
+
+ const handleShellDragOver = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {
+ return;
+ }
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ if (!isDragActive) {
+ setIsDragActive(true);
+ }
+ },
+ [canUploadImages, disabled, hasImageDrag, isDragActive, readOnly],
+ );
+
+ const handleShellDragLeave = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {
+ return;
+ }
+ event.preventDefault();
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
+ if (dragDepthRef.current === 0) {
+ setIsDragActive(false);
+ }
+ },
+ [canUploadImages, disabled, hasImageDrag, readOnly],
+ );
+
+ const handleShellDrop = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {
+ return;
+ }
+ dragDepthRef.current = 0;
+ setIsDragActive(false);
+ },
+ [canUploadImages, disabled, hasImageDrag, readOnly],
+ );
+
const slashCommands = useMemo<SlashCommand[]>(
() => [
{
@@ -315,8 +463,18 @@ export default function CommentEditor({
.run();
},
},
+ {
+ id: "image",
+ label: "Image",
+ group: "insert",
+ search: "image photo picture upload",
+ run: (activeEditor, range) => {
+ activeEditor.chain().focus().deleteRange(range).run();
+ openImagePicker(activeEditor);
+ },
+ },
],
- [],
+ [openImagePicker],
);
useEffect(() => {
@@ -375,6 +533,12 @@ export default function CommentEditor({
EmbedBlock,
KaneoIssueLink,
TaskList,
+ Image.configure({
+ HTMLAttributes: {
+ class: "kaneo-editor-image",
+ loading: "lazy",
+ },
+ }),
TaskItemWithCheckbox.configure({
nested: true,
}),
@@ -391,13 +555,24 @@ export default function CommentEditor({
editorProps: {
attributes: {
class: cn(
- "kaneo-comment-editor-prose",
+ proseClassName || "kaneo-comment-editor-prose",
readOnly && "kaneo-comment-editor-prose-readonly",
),
},
handlePaste: (view, event) => {
if (readOnly || disabled) return false;
+ const pastedFiles = Array.from(event.clipboardData?.files || []);
+ const pastedImage = pastedFiles.find((file) =>
+ file.type.toLowerCase().startsWith("image/"),
+ );
+
+ if (pastedImage) {
+ event.preventDefault();
+ void handleImageFileUpload(pastedImage, editor);
+ return true;
+ }
+
const plainText = event.clipboardData?.getData("text/plain") || "";
const taskListNodes = parseTaskListMarkdownToNodes(plainText);
if (taskListNodes) {
@@ -449,6 +624,29 @@ export default function CommentEditor({
setEmbedComposerError("");
return true;
},
+ handleDrop: (view, event) => {
+ if (readOnly || disabled) return false;
+
+ const droppedFiles = Array.from(event.dataTransfer?.files || []);
+ const droppedImage = droppedFiles.find((file) =>
+ file.type.toLowerCase().startsWith("image/"),
+ );
+
+ if (!droppedImage) return false;
+
+ event.preventDefault();
+ const coordinates = view.posAtCoords({
+ left: event.clientX,
+ top: event.clientY,
+ });
+
+ const dropRange = coordinates
+ ? { from: coordinates.pos, to: coordinates.pos }
+ : undefined;
+
+ void handleImageFileUpload(droppedImage, editor, dropRange);
+ return true;
+ },
handleKeyDown: (_view, event) => {
if (!readOnly && !disabled && slashMenu) {
if (event.key === "ArrowDown") {
@@ -555,7 +753,7 @@ export default function CommentEditor({
onChange(markdown);
},
},
- [toShikiLanguage],
+ [handleImageFileUpload, toShikiLanguage],
);
useEffect(() => {
@@ -590,6 +788,29 @@ export default function CommentEditor({
};
}, [editor]);
+ useEffect(() => {
+ if (!editor) return;
+
+ const handleImagePreviewClick = (event: MouseEvent) => {
+ const target = event.target as HTMLElement | null;
+ if (!(target instanceof HTMLImageElement)) return;
+ if (!target.classList.contains("kaneo-editor-image")) return;
+
+ event.preventDefault();
+ setPreviewImage({
+ src: target.currentSrc || target.src,
+ alt: target.alt || "Preview image",
+ });
+ };
+
+ const dom = editor.view.dom;
+ dom.addEventListener("click", handleImagePreviewClick);
+
+ return () => {
+ dom.removeEventListener("click", handleImagePreviewClick);
+ };
+ }, [editor]);
+
const updateSlashMenu = useCallback(
(activeEditor: Editor) => {
if (readOnly || disabled) {
@@ -1018,14 +1239,42 @@ export default function CommentEditor({
}, [editor, hoveredCodeBlock]);
return (
- <div
+ <section
ref={editorShellRef}
+ aria-label={readOnly ? "Comment content" : "Comment editor"}
className={cn(
"kaneo-comment-editor-shell",
+ isDragActive && "is-drag-active",
readOnly && "kaneo-comment-editor-shell-readonly",
className,
)}
+ onDragEnter={handleShellDragEnter}
+ onDragOver={handleShellDragOver}
+ onDragLeave={handleShellDragLeave}
+ onDrop={handleShellDrop}
>
+ {!readOnly && !disabled && (
+ <input
+ ref={imageInputRef}
+ type="file"
+ accept="image/*"
+ className="sr-only"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ const pendingInsert = pendingImageInsertRef.current;
+ pendingImageInsertRef.current = null;
+ void handleImageFileUpload(
+ file,
+ pendingInsert?.editor,
+ pendingInsert?.range,
+ );
+
+ event.target.value = "";
+ }}
+ />
+ )}
{editor && hoveredCodeBlock && !disabled && (
<div
className="kaneo-codeblock-language"
@@ -1098,6 +1347,7 @@ export default function CommentEditor({
className="kaneo-comment-editor-bubble"
shouldShow={({ editor: activeEditor, from, to }) => {
if (activeEditor.isActive("embedBlock")) return false;
+ if (activeEditor.isActive("image")) return false;
if (activeEditor.isEmpty) return false;
return from !== to;
}}
@@ -1189,6 +1439,15 @@ export default function CommentEditor({
>
<Link2 className="size-3.5" />
</Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="kaneo-comment-editor-bubble-btn"
+ onClick={() => openImagePicker(editor)}
+ >
+ <ImagePlus className="size-3.5" />
+ </Button>
</BubbleMenu>
)}
{slashMenu && !readOnly && !disabled && (
@@ -1345,10 +1604,37 @@ export default function CommentEditor({
)}
<EditorContent
editor={editor}
- className="kaneo-comment-editor-content"
+ className={cn("kaneo-comment-editor-content", contentClassName)}
onMouseMove={handleEditorMouseMove}
onMouseLeave={handleEditorMouseLeave}
/>
- </div>
+ {isDragActive && (
+ <div className="kaneo-editor-drop-indicator">
+ <span>Drop image to upload</span>
+ </div>
+ )}
+ <Dialog
+ open={Boolean(previewImage)}
+ onOpenChange={(open) => {
+ if (!open) setPreviewImage(null);
+ }}
+ >
+ <DialogPopup
+ className="max-w-6xl border-0 bg-transparent p-0 shadow-none before:hidden"
+ showCloseButton={false}
+ bottomStickOnMobile={false}
+ >
+ {previewImage && (
+ <div className="flex max-h-[90vh] items-center justify-center p-4">
+ <img
+ src={previewImage.src}
+ alt={previewImage.alt}
+ className="max-h-[85vh] max-w-[92vw] rounded-xl border border-white/12 bg-black/30 object-contain shadow-2xl"
+ />
+ </div>
+ )}
+ </DialogPopup>
+ </Dialog>
+ </section>
);
}
diff --git a/apps/web/src/components/activity/comment-input.tsx b/apps/web/src/components/activity/comment-input.tsx
index e49e4861f..8eb5531c2 100644
--- a/apps/web/src/components/activity/comment-input.tsx
+++ b/apps/web/src/components/activity/comment-input.tsx
@@ -53,6 +53,8 @@ export default function CommentInput({ taskId }: CommentInputProps) {
value={content}
onChange={setContent}
placeholder="Leave a comment..."
+ taskId={taskId}
+ uploadSurface="comment"
className="[&_.kaneo-comment-editor-content_.ProseMirror]:min-h-[3rem] [&_.kaneo-comment-editor-content_.ProseMirror]:max-h-none [&_.kaneo-comment-editor-content_.ProseMirror]:overflow-visible [&_.kaneo-comment-editor-content_.ProseMirror]:px-3 [&_.kaneo-comment-editor-content_.ProseMirror]:pt-3 [&_.kaneo-comment-editor-content_.ProseMirror]:pb-2"
onSubmitShortcut={handleSubmit}
/>
diff --git a/apps/web/src/components/public-project/markdown-renderer.tsx b/apps/web/src/components/public-project/markdown-renderer.tsx
index b9d7b7c7e..96af97df6 100644
--- a/apps/web/src/components/public-project/markdown-renderer.tsx
+++ b/apps/web/src/components/public-project/markdown-renderer.tsx
@@ -1,4 +1,4 @@
-import ReactMarkdown from "react-markdown";
+import CommentEditor from "@/components/activity/comment-editor";
type MarkdownRendererProps = {
content: string;
@@ -6,65 +6,13 @@ type MarkdownRendererProps = {
export function MarkdownRenderer({ content }: MarkdownRendererProps) {
return (
- <ReactMarkdown
- components={{
- h1: ({ children, ...props }) => (
- <h1 className="text-xl font-semibold mb-2 mt-4" {...props}>
- {children}
- </h1>
- ),
- h2: ({ children, ...props }) => (
- <h2 className="text-lg font-semibold mb-2 mt-3" {...props}>
- {children}
- </h2>
- ),
- h3: ({ children, ...props }) => (
- <h3 className="text-base font-semibold mb-1.5 mt-2.5" {...props}>
- {children}
- </h3>
- ),
- p: ({ children, ...props }) => (
- <p className="mb-2 leading-relaxed" {...props}>
- {children}
- </p>
- ),
- ul: ({ children, ...props }) => (
- <ul className="list-disc list-inside mb-2 space-y-1" {...props}>
- {children}
- </ul>
- ),
- ol: ({ children, ...props }) => (
- <ol className="list-decimal list-inside mb-2 space-y-1" {...props}>
- {children}
- </ol>
- ),
- code: ({ children, ...props }) => (
- <code
- className="bg-muted px-1.5 py-0.5 rounded text-xs font-mono"
- {...props}
- >
- {children}
- </code>
- ),
- pre: ({ children, ...props }) => (
- <pre
- className="bg-muted p-3 rounded border border-border/50 overflow-x-auto mb-2"
- {...props}
- >
- {children}
- </pre>
- ),
- blockquote: ({ children, ...props }) => (
- <blockquote
- className="border-l-2 border-border pl-3 italic text-muted-foreground mb-2"
- {...props}
- >
- {children}
- </blockquote>
- ),
- }}
- >
- {content}
- </ReactMarkdown>
+ <CommentEditor
+ value={content}
+ readOnly
+ showBubbleMenu={false}
+ proseClassName="kaneo-tiptap-prose"
+ contentClassName="kaneo-tiptap-content"
+ className="[&_.kaneo-tiptap-content_.ProseMirror]:max-h-none [&_.kaneo-tiptap-content_.ProseMirror]:overflow-visible [&_.kaneo-tiptap-content_.ProseMirror]:px-0 [&_.kaneo-tiptap-content_.ProseMirror]:py-0"
+ />
);
}
diff --git a/apps/web/src/components/public-project/task-detail-modal.tsx b/apps/web/src/components/public-project/task-detail-modal.tsx
index 9738a68d2..6d24321f1 100644
--- a/apps/web/src/components/public-project/task-detail-modal.tsx
+++ b/apps/web/src/components/public-project/task-detail-modal.tsx
@@ -73,14 +73,14 @@ export function PublicTaskDetailModal({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogPopup className="w-full max-w-3xl max-h-[85vh]">
- <div className="bg-background border border-border rounded-lg flex flex-col max-h-[85vh] shadow-lg">
- <div className="flex items-center justify-between p-4 border-b border-border shrink-0">
+ <DialogPopup className="w-full max-w-4xl max-h-[85vh] p-0">
+ <div className="bg-background border border-border rounded-xl flex flex-col max-h-[85vh] shadow-lg">
+ <div className="flex items-center justify-between px-4 py-3 border-b border-border/70 shrink-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
- <span className="text-xs font-mono text-muted-foreground shrink-0">
+ <span className="text-sm font-medium text-muted-foreground shrink-0">
{projectSlug.toUpperCase()}-{task.number}
</span>
- <span className="text-xs text-muted-foreground px-1.5 py-0.5 bg-muted rounded capitalize shrink-0">
+ <span className="text-xs text-muted-foreground px-1.5 py-0.5 bg-muted rounded-md capitalize shrink-0">
{task.status?.replace("-", " ")}
</span>
</div>
@@ -92,9 +92,9 @@ export function PublicTaskDetailModal({
</DialogClose>
</div>
- <div className="flex-1 overflow-y-auto p-6 space-y-6">
- <div className="space-y-4">
- <h2 className="text-xl font-semibold text-foreground pr-8">
+ <div className="flex-1 overflow-y-auto px-5 py-5 space-y-5">
+ <div className="space-y-3">
+ <h2 className="pr-8 text-2xl font-heading font-semibold leading-tight text-foreground">
{task.title}
</h2>
@@ -141,23 +141,18 @@ export function PublicTaskDetailModal({
</div>
</div>
- {labels.length > 0 && (
- <div className="space-y-2">
- <h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Labels
- </h3>
- <PublicTaskLabels labels={labels} />
+ {task.description && (
+ <div className="pt-1">
+ <MarkdownRenderer content={task.description} />
</div>
)}
- {task.description && (
+ {labels.length > 0 && (
<div className="space-y-2">
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Description
+ Labels
</h3>
- <div className="text-sm text-foreground leading-relaxed bg-muted/30 p-4 rounded-md border border-border/50">
- <MarkdownRenderer content={task.description} />
- </div>
+ <PublicTaskLabels labels={labels} />
</div>
)}
diff --git a/apps/web/src/components/shared/modals/create-task-modal.tsx b/apps/web/src/components/shared/modals/create-task-modal.tsx
index 7fedb546f..0ef8fca40 100644
--- a/apps/web/src/components/shared/modals/create-task-modal.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx
@@ -37,12 +37,15 @@ import {
} from "@/components/ui/popover";
import useCreateLabel from "@/hooks/mutations/label/use-create-label";
import useCreateTask from "@/hooks/mutations/task/use-create-task";
+import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
+import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";
import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { cn } from "@/lib/cn";
import { getPriorityIcon } from "@/lib/priority";
import { toast } from "@/lib/toast";
import useProjectStore from "@/store/project";
+import type Task from "@/types/task";
type CreateTaskModalProps = {
open: boolean;
@@ -74,6 +77,26 @@ type Label = {
type PopoverStep = "select" | "color";
+function normalizeTask(
+ task: Partial<Task> &
+ Pick<Task, "id" | "title" | "status" | "projectId" | "createdAt">,
+): Task {
+ return {
+ ...task,
+ number: task.number ?? null,
+ description: task.description ?? null,
+ priority: task.priority ?? null,
+ dueDate: task.dueDate ?? null,
+ position: task.position ?? 0,
+ userId: task.userId ?? null,
+ assigneeId: task.assigneeId ?? task.userId ?? null,
+ assigneeName: task.assigneeName ?? null,
+ assigneeImage: task.assigneeImage ?? null,
+ labels: task.labels ?? [],
+ externalLinks: task.externalLinks ?? [],
+ };
+}
+
const labelColors = [
{
value: "gray" as LabelColor,
@@ -137,6 +160,7 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
const [dueDate, setDueDate] = useState<Date | undefined>(undefined);
const [createMore, setCreateMore] = useState(false);
const [labels, setLabels] = useState<Label[]>([]);
+ const [draftTask, setDraftTask] = useState<Task | null>(null);
const [labelsOpen, setLabelsOpen] = useState(false);
const [labelsStep, setLabelsStep] = useState<PopoverStep>("select");
@@ -145,8 +169,12 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
const [newLabelName, setNewLabelName] = useState("");
const searchInputRef = useRef<HTMLInputElement>(null);
+ const draftCreationPromiseRef = useRef<Promise<Task> | null>(null);
+ const didSubmitRef = useRef(false);
- const { mutateAsync } = useCreateTask();
+ const { mutateAsync: createTask } = useCreateTask();
+ const { mutateAsync: updateTask } = useUpdateTask();
+ const { mutateAsync: deleteTask } = useDeleteTask();
const filteredLabels = (() => {
const searchFiltered = workspaceLabels.filter((label) =>
@@ -171,6 +199,8 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
);
const handleClose = () => {
+ const shouldDeleteDraft = draftTask && !didSubmitRef.current;
+
setTitle("");
setDescription("");
setPriority("no-priority");
@@ -182,57 +212,173 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
setSearchValue("");
setSelectedColor("gray");
setNewLabelName("");
+ draftCreationPromiseRef.current = null;
+ didSubmitRef.current = false;
+ setDraftTask(null);
onClose();
+
+ if (shouldDeleteDraft) {
+ void deleteTask(draftTask.id).catch(() => {
+ // ignore cleanup failures for abandoned empty drafts
+ });
+ }
};
+ const syncTaskIntoProject = useCallback(
+ (task: Task) => {
+ if (!project) return;
+
+ const updatedProject = produce(project, (draft) => {
+ let existingTask:
+ | (typeof draft.columns)[number]["tasks"][number]
+ | undefined;
+
+ for (const column of draft.columns ?? []) {
+ const taskIndex = column.tasks.findIndex(
+ (columnTask) => columnTask.id === task.id,
+ );
+
+ if (taskIndex !== -1) {
+ existingTask = column.tasks[taskIndex];
+ column.tasks.splice(taskIndex, 1);
+ break;
+ }
+ }
+
+ if (task.status === "planned" || task.status === "archived") {
+ return;
+ }
+
+ const targetColumn = draft.columns?.find(
+ (column) => column.id === task.status,
+ );
+ if (!targetColumn) return;
+
+ targetColumn.tasks.push({
+ ...existingTask,
+ ...task,
+ assigneeId: task.userId,
+ assigneeName:
+ workspace?.members?.find((member) => member.userId === task.userId)
+ ?.user?.name ??
+ existingTask?.assigneeName ??
+ null,
+ assigneeImage:
+ workspace?.members?.find((member) => member.userId === task.userId)
+ ?.user?.image ??
+ existingTask?.assigneeImage ??
+ null,
+ position: task.position ?? 0,
+ });
+ });
+
+ setProject(updatedProject);
+ },
+ [project, setProject, workspace?.members],
+ );
+
+ const ensureDraftTask = useCallback(async () => {
+ if (draftTask) {
+ return draftTask.id;
+ }
+
+ if (draftCreationPromiseRef.current) {
+ const pendingTask = await draftCreationPromiseRef.current;
+ return pendingTask.id;
+ }
+
+ if (!project?.id) {
+ toast.error("Choose a project before uploading images.");
+ return null;
+ }
+
+ const draftStatus = "planned";
+ const draftPromise = createTask({
+ title: title.trim() || "Untitled task",
+ description: description.trim() || "",
+ userId: assigneeId,
+ priority,
+ projectId: project.id,
+ dueDate: dueDate ? dueDate.toISOString() : undefined,
+ status: draftStatus,
+ }).then((task) => normalizeTask(task));
+
+ draftCreationPromiseRef.current = draftPromise;
+
+ try {
+ const createdTask = await draftPromise;
+ setDraftTask(createdTask);
+ return createdTask.id;
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Failed to prepare task",
+ );
+ return null;
+ } finally {
+ draftCreationPromiseRef.current = null;
+ }
+ }, [
+ assigneeId,
+ createTask,
+ description,
+ draftTask,
+ dueDate,
+ priority,
+ project?.id,
+ title,
+ ]);
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim() || !project?.id || !workspace?.id) return;
try {
const taskStatus = status ?? "to-do";
-
- const newTask = await mutateAsync({
- title: title.trim(),
- description: description.trim() || "",
- userId: assigneeId,
- priority,
- projectId: project?.id,
- dueDate: dueDate ? dueDate.toISOString() : undefined,
- status: taskStatus,
- });
+ didSubmitRef.current = true;
+
+ const savedTask = draftTask
+ ? normalizeTask(
+ await updateTask({
+ ...draftTask,
+ title: title.trim(),
+ description: description.trim() || "",
+ userId: assigneeId || null,
+ status: taskStatus,
+ priority,
+ dueDate: dueDate ? dueDate.toISOString() : null,
+ projectId: project.id,
+ }),
+ )
+ : normalizeTask(
+ await createTask({
+ title: title.trim(),
+ description: description.trim() || "",
+ userId: assigneeId,
+ priority,
+ projectId: project.id,
+ dueDate: dueDate ? dueDate.toISOString() : undefined,
+ status: taskStatus,
+ }),
+ );
for (const label of labels) {
try {
await createLabel({
name: label.name,
color: label.color,
- taskId: newTask.id,
- workspaceId: workspace?.id,
+ taskId: savedTask.id,
+ workspaceId: workspace.id,
});
} catch (error) {
console.error("Failed to create label:", error);
}
}
- const updatedProject = produce(project, (draft) => {
- if (newTask.status !== "planned" && newTask.status !== "archived") {
- const targetColumn = draft.columns?.find(
- (col) => col.id === newTask.status,
- );
- if (targetColumn) {
- targetColumn.tasks.push({
- ...newTask,
- assigneeId: assigneeId,
- assigneeName: assigneeId,
- position: 0,
- });
- }
- }
- });
-
- setProject(updatedProject);
- toast.success("Task created successfully");
+ setDraftTask(savedTask);
+ syncTaskIntoProject(savedTask);
+ toast.success(
+ draftTask ? "Task updated successfully" : "Task created successfully",
+ );
if (createMore) {
setTitle("");
@@ -245,10 +391,14 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
setSearchValue("");
setSelectedColor("gray");
setNewLabelName("");
+ draftCreationPromiseRef.current = null;
+ didSubmitRef.current = false;
+ setDraftTask(null);
} else {
handleClose();
}
} catch (error) {
+ didSubmitRef.current = false;
toast.error(
error instanceof Error ? error.message : "Failed to create task",
);
@@ -373,7 +523,7 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent
- className="max-w-2xl max-h-[90vh] flex flex-col"
+ className="kaneo-create-task-modal max-w-2xl max-h-[90vh] flex flex-col overflow-hidden"
showCloseButton={false}
>
<DialogHeader className="flex-shrink-0">
@@ -400,7 +550,7 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
onSubmit={handleSubmit}
className="flex flex-col flex-1 min-h-0 space-y-6"
>
- <div className="space-y-6 px-6">
+ <div className="flex-1 min-h-0 overflow-y-auto space-y-6 px-6">
<Input
unstyled
value={title}
@@ -416,6 +566,8 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
value={description}
onChange={setDescription}
placeholder="Add a description for your task..."
+ taskId={draftTask?.id}
+ ensureTaskId={ensureDraftTask}
/>
</div>
@@ -743,7 +895,7 @@ function CreateTaskModal({ open, onClose, status }: CreateTaskModalProps) {
</div>
</div>
- <DialogFooter>
+ <DialogFooter className="flex-shrink-0 border-t border-border bg-background px-6 py-4">
<div className="flex items-center gap-3 mr-auto">
<label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer hover:text-foreground transition-colors">
<input
diff --git a/apps/web/src/components/task/task-description-editor.tsx b/apps/web/src/components/task/task-description-editor.tsx
index 083842e24..7922399ec 100644
--- a/apps/web/src/components/task/task-description-editor.tsx
+++ b/apps/web/src/components/task/task-description-editor.tsx
@@ -4,18 +4,25 @@ type TaskDescriptionEditorProps = {
value: string;
onChange: (value: string) => void;
placeholder?: string;
+ taskId?: string;
+ ensureTaskId?: () => Promise<string | null>;
};
export default function TaskDescriptionEditor({
value,
onChange,
placeholder = "Add a description...",
+ taskId,
+ ensureTaskId,
}: TaskDescriptionEditorProps) {
return (
<CommentEditor
value={value}
onChange={onChange}
placeholder={placeholder}
+ taskId={taskId}
+ ensureTaskId={ensureTaskId}
+ uploadSurface="description"
className="[&_.kaneo-comment-editor-content_.ProseMirror]:min-h-[11rem] [&_.kaneo-comment-editor-content_.ProseMirror]:max-h-none [&_.kaneo-comment-editor-content_.ProseMirror]:overflow-visible [&_.kaneo-comment-editor-content_.ProseMirror]:px-0 [&_.kaneo-comment-editor-content_.ProseMirror]:pt-1 [&_.kaneo-comment-editor-content_.ProseMirror]:pb-2"
/>
);
diff --git a/apps/web/src/components/task/task-description.tsx b/apps/web/src/components/task/task-description.tsx
index 8e025a58b..5ac1bd683 100644
--- a/apps/web/src/components/task/task-description.tsx
+++ b/apps/web/src/components/task/task-description.tsx
@@ -1,4 +1,5 @@
import type { Editor } from "@tiptap/core";
+import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import { Table } from "@tiptap/extension-table";
import TableCell from "@tiptap/extension-table-cell";
@@ -33,6 +34,7 @@ import type { MouseEvent as ReactMouseEvent } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { bundledLanguages, type Highlighter } from "shiki";
import { Button } from "@/components/ui/button";
+import { Dialog, DialogPopup } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
DropdownMenu,
@@ -54,6 +56,8 @@ import {
normalizeUrl,
} from "@/lib/editor-url-utils";
import { getSharedShikiHighlighter } from "@/lib/shiki-highlighter";
+import { toast } from "@/lib/toast";
+import { uploadTaskImage } from "@/lib/upload-task-image";
import { EmbedBlock } from "./extensions/embed-block";
import { KaneoIssueLink } from "./extensions/kaneo-issue-link";
import {
@@ -248,10 +252,16 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const { mutateAsync: updateTaskDescription } = useUpdateTaskDescription();
const editorShellRef = useRef<HTMLDivElement | null>(null);
+ const imageInputRef = useRef<HTMLInputElement | null>(null);
+ const dragDepthRef = useRef(0);
const taskRef = useRef(task);
const updateTaskRef = useRef(updateTaskDescription);
const activeTaskIdRef = useRef<string | null>(null);
const lastEditorRef = useRef<Editor | null>(null);
+ const pendingImageInsertRef = useRef<{
+ editor: Editor;
+ range?: SlashRange;
+ } | null>(null);
const hasHydratedRef = useRef(false);
const isSyncingExternalContentRef = useRef(false);
const latestSyncedMarkdownRef = useRef("");
@@ -270,6 +280,11 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
null,
);
const [embedComposerError, setEmbedComposerError] = useState("");
+ const [isDragActive, setIsDragActive] = useState(false);
+ const [previewImage, setPreviewImage] = useState<{
+ src: string;
+ alt: string;
+ } | null>(null);
const slashMenuRef = useRef<SlashMenuState | null>(null);
useEffect(() => {
@@ -309,6 +324,124 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
[],
);
+ const handleImageFileUpload = useCallback(
+ async (file: File, targetEditor?: Editor | null, range?: SlashRange) => {
+ const activeEditor = targetEditor || lastEditorRef.current;
+
+ if (!activeEditor) {
+ toast.error("Image upload failed");
+ return;
+ }
+
+ const loadingToast = toast.loading("Uploading image...");
+
+ try {
+ const uploadedImage = await uploadTaskImage({
+ taskId,
+ surface: "description",
+ file,
+ });
+
+ const chain = activeEditor.chain().focus();
+ if (range) {
+ chain.deleteRange(range);
+ }
+
+ chain
+ .setImage({
+ src: uploadedImage.url,
+ alt: uploadedImage.alt,
+ })
+ .run();
+
+ toast.dismiss(loadingToast);
+ toast.success("Image uploaded");
+ } catch (error) {
+ toast.dismiss(loadingToast);
+ toast.error(
+ error instanceof Error ? error.message : "Failed to upload image",
+ );
+ }
+ },
+ [taskId],
+ );
+
+ const openImagePicker = useCallback(
+ (activeEditor?: Editor | null, range?: SlashRange) => {
+ pendingImageInsertRef.current = activeEditor
+ ? { editor: activeEditor, range }
+ : null;
+ imageInputRef.current?.click();
+ },
+ [],
+ );
+
+ const hasImageDrag = useCallback((event: React.DragEvent<HTMLElement>) => {
+ return Array.from(event.dataTransfer?.items || []).some((item) =>
+ item.type.toLowerCase().startsWith("image/"),
+ );
+ }, []);
+
+ const handleShellDragEnter = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (!taskId || !hasImageDrag(event)) return;
+ event.preventDefault();
+ dragDepthRef.current += 1;
+ setIsDragActive(true);
+ },
+ [hasImageDrag, taskId],
+ );
+
+ const handleShellDragOver = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (!taskId || !hasImageDrag(event)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ if (!isDragActive) {
+ setIsDragActive(true);
+ }
+ },
+ [hasImageDrag, isDragActive, taskId],
+ );
+
+ const handleShellDragLeave = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (!taskId || !hasImageDrag(event)) return;
+ event.preventDefault();
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
+ if (dragDepthRef.current === 0) {
+ setIsDragActive(false);
+ }
+ },
+ [hasImageDrag, taskId],
+ );
+
+ const handleShellDrop = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ if (!taskId || !hasImageDrag(event)) return;
+ dragDepthRef.current = 0;
+ setIsDragActive(false);
+ },
+ [hasImageDrag, taskId],
+ );
+
+ const slashCommands = useMemo(
+ () => [
+ ...SLASH_COMMANDS,
+ {
+ id: "image",
+ label: "Image",
+ group: "insert" as const,
+ search: "image photo picture upload",
+ run: (activeEditor: Editor, range: SlashRange) => {
+ activeEditor.chain().focus().deleteRange(range).run();
+ openImagePicker(activeEditor);
+ },
+ },
+ ],
+ [openImagePicker],
+ );
+
useEffect(() => {
let isDisposed = false;
@@ -377,6 +510,12 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
EmbedBlock,
KaneoIssueLink,
TaskList,
+ Image.configure({
+ HTMLAttributes: {
+ class: "kaneo-editor-image",
+ loading: "lazy",
+ },
+ }),
TaskItemWithCheckbox.configure({
nested: true,
}),
@@ -395,6 +534,17 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
class: "kaneo-tiptap-prose",
},
handlePaste: (view, event) => {
+ const pastedFiles = Array.from(event.clipboardData?.files || []);
+ const pastedImage = pastedFiles.find((file) =>
+ file.type.toLowerCase().startsWith("image/"),
+ );
+
+ if (pastedImage) {
+ event.preventDefault();
+ void handleImageFileUpload(pastedImage, editor);
+ return true;
+ }
+
const plainText = event.clipboardData?.getData("text/plain") || "";
const taskListNodes = parseTaskListMarkdownToNodes(plainText);
if (taskListNodes) {
@@ -447,6 +597,26 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
setEmbedComposerError("");
return true;
},
+ handleDrop: (view, event) => {
+ const droppedFiles = Array.from(event.dataTransfer?.files || []);
+ const droppedImage = droppedFiles.find((file) =>
+ file.type.toLowerCase().startsWith("image/"),
+ );
+
+ if (!droppedImage) return false;
+
+ event.preventDefault();
+ const coordinates = view.posAtCoords({
+ left: event.clientX,
+ top: event.clientY,
+ });
+ const dropRange = coordinates
+ ? { from: coordinates.pos, to: coordinates.pos }
+ : undefined;
+
+ void handleImageFileUpload(droppedImage, editor, dropRange);
+ return true;
+ },
handleKeyDown: (view, event) => {
if (
!(
@@ -480,7 +650,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
debouncedUpdate(markdown);
},
},
- [getOverlayPosition, toShikiLanguage],
+ [getOverlayPosition, handleImageFileUpload, toShikiLanguage],
);
useEffect(() => {
@@ -515,6 +685,29 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
};
}, [editor]);
+ useEffect(() => {
+ if (!editor) return;
+
+ const handleImagePreviewClick = (event: MouseEvent) => {
+ const target = event.target as HTMLElement | null;
+ if (!(target instanceof HTMLImageElement)) return;
+ if (!target.classList.contains("kaneo-editor-image")) return;
+
+ event.preventDefault();
+ setPreviewImage({
+ src: target.currentSrc || target.src,
+ alt: target.alt || "Preview image",
+ });
+ };
+
+ const dom = editor.view.dom;
+ dom.addEventListener("click", handleImagePreviewClick);
+
+ return () => {
+ dom.removeEventListener("click", handleImagePreviewClick);
+ };
+ }, [editor]);
+
useEffect(() => {
slashMenuRef.current = slashMenu;
}, [slashMenu]);
@@ -543,13 +736,13 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const filteredSlashCommands = useMemo(() => {
const query = slashMenu?.query.trim().toLowerCase() || "";
- if (!query) return SLASH_COMMANDS;
- return SLASH_COMMANDS.filter(
+ if (!query) return slashCommands;
+ return slashCommands.filter(
(command) =>
command.label.toLowerCase().includes(query) ||
command.search.includes(query),
);
- }, [slashMenu?.query]);
+ }, [slashCommands, slashMenu?.query]);
const filteredSlashCommandsRef = useRef<SlashCommand[]>(
filteredSlashCommands,
@@ -991,7 +1184,38 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
);
return (
- <div ref={editorShellRef} className="kaneo-tiptap-shell group">
+ <section
+ ref={editorShellRef}
+ aria-label="Task description editor"
+ className={cn(
+ "kaneo-tiptap-shell group",
+ isDragActive && "is-drag-active",
+ )}
+ onDragEnter={handleShellDragEnter}
+ onDragOver={handleShellDragOver}
+ onDragLeave={handleShellDragLeave}
+ onDrop={handleShellDrop}
+ >
+ <input
+ ref={imageInputRef}
+ type="file"
+ accept="image/*"
+ className="sr-only"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ const pendingInsert = pendingImageInsertRef.current;
+ pendingImageInsertRef.current = null;
+ void handleImageFileUpload(
+ file,
+ pendingInsert?.editor,
+ pendingInsert?.range,
+ );
+
+ event.target.value = "";
+ }}
+ />
{editor && hoveredCodeBlock && (
<div
className="kaneo-codeblock-language"
@@ -1058,7 +1282,16 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
)}
{editor && (
- <BubbleMenu editor={editor} className="kaneo-tiptap-bubble">
+ <BubbleMenu
+ editor={editor}
+ className="kaneo-tiptap-bubble"
+ shouldShow={({ editor: activeEditor, from, to }) => {
+ if (activeEditor.isActive("embedBlock")) return false;
+ if (activeEditor.isActive("image")) return false;
+ if (activeEditor.isEmpty) return false;
+ return from !== to;
+ }}
+ >
<Button
type="button"
variant="ghost"
@@ -1381,6 +1614,33 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
onMouseMove={handleEditorMouseMove}
onMouseLeave={handleEditorMouseLeave}
/>
- </div>
+ {isDragActive && (
+ <div className="kaneo-editor-drop-indicator">
+ <span>Drop image to upload</span>
+ </div>
+ )}
+ <Dialog
+ open={Boolean(previewImage)}
+ onOpenChange={(open) => {
+ if (!open) setPreviewImage(null);
+ }}
+ >
+ <DialogPopup
+ className="max-w-6xl border-0 bg-transparent p-0 shadow-none before:hidden"
+ showCloseButton={false}
+ bottomStickOnMobile={false}
+ >
+ {previewImage && (
+ <div className="flex max-h-[90vh] items-center justify-center p-4">
+ <img
+ src={previewImage.src}
+ alt={previewImage.alt}
+ className="max-h-[85vh] max-w-[92vw] rounded-xl border border-white/12 bg-black/30 object-contain shadow-2xl"
+ />
+ </div>
+ )}
+ </DialogPopup>
+ </Dialog>
+ </section>
);
}
diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx
index 4cc8dec01..74dde3be5 100644
--- a/apps/web/src/components/ui/toast.tsx
+++ b/apps/web/src/components/ui/toast.tsx
@@ -55,7 +55,7 @@ function Toasts({ position = "bottom-right" }: { position: ToastPosition }) {
<Toast.Portal data-slot="toast-portal">
<Toast.Viewport
className={cn(
- "fixed z-50 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
+ "fixed z-[200] mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
// Vertical positioning
"data-[position*=top]:top-(--toast-inset)",
"data-[position*=bottom]:bottom-(--toast-inset)",
diff --git a/apps/web/src/fetchers/task/create-image-upload.ts b/apps/web/src/fetchers/task/create-image-upload.ts
new file mode 100644
index 000000000..6c6e3dcae
--- /dev/null
+++ b/apps/web/src/fetchers/task/create-image-upload.ts
@@ -0,0 +1,34 @@
+import { client } from "@kaneo/libs";
+
+async function createImageUpload({
+ taskId,
+ filename,
+ contentType,
+ size,
+ surface,
+}: {
+ taskId: string;
+ filename: string;
+ contentType: string;
+ size: number;
+ surface: "description" | "comment";
+}) {
+ const response = await client.task["image-upload"][":id"].$put({
+ param: { id: taskId },
+ json: {
+ filename,
+ contentType,
+ size,
+ surface,
+ },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default createImageUpload;
diff --git a/apps/web/src/fetchers/workspace/create-workspace.ts b/apps/web/src/fetchers/workspace/create-workspace.ts
index b309521f7..7483c0648 100644
--- a/apps/web/src/fetchers/workspace/create-workspace.ts
+++ b/apps/web/src/fetchers/workspace/create-workspace.ts
@@ -1,4 +1,8 @@
import { authClient } from "@/lib/auth-client";
+import {
+ createUniqueWorkspaceSlug,
+ isWorkspaceSlugCollisionError,
+} from "@/lib/utils/create-workspace-slug";
export type CreateWorkspaceRequest = {
name: string;
@@ -14,19 +18,43 @@ const createWorkspace = async ({
logo,
}: CreateWorkspaceRequest) => {
const metadata = description ? { description } : undefined;
+ const existingWorkspaces = slug
+ ? []
+ : ((await authClient.organization.list()).data ?? []);
+ let workspaceSlug = slug
+ ? slug
+ : createUniqueWorkspaceSlug(
+ name,
+ existingWorkspaces.map((workspace) => workspace.slug),
+ );
- const { data, error } = await authClient.organization.create({
- name,
- slug: slug || name.toLowerCase().replace(/\s+/g, "-"), // TODO
- logo,
- metadata,
- });
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const { data, error } = await authClient.organization.create({
+ name,
+ slug: workspaceSlug,
+ logo,
+ metadata,
+ });
- if (error) {
- throw new Error(error.message || "Failed to create workspace");
+ if (!error) {
+ return data;
+ }
+
+ const createError = new Error(
+ error.message || "Failed to create workspace",
+ );
+
+ if (slug || !isWorkspaceSlugCollisionError(createError)) {
+ throw createError;
+ }
+
+ workspaceSlug = createUniqueWorkspaceSlug(name, [
+ ...existingWorkspaces.map((workspace) => workspace.slug),
+ workspaceSlug,
+ ]);
}
- return data;
+ throw new Error("Failed to create workspace");
};
export default createWorkspace;
diff --git a/apps/web/src/hooks/queries/workspace/use-create-workspace.ts b/apps/web/src/hooks/queries/workspace/use-create-workspace.ts
index d7a84fe66..d89252449 100644
--- a/apps/web/src/hooks/queries/workspace/use-create-workspace.ts
+++ b/apps/web/src/hooks/queries/workspace/use-create-workspace.ts
@@ -1,6 +1,9 @@
import { useMutation } from "@tanstack/react-query";
import { authClient } from "@/lib/auth-client";
-import { createSlug } from "@/lib/utils/create-slug";
+import {
+ createUniqueWorkspaceSlug,
+ isWorkspaceSlugCollisionError,
+} from "@/lib/utils/create-workspace-slug";
type CreateWorkspaceRequest = {
name: string;
@@ -22,22 +25,45 @@ function useCreateWorkspace() {
userId,
}: CreateWorkspaceRequest) => {
const metadata = description ? { description } : undefined;
- const workspaceSlug = slug || createSlug(name);
-
- const { data, error } = await authClient.organization.create({
- name,
- slug: workspaceSlug,
- logo: logo || undefined,
- metadata,
- keepCurrentActiveOrganization,
- userId: userId,
- });
-
- if (error) {
- throw new Error(error.message || "Failed to create workspace");
+ const existingWorkspaces = slug
+ ? []
+ : ((await authClient.organization.list()).data ?? []);
+ let workspaceSlug = slug
+ ? slug
+ : createUniqueWorkspaceSlug(
+ name,
+ existingWorkspaces.map((workspace) => workspace.slug),
+ );
+
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const { data, error } = await authClient.organization.create({
+ name,
+ slug: workspaceSlug,
+ logo: logo || undefined,
+ metadata,
+ keepCurrentActiveOrganization,
+ userId: userId,
+ });
+
+ if (!error) {
+ return data;
+ }
+
+ const createError = new Error(
+ error.message || "Failed to create workspace",
+ );
+
+ if (slug || !isWorkspaceSlugCollisionError(createError)) {
+ throw createError;
+ }
+
+ workspaceSlug = createUniqueWorkspaceSlug(name, [
+ ...existingWorkspaces.map((workspace) => workspace.slug),
+ workspaceSlug,
+ ]);
}
- return data;
+ throw new Error("Failed to create workspace");
},
});
}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 9273dff23..300672d0c 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -230,6 +230,11 @@
outline: none;
}
+ .kaneo-tiptap-shell.is-drag-active,
+ .kaneo-comment-editor-shell.is-drag-active {
+ z-index: 90;
+ }
+
.kaneo-tiptap-bubble {
display: inline-flex;
align-items: center;
@@ -543,6 +548,25 @@
color: color-mix(in srgb, var(--foreground) 78%, transparent);
}
+ .kaneo-tiptap-content .ProseMirror img.kaneo-editor-image,
+ .kaneo-comment-editor-prose img.kaneo-editor-image {
+ display: block;
+ max-width: min(100%, 44rem);
+ width: auto;
+ height: auto;
+ margin: 0.75rem 0;
+ border: 1px solid color-mix(in srgb, var(--border) 76%, transparent);
+ border-radius: calc(var(--radius) - 2px);
+ background: color-mix(in srgb, var(--accent) 22%, transparent);
+ object-fit: contain;
+ overflow: hidden;
+ }
+
+ .kaneo-create-task-modal .kaneo-comment-editor-prose img.kaneo-editor-image {
+ max-height: min(50vh, 28rem);
+ width: 100%;
+ }
+
.kaneo-tiptap-content .ProseMirror .is-editor-empty:first-child::before {
pointer-events: none;
content: attr(data-placeholder);
@@ -815,6 +839,23 @@
z-index: 80;
}
+ .kaneo-editor-drop-indicator {
+ pointer-events: none;
+ position: absolute;
+ left: 0.75rem;
+ right: 0.75rem;
+ top: 0.75rem;
+ height: 2px;
+ z-index: 85;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--ring) 78%, var(--primary));
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--background) 88%, transparent);
+ }
+
+ .kaneo-editor-drop-indicator span {
+ display: none;
+ }
+
.kaneo-comment-editor-shell-readonly {
pointer-events: auto;
}
diff --git a/apps/web/src/lib/upload-task-image.ts b/apps/web/src/lib/upload-task-image.ts
new file mode 100644
index 000000000..6dcc04f93
--- /dev/null
+++ b/apps/web/src/lib/upload-task-image.ts
@@ -0,0 +1,64 @@
+import createImageUpload from "@/fetchers/task/create-image-upload";
+
+const allowedImageMimeTypes = new Set([
+ "image/apng",
+ "image/avif",
+ "image/gif",
+ "image/heic",
+ "image/heif",
+ "image/jpeg",
+ "image/jpg",
+ "image/png",
+ "image/svg+xml",
+ "image/webp",
+]);
+
+type UploadSurface = "description" | "comment";
+
+export function isSupportedImageFile(file: File) {
+ return allowedImageMimeTypes.has(file.type.toLowerCase());
+}
+
+export function getImageAltText(filename: string) {
+ return filename
+ .replace(/\.[^/.]+$/, "")
+ .replace(/[-_]+/g, " ")
+ .trim();
+}
+
+export async function uploadTaskImage({
+ taskId,
+ surface,
+ file,
+}: {
+ taskId: string;
+ surface: UploadSurface;
+ file: File;
+}) {
+ if (!isSupportedImageFile(file)) {
+ throw new Error("Only image uploads are supported.");
+ }
+
+ const upload = await createImageUpload({
+ taskId,
+ filename: file.name || "image",
+ contentType: file.type,
+ size: file.size,
+ surface,
+ });
+
+ const response = await fetch(upload.uploadUrl, {
+ method: "PUT",
+ headers: upload.headers,
+ body: file,
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to upload image to storage.");
+ }
+
+ return {
+ url: upload.assetUrl,
+ alt: getImageAltText(file.name || "image"),
+ };
+}
diff --git a/apps/web/src/lib/utils/create-workspace-slug.ts b/apps/web/src/lib/utils/create-workspace-slug.ts
new file mode 100644
index 000000000..317704d93
--- /dev/null
+++ b/apps/web/src/lib/utils/create-workspace-slug.ts
@@ -0,0 +1,47 @@
+import { createSlug } from "./create-slug";
+
+const RANDOM_SUFFIX_LENGTH = 12;
+
+export function createWorkspaceBaseSlug(value: string): string {
+ return createSlug(value) || "workspace";
+}
+
+function createRandomSuffix(): string {
+ return crypto.randomUUID().replace(/-/g, "").slice(0, RANDOM_SUFFIX_LENGTH);
+}
+
+export function createUniqueWorkspaceSlug(
+ value: string,
+ existingSlugs: Iterable<string | null | undefined>,
+): string {
+ const baseSlug = createWorkspaceBaseSlug(value);
+ const usedSlugs = new Set(
+ Array.from(existingSlugs, (slug) => slug?.toLowerCase()).filter(Boolean),
+ );
+
+ if (!usedSlugs.has(baseSlug.toLowerCase())) {
+ return baseSlug;
+ }
+
+ let slug = `${baseSlug}-${createRandomSuffix()}`;
+
+ while (usedSlugs.has(slug.toLowerCase())) {
+ slug = `${baseSlug}-${createRandomSuffix()}`;
+ }
+
+ return slug;
+}
+
+export function isWorkspaceSlugCollisionError(error: unknown): boolean {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+
+ const message = error.message.toLowerCase();
+
+ return (
+ message.includes("already exists") ||
+ message.includes("workspace exists") ||
+ message.includes("slug")
+ );
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dcf37f48b..a60e8a5c7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -304,6 +304,9 @@ importers:
'@tiptap/extension-code-block-lowlight':
specifier: ^3.20.1
+ '@tiptap/extension-image':
+ specifier: ^3.20.1
+ version: 3.20.1(@tiptap/[email protected](@tiptap/[email protected]))
'@tiptap/extension-link':
specifier: ^3.20.1
version: 3.20.1(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
@@ -3344,6 +3347,11 @@ packages:
'@tiptap/core': ^3.20.1
'@tiptap/pm': ^3.20.1
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-/GPFSLNdYSZQ0E6VBXSAk0UFtDdn98HT1Aa2tO+STELqc5jAdFB42dfFnTC6KQzTvcUOUYkE2S1Q22YC5H2XNQ==}
+ peerDependencies:
+ '@tiptap/core': ^3.20.1
+
'@tiptap/[email protected]':
resolution: {integrity: sha512-ZYRX13Kt8tR8JOzSXirH3pRpi8x30o7LHxZY58uXBdUvr3tFzOkh03qbN523+diidSVeHP/aMd/+IrplHRkQug==}
peerDependencies:
@@ -10218,6 +10226,10 @@ snapshots:
'@tiptap/core': 3.20.1(@tiptap/[email protected])
'@tiptap/pm': 3.20.1
+ dependencies:
+ '@tiptap/core': 3.20.1(@tiptap/[email protected])
+
dependencies:
'@tiptap/core': 3.20.1(@tiptap/[email protected])