brain-lab / brain_lab /static /attention.js
Chungulus's picture
Deploy Brain Lab CPU classroom app with verified saved research playback
4155f6b verified
Raw History Blame Contribute Delete
9.61 kB
import {card,escape} from './common.js';
export async function attention(root){
root.innerHTML=card('Put your attention and memory to the test.',`<div class="segmented" role="tablist" aria-label="Attention lab activity"><button role="tab" aria-selected="true" id="attention-stroop-tab">Color clash</button><button role="tab" aria-selected="false" id="attention-memory-tab">Memory sequence</button></div>
<div id="attention-stroop"><p>Name the <b>ink color</b>, even when the word says something different. A round has 16 shuffled trials: eight matching and eight clashing words.</p><div class="attention-stage"><div id="stroop-word" aria-live="off">READY?</div><p id="stroop-prompt">Read the instructions, then start.</p></div><div id="stroop-choices" class="world-controls">${['Red','Blue','Green','Gold'].map((n,i)=>`<button class="secondary" data-stroop="${i}" disabled>${n} <small>${i+1}</small></button>`).join('')}</div><div class="world-controls"><button class="primary" id="stroop-start">Start 16 trials</button><button class="secondary" id="stroop-clear">Clear results</button></div><p id="stroop-feedback" class="message" role="status">Use the buttons or keys 1–4. The color names on the buttons stay neutral so the task remains about the word above.</p><div id="stroop-results" class="attention-results"></div><p class="note">Responses are timed locally after the browser paints the stimulus. Correct-response medians are shown separately for matching and clashing words. A short round is an illustration, not a clinical attention test.</p><div class="source-links"><a href="https://psychclassics.yorku.ca/Stroop/" target="_blank" rel="noreferrer">Stroop’s original study ↗</a><a href="https://openstax.org/books/psychology-2e/pages/8-1-how-memory-functions" target="_blank" rel="noreferrer">How memory functions · OpenStax ↗</a></div></div>
<div id="attention-memory" hidden><p>Watch the squares light up, then repeat the order. Each correct sequence adds one square. You control the flash speed and can replay a sequence.</p><div class="memory-grid" aria-label="Four memory squares">${Array.from({length:4},(_,i)=>`<button class="memory-pad" data-memory="${i}" aria-label="Memory square ${i+1}" disabled>${i+1}</button>`).join('')}</div><label class="range">Flash duration<input id="memory-speed" type="range" min="200" max="1200" step="100" value="600"><output id="memory-speed-value">600 ms</output></label><div class="world-controls"><button class="primary" id="memory-start">Start a new sequence</button><button class="secondary" id="memory-replay" disabled>Replay sequence</button></div><p id="memory-feedback" class="message" role="status">A short delay separates each flash. Keep your eyes on the four squares.</p><div class="attention-results" id="memory-results">Longest sequence: 0 · Sequences completed: 0</div><p class="note">Replaying provides extra practice. We mark that help in the result. This task illustrates working memory and rehearsal; it does not estimate IQ or diagnose a memory condition.</p></div>`,'TWO LIVE HUMAN EXPERIMENTS');
const $=s=>root.querySelector(s),colors=['#bb4d4d','#4a72b5','#398367','#ae7f21'],names=['RED','BLUE','GREEN','GOLD'];let alive=true,mode='stroop',deck=[],trial=0,results=[],current=null,start=0,timer,raf,accept=false,sequence=[],entered=0,longest=0,completed=0,playing=false,replayed=false,seqToken=0;
const random=n=>Math.floor(crypto.getRandomValues(new Uint32Array(1))[0]/4294967296*n);
function shuffle(a){for(let i=a.length-1;i>0;i--){const j=random(i+1);[a[i],a[j]]=[a[j],a[i]]}return a}
function stroopControls(v){root.querySelectorAll('[data-stroop]').forEach(b=>b.disabled=!v)}
function median(a){if(!a.length)return null;const s=[...a].sort((x,y)=>x-y),i=Math.floor(s.length/2);return s.length%2?s[i]:(s[i-1]+s[i])/2}
function renderResults(){const group=match=>results.filter(x=>x.match===match),a=group(true),b=group(false),ma=median(a.filter(x=>x.correct).map(x=>x.ms)),mb=median(b.filter(x=>x.correct).map(x=>x.ms));$('#stroop-results').innerHTML=`<div><b>${results.length}/16</b><span>trials answered</span></div><div><b>${results.filter(x=>x.correct).length}/${results.length}</b><span>correct</span></div><div><b>${ma===null?'—':Math.round(ma)+' ms'}</b><span>matching · ${a.filter(x=>x.correct).length} correct</span></div><div><b>${mb===null?'—':Math.round(mb)+' ms'}</b><span>clashing · ${b.filter(x=>x.correct).length} correct</span></div>${ma!==null&&mb!==null?`<p>Clashing minus matching: <b>${Math.round(mb-ma)} ms</b>. Your result may vary with practice, sample size, errors, and device timing.</p>`:''}`}
function nextTrial(){if(!alive||mode!=='stroop')return;if(trial>=deck.length){current=null;$('#stroop-word').textContent='ROUND COMPLETE';$('#stroop-prompt').textContent='Compare your matching and clashing trials below.';$('#stroop-start').disabled=false;renderResults();return}current=deck[trial];$('#stroop-word').textContent=names[current.word];$('#stroop-word').style.color=colors[current.ink];$('#stroop-prompt').textContent=`Trial ${trial+1} of 16 · choose the INK color`;raf=requestAnimationFrame(()=>{raf=requestAnimationFrame(()=>{start=performance.now();accept=true;stroopControls(true)})})}
function answer(color){if(!alive||!accept||mode!=='stroop')return;const ms=performance.now()-start;accept=false;stroopControls(false);const correct=color===current.ink;results.push({...current,correct,ms});trial++;$('#stroop-feedback').textContent=correct?'Correct. Get ready for the next word.':`The ink was ${names[current.ink].toLowerCase()}. Get ready for the next word.`;renderResults();$('#stroop-word').textContent='+';$('#stroop-word').style.color='#536f5d';timer=setTimeout(nextTrial,550)}
$('#stroop-start').onclick=()=>{clearTimeout(timer);cancelAnimationFrame(raf);results=[];trial=0;deck=shuffle(Array.from({length:16},(_,i)=>{const ink=i%4,match=i<8;return {ink,word:match?ink:(ink+1+random(3))%4,match}}));$('#stroop-start').disabled=true;$('#stroop-feedback').textContent='Name the ink color. Use keys 1–4 or the buttons.';renderResults();nextTrial()};
$('#stroop-clear').onclick=()=>{clearTimeout(timer);cancelAnimationFrame(raf);accept=false;current=null;results=[];stroopControls(false);$('#stroop-start').disabled=false;$('#stroop-word').textContent='READY?';$('#stroop-word').style.color='#536f5d';renderResults();$('#stroop-feedback').textContent='Results cleared. Start when ready.'};root.querySelectorAll('[data-stroop]').forEach(b=>b.onclick=()=>answer(Number(b.dataset.stroop)));
const keyboard=e=>{if(mode==='stroop'&&accept&&['1','2','3','4'].includes(e.key)){e.preventDefault();answer(Number(e.key)-1)}};document.addEventListener('keydown',keyboard);
function pads(v){root.querySelectorAll('[data-memory]').forEach(b=>b.disabled=!v)}
function clearPads(){root.querySelectorAll('[data-memory]').forEach(b=>b.classList.remove('lit'))}
function showSequence(){const token=++seqToken;playing=true;entered=0;pads(false);clearPads();$('#memory-replay').disabled=true;$('#memory-feedback').textContent=`Watch ${sequence.length} flash${sequence.length===1?'':'es'}…`;const speed=Number($('#memory-speed').value);let i=0;function flash(){if(!alive||token!==seqToken||mode!=='memory')return;if(i>=sequence.length){playing=false;pads(true);$('#memory-replay').disabled=false;$('#memory-feedback').textContent=`Your turn: repeat ${sequence.length} square${sequence.length===1?'':'s'} in order.`;return}const b=root.querySelector(`[data-memory="${sequence[i]}"]`);b.classList.add('lit');timer=setTimeout(()=>{b.classList.remove('lit');i++;timer=setTimeout(flash,220)},speed)}timer=setTimeout(flash,450)}
$('#memory-start').onclick=()=>{clearTimeout(timer);replayed=false;sequence=[random(4)];showSequence()};$('#memory-replay').onclick=()=>{clearTimeout(timer);replayed=true;showSequence()};$('#memory-speed').oninput=e=>$('#memory-speed-value').textContent=e.target.value+' ms';
root.querySelectorAll('[data-memory]').forEach(b=>b.onclick=()=>{if(playing||mode!=='memory')return;const value=Number(b.dataset.memory);if(value!==sequence[entered]){pads(false);$('#memory-feedback').textContent=`Sequence ended at length ${sequence.length}. Square ${sequence[entered]+1} was next. Replay it to practice or start again.`;$('#memory-replay').disabled=false;return}entered++;if(entered===sequence.length){completed++;longest=Math.max(longest,sequence.length);pads(false);$('#memory-results').textContent=`Longest sequence: ${longest} · Sequences completed: ${completed}${replayed?' · This sequence was replayed':''}`;$('#memory-feedback').textContent=`Correct! You repeated ${sequence.length}. One more square is coming.`;sequence.push(random(4));replayed=false;timer=setTimeout(showSequence,900)}else $('#memory-feedback').textContent=`${entered} of ${sequence.length} entered. Keep going.`});
function tab(value){clearTimeout(timer);cancelAnimationFrame(raf);accept=false;seqToken++;clearPads();pads(false);mode=value;$('#attention-stroop').hidden=value!=='stroop';$('#attention-memory').hidden=value!=='memory';$('#attention-stroop-tab').setAttribute('aria-selected',String(value==='stroop'));$('#attention-memory-tab').setAttribute('aria-selected',String(value==='memory'));stroopControls(false);$('#stroop-start').disabled=false;$('#memory-replay').disabled=!sequence.length}
$('#attention-stroop-tab').onclick=()=>tab('stroop');$('#attention-memory-tab').onclick=()=>tab('memory');renderResults();
return()=>{alive=false;accept=false;seqToken++;clearTimeout(timer);cancelAnimationFrame(raf);document.removeEventListener('keydown',keyboard)};
}