aabroukh's picture
Add files using upload-large-folder tool
b136cbe verified
Raw History Blame Contribute Delete
4.12 kB
import { useEffect, useState } from "react";
import { db, auth } from "../firebase";
import {
doc,
getDoc,
setDoc,
runTransaction
} from "firebase/firestore";
function AssignModalityAndTrials({ onComplete }) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const assign = async () => {
const uid = auth.currentUser?.uid;
if (!uid) return setError("No authenticated user.");
const participantRef = doc(db, "participants", uid);
const participantSnap = await getDoc(participantRef);
// If already assigned, skip
if (participantSnap.exists() && participantSnap.data().assignedTrialIds) {
onComplete(participantSnap.data());
return;
}
try {
// 1. Load survey data from JSON
const response = await fetch('/survey_data.json');
const allSamples = await response.json();
if (!allSamples || allSamples.length === 0) {
return setError("No survey data available.");
}
// 2. BALANCED SAMPLING: Use global counter to ensure equal distribution
const TRIALS_PER_PARTICIPANT = 20;
const totalTrials = allSamples.length;
const numBlocks = Math.ceil(totalTrials / TRIALS_PER_PARTICIPANT);
// Get next participant number using transaction to avoid race conditions
const counterRef = doc(db, "system", "participantCounter");
const participantNumber = await runTransaction(db, async (transaction) => {
const counterDoc = await transaction.get(counterRef);
const currentCount = counterDoc.exists() ? (counterDoc.data().count || 0) : 0;
const nextCount = currentCount + 1;
transaction.set(counterRef, { count: nextCount, lastUpdated: new Date().toISOString() }, { merge: true });
return currentCount;
});
// 3. Deterministically assign modality (ensures 50/50 split)
// Even participant numbers get text, odd get audio
const modality = participantNumber % 2 === 0 ? "text" : "audio";
// Determine which block this participant gets (round-robin)
const blockIndex = participantNumber % numBlocks;
// Get the trials for this block
const startIdx = blockIndex * TRIALS_PER_PARTICIPANT;
const endIdx = Math.min(startIdx + TRIALS_PER_PARTICIPANT, totalTrials);
let blockTrials = allSamples.slice(startIdx, endIdx);
// If the last block has fewer than 20 trials, wrap around to fill it
if (blockTrials.length < TRIALS_PER_PARTICIPANT) {
const needed = TRIALS_PER_PARTICIPANT - blockTrials.length;
blockTrials = [...blockTrials, ...allSamples.slice(0, needed)];
}
// Shuffle within the block to randomize order
const shuffled = [...blockTrials];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
const trialIds = shuffled.map((sample) => sample.id.toString());
// 4. Update participant document
await setDoc(
participantRef,
{
modality,
assignedTrialIds: trialIds,
participantNumber,
blockIndex,
assignedAt: new Date().toISOString()
},
{ merge: true }
);
onComplete({ modality, assignedTrialIds: trialIds, participantNumber });
} catch (err) {
console.error("Failed to load survey data:", err);
setError("Failed to load survey data. Please try again later.");
}
};
assign().catch((err) => {
console.error("Assignment failed:", err);
setError("Something went wrong. Please try again later.");
}).finally(() => setLoading(false));
}, [onComplete]);
if (loading) return <p>Assigning you to a group...</p>;
if (error) return <p style={{ color: "red" }}>{error}</p>;
return null; // Done → parent will move forward
}
export default AssignModalityAndTrials;