feat: improve form response experience
This commit is contained in:
@@ -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"]');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user