File size: 17,948 Bytes
48b8b15
 
 
 
 
 
f029479
48b8b15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f029479
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
(() => {
  const HOST_ID = 'onehit-music-beholder-root';
  const old = document.getElementById(HOST_ID);
  if (old) { old.remove(); return; }

  const scriptURL = document.currentScript?.src || 'https://music-beholder.vercel.app/music-beholder.js';
  const INDEX_URL = 'https://music-beholder.vercel.app/music-index.json';
  const AUDIO_ORIGIN = 'https://1hit.no';
  const HISTORY_KEY = 'onehit-music-beholder-history-v1';
  const BAG_KEY = 'onehit-music-beholder-bag-v1';
  const MAX_HISTORY = 80;
  const host = document.createElement('div');
  host.id = HOST_ID;
  Object.assign(host.style, { position:'fixed', inset:'0', zIndex:'2147483647', pointerEvents:'none', overflow:'hidden' });
  (document.documentElement || document.body).appendChild(host);
  const shadow = host.attachShadow({mode:'open'});

  const style = document.createElement('style');
  style.textContent = `
    :host{all:initial;color-scheme:dark}
    *{box-sizing:border-box}
    .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}
    .beholder:active{cursor:grabbing}
    .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}
    .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}
    .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}
    .pupil:after{content:"";position:absolute;width:8px;height:8px;left:5px;top:5px;border-radius:50%;background:#fff}
    .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}
    .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}
    .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}
    .tiny-pupil{position:absolute;z-index:3;width:8px;height:11px;left:50%;top:-9px;transform:translateX(-50%);border-radius:50%;background:#20292a}
    .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)}
    .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)}
    .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%)}
    .cheek{position:absolute;top:140px;width:15px;height:9px;border-radius:50%;background:#c57d61;opacity:.65}.c1{left:60px}.c2{left:151px}
    .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}
    .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}
    .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}
    .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}
    .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}
    @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}}
    @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)}}
    @media(prefers-reduced-motion:reduce){.beholder,.stalk,.lid,.beholder.playing .mouth{animation:none!important}}
  `;
  shadow.appendChild(style);

  const creature = document.createElement('div');
  creature.className = 'beholder';
  creature.setAttribute('role','button');
  creature.setAttribute('aria-label','Music Beholder. Click to play a random track. Drag to move. Press Escape to dismiss.');
  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>`;
  shadow.appendChild(creature);

  const panel = document.createElement('section');
  panel.className = 'panel';
  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>`;
  shadow.appendChild(panel);

  const audio = document.createElement('audio');
  audio.preload = 'none';
  audio.volume = 0.75;
  shadow.appendChild(audio);
  const $ = s => shadow.querySelector(s);
  const pupil = creature.querySelector('.pupil');
  const tinyPupils = [...creature.querySelectorAll('.tiny-pupil')];
  let tracks = [], current = null, history = readJSON(HISTORY_KEY, []), bag = readJSON(BAG_KEY, []);
  let dragging = false, moved = false, offsetX = 0, offsetY = 0, startX = 0, startY = 0;
  let loading = false, destroyed = false;

  function readJSON(key, fallback) { try { const v = JSON.parse(localStorage.getItem(key) || 'null'); return v ?? fallback; } catch { return fallback; } }
  function saveJSON(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch {} }
  function cleanTitle(t) { return String(t?.title || 'Untitled track').trim(); }
  function audioURL(t) { const p = t.audioPath || t.filename || ''; return /^https?:\/\//i.test(p) ? p : new URL(p.replace(/^\//,''), AUDIO_ORIGIN + '/').href; }
  function setStatus(s) { $('#mb-status').textContent = s; }
  function renderHistory() {
    const box = $('#mb-history');
    if (!history.length) { box.innerHTML = '<div class="empty">Nothing played yet. Click the creature to begin.</div>'; return; }
    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('');
    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); }));
  }
  function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
  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; }
  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); }
  function pickRandom() {
    if (!tracks.length) return null;
    const byId = new Map(tracks.map(t => [t.id,t]));
    while (bag.length && !byId.has(bag[bag.length-1])) bag.pop();
    if (!bag.length) refillBag();
    const id = bag.pop(); saveJSON(BAG_KEY,bag);
    return byId.get(id) || tracks[Math.floor(Math.random()*tracks.length)];
  }
  async function loadIndex() {
    if (loading || tracks.length) return;
    loading = true;
    try {
      const r = await fetch(INDEX_URL, {cache:'no-cache'});
      if (!r.ok) throw new Error('Index HTTP ' + r.status);
      const data = await r.json();
      const list = Array.isArray(data) ? data : Array.isArray(data.tracks) ? data.tracks : [];
      tracks = list.filter(t => t && t.id && (t.audioPath || t.filename));
      if (!tracks.length) throw new Error('No playable tracks found');
      const valid = new Set(tracks.map(t=>t.id));
      bag = Array.isArray(bag) ? bag.filter(id=>valid.has(id)) : [];
      if (!bag.length) refillBag();
      setStatus(tracks.length.toLocaleString() + ' tracks loaded · 3 catalogues');
      if (current) updateNow();
    } catch (e) {
      setStatus('Could not load music index');
      $('#mb-title').textContent = 'The catalogue is taking a nap';
      $('#mb-meta').textContent = e.message + ' · Check your connection';
    } finally { loading = false; }
  }
  function updateNow() {
    if (!current) return;
    $('#mb-title').textContent = cleanTitle(current);
    $('#mb-meta').textContent = [current.catalog, current.duration ? formatTime(current.duration) : '', current.artist].filter(Boolean).join(' · ');
    $('#mb-download').disabled = false;
    $('#mb-play').textContent = audio.paused ? '▶ Play' : 'Ⅱ Pause';
  }
  function formatTime(n) { n=Number(n)||0; return Math.floor(n/60)+':'+String(Math.floor(n%60)).padStart(2,'0'); }
  async function play(t) {
    if (!t) return;
    current = t;
    audio.src = audioURL(t);
    updateNow();
    history.unshift({id:t.id,title:cleanTitle(t),catalog:t.catalog||'1hit',playedAt:new Date().toLocaleString()});
    history = history.slice(0,MAX_HISTORY);
    saveJSON(HISTORY_KEY,history);
    renderHistory();
    creature.classList.add('excited');
    setTimeout(()=>creature.classList.remove('excited'),1000);
    try { await audio.play(); setStatus('Now playing · ' + (t.catalog || '1hit')); }
    catch { setStatus('Ready · press Play to start'); }
    updateNow();
  }
  async function randomPlay() {
    if (!tracks.length) await loadIndex();
    if (!tracks.length) { panel.classList.remove('hidden'); return; }
    panel.classList.remove('hidden');
    const t = pickRandom();
    await play(t);
  }
  async function downloadCurrent() {
    if (!current) return;
    const b = $('#mb-download'); b.disabled = true; b.textContent = '…';
    const url = audioURL(current);
    try {
      const r = await fetch(url, {mode:'cors'});
      if (!r.ok) throw new Error('HTTP '+r.status);
      const blob = await r.blob();
      const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
      a.download = safeFile(cleanTitle(current)) + '.mp3'; a.style.display='none'; shadow.appendChild(a); a.click(); a.remove();
      setTimeout(()=>URL.revokeObjectURL(a.href),30000);
      setStatus('Download started');
    } catch {
      window.open(url, '_blank', 'noopener');
      setStatus('Opened MP3 directly · use Save audio if needed');
    } finally { b.disabled = false; b.textContent = '↓ MP3'; }
  }
  function safeFile(s) { return String(s||'track').replace(/[\\/:*?"<>|\x00-\x1f]/g,'_').trim().slice(0,100)||'track'; }
  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)`); }
  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); }
  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(); }
  function onUp(){dragging=false;}
  function onKey(e){if(e.key==='Escape')cleanup();}
  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();}

  creature.addEventListener('pointerdown',onDown);
  creature.addEventListener('click',e=>{if(moved){e.preventDefault();return;}randomPlay();});
  document.addEventListener('pointermove',onMove,true);document.addEventListener('pointerup',onUp,true);document.addEventListener('keydown',onKey,true);
  $('#mb-close').addEventListener('click',()=>panel.classList.add('hidden'));
  $('#mb-play').addEventListener('click',()=>{if(!current){randomPlay();return;}if(audio.paused)audio.play().catch(()=>{});else audio.pause();});
  $('#mb-next').addEventListener('click',randomPlay);
  $('#mb-download').addEventListener('click',downloadCurrent);
  $('#mb-volume').addEventListener('input',e=>audio.volume=Number(e.target.value));
  $('#mb-clear').addEventListener('click',()=>{history=[];saveJSON(HISTORY_KEY,history);renderHistory();});
  audio.addEventListener('play',()=>{creature.classList.add('playing');$('#mb-play').textContent='Ⅱ Pause';});
  audio.addEventListener('pause',()=>{creature.classList.remove('playing');$('#mb-play').textContent='▶ Play';});
  audio.addEventListener('ended',randomPlay);
  renderHistory();
  loadIndex().then(()=>{if(tracks.length && !history.length)setStatus(tracks.length.toLocaleString()+' tracks ready · click me');});
})();