haraberget commited on
Commit
48b8b15
·
verified ·
1 Parent(s): 6e6f44b

Upload music-beholder.js

Browse files
Files changed (1) hide show
  1. music-beholder.js +182 -0
music-beholder.js ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (() => {
2
+ const HOST_ID = 'onehit-music-beholder-root';
3
+ const old = document.getElementById(HOST_ID);
4
+ if (old) { old.remove(); return; }
5
+
6
+ const scriptURL = document.currentScript?.src || 'https://music-beholder.vercel.app/music-beholder.js';
7
+ const INDEX_URL = new URL('music-index.json', scriptURL).href;
8
+ const AUDIO_ORIGIN = 'https://1hit.no';
9
+ const HISTORY_KEY = 'onehit-music-beholder-history-v1';
10
+ const BAG_KEY = 'onehit-music-beholder-bag-v1';
11
+ const MAX_HISTORY = 80;
12
+ const host = document.createElement('div');
13
+ host.id = HOST_ID;
14
+ Object.assign(host.style, { position:'fixed', inset:'0', zIndex:'2147483647', pointerEvents:'none', overflow:'hidden' });
15
+ (document.documentElement || document.body).appendChild(host);
16
+ const shadow = host.attachShadow({mode:'open'});
17
+
18
+ const style = document.createElement('style');
19
+ style.textContent = `
20
+ :host{all:initial;color-scheme:dark}
21
+ *{box-sizing:border-box}
22
+ .beholder{--skin:#8b9c55;--dark:#26301b;--eye:#f4e7c5;position:fixed;right:clamp(18px,4vw,58px);bottom:24px;width:220px;height:210px;pointer-events:auto;cursor:grab;transform-origin:50% 65%;animation:hover 4.8s ease-in-out infinite;filter:drop-shadow(0 13px 12px #0007);user-select:none;touch-action:none}
23
+ .beholder:active{cursor:grabbing}
24
+ .body{position:absolute;left:36px;top:76px;width:150px;height:116px;border-radius:48% 52% 46% 54%/55% 52% 48% 45%;background:radial-gradient(ellipse at 34% 25%,#c1ca7a 0 8%,transparent 35%),radial-gradient(ellipse at 65% 72%,#536538 0 5%,transparent 42%),linear-gradient(145deg,#a8b76b,var(--skin) 58%,#56673a);border:3px solid #52613a;box-shadow:inset -10px -13px 17px #26351e88,inset 8px 7px 14px #e5e9a655}
25
+ .main-eye{position:absolute;left:75px;top:27px;width:84px;height:84px;border-radius:50%;background:radial-gradient(circle at 36% 30%,white,var(--eye) 58%,#c6b994);border:5px solid #53613b;box-shadow:inset 0 0 0 2px #fff8,0 2px 8px #0006;overflow:hidden;z-index:4}
26
+ .pupil{position:absolute;left:29px;top:24px;width:28px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#5d6e75,#10191d 70%);transition:transform .12s ease-out}
27
+ .pupil:after{content:"";position:absolute;width:8px;height:8px;left:5px;top:5px;border-radius:50%;background:#fff}
28
+ .lid{position:absolute;inset:-2px 0 auto;height:0;z-index:5;background:linear-gradient(#81934d,#64773d);border-radius:50%;animation:blink 5.7s infinite}
29
+ .stalk{position:absolute;width:8px;height:66px;border-radius:100% 100% 35% 35%;background:linear-gradient(90deg,#53673a,#b3bf70 48%,#687b42);transform-origin:50% 100%;z-index:2;border:1px solid #52613a;animation:sway var(--dur,3s) ease-in-out infinite alternate}
30
+ .stalk:after{content:"";position:absolute;width:27px;height:27px;left:50%;top:-17px;transform:translateX(-50%);border-radius:50%;background:radial-gradient(circle at 35% 30%,#fff,#e9dfbd 55%,#a79d7b);border:3px solid #53613b;box-shadow:0 2px 4px #0005}
31
+ .tiny-pupil{position:absolute;z-index:3;width:8px;height:11px;left:50%;top:-9px;transform:translateX(-50%);border-radius:50%;background:#20292a}
32
+ .s1{left:49px;top:48px;--dur:2.7s;transform:rotate(-43deg)}.s2{left:75px;top:34px;--dur:3.2s;transform:rotate(-20deg)}.s3{left:151px;top:36px;--dur:2.4s;transform:rotate(22deg)}.s4{left:177px;top:57px;--dur:3.5s;transform:rotate(47deg)}.s5{left:35px;top:94px;--dur:2.9s;transform:rotate(-65deg)}
33
+ .mouth{position:absolute;z-index:6;left:83px;top:151px;width:64px;height:25px;border-radius:10px 10px 45px 45px;background:#321d20;border:3px solid #45542f;overflow:hidden;transform:rotate(-3deg)}
34
+ .teeth{position:absolute;left:6px;top:0;width:48px;height:10px;background:repeating-linear-gradient(90deg,#fff0d5 0 8px,#b7ad8e 8px 10px);clip-path:polygon(0 0,100% 0,94% 100%,82% 60%,70% 100%,57% 60%,44% 100%,30% 60%,17% 100%,7% 60%)}
35
+ .cheek{position:absolute;top:140px;width:15px;height:9px;border-radius:50%;background:#c57d61;opacity:.65}.c1{left:60px}.c2{left:151px}
36
+ .spark{position:absolute;right:15px;top:83px;color:#e7e6ad;font:bold 20px sans-serif;opacity:0}.beholder.excited .spark{animation:sparkle .65s ease-out}.beholder.excited .body{filter:brightness(1.2) saturate(1.25)}.beholder.excited{animation:bounce .55s ease-out 2}.beholder.playing .mouth{animation:chew .24s ease-in-out infinite alternate}
37
+ .hint{position:absolute;bottom:-2px;left:35px;width:150px;text-align:center;color:#f4f0d8;font:11px/1.2 system-ui,sans-serif;opacity:0;text-shadow:0 1px 3px #000;transition:opacity .2s}.beholder:hover .hint{opacity:.9}
38
+ .panel{position:fixed;right:18px;bottom:244px;width:min(330px,calc(100vw - 28px));max-height:min(470px,calc(100vh - 270px));overflow:hidden;pointer-events:auto;background:linear-gradient(150deg,#1b2119f5,#10151bf5);color:#f4f0df;border:1px solid #7c8d53;border-radius:17px;box-shadow:0 15px 50px #0009;font:13px/1.4 system-ui,sans-serif;backdrop-filter:blur(16px);display:flex;flex-direction:column}
39
+ .panel.hidden{display:none}.panel-head{padding:12px 14px 9px;border-bottom:1px solid #ffffff20;display:flex;align-items:center;justify-content:space-between;gap:8px}.brand{font-weight:900;letter-spacing:.06em;font-size:12px;color:#d8e6a3}.status{font-size:10px;color:#aebc8e}.close{border:0;background:transparent;color:#ddd;font-size:20px;cursor:pointer;padding:0 4px}
40
+ .now{padding:13px 14px 10px}.now-title{font-weight:800;font-size:15px;line-height:1.25;overflow-wrap:anywhere}.now-meta{color:#b4bea1;font-size:11px;margin-top:5px}.controls{display:flex;align-items:center;gap:7px;margin-top:10px}.btn{border:1px solid #66784b;background:#252f20;color:#f5f2df;border-radius:9px;padding:7px 10px;font:inherit;cursor:pointer}.btn.primary{background:#c4d978;color:#17200f;border-color:#d7e99b;font-weight:800}.btn:disabled{opacity:.4;cursor:wait}.vol{width:74px;accent-color:#c4d978}.hist-head{display:flex;align-items:center;justify-content:space-between;padding:8px 14px 6px;border-top:1px solid #ffffff20;color:#d9e7b1;font-weight:800;font-size:11px}.history{overflow:auto;min-height:50px;padding:0 8px 9px}.entry{display:flex;align-items:center;gap:7px;padding:7px 6px;border-radius:8px}.entry:hover{background:#ffffff0d}.entry-info{min-width:0;flex:1}.entry-title{font-size:11px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entry-meta{font-size:10px;color:#aeb99b}.entry button{font-size:10px;padding:5px 7px;white-space:nowrap}.empty{padding:15px 8px;color:#aeb99b;text-align:center;font-size:11px}.foot{padding:7px 14px 10px;color:#8f9a7b;font-size:10px;border-top:1px solid #ffffff15}
41
+ @keyframes hover{0%,100%{transform:translateY(0) rotate(-1deg)}50%{transform:translateY(-10px) rotate(1deg)}}@keyframes sway{from{rotate:-5deg}to{rotate:7deg}}@keyframes blink{0%,44%,48%,100%{height:0}46%{height:88px}}@keyframes sparkle{0%{opacity:0;transform:scale(.4) rotate(0)}35%{opacity:1;transform:scale(1.3) rotate(25deg)}100%{opacity:0;transform:scale(.6) rotate(55deg)}}@keyframes bounce{0%,100%{translate:0 0}35%{translate:0 -17px}65%{translate:0 4px}}@keyframes chew{from{height:18px}to{height:28px}}
42
+ @media(max-width:520px){.beholder{right:6px;bottom:8px;transform:scale(.82);transform-origin:bottom right}.panel{right:8px;bottom:190px;width:calc(100vw - 16px);max-height:calc(100vh - 210px)}}
43
+ @media(prefers-reduced-motion:reduce){.beholder,.stalk,.lid,.beholder.playing .mouth{animation:none!important}}
44
+ `;
45
+ shadow.appendChild(style);
46
+
47
+ const creature = document.createElement('div');
48
+ creature.className = 'beholder';
49
+ creature.setAttribute('role','button');
50
+ creature.setAttribute('aria-label','Music Beholder. Click to play a random track. Drag to move. Press Escape to dismiss.');
51
+ creature.innerHTML = `<div class="stalk s1"><i class="tiny-pupil"></i></div><div class="stalk s2"><i class="tiny-pupil"></i></div><div class="stalk s3"><i class="tiny-pupil"></i></div><div class="stalk s4"><i class="tiny-pupil"></i></div><div class="stalk s5"><i class="tiny-pupil"></i></div><div class="body"></div><div class="main-eye"><div class="pupil"></div><div class="lid"></div></div><div class="cheek c1"></div><div class="cheek c2"></div><div class="mouth"><div class="teeth"></div></div><div class="spark">✦</div><div class="hint">click · random music · drag</div>`;
52
+ shadow.appendChild(creature);
53
+
54
+ const panel = document.createElement('section');
55
+ panel.className = 'panel';
56
+ panel.innerHTML = `<div class="panel-head"><div><div class="brand">MUSIC BEHOLDER</div><div class="status" id="mb-status">Waking up…</div></div><button class="close" id="mb-close" aria-label="Close panel">×</button></div><div class="now"><div class="now-title" id="mb-title">Finding a tune…</div><div class="now-meta" id="mb-meta">Three catalogues · random discovery</div><div class="controls"><button class="btn primary" id="mb-play">▶ Play</button><button class="btn" id="mb-next">↻ Random</button><button class="btn" id="mb-download" disabled>↓ MP3</button><input class="vol" id="mb-volume" type="range" min="0" max="1" step="0.01" value="0.75" title="Volume"></div></div><div class="hist-head"><span>RECENTLY PLAYED</span><button class="btn" id="mb-clear" style="font-size:10px;padding:4px 7px">Clear</button></div><div class="history" id="mb-history"><div class="empty">Your listening history will appear here.</div></div><div class="foot">Click the creature for another random track · history is saved in this browser</div>`;
57
+ shadow.appendChild(panel);
58
+
59
+ const audio = document.createElement('audio');
60
+ audio.preload = 'none';
61
+ audio.volume = 0.75;
62
+ shadow.appendChild(audio);
63
+ const $ = s => shadow.querySelector(s);
64
+ const pupil = creature.querySelector('.pupil');
65
+ const tinyPupils = [...creature.querySelectorAll('.tiny-pupil')];
66
+ let tracks = [], current = null, history = readJSON(HISTORY_KEY, []), bag = readJSON(BAG_KEY, []);
67
+ let dragging = false, moved = false, offsetX = 0, offsetY = 0, startX = 0, startY = 0;
68
+ let loading = false, destroyed = false;
69
+
70
+ function readJSON(key, fallback) { try { const v = JSON.parse(localStorage.getItem(key) || 'null'); return v ?? fallback; } catch { return fallback; } }
71
+ function saveJSON(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch {} }
72
+ function cleanTitle(t) { return String(t?.title || 'Untitled track').trim(); }
73
+ function audioURL(t) { const p = t.audioPath || t.filename || ''; return /^https?:\/\//i.test(p) ? p : new URL(p.replace(/^\//,''), AUDIO_ORIGIN + '/').href; }
74
+ function setStatus(s) { $('#mb-status').textContent = s; }
75
+ function renderHistory() {
76
+ const box = $('#mb-history');
77
+ if (!history.length) { box.innerHTML = '<div class="empty">Nothing played yet. Click the creature to begin.</div>'; return; }
78
+ box.innerHTML = history.slice(0, MAX_HISTORY).map((h,i) => `<div class="entry"><div class="entry-info"><div class="entry-title" title="${esc(cleanTitle(h))}">${esc(cleanTitle(h))}</div><div class="entry-meta">${esc(h.catalog || '1hit')} · ${esc(h.playedAt || '')}</div></div><button class="btn" data-history="${i}">▶ Back</button></div>`).join('');
79
+ box.querySelectorAll('[data-history]').forEach(b => b.addEventListener('click', () => { const h = history[Number(b.dataset.history)]; const t = tracks.find(x => x.id === h.id); if (t) play(t); }));
80
+ }
81
+ function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
82
+ function shuffled(a) { const x = a.slice(); for (let i=x.length-1;i>0;i--) { const j=Math.floor(Math.random()*(i+1)); [x[i],x[j]]=[x[j],x[i]]; } return x; }
83
+ function refillBag() { bag = shuffled(tracks.map(t => t.id)); if (bag.length > 1 && current && bag[bag.length-1] === current.id) [bag[0],bag[bag.length-1]] = [bag[bag.length-1],bag[0]]; saveJSON(BAG_KEY,bag); }
84
+ function pickRandom() {
85
+ if (!tracks.length) return null;
86
+ const byId = new Map(tracks.map(t => [t.id,t]));
87
+ while (bag.length && !byId.has(bag[bag.length-1])) bag.pop();
88
+ if (!bag.length) refillBag();
89
+ const id = bag.pop(); saveJSON(BAG_KEY,bag);
90
+ return byId.get(id) || tracks[Math.floor(Math.random()*tracks.length)];
91
+ }
92
+ async function loadIndex() {
93
+ if (loading || tracks.length) return;
94
+ loading = true;
95
+ try {
96
+ const r = await fetch(INDEX_URL, {cache:'no-cache'});
97
+ if (!r.ok) throw new Error('Index HTTP ' + r.status);
98
+ const data = await r.json();
99
+ const list = Array.isArray(data) ? data : Array.isArray(data.tracks) ? data.tracks : [];
100
+ tracks = list.filter(t => t && t.id && (t.audioPath || t.filename));
101
+ if (!tracks.length) throw new Error('No playable tracks found');
102
+ const valid = new Set(tracks.map(t=>t.id));
103
+ bag = Array.isArray(bag) ? bag.filter(id=>valid.has(id)) : [];
104
+ if (!bag.length) refillBag();
105
+ setStatus(tracks.length.toLocaleString() + ' tracks loaded · 3 catalogues');
106
+ if (current) updateNow();
107
+ } catch (e) {
108
+ setStatus('Could not load music index');
109
+ $('#mb-title').textContent = 'The catalogue is taking a nap';
110
+ $('#mb-meta').textContent = e.message + ' · Check your connection';
111
+ } finally { loading = false; }
112
+ }
113
+ function updateNow() {
114
+ if (!current) return;
115
+ $('#mb-title').textContent = cleanTitle(current);
116
+ $('#mb-meta').textContent = [current.catalog, current.duration ? formatTime(current.duration) : '', current.artist].filter(Boolean).join(' · ');
117
+ $('#mb-download').disabled = false;
118
+ $('#mb-play').textContent = audio.paused ? '▶ Play' : 'Ⅱ Pause';
119
+ }
120
+ function formatTime(n) { n=Number(n)||0; return Math.floor(n/60)+':'+String(Math.floor(n%60)).padStart(2,'0'); }
121
+ async function play(t) {
122
+ if (!t) return;
123
+ current = t;
124
+ audio.src = audioURL(t);
125
+ updateNow();
126
+ history.unshift({id:t.id,title:cleanTitle(t),catalog:t.catalog||'1hit',playedAt:new Date().toLocaleString()});
127
+ history = history.slice(0,MAX_HISTORY);
128
+ saveJSON(HISTORY_KEY,history);
129
+ renderHistory();
130
+ creature.classList.add('excited');
131
+ setTimeout(()=>creature.classList.remove('excited'),1000);
132
+ try { await audio.play(); setStatus('Now playing · ' + (t.catalog || '1hit')); }
133
+ catch { setStatus('Ready · press Play to start'); }
134
+ updateNow();
135
+ }
136
+ async function randomPlay() {
137
+ if (!tracks.length) await loadIndex();
138
+ if (!tracks.length) { panel.classList.remove('hidden'); return; }
139
+ panel.classList.remove('hidden');
140
+ const t = pickRandom();
141
+ await play(t);
142
+ }
143
+ async function downloadCurrent() {
144
+ if (!current) return;
145
+ const b = $('#mb-download'); b.disabled = true; b.textContent = '…';
146
+ const url = audioURL(current);
147
+ try {
148
+ const r = await fetch(url, {mode:'cors'});
149
+ if (!r.ok) throw new Error('HTTP '+r.status);
150
+ const blob = await r.blob();
151
+ const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
152
+ a.download = safeFile(cleanTitle(current)) + '.mp3'; a.style.display='none'; shadow.appendChild(a); a.click(); a.remove();
153
+ setTimeout(()=>URL.revokeObjectURL(a.href),30000);
154
+ setStatus('Download started');
155
+ } catch {
156
+ window.open(url, '_blank', 'noopener');
157
+ setStatus('Opened MP3 directly · use Save audio if needed');
158
+ } finally { b.disabled = false; b.textContent = '↓ MP3'; }
159
+ }
160
+ function safeFile(s) { return String(s||'track').replace(/[\\/:*?"<>|\x00-\x1f]/g,'_').trim().slice(0,100)||'track'; }
161
+ function look(x,y) { const r=creature.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+70,dx=Math.max(-9,Math.min(9,(x-cx)/22)),dy=Math.max(-9,Math.min(9,(y-cy)/22));pupil.style.transform=`translate(${dx}px,${dy}px)`;tinyPupils.forEach((p,i)=>p.style.transform=`translate(calc(-50% + ${dx*(i%2?.35:-.35)}px),${dy*.35}px)`); }
162
+ function onMove(e) { if(dragging){if(Math.abs(e.clientX-startX)+Math.abs(e.clientY-startY)>5)moved=true;creature.style.left=`${e.clientX-offsetX}px`;creature.style.top=`${e.clientY-offsetY}px`;creature.style.right='auto';creature.style.bottom='auto';}look(e.clientX,e.clientY); }
163
+ function onDown(e) { if(!creature.contains(e.target))return;dragging=true;moved=false;const r=creature.getBoundingClientRect();offsetX=e.clientX-r.left;offsetY=e.clientY-r.top;startX=e.clientX;startY=e.clientY;creature.setPointerCapture?.(e.pointerId);e.preventDefault(); }
164
+ function onUp(){dragging=false;}
165
+ function onKey(e){if(e.key==='Escape')cleanup();}
166
+ function cleanup(){if(destroyed)return;destroyed=true;audio.pause();document.removeEventListener('pointermove',onMove,true);document.removeEventListener('pointerup',onUp,true);document.removeEventListener('keydown',onKey,true);host.remove();}
167
+
168
+ creature.addEventListener('pointerdown',onDown);
169
+ creature.addEventListener('click',e=>{if(moved){e.preventDefault();return;}randomPlay();});
170
+ document.addEventListener('pointermove',onMove,true);document.addEventListener('pointerup',onUp,true);document.addEventListener('keydown',onKey,true);
171
+ $('#mb-close').addEventListener('click',()=>panel.classList.add('hidden'));
172
+ $('#mb-play').addEventListener('click',()=>{if(!current){randomPlay();return;}if(audio.paused)audio.play().catch(()=>{});else audio.pause();});
173
+ $('#mb-next').addEventListener('click',randomPlay);
174
+ $('#mb-download').addEventListener('click',downloadCurrent);
175
+ $('#mb-volume').addEventListener('input',e=>audio.volume=Number(e.target.value));
176
+ $('#mb-clear').addEventListener('click',()=>{history=[];saveJSON(HISTORY_KEY,history);renderHistory();});
177
+ audio.addEventListener('play',()=>{creature.classList.add('playing');$('#mb-play').textContent='Ⅱ Pause';});
178
+ audio.addEventListener('pause',()=>{creature.classList.remove('playing');$('#mb-play').textContent='▶ Play';});
179
+ audio.addEventListener('ended',randomPlay);
180
+ renderHistory();
181
+ loadIndex().then(()=>{if(tracks.length && !history.length)setStatus(tracks.length.toLocaleString()+' tracks ready · click me');});
182
+ })();