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.

fix(custom-fields): preserve drafts and reconcile stale filters

Tin3654dbcbbc72
diff --git a/apps/api/src/custom-field/controllers/create-custom-field.ts b/apps/api/src/custom-field/controllers/create-custom-field.ts
index c0ea79d4c..141a05116 100644
--- a/apps/api/src/custom-field/controllers/create-custom-field.ts
+++ b/apps/api/src/custom-field/controllers/create-custom-field.ts
@@ -132,7 +132,9 @@ async function createCustomField(
}
const storedDefaultValue =
- type === "date" ? defaultValue?.trim() : defaultValue;
+ type === "date" || type === "dropdown"
+ ? defaultValue?.trim()
+ : defaultValue;
const [maxPositionResult] = await db
.select({ maxPosition: max(customFieldDefinitionTable.position) })
diff --git a/apps/api/src/custom-field/controllers/update-custom-field.ts b/apps/api/src/custom-field/controllers/update-custom-field.ts
index b0e9be71c..a7417916b 100644
--- a/apps/api/src/custom-field/controllers/update-custom-field.ts
+++ b/apps/api/src/custom-field/controllers/update-custom-field.ts
@@ -94,7 +94,7 @@ export default async function updateCustomField(
}
return replacement;
};
- if (field.type === "dropdown") return replace(value);
+ if (field.type === "dropdown") return replace(value.trim());
let selected: unknown;
try {
selected = JSON.parse(value);
@@ -118,11 +118,16 @@ export default async function updateCustomField(
defaultValue =
withoutHiddenOptions(defaultValue, field.type, hiddenOptions) || null;
}
- const values = await tx
- .select()
- .from(customFieldValueTable)
- .where(eq(customFieldValueTable.fieldId, id))
- .for("update");
+ const needsMigration = oldOptions.some(
+ (option) => replacements.get(option) !== option,
+ );
+ const values = needsMigration
+ ? await tx
+ .select()
+ .from(customFieldValueTable)
+ .where(eq(customFieldValueTable.fieldId, id))
+ .for("update")
+ : [];
const changed = values
.map((row) => ({
id: row.id,
diff --git a/apps/api/src/custom-field/index.ts b/apps/api/src/custom-field/index.ts
index 5ab9b476a..12e8c769e 100644
--- a/apps/api/src/custom-field/index.ts
+++ b/apps/api/src/custom-field/index.ts
@@ -237,9 +237,7 @@ const updateCustomFieldRoute = createRoute({
},
responses: {
200: jsonResponse("The updated custom field", customFieldDefinitionSchema),
- 400: errorResponse(
- "Invalid options, an option is in use, or unknown field",
- ),
+ 400: errorResponse("Invalid options or an option is in use"),
403: errorResponse(
"No workspace access or missing project:update permission",
),
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index bd257cf39..babbc395c 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -17091,7 +17091,7 @@
}
},
"400": {
- "description": "Invalid options, an option is in use, or unknown field",
+ "description": "Invalid options or an option is in use",
"content": {
"text/plain": {
"schema": {
diff --git a/apps/web/src/components/project/custom-field-editor.tsx b/apps/web/src/components/project/custom-field-editor.tsx
index be82bb5e6..97fce35cd 100644
--- a/apps/web/src/components/project/custom-field-editor.tsx
+++ b/apps/web/src/components/project/custom-field-editor.tsx
@@ -561,7 +561,9 @@ export default function CustomFieldEditor({
variant="ghost"
size="sm"
className="h-7 w-7 p-0 shrink-0"
- disabled={!canUpdateProjects || deletingField || isReordering}
+ disabled={
+ !canUpdateProjects() || deletingField || isReordering
+ }
onClick={() => setEditingField(field)}
aria-label={t("settings:customFields.editButton")}
>
diff --git a/apps/web/src/components/task/task-details-content.tsx b/apps/web/src/components/task/task-details-content.tsx
index 4058525b9..fceebb02b 100644
--- a/apps/web/src/components/task/task-details-content.tsx
+++ b/apps/web/src/components/task/task-details-content.tsx
@@ -1,7 +1,7 @@
import { useNavigate } from "@tanstack/react-router";
import { format, isValid, parseISO } from "date-fns";
import { ArrowUpRight, CalendarIcon, X } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import Activity from "@/components/activity";
import CommentInput from "@/components/activity/comment-input";
@@ -39,6 +39,7 @@ 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 { useCustomFieldDrafts } from "@/hooks/use-custom-field-drafts";
import { useWorkspacePermission } from "@/hooks/use-workspace-permission";
import { cn } from "@/lib/cn";
import { toast } from "@/lib/toast";
@@ -94,6 +95,9 @@ function safeParseMultiselect(raw: string | null | undefined): string[] {
}
}
+const EMPTY_CUSTOM_FIELDS: CustomFieldDefinition[] = [];
+const EMPTY_CUSTOM_FIELD_VALUES: never[] = [];
+
export default function TaskDetailsContent({
taskId,
projectId,
@@ -110,21 +114,19 @@ export default function TaskDetailsContent({
const { data: relations = [] } = useGetTaskRelations(taskId ?? "");
const { user } = useAuth();
- const { data: customFields = [] } = useGetCustomFieldsByProject(
- projectId,
- ) as { data: CustomFieldDefinition[] | undefined };
+ const { data: customFields = EMPTY_CUSTOM_FIELDS } =
+ useGetCustomFieldsByProject(projectId) as {
+ data: CustomFieldDefinition[] | undefined;
+ };
- const { data: customFieldValues = [] } = useGetCustomFieldValuesByTask(
- taskId ?? "",
- );
+ const { data: customFieldValues = EMPTY_CUSTOM_FIELD_VALUES } =
+ useGetCustomFieldValuesByTask(taskId ?? "");
const { mutateAsync: setCustomFieldValue } = useSetCustomFieldValue();
const { canUpdateTasks } = useWorkspacePermission();
const canEdit = canUpdateTasks();
- const [localValues, setLocalValues] = useState<CustomFieldValueMap>({});
-
- useEffect(() => {
+ const serverValues = useMemo(() => {
const valuesMap: CustomFieldValueMap = {};
for (const field of customFields) {
@@ -142,15 +144,14 @@ export default function TaskDetailsContent({
: (val.value ?? "");
}
- setLocalValues(valuesMap);
+ return valuesMap;
}, [customFields, customFieldValues]);
- const handleLocalChange = (fieldId: string, val: string | string[]) => {
- setLocalValues((prev: CustomFieldValueMap) => ({
- ...prev,
- [fieldId]: val,
- }));
- };
+ const {
+ values: localValues,
+ change: handleLocalChange,
+ finish,
+ } = useCustomFieldDrafts(taskId, serverValues);
const handleSaveField = async (fieldId: string, value: string | string[]) => {
if (!taskId) return;
@@ -169,7 +170,10 @@ export default function TaskDetailsContent({
? JSON.stringify(safeParseMultiselect(existingRaw))
: existingRaw;
- if (serializedValue === existingComparable) return;
+ if (serializedValue === existingComparable) {
+ finish(fieldId, value);
+ return;
+ }
try {
await setCustomFieldValue({
@@ -179,10 +183,12 @@ export default function TaskDetailsContent({
projectId,
});
+ finish(fieldId, value);
toast.success(t("tasks:detail.customFieldUpdated", "Field updated"));
} catch (error) {
- handleLocalChange(
+ finish(
fieldId,
+ value,
isMultiselect ? safeParseMultiselect(existingRaw) : existingRaw,
);
toast.error(
diff --git a/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts b/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts
index 2670844cd..5614fba18 100644
--- a/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts
+++ b/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts
@@ -17,8 +17,6 @@ export default function useUpdateCustomField() {
["custom-fields", field.projectId],
["custom-field-values"],
["custom-field-filter-values", field.projectId],
- ["tasks", field.projectId],
- ["task"],
].map((queryKey) => queryClient.invalidateQueries({ queryKey })),
);
},
diff --git a/apps/web/src/hooks/use-custom-field-drafts.test.tsx b/apps/web/src/hooks/use-custom-field-drafts.test.tsx
new file mode 100644
index 000000000..afb74821d
--- /dev/null
+++ b/apps/web/src/hooks/use-custom-field-drafts.test.tsx
@@ -0,0 +1,44 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { useCustomFieldDrafts } from "./use-custom-field-drafts";
+
+describe("custom field drafts", () => {
+ it("preserves dirty text and selections while refreshing clean fields", () => {
+ const { result, rerender } = renderHook(
+ ({ values }) => useCustomFieldDrafts("task", values),
+ {
+ initialProps: {
+ values: { text: "Saved", people: ["Alice"], clean: "Old" },
+ },
+ },
+ );
+ act(() => {
+ result.current.change("text", "Typing");
+ result.current.change("people", ["Bob"]);
+ });
+ rerender({ values: { text: "Saved", people: ["Alex"], clean: "New" } });
+ expect(result.current.values).toEqual({
+ text: "Typing",
+ people: ["Bob"],
+ clean: "New",
+ });
+ act(() => result.current.finish("text", "Typing"));
+ rerender({ values: { text: "Remote", people: ["Alex"], clean: "New" } });
+ expect(result.current.values.text).toBe("Remote");
+ });
+ it("rolls back only the submitted edit and resets when switching tasks", () => {
+ const { result, rerender } = renderHook(
+ ({ id, values }) => useCustomFieldDrafts(id, values),
+ { initialProps: { id: "one", values: { text: "Saved" } } },
+ );
+ act(() => result.current.change("text", "First"));
+ act(() => result.current.change("text", "Second"));
+ act(() => result.current.finish("text", "First", "Saved"));
+ expect(result.current.values.text).toBe("Second");
+ act(() => result.current.finish("text", "Second", "Saved"));
+ expect(result.current.values.text).toBe("Saved");
+ act(() => result.current.change("text", "Unfinished"));
+ rerender({ id: "two", values: { text: "Other task" } });
+ expect(result.current.values.text).toBe("Other task");
+ });
+});
diff --git a/apps/web/src/hooks/use-custom-field-drafts.ts b/apps/web/src/hooks/use-custom-field-drafts.ts
new file mode 100644
index 000000000..7bfc2e30a
--- /dev/null
+++ b/apps/web/src/hooks/use-custom-field-drafts.ts
@@ -0,0 +1,41 @@
+import { useEffect, useRef, useState } from "react";
+
+type Value = string | string[];
+type Values = Record<string, Value>;
+
+export function useCustomFieldDrafts(
+ taskId: string | undefined,
+ serverValues: Values,
+) {
+ const [values, setValues] = useState<Values>(serverValues);
+ const dirty = useRef(new Map<string, Value>());
+ const currentTask = useRef(taskId);
+ useEffect(() => {
+ if (currentTask.current !== taskId) {
+ currentTask.current = taskId;
+ dirty.current.clear();
+ }
+ setValues((previous) =>
+ Object.fromEntries(
+ Object.entries(serverValues).map(([id, value]) => [
+ id,
+ dirty.current.has(id) ? previous[id] : value,
+ ]),
+ ),
+ );
+ }, [taskId, serverValues]);
+
+ const change = (id: string, value: Value) => {
+ dirty.current.set(id, value);
+ setValues((previous) => ({ ...previous, [id]: value }));
+ };
+ const finish = (id: string, submitted: Value, rollback?: Value) => {
+ // A response for an older save must not erase a newer edit or another task's draft.
+ if (currentTask.current !== taskId || dirty.current.get(id) !== submitted)
+ return;
+ dirty.current.delete(id);
+ if (rollback !== undefined)
+ setValues((previous) => ({ ...previous, [id]: rollback }));
+ };
+ return { values, change, finish };
+}
diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
index b872dfc26..bcd2052c4 100644
--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
@@ -53,7 +53,7 @@ describe("project WebSocket lifecycle", () => {
vi.unstubAllEnvs();
});
- it("refreshes definitions, selections, filters and tasks after an option rename", () => {
+ it("refreshes definitions, selections, filters after an option rename", () => {
renderHook(() => useProjectWebSocket("project-a"));
act(() =>
TestSocket.instances[0].onmessage?.({
@@ -63,12 +63,11 @@ describe("project WebSocket lifecycle", () => {
}),
}),
);
+ expect(client.invalidateQueries).toHaveBeenCalledTimes(3);
for (const queryKey of [
["custom-fields", "project-a"],
["custom-field-values"],
["custom-field-filter-values", "project-a"],
- ["tasks", "project-a"],
- ["task"],
]) {
expect(client.invalidateQueries).toHaveBeenCalledWith({ queryKey });
}
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index fe7286dff..8d836ad89 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -67,8 +67,6 @@ export function useProjectWebSocket(projectId: string) {
["custom-fields", projectId],
["custom-field-values"],
["custom-field-filter-values", projectId],
- ["tasks", projectId],
- ["task"],
]) {
void queryClient.invalidateQueries({ queryKey });
}
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 c1ede7365..576548a89 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
@@ -5,6 +5,7 @@ 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";
+import { useValidCustomFieldFilters } from "./use-valid-custom-field-filters";
const DEFAULT_FILTERS: BoardFilters = {
status: null,
@@ -98,6 +99,8 @@ export function useTaskFiltersWithLabelsSupport(
}
}, [filters, storageKey]);
+ useValidCustomFieldFilters(projectId, setFilters);
+
const filterTasks = useCallback(
(tasks: Task[]): Task[] => {
const normalizedTextQuery = textQuery?.trim().toLowerCase();
diff --git a/apps/web/src/hooks/use-task-filters.ts b/apps/web/src/hooks/use-task-filters.ts
index bbd352ca2..a2b41bb46 100644
--- a/apps/web/src/hooks/use-task-filters.ts
+++ b/apps/web/src/hooks/use-task-filters.ts
@@ -3,6 +3,7 @@ import { useEffect, useState } from "react";
import { useUserPreferencesStore } from "@/store/user-preferences";
import type { ProjectWithTasks } from "@/types/project";
import type Task from "@/types/task";
+import { useValidCustomFieldFilters } from "./use-valid-custom-field-filters";
export type BoardFilters = {
status: string[] | null;
@@ -97,6 +98,8 @@ export function useTaskFilters(
}
}, [filters, storageKey]);
+ useValidCustomFieldFilters(projectId, setFilters);
+
const filterTasks = (tasks: Task[]): Task[] => {
return tasks.filter((task) => {
if (
diff --git a/apps/web/src/hooks/use-valid-custom-field-filters.test.tsx b/apps/web/src/hooks/use-valid-custom-field-filters.test.tsx
new file mode 100644
index 000000000..5496a44c1
--- /dev/null
+++ b/apps/web/src/hooks/use-valid-custom-field-filters.test.tsx
@@ -0,0 +1,46 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { useState } from "react";
+import { describe, expect, it, vi } from "vitest";
+import type { BoardFilters } from "./use-task-filters";
+import { useValidCustomFieldFilters } from "./use-valid-custom-field-filters";
+
+let fields:
+ | { id: string; type: string; options: string[]; hiddenOptions: string[] }[]
+ | undefined;
+vi.mock("./queries/custom-field/use-get-custom-fields-by-project", () => ({
+ default: () => ({ data: fields }),
+}));
+describe("persisted custom field filters", () => {
+ it("drops obsolete choices after loading or renaming while retaining historical hidden choices", async () => {
+ fields = undefined;
+ const { result, rerender } = renderHook(() => {
+ const [filters, setFilters] = useState<BoardFilters>({
+ status: ["planned"],
+ priority: null,
+ assignee: null,
+ labels: null,
+ dueDate: null,
+ customFields: { people: ["Alice", "Bob"], removed: ["Gone"] },
+ });
+ useValidCustomFieldFilters("project", setFilters);
+ return filters;
+ });
+ expect(result.current.customFields?.people).toEqual(["Alice", "Bob"]);
+ fields = [
+ {
+ id: "people",
+ type: "multiselect",
+ options: ["Alex", "Bob"],
+ hiddenOptions: ["Bob"],
+ },
+ ];
+ rerender();
+ await waitFor(() =>
+ expect(result.current.customFields).toEqual({ people: ["Bob"] }),
+ );
+ fields = [{ ...fields[0], options: ["Alex", "Robert"] }];
+ rerender();
+ await waitFor(() => expect(result.current.customFields).toBeNull());
+ expect(result.current.status).toEqual(["planned"]);
+ });
+});
diff --git a/apps/web/src/hooks/use-valid-custom-field-filters.ts b/apps/web/src/hooks/use-valid-custom-field-filters.ts
new file mode 100644
index 000000000..bffd9be09
--- /dev/null
+++ b/apps/web/src/hooks/use-valid-custom-field-filters.ts
@@ -0,0 +1,36 @@
+import { type Dispatch, type SetStateAction, useEffect } from "react";
+import useGetCustomFieldsByProject from "./queries/custom-field/use-get-custom-fields-by-project";
+import type { BoardFilters } from "./use-task-filters";
+
+// Reconcile on load as well as refetch, including edits made while this client was offline.
+export function useValidCustomFieldFilters(
+ projectId: string | undefined,
+ setFilters: Dispatch<SetStateAction<BoardFilters>>,
+) {
+ const { data: fields } = useGetCustomFieldsByProject(projectId ?? "");
+ useEffect(() => {
+ if (!fields) return;
+ setFilters((previous) => {
+ if (!previous.customFields) return previous;
+ const next = Object.fromEntries(
+ Object.entries(previous.customFields).flatMap(([id, values]) => {
+ const field = fields.find((candidate) => candidate.id === id);
+ if (!field || !Array.isArray(values)) return [];
+ const options = field.options;
+ const valid =
+ (field.type === "dropdown" || field.type === "multiselect") &&
+ Array.isArray(options)
+ ? values.filter((value) => options.includes(value))
+ : values;
+ return valid.length ? [[id, valid]] : [];
+ }),
+ );
+ if (JSON.stringify(next) === JSON.stringify(previous.customFields))
+ return previous;
+ return {
+ ...previous,
+ customFields: Object.keys(next).length ? next : null,
+ };
+ });
+ }, [fields, setFilters]);
+}
diff --git a/tests/api-integration/custom-field-edit.test.ts b/tests/api-integration/custom-field-edit.test.ts
index ceba583bc..4b71c64f4 100644
--- a/tests/api-integration/custom-field-edit.test.ts
+++ b/tests/api-integration/custom-field-edit.test.ts
@@ -69,6 +69,23 @@ async function fixture(type = "multiselect", role = "admin") {
}
describe("custom field editing", () => {
+ it("normalizes legacy dropdown defaults before renaming options", async () => {
+ const { field, update } = await fixture("dropdown");
+ await db
+ .update(schema.customFieldDefinitionTable)
+ .set({ defaultValue: " Alice ", updatedAt: field.updatedAt })
+ .where(eq(schema.customFieldDefinitionTable.id, field.id));
+ const response = await update({
+ options: [
+ { originalValue: "Alice", value: "Alex" },
+ { originalValue: "Bob", value: "Bob" },
+ { originalValue: "Unused", value: "Unused" },
+ ],
+ });
+ expect(response.status).toBe(200);
+ expect((await response.json()).defaultValue).toBe("Alex");
+ });
+
it.each(["dropdown", "multiselect"])(
"renames %s selections and defaults together, and adds/removes unused options",
async (type) => {