The Missing Golden Key is a free interactive reading comprehension activity for children in approximately Grades 4–5. A golden key has disappeared from an old town library, and young detective Emma must examine clues, question suspects, and decide what really happened.
Instead of reading one long passage and answering a worksheet afterward, children move through the mystery one scene at a time. Each chapter includes short reading and language activities while the details are still fresh.
The mystery asks readers to use evidence before making a conclusion. Some clues make a suspect look guilty at first, while later details may change what the reader thinks.
Emma arrives at the old town library and discovers that the Golden Library Key is missing from its brass hook. The key opens a Secret Reading Room filled with rare books, journals, and stories from the town's founders.
Several possible suspects were inside the library: Leo the janitor, Mia the student helper, Mr. Cruz the history teacher, and Pip the library cat. A wet blue paint trail, a broken paintbrush, suspicious fingerprints, a blueprint, and a set of muddy or clean shoes gradually change what Emma knows.
Readers must follow the evidence carefully. Finding the key does not immediately solve the mystery, because one question still remains: who first moved it from the front desk, and why?
What reading and language skills does it practise?
Inference from evidenceReaders decide which clues make a suspect more or less suspicious and revise conclusions as new information appears.
Supporting detailsChildren identify which facts from the story support a claim or prove that an event happened.
SequencingReaders track the order of clues, interviews, and discoveries throughout the investigation.
Cause and effectChildren connect events such as the crash, the paint trail, and Pip's movement to later discoveries.
Context cluesVocabulary such as examined, hesitated, and suspicious is understood through the surrounding story.
Vocabulary relationshipsActivities include synonyms, antonyms, multiple-meaning words, and story-specific vocabulary.
Grammar in contextChildren work with pronouns, adjectives, verb tense, and correct sentence forms inside the story.
Fact and opinionReaders distinguish details directly stated in the text from judgments or assumptions.
PredictionChildren decide what Emma should do next based on what a careful investigator would reasonably do.
Main ideaReaders identify the important meaning of clues such as the library blueprint rather than focusing on minor details.
ThemeThe final deduction reinforces the idea that good readers use evidence before deciding what happened.
Written responseThe Detective Report asks children to explain the mystery in their own words and recall the strongest evidence.
How the interactive mystery works
The child enters a detective name and begins the case.
Each scene appears on its own screen so the reader can focus on one part of the mystery at a time.
Every scene contains short Word Lab and Case Lab questions.
Questions must be completed before the reader can file the scene's evidence and continue.
The Case File keeps track of clues and changes each suspect's status as new evidence appears.
Answers receive immediate feedback with a short explanation.
The final Detective Report asks the child to explain what happened and identify the most important clues.
Progress is saved in the browser on the same device, and the case can be replayed after completion.
Parent and teacher guide
Recommended level
The activity is designed primarily for Grades 4–5. A confident Grade 3 reader may enjoy it with some adult support, while an older learner who needs approachable comprehension practice may also benefit from the short scenes and immediate feedback.
Estimated time
Independent work: approximately 30–45 minutes
Guided lesson: approximately 45–60 minutes with discussion
Shorter sessions: complete several scenes at a time and return using the same browser and device
Before reading
Ask: What makes someone a good detective? Encourage the child to think beyond "finding clues." A good answer may include noticing details, checking whether clues match, listening carefully, and avoiding conclusions before enough evidence is available.
While the child reads
Let the child answer before giving help. If an answer is incorrect, ask the child to return to the exact sentence, picture, or clue that could help. When a suspect seems guilty, ask: What evidence do we have? What evidence do we still need?
After the activity
Discussion questions
Why did Leo become less suspicious after Emma looked at his boots?
Why did Mia seem suspicious before the whole story was known?
Which clue was most important in showing that the mystery began downstairs?
What did Pip explain, and what did Pip fail to explain?
Did Mia make a good decision when she hid the key? Why or why not?
What would have happened if Emma had accused the first suspicious person immediately?
Which clue changed your mind the most during the investigation?
What does the story suggest about using evidence before making a judgment?
Extend the lesson
Evidence chart: Make three columns labeled Suspect, Evidence For, and Evidence Against. Add Leo, Mia, Mr. Cruz, and Pip.
Writing connection: Write a short new library mystery with three suspects and at least four clues.
Vocabulary connection: Choose five new words from the case and write a new sentence for each one.
Speaking connection: Let the child present the case as if reporting the solution to Mrs. Alvarez.
Critical-thinking connection: Invent one misleading clue that would make an innocent suspect seem guilty at first.
Progress note: The activity saves progress in the browser on the device being used. It does not require an account. Clearing browser data, using private browsing, or moving to another device may reset saved progress.
Frequently asked questions
Is The Missing Golden Key free?
Yes. Children can read the complete mystery and finish all interactive reading, language, evidence, and writing activities for free.
Does the child need an account?
No. The activity works without a sign-in or student account.
What grade level is this activity for?
It is designed mainly for Grades 4–5, although younger strong readers and older learners who need accessible comprehension practice may also enjoy it.
Is this only a multiple-choice quiz?
No. The mystery combines story reading with vocabulary, grammar, sequencing, inference, evidence analysis, prediction, fact and opinion, theme, and a final written Detective Report.
Can it be used for homeschooling or tutoring?
Yes. It can be completed independently, assigned as an online reading activity, or used as a guided comprehension lesson with the discussion and extension activities above.
Does the activity save progress?
Yes. Progress is stored locally in the same browser and device. Clearing browser data or switching devices may reset it.
Can the child play the mystery again?
Yes. After completing the case, the child can reset the activity and investigate again.
Written and checked by Teacher Abi
Abigail is a licensed teacher who has tutored since 2006. She writes every item, solves it again before posting, and fixes errors readers report.
Read the questions in the test booklet. Shade your answers on the separate answer sheet, the way you will on exam day. Click a shaded circle again to erase it.
' +
'
' + (D.rules || []).map(function (r) { return '
' + r + '
'; }).join('') + '
' +
'' +
'
' +
'
' +
'
Prefer paper? Print the booklet and answer sheet, take it with a timer, then to see your results.
' +
'
Your answers are saved on this device only.
' +
'' +
// exam
'' +
'
' + esc(D.short || D.title) + '
' +
'
' +
'
' +
'
Test booklet
' + bookletHTML() + '
End of test. Check your answer sheet, then submit.
' +
'' +
'
' +
// phone strip
'
' +
'' +
// result
'' +
// dialog
'
Submit your answer sheet?
' +
'
');
var X = root.querySelector('.abi-x');
function q(s) { return X.querySelector(s); }
function qa(s) { return X.querySelectorAll(s); }
function setPhase(p) { S.phase = p; X.setAttribute('data-phase', p); save(); }
/* shading */
function paint() {
Array.prototype.forEach.call(qa('.abi-x-rows .abi-x-bub, .abi-x-striprow .abi-x-bub'), function (b) {
var on = S.answers[+b.dataset.i] === +b.dataset.j;
b.classList.toggle('on', on); b.setAttribute('aria-pressed', on ? 'true' : 'false');
});
var a = S.answers.filter(function (x) { return x != null; }).length;
var txt = a + ' answered · ' + (N - a) + ' blank';
q('.abi-x-count').textContent = txt; q('.abi-x-count2').textContent = txt;
}
X.addEventListener('click', function (e) {
var b = e.target.closest('.abi-x-bub[data-j]');
if (b && S.phase !== 'done') {
var i = +b.dataset.i, j = +b.dataset.j;
S.answers[i] = S.answers[i] === j ? null : j; save(); paint();
return;
}
var jmp = e.target.closest('[data-jump]');
if (jmp) {
var el = document.getElementById('abi-x-' + n + '-q' + (+jmp.dataset.jump + 1));
if (el) { X.classList.remove('abi-x-sheetopen'); el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
}
});
/* phone strip: shows the row for the question at the top of the screen */
var cur = 0;
function strip(i) {
cur = i;
var row = sheetHTML(false).split('
Name ____________________________ Date ____________ Time started ________ Time ended ________
' +
'
Instructions
Set a timer for ' + (D.minutes || 60) + ' minutes.
Shade your answers on the separate answer sheet (last page) with a pencil. Shade one circle per item completely.
' + (D.rules || []).map(function (r) { return '
' + r + '
'; }).join('') + '
When you finish, open the test online and choose “enter your paper answers” to see your results.
' +
'
teacherabiworksheets.blogspot.com · Independent practice, not affiliated with the exam’s official administrator.
' +
'
' + bookletHTML(true) + '
' +
'
Answer sheet
Name ____________________________ Score ______ / ' + N + '
' + colHTML + '
';
document.body.appendChild(div);
document.body.classList.add('abi-printing');
var done = function () { document.body.classList.remove('abi-printing'); window.removeEventListener('afterprint', done); };
window.addEventListener('afterprint', done);
setTimeout(function () { window.print(); }, 60);
};
/* restore */
if (S.phase === 'exam' && S.mode === 'timed' && left() <= 0) { S.phase = 'exam'; finish(true); }
else if (S.phase === 'exam') { if (S.mode === 'paper') X.classList.add('abi-x-papermode'); startExam(S.mode || 'timed'); }
else if (S.phase === 'done') { X.setAttribute('data-phase', 'done'); render(); }
paint();
}
})();
/* ============================================================
TEACHER ABI LEVELED LESSON ENGINE
A post holds the lesson as readable HTML; this turns it into the
step-by-step session: Quick check → Level 1/2/3 → Mastery.
questions
Why this level
Heading
body
Problem
Hint
Answer
5 questions
5 more
...levels 2 and 3...
..
..
A question:
..
Said simply
choice
...
worked answer
{3/4} and {1 7/8} are written as stacked fractions.
Progress is saved on this device: abiLesson:, plus a summary in abiLessons.
============================================================ */
(function () {
'use strict';
var roots = document.querySelectorAll('.abi-lesson');
if (!roots.length) return;
var MSG = (window.TA_CONFIG && window.TA_CONFIG.messenger) || 'https://m.me/araltayo.ph';
var NAVY = '#18344d', PEN = '#b04a31', RUST = '#c95f45', PAPER = '#fffaf4', LINE = '#b9ab9c', MINT = '#cfe0d8', GREEN = '#315d52';
Array.prototype.forEach.call(roots, function (root) { try { init(root); } catch (e) { root.classList.remove('abi-l-on'); if (window.console) console.error(e); } });
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
function frac(s) {
return String(s).replace(/\{(\d+) (\d+)\/(\d+)\}/g, '$1$2$3')
.replace(/\{(\d+)\/(\d+)\}/g, '$1$2');
}
function store(k, v) { try { if (v === undefined) return JSON.parse(localStorage.getItem(k) || 'null'); localStorage.setItem(k, JSON.stringify(v)); } catch (e) { return null; } }
/* ---------- figures ---------- */
function bar(n, k, w, h, color) {
w = w || 300; h = h || 54;
var s = '';
}
function stack(list) {
var rowH = 46, w = 300, s = '';
}
function dots(total, groups, take) {
var per = total / groups, s = '';
}
function boxes(n, k, label, total) {
var w = 380, bw = w / n, s = '';
}
function fig(code) {
if (!code) return '';
var p = code.split(':');
if (p[0] === 'bar') return bar(+p[1], +p[2], +p[3] || undefined, +p[4] || undefined, p[5] === 'red' ? RUST : undefined);
if (p[0] === 'stack') return stack(p[1].split(','));
if (p[0] === 'dots') return dots(+p[1], +p[2], +p[3]);
if (p[0] === 'boxes') return boxes(+p[1], +p[2], p[3], p[4]);
return '';
}
function figHTML(el) {
if (!el) return '';
var code = el.getAttribute('data-fig');
return '
' + (code ? fig(code) : el.innerHTML) + '
';
}
/* ---------- read the lesson from the page ---------- */
function readQ(el) {
var a = (el.getAttribute('data-a') || 'A').trim().toUpperCase();
var say = el.querySelector('.say'), why = el.querySelector('.why'), stem = el.querySelector('.stem');
return {
lv: +el.getAttribute('data-lv') || 0,
q: stem ? stem.innerHTML : '',
p: say ? say.innerHTML : '',
f: figHTML(el.querySelector('.fig')),
o: Array.prototype.map.call(el.querySelectorAll('ol > li'), function (li) { return li.innerHTML; }),
a: 'ABCDE'.indexOf(a),
w: why ? why.innerHTML : '',
keep: el.hasAttribute('data-keep-order')
};
}
function readSets(sec) {
return Array.prototype.map.call(sec.querySelectorAll('.set'), function (s) {
return Array.prototype.map.call(s.querySelectorAll('.q'), readQ);
});
}
function read(root) {
var L = { check: [], levels: {}, mastery: [] };
var c = root.querySelector('[data-part="check"]');
if (c) L.check = Array.prototype.map.call(c.querySelectorAll('.q'), readQ);
Array.prototype.forEach.call(root.querySelectorAll('[data-part="level"]'), function (sec) {
var n = +sec.getAttribute('data-level');
var why = sec.querySelector(':scope > .why');
var rt = sec.querySelector('.reteach');
L.levels[n] = {
n: n, name: sec.getAttribute('data-name') || ('Level ' + n),
why: why ? why.innerHTML : '',
cards: Array.prototype.map.call(sec.querySelectorAll('.card'), function (c) {
var h = c.querySelector('h3'), ans = c.querySelector('.ans'), f = c.querySelector('.fig');
var body = c.cloneNode(true);
Array.prototype.forEach.call(body.querySelectorAll('h3, .ans, .fig'), function (x) { x.parentNode.removeChild(x); });
return { k: c.getAttribute('data-k') || '', h: h ? h.innerHTML : '', b: body.innerHTML, f: figHTML(f), tr: c.classList.contains('try'), ans: ans ? ans.innerHTML : '' };
}),
reteach: rt ? (function () {
var h = rt.querySelector('h3'), f = rt.querySelector('.fig'), body = rt.cloneNode(true);
Array.prototype.forEach.call(body.querySelectorAll('h3, .fig'), function (x) { x.parentNode.removeChild(x); });
return { h: h ? h.innerHTML : '', f: figHTML(f), b: body.innerHTML };
})() : null,
sets: readSets(sec)
};
});
var m = root.querySelector('[data-part="mastery"]');
if (m) L.mastery = readSets(m);
return L;
}
/* shuffle choices so the answer isn't always in the same place */
function prep(list) {
return list.map(function (q) {
var idx = q.o.map(function (_, i) { return i; });
if (!q.keep) for (var i = idx.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var t = idx[i]; idx[i] = idx[j]; idx[j] = t; }
var c = {}; for (var k in q) c[k] = q[k];
c.o = idx.map(function (i) { return q.o[i]; }); c.a = idx.indexOf(q.a);
return c;
});
}
function init(root) {
var L = read(root);
var ID = root.getAttribute('data-id') || 'lesson';
var TITLE = root.getAttribute('data-title') || 'This topic';
var KEY = 'abiLesson:' + ID;
var NEXT = root.getAttribute('data-next-url'), NEXT_T = root.getAttribute('data-next-title');
var HUB = root.getAttribute('data-hub-url');
var IMG_THINK = root.getAttribute('data-img-think') || '';
var IMG_TALK = root.getAttribute('data-img-talk') || '';
var ART = (window.TA_CONFIG && window.TA_CONFIG.art) || {};
function pic(src, cls) { return src ? '' : ''; }
var LV = Object.keys(L.levels).map(Number).sort();
var TOP = LV[LV.length - 1] || 3;
function fresh() { var s = { step: 'start', check: [], level: 0, stars: {}, done: { check: false, m: false }, tries: { m: 0 }, card: 0, i: 0, ans: [], set: 0, simple: false, reveal: false }; LV.forEach(function (n) { s.stars[n] = 0; s.done[n] = false; s.tries[n] = 0; }); return s; }
var S = fresh();
var sv = store(KEY);
if (sv && sv.stars) { S.check = sv.check || []; S.level = sv.level || 0; S.stars = sv.stars; S.done = sv.done; S.tries = sv.tries || S.tries; }
function save() {
store(KEY, { check: S.check, level: S.level, stars: S.stars, done: S.done, tries: S.tries });
var all = store('abiLessons') || {};
all[ID] = { title: TITLE, level: S.level, stars: S.stars, mastered: !!S.done.m, url: location.href.split(/[?#]/)[0], t: Date.now() };
store('abiLessons', all);
}
/* page frame. The original content stays in the page for search engines and no-JS readers. */
var src = document.createElement('div');
src.className = 'abi-l-src';
while (root.firstChild) src.appendChild(root.firstChild);
root.innerHTML =
'
';
stage(h, !done);
Array.prototype.forEach.call(STAGE.querySelectorAll('.abi-l-opt'), function (b) {
b.onclick = function () { if (S.ans[S.i] != null) return; S.ans[S.i] = +b.getAttribute('data-k'); render(); var n = $('[data-act="next"]'); if (n) n.focus({ preventScroll: true }); };
});
on('[data-act="say"]', function () { S.simple = true; render(); });
on('[data-act="next"]', function () { S.simple = false; if (S.i < list.length - 1) { S.i++; render(); } else onDone(); });
}
function placeFromCheck() {
var c = S.cur.map(function (q, j) { return S.ans[j] === q.a; });
S.check = c; S.done.check = true;
var lv = TOP + 1;
for (var x = 0; x < LV.length; x++) {
var n = LV[x], miss = S.cur.some(function (q, j) { return (q.lv || 1) === n && !c[j]; });
if (miss) { lv = n; break; }
}
LV.forEach(function (n) { if (n < lv) { S.done[n] = true; S.stars[n] = Math.max(S.stars[n], 3); } });
S.level = lv; save(); S.step = 'placed'; render();
}
function screenPlaced() {
var n = S.check.filter(Boolean).length, lv = S.level, top = lv > TOP;
var msg = top ? ['You got all ' + n + '. Impressive!', 'You already handle ' + esc(TITLE.toLowerCase()) + ' at NCE challenge level. Let’s go straight to the mastery check.'] :
lv === TOP ? ['Your ' + esc(TITLE.toLowerCase()) + ' skills are strong.', 'Start at Level ' + lv + ', ' + esc(L.levels[lv].name) + ': the hardest kind of NCE questions on this topic, with more steps, traps, and patterns.'] :
lv > LV[0] ? ['Your rules are solid.', 'Start at Level ' + lv + ', ' + esc(L.levels[lv].name) + ': two- and three-step problems like the ones on the NCE.'] :
['Let’s tune up the rules first.', 'We’ll begin with Level ' + lv + ', ' + esc(L.levels[lv].name) + ': a fast review of the basics. It won’t take long.'];
stage('
' + tag('Quick check done, ' + n + ' of ' + S.check.length + ' correct') + '
' + msg[0] + '
' + msg[1] + '
' +
'
' + pic(ART.pointing) + '
');
on('[data-act="go"]', function () { if (top) startMastery(); else startLevel(lv); render(); });
}
function startLevel(lv) { S.level = lv; S.step = 'cards'; S.card = 0; S.reveal = false; save(); }
function screenCards() {
var Lv = L.levels[S.level], c = Lv.cards[S.card];
var h = '
Level ' + Lv.n + ', ' + esc(Lv.name) + '
';
if (S.card === 0 && Lv.why) h += '
' + Lv.why + '
';
h += tag(c.k) + '
' + c.h + '
' + c.f + '
' + c.b + '
';
if (c.tr) h += '' +
(S.reveal ? '
Here’s how:
' + c.ans + '
' : '');
h += '
' +
'
';
stage(h);
on('[data-act="reveal"]', function () { S.reveal = !S.reveal; render(); });
on('[data-act="back"]', function () { if (S.card > 0) { S.card--; S.reveal = false; render(); } });
on('[data-act="next"]', function () { S.reveal = false; if (S.card < Lv.cards.length - 1) { S.card++; render(); } else { startPractice(0); render(); } });
}
function startPractice(set) { S.counted = false; S.set = set; S.step = 'practice'; S.i = 0; S.ans = []; S.simple = false; S.cur = prep(L.levels[S.level].sets[set]); }
function screenPractice() { questionScreen(S.cur, 'Level ' + S.level + ' practice', function () { S.step = 'pres'; render(); }); }
function screenPracticeResult() {
var Lv = L.levels[S.level], list = S.cur, len = list.length, n = list.filter(function (q, j) { return S.ans[j] === q.a; }).length;
var other = (S.set + 1) % Lv.sets.length;
if (!S.counted) { S.tries[S.level] = (S.tries[S.level] || 0) + 1; S.counted = true; }
var st = n >= len ? 3 : n >= len - 1 ? 2 : n >= len - 2 ? 1 : 0;
S.stars[S.level] = Math.max(S.stars[S.level], st);
var up = n >= len - 1; if (up) S.done[S.level] = true; save();
var h = '
Level ' + Lv.n + ', ' + esc(Lv.name) + '
' + starRow(n, len);
if (up) {
var last = S.level === TOP;
h += '
' + (n === len ? 'Perfect! ' : 'Great work! ') + (last ? 'You’re ready for the mastery check.' : 'Level up!') + '
' + n + ' of ' + len + ' correct. ' +
(last ? 'Last step: ' + L.mastery[0].length + ' mixed questions. Get them all to master ' + esc(TITLE.toLowerCase()) + '.' : 'Next: Level ' + (S.level + 1) + ', ' + esc(L.levels[S.level + 1].name) + '.') + '
' +
'';
stage(h);
on('[data-act="go"]', function () { S.counted = false; if (last) startMastery(); else startLevel(S.level + 1); render(); });
} else if (n === len - 2) {
h += '
So close!
' + n + ' of ' + len + ' correct. You need ' + (len - 1) + ' to move up. Try a fresh set. You’ve got this.
' +
'';
stage(h);
on('[data-act="go"]', function () { S.counted = false; startPractice(other); render(); });
on('[data-act="cards"]', function () { S.counted = false; startLevel(S.level); render(); });
} else {
var R = Lv.reteach, second = S.tries[S.level] >= 2;
h += '
' + (second ? 'This one is tricky. That’s okay.' : 'Let’s look at it another way.') + '
' + n + ' of ' + len + ' correct. ' +
(second ? 'Ask your teacher or parent to go through it with you, or send me a message.' : 'Here’s a different way to see it. Then try a fresh set.') + '
';
stage(h);
on('[data-act="go"]', function () { S.counted = false; startPractice(other); render(); });
}
}
function startMastery() { S.step = 'mastery'; S.level = TOP + 1; S.i = 0; S.ans = []; S.simple = false; S.counted = false; S.set = (S.tries.m || 0) % Math.max(1, L.mastery.length); S.cur = prep(L.mastery[S.set] || []); save(); }
function screenMastery() { questionScreen(S.cur, 'Mastery check', function () { S.step = 'mres'; render(); }); }
function screenMasteryResult() {
var list = S.cur, len = list.length, n = list.filter(function (q, j) { return S.ans[j] === q.a; }).length;
if (!S.counted) { S.tries.m = (S.tries.m || 0) + 1; S.counted = true; }
if (n === len) { S.done.m = true; S.done[TOP] = true; save(); S.counted = false; S.step = 'finished'; render(); return; }
save();
stage(tag('Mastery check, ' + n + ' of ' + len) + '
' + (n === len - 1 ? 'Almost there!' : 'Not yet, and that’s fine.') + '
' +
'
Mastery means ' + len + ' out of ' + len + '. ' + (n === len - 1 ? 'One more try with a fresh set.' : 'Go back to Level ' + TOP + ' for more practice, then try again.') + '
' +
'
' +
(n === len - 1 ? '' : '') + '
');
on('[data-act="go"]', function () { S.counted = false; if (n === len - 1) startMastery(); else startLevel(TOP); render(); });
on('[data-act="l3"]', function () { S.counted = false; startLevel(TOP); render(); });
}
function screenFinished() {
stage('
' + pic(ART.trophy || IMG_TALK) + '
' +
'
Mastered
You mastered ' + esc(TITLE.toLowerCase()) + '!
' +
'
Every question right at NCE challenge level. That’s a real Pisay skill.
');
on('[data-act="again"]', function () { startLevel(TOP); render(); });
}
function render() {
if (S.step === 'start') screenStart();
else if (S.step === 'check') questionScreen(S.cur, 'Quick check', placeFromCheck);
else if (S.step === 'placed') screenPlaced();
else if (S.step === 'cards') screenCards();
else if (S.step === 'practice') screenPractice();
else if (S.step === 'pres') screenPracticeResult();
else if (S.step === 'mastery') screenMastery();
else if (S.step === 'mres') screenMasteryResult();
else if (S.step === 'finished') screenFinished();
}
if (/[?&]abitest/.test(location.search)) root.__abiAnswer = function () { return S.cur && S.cur[S.i] ? S.cur[S.i].a : null; };
render();
}
})();
/* ============================================================
TEACHER ABI STUDENT HUB
One page per exam that tells a student what to do next, from their
real results on this device:
abiResults - finished diagnostics (written by the diagnostic engine)
abiLessons - leveled lesson progress (written by the lesson engine)
abiHub: - this hub's own settings (name, sessions, ticked reviewers)
...readable list of links for search engines and readers without scripts...
============================================================ */
(function () {
'use strict';
var roots = document.querySelectorAll('.abi-sh');
if (!roots.length) return;
var MSG = (window.TA_CONFIG && window.TA_CONFIG.messenger) || 'https://m.me/araltayo.ph';
var ART = (window.TA_CONFIG && window.TA_CONFIG.art) || {};
var SUBJECT_ART = { quantitative: 'calculator', verbal: 'reading' };
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
function store(k, v) { try { if (v === undefined) return JSON.parse(localStorage.getItem(k) || 'null'); localStorage.setItem(k, JSON.stringify(v)); } catch (e) { return null; } }
Array.prototype.forEach.call(roots, function (root) {
try { init(root); } catch (e) { root.classList.remove('abi-sh-on'); if (window.console) console.error(e); }
});
function init(root) {
var D = JSON.parse(root.querySelector('script.abi-sh-data').textContent);
var KEY = 'abiHub:' + (D.id || 'hub');
var S = store(KEY) || {};
/* carry over the name a student typed into an older hub */
if (!S.name && D.legacyStore) { var old = store(D.legacyStore); if (old && old.name) S.name = String(old.name).slice(0, 24); }
S.sessions = S.sessions || 3;
S.done = S.done || {};
function save() { store(KEY, S); }
var src = document.createElement('div');
src.className = 'abi-sh-src';
while (root.firstChild) src.appendChild(root.firstChild);
var app = document.createElement('div');
app.className = 'abi-sh-app';
root.appendChild(app);
root.appendChild(src);
root.classList.add('abi-sh-on');
/* ---------- what the student has done ---------- */
function results() { return store('abiResults') || {}; }
function lessons() { return store('abiLessons') || {}; }
function testResult(t) { var r = results()[t.diag]; return r && typeof r.pct === 'number' ? r : null; }
function topicState(tp) {
if (tp.lesson) {
var l = lessons()[tp.lesson];
if (!l) return { kind: 'new' };
if (l.mastered) return { kind: 'mastered' };
var lv = l.level || 0, stars = 0;
if (l.stars) Object.keys(l.stars).forEach(function (k) { stars += l.stars[k] || 0; });
return { kind: 'going', level: lv, stars: stars };
}
return S.done[tp.url] ? { kind: 'ticked' } : { kind: 'new' };
}
function isDone(tp) { var k = topicState(tp).kind; return k === 'mastered' || k === 'ticked'; }
function areaScore(test, area) { var r = testResult(test); return r && r.areas && r.areas[area] ? r.areas[area].p : null; }
/* the to-do queue: untaken diagnostics, then topics in the weakest areas, then the rest in order */
function queue() {
var q = [];
D.tests.forEach(function (t) {
if (!testResult(t)) q.push({ type: 'test', t: t, title: 'Take Test ' + t.n + ': ' + t.name, why: 'A ' + (t.minutes || 60) + '-minute diagnostic. Your result shows which topics to study first.', url: t.url, cta: 'Take Test ' + t.n });
});
D.tests.forEach(function (t) {
var list = (D.topics || {})[t.key] || [];
var scored = list.map(function (tp, i) {
var a = areaScore(t, tp.area);
return { tp: tp, i: i, a: a };
}).filter(function (x) { return !isDone(x.tp); });
/* lessons already started come first, then the weakest areas, then the learning order */
scored.sort(function (x, y) {
var gx = topicState(x.tp).kind === 'going' ? 0 : 1, gy = topicState(y.tp).kind === 'going' ? 0 : 1;
var wx = x.a != null && x.a < 75 ? x.a : 999, wy = y.a != null && y.a < 75 ? y.a : 999;
return gx - gy || wx - wy || x.i - y.i;
});
scored.forEach(function (x) {
var st = topicState(x.tp), going = st.kind === 'going';
var why = going ? 'You stopped at Level ' + st.level + '. Pick up where you left off.' :
(x.a != null && x.a < 75 ? 'Your Test ' + t.n + ' result in ' + (testResult(t).areas[x.tp.area].name || x.tp.area) + ' was ' + x.a + '%. This topic is part of that area.' :
'Next in the learning order for ' + t.name + '.');
q.push({ type: 'topic', t: t, tp: x.tp, title: (going ? 'Continue ' : 'Learn ') + x.tp.title, why: why, url: x.tp.url, cta: going ? 'Continue the lesson' : (x.tp.lesson ? 'Start the lesson' : 'Open the reviewer') });
});
});
return q;
}
function daysLeft() {
if (!D.date) return null;
var exam = new Date(D.date + 'T00:00:00+08:00'), now = new Date();
return Math.max(0, Math.ceil((exam - now) / 86400000));
}
function fmtDate(d) {
var m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var p = d.split('-'); return m[+p[1] - 1] + ' ' + (+p[2]) + ', ' + p[0];
}
/* ---------- screens ---------- */
function render() {
var q = queue(), next = q[0], days = daysLeft();
var h = '';
/* top: greeting, countdown, next step */
h += '';
h += '
';
});
h += '';
/* topics per test; tests with no reviewers yet share one short note */
var soon = [];
D.tests.forEach(function (t) {
var list = (D.topics || {})[t.key] || [];
if (!list.length) { soon.push(t); return; }
var done = list.filter(isDone).length;
var art = ART[SUBJECT_ART[t.key]];
h += '' + (art ? '' : '') + '
' + esc(t.name) + ': ' + list.length + ' topics
' + done + ' of ' + list.length + ' done
' +
'
' +
'
Work through them in this order. Leveled lessons record your progress here by themselves; for the other reviewers, tick Done when you finish.
';
list.forEach(function (tp) {
var st = topicState(tp), a = areaScore(t, tp.area), r = testResult(t);
var weak = a != null && a < 60 && !isDone(tp);
var meta = (tp.lesson ? 'Leveled lesson' : 'Reviewer') + (weak ? 'Start here (' + a + '%)' : '');
var status = tp.lesson ?
(st.kind === 'mastered' ? '\u2713 Mastered' :
st.kind === 'going' ? 'Level ' + st.level + ', in progress' : 'Not started') :
'';
h += '
';
});
h += '';
});
if (soon.length) {
var names = soon.map(function (t) { return t.name; });
var joined = names.length > 1 ? names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1] : names[0];
h += '
' + esc(joined) + '
Reviewers for ' + (soon.length > 1 ? 'these tests' : 'this test') + ' are being written. Until then, take ' +
(function (l) { return l.length > 1 ? l.slice(0, -1).join(', ') + ' and ' + l[l.length - 1] : l[0]; })(soon.map(function (t) { return 'Test ' + esc(t.n) + ''; })) + ' and use your result to see what to practice.
';
}
/* this week */
var week = q.slice(0, S.sessions);
h += '
Your progress is saved on this device only. If you switch phones or clear your browser, it starts fresh.
';
}
app.innerHTML = h;
wire();
}
function wire() {
var nb = app.querySelector('[data-act="name"]'), form = app.querySelector('.abi-sh-nameform');
nb.onclick = function () { form.hidden = !form.hidden; if (!form.hidden) form.querySelector('input').focus(); };
form.onsubmit = function (e) { e.preventDefault(); S.name = form.querySelector('input').value.trim().slice(0, 24); save(); render(); };
Array.prototype.forEach.call(app.querySelectorAll('[data-sessions]'), function (b) {
b.onclick = function () { S.sessions = +b.getAttribute('data-sessions'); save(); render(); app.querySelector('[data-sessions="' + S.sessions + '"]').focus(); };
});
Array.prototype.forEach.call(app.querySelectorAll('[data-done]'), function (c) {
c.onchange = function () { var u = c.getAttribute('data-done'); if (c.checked) S.done[u] = Date.now(); else delete S.done[u]; save(); render(); var x = app.querySelector('[data-done="' + u.replace(/"/g, '\\"') + '"]'); if (x) x.focus(); };
});
}
render();
/* come back from a lesson or test in another tab: refresh */
window.addEventListener('storage', function (e) { if (!e.key || /^abi(Results|Lessons|Hub)/.test(e.key)) render(); });
window.addEventListener('pageshow', function (e) { if (e.persisted) render(); });
}
})();
//]]>