import { useState, useEffect } from "react"; import { db, auth } from "../firebase"; import { TEXT_COMPLETION_URL } from "../config"; import { doc, setDoc } from "firebase/firestore"; function TrialTaskText({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) { const [trialData, setTrialData] = useState(null); const [order, setOrder] = useState([1, 2]); const [ratings, setRatings] = useState({ r1: null, r2: null }); const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B' const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]); const [startTime, setStartTime] = useState(null); const [timestamps, setTimestamps] = useState({ r1: null, r2: null }); const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] }); const [justification, setJustification] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const isAttentionCheck = trialIndex === 0; useEffect(() => { // Scroll to top when new trial loads window.scrollTo(0, 0); const loadTrial = async () => { try { // If this is the first trial, use it as an attention check if (isAttentionCheck) { const attentionCheckData = { id: "attention_check", query: "Hello AI! I need some help writing a text message", text_resp_1: "Of course! Who is the recipient and what would you like to convey in the message?", text_resp_2: "that doesn't sound like a bot. Here's a sample I tried:\n\nSup, it's [Name]. How are you? This is [name] speaking. I am calling to inquire about [insert product or service here]\n\nWhere am I going wrong?", prev_hist: "", conv_id: "attention", turn_no: "0", synth_text_1_rating: 85, synth_text_2_rating: 15, text_1_score: null, text_2_score: null }; setTrialData(attentionCheckData); } else { // Load survey data from JSON const response = await fetch('/survey_data.json'); const allSamples = await response.json(); // Find the trial by ID const trial = allSamples.find(sample => sample.id.toString() === trialId.toString()); if (trial) { setTrialData(trial); } } // Deterministic order assignment (ensures 5x5 split per modality) // Every 2 participants get the same order, alternating between [1,2] and [2,1] const orderFlip = Math.floor(participantNumber / 2) % 2; setOrder(orderFlip === 0 ? [1, 2] : [2, 1]); // Reset ratings and timestamps for new trial setRatings({ r1: null, r2: null }); setTimestamps({ r1: null, r2: null }); setRatingChanges({ r1: [], r2: [] }); setOverallPreference(null); setOverallPreferenceChanges([]); setJustification(""); setIsSubmitting(false); // Set start time setStartTime(Date.now()); } catch (error) { console.error("Failed to load trial data:", error); } }; loadTrial(); }, [trialId, isAttentionCheck, participantNumber]); const handleSliderChange = (responseNum, value) => { setRatings((prev) => ({ ...prev, [`r${responseNum}`]: value })); }; const handleSliderRelease = (responseNum, value) => { setTimestamps((prev) => ({ ...prev, [`r${responseNum}`]: Date.now() })); // Determine the other rating's value const otherResponseNum = responseNum === 1 ? 2 : 1; const otherRatingValue = ratings[`r${otherResponseNum}`]; setRatingChanges((prev) => ({ ...prev, [`r${responseNum}`]: [ ...prev[`r${responseNum}`], { value, timestamp: new Date().toISOString(), otherRatingValue } ] })); }; const calculatePreferenceChanges = () => { // Build a timeline of all rating changes const timeline = []; ratingChanges.r1.forEach(change => { timeline.push({ timestamp: change.timestamp, r1: change.value, r2: change.otherRatingValue }); }); ratingChanges.r2.forEach(change => { timeline.push({ timestamp: change.timestamp, r1: change.otherRatingValue, r2: change.value }); }); // Sort by timestamp timeline.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp)); // Count preference changes let preferenceChanges = 0; let lastPreference = null; // 'r1', 'r2', or 'tie' timeline.forEach(entry => { if (entry.r1 !== null && entry.r2 !== null) { let currentPreference; if (entry.r1 > entry.r2) { currentPreference = 'r1'; } else if (entry.r2 > entry.r1) { currentPreference = 'r2'; } else { currentPreference = 'tie'; } if (lastPreference !== null && lastPreference !== currentPreference) { preferenceChanges++; } lastPreference = currentPreference; } }); return preferenceChanges; }; const handleOverallPreferenceChange = (newPreference) => { setOverallPreference(newPreference); setOverallPreferenceChanges((prev) => [ ...prev, { value: newPreference, timestamp: new Date().toISOString(), previousValue: overallPreference } ]); }; const handleSubmit = async (e) => { e.preventDefault(); // Prevent double submission if (isSubmitting) return; if (ratings.r1 === null || ratings.r2 === null || overallPreference === null) return; setIsSubmitting(true); const endTime = Date.now(); const totalPreferenceChanges = calculatePreferenceChanges(); // Determine which response was shown first based on order const response1InOrder = order[0] === 1 ? trialData.text_resp_1 : trialData.text_resp_2; const response2InOrder = order[1] === 1 ? trialData.text_resp_1 : trialData.text_resp_2; const responseData = { // Participant and Trial Info participantId: auth.currentUser.uid, promptId: `${trialData.conv_id}_${trialData.turn_no}`, trialNumber: trialIndex, // Now 0 for attention check, 1-20 for real trials trialId: isAttentionCheck ? "attention_check" : trialId, // Content conversationHistory: trialData.prev_hist || "", query: trialData.query, responseText1: response1InOrder, responseText2: response2InOrder, numCharacters1: response1InOrder.length, numCharacters2: response2InOrder.length, // AI Ratings (original order) aiRatingResponse1: trialData.synth_text_1_rating, aiRatingResponse2: trialData.synth_text_2_rating, prismRating1: trialData.text_1_score || null, prismRating2: trialData.text_2_score || null, // Participant Ratings participantRatingNum: trialIndex + 1, ratingResponse1: ratings.r1, ratingResponse2: ratings.r2, // Timing taskStartTime: new Date(startTime).toISOString(), taskEndTime: new Date(endTime).toISOString(), timestampRating1: timestamps.r1 ? new Date(timestamps.r1).toISOString() : null, timestampRating2: timestamps.r2 ? new Date(timestamps.r2).toISOString() : null, totalTaskDurationMs: endTime - startTime, // Order Info orderPresented: order, responseShownFirst: order[0], originalResponse1ShownAs: order[0] === 1 ? "A" : "B", originalResponse2ShownAs: order[0] === 2 ? "A" : "B", // Metadata modality: "text", submittedAt: new Date().toISOString(), isAttentionCheck: isAttentionCheck, ratingChangeHistory1: ratingChanges.r1, ratingChangeHistory2: ratingChanges.r2, // Preference Changes totalPreferenceChanges: totalPreferenceChanges, // Overall Preference overallPreference: overallPreference, overallPreferenceChangeHistory: overallPreferenceChanges, // Justification preferenceJustification: justification.trim() || null, }; const responseDocId = isAttentionCheck ? `${auth.currentUser.uid}_${sessionId}_text_attention_check` : `${auth.currentUser.uid}_${sessionId}_text_${trialId}`; console.log(auth.currentUser?.uid, responseDocId); await setDoc(doc(db, "responses", responseDocId), responseData); onNext(); // move to next trial }; if (!trialData) return
Loading trial...
; const [first, second] = order; return ( ); } export default TrialTaskText;