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 custom fields support

MonsPropre222a5bcee263
diff --git a/apps/api/src/custom-field/controllers/create-custom-field.ts b/apps/api/src/custom-field/controllers/create-custom-field.ts
new file mode 100644
index 000000000..c05e9796c
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/create-custom-field.ts
@@ -0,0 +1,134 @@
+import { eq, max } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ customFieldDefinitionTable,
+ customFieldValueTable,
+ projectTable,
+ taskTable,
+} from "../../database/schema";
+
+async function createCustomField(
+ projectId: string,
+ name: string,
+ type: string,
+ required: boolean,
+ defaultValue?: string,
+ options?: string[],
+) {
+ const [project] = await db
+ .select({ id: projectTable.id })
+ .from(projectTable)
+ .where(eq(projectTable.id, projectId))
+ .limit(1);
+
+ if (!project) {
+ throw new HTTPException(404, { message: "Project not found" });
+ }
+
+ if (required && (defaultValue === undefined || defaultValue === null || defaultValue.trim() === "")) {
+ throw new HTTPException(400, { message: "Required fields must have a default value" });
+ }
+
+ if (defaultValue !== undefined && defaultValue !== null) {
+ const trimmedValue = defaultValue.trim();
+
+ if (trimmedValue) {
+ if (type === "number") {
+ const numberRegex = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
+ if (!numberRegex.test(trimmedValue)) {
+ throw new HTTPException(400, {
+ message:
+ "Default value must be a valid number for number type fields",
+ });
+ }
+ const parsed = Number(trimmedValue);
+ if (Number.isNaN(parsed) || !Number.isFinite(parsed)) {
+ throw new HTTPException(400, {
+ message:
+ "Default value must be a valid number for number type fields",
+ });
+ }
+ } else if (type === "boolean") {
+ if (trimmedValue !== "true" && trimmedValue !== "false") {
+ throw new HTTPException(400, {
+ message:
+ "Default value must be 'true' or 'false' for boolean type fields",
+ });
+ }
+ } else if (type === "date") {
+ const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
+ if (!dateRegex.test(trimmedValue)) {
+ const parsedDate = new Date(trimmedValue);
+ if (Number.isNaN(parsedDate.getTime())) {
+ throw new HTTPException(400, {
+ message:
+ "Default value must be a valid date in ISO format (YYYY-MM-DD)",
+ });
+ }
+ }
+ } else if (type === "dropdown") {
+ if (options && options.length > 0) {
+ const normalizedOptions = options.map((opt) => opt.trim());
+ if (!normalizedOptions.includes(trimmedValue)) {
+ throw new HTTPException(400, {
+ message: "Default value must be one of the dropdown options",
+ });
+ }
+ }
+ }
+ }
+ }
+
+ if (type === "dropdown" && (!options || options.length === 0)) {
+ throw new HTTPException(400, {
+ message: "Dropdown fields must have at least one option",
+ });
+ }
+
+ const [maxPositionResult] = await db
+ .select({ maxPosition: max(customFieldDefinitionTable.position) })
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.projectId, projectId));
+
+ const [field] = await db
+ .insert(customFieldDefinitionTable)
+ .values({
+ projectId,
+ name,
+ type,
+ required,
+ defaultValue: defaultValue ?? null,
+ options: options ?? null,
+ position: (maxPositionResult?.maxPosition ?? 0) + 1,
+ })
+ .returning();
+
+ if (!field) {
+ throw new HTTPException(500, { message: "Failed to create custom field" });
+ }
+
+ if (defaultValue !== undefined && defaultValue !== null) {
+ const tasks = await db
+ .select({ id: taskTable.id })
+ .from(taskTable)
+ .where(eq(taskTable.projectId, projectId));
+
+ if (tasks.length > 0) {
+ const valuesToInsert = tasks.map((task) => ({
+ taskId: task.id,
+ fieldId: field.id,
+ value: defaultValue,
+ }));
+
+ await db
+ .insert(customFieldValueTable)
+ .values(valuesToInsert)
+ .onConflictDoNothing();
+ }
+ }
+
+ return field;
+}
+
+export default createCustomField;
\ No newline at end of file
diff --git a/apps/api/src/custom-field/controllers/delete-custom-field.ts b/apps/api/src/custom-field/controllers/delete-custom-field.ts
new file mode 100644
index 000000000..32f589de9
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/delete-custom-field.ts
@@ -0,0 +1,49 @@
+import { eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { customFieldDefinitionTable, projectTable } from "../../database/schema";
+
+async function deleteCustomField(id: string) {
+ const [field] = await db
+ .select({
+ projectId: customFieldDefinitionTable.projectId,
+ workspaceId: projectTable.workspaceId,
+ })
+ .from(customFieldDefinitionTable)
+ .innerJoin(
+ projectTable,
+ eq(projectTable.id, customFieldDefinitionTable.projectId),
+ )
+ .where(eq(customFieldDefinitionTable.id, id))
+ .limit(1);
+
+ if (!field) {
+ throw new HTTPException(404, {
+ message: "Custom field or project not found",
+ });
+ }
+
+ if (!field.workspaceId) {
+ throw new HTTPException(400, {
+ message: "The project is not associated with a workspace",
+ });
+ }
+
+ const [deleted] = await db
+ .delete(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.id, id))
+ .returning();
+
+ if (!deleted) {
+ throw new HTTPException(404, {
+ message: "Custom field not found",
+ });
+ }
+
+ return {
+ ...deleted,
+ workspaceId: field.workspaceId,
+ };
+}
+
+export default deleteCustomField;
\ No newline at end of file
diff --git a/apps/api/src/custom-field/controllers/get-custom-field-filter-values.ts b/apps/api/src/custom-field/controllers/get-custom-field-filter-values.ts
new file mode 100644
index 000000000..cd2ae11b0
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/get-custom-field-filter-values.ts
@@ -0,0 +1,37 @@
+import { and, eq, isNotNull, ne } from "drizzle-orm";
+import db from "../../database";
+import {
+ customFieldDefinitionTable,
+ customFieldValueTable,
+} from "../../database/schema";
+
+export default async function getCustomFieldFilterValues(projectId: string) {
+ const fields = await db
+ .select()
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.projectId, projectId));
+
+ const result = await Promise.all(
+ fields.map(async (field) => {
+ const rawValues = await db
+ .selectDistinct({ value: customFieldValueTable.value })
+ .from(customFieldValueTable)
+ .where(
+ and(
+ eq(customFieldValueTable.fieldId, field.id),
+ isNotNull(customFieldValueTable.value),
+ ne(customFieldValueTable.value, ""),
+ ),
+ );
+
+ return {
+ fieldId: field.id,
+ fieldName: field.name,
+ fieldType: field.type,
+ values: rawValues.map((r) => r.value as string),
+ };
+ }),
+ );
+
+ return result;
+}
\ No newline at end of file
diff --git a/apps/api/src/custom-field/controllers/get-custom-field-values-by-task.ts b/apps/api/src/custom-field/controllers/get-custom-field-values-by-task.ts
new file mode 100644
index 000000000..8be404b45
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/get-custom-field-values-by-task.ts
@@ -0,0 +1,27 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import {
+ customFieldDefinitionTable,
+ customFieldValueTable,
+} from "../../database/schema";
+
+async function getCustomFieldValuesByTask(taskId: string) {
+ return db
+ .select({
+ id: customFieldValueTable.id,
+ taskId: customFieldValueTable.taskId,
+ fieldId: customFieldValueTable.fieldId,
+ value: customFieldValueTable.value,
+ fieldName: customFieldDefinitionTable.name,
+ fieldType: customFieldDefinitionTable.type,
+ fieldOptions: customFieldDefinitionTable.options,
+ })
+ .from(customFieldValueTable)
+ .innerJoin(
+ customFieldDefinitionTable,
+ eq(customFieldValueTable.fieldId, customFieldDefinitionTable.id),
+ )
+ .where(eq(customFieldValueTable.taskId, taskId));
+}
+
+export default getCustomFieldValuesByTask;
\ No newline at end of file
diff --git a/apps/api/src/custom-field/controllers/get-custom-fields-by-project.ts b/apps/api/src/custom-field/controllers/get-custom-fields-by-project.ts
new file mode 100644
index 000000000..75029ed8c
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/get-custom-fields-by-project.ts
@@ -0,0 +1,13 @@
+import { asc, eq } from "drizzle-orm";
+import db from "../../database";
+import { customFieldDefinitionTable } from "../../database/schema";
+
+async function getCustomFieldsByProject(projectId: string) {
+ return db
+ .select()
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.projectId, projectId))
+ .orderBy(asc(customFieldDefinitionTable.position));
+}
+
+export default getCustomFieldsByProject;
diff --git a/apps/api/src/custom-field/controllers/reorder-custom-field.ts b/apps/api/src/custom-field/controllers/reorder-custom-field.ts
new file mode 100644
index 000000000..970432942
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/reorder-custom-field.ts
@@ -0,0 +1,39 @@
+import { and, eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { customFieldDefinitionTable } from "../../database/schema";
+
+async function reorderCustomFields(
+ projectId: string,
+ customFields: Array<{ id: string; position: number }>,
+) {
+ await db.transaction(async (tx) => {
+ for (const field of customFields) {
+ const [updated] = await tx
+ .update(customFieldDefinitionTable)
+ .set({ position: field.position })
+ .where(
+ and(
+ eq(customFieldDefinitionTable.id, field.id),
+ eq(customFieldDefinitionTable.projectId, projectId),
+ ),
+ )
+ .returning({ id: customFieldDefinitionTable.id });
+
+ if (!updated) {
+ throw new HTTPException(400, {
+ message: `Custom field ${field.id} does not belong to this project`,
+ });
+ }
+ }
+ });
+
+ const updated = await db.query.customFieldDefinitionTable.findMany({
+ where: eq(customFieldDefinitionTable.projectId, projectId),
+ orderBy: (columns, { asc }) => [asc(columns.position)],
+ });
+
+ return updated;
+}
+
+export default reorderCustomFields;
\ No newline at end of file
diff --git a/apps/api/src/custom-field/controllers/set-custom-field-value.ts b/apps/api/src/custom-field/controllers/set-custom-field-value.ts
new file mode 100644
index 000000000..fe661b7d3
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/set-custom-field-value.ts
@@ -0,0 +1,103 @@
+import { HTTPException } from "hono/http-exception";
+import { eq, sql } from "drizzle-orm";
+
+import db from "../../database";
+import {
+ taskTable,
+ customFieldDefinitionTable,
+ customFieldValueTable,
+} from "../../database/schema";
+
+async function setCustomFieldValue(
+ taskId: string,
+ fieldId: string,
+ value: string,
+) {
+ const [task] = await db
+ .select({
+ projectId: taskTable.projectId,
+ })
+ .from(taskTable)
+ .where(eq(taskTable.id, taskId))
+ .limit(1);
+
+ if (!task) {
+ throw new HTTPException(404, {
+ message: "Task not found",
+ });
+ }
+
+ const [field] = await db
+ .select()
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.id, fieldId))
+ .limit(1);
+
+ if (!field || field.projectId !== task.projectId) {
+ throw new HTTPException(404, {
+ message: "Custom field not found",
+ });
+ }
+
+ const normalizedValue = value.trim();
+
+ if (field.required && normalizedValue.length === 0) {
+ throw new HTTPException(400, {
+ message: "This custom field is required",
+ });
+ }
+
+ if (
+ field.type === "dropdown" &&
+ normalizedValue.length > 0 &&
+ Array.isArray(field.options) &&
+ !field.options.includes(normalizedValue)
+ ) {
+ throw new HTTPException(400, {
+ message: "Invalid option for this custom field",
+ });
+ }
+
+ if (
+ field.type === "number" &&
+ normalizedValue.length > 0 &&
+ Number.isNaN(Number(normalizedValue))
+ ) {
+ throw new HTTPException(400, {
+ message: "Value must be a valid number",
+ });
+ }
+
+ if (
+ field.type === "boolean" &&
+ normalizedValue.length > 0 &&
+ normalizedValue !== "true" &&
+ normalizedValue !== "false"
+ ) {
+ throw new HTTPException(400, {
+ message: "Value must be true or false",
+ });
+ }
+
+ const [result] = await db
+ .insert(customFieldValueTable)
+ .values({
+ taskId,
+ fieldId,
+ value: normalizedValue,
+ })
+ .onConflictDoUpdate({
+ target: [
+ customFieldValueTable.taskId,
+ customFieldValueTable.fieldId,
+ ],
+ set: {
+ value: sql`excluded.value`,
+ },
+ })
+ .returning();
+
+ return result;
+}
+
+export default setCustomFieldValue;
\ No newline at end of file
diff --git a/apps/api/src/custom-field/index.ts b/apps/api/src/custom-field/index.ts
new file mode 100644
index 000000000..3964aa15f
--- /dev/null
+++ b/apps/api/src/custom-field/index.ts
@@ -0,0 +1,278 @@
+import { Hono } from "hono";
+import { describeRoute, resolver, validator } from "hono-openapi";
+import * as v from "valibot";
+import { requireWorkspacePermission } from "../utils/require-workspace-permission";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+import createCustomField from "./controllers/create-custom-field";
+import deleteCustomField from "./controllers/delete-custom-field";
+import getCustomFieldFilterValues from "./controllers/get-custom-field-filter-values";
+import getCustomFieldValuesByTask from "./controllers/get-custom-field-values-by-task";
+import getCustomFieldsByProject from "./controllers/get-custom-fields-by-project";
+import reorderCustomFields from "./controllers/reorder-custom-field";
+import setCustomFieldValue from "./controllers/set-custom-field-value";
+
+const customFieldDefinitionSchema = v.object({
+ id: v.string(),
+ projectId: v.string(),
+ name: v.string(),
+ type: v.string(),
+ required: v.boolean(),
+ defaultValue: v.nullable(v.string()),
+ options: v.nullable(v.any()),
+ position: v.number(),
+ createdAt: v.date(),
+ updatedAt: v.date(),
+});
+
+const customFieldValueSchema = v.object({
+ id: v.string(),
+ taskId: v.string(),
+ fieldId: v.string(),
+ value: v.nullable(v.string()),
+ fieldName: v.string(),
+ fieldType: v.string(),
+ fieldOptions: v.nullable(v.any()),
+});
+
+const customField = new Hono<{
+ Variables: {
+ userId: string;
+ workspaceId: string;
+ };
+}>()
+ .get(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "getCustomFieldsByProject",
+ tags: ["Custom Fields"],
+ description: "Get all custom field definitions for a project",
+ responses: {
+ 200: {
+ description: "List of custom field definitions",
+ content: {
+ "application/json": {
+ schema: resolver(v.array(customFieldDefinitionSchema)),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const fields = await getCustomFieldsByProject(projectId);
+ return c.json(fields);
+ },
+ )
+ .get(
+ "/task/:taskId",
+ describeRoute({
+ operationId: "getCustomFieldValuesByTask",
+ tags: ["Custom Fields"],
+ description: "Get all custom field values for a task",
+ responses: {
+ 200: {
+ description: "List of custom field values with their definitions",
+ content: {
+ "application/json": {
+ schema: resolver(v.array(customFieldValueSchema)),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ taskId: v.string() })),
+ workspaceAccess.fromTaskId("taskId"),
+ async (c) => {
+ const { taskId } = c.req.valid("param");
+ const values = await getCustomFieldValuesByTask(taskId);
+ return c.json(values);
+ },
+ )
+ .get(
+ "/project/:projectId/filter-values",
+ describeRoute({
+ operationId: "getCustomFieldFilterValues",
+ tags: ["Custom Fields"],
+ description:
+ "Get distinct values actually used by tasks for each custom field of a project (for filters)",
+ responses: {
+ 200: {
+ description: "List of custom fields with their distinct used values",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.array(
+ v.object({
+ fieldId: v.string(),
+ fieldName: v.string(),
+ fieldType: v.string(),
+ values: v.array(v.string()),
+ }),
+ ),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const filterValues = await getCustomFieldFilterValues(projectId);
+ return c.json(filterValues);
+ },
+ )
+ .post(
+ "/",
+ describeRoute({
+ operationId: "createCustomField",
+ tags: ["Custom Fields"],
+ description: "Create a new custom field definition for a project",
+ responses: {
+ 200: {
+ description: "Custom field created successfully",
+ content: {
+ "application/json": {
+ schema: resolver(customFieldDefinitionSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ projectId: v.string(),
+ name: v.string(),
+ type: v.picklist(["text", "number", "date", "dropdown", "boolean"]),
+ required: v.optional(v.boolean(), false),
+ defaultValue: v.optional(v.string()),
+ options: v.optional(v.array(v.string())),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ project: ["update"] }),
+ async (c) => {
+ const { projectId, name, type, required, defaultValue, options } =
+ c.req.valid("json");
+
+ const field = await createCustomField(
+ projectId,
+ name,
+ type,
+ required,
+ defaultValue,
+ options,
+ );
+ return c.json(field);
+ },
+ )
+ .put(
+ "/reorder/:projectId",
+ describeRoute({
+ operationId: "reorderCustomFields",
+ tags: ["Custom Fields"],
+ description: "Reorder custom fields in a project",
+ responses: {
+ 200: {
+ description: "Custom fields reordered successfully",
+ content: {
+ "application/json": { schema: resolver(v.any()) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ validator(
+ "json",
+ v.object({
+ fields: v.array(
+ v.object({
+ id: v.string(),
+ position: v.number(),
+ }),
+ ),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ project: ["update"] }),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const { fields } = c.req.valid("json");
+ const result = await reorderCustomFields(projectId, fields);
+ return c.json(result);
+ },
+ )
+ .put(
+ "/value",
+ describeRoute({
+ operationId: "setCustomFieldValue",
+ tags: ["Custom Fields"],
+ description: "Set (create or update) a custom field value for a task",
+ responses: {
+ 200: {
+ description: "Custom field value set successfully",
+ content: {
+ "application/json": {
+ schema: resolver(
+ v.object({
+ id: v.string(),
+ taskId: v.string(),
+ fieldId: v.string(),
+ value: v.nullable(v.string()),
+ }),
+ ),
+ },
+ },
+ },
+ },
+ }),
+ validator(
+ "json",
+ v.object({
+ taskId: v.string(),
+ fieldId: v.string(),
+ value: v.string(),
+ }),
+ ),
+ workspaceAccess.fromTaskId("taskId"),
+ requireWorkspacePermission({ task: ["update"] }),
+ async (c) => {
+ const { taskId, fieldId, value } = c.req.valid("json");
+
+ const result = await setCustomFieldValue(taskId, fieldId, value);
+
+ return c.json(result);
+ },
+ )
+ .delete(
+ "/:id",
+ describeRoute({
+ operationId: "deleteCustomField",
+ tags: ["Custom Fields"],
+ description: "Delete a custom field definition by ID",
+ responses: {
+ 200: {
+ description: "Custom field deleted successfully",
+ content: {
+ "application/json": {
+ schema: resolver(customFieldDefinitionSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ id: v.string() })),
+ workspaceAccess.fromCustomField(),
+ requireWorkspacePermission({ project: ["update"] }),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ const field = await deleteCustomField(id);
+ return c.json(field);
+ },
+ );
+
+export default customField;
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index 487211735..3dde30f57 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -8,6 +8,8 @@ import {
assetTableRelations,
columnTableRelations,
commentTableRelations,
+ customFieldDefinitionTableRelations,
+ customFieldValueTableRelations,
externalLinkTableRelations,
githubIntegrationTableRelations,
integrationTableRelations,
@@ -40,6 +42,8 @@ import {
billingEventTable,
columnTable,
commentTable,
+ customFieldDefinitionTable,
+ customFieldValueTable,
deviceCodeTable,
externalLinkTable,
githubIntegrationTable,
@@ -128,6 +132,10 @@ export const schema = {
workspaceRoleTableRelations,
workspaceTableRelations,
workspaceUserTableRelations,
+ customFieldDefinitionTable,
+ customFieldValueTable,
+ customFieldDefinitionTableRelations,
+ customFieldValueTableRelations,
};
type DatabaseInstance = ReturnType<typeof drizzle<typeof schema>>;
diff --git a/apps/api/src/database/relations.ts b/apps/api/src/database/relations.ts
index 76098a344..cf0c48478 100644
--- a/apps/api/src/database/relations.ts
+++ b/apps/api/src/database/relations.ts
@@ -6,6 +6,8 @@ import {
assetTable,
columnTable,
commentTable,
+ customFieldDefinitionTable,
+ customFieldValueTable,
externalLinkTable,
githubIntegrationTable,
integrationTable,
@@ -156,6 +158,7 @@ export const taskTableRelations = relations(taskTable, ({ one, many }) => ({
sourceRelations: many(taskRelationTable, { relationName: "sourceTask" }),
targetRelations: many(taskRelationTable, { relationName: "targetTask" }),
remindersSent: many(taskReminderSentTable),
+ customFieldValues: many(customFieldValueTable),
}));
export const timeEntryTableRelations = relations(timeEntryTable, ({ one }) => ({
@@ -392,3 +395,28 @@ export const commentTableRelations = relations(commentTable, ({ one }) => ({
references: [userTable.id],
}),
}));
+
+export const customFieldDefinitionTableRelations = relations(
+ customFieldDefinitionTable,
+ ({ one, many }) => ({
+ project: one(projectTable, {
+ fields: [customFieldDefinitionTable.projectId],
+ references: [projectTable.id],
+ }),
+ values: many(customFieldValueTable),
+ }),
+);
+
+export const customFieldValueTableRelations = relations(
+ customFieldValueTable,
+ ({ one }) => ({
+ field: one(customFieldDefinitionTable, {
+ fields: [customFieldValueTable.fieldId],
+ references: [customFieldDefinitionTable.id],
+ }),
+ task: one(taskTable, {
+ fields: [customFieldValueTable.taskId],
+ references: [taskTable.id],
+ }),
+ }),
+);
diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.ts
index 51f591a65..555fbfacd 100644
--- a/apps/api/src/database/schema.ts
+++ b/apps/api/src/database/schema.ts
@@ -1097,3 +1097,65 @@ export const organizationRoleRelations = relations(
}),
}),
);
+
+export const customFieldDefinitionTable = pgTable(
+ "custom_field_definition",
+ {
+ id: text("id")
+ .$defaultFn(() => createId())
+ .primaryKey(),
+ projectId: text("project_id")
+ .notNull()
+ .references(() => projectTable.id, {
+ onDelete: "cascade",
+ onUpdate: "cascade",
+ }),
+ name: text("name").notNull(),
+ type: text("type").notNull(), // 'text' | 'number' | 'date' | 'dropdown' | 'boolean'
+ required: boolean("required").default(false).notNull(),
+ defaultValue: text("default_value"),
+ options: jsonb("options"),
+ position: integer("position").default(0).notNull(),
+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),
+ updatedAt: timestamp("updated_at", { mode: "date" })
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
+ },
+ (table) => [index("custom_field_def_projectId_idx").on(table.projectId)],
+);
+
+export const customFieldValueTable = pgTable(
+ "custom_field_value",
+ {
+ id: text("id")
+ .$defaultFn(() => createId())
+ .primaryKey(),
+ taskId: text("task_id")
+ .notNull()
+ .references(() => taskTable.id, {
+ onDelete: "cascade",
+ onUpdate: "cascade",
+ }),
+ fieldId: text("field_id")
+ .notNull()
+ .references(() => customFieldDefinitionTable.id, {
+ onDelete: "cascade",
+ onUpdate: "cascade",
+ }),
+ value: text("value"),
+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),
+ updatedAt: timestamp("updated_at", { mode: "date" })
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
+ },
+ (table) => [
+ index("custom_field_value_taskId_idx").on(table.taskId),
+ index("custom_field_value_fieldId_idx").on(table.fieldId),
+ unique("custom_field_value_task_field_unique").on(
+ table.taskId,
+ table.fieldId,
+ ),
+ ],
+);
\ No newline at end of file
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 308df6a85..2a8ff72c9 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -24,6 +24,7 @@ import billing from "./billing";
import column from "./column";
import comment from "./comment";
import config from "./config";
+import customField from "./custom-field";
import db, { getDatabase, schema } from "./database";
import { prepareDatabaseStartup } from "./database/prepare-database-startup";
import { waitForDatabase } from "./database/wait-for-database";
@@ -589,6 +590,7 @@ export function createApp() {
const workflowRuleApi = api.route("/workflow-rule", workflowRule);
const invitationApi = api.route("/invitation", invitation);
const workspaceApi = api.route("/workspace", workspace);
+ const customFieldApi = api.route("/custom-field", customField);
app.route(
"/",
@@ -753,6 +755,7 @@ export function createApp() {
timeEntryApi,
workflowRuleApi,
workspaceApi,
+ customFieldApi,
oauthApi,
};
}
@@ -870,6 +873,7 @@ const {
timeEntryApi,
workflowRuleApi,
workspaceApi,
+ customFieldApi,
oauthApi,
} = createdApp;
@@ -907,6 +911,7 @@ export type AppType =
| typeof workflowRuleApi
| typeof invitationApi
| typeof workspaceApi
+ | typeof customFieldApi
| typeof publicProjectApi
| typeof invitationPublicApi
| typeof oauthApi;
diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.ts
index b66825f7e..889518b62 100644
--- a/apps/api/src/task/controllers/create-task.ts
+++ b/apps/api/src/task/controllers/create-task.ts
@@ -1,11 +1,40 @@
import { and, eq, max } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
-import { columnTable, taskTable, userTable } from "../../database/schema";
+import {
+ columnTable,
+ customFieldValueTable,
+ taskTable,
+ userTable,
+} from "../../database/schema";
import { publishEvent } from "../../events";
-import { assertValidTaskStatus } from "../validate-task-fields";
+import {
+ assertRequiredCustomFields,
+ assertValidTaskStatus,
+} from "../validate-task-fields";
import { claimTaskNumber } from "./claim-task-numbers";
+type CustomFieldInput = {
+ fieldId: string;
+ value: string;
+};
+
+function deduplicateCustomFields(
+ customFields?: CustomFieldInput[],
+): CustomFieldInput[] | undefined {
+ if (!customFields) {
+ return undefined;
+ }
+
+ const fieldsById = new Map<string, CustomFieldInput>();
+
+ for (const customField of customFields) {
+ fieldsById.set(customField.fieldId, customField);
+ }
+
+ return Array.from(fieldsById.values());
+}
+
async function createTask({
projectId,
currentUserId,
@@ -16,6 +45,7 @@ async function createTask({
dueDate,
description,
priority,
+ customFields,
}: {
projectId: string;
currentUserId: string;
@@ -26,12 +56,16 @@ async function createTask({
dueDate?: Date;
description?: string;
priority?: string;
+ customFields?: CustomFieldInput[];
}) {
const resolvedStatus = status || "to-do";
const resolvedPriority = priority || "no-priority";
+ const normalizedCustomFields = deduplicateCustomFields(customFields);
await assertValidTaskStatus(resolvedStatus, projectId);
+ await assertRequiredCustomFields(projectId, normalizedCustomFields);
+
const [assignee] = await db
.select({ name: userTable.name })
.from(userTable)
@@ -78,6 +112,16 @@ async function createTask({
})
.returning();
+ if (task && normalizedCustomFields?.length) {
+ await tx.insert(customFieldValueTable).values(
+ normalizedCustomFields.map(({ fieldId, value }) => ({
+ taskId: task.id,
+ fieldId,
+ value,
+ })),
+ );
+ }
+
return task;
});
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index d984a02fe..89997f72d 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -197,6 +197,14 @@ const task = new Hono<{
priority: v.picklist(VALID_PRIORITIES),
status: v.string(),
userId: v.optional(v.string()),
+ customFields: v.optional(
+ v.array(
+ v.object({
+ fieldId: v.string(),
+ value: v.string(),
+ }),
+ ),
+ ),
}),
),
workspaceAccess.fromProject("projectId"),
@@ -212,6 +220,7 @@ const task = new Hono<{
priority,
status,
userId,
+ customFields,
} = c.req.valid("json");
const parsedStartDate =
@@ -235,6 +244,7 @@ const task = new Hono<{
dueDate: parsedDueDate,
priority,
status,
+ customFields,
});
return c.json(task);
@@ -342,6 +352,14 @@ const task = new Hono<{
projectId: v.string(),
position: v.number(),
userId: v.optional(v.string()),
+ customFields: v.optional(
+ v.array(
+ v.object({
+ fieldId: v.string(),
+ value: v.string(),
+ }),
+ ),
+ ),
}),
),
workspaceAccess.fromTask(),
diff --git a/apps/api/src/task/validate-task-fields.ts b/apps/api/src/task/validate-task-fields.ts
index 1697f8a96..9eb506247 100644
--- a/apps/api/src/task/validate-task-fields.ts
+++ b/apps/api/src/task/validate-task-fields.ts
@@ -1,7 +1,85 @@
import { asc, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../database";
-import { columnTable } from "../database/schema";
+import { columnTable, customFieldDefinitionTable } from "../database/schema";
+
+export async function assertRequiredCustomFields(
+ projectId: string,
+ customFields: { fieldId: string; value: string }[] = [],
+): Promise<void> {
+ const allFields = await db
+ .select({
+ id: customFieldDefinitionTable.id,
+ name: customFieldDefinitionTable.name,
+ type: customFieldDefinitionTable.type,
+ required: customFieldDefinitionTable.required,
+ defaultValue: customFieldDefinitionTable.defaultValue,
+ options: customFieldDefinitionTable.options,
+ })
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.projectId, projectId));
+
+ const validFieldIds = new Set(allFields.map((f) => f.id));
+
+ for (const cf of customFields) {
+ if (!validFieldIds.has(cf.fieldId)) {
+ throw new HTTPException(400, {
+ message: `Field "${cf.fieldId}" does not belong to this project.`,
+ });
+ }
+ }
+
+ for (const cf of customFields) {
+ if (cf.value.trim() === "") continue;
+ const def = allFields.find((f) => f.id === cf.fieldId);
+ if (!def) continue;
+
+ if (def.type === "number" && Number.isNaN(Number(cf.value))) {
+ throw new HTTPException(400, {
+ message: `Custom field "${def.name}" expects a number, got "${cf.value}".`,
+ });
+ }
+ if (def.type === "boolean" && !["true", "false"].includes(cf.value)) {
+ throw new HTTPException(400, {
+ message: `Custom field "${def.name}" expects "true" or "false", got "${cf.value}".`,
+ });
+ }
+ if (def.type === "date" && Number.isNaN(Date.parse(cf.value))) {
+ throw new HTTPException(400, {
+ message: `Custom field "${def.name}" expects a valid ISO 8601 date, got "${cf.value}".`,
+ });
+ }
+ if (def.type === "dropdown") {
+ const options: string[] = Array.isArray(def.options)
+ ? def.options
+ : typeof def.options === "string"
+ ? JSON.parse(def.options)
+ : [];
+
+ if (!options.includes(cf.value.trim())) {
+ throw new HTTPException(400, {
+ message: `Custom field "${def.name}" expects one of: ${options.join(", ")}, got "${cf.value}".`,
+ });
+ }
+ }
+ }
+
+ const providedIds = new Set(
+ customFields.filter((f) => f.value.trim() !== "").map((f) => f.fieldId),
+ );
+
+ for (const field of allFields.filter((f) => f.required)) {
+ const isSatisfied =
+ providedIds.has(field.id) ||
+ (field.defaultValue != null && field.defaultValue.trim() !== "");
+
+ if (!isSatisfied) {
+ throw new HTTPException(400, {
+ message: `Custom field "${field.name}" is required to create a task.`,
+ });
+ }
+ }
+}
export const VALID_PRIORITIES = [
"no-priority",
diff --git a/apps/api/src/utils/workspace-access-middleware.ts b/apps/api/src/utils/workspace-access-middleware.ts
index 89ed0eeeb..e431cb1a9 100644
--- a/apps/api/src/utils/workspace-access-middleware.ts
+++ b/apps/api/src/utils/workspace-access-middleware.ts
@@ -18,7 +18,8 @@ type WorkspaceIdSource =
| "activity"
| "comment"
| "column"
- | "workflowRule";
+ | "workflowRule"
+ | "customField";
idKey: string;
}
| {
@@ -137,7 +138,8 @@ async function lookupWorkspaceId(
| "activity"
| "comment"
| "column"
- | "workflowRule",
+ | "workflowRule"
+ | "customField",
id: string,
): Promise<string | null> {
try {
@@ -267,6 +269,24 @@ async function lookupWorkspaceId(
return workflowRule?.workspaceId || null;
}
+ case "customField": {
+ const [field] = await db
+ .select({
+ workspaceId: schema.projectTable.workspaceId,
+ })
+ .from(schema.customFieldDefinitionTable)
+ .innerJoin(
+ schema.projectTable,
+ eq(
+ schema.customFieldDefinitionTable.projectId,
+ schema.projectTable.id,
+ ),
+ )
+ .where(eq(schema.customFieldDefinitionTable.id, id))
+ .limit(1);
+ return field?.workspaceId || null;
+ }
+
default:
return null;
}
@@ -359,4 +379,17 @@ export const workspaceAccess = {
{ type: "query", key: "workspaceId" },
],
}),
+
+ fromCustomField: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [{ type: "lookup", resource: "customField", idKey }],
+ }),
+
+ fromProjectId: (idKey = "projectId") =>
+ workspaceAccessMiddleware({
+ sources: [
+ { type: "lookup", resource: "project", idKey },
+ { type: "query", key: "workspaceId" },
+ ],
+ }),
};
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index f070001a4..9fb6a58d5 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -90,6 +90,211 @@
"organizationId",
"createdAt"
]
+ },
+ "CustomFieldDefinition": {
+ "type": "object",
+ "required": [
+ "id",
+ "projectId",
+ "name",
+ "type",
+ "required",
+ "defaultValue",
+ "options",
+ "position",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "projectId": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "defaultValue": {
+ "type": "string",
+ "nullable": true
+ },
+ "options": {
+ "nullable": true
+ },
+ "position": {
+ "type": "number"
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time"
+ }
+ }
+ },
+ "CustomFieldValue": {
+ "type": "object",
+ "required": [
+ "id",
+ "taskId",
+ "fieldId",
+ "value",
+ "fieldName",
+ "fieldType",
+ "fieldOptions"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "taskId": {
+ "type": "string"
+ },
+ "fieldId": {
+ "type": "string"
+ },
+ "value": {
+ "type": "string",
+ "nullable": true
+ },
+ "fieldName": {
+ "type": "string"
+ },
+ "fieldType": {
+ "type": "string"
+ },
+ "fieldOptions": {
+ "nullable": true
+ }
+ }
+ },
+ "CustomFieldFilterValues": {
+ "type": "object",
+ "required": [
+ "fieldId",
+ "fieldName",
+ "fieldType",
+ "values"
+ ],
+ "properties": {
+ "fieldId": {
+ "type": "string"
+ },
+ "fieldName": {
+ "type": "string"
+ },
+ "fieldType": {
+ "type": "string"
+ },
+ "values": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "CreateCustomFieldBody": {
+ "type": "object",
+ "required": [
+ "projectId",
+ "name",
+ "type"
+ ],
+ "properties": {
+ "projectId": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "text",
+ "number",
+ "date",
+ "dropdown",
+ "boolean"
+ ]
+ },
+ "required": {
+ "type": "boolean",
+ "default": false
+ },
+ "defaultValue": {
+ "type": "string"
+ },
+ "options": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "SetCustomFieldValueBody": {
+ "type": "object",
+ "required": [
+ "taskId",
+ "fieldId",
+ "value"
+ ],
+ "properties": {
+ "taskId": {
+ "type": "string"
+ },
+ "fieldId": {
+ "type": "string"
+ },
+ "value": {
+ "type": "string",
+ "description": "String representation of the value. For boolean fields: 'true' or 'false'. For number fields: a valid numeric string. For dropdown fields: one of the field's defined options."
+ }
+ }
+ },
+ "CustomFieldValueResult": {
+ "type": "object",
+ "required": [
+ "id",
+ "taskId",
+ "fieldId",
+ "value",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "taskId": {
+ "type": "string"
+ },
+ "fieldId": {
+ "type": "string"
+ },
+ "value": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ },
+ "HTTPError": {
+ "type": "object",
+ "properties": {
+ "message": {
+ "type": "string"
+ }
+ }
}
}
},
@@ -2921,6 +3126,302 @@
"summary": "Delete Column"
}
},
+ "/custom-field/project/{projectId}": {
+ "get": {
+ "operationId": "getCustomFieldsByProject",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Get fields by project",
+ "description": "Get all custom field definitions for a project",
+ "parameters": [
+ {
+ "name": "projectId",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of custom field definitions",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CustomFieldDefinition"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/custom-field/task/{taskId}": {
+ "get": {
+ "operationId": "getCustomFieldValuesByTask",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Get field values by task",
+ "description": "Get all custom field values for a task",
+ "parameters": [
+ {
+ "name": "taskId",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of custom field values with their definitions",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CustomFieldValue"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/custom-field/project/{projectId}/filter-values": {
+ "get": {
+ "operationId": "getCustomFieldFilterValues",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Get custom field filter values",
+ "description": "Get distinct values actually used by tasks for each custom field of a project (for filters)",
+ "parameters": [
+ {
+ "name": "projectId",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of custom fields with their distinct used values",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CustomFieldFilterValues"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/custom-field/": {
+ "post": {
+ "operationId": "createCustomField",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Create a custom field",
+ "description": "Create a new custom field definition for a project",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCustomFieldBody"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Custom field created successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomFieldDefinition"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/custom-field/value": {
+ "put": {
+ "operationId": "setCustomFieldValue",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Set a custom field value",
+ "description": "Set (create or update) a custom field value for a task",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetCustomFieldValueBody"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Custom field value set successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomFieldValueResult"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Validation error (required field empty, invalid dropdown option, invalid number, invalid boolean)",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Custom field not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/custom-field/reorder/{projectId}": {
+ "put": {
+ "operationId": "reorderCustomFields",
+ "tags": [
+ "Custom Fields"
+ ],
+ "description": "Reorder custom fields in a project",
+ "responses": {
+ "200": {
+ "description": "Custom fields reordered successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object"
+ }
+ }
+ }
+ }
+ },
+ "parameters": [
+ {
+ "in": "path",
+ "name": "projectId",
+ "schema": {
+ "type": "string"
+ },
+ "required": true
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "fields": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "position": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "id",
+ "position"
+ ]
+ }
+ }
+ },
+ "required": [
+ "fields"
+ ]
+ }
+ }
+ }
+ },
+ "summary": "Reorder Custom Fields"
+ }
+ },
+ "/custom-field/{id}": {
+ "delete": {
+ "operationId": "deleteCustomField",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Delete a custom field",
+ "description": "Delete a custom field definition by ID",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Custom field deleted successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomFieldDefinition"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Custom field not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/activity/{taskId}": {
"get": {
"operationId": "getActivities",
diff --git a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
index 95de5bd80..bd7894a78 100644
--- a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
+++ b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
@@ -2,7 +2,12 @@ import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useNavigate } from "@tanstack/react-router";
import { format } from "date-fns";
-import { Calendar, CalendarClock, CalendarX } from "lucide-react";
+import {
+ Calendar,
+ CalendarClock,
+ CalendarX,
+ SlidersHorizontal,
+} from "lucide-react";
import { type CSSProperties, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -16,7 +21,13 @@ import {
} from "@/components/ui/alert-dialog";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@/components/ui/preview-card";
import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
+import useGetCustomFieldValuesByTask from "@/hooks/queries/custom-field/use-get-custom-field-values-by-task";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
import { cn } from "@/lib/cn";
@@ -80,6 +91,14 @@ export default function BacklogTaskRow({ task }: BacklogTaskRowProps) {
);
}, [workspaceUsers, task.userId]);
+ const { data: customFieldValues = [] } = useGetCustomFieldValuesByTask(
+ task.id,
+ );
+
+ const activeCustomFieldValues = useMemo(() => {
+ return customFieldValues.filter((f) => f.value !== null && f.value !== "");
+ }, [customFieldValues]);
+
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition: transition || "transform 200ms cubic-bezier(0.23, 1, 0.32, 1)",
@@ -198,6 +217,39 @@ export default function BacklogTaskRow({ task }: BacklogTaskRowProps) {
</div>
)}
+ {activeCustomFieldValues.length > 0 && (
+ <HoverCard openDelay={200} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <span className="inline-flex items-center gap-1 rounded border border-border/70 bg-muted/55 px-2 py-1 text-[10px] font-medium text-muted-foreground cursor-default">
+ <SlidersHorizontal className="w-3 h-3" />
+ <span>{activeCustomFieldValues.length}</span>
+ </span>
+ </HoverCardTrigger>
+ <HoverCardContent
+ className="w-fit p-2.5"
+ side="bottom"
+ onClick={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <div className="space-y-1.5">
+ {activeCustomFieldValues.map((field) => (
+ <div
+ key={field.id}
+ className="flex items-center justify-between gap-2 text-xs"
+ >
+ <span className="font-medium text-muted-foreground truncate">
+ {field.fieldName}
+ </span>
+ <span className="text-foreground truncate max-w-24">
+ {field.value}
+ </span>
+ </div>
+ ))}
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+ )}
+
{showAssignees && (
<div className="flex-shrink-0">
{task.userId ? (
diff --git a/apps/web/src/components/board/board-toolbar.tsx b/apps/web/src/components/board/board-toolbar.tsx
index 2caeaaa31..10e437f44 100644
--- a/apps/web/src/components/board/board-toolbar.tsx
+++ b/apps/web/src/components/board/board-toolbar.tsx
@@ -2,6 +2,7 @@ import { Filter, PanelsTopLeft, Rows3, X } from "lucide-react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import SortControl from "@/components/common/sort-control";
+import type { CustomFieldDefinition } from "@/components/project/custom-field-editor";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
DropdownMenu,
@@ -51,6 +52,7 @@ type BoardToolbarProps = {
value: BoardFilters[keyof BoardFilters],
) => void;
updateLabelFilter: (labelId: string) => void;
+ updateCustomFieldFilter: (fieldId: string, value: string) => void;
clearFilters: () => void;
hasActiveFilters: boolean;
users?: ActiveUsers;
@@ -59,6 +61,8 @@ type BoardToolbarProps = {
setViewMode: (mode: "board" | "list") => void;
sort: SortConfig;
onSortChange: (sort: SortConfig) => void;
+ customFieldDefinitions?: CustomFieldDefinition[];
+ usedCustomFieldValues?: Record<string, string[]>;
};
function CheckSlot({ checked }: { checked: boolean }) {
@@ -121,7 +125,9 @@ function StackedIcons({
{items.slice(0, 3).map((item) => (
<span
key={item.id}
- className={`inline-flex size-4 items-center justify-center rounded-full bg-background ${itemClassName ?? ""}`}
+ className={`inline-flex size-4 items-center justify-center rounded-full bg-background ${
+ itemClassName ?? ""
+ }`}
>
{item.node}
</span>
@@ -135,6 +141,7 @@ export default function BoardToolbar({
filters,
updateFilter,
updateLabelFilter,
+ updateCustomFieldFilter,
clearFilters,
hasActiveFilters,
users,
@@ -143,6 +150,8 @@ export default function BoardToolbar({
setViewMode,
sort,
onSortChange,
+ customFieldDefinitions = [],
+ usedCustomFieldValues = {},
}: BoardToolbarProps) {
const { t } = useTranslation();
const selectedStatusIds = filters.status ?? [];
@@ -150,6 +159,15 @@ export default function BoardToolbar({
const selectedAssigneeIds = filters.assignee ?? [];
const selectedDueDateFilters = filters.dueDate ?? [];
+ const filterableCustomFields = customFieldDefinitions;
+
+ const activeCustomFieldCount = filters.customFields
+ ? Object.values(filters.customFields).reduce(
+ (sum, vals) => sum + (vals?.length ?? 0),
+ 0,
+ )
+ : 0;
+
const getStatusDisplayName = (statusId: string) => {
const column = project?.columns?.find((col) => col.id === statusId);
return column?.name || statusId;
@@ -251,6 +269,20 @@ export default function BoardToolbar({
for (const labelId of filters.labels) updateLabelFilter(labelId);
};
+ const clearCustomFieldFilter = (fieldId: string) => {
+ const current = filters.customFields ?? {};
+ const updated = { ...current };
+ delete updated[fieldId];
+ updateFilter(
+ "customFields",
+ Object.keys(updated).length > 0 ? updated : null,
+ );
+ };
+
+ const clearAllCustomFieldFilters = () => {
+ updateFilter("customFields", null);
+ };
+
return (
<div className="border-border/80 border-b bg-card/80 backdrop-blur supports-[backdrop-filter]:bg-card/70">
<div className="flex min-h-10 items-center px-2 py-1.5 md:px-3">
@@ -514,6 +546,128 @@ export default function BoardToolbar({
</DropdownMenuSubContent>
</DropdownMenuSub>
+ {filterableCustomFields.length > 0 && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="h-8 rounded-md text-sm">
+ <span className="flex flex-1 items-center justify-between gap-2">
+ <span>{t("tasks:common.customFields")}</span>
+ {activeCustomFieldCount > 0 && (
+ <span className="ml-auto inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground">
+ {activeCustomFieldCount}
+ </span>
+ )}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-52">
+ {activeCustomFieldCount > 0 && (
+ <>
+ <button
+ className="inline-flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left text-xs text-muted-foreground hover:bg-accent/60 hover:text-foreground"
+ onClick={clearAllCustomFieldFilters}
+ type="button"
+ >
+ {t("common:actions.clearAllFilters", {
+ defaultValue: "Clear all",
+ })}
+ </button>
+ <DropdownMenuSeparator />
+ </>
+ )}
+
+ {filterableCustomFields.map((field) => {
+ const selectedValues =
+ filters.customFields?.[field.id] ?? [];
+
+ let displayOptions: string[] = [];
+ if (field.type === "dropdown") {
+ displayOptions = field.options ?? [];
+ } else if (field.type === "boolean") {
+ displayOptions = ["true", "false"];
+ } else {
+ displayOptions =
+ usedCustomFieldValues[field.id] ?? [];
+ }
+
+ const labelForOption = (opt: string) => {
+ if (field.type === "boolean")
+ return opt === "true" ? "True" : "False";
+ return opt;
+ };
+
+ return (
+ <DropdownMenuSub key={field.id}>
+ <DropdownMenuSubTrigger className="h-8 rounded-md text-sm">
+ <span className="flex flex-1 items-center justify-between gap-2">
+ <span className="truncate">{field.name}</span>
+ {selectedValues.length > 0 && (
+ <span className="ml-auto inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground">
+ {selectedValues.length}
+ </span>
+ )}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-48">
+ <div className="grid grid-cols-1 gap-1 p-1">
+ <button
+ className={`inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-left text-xs ${
+ selectedValues.length === 0
+ ? "bg-accent text-accent-foreground"
+ : "text-foreground/90 hover:bg-accent/60 hover:text-foreground"
+ }`}
+ onClick={() =>
+ clearCustomFieldFilter(field.id)
+ }
+ type="button"
+ >
+ <CheckSlot
+ checked={selectedValues.length === 0}
+ />
+ {t("tasks:boardFilters.all")}
+ </button>
+ {displayOptions.length === 0 ? (
+ <>
+ <DropdownMenuSeparator />
+ <span className="px-2 py-1 text-xs text-muted-foreground">
+ {t("tasks:boardFilters.noValuesUsedYet")}
+ </span>
+ </>
+ ) : (
+ displayOptions.map((option) => (
+ <button
+ key={option}
+ className={`inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-left text-xs ${
+ selectedValues.includes(option)
+ ? "bg-accent text-accent-foreground"
+ : "text-foreground/90 hover:bg-accent/60 hover:text-foreground"
+ }`}
+ onClick={() =>
+ updateCustomFieldFilter(
+ field.id,
+ option,
+ )
+ }
+ type="button"
+ >
+ <CheckSlot
+ checked={selectedValues.includes(
+ option,
+ )}
+ />
+ <span className="truncate">
+ {labelForOption(option)}
+ </span>
+ </button>
+ ))
+ )}
+ </div>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+
{hasActiveFilters && (
<>
<DropdownMenuSeparator />
@@ -641,6 +795,29 @@ export default function BoardToolbar({
onClear={clearLabelFilters}
/>
)}
+
+ {filters.customFields &&
+ Object.entries(filters.customFields).map(([fieldId, values]) => {
+ if (!values || values.length === 0) return null;
+ const fieldDef = customFieldDefinitions.find(
+ (f) => f.id === fieldId,
+ );
+ return (
+ <ActiveFilterChip
+ key={fieldId}
+ subject={fieldDef?.name ?? fieldId}
+ operator={t("tasks:boardFilters.operators.isAnyOf")}
+ value={
+ values.length === 1
+ ? values[0]
+ : t("tasks:boardFilters.selectedCount", {
+ count: values.length,
+ })
+ }
+ onClear={() => clearCustomFieldFilter(fieldId)}
+ />
+ );
+ })}
</div>
<div className="inline-flex items-center gap-1">
diff --git a/apps/web/src/components/kanban-board/task-card.tsx b/apps/web/src/components/kanban-board/task-card.tsx
index d21cd5c10..13b9a25f7 100644
--- a/apps/web/src/components/kanban-board/task-card.tsx
+++ b/apps/web/src/components/kanban-board/task-card.tsx
@@ -8,6 +8,7 @@ import {
CalendarX,
GitMerge,
GitPullRequest,
+ SlidersHorizontal,
} from "lucide-react";
import { type CSSProperties, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -27,6 +28,7 @@ import {
HoverCardTrigger,
} from "@/components/ui/preview-card";
import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
+import useGetCustomFieldValuesByTask from "@/hooks/queries/custom-field/use-get-custom-field-values-by-task";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
import {
@@ -112,6 +114,14 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {
};
};
+ const { data: customFieldValues = [] } = useGetCustomFieldValuesByTask(
+ task.id,
+ );
+
+ const activeCustomFieldValues = useMemo(() => {
+ return customFieldValues.filter((f) => f.value !== null && f.value !== "");
+ }, [customFieldValues]);
+
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition:
@@ -263,6 +273,39 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {
</span>
)}
+ {activeCustomFieldValues.length > 0 && (
+ <HoverCard openDelay={200} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <span className="inline-flex items-center gap-1 rounded border border-border/70 bg-muted/55 px-2 py-1 text-[10px] font-medium text-muted-foreground cursor-default">
+ <SlidersHorizontal className="w-3 h-3" />
+ <span>{activeCustomFieldValues.length}</span>
+ </span>
+ </HoverCardTrigger>
+ <HoverCardContent
+ className="w-fit p-2.5"
+ side="bottom"
+ onClick={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <div className="space-y-1.5">
+ {activeCustomFieldValues.map((field) => (
+ <div
+ key={field.id}
+ className="flex items-center justify-between gap-2 text-xs"
+ >
+ <span className="font-medium text-muted-foreground truncate">
+ {field.fieldName}
+ </span>
+ <span className="text-foreground truncate max-w-24">
+ {field.value}
+ </span>
+ </div>
+ ))}
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+ )}
+
{showDueDates && task.dueDate && (
<div
className={`flex items-center gap-1 text-[10px] px-2 py-1 rounded ${dueDateStatusColors[getDueDateStatus(task.dueDate, taskIsCompleted)]}`}
diff --git a/apps/web/src/components/project/custom-field-editor.tsx b/apps/web/src/components/project/custom-field-editor.tsx
new file mode 100644
index 000000000..666fc960c
--- /dev/null
+++ b/apps/web/src/components/project/custom-field-editor.tsx
@@ -0,0 +1,516 @@
+import { format, isValid, parseISO } from "date-fns";
+import {
+ CalendarIcon,
+ CheckSquare,
+ GripVertical,
+ Hash,
+ List,
+ Plus,
+ Trash2,
+ Type,
+} from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { Calendar } from "@/components/ui/calendar";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@/components/ui/preview-card";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import useCreateCustomField from "@/hooks/mutations/custom-field/use-create-custom-field";
+import useDeleteCustomField from "@/hooks/mutations/custom-field/use-delete-custom-field";
+import { useReorderCustomFields } from "@/hooks/mutations/custom-field/use-reorder-custom-field";
+import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+
+type CustomFieldType = "text" | "number" | "date" | "dropdown" | "boolean";
+export type CustomFieldDefinition = {
+ id: string;
+ projectId: string;
+ name: string;
+ type: CustomFieldType;
+ required: boolean;
+ defaultValue: string | null;
+ options: string[] | null;
+ position: number;
+ createdAt: string;
+ updatedAt: string;
+};
+const CUSTOM_FIELD_TYPES: Array<{
+ value: CustomFieldType;
+ icon: React.ElementType;
+}> = [
+ { value: "text", icon: Type },
+ { value: "number", icon: Hash },
+ { value: "date", icon: CalendarIcon },
+ { value: "dropdown", icon: List },
+ { value: "boolean", icon: CheckSquare },
+];
+type CustomFieldEditorProps = {
+ projectId: string;
+};
+export default function CustomFieldEditor({
+ projectId,
+}: CustomFieldEditorProps) {
+ const { t } = useTranslation();
+ const { data: customFields = [], isLoading: customFieldsLoading } =
+ useGetCustomFieldsByProject(projectId) as {
+ data: CustomFieldDefinition[] | undefined;
+ isLoading: boolean;
+ };
+ const { mutateAsync: createCustomField, isPending: savingField } =
+ useCreateCustomField();
+ const { mutateAsync: deleteCustomField, isPending: deletingField } =
+ useDeleteCustomField(projectId);
+ const { mutateAsync: reorderCustomFields } = useReorderCustomFields();
+ const [name, setName] = useState("");
+ const [type, setType] = useState<CustomFieldType>("text");
+ const [required, setRequired] = useState(false);
+ const [defaultValue, setDefaultValue] = useState("");
+ const [optionsText, setOptionsText] = useState("");
+ const [deletingFieldId, setDeletingFieldId] = useState<string | null>(null);
+ const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
+ const dragPreviewRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ return () => {
+ dragPreviewRef.current?.remove();
+ };
+ }, []);
+
+ async function handleCreate() {
+ try {
+ if (!name.trim()) return;
+ const options =
+ type === "dropdown"
+ ? optionsText
+ .split(",")
+ .map((v) => v.trim())
+ .filter(Boolean)
+ : undefined;
+ await createCustomField({
+ projectId,
+ name: name.trim(),
+ type,
+ required,
+ defaultValue: defaultValue || undefined,
+ options,
+ });
+
+ setName("");
+ setType("text");
+ setRequired(false);
+ setDefaultValue("");
+ setOptionsText("");
+
+ toast.success(t("settings:customFields.createSuccess"));
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("settings:customFields.createError"),
+ );
+ }
+ }
+
+ async function handleDelete(id: string) {
+ try {
+ setDeletingFieldId(id);
+ await deleteCustomField({ id });
+ toast.success(t("settings:customFields.deleteSuccess"));
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("settings:customFields.deleteError"),
+ );
+ } finally {
+ setDeletingFieldId(null);
+ }
+ }
+
+ const handleDragStart = (
+ e: React.DragEvent<HTMLDivElement>,
+ index: number,
+ ) => {
+ setDraggedIndex(index);
+
+ dragPreviewRef.current?.remove();
+
+ const sourceElement = e.currentTarget;
+ const sourceRect = sourceElement.getBoundingClientRect();
+
+ const dragPreview = sourceElement.cloneNode(true) as HTMLDivElement;
+
+ dragPreview.setAttribute("aria-hidden", "true");
+ dragPreview.inert = true;
+
+ Object.assign(dragPreview.style, {
+ position: "fixed",
+ top: "-10000px",
+ left: "-10000px",
+ width: `${sourceRect.width}px`,
+ height: `${sourceRect.height}px`,
+ margin: "0",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ pointerEvents: "none",
+ transform: "none",
+ contain: "layout paint",
+ });
+
+ document.body.appendChild(dragPreview);
+ dragPreviewRef.current = dragPreview;
+
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData("text/plain", String(index));
+ e.dataTransfer.setDragImage(
+ dragPreview,
+ e.clientX - sourceRect.left,
+ e.clientY - sourceRect.top,
+ );
+ };
+
+ const handleDragOver = (e: React.DragEvent, index: number) => {
+ e.preventDefault();
+ if (draggedIndex === null || draggedIndex === index || !customFields)
+ return;
+
+ const reordered = [...customFields];
+ const [removed] = reordered.splice(draggedIndex, 1);
+ reordered.splice(index, 0, removed);
+
+ const updates = reordered.map((col, i) => ({ id: col.id, position: i }));
+ reorderCustomFields({ projectId, fields: updates });
+ setDraggedIndex(index);
+ };
+
+ const handleDragEnd = () => {
+ setDraggedIndex(null);
+
+ dragPreviewRef.current?.remove();
+ dragPreviewRef.current = null;
+ };
+
+ const hasExtraInput =
+ type === "dropdown" || type === "date" || type === "boolean";
+ const dropdownOptions = optionsText
+ .split(",")
+ .map((v) => v.trim())
+ .filter(Boolean);
+ const currentType = CUSTOM_FIELD_TYPES.find((t) => t.value === type);
+ const CurrentIcon = currentType?.icon || Type;
+
+ return (
+ <div className="space-y-3">
+ <div className="space-y-1">
+ {customFieldsLoading ? (
+ <div className="text-sm text-muted-foreground">
+ {t("settings:customFields.loading")}
+ </div>
+ ) : customFields.length === 0 ? (
+ <div className="text-sm text-muted-foreground border border-border rounded-md bg-sidebar p-4">
+ {t("settings:customFields.empty")}
+ </div>
+ ) : (
+ customFields.map((field, index) => {
+ const FieldType = CUSTOM_FIELD_TYPES.find(
+ (t) => t.value === field.type,
+ );
+ const FieldIcon = FieldType?.icon || Type;
+ return (
+ // biome-ignore lint/a11y/useSemanticElements: false positive for role="listitem"
+ <div
+ key={field.id}
+ role="listitem"
+ draggable
+ onDragStart={(e) => handleDragStart(e, index)}
+ onDragOver={(e) => handleDragOver(e, index)}
+ onDragEnd={handleDragEnd}
+ className="flex items-center gap-2 p-2 border border-border rounded-md bg-sidebar hover:bg-sidebar-accent/50 transition-colors active:cursor-grabbing"
+ >
+ <GripVertical className="w-4 h-4 text-muted-foreground cursor-grab shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <FieldIcon className="w-4 h-4 text-muted-foreground" />
+ <span className="truncate text-sm font-medium">
+ {field.name}
+ </span>
+ <span className="rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ {t(`settings:customFields.types.${field.type}`)}
+ </span>
+ {field.required && (
+ <span className="rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ {t("settings:customFields.required")}
+ </span>
+ )}
+ {field.type === "dropdown" && field.options?.length ? (
+ <HoverCard>
+ <HoverCardTrigger asChild>
+ <span className="inline-flex items-center gap-1 rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors">
+ {field.options.length}{" "}
+ {t("settings:customFields.options", "options")}
+ </span>
+ </HoverCardTrigger>
+ <HoverCardContent
+ className="w-64 max-w-[calc(100vw-3rem)]"
+ align="start"
+ >
+ <div className="space-y-1.5">
+ <div className="text-xs font-medium text-muted-foreground">
+ {t(
+ "settings:customFields.availableOptions",
+ "Available options",
+ )}
+ </div>
+
+ <div className="flex max-h-48 flex-wrap gap-1.5 overflow-y-auto">
+ {field.options.map((option) => (
+ <span
+ key={`field_${field.id}_option_${option}`}
+ className="max-w-full whitespace-normal break-words rounded bg-secondary px-2.5 py-1 text-xs"
+ >
+ {option}
+ </span>
+ ))}
+ </div>
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+ ) : null}
+ {field.defaultValue && (
+ <span className="truncate text-xs text-muted-foreground">
+ {t("settings:customFields.defaultLabel")}:{" "}
+ <span className="text-foreground">
+ {field.defaultValue}
+ </span>
+ </span>
+ )}
+ </div>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={deletingField || deletingFieldId === field.id}
+ onClick={() => void handleDelete(field.id)}
+ className="h-7 w-7 p-0 text-muted-foreground hover:text-destructive shrink-0"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ <span className="sr-only">
+ {t("settings:customFields.deleteButton")}
+ </span>
+ </Button>
+ </div>
+ );
+ })
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 w-full">
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-8 w-8 p-0 shrink-0"
+ title={t("settings:customFields.typePlaceholder")}
+ >
+ <CurrentIcon className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-48" align="start">
+ <div className="space-y-1 px-0.5 py-1">
+ {CUSTOM_FIELD_TYPES.map((item) => {
+ const Icon = item.icon;
+ return (
+ <Button
+ key={item.value}
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setType(item.value)}
+ className={cn(
+ "w-full justify-start gap-2 text-sm rounded-sm",
+ type === item.value &&
+ "bg-sidebar-accent text-sidebar-accent-foreground",
+ )}
+ >
+ <Icon className="h-4 w-4" />
+ {t(`settings:customFields.types.${item.value}`)}
+ </Button>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("settings:customFields.namePlaceholder")}
+ className={cn(
+ "h-8 text-sm",
+ hasExtraInput ? "w-32 flex-[2_0_0]" : "flex-1",
+ )}
+ />
+
+ {type === "dropdown" && (
+ <Input
+ value={optionsText}
+ onChange={(e) => setOptionsText(e.target.value)}
+ placeholder={t("settings:customFields.optionsPlaceholder")}
+ className="h-8 text-sm w-48 flex-[2_0_0]"
+ />
+ )}
+
+ {type === "date" && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className={cn(
+ "h-8 w-48 flex-[2_0_0] justify-start bg-background text-left text-sm font-normal",
+ !defaultValue && "text-muted-foreground",
+ )}
+ >
+ <CalendarIcon className="mr-2 h-4 w-4 opacity-70" />
+ {defaultValue && isValid(parseISO(defaultValue))
+ ? format(parseISO(defaultValue), "dd MMM yyyy")
+ : t("tasks:detail.pickDate", "Pick a date")}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent side="bottom" align="start" className="w-auto p-0">
+ <Calendar
+ mode="single"
+ selected={
+ defaultValue && isValid(parseISO(defaultValue))
+ ? parseISO(defaultValue)
+ : undefined
+ }
+ onSelect={(date) => {
+ setDefaultValue(date ? format(date, "yyyy-MM-dd") : "");
+ }}
+ captionLayout="dropdown"
+ />
+ </PopoverContent>
+ </Popover>
+ )}
+
+ {type === "boolean" ? (
+ <Select
+ value={defaultValue || "false"}
+ onValueChange={(value) => setDefaultValue(value as string)}
+ >
+ <SelectTrigger className="h-8 w-48 flex-[2_0_0] text-sm">
+ <SelectValue
+ placeholder={t("settings:customFields.defaultValuePlaceholder")}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="true">{t("common:true", "True")}</SelectItem>
+ <SelectItem value="false">
+ {t("common:false", "False")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ ) : type === "dropdown" ? (
+ <Select
+ value={defaultValue}
+ onValueChange={(value) => setDefaultValue(value as string)}
+ disabled={dropdownOptions.length === 0}
+ >
+ <SelectTrigger className="h-8 w-48 flex-[2_0_0] text-sm disabled:opacity-50">
+ <SelectValue
+ placeholder={
+ dropdownOptions.length === 0
+ ? t(
+ "settings:customFields.noOptionsPlaceholder",
+ "No options",
+ )
+ : t(
+ "settings:customFields.defaultValuePlaceholder",
+ "Default value",
+ )
+ }
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {dropdownOptions.map((option) => (
+ <SelectItem key={`field_option_${option}`} value={option}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : type === "number" ? (
+ <Input
+ value={defaultValue}
+ type="number"
+ onChange={(e) => setDefaultValue(e.target.value)}
+ placeholder={t("settings:customFields.defaultValuePlaceholder")}
+ className="h-8 text-sm w-48 flex-[2_0_0]"
+ />
+ ) : (
+ type !== "date" && (
+ <Input
+ value={defaultValue}
+ onChange={(e) => setDefaultValue(e.target.value)}
+ placeholder={t("settings:customFields.defaultValuePlaceholder")}
+ className="h-8 text-sm w-48 flex-[2_0_0]"
+ />
+ )
+ )}
+
+ <div className="flex items-center gap-2 shrink-0">
+ <Checkbox
+ id="required-field"
+ checked={required}
+ onCheckedChange={(checked) => setRequired(Boolean(checked))}
+ className="h-4 w-4"
+ />
+ <label
+ htmlFor="required-field"
+ className="text-xs text-muted-foreground whitespace-nowrap"
+ >
+ {t("settings:customFields.required")}
+ </label>
+ </div>
+
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={handleCreate}
+ disabled={
+ !name.trim() ||
+ savingField ||
+ (type === "dropdown" && !optionsText.trim()) ||
+ (required && !defaultValue)
+ }
+ className="h-8 gap-1 shrink-0"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ {t("settings:customFields.addButton")}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/shared/modals/create-task-modal.test.tsx b/apps/web/src/components/shared/modals/create-task-modal.test.tsx
index 90d85fe97..270e2d651 100644
--- a/apps/web/src/components/shared/modals/create-task-modal.test.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.test.tsx
@@ -1,7 +1,29 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import CreateTaskModal from "./create-task-modal";
+function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+}
+
+function createWrapper() {
+ const queryClient = createTestQueryClient();
+
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
const useLocation = vi.fn();
const createTask = vi.fn(async (input: Record<string, unknown>) => ({
id: "task-1",
@@ -91,7 +113,9 @@ describe("CreateTaskModal project picker", () => {
pathname: "/dashboard/workspace/workspace-1",
});
- render(<CreateTaskModal open onClose={vi.fn()} />);
+ render(<CreateTaskModal open onClose={vi.fn()} />, {
+ wrapper: createWrapper(),
+ });
const pickerTrigger = screen.getByText(
"common:modals.createTask.selectProject",
@@ -122,7 +146,9 @@ describe("CreateTaskModal project picker", () => {
pathname: "/dashboard/workspace/workspace-1/project/project-1/board",
});
- render(<CreateTaskModal open onClose={vi.fn()} />);
+ render(<CreateTaskModal open onClose={vi.fn()} />, {
+ wrapper: createWrapper(),
+ });
expect(
screen.queryByText("common:modals.createTask.selectProject"),
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 b4c188f10..c35e474ba 100644
--- a/apps/web/src/components/shared/modals/create-task-modal.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx
@@ -37,10 +37,20 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import useSetCustomFieldValue from "@/hooks/mutations/custom-field/use-set-custom-field-value";
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 useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";
import useGetProjects from "@/hooks/queries/project/use-get-projects";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
@@ -85,6 +95,21 @@ type Label = {
type PopoverStep = "select" | "color";
+type CustomFieldType = "text" | "number" | "date" | "dropdown" | "boolean";
+
+type CustomFieldDefinition = {
+ id: string;
+ projectId: string;
+ name: string;
+ type: CustomFieldType;
+ required: boolean;
+ defaultValue: string | null;
+ options: string[] | null;
+ position: number;
+ createdAt: string;
+ updatedAt: string;
+};
+
function normalizeTask(
task: Partial<Task> &
Pick<Task, "id" | "title" | "status" | "projectId" | "createdAt">,
@@ -219,6 +244,41 @@ function CreateTaskModal({
const { mutateAsync: updateTask } = useUpdateTask();
const { mutateAsync: deleteTask } = useDeleteTask();
+ const { data: rawCustomFields } = useGetCustomFieldsByProject(
+ resolvedProjectId,
+ ) as { data: CustomFieldDefinition[] | undefined };
+
+ const customFields = useMemo(() => rawCustomFields ?? [], [rawCustomFields]);
+
+ const { mutateAsync: setCustomFieldValue } = useSetCustomFieldValue();
+
+ const [customFieldValues, setCustomFieldValues] = useState<
+ Record<string, string>
+ >({});
+
+ const handleCustomFieldChange = (fieldId: string, value: string) => {
+ setCustomFieldValues((prev) => ({
+ ...prev,
+ [fieldId]: value,
+ }));
+ };
+
+ useEffect(() => {
+ if (customFields && customFields.length > 0) {
+ setCustomFieldValues((prev) => {
+ const next = { ...prev };
+ for (const field of customFields) {
+ if (next[field.id] === undefined) {
+ next[field.id] = field.defaultValue || "";
+ }
+ }
+ return next;
+ });
+ } else {
+ setCustomFieldValues({});
+ }
+ }, [customFields]);
+
const filteredLabels = (() => {
const searchFiltered = workspaceLabels.filter((label) =>
label.name.toLowerCase().includes(searchValue.toLowerCase()),
@@ -241,6 +301,13 @@ function CreateTaskModal({
(label) => label.name.toLowerCase() === searchValue.toLowerCase(),
);
+ const buildDefaultCustomFieldValues = useCallback(() => {
+ return customFields.reduce<Record<string, string>>((acc, field) => {
+ acc[field.id] = field.defaultValue ?? "";
+ return acc;
+ }, {});
+ }, [customFields]);
+
const handleClose = () => {
const shouldDeleteDraft = draftTask && !didSubmitRef.current;
@@ -259,6 +326,7 @@ function CreateTaskModal({
draftCreationPromiseRef.current = null;
didSubmitRef.current = false;
setDraftTask(null);
+ setCustomFieldValues(buildDefaultCustomFieldValues());
onClose();
if (shouldDeleteDraft) {
@@ -348,6 +416,12 @@ function CreateTaskModal({
startDate: startDate ? startDate.toISOString() : undefined,
dueDate: dueDate ? dueDate.toISOString() : undefined,
status: draftStatus,
+ customFields: Object.entries(customFieldValues)
+ .filter(([_, value]) => value.trim() !== "")
+ .map(([fieldId, value]) => ({
+ fieldId,
+ value,
+ })),
}).then((task) => normalizeTask(task));
draftCreationPromiseRef.current = draftPromise;
@@ -377,6 +451,7 @@ function CreateTaskModal({
resolvedProjectId,
title,
t,
+ customFieldValues,
]);
const handleSubmit = async (e: React.FormEvent) => {
@@ -399,6 +474,9 @@ function CreateTaskModal({
startDate: startDate ? startDate.toISOString() : null,
dueDate: dueDate ? dueDate.toISOString() : null,
projectId: resolvedProjectId,
+ customFieldValues: Object.entries(customFieldValues)
+ .filter(([_, value]) => value.trim() !== "")
+ .map(([fieldId, value]) => ({ fieldId, value })),
}),
)
: normalizeTask(
@@ -411,6 +489,12 @@ function CreateTaskModal({
startDate: startDate ? startDate.toISOString() : undefined,
dueDate: dueDate ? dueDate.toISOString() : undefined,
status: taskStatus,
+ customFields: Object.entries(customFieldValues)
+ .filter(([_, value]) => value.trim() !== "")
+ .map(([fieldId, value]) => ({
+ fieldId,
+ value,
+ })),
}),
);
@@ -427,6 +511,16 @@ function CreateTaskModal({
}
}
+ for (const [fieldId, value] of Object.entries(customFieldValues)) {
+ if (value) {
+ await setCustomFieldValue({
+ taskId: savedTask.id,
+ fieldId,
+ value: String(value),
+ });
+ }
+ }
+
setDraftTask(savedTask);
syncTaskIntoProject(savedTask);
toast.success(
@@ -450,6 +544,7 @@ function CreateTaskModal({
draftCreationPromiseRef.current = null;
didSubmitRef.current = false;
setDraftTask(null);
+ setCustomFieldValues(buildDefaultCustomFieldValues());
} else {
handleClose();
}
@@ -592,6 +687,90 @@ function CreateTaskModal({
setLabels(labels.filter((l) => l.name !== labelName));
};
+ const renderCustomFieldInput = (field: CustomFieldDefinition) => {
+ const value = customFieldValues[field.id] ?? "";
+
+ switch (field.type) {
+ case "dropdown": {
+ const options = field.options || [];
+
+ return (
+ <Select
+ value={value}
+ onValueChange={(val) =>
+ handleCustomFieldChange(field.id, val as string)
+ }
+ >
+ <SelectTrigger className="h-9 w-full text-sm bg-background">
+ <SelectValue
+ placeholder={t(
+ "common:modals.createTask.selectOptionPlaceholder",
+ "Select an option",
+ )}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((opt) => (
+ <SelectItem key={opt} value={opt}>
+ {opt}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+ }
+
+ case "date":
+ return (
+ <Input
+ type="date"
+ value={value}
+ onChange={(e) => handleCustomFieldChange(field.id, e.target.value)}
+ required={field.required}
+ className="h-9 w-full text-sm bg-background"
+ />
+ );
+
+ case "number":
+ return (
+ <Input
+ type="number"
+ value={value}
+ onChange={(e) => handleCustomFieldChange(field.id, e.target.value)}
+ placeholder={field.defaultValue || ""}
+ required={field.required}
+ className="h-9 w-full text-sm bg-background"
+ />
+ );
+
+ case "boolean":
+ return (
+ <div className="flex h-9 w-full items-center justify-between rounded-md border border-input bg-background px-3 text-sm">
+ <span className="text-sm text-foreground capitalize">{value}</span>
+
+ <Switch
+ checked={value === "true"}
+ onCheckedChange={(checked) =>
+ handleCustomFieldChange(field.id, checked ? "true" : "false")
+ }
+ />
+ </div>
+ );
+
+ default:
+ return (
+ <Input
+ type="text"
+ value={value}
+ onChange={(e) => handleCustomFieldChange(field.id, e.target.value)}
+ placeholder={field.defaultValue || ""}
+ required={field.required}
+ className="h-9 w-full text-sm bg-background"
+ />
+ );
+ }
+ };
+
// Defense-in-depth: if the user lacks task-create permission, don't render
// the modal even if a stale trigger somehow opens it (e.g., keyboard
// shortcut after the capability has changed).
@@ -650,6 +829,33 @@ function CreateTaskModal({
/>
</div>
+ {customFields.length > 0 && (
+ <div className="space-y-4 pt-4 border-t border-border">
+ <h4 className="text-sm font-semibold text-foreground">
+ {t("tasks:common.customFields")}
+ </h4>
+ <div className="grid gap-4 sm:grid-cols-2">
+ {customFields.map((field) => (
+ <div
+ key={`custom-field_${field.id}`}
+ className="space-y-1.5"
+ >
+ <label
+ htmlFor={`custom-field_${field.id}`}
+ className="text-xs font-medium text-muted-foreground flex items-center gap-1"
+ >
+ {field.name}
+ {field.required && (
+ <span className="text-destructive">*</span>
+ )}
+ </label>
+ {renderCustomFieldInput(field)}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
{labels.length > 0 && (
<div className="flex flex-wrap mb-2">
{labels.map((label) => (
diff --git a/apps/web/src/components/task/task-details-content.tsx b/apps/web/src/components/task/task-details-content.tsx
index c6c9d0234..2ee675bdc 100644
--- a/apps/web/src/components/task/task-details-content.tsx
+++ b/apps/web/src/components/task/task-details-content.tsx
@@ -1,23 +1,68 @@
import { useNavigate } from "@tanstack/react-router";
-import { ArrowUpRight } from "lucide-react";
+import { format, isValid, parseISO } from "date-fns";
+import { ArrowUpRight, CalendarIcon } from "lucide-react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import Activity from "@/components/activity";
import CommentInput from "@/components/activity/comment-input";
import { isCommentActivity } from "@/components/activity/utils";
import { ExternalLinksAccordion } from "@/components/external-links/external-links-accordion";
import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Button } from "@/components/ui/button";
+import { Calendar } from "@/components/ui/calendar";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
import { Timeline } from "@/components/ui/timeline";
+import useSetCustomFieldValue from "@/hooks/mutations/custom-field/use-set-custom-field-value";
import useGetActivitiesByTaskId from "@/hooks/queries/activity/use-get-activities-by-task-id";
+import useGetCustomFieldValuesByTask from "@/hooks/queries/custom-field/use-get-custom-field-values-by-task";
+import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
import useExternalLinks from "@/hooks/queries/external-link/use-external-links";
import useGetProject from "@/hooks/queries/project/use-get-project";
import useGetTask from "@/hooks/queries/task/use-get-task";
import useGetTaskRelations from "@/hooks/queries/task-relation/use-get-task-relations";
+import { useWorkspacePermission } from "@/hooks/use-workspace-permission";
+import { cn } from "@/lib/cn";
+import { toast } from "@/lib/toast";
import type { ExternalLink } from "@/types/external-link";
import TaskDescription from "./task-description";
import TaskRelations from "./task-relations";
import TaskSubtasks from "./task-subtasks";
import TaskTitle from "./task-title";
+type CustomFieldType = "text" | "number" | "date" | "dropdown" | "boolean";
+
+type CustomFieldDefinition = {
+ id: string;
+ projectId: string;
+ name: string;
+ type: CustomFieldType;
+ required: boolean;
+ defaultValue: string | null;
+ options: string[] | null;
+ position: number;
+ createdAt: string;
+ updatedAt: string;
+};
+
type TaskDetailsContentProps = {
taskId: string | undefined;
projectId: string;
@@ -41,6 +86,64 @@ export default function TaskDetailsContent({
const { data: relations = [] } = useGetTaskRelations(taskId ?? "");
const { user } = useAuth();
+ const { data: customFields = [] } = useGetCustomFieldsByProject(
+ projectId,
+ ) as { data: CustomFieldDefinition[] | undefined };
+
+ const { data: customFieldValues = [] } = useGetCustomFieldValuesByTask(
+ taskId ?? "",
+ );
+
+ const { mutateAsync: setCustomFieldValue } = useSetCustomFieldValue();
+ const { canManageTasks } = useWorkspacePermission();
+ const canEdit = canManageTasks();
+
+ const [localValues, setLocalValues] = useState<Record<string, string>>({});
+
+ useEffect(() => {
+ const valuesMap: Record<string, string> = {};
+
+ for (const field of customFields) {
+ valuesMap[field.id] = field.defaultValue || "";
+ }
+
+ for (const val of customFieldValues) {
+ if (val.value !== null) {
+ valuesMap[val.fieldId] = val.value;
+ }
+ }
+
+ setLocalValues(valuesMap);
+ }, [customFields, customFieldValues]);
+
+ const handleLocalChange = (fieldId: string, val: string) => {
+ setLocalValues((prev) => ({ ...prev, [fieldId]: val }));
+ };
+
+ const handleSaveField = async (fieldId: string, value: string) => {
+ if (!taskId) return;
+
+ const existingValObj = customFieldValues.find((v) => v.fieldId === fieldId);
+ const existingVal = existingValObj ? (existingValObj.value ?? "") : "";
+
+ if (value === existingVal) return;
+
+ try {
+ await setCustomFieldValue({
+ taskId,
+ fieldId,
+ value,
+ projectId,
+ });
+
+ toast.success(t("tasks:detail.customFieldUpdated", "Field updated"));
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Failed to update field",
+ );
+ }
+ };
+
const parentRelation = relations.find(
(rel) => rel.relationType === "subtask" && rel.targetTaskId === taskId,
);
@@ -73,12 +176,174 @@ export default function TaskDetailsContent({
</span>
</button>
)}
+
<p className="text-xs font-semibold text-foreground/70">
{project?.slug}-{task?.number}
</p>
+
<TaskTitle taskId={taskId} />
<TaskDescription taskId={taskId} />
</div>
+
+ {customFields.length > 0 && (
+ <div className="mt-2">
+ <Accordion className="w-full">
+ <AccordionItem
+ value="custom-fields"
+ className="rounded-lg border border-border bg-sidebar/30 px-4"
+ >
+ <AccordionTrigger className="py-4 hover:no-underline">
+ <div className="flex items-center gap-2 text-left">
+ <span className="text-sm font-semibold text-foreground">
+ {t("tasks:common.customFields")}
+ </span>
+ <span className="rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ {customFields.length}
+ </span>
+ </div>
+ </AccordionTrigger>
+
+ <AccordionContent className="pb-4">
+ <div className="grid gap-4 sm:grid-cols-2">
+ {customFields.map((field) => {
+ const val = localValues[field.id] ?? "";
+
+ return (
+ <div
+ key={`custom-field-${field.id}`}
+ className="space-y-1.5"
+ >
+ <label
+ htmlFor={`custom-field-${field.id}`}
+ className="flex items-center gap-1 text-xs font-medium text-muted-foreground"
+ >
+ {field.name}
+ {field.required && (
+ <span className="text-destructive">*</span>
+ )}
+ </label>
+
+ {field.type === "dropdown" ? (
+ <Select
+ value={val}
+ onValueChange={(newVal) => {
+ handleLocalChange(field.id, newVal as string);
+ void handleSaveField(field.id, newVal as string);
+ }}
+ disabled={!canEdit}
+ >
+ <SelectTrigger className="h-9 w-full bg-background text-sm">
+ <SelectValue
+ placeholder={t(
+ "tasks:detail.selectOption",
+ "Select option",
+ )}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {(field.options || []).map((opt) => (
+ <SelectItem key={opt} value={opt}>
+ {opt}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : field.type === "date" ? (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <Button
+ variant="outline"
+ disabled={!canEdit}
+ className={cn(
+ "h-9 w-full justify-start bg-background text-left text-sm font-normal",
+ !val && "text-muted-foreground",
+ )}
+ >
+ <CalendarIcon className="mr-2 h-4 w-4 opacity-70" />
+ {val && isValid(parseISO(val))
+ ? format(parseISO(val), "dd MMM yyyy")
+ : t("tasks:detail.pickDate", "Pick a date")}
+ </Button>
+ }
+ />
+ <PopoverContent
+ side="bottom"
+ align="start"
+ className="w-auto p-0"
+ >
+ <Calendar
+ mode="single"
+ selected={
+ val && isValid(parseISO(val))
+ ? parseISO(val)
+ : undefined
+ }
+ onSelect={(date) => {
+ const iso = date
+ ? format(date, "yyyy-MM-dd")
+ : "";
+ handleLocalChange(field.id, iso);
+ void handleSaveField(field.id, iso);
+ }}
+ captionLayout="dropdown"
+ />
+ </PopoverContent>
+ </Popover>
+ ) : field.type === "number" ? (
+ <Input
+ type="number"
+ value={val}
+ onChange={(e) =>
+ handleLocalChange(field.id, e.target.value)
+ }
+ onBlur={() => void handleSaveField(field.id, val)}
+ disabled={!canEdit}
+ className="h-9 w-full bg-background text-sm"
+ />
+ ) : field.type === "boolean" ? (
+ <div
+ className={cn(
+ "flex h-9 w-full items-center justify-between rounded-md border border-input bg-muted px-3 text-sm",
+ !canEdit && "cursor-not-allowed opacity-50",
+ )}
+ >
+ <span className="text-sm text-foreground capitalize">
+ {val}
+ </span>
+
+ <Switch
+ checked={val === "true"}
+ onCheckedChange={(checked) => {
+ const nextValue = checked ? "true" : "false";
+ handleLocalChange(field.id, nextValue);
+ void handleSaveField(field.id, nextValue);
+ }}
+ disabled={!canEdit}
+ />
+ </div>
+ ) : (
+ <Input
+ type="text"
+ value={val}
+ onChange={(e) =>
+ handleLocalChange(field.id, e.target.value)
+ }
+ onBlur={() => void handleSaveField(field.id, val)}
+ disabled={!canEdit}
+ className="h-9 w-full bg-background text-sm"
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ </div>
+ )}
+
{!isLoadingExternalLinks && externalLinks.length > 0 && (
<div className="mt-4">
<ExternalLinksAccordion
@@ -87,6 +352,7 @@ export default function TaskDetailsContent({
/>
</div>
)}
+
<div className="mt-4">
{task && (
<TaskSubtasks
@@ -97,6 +363,7 @@ export default function TaskDetailsContent({
/>
)}
</div>
+
<div className="mt-2">
<TaskRelations
taskId={taskId}
@@ -107,7 +374,9 @@ export default function TaskDetailsContent({
<span className="text-sm font-medium text-muted-foreground h-[1px] bg-border w-full block shrink-0" />
<div className="flex flex-col gap-4">
<h1 className="text-md font-semibold">{t("tasks:detail.activity")}</h1>
+
{user?.id && taskId && <CommentInput taskId={taskId} />}
+
{activities.length > 0 ? (
<Timeline>
{activities.map((activity, index) => {
diff --git a/apps/web/src/fetchers/custom-field/create-custom-field.ts b/apps/web/src/fetchers/custom-field/create-custom-field.ts
new file mode 100644
index 000000000..ef80632bf
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/create-custom-field.ts
@@ -0,0 +1,35 @@
+import { client } from "@kaneo/libs";
+import type { InferRequestType } from "hono/client";
+
+export type CreateCustomFieldRequest = InferRequestType<
+ (typeof client)["custom-field"]["$post"]
+>["json"];
+
+async function createCustomField({
+ projectId,
+ name,
+ type,
+ required,
+ defaultValue,
+ options,
+}: CreateCustomFieldRequest) {
+ const response = await client["custom-field"].$post({
+ json: {
+ projectId,
+ name,
+ type,
+ required,
+ defaultValue,
+ options,
+ },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default createCustomField;
diff --git a/apps/web/src/fetchers/custom-field/delete-custom-field.ts b/apps/web/src/fetchers/custom-field/delete-custom-field.ts
new file mode 100644
index 000000000..f8d23c06e
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/delete-custom-field.ts
@@ -0,0 +1,16 @@
+import { client } from "@kaneo/libs";
+
+async function deleteCustomField({ id }: { id: string }) {
+ const response = await client["custom-field"][":id"].$delete({
+ param: { id },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default deleteCustomField;
diff --git a/apps/web/src/fetchers/custom-field/get-custom-field-filter-values.ts b/apps/web/src/fetchers/custom-field/get-custom-field-filter-values.ts
new file mode 100644
index 000000000..9089169c2
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/get-custom-field-filter-values.ts
@@ -0,0 +1,22 @@
+import { client } from "@kaneo/libs";
+
+async function getCustomFieldFilterValues({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const response = await client["custom-field"].project[":projectId"][
+ "filter-values"
+ ].$get({
+ param: { projectId },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default getCustomFieldFilterValues;
diff --git a/apps/web/src/fetchers/custom-field/get-custom-field-values-by-task.ts b/apps/web/src/fetchers/custom-field/get-custom-field-values-by-task.ts
new file mode 100644
index 000000000..cb504a654
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/get-custom-field-values-by-task.ts
@@ -0,0 +1,16 @@
+import { client } from "@kaneo/libs";
+
+async function getCustomFieldValuesByTask({ taskId }: { taskId: string }) {
+ const response = await client["custom-field"].task[":taskId"].$get({
+ param: { taskId },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default getCustomFieldValuesByTask;
diff --git a/apps/web/src/fetchers/custom-field/get-custom-fields-by-project.ts b/apps/web/src/fetchers/custom-field/get-custom-fields-by-project.ts
new file mode 100644
index 000000000..36d7e7517
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/get-custom-fields-by-project.ts
@@ -0,0 +1,16 @@
+import { client } from "@kaneo/libs";
+
+async function getCustomFieldsByProject({ projectId }: { projectId: string }) {
+ const response = await client["custom-field"].project[":projectId"].$get({
+ param: { projectId },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default getCustomFieldsByProject;
diff --git a/apps/web/src/fetchers/custom-field/reorder-custom-field.ts b/apps/web/src/fetchers/custom-field/reorder-custom-field.ts
new file mode 100644
index 000000000..cd6b632f8
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/reorder-custom-field.ts
@@ -0,0 +1,20 @@
+import { client } from "@kaneo/libs";
+
+async function reorderCustomFields(
+ projectId: string,
+ fields: Array<{ id: string; position: number }>,
+) {
+ const response = await client["custom-field"].reorder[":projectId"].$put({
+ param: { projectId },
+ json: { fields },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default reorderCustomFields;
diff --git a/apps/web/src/fetchers/custom-field/set-custom-field-value.ts b/apps/web/src/fetchers/custom-field/set-custom-field-value.ts
new file mode 100644
index 000000000..4b537953c
--- /dev/null
+++ b/apps/web/src/fetchers/custom-field/set-custom-field-value.ts
@@ -0,0 +1,25 @@
+import { client } from "@kaneo/libs";
+import type { InferRequestType } from "hono/client";
+
+export type SetCustomFieldValueRequest = InferRequestType<
+ (typeof client)["custom-field"]["value"]["$put"]
+>["json"];
+
+async function setCustomFieldValue({
+ taskId,
+ fieldId,
+ value,
+}: SetCustomFieldValueRequest) {
+ const response = await client["custom-field"].value.$put({
+ json: { taskId, fieldId, value },
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return response.json();
+}
+
+export default setCustomFieldValue;
diff --git a/apps/web/src/fetchers/task/create-task.ts b/apps/web/src/fetchers/task/create-task.ts
index 0729db2c0..e7783672b 100644
--- a/apps/web/src/fetchers/task/create-task.ts
+++ b/apps/web/src/fetchers/task/create-task.ts
@@ -15,6 +15,7 @@ async function createTask(
startDate: Date | undefined,
dueDate: Date | undefined,
priority: CreateTaskRequest["priority"],
+ customFields?: { fieldId: string; value: string }[],
) {
if (!projectId) {
throw new Error("No project selected for task creation");
@@ -29,6 +30,7 @@ async function createTask(
startDate: startDate?.toISOString() || undefined,
dueDate: dueDate?.toISOString() || undefined,
priority,
+ customFields,
},
param: { projectId },
});
diff --git a/apps/web/src/hooks/mutations/custom-field/use-create-custom-field.ts b/apps/web/src/hooks/mutations/custom-field/use-create-custom-field.ts
new file mode 100644
index 000000000..3e3a12238
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-create-custom-field.ts
@@ -0,0 +1,26 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { CreateCustomFieldRequest } from "@/fetchers/custom-field/create-custom-field";
+import createCustomField from "@/fetchers/custom-field/create-custom-field";
+
+function useCreateCustomField() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: createCustomField,
+ onSuccess: (created, variables: CreateCustomFieldRequest) => {
+ queryClient.setQueryData(
+ ["custom-fields", variables.projectId],
+ (existing: Array<typeof created> | undefined) => {
+ if (!existing) return [created];
+ return [...existing, created];
+ },
+ );
+
+ void queryClient.invalidateQueries({
+ queryKey: ["custom-fields", variables.projectId],
+ });
+ },
+ });
+}
+
+export default useCreateCustomField;
diff --git a/apps/web/src/hooks/mutations/custom-field/use-create-task.tsx b/apps/web/src/hooks/mutations/custom-field/use-create-task.tsx
new file mode 100644
index 000000000..405ef1ff3
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-create-task.tsx
@@ -0,0 +1,40 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import createTask, {
+ type CreateTaskRequest,
+} from "@/fetchers/task/create-task";
+
+function useCreateTask() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ title,
+ description,
+ userId,
+ projectId,
+ status,
+ startDate,
+ dueDate,
+ priority,
+ customFields,
+ }: CreateTaskRequest) =>
+ createTask(
+ title,
+ description,
+ projectId,
+ userId ?? "",
+ status,
+ startDate ? new Date(startDate) : undefined,
+ dueDate ? new Date(dueDate) : undefined,
+ priority,
+ customFields,
+ ),
+ onSuccess: (_data, variables) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", variables.projectId],
+ });
+ },
+ });
+}
+
+export default useCreateTask;
diff --git a/apps/web/src/hooks/mutations/custom-field/use-delete-custom-field.ts b/apps/web/src/hooks/mutations/custom-field/use-delete-custom-field.ts
new file mode 100644
index 000000000..8899d259a
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-delete-custom-field.ts
@@ -0,0 +1,25 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import deleteCustomField from "@/fetchers/custom-field/delete-custom-field";
+
+function useDeleteCustomField(projectId: string) {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: deleteCustomField,
+ onSuccess: (_data, variables) => {
+ queryClient.setQueryData(
+ ["custom-fields", projectId],
+ (existing: Array<{ id: string }> | undefined) => {
+ if (!existing) return [];
+ return existing.filter((f) => f.id !== variables.id);
+ },
+ );
+
+ void queryClient.invalidateQueries({
+ queryKey: ["custom-fields", projectId],
+ });
+ },
+ });
+}
+
+export default useDeleteCustomField;
diff --git a/apps/web/src/hooks/mutations/custom-field/use-get-all-custom-field-values-by-project.ts b/apps/web/src/hooks/mutations/custom-field/use-get-all-custom-field-values-by-project.ts
new file mode 100644
index 000000000..da51126ae
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-get-all-custom-field-values-by-project.ts
@@ -0,0 +1,21 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { useCallback } from "react";
+
+function useGetCachedCustomFieldValues() {
+ const queryClient = useQueryClient();
+
+ const getValuesForTask = useCallback(
+ (taskId: string) => {
+ return (
+ (queryClient.getQueryData(["custom-field-values", taskId]) as
+ | Array<{ fieldId: string; value: string | null }>
+ | undefined) ?? []
+ );
+ },
+ [queryClient],
+ );
+
+ return { getValuesForTask };
+}
+
+export default useGetCachedCustomFieldValues;
diff --git a/apps/web/src/hooks/mutations/custom-field/use-reorder-custom-field.ts b/apps/web/src/hooks/mutations/custom-field/use-reorder-custom-field.ts
new file mode 100644
index 000000000..4272ae4d9
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-reorder-custom-field.ts
@@ -0,0 +1,19 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import reorderCustomFields from "@/fetchers/custom-field/reorder-custom-field";
+
+export function useReorderCustomFields() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ projectId,
+ fields,
+ }: {
+ projectId: string;
+ fields: Array<{ id: string; position: number }>;
+ }) => reorderCustomFields(projectId, fields),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ refetchType: "all" });
+ },
+ });
+}
diff --git a/apps/web/src/hooks/mutations/custom-field/use-set-custom-field-value.ts b/apps/web/src/hooks/mutations/custom-field/use-set-custom-field-value.ts
new file mode 100644
index 000000000..5abc597ae
--- /dev/null
+++ b/apps/web/src/hooks/mutations/custom-field/use-set-custom-field-value.ts
@@ -0,0 +1,34 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { SetCustomFieldValueRequest } from "@/fetchers/custom-field/set-custom-field-value";
+import setCustomFieldValue from "@/fetchers/custom-field/set-custom-field-value";
+
+type SetCustomFieldValueArgs = SetCustomFieldValueRequest & {
+ projectId?: string;
+};
+
+function useSetCustomFieldValue() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ taskId, fieldId, value }: SetCustomFieldValueArgs) =>
+ setCustomFieldValue({ taskId, fieldId, value }),
+ onSuccess: (_data, variables: SetCustomFieldValueArgs) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["custom-field-values", variables.taskId],
+ });
+ if (variables.projectId) {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", variables.projectId],
+ });
+ void queryClient.invalidateQueries({
+ queryKey: ["custom-field-filter-values", variables.projectId],
+ });
+ }
+ void queryClient.invalidateQueries({
+ queryKey: ["task", variables.taskId],
+ });
+ },
+ });
+}
+
+export default useSetCustomFieldValue;
diff --git a/apps/web/src/hooks/queries/custom-field/use-get-all-custom-field-values-by-project.ts b/apps/web/src/hooks/queries/custom-field/use-get-all-custom-field-values-by-project.ts
new file mode 100644
index 000000000..da51126ae
--- /dev/null
+++ b/apps/web/src/hooks/queries/custom-field/use-get-all-custom-field-values-by-project.ts
@@ -0,0 +1,21 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { useCallback } from "react";
+
+function useGetCachedCustomFieldValues() {
+ const queryClient = useQueryClient();
+
+ const getValuesForTask = useCallback(
+ (taskId: string) => {
+ return (
+ (queryClient.getQueryData(["custom-field-values", taskId]) as
+ | Array<{ fieldId: string; value: string | null }>
+ | undefined) ?? []
+ );
+ },
+ [queryClient],
+ );
+
+ return { getValuesForTask };
+}
+
+export default useGetCachedCustomFieldValues;
diff --git a/apps/web/src/hooks/queries/custom-field/use-get-custom-field-filter-values.ts b/apps/web/src/hooks/queries/custom-field/use-get-custom-field-filter-values.ts
new file mode 100644
index 000000000..3da374ec9
--- /dev/null
+++ b/apps/web/src/hooks/queries/custom-field/use-get-custom-field-filter-values.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import getCustomFieldFilterValues from "@/fetchers/custom-field/get-custom-field-filter-values";
+
+function useGetCustomFieldFilterValues(projectId: string) {
+ return useQuery({
+ queryKey: ["custom-field-filter-values", projectId],
+ queryFn: () => getCustomFieldFilterValues({ projectId }),
+ enabled: !!projectId,
+ });
+}
+
+export default useGetCustomFieldFilterValues;
diff --git a/apps/web/src/hooks/queries/custom-field/use-get-custom-field-values-by-task.ts b/apps/web/src/hooks/queries/custom-field/use-get-custom-field-values-by-task.ts
new file mode 100644
index 000000000..c696122a9
--- /dev/null
+++ b/apps/web/src/hooks/queries/custom-field/use-get-custom-field-values-by-task.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import getCustomFieldValuesByTask from "@/fetchers/custom-field/get-custom-field-values-by-task";
+
+function useGetCustomFieldValuesByTask(taskId: string) {
+ return useQuery({
+ queryKey: ["custom-field-values", taskId],
+ queryFn: () => getCustomFieldValuesByTask({ taskId }),
+ enabled: !!taskId,
+ });
+}
+
+export default useGetCustomFieldValuesByTask;
diff --git a/apps/web/src/hooks/queries/custom-field/use-get-custom-fields-by-project.ts b/apps/web/src/hooks/queries/custom-field/use-get-custom-fields-by-project.ts
new file mode 100644
index 000000000..b9c401ca3
--- /dev/null
+++ b/apps/web/src/hooks/queries/custom-field/use-get-custom-fields-by-project.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import getCustomFieldsByProject from "@/fetchers/custom-field/get-custom-fields-by-project";
+
+function useGetCustomFieldsByProject(projectId: string) {
+ return useQuery({
+ queryKey: ["custom-fields", projectId],
+ queryFn: () => getCustomFieldsByProject({ projectId }),
+ enabled: !!projectId,
+ });
+}
+
+export default useGetCustomFieldsByProject;
diff --git a/apps/web/src/hooks/use-task-filters-with-labels-support.test.tsx b/apps/web/src/hooks/use-task-filters-with-labels-support.test.tsx
index 45170836c..25de415b5 100644
--- a/apps/web/src/hooks/use-task-filters-with-labels-support.test.tsx
+++ b/apps/web/src/hooks/use-task-filters-with-labels-support.test.tsx
@@ -1,7 +1,28 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { useTaskFiltersWithLabelsSupport } from "./use-task-filters-with-labels-support";
+function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+}
+
+function createWrapper() {
+ const queryClient = createTestQueryClient();
+
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
describe("useTaskFiltersWithLabelsSupport", () => {
const storageKey = "kaneo:board-filters:project-1";
@@ -90,8 +111,11 @@ describe("useTaskFiltersWithLabelsSupport", () => {
archivedTasks: [],
};
- const { result } = renderHook(() =>
- useTaskFiltersWithLabelsSupport(project, "project-1"),
+ const { result } = renderHook(
+ () => useTaskFiltersWithLabelsSupport(project, "project-1"),
+ {
+ wrapper: createWrapper(),
+ },
);
await waitFor(() => {
@@ -172,8 +196,11 @@ describe("useTaskFiltersWithLabelsSupport", () => {
archivedTasks: [],
};
- const { result } = renderHook(() =>
- useTaskFiltersWithLabelsSupport(project, "project-1", textQuery),
+ const { result } = renderHook(
+ () => useTaskFiltersWithLabelsSupport(project, "project-1", textQuery),
+ {
+ wrapper: createWrapper(),
+ },
);
expect(result.current.filteredProject?.columns[0]?.tasks).toEqual([
diff --git a/apps/web/src/hooks/use-task-filters-with-labels-support.ts b/apps/web/src/hooks/use-task-filters-with-labels-support.ts
index 6cc3647a4..92dc594c4 100644
--- a/apps/web/src/hooks/use-task-filters-with-labels-support.ts
+++ b/apps/web/src/hooks/use-task-filters-with-labels-support.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { useUserPreferencesStore } from "@/store/user-preferences";
import type { ProjectWithTasks } from "@/types/project";
import type Task from "@/types/task";
+import useGetCachedCustomFieldValues from "./queries/custom-field/use-get-all-custom-field-values-by-project";
import { type BoardFilters, DUE_DATE_FILTER_VALUES } from "./use-task-filters";
const DEFAULT_FILTERS: BoardFilters = {
@@ -11,6 +12,7 @@ const DEFAULT_FILTERS: BoardFilters = {
assignee: null,
dueDate: null,
labels: null,
+ customFields: null,
};
const FILTER_KEYS: Array<keyof BoardFilters> = [
@@ -19,6 +21,7 @@ const FILTER_KEYS: Array<keyof BoardFilters> = [
"assignee",
"dueDate",
"labels",
+ "customFields",
];
function normalizeFilters(raw: unknown): BoardFilters {
@@ -30,6 +33,24 @@ function normalizeFilters(raw: unknown): BoardFilters {
const normalized = { ...DEFAULT_FILTERS };
for (const key of FILTER_KEYS) {
+ if (key === "customFields") {
+ const value = candidate.customFields;
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ const customFields = Object.fromEntries(
+ Object.entries(value).filter(
+ ([, values]) =>
+ Array.isArray(values) &&
+ values.length > 0 &&
+ values.every((item) => typeof item === "string"),
+ ),
+ ) as Record<string, string[]>;
+
+ normalized.customFields =
+ Object.keys(customFields).length > 0 ? customFields : null;
+ }
+
+ continue;
+ }
const value = candidate[key];
if (Array.isArray(value)) {
const values = value.filter((v): v is string => typeof v === "string");
@@ -48,6 +69,7 @@ export function useTaskFiltersWithLabelsSupport(
const weekStartsOn = useUserPreferencesStore((state) => state.weekStartsOn);
const storageKey = projectId ? `kaneo:board-filters:${projectId}` : null;
const [filters, setFilters] = useState<BoardFilters>(DEFAULT_FILTERS);
+ const { getValuesForTask } = useGetCachedCustomFieldValues();
useEffect(() => {
if (!storageKey || typeof window === "undefined") return;
@@ -179,10 +201,27 @@ export function useTaskFiltersWithLabelsSupport(
}
}
+ if (
+ filters.customFields &&
+ Object.keys(filters.customFields).length > 0
+ ) {
+ const taskFieldValues = getValuesForTask(task.id);
+ const matchesAllFields = Object.entries(filters.customFields).every(
+ ([fieldId, allowedValues]) => {
+ const fieldEntry = taskFieldValues.find(
+ (v) => v.fieldId === fieldId,
+ );
+ if (!fieldEntry?.value) return false;
+ return allowedValues.includes(fieldEntry.value);
+ },
+ );
+ if (!matchesAllFields) return false;
+ }
+
return true;
});
},
- [filters, project?.slug, textQuery, weekStartsOn],
+ [filters, project?.slug, textQuery, weekStartsOn, getValuesForTask],
);
const filteredProject = useMemo(() => {
@@ -230,11 +269,29 @@ export function useTaskFiltersWithLabelsSupport(
});
};
+ const updateCustomFieldFilter = (fieldId: string, value: string) => {
+ setFilters((prev) => {
+ const current = prev.customFields ?? {};
+ const existing = current[fieldId] ?? [];
+ const isSelected = existing.includes(value);
+ const next = isSelected
+ ? existing.filter((v) => v !== value)
+ : [...existing, value];
+ const updated = { ...current, [fieldId]: next };
+ if (updated[fieldId].length === 0) delete updated[fieldId];
+ return {
+ ...prev,
+ customFields: Object.keys(updated).length > 0 ? updated : null,
+ };
+ });
+ };
+
return {
filters,
setFilters,
updateFilter,
updateLabelFilter,
+ updateCustomFieldFilter,
filteredProject,
hasActiveFilters,
clearFilters,
diff --git a/apps/web/src/hooks/use-task-filters.ts b/apps/web/src/hooks/use-task-filters.ts
index cbbce1cb8..63a3da184 100644
--- a/apps/web/src/hooks/use-task-filters.ts
+++ b/apps/web/src/hooks/use-task-filters.ts
@@ -10,6 +10,7 @@ export type BoardFilters = {
assignee: string[] | null;
dueDate: string[] | null;
labels: string[] | null;
+ customFields: Record<string, string[]> | null;
};
export const DUE_DATE_FILTER_VALUES = {
@@ -24,6 +25,7 @@ const DEFAULT_FILTERS: BoardFilters = {
assignee: null,
dueDate: null,
labels: null,
+ customFields: null,
};
const FILTER_KEYS: Array<keyof BoardFilters> = [
@@ -32,6 +34,7 @@ const FILTER_KEYS: Array<keyof BoardFilters> = [
"assignee",
"dueDate",
"labels",
+ "customFields",
];
function normalizeFilters(raw: unknown): BoardFilters {
@@ -43,6 +46,13 @@ function normalizeFilters(raw: unknown): BoardFilters {
const normalized = { ...DEFAULT_FILTERS };
for (const key of FILTER_KEYS) {
+ if (key === "customFields") {
+ const value = candidate.customFields;
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ normalized.customFields = value as Record<string, string[]>;
+ }
+ continue;
+ }
const value = candidate[key];
if (Array.isArray(value)) {
const values = value.filter((v): v is string => typeof v === "string");
@@ -153,6 +163,19 @@ export function useTaskFilters(
}
}
+ if (
+ filters.customFields &&
+ Object.keys(filters.customFields).length > 0
+ ) {
+ for (const [fieldId, values] of Object.entries(filters.customFields)) {
+ if (values.length === 0) continue;
+ const taskValue =
+ task.customFieldValues?.find((v) => v.fieldId === fieldId)?.value ??
+ null;
+ if (!taskValue || !values.includes(taskValue)) return false;
+ }
+ }
+
return true;
});
};
@@ -200,11 +223,29 @@ export function useTaskFilters(
});
};
+ const updateCustomFieldFilter = (fieldId: string, value: string) => {
+ setFilters((prev) => {
+ const current = prev.customFields ?? {};
+ const existing = current[fieldId] ?? [];
+ const isSelected = existing.includes(value);
+ const next = isSelected
+ ? existing.filter((v) => v !== value)
+ : [...existing, value];
+ const updated = { ...current, [fieldId]: next };
+ if (updated[fieldId].length === 0) delete updated[fieldId];
+ return {
+ ...prev,
+ customFields: Object.keys(updated).length > 0 ? updated : null,
+ };
+ });
+ };
+
return {
filters,
setFilters,
updateFilter,
updateLabelFilter,
+ updateCustomFieldFilter,
filteredProject,
hasActiveFilters,
clearFilters,
diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/workflow.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/workflow.tsx
index 3d1451bc0..899727dd0 100644
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/workflow.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/workflow.tsx
@@ -2,6 +2,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import PageTitle from "@/components/page-title";
import ColumnEditor from "@/components/project/column-editor";
+import CustomFieldEditor from "@/components/project/custom-field-editor";
import WorkflowEditor from "@/components/project/workflow-editor";
export const Route = createFileRoute(
@@ -39,6 +40,18 @@ function RouteComponent() {
<ColumnEditor projectId={projectId} />
</div>
+ <div className="space-y-6">
+ <div className="space-y-1">
+ <h2 className="text-md font-medium">
+ {t("settings:customFields.heading")}
+ </h2>
+ <p className="text-xs text-muted-foreground">
+ {t("settings:customFields.hint")}
+ </p>
+ </div>
+ <CustomFieldEditor projectId={projectId} />
+ </div>
+
<div className="space-y-6">
<div className="space-y-1">
<h2 className="text-md font-medium">
diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/backlog.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/backlog.tsx
index cb547df02..b7e00bf6f 100644
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/backlog.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/backlog.tsx
@@ -20,11 +20,17 @@ import {
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/menu";
import labelColors from "@/constants/label-colors";
import { shortcuts } from "@/constants/shortcuts";
import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";
+import useGetCachedCustomFieldValues from "@/hooks/queries/custom-field/use-get-all-custom-field-values-by-project";
+import useGetCustomFieldFilterValues from "@/hooks/queries/custom-field/use-get-custom-field-filter-values";
+import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";
import { useGetTasks } from "@/hooks/queries/task/use-get-tasks";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
@@ -71,6 +77,17 @@ function RouteComponent() {
const { data: workspaceLabels = [] } = useGetLabelsByWorkspace(workspaceId);
const queryClient = useQueryClient();
+ const { data: rawCustomFields = [] } = useGetCustomFieldsByProject(projectId);
+ const { data: filterValuesData = [] } =
+ useGetCustomFieldFilterValues(projectId);
+ const { getValuesForTask } = useGetCachedCustomFieldValues();
+
+ const usedCustomFieldValues = useMemo<Record<string, string[]>>(
+ () =>
+ Object.fromEntries(filterValuesData.map((f) => [f.fieldId, f.values])),
+ [filterValuesData],
+ );
+
const handleCloseTaskSheet = useCallback(() => {
navigate({
to: ".",
@@ -114,6 +131,7 @@ function RouteComponent() {
assignee: null as string | null,
dueDate: null as string | null,
labels: [] as string[],
+ customFields: {} as Record<string, string[]>,
});
const updateFilter = (key: string, value: string | null) => {
@@ -129,18 +147,51 @@ function RouteComponent() {
}));
};
+ const updateCustomFieldFilter = (fieldId: string, value: string) => {
+ setFilters((prev) => {
+ const existing = prev.customFields[fieldId] ?? [];
+ const next = existing.includes(value)
+ ? existing.filter((v) => v !== value)
+ : [...existing, value];
+ const updated = { ...prev.customFields };
+ if (next.length > 0) {
+ updated[fieldId] = next;
+ } else {
+ delete updated[fieldId];
+ }
+ return { ...prev, customFields: updated };
+ });
+ };
+
+ const clearCustomFieldFilter = (fieldId: string) => {
+ setFilters((prev) => {
+ const updated = { ...prev.customFields };
+ delete updated[fieldId];
+ return { ...prev, customFields: updated };
+ });
+ };
+
const clearFilters = () => {
setFilters({
priority: null,
assignee: null,
dueDate: null,
labels: [],
+ customFields: {},
});
};
- const hasActiveFilters = Object.values(filters).some((filter) =>
- Array.isArray(filter) ? filter.length > 0 : filter !== null,
- );
+ const hasActiveFilters = Object.values(filters).some((filter) => {
+ if (Array.isArray(filter)) {
+ return filter.length > 0;
+ }
+
+ if (filter && typeof filter === "object") {
+ return Object.keys(filter).length > 0;
+ }
+
+ return filter !== null && filter !== undefined;
+ });
useEffect(() => {
if (data) {
@@ -234,6 +285,18 @@ function RouteComponent() {
}
}
+ if (Object.keys(filters.customFields).length > 0) {
+ const taskFieldValues = getValuesForTask(task.id);
+ const allMatch = Object.entries(filters.customFields).every(
+ ([fieldId, selectedVals]) => {
+ if (!selectedVals.length) return true;
+ const entry = taskFieldValues.find((v) => v.fieldId === fieldId);
+ return entry?.value != null && selectedVals.includes(entry.value);
+ },
+ );
+ if (!allMatch) return false;
+ }
+
return true;
});
};
@@ -243,7 +306,7 @@ function RouteComponent() {
plannedTasks: filterTasks(project.plannedTasks || []),
archivedTasks: filterTasks(project.archivedTasks || []),
};
- }, [project, filters, getTaskLabels]);
+ }, [project, filters, getTaskLabels, getValuesForTask]);
const uniqueLabels = workspaceLabels.reduce(
(
@@ -518,6 +581,46 @@ function RouteComponent() {
</Button>
))}
+ {Object.entries(filters.customFields).map(([fieldId, vals]) => {
+ if (!vals.length) return null;
+ const field = rawCustomFields.find((f) => f.id === fieldId);
+ if (!field) return null;
+ return (
+ <Button
+ key={fieldId}
+ variant="secondary"
+ size="xs"
+ className="h-7 rounded-md px-2 text-xs font-medium gap-1.5"
+ >
+ <span>{field.name}</span>
+ <span className="text-muted-foreground">:</span>
+ <span>
+ {vals.length === 1
+ ? field.type === "boolean"
+ ? vals[0] === "true"
+ ? "True"
+ : "False"
+ : vals[0]
+ : t("tasks:boardFilters.selectedCount", {
+ count: vals.length,
+ defaultValue: `${vals.length} selected`,
+ })}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-4 w-4 p-0 ml-1 hover:bg-destructive hover:text-destructive-foreground"
+ onClick={(e) => {
+ e.stopPropagation();
+ clearCustomFieldFilter(fieldId);
+ }}
+ >
+ <X className="h-2.5 w-2.5" />
+ </Button>
+ </Button>
+ );
+ })}
+
<SortControl sort={sort} onSortChange={setSort} />
<DropdownMenu>
@@ -680,6 +783,97 @@ function RouteComponent() {
<span>{t("tasks:labels.empty")}</span>
</DropdownMenuItem>
)}
+ {rawCustomFields.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-[11px] uppercase tracking-wide">
+ Custom Fields
+ </DropdownMenuLabel>
+ </DropdownMenuGroup>
+
+ {rawCustomFields.map((field) => {
+ const selectedVals =
+ filters.customFields[field.id] ?? [];
+
+ let displayOptions: string[] = [];
+ if (field.type === "dropdown") {
+ displayOptions = Array.isArray(field.options)
+ ? (field.options as string[])
+ : [];
+ } else if (field.type === "boolean") {
+ displayOptions = ["true", "false"];
+ } else {
+ displayOptions =
+ usedCustomFieldValues[field.id] ?? [];
+ }
+
+ const labelForOption = (opt: string) => {
+ if (field.type === "boolean")
+ return opt === "true" ? "True" : "False";
+ return opt;
+ };
+
+ return (
+ <DropdownMenuSub key={field.id}>
+ <DropdownMenuSubTrigger className="h-8 rounded-md text-sm">
+ <span className="flex flex-1 items-center justify-between gap-2">
+ <span className="truncate">{field.name}</span>
+ {selectedVals.length > 0 && (
+ <span className="ml-auto inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground">
+ {selectedVals.length}
+ </span>
+ )}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-48">
+ {selectedVals.length > 0 && (
+ <>
+ <DropdownMenuItem
+ onClick={() =>
+ clearCustomFieldFilter(field.id)
+ }
+ className="h-8 rounded-md text-sm text-muted-foreground"
+ >
+ {t("common:actions.clearAllFilters", {
+ defaultValue: "Clear",
+ })}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {displayOptions.length === 0 ? (
+ <DropdownMenuItem
+ disabled
+ className="h-8 rounded-md text-sm text-muted-foreground"
+ >
+ {t("tasks:boardFilters.noValuesUsedYet")}
+ </DropdownMenuItem>
+ ) : (
+ displayOptions.map((option) => (
+ <DropdownMenuCheckboxItem
+ key={option}
+ checked={selectedVals.includes(option)}
+ onCheckedChange={() =>
+ updateCustomFieldFilter(
+ field.id,
+ option,
+ )
+ }
+ className="h-8 rounded-md text-sm"
+ >
+ <span className="truncate">
+ {labelForOption(option)}
+ </span>
+ </DropdownMenuCheckboxItem>
+ ))
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })}
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
index 087c2e4bd..84f2a14d6 100644
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx
@@ -7,10 +7,13 @@ import ProjectLayout from "@/components/common/project-layout";
import KanbanBoard from "@/components/kanban-board";
import ListView from "@/components/list-view";
import PageTitle from "@/components/page-title";
+import type { CustomFieldDefinition } from "@/components/project/custom-field-editor";
import CreateTaskModal from "@/components/shared/modals/create-task-modal";
import TaskDetailsSheet from "@/components/task/task-details-sheet";
import { Input } from "@/components/ui/input";
import { shortcuts } from "@/constants/shortcuts";
+import useGetCustomFieldFilterValues from "@/hooks/queries/custom-field/use-get-custom-field-filter-values";
+import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";
import { useGetTasks } from "@/hooks/queries/task/use-get-tasks";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
@@ -93,6 +96,28 @@ function RouteComponent() {
const { data: users } = useGetActiveWorkspaceUsers(workspaceId);
const { data: workspaceLabels = [] } = useGetLabelsByWorkspace(workspaceId);
+ const { data: rawCustomFields = [] } = useGetCustomFieldsByProject(projectId);
+
+ const { data: filterValuesData = [] } =
+ useGetCustomFieldFilterValues(projectId);
+
+ const customFieldDefinitions = useMemo<CustomFieldDefinition[]>(
+ () =>
+ rawCustomFields.map((f, index) => ({
+ ...f,
+ type: f.type as CustomFieldDefinition["type"],
+ options: Array.isArray(f.options) ? (f.options as string[]) : null,
+ position: index,
+ })),
+ [rawCustomFields],
+ );
+
+ const usedCustomFieldValues = useMemo<Record<string, string[]>>(() => {
+ return Object.fromEntries(
+ filterValuesData.map((f) => [f.fieldId, f.values]),
+ );
+ }, [filterValuesData]);
+
const handleCloseTaskSheet = useCallback(() => {
navigate({
to: ".",
@@ -160,6 +185,7 @@ function RouteComponent() {
filters,
updateFilter,
updateLabelFilter,
+ updateCustomFieldFilter,
filteredProject,
hasActiveFilters,
clearFilters,
@@ -222,6 +248,7 @@ function RouteComponent() {
filters={filters}
updateFilter={updateFilter}
updateLabelFilter={updateLabelFilter}
+ updateCustomFieldFilter={updateCustomFieldFilter}
clearFilters={clearFilters}
hasActiveFilters={hasActiveFilters}
users={users}
@@ -230,6 +257,8 @@ function RouteComponent() {
setViewMode={setViewMode}
sort={sort}
onSortChange={setSort}
+ customFieldDefinitions={customFieldDefinitions}
+ usedCustomFieldValues={usedCustomFieldValues}
/>
<div className="flex h-full flex-1 overflow-hidden bg-background">
diff --git a/apps/web/src/types/task/index.ts b/apps/web/src/types/task/index.ts
index 9e62f501b..2705509aa 100644
--- a/apps/web/src/types/task/index.ts
+++ b/apps/web/src/types/task/index.ts
@@ -15,6 +15,11 @@ type TaskExternalLink = {
metadata: Record<string, unknown> | null;
};
+type TaskCustomFieldValue = {
+ fieldId: string;
+ value: string | null;
+};
+
type Task = {
id: string;
title: string;
@@ -35,6 +40,7 @@ type Task = {
columnId?: string | null;
labels?: TaskLabel[];
externalLinks?: TaskExternalLink[];
+ customFieldValues?: TaskCustomFieldValue[];
};
export default Task;
diff --git a/i18n/en-US.json b/i18n/en-US.json
index f80ce52a9..3f2563d4e 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -856,6 +856,34 @@
"newColumnPlaceholder": "New column name...",
"add": "Add"
},
+ "customFields": {
+ "heading": "Custom fields",
+ "hint": "Create additional task fields for this project.",
+ "namePlaceholder": "Field name",
+ "typePlaceholder": "Select field type",
+ "noOptionsPlaceholder": "No options",
+ "defaultValuePlaceholder": "Default value",
+ "optionsPlaceholder": "Options separated by commas",
+ "required": "Required",
+ "addButton": "Add",
+ "creating": "Creating...",
+ "loading": "Loading custom fields...",
+ "empty": "No custom fields configured yet.",
+ "defaultLabel": "Default",
+ "createSuccess": "Custom field created.",
+ "createError": "Failed to create custom field.",
+ "deleteButton": "Delete",
+ "deleting": "Deleting...",
+ "deleteSuccess": "Custom field deleted.",
+ "deleteError": "Failed to delete custom field.",
+ "types": {
+ "text": "Text",
+ "number": "Number",
+ "date": "Date",
+ "dropdown": "Dropdown",
+ "boolean": "Boolean"
+ }
+ },
"githubIntegration": {
"validation": {
"ownerRequired": "Repository owner is required",
@@ -1535,10 +1563,13 @@
"selectTask": "Select task",
"loadingTask": "Loading task...",
"taskNotFound": "Task not found",
- "taskNotFoundDescription": "The task you are looking for does not exist or has been deleted."
+ "taskNotFoundDescription": "The task you are looking for does not exist or has been deleted.",
+ "customFields": "Custom Fields"
},
"detail": {
"subtaskOf": "Subtask of",
+ "customFieldUpdated": "Field updated",
+ "selectOption": "Select option",
"activity": "Activity",
"noActivity": "No activity found",
"openInFullPage": "Open in full page",
@@ -1789,7 +1820,11 @@
"allAssignees": "All assignees",
"allDueDates": "All due dates",
"allLabels": "All labels",
+ "noValuesUsedYet": "No values used yet",
+ "noCustomFieldValues": "No custom field values",
+ "allCustomFieldValues": "All values",
"selectedCount": "{{count}} selected",
+ "all": "All",
"subjects": {
"status": "Status",
"priority": "Priority",