Spaces:
Running
Running
Download app.js from danishk84/LearnGerman: direct link, hf CLI and curl.
- Browser
- Download file 21.3 kB
-
https://huggingface.co/spaces/danishk84/LearnGerman/resolve/main/app.js
- Command line
-
hf download hf://spaces/danishk84/LearnGerman/app.js
-
curl -L -o app.js https://huggingface.co/spaces/danishk84/LearnGerman/resolve/main/app.js
21.3 kB
| let LESSONS=[], state=null, currentView="home", currentLesson=null; | |
| const KEY="familieDeutschA1_v1"; | |
| const avatars=["👨","👩","👧","👦","🧑","👱","🧕","🧔","👩🎓","👨💻","🦸","🧙","🐻","🦊","🐼","🐯","🐸","🐧"]; | |
| function defaultState(){ | |
| return {activeProfile:null, profiles:[], settings:{dailyGoal:20, sound:true}}; | |
| } | |
| function loadState(){ try{return JSON.parse(localStorage.getItem(KEY))||defaultState()}catch{return defaultState()}} | |
| function saveState(){localStorage.setItem(KEY,JSON.stringify(state))} | |
| function profile(){ | |
| return state.profiles.find(p=>p.id===state.activeProfile)||null; | |
| } | |
| function newProfile(name, avatar){ | |
| return {id:crypto.randomUUID?crypto.randomUUID():Date.now().toString(),name,avatar,created:new Date().toISOString(),completed:[],scores:{},difficult:{},lastStudy:null,streak:0,xp:0}; | |
| } | |
| function escapeHTML(s){return String(s).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">","\"":""","'":"'"}[c]))} | |
| function toast(msg){let t=document.getElementById("toast");t.textContent=msg;t.classList.add("show");setTimeout(()=>t.classList.remove("show"),2200)} | |
| function speak(text){ | |
| if(!state.settings.sound||!("speechSynthesis" in window))return toast("Audio is disabled or unavailable."); | |
| speechSynthesis.cancel(); let u=new SpeechSynthesisUtterance(text);u.lang="de-DE";u.rate=.78;speechSynthesis.speak(u); | |
| } | |
| function setView(v){currentView=v;currentLesson=null;closeDrawer();render();window.scrollTo({top:0,behavior:"smooth"})} | |
| function openDrawer(){drawer.classList.add("open");overlay.classList.add("open")} | |
| function closeDrawer(){drawer.classList.remove("open");overlay.classList.remove("open")} | |
| function ensureProfile(){ | |
| if(!profile()){renderProfiles(true);return false} return true; | |
| } | |
| function completedPct(p){return Math.round((p.completed.length/30)*100)} | |
| function updateStreak(p){ | |
| const today=new Date().toISOString().slice(0,10); | |
| if(p.lastStudy===today)return; | |
| const y=new Date();y.setDate(y.getDate()-1); | |
| p.streak=p.lastStudy===y.toISOString().slice(0,10)?p.streak+1:1; | |
| p.lastStudy=today; | |
| } | |
| function nextDay(p){for(let d=1;d<=30;d++)if(!p.completed.includes(d))return d;return 30} | |
| function render(){ | |
| if(currentView==="profiles")return renderProfiles(false); | |
| if(!state.profiles.length)return renderWelcome(); | |
| if(!profile())state.activeProfile=state.profiles[0].id; | |
| document.getElementById("profileBtn").textContent=profile().avatar; | |
| const routes={home:renderHome,journey:renderJourney,vocabulary:renderVocabulary,review:renderReview,progress:renderProgress,family:renderFamily,settings:renderSettings}; | |
| (routes[currentView]||renderHome)(); | |
| } | |
| function renderWelcome(){ | |
| app.innerHTML=`<section class="hero"><div class="hero-row"><div class="hero-avatar">🌳</div><div><h1>Willkommen!</h1><p>A friendly 30-day German A1 journey for your whole family.</p></div></div></section> | |
| <section class="card" style="margin-top:16px"><h2>Create the first learner</h2><p class="muted">Each person receives an avatar, private progress, quiz scores, difficult-word review and a learning streak.</p> | |
| <button class="btn btn-primary btn-block" onclick="renderProfiles(true)">Create family profile</button></section>`; | |
| } | |
| function renderHome(){ | |
| const p=profile(), nd=nextDay(p), l=LESSONS[nd-1], pct=completedPct(p); | |
| app.innerHTML=`<section class="hero"><div class="hero-row"><div class="hero-avatar">${p.avatar}</div><div><h1>Hallo, ${escapeHTML(p.name)}!</h1><p>${p.completed.length===30?"Du hast alle 30 Tage geschafft!":"Bereit für deine heutige Deutsch-Mission?"}</p></div></div> | |
| <div class="progressbar"><span style="width:${pct}%"></span></div><small>${p.completed.length} of 30 days · ${pct}% complete</small></section> | |
| <div class="grid"> | |
| <div class="card"><div class="muted">Streak</div><div class="metric">🔥 ${p.streak}</div><small>days</small></div> | |
| <div class="card"><div class="muted">XP</div><div class="metric">⭐ ${p.xp}</div><small>points</small></div> | |
| <div class="card"><div class="muted">Words to review</div><div class="metric">🧠 ${Object.keys(p.difficult).length}</div><small>difficult</small></div> | |
| <div class="card"><div class="muted">Quiz average</div><div class="metric">${averageScore(p)}%</div><small>accuracy</small></div> | |
| </div> | |
| <div class="section-title"><h2>Today’s lesson</h2><span class="pill">15–25 min</span></div> | |
| <section class="card lesson-card"><div class="lesson-icon">${l.icon}</div><div class="grow"><strong>Day ${l.day}: ${l.title}</strong><div class="muted">${l.subtitle}</div></div><button class="btn btn-primary" onclick="openLesson(${l.day})">${p.completed.includes(l.day)?"Review":"Start"}</button></section> | |
| <div class="section-title"><h2>Quick actions</h2></div> | |
| <div class="grid"> | |
| <button class="card btn" onclick="setView('review')">🔁<br><strong>Difficult words</strong></button> | |
| <button class="card btn" onclick="setView('journey')">🗓️<br><strong>30-day journey</strong></button> | |
| <button class="card btn" onclick="setView('family')">🌳<br><strong>Family tree</strong></button> | |
| <button class="card btn" onclick="setView('progress')">📊<br><strong>My progress</strong></button> | |
| </div>`; | |
| } | |
| function averageScore(p){let vals=Object.values(p.scores);return vals.length?Math.round(vals.reduce((a,b)=>a+b,0)/vals.length):0} | |
| function openLesson(day){currentLesson=LESSONS[day-1];renderLesson(0)} | |
| function renderLesson(step=0){ | |
| const l=currentLesson,p=profile(); | |
| const stepNames=["Goal","Words","Build","Maple","Play","Quiz","Finish"]; | |
| if(step===0){ | |
| app.innerHTML=`<button class="btn btn-secondary" onclick="setView('journey')">← Journey</button> | |
| <section class="lesson-head" style="margin-top:12px"><div class="big-icon">${l.icon}</div><span class="pill">Day ${l.day}</span><h1>${l.title}</h1><p>${l.subtitle}</p></section> | |
| <section class="card mission step"><h2>🎯 Today’s goal</h2><p>Learn ${l.words.length} useful words, practise ${l.patterns.length} sentence patterns and complete Maple’s family mission.</p><h3>Family mission</h3><p>${l.mission}</p> | |
| <button class="btn btn-primary btn-block" onclick="renderLesson(1)">Start learning</button></section>`; | |
| } else if(step===1){ | |
| app.innerHTML=lessonHeader(l,stepNames,step)+`<div class="grid">${l.words.map(w=>`<div class="card word-card"><div><div class="de">${w[0]}</div><div>${w[1]}</div><div class="pron">${w[2]}</div></div><button class="speaker" onclick='speak(${JSON.stringify(w[0])})'>🔊</button></div>`).join("")}</div> | |
| <button class="btn btn-primary btn-block step" onclick="renderLesson(2)">Build sentences →</button>`; | |
| } else if(step===2){ | |
| app.innerHTML=lessonHeader(l,stepNames,step)+`<section class="card"><h2>Useful patterns</h2>${l.patterns.map(x=>`<div class="pattern"><strong>${x[0]}</strong><br><span class="muted">${x[1]}</span><button class="speaker" style="float:right" onclick='speak(${JSON.stringify(x[0].replace("_____","Danish"))})'>🔊</button></div>`).join("")}<h3>Small grammar capsule</h3><p>${l.grammar}</p></section> | |
| <button class="btn btn-primary btn-block step" onclick="renderLesson(3)">Speak with Maple →</button>`; | |
| } else if(step===3){ | |
| app.innerHTML=lessonHeader(l,stepNames,step)+`<section class="card maple"><h2>🦊 Maple says</h2>${l.maple.map((x,i)=>`<div class="pattern"><strong>${x}</strong><button class="speaker" style="float:right" onclick='speak(${JSON.stringify(x)})'>🔊</button></div>`).join("")}<p class="muted">Answer aloud. The goal is confidence, not perfection.</p></section> | |
| <button class="btn btn-primary btn-block step" onclick="renderLesson(4)">Play →</button>`; | |
| } else if(step===4){ | |
| const shuffled=[...l.words].sort(()=>Math.random()-.5); | |
| app.innerHTML=lessonHeader(l,stepNames,step)+`<section class="card"><h2>Match from memory</h2><p>Tap each German word and say its meaning aloud.</p>${shuffled.map(w=>`<button class="quiz-option" onclick="this.innerHTML='<strong>${escapeHTML(w[0])}</strong><br>${escapeHTML(w[1])} · <span class=pron>${escapeHTML(w[2])}</span>'">${w[0]} — reveal meaning</button>`).join("")}</section> | |
| <button class="btn btn-primary btn-block step" onclick="startQuiz()">Take today’s quiz →</button>`; | |
| } else if(step===6){finishLesson(l)} | |
| } | |
| function lessonHeader(l,names,step){return `<button class="btn btn-secondary" onclick="setView('home')">← Home</button><section class="lesson-head" style="margin-top:12px"><span class="pill">Day ${l.day} · ${names[step]}</span><h1>${l.icon} ${l.title}</h1><div class="progressbar" style="background:#d1fae5"><span style="width:${Math.round((step/6)*100)}%;background:var(--primary)"></span></div></section>`} | |
| let quizIndex=0,quizCorrect=0,quizAnswers=[]; | |
| function startQuiz(){quizIndex=0;quizCorrect=0;quizAnswers=[];renderQuiz()} | |
| function renderQuiz(){ | |
| const l=currentLesson,q=l.quiz[quizIndex]; | |
| app.innerHTML=lessonHeader(l,["","","","","","Quiz",""],5)+`<section class="card"><span class="pill">Question ${quizIndex+1} of ${l.quiz.length}</span><h2>${q.q}</h2><div id="options">${q.options.map(o=>`<button class="quiz-option" onclick='answerQuiz(this,${JSON.stringify(o)},${JSON.stringify(q.answer)})'>${o}</button>`).join("")}</div><div id="quizNext"></div></section>`; | |
| } | |
| function answerQuiz(btn,answer,correct){ | |
| document.querySelectorAll(".quiz-option").forEach(b=>b.disabled=true); | |
| const ok=answer===correct;if(ok){quizCorrect++;btn.classList.add("correct")}else{btn.classList.add("wrong");[...document.querySelectorAll(".quiz-option")].find(b=>b.textContent===correct)?.classList.add("correct")} | |
| quizAnswers.push({ok,answer,correct}); | |
| const l=currentLesson,p=profile(); | |
| if(!ok){ | |
| const word=l.words.find(w=>w[1]===correct||w[0]===correct); | |
| if(word)p.difficult[word[0]]={de:word[0],en:word[1],pron:word[2],count:(p.difficult[word[0]]?.count||0)+1,last:new Date().toISOString()}; | |
| } | |
| saveState(); | |
| document.getElementById("quizNext").innerHTML=`<p><strong>${ok?"Richtig! 🎉":"Fast richtig. The correct answer is: "+correct}</strong></p><button class="btn btn-primary btn-block" onclick="nextQuiz()">${quizIndex+1<l.quiz.length?"Next question":"See result"}</button>`; | |
| } | |
| function nextQuiz(){quizIndex++;if(quizIndex<currentLesson.quiz.length)renderQuiz();else finishLesson(currentLesson)} | |
| function finishLesson(l){ | |
| const p=profile(),score=Math.round((quizCorrect/l.quiz.length)*100); | |
| p.scores[l.day]=Math.max(p.scores[l.day]||0,score); | |
| if(!p.completed.includes(l.day)){p.completed.push(l.day);p.xp+=50+quizCorrect*10} | |
| updateStreak(p);saveState(); | |
| app.innerHTML=lessonHeader(l,["","","","","","","Finish"],6)+`<section class="card" style="text-align:center"><div style="font-size:4rem">${score>=80?"🏆":"🌟"}</div><h1>Day ${l.day} completed!</h1><p class="metric">${score}%</p><p>${score>=80?"Wunderbar! You are ready to continue.":"Good work. Review the difficult words and try again later."}</p><p>+${50+quizCorrect*10} XP</p> | |
| <button class="btn btn-primary btn-block" onclick="setView('home')">Back to home</button><button class="btn btn-secondary btn-block step" onclick="openLesson(${l.day})">Repeat lesson</button></section>`; | |
| } | |
| function renderJourney(){ | |
| const p=profile(); | |
| app.innerHTML=`<div class="section-title"><div><h1>30-Day Journey</h1><p class="muted">Small steps, practical German and a review every seventh day.</p></div></div> | |
| ${LESSONS.map(l=>`<section class="card lesson-card" style="margin-bottom:10px"><div class="lesson-icon">${l.icon}</div><div class="grow"><strong>Day ${l.day}: ${l.title}</strong><div class="muted">${l.subtitle}</div></div><span class="pill ${p.completed.includes(l.day)?"done":""}">${p.completed.includes(l.day)?"✓ Done":(l.day===nextDay(p)?"Next":"Open")}</span><button class="btn btn-secondary" onclick="openLesson(${l.day})">View</button></section>`).join("")}`; | |
| } | |
| function renderVocabulary(){ | |
| const all=LESSONS.flatMap(l=>l.words.map(w=>({day:l.day,...{de:w[0],en:w[1],pron:w[2]}}))); | |
| app.innerHTML=`<h1>Vocabulary Library</h1><p class="muted">${all.length} curated A1 learning items across the 30-day path.</p><input id="vocabSearch" class="input search" placeholder="Search German or English…" oninput="filterVocab(this.value)"> | |
| <div id="vocabList">${vocabHTML(all)}</div>`; | |
| } | |
| function vocabHTML(items){return items.map(w=>`<div class="card list-row"><button class="speaker" onclick='speak(${JSON.stringify(w.de)})'>🔊</button><div class="grow"><strong>${w.de}</strong><div>${w.en}</div><small class="pron">${w.pron} · Day ${w.day}</small></div></div>`).join("")} | |
| function filterVocab(q){q=q.toLowerCase();const all=LESSONS.flatMap(l=>l.words.map(w=>({day:l.day,de:w[0],en:w[1],pron:w[2]}))).filter(w=>(w.de+" "+w.en).toLowerCase().includes(q));document.getElementById("vocabList").innerHTML=vocabHTML(all)} | |
| function renderReview(){ | |
| const p=profile(),items=Object.values(p.difficult); | |
| app.innerHTML=`<h1>Difficult Words</h1><p class="muted">Words enter this list after an incorrect answer. Mark them mastered after successful review.</p>${items.length?items.map(w=>`<section class="card list-row"><button class="speaker" onclick='speak(${JSON.stringify(w.de)})'>🔊</button><div class="grow"><strong>${w.de}</strong><div>${w.en}</div><small class="pron">${w.pron} · missed ${w.count} time(s)</small></div><button class="btn btn-secondary" onclick='masterWord(${JSON.stringify(w.de)})'>Mastered</button></section>`).join(""):`<section class="card"><h2>🎉 No difficult words</h2><p>Complete quizzes and this area will create a personalised review list.</p></section>`}`; | |
| } | |
| function masterWord(de){delete profile().difficult[de];profile().xp+=10;saveState();toast("Word marked as mastered +10 XP");renderReview()} | |
| function renderProgress(){ | |
| const p=profile(),pct=completedPct(p); | |
| const weeks=[p.completed.filter(d=>d<=7).length,p.completed.filter(d=>d>7&&d<=14).length,p.completed.filter(d=>d>14&&d<=21).length,p.completed.filter(d=>d>21).length]; | |
| app.innerHTML=`<h1>${p.avatar} ${escapeHTML(p.name)}’s Progress</h1><section class="hero"><h2>${pct}% complete</h2><div class="progressbar"><span style="width:${pct}%"></span></div><p>${p.completed.length} lessons · ${p.xp} XP · ${p.streak}-day streak</p></section> | |
| <div class="section-title"><h2>Weekly path</h2></div>${weeks.map((n,i)=>`<section class="card" style="margin-bottom:10px"><strong>Week ${i+1}</strong><div class="progressbar" style="background:#d1fae5"><span style="width:${Math.round((n/(i===3?9:7))*100)}%;background:var(--primary)"></span></div><small>${n} completed</small></section>`).join("")} | |
| <div class="section-title"><h2>Lesson scores</h2></div><section class="card">${Object.keys(p.scores).length?Object.entries(p.scores).map(([d,s])=>`<div class="list-row"><span>Day ${d}: ${LESSONS[d-1].title}</span><strong style="margin-left:auto">${s}%</strong></div>`).join(""):"No quiz scores yet."}</section> | |
| ${p.completed.length===30?`<section class="certificate step"><h1>Urkunde</h1><h2>German A1 Family Foundation</h2><p>This certifies that</p><h1>${escapeHTML(p.name)}</h1><p>completed the 30-day family learning journey.</p><p>Familie lernt Deutsch · ${new Date().toLocaleDateString()}</p></section>`:""}`; | |
| } | |
| function renderFamily(){ | |
| const total=state.profiles.reduce((a,p)=>a+p.completed.length,0),xp=state.profiles.reduce((a,p)=>a+p.xp,0); | |
| app.innerHTML=`<h1>Family Progress</h1><section class="hero"><h2>🌳 Gemeinsam lernen</h2><p>Together your family has completed ${total} lessons and earned ${xp} XP.</p><div class="progressbar"><span style="width:${Math.min(100,Math.round(total/(state.profiles.length*30)*100))}%"></span></div></section> | |
| <div class="profile-grid step">${state.profiles.map(p=>`<section class="card profile-card ${p.id===state.activeProfile?"active":""}"><div class="avatar">${p.avatar}</div><h3>${escapeHTML(p.name)}</h3><div class="metric">${completedPct(p)}%</div><p class="muted">${p.completed.length}/30 · 🔥 ${p.streak} · ⭐ ${p.xp}</p><button class="btn btn-secondary" onclick='switchProfile(${JSON.stringify(p.id)})'>Open</button></section>`).join("")}</div> | |
| <section class="card step"><h2>Family learning tree</h2><div style="font-size:3rem;line-height:1.2;text-align:center">${"🌿".repeat(Math.min(10,Math.ceil(total/3)))}<br>🌳</div><p class="muted" style="text-align:center">A new leaf appears for every three family lessons.</p></section>`; | |
| } | |
| function renderProfiles(forceCreate=false){ | |
| currentView="profiles"; | |
| app.innerHTML=`<h1>Profiles & Avatars</h1><p class="muted">Select a learner or create a separate profile. Progress is never mixed between family members.</p> | |
| <div class="profile-grid">${state.profiles.map(p=>`<section class="card profile-card ${p.id===state.activeProfile?"active":""}"><div class="avatar">${p.avatar}</div><h3>${escapeHTML(p.name)}</h3><p>${p.completed.length}/30 days</p><button class="btn btn-secondary" onclick='switchProfile(${JSON.stringify(p.id)})'>Select</button><button class="btn btn-danger" style="margin-top:8px" onclick='deleteProfile(${JSON.stringify(p.id)})'>Delete</button></section>`).join("")}</div> | |
| <section class="card step"><h2>Add family member</h2><label>Name</label><input id="newName" class="input" maxlength="24" placeholder="Learner name"><h3>Choose an avatar</h3><div class="avatar-grid">${avatars.map((a,i)=>`<button class="avatar-choice ${i===0?"selected":""}" onclick="chooseAvatar(this,'${a}')">${a}</button>`).join("")}</div><input id="chosenAvatar" type="hidden" value="${avatars[0]}"><button class="btn btn-primary btn-block step" onclick="addProfile()">Create profile</button></section>`; | |
| } | |
| function chooseAvatar(btn,a){document.querySelectorAll(".avatar-choice").forEach(x=>x.classList.remove("selected"));btn.classList.add("selected");document.getElementById("chosenAvatar").value=a} | |
| function addProfile(){const name=document.getElementById("newName").value.trim(),a=document.getElementById("chosenAvatar").value;if(!name)return toast("Please enter a name.");const p=newProfile(name,a);state.profiles.push(p);state.activeProfile=p.id;saveState();toast("Profile created");setView("home")} | |
| function switchProfile(id){state.activeProfile=id;saveState();toast("Profile selected");setView("home")} | |
| function deleteProfile(id){if(!confirm("Delete this learner and all progress?"))return;state.profiles=state.profiles.filter(p=>p.id!==id);if(state.activeProfile===id)state.activeProfile=state.profiles[0]?.id||null;saveState();renderProfiles()} | |
| function renderSettings(){ | |
| app.innerHTML=`<h1>Settings & Backup</h1><section class="card"><h2>Learning settings</h2><label><input type="checkbox" ${state.settings.sound?"checked":""} onchange="state.settings.sound=this.checked;saveState()"> German text-to-speech audio</label><br><br><label>Daily goal (minutes)</label><select class="input" onchange="state.settings.dailyGoal=+this.value;saveState()"><option ${state.settings.dailyGoal===15?"selected":""}>15</option><option ${state.settings.dailyGoal===20?"selected":""}>20</option><option ${state.settings.dailyGoal===25?"selected":""}>25</option></select></section> | |
| <section class="card step"><h2>Family backup</h2><p class="muted">Progress is stored in this browser. Export a backup to move or restore it on another family phone.</p><button class="btn btn-primary" onclick="exportBackup()">Export backup</button><label class="btn btn-secondary" style="display:inline-block">Import backup<input type="file" accept=".json" hidden onchange="importBackup(this.files[0])"></label></section> | |
| <section class="card step"><h2>Install on mobile</h2><p>Open the deployed website in the phone browser and choose <strong>Add to Home Screen</strong>. It will behave like a lightweight family learning app.</p></section> | |
| <section class="card step"><h2>Storage note</h2><p class="muted">This release uses private browser storage. Profiles on one phone stay together. To combine progress from multiple phones, export the latest family backup and import it on the main family device.</p></section>`; | |
| } | |
| function exportBackup(){const blob=new Blob([JSON.stringify(state,null,2)],{type:"application/json"});const a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download="familie-deutsch-backup.json";a.click();URL.revokeObjectURL(a.href)} | |
| function importBackup(file){if(!file)return;const r=new FileReader();r.onload=()=>{try{const x=JSON.parse(r.result);if(!Array.isArray(x.profiles))throw Error();state=x;saveState();toast("Backup imported");setView("home")}catch{toast("Invalid backup file")}};r.readAsText(file)} | |
| document.addEventListener("click",e=>{const b=e.target.closest("[data-view]");if(b)setView(b.dataset.view)}); | |
| document.getElementById("menuBtn").onclick=openDrawer;document.getElementById("closeDrawer").onclick=closeDrawer;document.getElementById("overlay").onclick=closeDrawer;document.getElementById("profileBtn").onclick=()=>setView("profiles"); | |
| fetch("data/lessons.json").then(r=>r.json()).then(x=>{LESSONS=x;state=loadState();render()}).catch(()=>{app.innerHTML="<div class=card><h2>Unable to load lessons.</h2><p>Please run this website through a web server rather than opening index.html directly.</p></div>"}); | |
| if("serviceWorker" in navigator)window.addEventListener("load",()=>navigator.serviceWorker.register("sw.js")); | |