feat: improve form response experience

This commit is contained in:
2026-07-24 22:11:42 +07:00 Unverified
parent 29df784aeb
commit 7a9e67e283
12 changed files with 1279 additions and 349 deletions
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import {
decodeCheckboxAnswer,
encodeAnswerValue,
formatStoredAnswer,
} from "@/lib/form-answer-values";
describe("form answer values", () => {
test("round-trips checkbox choices containing commas", () => {
const choices = ["Alpha, beta", "Gamma"];
const stored = encodeAnswerValue(choices);
expect(decodeCheckboxAnswer(stored)).toEqual(choices);
expect(formatStoredAnswer(stored, "checkbox")).toBe("Alpha, beta, Gamma");
});
test("continues to read legacy comma-separated checkbox answers", () => {
expect(decodeCheckboxAnswer("Alpha, Beta")).toEqual(["Alpha", "Beta"]);
});
test("does not decode JSON-looking text answers", () => {
expect(formatStoredAnswer('["plain text"]', "text")).toBe('["plain text"]');
});
});
+41
View File
@@ -0,0 +1,41 @@
import type { QuestionType } from "@/db/schema/form";
export type FormAnswerValue = string | string[];
export function decodeCheckboxAnswer(value: FormAnswerValue | undefined): string[] {
if (Array.isArray(value)) {
return value.filter((item): item is string => typeof item === "string");
}
if (!value) {
return [];
}
try {
const parsed: unknown = JSON.parse(value);
if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
return parsed;
}
} catch {
// Older checkbox answers were stored as comma-separated text.
}
return value.split(", ").filter(Boolean);
}
export function encodeAnswerValue(value: FormAnswerValue): string {
return Array.isArray(value) ? JSON.stringify(value) : value;
}
export function formatStoredAnswer(
value: string | undefined,
questionType: QuestionType | string
): string {
if (!value) {
return "";
}
return questionType === "checkbox"
? decodeCheckboxAnswer(value).join(", ")
: value;
}