Back to Morse Tree
SOURCE / PINNED RELEASE

Made of little things.

Morse Tree

Release
52c388d28ec3…
Author-recorded commit
fd8192a198f7…
License
Check the original source
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-6ab5aa84ba1

The hash-verified playable HTML, which may contain bundled or minified code. This view does not execute it.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <title>Morse Tree</title>
    <meta name="description" content="Learn Morse code on its binary tree: dots go left, dashes go right. Tap a letter to hear it and see it flashed from the boat; key dots and dashes on one straight key with real Morse timing to walk the tree and write." />
    <script type="module" crossorigin>function lt(){const e=new Map;function t(o,a){if(e.has(o))throw new Error(`NAP domain "${o}" is already registered`);e.set(o,a)}function n(o){const a=o.type.indexOf(".");if(a<=0)return!1;const i=o.type.slice(0,a),d=e.get(i);return d?(d(o),!0):!1}function s(){return Array.from(e.keys())}return{registerNap:t,dispatch:n,getRegisteredDomains:s}}var ut=lt(),dt=ut.registerNap,Te="storage";dt(Te,e=>{});function pt(){const e=window;if(!e.napplet)throw new Error("window.napplet is unavailable -- runtime did not inject the napplet namespace");return e.napplet}function S(e){const n=pt()[e];if(!n)throw new Error(`window.napplet.${String(e)} is unavailable -- runtime did not inject this domain`);return n}var Re={getItem(e){return S("storage").getItem(e)},setItem(e,t){return S("storage").setItem(e,t)},removeItem(e){return S("storage").removeItem(e)},keys(){return S("storage").keys()},instance:{getItem(e){return S("storage").instance.getItem(e)},setItem(e,t){return S("storage").instance.setItem(e,t)},removeItem(e){return S("storage").instance.removeItem(e)},keys(){return S("storage").instance.keys()}}};function ft(e,t){return!!(e!=null&&e[t])}function _e(e){return ft(window.napplet,e)}const ve={A:".-",B:"-...",C:"-.-.",D:"-..",E:".",F:"..-.",G:"--.",H:"....",I:"..",J:".---",K:"-.-",L:".-..",M:"--",N:"-.",O:"---",P:".--.",Q:"--.-",R:".-.",S:"...",T:"-",U:"..-",V:"...-",W:".--",X:"-..-",Y:"-.--",Z:"--.."},re=4,mt=Object.fromEntries(Object.entries(ve).map(([e,t])=>[t,e]));function U(e){return mt[e]??null}function le(e){return ve[e.toUpperCase()]??null}function ht(){const e=[""];for(let t=1;t<=re;t+=1)for(let n=0;n<2**t;n+=1)e.push(yt(t,n));return e}function gt(){return ht().filter(e=>e===""||U(e)!==null)}function oe(e){return e===""||U(e)!==null}function wt(){const e=new Map;let t=0;const n=s=>{const o=s.length<re&&oe(s+".")?n(s+"."):null,a=s.length<re&&oe(s+"-")?n(s+"-"):null;let i;return o!==null&&a!==null?i=(o+a)/2:o!==null?i=o+.5:a!==null?i=a-.5:i=t++,e.set(s,i),i};return n(""),{slots:e,count:t}}function yt(e,t){let n="";for(let s=e-1;s>=0;s-=1)n+=t>>s&1?"-":".";return n}function qe(e){return 1200/e}function bt(e){const t=[];let n=0,s=0;return[...e].forEach((o,a)=>{if(o===" "){t.length>0&&(s=7);return}const i=le(o);i&&(n+=s,[...i].forEach((d,f)=>{f>0&&(n+=1);const b=d==="-"?3:1;t.push({start:n,length:b,symbol:f,letter:a}),n+=b}),s=3)}),{tones:t,length:n}}const Tt=15,ue=2,ge=2,ze=5;function vt(e,t){return e<Tt?null:e<ue*t?".":"-"}function xt(e,t){return e<ge*t?"symbol":e<ze*t?"letter":"word"}function xe(e){return{".":1,"-":3,symbol:1,letter:3,word:7}[e]}function kt(e,t,n){const s=xe(n)*t;return Math.max(0,1-Math.abs(e-s)/s)}const Lt="http://www.w3.org/2000/svg",ne=[5,8,12,16,20],Be=240;function h(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing required element: ${e}`);return t}const r={app:h("#app"),stage:h("#stage"),tree:h("#tree"),compact:h("#compact"),banner:h("#banner"),tapeText:h("#tapeText"),playTape:h("#playTape"),backspace:h("#backspace"),clearTape:h("#clearTape"),key:h("#morseKey"),meterFill:h("#meterFill"),strip:h("#strip"),rhythm:h("#rhythm"),sea:h("#sea"),house:h("#sea .house"),boat:h("#sea .boat"),quiz:h("#quizToggle"),lightQuiz:h("#lightQuizToggle"),speed:h("#speedToggle"),sound:h("#soundToggle")},l={tape:"",wpm:8,sound:!0,best:0};let p="",c=null;const Ve="morse-tree-state";let Ie=0;function Ge(e,t){let n=0;return Promise.race([e,new Promise((s,o)=>{n=window.setTimeout(()=>o(new Error("timeout")),t)})]).finally(()=>window.clearTimeout(n))}async function Et(){if(_e(Te))try{const e=await Ge(Re.getItem(Ve),3e3);if(!e)return;const t=JSON.parse(e);typeof t.tape=="string"&&(l.tape=t.tape.slice(-Be)),typeof t.wpm=="number"&&ne.includes(t.wpm)&&(l.wpm=t.wpm),typeof t.sound=="boolean"&&(l.sound=t.sound),typeof t.best=="number"&&t.best>=0&&(l.best=Math.floor(t.best))}catch{}}function F(){_e(Te)&&(window.clearTimeout(Ie),Ie=window.setTimeout(()=>{Ge(Re.setItem(Ve,JSON.stringify(l)),3e3).catch(()=>{})},400))}let y=null,P=null;const We=640;function _(){if(y){y.state==="suspended"&&y.resume();return}try{y=new AudioContext,P=y.createGain(),P.gain.value=.22,P.connect(y.destination)}catch{y=null}}let j=[];function V(e,t,n=We,s="sine"){if(!y||!P||!l.sound)return;const o=y.currentTime+e/1e3+.01,a=o+t/1e3,i=y.createOscillator(),d=y.createGain();i.type=s,i.frequency.value=n,d.gain.setValueAtTime(0,o),d.gain.linearRampToValueAtTime(1,o+.006),d.gain.setValueAtTime(1,Math.max(o+.006,a-.006)),d.gain.linearRampToValueAtTime(0,a),i.connect(d).connect(P),i.start(o),i.stop(a+.02),j.push(i),i.onended=()=>{j=j.filter(f=>f!==i)}}function Fe(){V(0,90,160,"square"),V(110,140,120,"square")}function $t(){V(0,70,880,"triangle"),V(80,70,1175,"triangle"),V(160,140,1568,"triangle")}function W(e,t){r[e].classList.toggle("lit",t)}let ke=0,we=[];function M(){ke+=1,we.forEach(e=>window.clearTimeout(e)),we=[];for(const e of j)try{e.stop()}catch{}j=[],r.tapeText.querySelectorAll(".playing").forEach(e=>e.classList.remove("playing")),r.playTape.classList.remove("active"),W("boat",!1),W("house",!1),E("")}function te(e,t,n){we.push(window.setTimeout(()=>{t===ke&&n()},e))}function de(e,t,n,s=!0,o=!1,a="boat"){M(),_();const i=ke,d=qe(l.wpm),{tones:f,length:b}=bt(e),g=[...e];for(const u of f){const v=le(g[u.letter])??"";o||V(u.start*d,u.length*d),te(u.start*d,i,()=>W(a,!0)),te((u.start+u.length)*d,i,()=>W(a,!1)),s&&te(u.start*d,i,()=>{u.symbol===0&&(t==null||t(u.letter),E("")),He(v.slice(0,u.symbol+1),u.length*d)})}te(b*d+450,i,()=>{E(""),n==null||n()})}const x=new Map,ye=new Map;let O=null,w=null,Ne="";function m(e,t,n){const s=document.createElementNS(Lt,e);for(const[o,a]of Object.entries(t))s.setAttribute(o,String(a));return n==null||n.append(s),s}function Qe(){const e=r.stage.clientWidth,t=r.stage.clientHeight,n=e<170||t<120;r.stage.classList.toggle("is-compact",n);const s=`${e}x${t}`;if(s===Ne)return;if(Ne=s,r.tree.replaceChildren(),x.clear(),ye.clear(),n||e===0){Je();return}r.tree.setAttribute("viewBox",`0 0 ${e} ${t}`);const o=e>=t*.85,a=o?e:t,i=o?t:e,{slots:d,count:f}=wt(),b=a/f,g=Math.min(i*.1,34),u=(i-g*2)/re,v=Math.max(7,Math.min(b*.42,u*.34,30)),X=[.8,1.3,1.18,1,1],fe=T=>{const A=T.length,$=((d.get(T)??0)+.5)*b,k=g+A*u;return o?{x:$,y:k}:{x:k,y:$}},Me=m("g",{class:"edges"},r.tree),Ae=m("g",{class:"nodes"},r.tree);for(const T of gt()){const{x:A,y:$}=fe(T),k=T.length,I=v*X[k],q=U(T);if(k>0){const z=fe(T.slice(0,-1)),ct=T.endsWith("-"),he=m("g",{class:`edge ${ct?"edge-dah":"edge-dit"}`},Me);m("line",{x1:z.x,y1:z.y,x2:A,y2:$,class:"edge-under"},he),m("line",{x1:z.x,y1:z.y,x2:A,y2:$,class:"edge-line"},he),ye.set(T,he)}const N=m("g",{class:`node depth-${k}${q?" has-letter":""}${k===0?" root":""}`,transform:`translate(${A} ${$})`},Ae);q&&m("circle",{r:Math.max(I,Math.min(b,u)*.5),class:"node-hit"},N);const me=m("g",{class:"node-body"},N);m("circle",{r:I,class:"node-disc"},me);const Ce=m("text",{class:"node-label","text-anchor":"middle","dominant-baseline":"central","font-size":I*1.05},me);Ce.textContent=k===0?"":q??"",k===0&&m("circle",{r:I*.28,class:"root-dot"},me),q&&(N.setAttribute("role","button"),N.setAttribute("tabindex","-1"),N.setAttribute("aria-label",`${q}: ${Mt(T)}`),N.addEventListener("pointerdown",z=>{z.preventDefault(),at(q)})),x.set(T,{group:N,label:Ce,x:A,y:$,r:I})}const L=fe(""),ee=v*(o?1.9:3.2),Se=o?[["legend legend-dit","●  dot",L.x-ee,L.y],["legend legend-dah","dash  ▬",L.x+ee,L.y]]:[["legend legend-dit","● dot",L.x-v*.8,L.y-ee],["legend legend-dah","▬ dash",L.x-v*.8,L.y+ee]];u<v*3&&(Se.length=0);for(const[T,A,$,k]of Se){const I=m("text",{class:T,x:$,y:k,"text-anchor":o&&T.includes("dit")?"end":"start","dominant-baseline":"central","font-size":Math.max(10,Math.min(15,v*.6))},Ae);I.textContent=A}O=m("circle",{class:"spark",r:Math.max(4,v*.3),cx:0,cy:0},Me),O.style.transform=`translate(${L.x}px, ${L.y}px)`,w=null,Ke()}function Mt(e){return[...e].map(t=>t==="-"?"dah":"dit").join(" ")}function E(e){for(const[t,n]of x)n.group.classList.toggle("on-path",e.startsWith(t)&&t.length<=e.length),n.group.classList.toggle("current",t===e&&e!=="");for(const[t,n]of ye)n.classList.toggle("lit",e.startsWith(t));if(e===""&&O){const t=x.get("");t&&je(t,0)}Je(e)}function je(e,t){O&&(O.style.transitionDuration=`${Math.round(t)}ms`,O.style.transform=`translate(${e.x}px, ${e.y}px)`,O.classList.toggle("moving",t>0))}function He(e,t){E(e);const n=x.get(e);n&&(je(n,t),At(n.group))}function At(e){var t;e.classList.remove("pop"),(t=e.getBBox)==null||t.call(e),e.classList.add("pop")}function Ke(){E(p)}function Ue(e){var n;for(const[s,o]of x)o.group.classList.toggle("preview",s===e);const t=e!==null&&!oe(e);(n=x.get(p))==null||n.group.classList.toggle("preview-none",t),e===null&&x.forEach(s=>s.group.classList.remove("preview-none"))}function ae(e){var n,s;const t=x.get(e);t&&(t.group.classList.remove("reveal"),(s=(n=t.group).getBBox)==null||s.call(n),t.group.classList.add("reveal"),window.setTimeout(()=>t.group.classList.remove("reveal"),1400))}function Ye(e){var n,s;const t=x.get(e)??x.get("");t&&(t.group.classList.remove("shake"),(s=(n=t.group).getBBox)==null||s.call(n),t.group.classList.add("shake"),window.setTimeout(()=>t.group.classList.remove("shake"),500))}function St(e){const t=x.get(e);if(!t)return;const n=["#ff6b5a","#1fb5a8","#ffc83d","#8b6cff"],s=m("g",{class:"burst",transform:`translate(${t.x} ${t.y})`},r.tree);for(let o=0;o<14;o+=1){const a=o/14*Math.PI*2,i=t.r*(1.8+Math.random()*1.4),d=m("circle",{r:Math.max(2,t.r*.16),fill:n[o%n.length]},s);d.style.setProperty("--dx",`${Math.cos(a)*i}px`),d.style.setProperty("--dy",`${Math.sin(a)*i}px`)}window.setTimeout(()=>s.remove(),900)}function Je(e=p){if(!r.stage.classList.contains("is-compact"))return;const n=U(e)??"?";r.compact.innerHTML="";const s=document.createElement("div");s.className="compact-letter",s.textContent=e===""?"":n;const o=document.createElement("div");o.className="compact-code",o.textContent=e===""?"tap ● hold ▬":[...e].map(a=>a==="-"?"▬":"●").join(" "),r.compact.append(s,o)}let D=0,K=0,Le=0,Ze=0,Xe=0,ie=!1,se=null;function R(){return qe(l.wpm)}function Ct(){if(!y||!P||!l.sound)return;const e=y.currentTime,t=y.createOscillator(),n=y.createGain();t.frequency.value=We,n.gain.setValueAtTime(0,e),n.gain.linearRampToValueAtTime(1,e+.005),t.connect(n).connect(P),t.start(e),se={osc:t,gain:n}}function It(){if(!y||!se)return;const e=y.currentTime,{osc:t,gain:n}=se;n.gain.cancelScheduledValues(e),n.gain.setValueAtTime(n.gain.value,e),n.gain.linearRampToValueAtTime(0,e+.005),t.stop(e+.02),se=null}function Y(){window.clearTimeout(Ze),window.clearTimeout(Xe),w==null||w.remove(),w=null}function Nt(e){w==null||w.remove(),w=null;const t=x.get(p);if(!t||p==="")return;const n=t.r*1.32;w=m("circle",{r:n,class:"commit-ring",transform:"rotate(-90)"},t.group);const s=2*Math.PI*n;w.style.strokeDasharray=`${s}`,w.style.setProperty("--circ",`${s}`),w.style.animationDuration=`${e}ms`}function et(){if(D)return;_(),M(),E(p),Y();const e=performance.now();if(K){const t=e-K,n=xt(t,R());n!=="word"||t<xe("word")*2*R()?ce(n,t):ce("pause",t)}D=e,Ct(),W("house",!0),r.key.classList.add("down"),r.meterFill.classList.remove("fade"),Le=requestAnimationFrame(tt)}function tt(){if(!D)return;const e=R(),t=performance.now()-D,n=t>=ue*e;r.key.classList.toggle("is-dah",n),r.meterFill.style.width=`${Math.min(1,t/(4*e))*100}%`,Ue(ie?null:p+(n?"-":".")),Q(t),Le=requestAnimationFrame(tt)}function J(){if(!D)return;const e=performance.now(),t=e-D;D=0,cancelAnimationFrame(Le),It(),W("house",!1),r.key.classList.remove("down","is-dah"),r.meterFill.classList.add("fade"),Ue(null);const n=R(),s=vt(t,n);if(!s){Q();return}if(K=e,ce(s,t),Ze=window.setTimeout(nt,ge*n),Xe=window.setTimeout(Ot,ze*n),ie)return;const o=p+s;if(!oe(o)){ie=!0,Ye(p),Fe(),c?(p="",$e(null,o)):(C(`${Ee(o)} is not a letter.`,"warn"),p="",window.setTimeout(()=>E(p),260));return}p=o,He(p,Math.min(t,180)),c||C(""),Nt(ge*n)}function nt(){if(w==null||w.remove(),w=null,ie=!1,p==="")return;const e=p,t=U(e);if(p="",ce("char",0,t??"?"),c){$e(t,e);return}t&&(ae(e),st(t),window.setTimeout(()=>{p===""&&E("")},350))}function Ot(){c||l.tape===""||l.tape.endsWith(" ")||st(" ")}function st(e){l.tape=(l.tape+e).slice(-Be),Z(!0),F()}function rt(){if(M(),p){Y(),p="",K=0,E(p);return}l.tape!==""&&(l.tape=l.tape.slice(0,-1),Z(!1),F())}function Ee(e){return[...e].map(t=>t==="-"?"▬":"●").join(" ")}const Oe=80,B=[],G=[];function ce(e,t,n){const o=e!=="pause"&&e!=="char"?kt(t,R(),e):null;B.push({kind:e,ms:t,score:o,char:n}),B.length>Oe&&B.splice(0,B.length-Oe),o!==null&&(G.push(o),G.length>20&&G.shift()),Q()}function Q(e=0){const t=r.strip.clientWidth,n=r.strip.clientHeight;if(t===0||n===0)return;r.strip.setAttribute("viewBox",`0 0 ${t} ${n}`),r.strip.replaceChildren();const s=R(),o=Math.max(3,Math.min(12,t/52)),a=Math.min(14,n*.3),i=n-a-Math.max(4,n*.15),d=Math.max(8,Math.min(12,i-4));let f=t-8;if(e>0){const b=e/s*o,g=e>=ue*s;m("rect",{x:f-b,y:i,width:b,height:a,rx:a/2,class:`strip-mark live ${g?"dah":"dit"}`},r.strip),f-=b}for(let b=B.length-1;b>=0&&f>0;b-=1){const g=B[b];if(g.kind==="."||g.kind==="-"){const u=g.ms/s*o,v=xe(g.kind)*o,X=g.kind==="-"?"dah":"dit";m("rect",{x:f-v,y:i-3,width:v,height:a+6,rx:(a+6)/2,class:`strip-ideal ${X}`},r.strip),m("rect",{x:f-u,y:i,width:u,height:a,rx:a/2,class:`strip-mark ${X} ${ot(g.score)}`},r.strip),f-=Math.max(u,v)}else if(g.kind==="char"){const u=m("text",{x:f+1.5*o,y:i-4,class:"strip-char","text-anchor":"middle","font-size":d},r.strip);u.textContent=g.char??""}else if(g.kind==="pause")f-=4*o,m("line",{x1:f+2*o,y1:i-4,x2:f+2*o,y2:i+a+4,class:"strip-pause"},r.strip);else{const u=Math.min(g.ms/s,9)*o;g.kind==="word"&&m("line",{x1:f-u/2,y1:i-4,x2:f-u/2,y2:i+a+4,class:"strip-word"},r.strip),f-=u}}Pt()}function ot(e){return e===null?"":e>=.75?"good":e>=.45?"fair":"poor"}function Pt(){if(G.length<3){r.rhythm.textContent="rhythm",r.rhythm.className="rhythm";return}const e=G.reduce((t,n)=>t+n,0)/G.length;r.rhythm.textContent=`rhythm ${Math.round(e*100)}%`,r.rhythm.className=`rhythm ${ot(e)}`}function at(e){_(),Y(),p="",K=0;const t=le(e)??"";if(c){$e(e,t);return}C(`${e}  ${Ee(t)}`,"info"),ae(t),de(e)}function Z(e){r.tapeText.replaceChildren();const t=[...l.tape];t.forEach((s,o)=>{const a=document.createElement("span");a.className=s===" "?"tape-char tape-space":"tape-char",a.textContent=s===" "?" ":s,e&&o===t.length-1&&a.classList.add("pop"),r.tapeText.append(a)});const n=document.createElement("span");if(n.className="tape-caret",r.tapeText.append(n),t.length===0){const s=document.createElement("span");s.className="tape-hint",s.textContent="tap a letter, or hold the key",r.tapeText.append(s)}r.tapeText.scrollLeft=r.tapeText.scrollWidth,r.playTape.disabled=l.tape.trim()==="",r.backspace.disabled=l.tape==="",r.clearTape.disabled=l.tape===""}function Dt(){if(r.playTape.classList.contains("active")){M();return}const e=l.tape,t=[...r.tapeText.querySelectorAll(".tape-char")];de(e,n=>{var s;t.forEach((o,a)=>o.classList.toggle("playing",a===n)),(s=t[n])==null||s.scrollIntoView({block:"nearest",inline:"nearest"})},()=>{t.forEach(n=>n.classList.remove("playing")),r.playTape.classList.remove("active")},!0,!1,"house"),r.playTape.classList.add("active")}const Pe=Object.keys(ve);function Rt(){const e=c?c.streak:0;return`${(c==null?void 0:c.mode)==="light"?"What did the boat flash?":"Which letter was that?"} Tap it or key it.  ★ ${e}  best ${l.best}`}function be(){if(!c)return;let e=c.target;for(;e===c.target;)e=Pe[Math.floor(Math.random()*Pe.length)];c.target=e,C(Rt(),"quiz"),it()}function it(){c&&de(c.target,void 0,void 0,!1,c.mode==="light")}function _t(){it()}function $e(e,t){if(!c)return;M();const n=c.target,s=le(n)??"";if(e===n){c.streak+=1,c.streak>l.best&&(l.best=c.streak,F()),ae(s),St(s),E(s),$t(),C(`Yes, ${n}!  ★ ${c.streak}  best ${l.best}`,"ok"),window.setTimeout(be,1100);return}c.streak=0,Ye(t),Fe();const o=e?`That was ${e}.`:"No letter there.";C(`${o} It was ${n}: ${Ee(s)}`,"warn"),window.setTimeout(()=>{c&&(ae(s),de(n,void 0,()=>window.setTimeout(be,500)))},600)}function H(e="sound"){_(),M(),p="",Y(),(c==null?void 0:c.mode)===e?(c=null,C("")):(c={target:"",streak:0,mode:e},be());for(const[t,n]of[[r.quiz,"sound"],[r.lightQuiz,"light"]]){const s=(c==null?void 0:c.mode)===n;t.setAttribute("aria-pressed",String(s)),t.classList.toggle("active",s)}r.app.classList.toggle("quiz-mode",!!c),r.app.classList.toggle("light-quiz",(c==null?void 0:c.mode)==="light")}let De=0;function C(e,t="info"){if(window.clearTimeout(De),r.banner.className=`banner banner-${t}${e?" show":""}`,r.banner.replaceChildren(),!e)return;const n=document.createElement("span");if(n.textContent=e,r.banner.append(n),t==="quiz"){const s=document.createElement("button");s.type="button",s.className="banner-replay",s.textContent="↻ again",s.addEventListener("click",_t),r.banner.append(s)}(t==="info"||t==="warn"&&!c)&&(De=window.setTimeout(()=>r.banner.classList.remove("show"),2600))}function pe(){r.speed.textContent=String(l.wpm),r.speed.title=`Speed: ${l.wpm} words per minute`,r.speed.setAttribute("aria-label",`Speed ${l.wpm} words per minute`),r.sound.textContent=l.sound?"🔊":"🔇",r.sound.setAttribute("aria-pressed",String(l.sound)),r.sound.setAttribute("aria-label",l.sound?"Sound on":"Sound off"),Ke()}r.key.addEventListener("pointerdown",e=>{e.button===0&&(e.preventDefault(),r.key.setPointerCapture(e.pointerId),et())});r.key.addEventListener("pointerup",J);r.key.addEventListener("pointercancel",J);r.key.addEventListener("lostpointercapture",J);r.key.addEventListener("contextmenu",e=>e.preventDefault());r.backspace.addEventListener("click",rt);r.playTape.addEventListener("click",()=>{_(),Dt()});r.clearTape.addEventListener("click",()=>{M(),l.tape="",Z(!1),F()});r.quiz.addEventListener("click",()=>H("sound"));r.lightQuiz.addEventListener("click",()=>H("light"));r.speed.addEventListener("click",()=>{l.wpm=ne[(ne.indexOf(l.wpm)+1)%ne.length],pe(),Q(),F();const e=Math.round(R());C(`${l.wpm} wpm: dot ${e} ms, dash from ${e*ue} ms`,"info")});r.sound.addEventListener("click",()=>{l.sound=!l.sound,l.sound||M(),_(),pe(),F()});window.addEventListener("keydown",e=>{if(e.ctrlKey||e.metaKey||e.altKey)return;const t=e.key;if(t===" ")e.preventDefault(),e.repeat||et();else if(t==="Backspace")e.preventDefault(),rt();else if(t==="Escape")c?H(c.mode):M();else if(/^[a-zA-Z]$/.test(t)&&!e.repeat){const n=t.toUpperCase();n==="Q"&&e.shiftKey?H("sound"):n==="L"&&e.shiftKey?r.sea.offsetParent!==null&&H("light"):at(n)}});window.addEventListener("keyup",e=>{e.key===" "&&(e.preventDefault(),J())});document.addEventListener("click",e=>{var t;e.detail>0&&e.target instanceof Element&&((t=e.target.closest("button"))==null||t.blur())});document.addEventListener("touchend",_,{passive:!0});window.addEventListener("blur",()=>{J(),Y(),p&&nt()});new ResizeObserver(()=>{Qe(),Q()}).observe(r.stage);Z(!1);pe();Qe();Q();Et().then(()=>{Z(!1),pe()});
</script>
    <style>:root{color-scheme:light;--paper: #fff6e4;--paper-line: #f1e2c4;--ink: #2b2340;--ink-soft: #7a6f8f;--dit: #ff6b5a;--dit-deep: #d9483a;--dah: #1fb5a8;--dah-deep: #138a80;--sun: #ffc83d;--sun-deep: #f29f05;--card: #ffffff;--grape: #8b6cff;--font: ui-rounded, "SF Pro Rounded", "Nunito", "Varela Round", "Trebuchet MS", system-ui, sans-serif;--key-h: clamp(44px, 16vh, 84px)}*{box-sizing:border-box}html,body,#app{height:100%;margin:0}body{background:var(--paper);background-image:repeating-linear-gradient(0deg,transparent 0 27px,var(--paper-line) 27px 28px);color:var(--ink);font-family:var(--font);overflow:hidden;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}button{font:inherit;color:inherit;cursor:pointer;touch-action:manipulation}button:focus-visible,.node:focus-visible{outline:3px solid var(--grape);outline-offset:2px}.app{display:flex;flex-direction:column;gap:clamp(4px,1.4vh,10px);padding:clamp(4px,1.4vmin,12px);padding-bottom:max(clamp(4px,1.4vmin,12px),env(safe-area-inset-bottom))}.tape{display:flex;align-items:center;gap:6px;flex:none}.tape-paper{flex:1;min-width:0;background:var(--card);border:2px solid var(--ink);border-radius:12px;box-shadow:0 3px 0 var(--ink);padding:0 10px;height:clamp(32px,9vh,52px);display:flex;align-items:center}.tape-text{display:flex;align-items:center;width:100%;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;white-space:pre;font-size:clamp(16px,5vh,30px);font-weight:800;letter-spacing:.08em}.tape-text::-webkit-scrollbar{display:none}.tape-char{display:inline-block;border-radius:6px;padding:0 1px;transition:background .12s}.tape-char.pop{animation:tape-pop .32s cubic-bezier(.3,1.6,.5,1)}.tape-char.playing{background:var(--sun)}.tape-caret{display:inline-block;width:3px;height:1em;margin-left:2px;background:var(--dit);border-radius:2px;animation:blink 1s steps(1) infinite;flex:none}.tape-hint{margin-left:8px;font-size:clamp(11px,2.4vh,15px);font-weight:600;letter-spacing:0;color:var(--ink-soft)}.tape-actions{display:flex;gap:4px;flex:none}.chip{min-width:40px;min-height:40px;padding:0 8px;border:2px solid var(--ink);border-radius:12px;background:var(--card);box-shadow:0 3px 0 var(--ink);font-size:18px;line-height:1;transition:transform 80ms,box-shadow 80ms,background .12s}.chip:active:not(:disabled){transform:translateY(2px);box-shadow:0 1px 0 var(--ink)}.chip:disabled{opacity:.35;cursor:default}.chip.active{background:var(--sun)}.chip-text{font-weight:800;font-size:15px}.chip-text:after{content:"wpm";display:block;font-size:9px;font-weight:700;color:var(--ink-soft)}.sea{--lamp: #ffe46b;position:relative;flex:none;display:flex;justify-content:space-between;align-items:stretch;height:clamp(46px,12vh,100px);border:2px solid var(--ink);border-radius:12px;overflow:hidden;background:linear-gradient(180deg,#27306a,#5a4f8f 34%,#f0a17c 60%,#2f6fa3 60%,#1f4e7c)}.sea svg{height:100%;width:auto;flex:none;overflow:visible}.waves{position:absolute;left:0;right:0;bottom:0;height:18%;z-index:2;pointer-events:none;background:radial-gradient(circle at 12px -7px,transparent 12px,rgba(255,255,255,.7) 12.5px 14.5px,#23598a 15px) 0 0 / 24px 100% repeat-x;animation:waves 4s linear infinite}.cliff{fill:#74c365;stroke:var(--ink);stroke-width:2}.wall,.cabin{fill:#fffdf6;stroke:var(--ink);stroke-width:1.6}.roof{fill:var(--dit);stroke:var(--ink);stroke-width:1.6;stroke-linejoin:round}.window{fill:#7cc8f0;stroke:var(--ink);stroke-width:1}.balcony{fill:#c98a4b;stroke:var(--ink);stroke-width:1.2}.rail{stroke-width:1}.door{fill:var(--sun-deep);stroke:var(--ink);stroke-width:1}.post,.mast,.rig{fill:none;stroke:var(--ink);stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}.rig{stroke-width:.8}.hull{fill:#2f4f9e;stroke:var(--ink);stroke-width:1.8;stroke-linejoin:round}.lamp{fill:#5d5872;stroke:var(--ink);stroke-width:1.4}.glow,.beam{fill:var(--lamp);opacity:0}.lit .lamp{fill:var(--lamp)}.lit .glow{opacity:.8}.lit .beam{opacity:.45}.boat-body{transform-box:view-box;transform-origin:60px 70px;animation:bob 3.2s ease-in-out infinite}.light-quiz .sea{box-shadow:0 0 0 3px var(--sun)}.stage{position:relative;flex:1;min-height:0}.tree{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;overflow:visible}.edge-under{stroke:var(--paper);stroke-width:9;stroke-linecap:round}.edge-line{stroke-width:4;stroke-linecap:round;opacity:.4;transition:opacity .15s,stroke-width .15s}.edge-dit .edge-line{stroke:var(--dit);stroke-dasharray:.1 9;stroke-width:6}.edge-dah .edge-line{stroke:var(--dah);stroke-dasharray:14 7}.edge.lit .edge-line{opacity:1;stroke-width:7}.edge-dit.lit .edge-line{stroke-width:9}.node-hit{fill:transparent}.node-body{transform-box:fill-box;transform-origin:center;transition:transform .16s}.node-disc{fill:var(--card);stroke:var(--ink);stroke-width:2.5;transition:fill .15s}.node.has-letter{cursor:pointer}.node.has-letter:hover .node-body{transform:scale(1.08)}.node-label{fill:var(--ink);font-weight:800;pointer-events:none;transition:opacity .15s}.root .node-disc{fill:var(--ink)}.root-dot{fill:var(--sun)}.node.on-path .node-disc{fill:#fff0bf}.node.current .node-disc{fill:var(--sun);stroke-width:3.5}.root.on-path .node-disc{fill:var(--ink)}.node.preview .node-disc{stroke:var(--grape);stroke-width:4;stroke-dasharray:4 3}.node.preview-none .node-disc{stroke:var(--dit-deep);stroke-width:4}.node.pop .node-body{animation:node-pop .28s cubic-bezier(.3,1.8,.5,1)}.node.reveal .node-body{animation:node-pop .38s cubic-bezier(.3,1.8,.5,1)}.node.shake .node-body{animation:shake .42s}.legend{font-weight:800;pointer-events:none}.legend-dit{fill:var(--dit-deep)}.legend-dah{fill:var(--dah-deep)}.spark{fill:var(--sun);stroke:var(--ink);stroke-width:2;pointer-events:none;transition-property:transform;transition-timing-function:linear;opacity:0}.spark.moving{opacity:1}.commit-ring{fill:none;stroke:var(--grape);stroke-width:3.5;stroke-linecap:round;pointer-events:none;animation-name:drain;animation-timing-function:linear;animation-fill-mode:forwards}.burst circle{animation:burst .8s cubic-bezier(.2,.8,.4,1) forwards}.compact,.stage.is-compact .tree{display:none}.stage.is-compact .compact{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px}.compact-letter{font-size:clamp(22px,18vh,56px);font-weight:900;line-height:1;color:var(--ink)}.compact-code{font-size:13px;font-weight:800;color:var(--ink-soft)}.banner{flex:none;align-self:center;max-width:100%;height:34px;display:flex;align-items:center;gap:8px;padding:0 12px;border:2px solid transparent;border-radius:999px;font-size:clamp(12px,2.4vh,16px);font-weight:700;white-space:nowrap;opacity:0;transform:translateY(4px);pointer-events:none;transition:opacity .16s,transform .16s}.banner>span{overflow:hidden;text-overflow:ellipsis}.banner.show{opacity:1;transform:none;pointer-events:auto;border-color:var(--ink);box-shadow:0 3px 0 var(--ink)}.banner-info{background:var(--card)}.banner-ok{background:#d9fbe9}.banner-warn{background:#ffe1dc}.banner-quiz{background:#ece6ff}.banner-replay{flex:none;border:2px solid var(--ink);border-radius:999px;background:var(--sun);padding:0 10px;height:26px;font-weight:800}.keys{display:flex;align-items:stretch;gap:clamp(4px,1.5vw,12px);flex:none}.key{flex:1;min-height:44px;height:var(--key-h);border:3px solid var(--ink);border-radius:18px;box-shadow:0 5px 0 var(--ink);background:var(--ink);color:#fff;display:flex;flex-direction:column;align-items:stretch;justify-content:center;gap:clamp(3px,1vh,8px);padding:0 clamp(10px,3vw,22px);touch-action:none;-webkit-touch-callout:none;transition:transform 50ms,box-shadow 50ms,background 80ms}.key.down{transform:translateY(3px);box-shadow:0 2px 0 var(--ink);background:#3d3358}.key-label{display:flex;font-size:clamp(13px,3.4vh,20px);font-weight:900;letter-spacing:.06em;text-transform:uppercase}.key-label>span{flex:1;text-align:center;opacity:.55;transition:opacity 80ms,color 80ms}.key.down:not(.is-dah) .key-dit{opacity:1;color:var(--dit)}.key.down.is-dah .key-dah{opacity:1;color:var(--dah)}.meter{position:relative;height:clamp(8px,2.4vh,14px);border-radius:999px;background:linear-gradient(90deg,#ff6b5a40 0,#ff6b5a40 50%,#1fb5a840 50%,#1fb5a840);overflow:hidden}.meter-fill{position:absolute;inset:0 auto 0 0;width:0;background:var(--dit);border-radius:999px}.key.is-dah .meter-fill{background:var(--dah)}.meter-fill.fade{transition:opacity .9s .3s;opacity:.35}.meter-split{position:absolute;left:50%;top:0;bottom:0;width:3px;margin-left:-1.5px;background:#fff}.meter-ideal{position:absolute;top:50%;width:6px;height:6px;margin:-3px 0 0 -3px;border-radius:50%;background:#fff;opacity:.8}.ideal-dit{left:25%}.ideal-dah{left:75%}.timing{flex:none;display:flex;align-items:center;gap:8px;height:clamp(30px,8vh,48px)}.rhythm{flex:none;min-width:92px;padding:4px 10px;border:2px solid var(--ink);border-radius:999px;background:var(--card);font-size:13px;font-weight:800;text-align:center;color:var(--ink-soft)}.rhythm.good{background:#d9fbe9;color:var(--ink)}.rhythm.fair{background:#fff0bf;color:var(--ink)}.rhythm.poor{background:#ffe1dc;color:var(--ink)}.strip{flex:1;min-width:0;height:100%;background:var(--card);border:2px solid var(--ink);border-radius:12px}.strip-ideal{fill:none;stroke-width:1.5;stroke-dasharray:3 2}.strip-ideal.dit{stroke:var(--dit-deep)}.strip-ideal.dah{stroke:var(--dah-deep)}.strip-mark.dit{fill:var(--dit)}.strip-mark.dah{fill:var(--dah)}.strip-mark.fair{opacity:.75}.strip-mark.poor{opacity:.45}.strip-char{fill:var(--ink);font-weight:900}.strip-word,.strip-pause{stroke:var(--ink-soft);stroke-width:2;stroke-linecap:round}.strip-pause{stroke-dasharray:2 3}.tools{display:grid;grid-template-columns:repeat(4,auto);gap:4px;align-content:center}@media(max-width:520px){.keys{flex-wrap:wrap}.tools{order:-1;width:100%;grid-template-columns:repeat(4,1fr)}}@media(max-height:260px){.banner{height:26px}.tape-hint,.key-label,.timing,.sea,#lightQuizToggle{display:none}.chip{min-height:32px;min-width:32px;font-size:15px}.chip-text:after{display:none}}@media(max-height:260px)and (max-width:520px){.tools{display:none}}@keyframes waves{to{background-position:24px 0}}@keyframes bob{0%,to{transform:translateY(0) rotate(-1.5deg)}50%{transform:translateY(2px) rotate(1.5deg)}}@keyframes blink{50%{opacity:0}}@keyframes tape-pop{0%{transform:translateY(-14px) scale(1.6);color:var(--dit)}to{transform:none}}@keyframes node-pop{40%{transform:scale(1.28)}to{transform:scale(1)}}@keyframes shake{20%,60%{transform:translate(-5px) rotate(-6deg)}40%,80%{transform:translate(5px) rotate(6deg)}}@keyframes drain{0%{stroke-dashoffset:0}to{stroke-dashoffset:var(--circ)}}@keyframes burst{0%{transform:translate(0) scale(1);opacity:1}to{transform:translate(var(--dx),var(--dy)) scale(.3);opacity:0}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:1ms!important;animation-iteration-count:1!important}.spark{transition-duration:0ms!important}.commit-ring{display:none}}
</style>
    <meta name="napplet-type" content="morse-tree">
    <meta name="napplet-config-schema" content="{&quot;$schema&quot;:&quot;http://json-schema.org/draft-07/schema#&quot;,&quot;$version&quot;:1,&quot;type&quot;:&quot;object&quot;,&quot;additionalProperties&quot;:false,&quot;properties&quot;:{}}">
  </head>
  <body>
    <main id="app" class="app">
      <section class="tape" aria-label="Written text">
        <div class="tape-paper">
          <div id="tapeText" class="tape-text" aria-live="polite"></div>
        </div>
        <div class="tape-actions">
          <button id="playTape" type="button" class="chip" title="Play the written text" aria-label="Play the written text">▶</button>
          <button id="backspace" type="button" class="chip" title="Delete last letter (Backspace)" aria-label="Delete last letter">⌫</button>
          <button id="clearTape" type="button" class="chip" title="Clear the tape" aria-label="Clear the tape">✕</button>
        </div>
      </section>

      <section id="sea" class="sea" aria-label="A house on the cliff and a boat signal each other with Morse light">
        <svg class="house" viewBox="0 0 120 80" role="img" aria-label="The house: the lamp on its balcony flashes when you key">
          <title>The house</title>
          <polygon class="beam" points="64,16 190,1 190,33" />
          <path class="cliff" d="M-4 84 L-4 34 Q22 26 50 31 Q74 35 86 50 Q96 64 104 84 Z" />
          <rect class="wall" x="16" y="17" width="34" height="15" rx="1.5" />
          <polygon class="roof" points="11,18 33,5 55,18" />
          <rect class="window" x="22" y="21" width="7" height="6" rx="1" />
          <rect class="door" x="37" y="22" width="7" height="10" rx="1" />
          <rect class="balcony" x="50" y="24" width="15" height="2.4" rx="1" />
          <polyline class="post" points="51,24 51,20 64,20 64,24" />
          <line class="post rail" x1="55.5" y1="20" x2="55.5" y2="24" />
          <line class="post rail" x1="60" y1="20" x2="60" y2="24" />
          <circle class="glow" cx="64" cy="16" r="13" />
          <circle class="lamp" cx="64" cy="16" r="4.2" />
        </svg>
        <span class="waves"></span>
        <svg class="boat" viewBox="0 0 120 80" role="img" aria-label="The boat: its lamp flashes the Morse you receive">
          <title>The boat</title>
          <g class="boat-body">
            <polygon class="beam" points="70,25 -70,8 -70,44" />
            <line class="mast" x1="40" y1="52" x2="40" y2="10" />
            <polyline class="rig" points="12,50 40,12 104,50" />
            <rect class="cabin" x="56" y="33" width="30" height="19" rx="2" />
            <rect class="window" x="61" y="38" width="7" height="6" rx="1" />
            <rect class="window" x="73" y="38" width="7" height="6" rx="1" />
            <path class="hull" d="M6 51 L114 51 L101 70 L19 70 Z" />
            <line class="post" x1="70" y1="33" x2="70" y2="29" />
            <circle class="glow" cx="70" cy="25" r="13" />
            <circle class="lamp" cx="70" cy="25" r="4.2" />
          </g>
        </svg>
      </section>

      <section id="stage" class="stage">
        <svg id="tree" class="tree" role="group" aria-label="Morse code tree: dot goes left, dash goes right"></svg>
        <div id="compact" class="compact" aria-hidden="true"></div>
      </section>

      <div id="banner" class="banner" aria-live="polite"></div>

      <section class="timing" aria-label="Your timing">
        <span id="rhythm" class="rhythm">rhythm</span>
        <svg id="strip" class="strip" aria-hidden="true"></svg>
      </section>

      <section class="keys" aria-label="Morse key">
        <div class="tools" role="toolbar" aria-label="Options">
          <button id="quizToggle" type="button" class="chip" title="Listening quiz (Shift+Q)" aria-pressed="false">🎧</button>
          <button id="lightQuizToggle" type="button" class="chip" title="Light quiz: read the lamp on the boat (Shift+L)" aria-pressed="false">🚢</button>
          <button id="speedToggle" type="button" class="chip chip-text" title="Speed in words per minute">8</button>
          <button id="soundToggle" type="button" class="chip" title="Sound on/off" aria-pressed="true">🔊</button>
        </div>
        <button id="morseKey" type="button" class="key" aria-label="Morse key: tap for dot, hold for dash (Space)">
          <span class="key-label"><span class="key-dit">tap ●</span><span class="key-dah">hold ▬</span></span>
          <span class="meter" aria-hidden="true">
            <span id="meterFill" class="meter-fill"></span>
            <span class="meter-ideal ideal-dit"></span>
            <span class="meter-split"></span>
            <span class="meter-ideal ideal-dah"></span>
          </span>
        </button>
      </section>
    </main>
  </body>
</html>