Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/survey-system.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ End-to-end survey flow, session management, and answer data structures.
- Questions loaded from YAML files, organized by sections
- Answers collected as: `{ "question-id": choiceIndex, "question-id-others": "text" }`
- Each section submitted via `submitAnswers` action
- Server validates session, saves to Firestore with userId as document ID (prevents duplicates)
- Server validates session, saves to Firestore collection `results-{SURVEY_YEAR}` with userId as document ID (prevents duplicates)
- New edition: bump `SURVEY_YEAR` (`src/lib/firebase/database.ts`) and `STORAGE_VERSION` (`src/components/survey/survey-context.tsx`)

### 3. Data Export (GitHub Actions daily at 12:00 AM UTC)

Expand Down
15 changes: 11 additions & 4 deletions src/actions/submit-answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,21 @@ import { z } from "astro:schema";
import { getAuth } from "firebase-admin/auth";
import { saveAnswers } from "@/lib/firebase/database";
import { getActiveApp } from "@/lib/firebase/server";
import { findInvalidAnswer } from "@/lib/validators/answers";

export const submitAnswers = defineAction({
accept: "json",
input: z.object({
answers: z.record(
z.string(),
z.union([z.number(), z.string().max(200), z.array(z.number()), z.null()])
)
answers: z
.record(
z.string(),
z.union([z.number(), z.string().max(200), z.array(z.number()), z.null()])
)
.superRefine((answers, ctx) => {
const error = findInvalidAnswer(answers);
if (error)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: error });
})
}),
handler: async ({ answers }, { cookies }) => {
const auth = getAuth(getActiveApp());
Expand Down
1 change: 1 addition & 0 deletions src/components/header.astro
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const navItems = [
{ year: 2022, href: "/2022" },
{ year: 2023, href: "/2023" },
{ year: 2024, href: "/2024" },
{ year: 2025, href: "/2025" },
{ label: "Playground", href: "/playground", icon: Chart },
{ label: "FAQ", href: "/faq" },
{ label: "Github", href: website.repoGithub, icon: Github, external: true }
Expand Down
2 changes: 1 addition & 1 deletion src/components/home/hero.astro
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ import Crea2 from "../../assets/undraw_visual_data.svg";
Take part in the survey{" "}
</div>
</a>
<a href="/2024" class="">
<a href="/2025" class="">
<div
class="relative inline-flex h-12 w-full items-center justify-center bg-muted px-6 font-medium tracking-wide text-muted-foreground border-2 border-border transition duration-200 md:w-auto focus:outline-none hover:opacity-90"
>
Expand Down
4 changes: 2 additions & 2 deletions src/components/survey/choice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ export function Choice({
>
</label>
<div
className="absolute pointer-events-none left-4 h-5 w-5 border-2 border-input bg-muted
className={`absolute pointer-events-none left-4 h-5 w-5 border-2 border-input bg-muted ${multiple ? "" : "rounded-full"}
peer-checked:border-primary peer-checked:bg-primary peer-checked:shadow-md peer-checked:shadow-primary/50
transition-all duration-200"
transition-all duration-200`}
>
</div>
<span
Expand Down
10 changes: 8 additions & 2 deletions src/components/survey/question.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ export function Question({
if (question.multiple) {
// Multiple choice: toggle in array
const currentArray = Array.isArray(value) ? value : [];
if (checked && question.maxChoices && currentArray.length >= question.maxChoices)
return;
const newValue = checked
? [...currentArray, choiceIndex]
: currentArray.filter(v => v !== choiceIndex);
Expand All @@ -74,7 +76,7 @@ export function Question({
onAnswerChange(choiceIndex);
}
},
[question.multiple, value, onAnswerChange]
[question.multiple, question.maxChoices, value, onAnswerChange]
);

const handleOthersChange = useCallback(
Expand Down Expand Up @@ -113,7 +115,11 @@ export function Question({
</label>

<span className="font-normal text-sm pl-2.5">
{question.multiple ? "- You can choose multiple answers " : ""}
{question.multiple
? question.maxChoices
? `- You can choose up to ${question.maxChoices} answers `
: "- You can choose multiple answers "
: ""}
</span>
<span className="font-normal text-sm pl-2.5">
{question.required ? "" : "- Click skip button if not applicable"}
Expand Down
3 changes: 2 additions & 1 deletion src/components/survey/survey-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { createSurveyInspector } from "./survey-inspector";
import { surveyMachine } from "./survey-machine";

const STORAGE_KEY = "survey-state";
const STORAGE_VERSION = 1;
// Bump each edition: question ids are reused with new meanings, so stale progress must be dropped
const STORAGE_VERSION = 2026;

interface PersistedState {
version: number;
Expand Down
5 changes: 3 additions & 2 deletions src/components/survey/survey-machine.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { SurveyQuestionsYamlFile } from "@/lib/validators/survey-schema";
import { assign, fromPromise, setup } from "xstate";
import {
clearHiddenAnswers,
getFirstVisibleQuestionIndex,
getLastVisibleQuestionIndex,
getNextVisibleQuestionIndex,
Expand Down Expand Up @@ -154,10 +155,10 @@ export const surveyMachine = setup({
answers: ({ context, event }) => {
if (event.type !== "ANSWER_CHANGE")
return context.answers;
return {
return clearHiddenAnswers(context.sections, {
...context.answers,
[event.questionId]: event.value
};
});
}
}),
incrementQuestion: assign({
Expand Down
33 changes: 33 additions & 0 deletions src/lib/conditions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Answers, QuestionList, SectionList } from "./conditions";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {

clearHiddenAnswers,
evaluateCondition,
getFirstVisibleQuestionIndex,
getLastVisibleQuestionIndex,
Expand Down Expand Up @@ -443,3 +444,35 @@ describe("hasPrevVisibleQuestion", () => {
expect(hasPrevVisibleQuestion(questions, 1, answers)).toBe(false);
});
});

describe("clearHiddenAnswers", () => {
// setup -> contract (setup 0) -> salary (contract 0)
const sections = [{
label: "work",
questions: [
{},
{ showIf: { question: "work-q-0", equals: 0 } },
{ showIf: { question: "work-q-1", equals: 0 } }
]
}];

it("cascades: changing the routing answer nulls dependent answers and their others text", () => {
const answers: Answers = { "work-q-0": 1, "work-q-1": 0, "work-q-2": 3, "work-q-2-others": "x" };
expect(clearHiddenAnswers(sections, answers)).toEqual({
"work-q-0": 1,
"work-q-1": null,
"work-q-2": null,
"work-q-2-others": ""
});
});

it("keeps answers of visible questions", () => {
const answers: Answers = { "work-q-0": 0, "work-q-1": 0, "work-q-2": 3 };
expect(clearHiddenAnswers(sections, answers)).toEqual(answers);
});

it("nulls answers of a hidden section", () => {
const hidden = [{ label: "ai", showIf: { question: "work-q-0", equals: 0 }, questions: [{}] }];
expect(clearHiddenAnswers(hidden, { "work-q-0": 1, "ai-q-0": 2 })).toEqual({ "work-q-0": 1, "ai-q-0": null });
});
});
25 changes: 25 additions & 0 deletions src/lib/conditions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,28 @@ export function hasPrevVisibleQuestion(
): boolean {
return getPrevVisibleQuestionIndex(questions, fromIdx, answers) != null;
}

/**
* Nulls answers of questions that are no longer visible, so a changed routing answer
* doesn't keep dependent answers alive. Null (not delete) so the merge-save overwrites
* values already stored. Single pass works because showIf only points at earlier questions
* (enforced by survey-validator.ts "Check 7").
*/
export function clearHiddenAnswers(
sections: Array<{ label: string; showIf?: ShowIfCondition; questions: QuestionList }>,
answers: Answers
): Answers {
const result = { ...answers };
for (const section of sections) {
const sectionVisible = evaluateCondition(section.showIf, result);
section.questions.forEach((question, i) => {
const id = `${section.label}-q-${i}`;
if (result[id] == null || (sectionVisible && evaluateCondition(question.showIf, result)))
return;
result[id] = null;
if (`${id}-others` in result)
result[`${id}-others`] = "";
});
}
return result;
}
4 changes: 3 additions & 1 deletion src/lib/firebase/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { getActiveApp } from "./server";

const db = () => getFirestore(getActiveApp());

const getResults = () => db().collection("results");
// One collection per edition: anonymous uids persist across years, and question ids change meaning between editions
const SURVEY_YEAR = 2026;
const getResults = () => db().collection(`results-${SURVEY_YEAR}`);

interface Answers {
[key: string]: number | string | number[] | null;
Expand Down
43 changes: 43 additions & 0 deletions src/lib/validators/answers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { SurveyQuestion } from "./survey-schema";
import { validateSurveyFile } from "./survey-schema";

type AnswerValue = number | string | number[] | null;

const files = import.meta.glob<{ default: unknown }>("/survey/*.yml", { eager: true });

const QUESTIONS = new Map<string, SurveyQuestion>();
for (const [path, mod] of Object.entries(files)) {
const section = validateSurveyFile(mod.default, path);
section.questions.forEach((question, i) => QUESTIONS.set(`${section.label}-q-${i}`, question));
}

function isChoice(v: unknown, question: SurveyQuestion) {
return Number.isInteger(v) && (v as number) >= 0 && (v as number) < question.choices.length;
}

// Server-side mirror of what the survey UI can produce; the client is not trusted
export function findInvalidAnswer(answers: Record<string, AnswerValue>): string | null {
for (const [key, value] of Object.entries(answers)) {
if (key.endsWith("-others")) {
if (!QUESTIONS.has(key.slice(0, -"-others".length)) || typeof value !== "string")
return `Invalid answer: ${key}`;
continue;
}

const question = QUESTIONS.get(key);
if (!question)
return `Unknown question: ${key}`;
if (value === null || (Array.isArray(value) && value.length === 0))
continue; // skipped

const valid = question.multiple
? Array.isArray(value)
&& value.every(v => isChoice(v, question))
&& new Set(value).size === value.length
&& value.length <= (question.maxChoices ?? question.choices.length)
: isChoice(value, question);
if (!valid)
return `Invalid answer: ${key}`;
}
return null;
}
2 changes: 2 additions & 0 deletions src/lib/validators/survey-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export const SurveyQuestionSchema = z.object({

multiple: z.boolean().optional().default(false),

maxChoices: z.number().int().positive().optional(),

choices: z
.array(
z
Expand Down
7 changes: 4 additions & 3 deletions survey/1-profile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ questions:
- Europe
- "US & Canada"
- Middle East
- Others
- Other (Africa, Asia, Oceania...)

- label: What is your occupation?
required: true
Expand Down Expand Up @@ -71,7 +71,8 @@ questions:
- Blockchain developer
- AI engineer
- Cloud architect
- Student (coding professionally)
- Student
- Other

- label: What is/was your coding education background?
required: true
Expand All @@ -95,7 +96,7 @@ questions:
- 3-4 years
- 5-6 years
- 7-10 years
- 11-16 years
- 11-15 years
- 16+ years

- label: Do you code outside of work or studies?
Expand Down
4 changes: 4 additions & 0 deletions survey/2-learning-and-education.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ position: 2
questions:
- label: Which areas did your formal education fail to adequately prepare you for?
required: true
showIf:
question: profile-q-4
notEquals: 0
multiple: true
choices:
- Modern tech stack (frameworks, DevOps, cloud platforms)
Expand Down Expand Up @@ -57,6 +60,7 @@ questions:
- Other platforms

- label: What are the biggest challenges you find in learning new technologies (pick 3)?
maxChoices: 3
required: true
multiple: true
choices:
Expand Down
Loading
Loading