studius / studios5.js
2Btainment's picture
P9.3: Space-Paket Direkt-Fallback zu SpaceForge bei HF-Limit, v136
9ceefcc verified
Raw History Blame Contribute Delete
54.2 kB
// STUDIUS P5: Radio Studio · Social/Marketing Studio · Shop Studio (JDT link-shop) + video reframe helper.
// Every result goes on the asset bus (save to workspace / send to studio). Nothing is ever posted or published externally.
import { STUDIOS } from './widgets.js?v=50';
import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, signedIn, TF, CHAT, FLUX } from './real.js?v=136';
import { Avatars } from './avatar.js?v=136';
import { toWav, toMp3 } from './master.js?v=136';
const bucket = () => signedIn() && window.__ws?.bucket;
const wsFile = (p) => '/api/ws/file?bucket=' + encodeURIComponent(window.__ws.bucket) + '&path=' + encodeURIComponent(p);
const toBlob = async (u) => u instanceof Blob ? u : (await fetch(u, { credentials: 'include' })).blob();
const slug = (n) => (n || 'x').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'x';
const ts = () => new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '');
async function upload(path, blob, studio) { if (!bucket()) throw new Error('Bitte anmelden + Workspace-Bucket verbinden'); const f = new FormData(); f.append('bucket', window.__ws.bucket); f.append('path', path); f.append('studio', studio); f.append('file', blob, path.split('/').pop());
const r = await fetch('/api/ws/upload', { method: 'POST', body: f, credentials: 'include' }); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || 'Upload ' + r.status); return r.json(); }
async function wsList(prefix = '') { if (!bucket()) return []; const r = await fetch('/api/ws/list?bucket=' + encodeURIComponent(window.__ws.bucket) + '&prefix=' + encodeURIComponent(prefix), { credentials: 'include' }); return r.ok ? (await r.json()).files || [] : []; }
async function wsJson(path, dflt) { if (!bucket()) return dflt; try { const r = await fetch(wsFile(path), { credentials: 'include' }); return r.ok ? await r.json() : dflt; } catch (e) { return dflt; } }
const saveJson = (path, obj, studio) => upload(path, new Blob([JSON.stringify(obj, null, 1)], { type: 'application/json' }), studio);
async function llm(prompt, on = {}) { const r = await MODULES.chat.actions.reply.run({ prompt }, on); return (r.text || '').replace(/\*\*/g, '').replace(/^[ \t]*["„“]|["“”][ \t]*$/gm, '').replace(/\n{3,}/g, '\n\n').trim(); }
const dl = (blob, name) => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); };
const canvasBlob = (c, t = 'image/png') => new Promise(r => c.toBlob(r, t, .92));
const loadImg = (src) => new Promise((ok, no) => { const i = new Image(); i.crossOrigin = 'anonymous'; i.onload = () => ok(i); i.onerror = () => no(new Error('Bild lädt nicht')); i.src = src; });
const cover = (x, img, X, Y, W, H) => { const s = Math.max(W / img.width, H / img.height), w = img.width * s, h = img.height * s; x.save(); x.beginPath(); x.rect(X, Y, W, H); x.clip(); x.drawImage(img, X + (W - w) / 2, Y + (H - h) / 2, w, h); x.restore(); };
function wrap(x, text, X, Y, maxW, lh, maxLines = 4) { const words = String(text).split(/\s+/); let line = '', n = 0; for (const w of words) { const t = line ? line + ' ' + w : w; if (x.measureText(t).width > maxW && line) { x.fillText(line, X, Y + n * lh); line = w; if (++n >= maxLines) return; } else line = t; } if (line) x.fillText(line, X, Y + n * lh); }
const avOptions = async (sel, empty) => { const l = await Avatars.list().catch(() => []); sel.innerHTML = `<option value="">${empty}</option>` + l.map(a => `<option value="${esc(a.id)}">${esc(a.name || a.id)}</option>`).join(''); sel._list = l; return l; };
/* ---------- shared: reframe a video (server ffmpeg) ---------- */
export async function reframe(video, aspect = '9:16', mode = 'blur', name = 'video') {
const f = new FormData(); f.append('aspect', aspect); f.append('mode', mode); f.append('name', name);
if (typeof video === 'string' && video.startsWith('/api/tmp/')) f.append('src', video); else f.append('file', await toBlob(video), name + '.mp4');
const r = await fetch('/api/reframe', { method: 'POST', body: f, credentials: 'include' }); if (!r.ok) throw new Error('Reframe: ' + ((await r.json().catch(() => ({}))).detail || r.status)); return r.json(); }
window.__reframe = reframe;
export function reframeRow(host, getVideo, base = {}) { // UI row: format + mode → new video asset on the bus
const d = document.createElement('div'); d.className = 'row reframe'; d.innerHTML = `<select class="rfa" aria-label="Zielformat"><option value="9:16">9:16 Reel/TikTok/Story</option><option value="16:9">16:9 YouTube</option><option value="4:5">4:5 Instagram</option><option value="1:1">1:1 Quadrat</option></select><select class="rfm" aria-label="Füllmodus"><option value="blur">Unscharfer Hintergrund</option><option value="crop">Zuschneiden</option></select><button class="btn alt rfgo">↔ Umformatieren</button><small class="rfst mut"></small><div class="rfout" style="width:100%"></div>`;
host.append(d); const q = (s) => d.querySelector(s);
q('.rfgo').onclick = async () => { const v = getVideo(); if (!v) return q('.rfst').textContent = 'kein Video'; q('.rfgo').disabled = true; q('.rfst').textContent = 'ffmpeg…';
try { const r = await reframe(v, q('.rfa').value, q('.rfm').value, base.name || 'video'); q('.rfout').innerHTML = `<video controls playsinline src="${esc(r.url)}" style="max-height:260px"></video>`; q('.rfst').textContent = `✔ ${r.width}×${r.height}`; window.__reframed = r;
result(q('.rfout'), { kind: 'video', mime: 'video/mp4', url: r.url, name: `${slug(base.name || 'video')}-${r.aspect.replace(':', 'x')}-${Date.now()}.mp4`, studio: base.studio || 'videoedit', prompt: base.prompt || '', model: 'ffmpeg reframe ' + r.aspect + ' ' + r.mode }); }
catch (e) { q('.rfst').textContent = '⚠ ' + e.message; } finally { q('.rfgo').disabled = false; } };
return d;
}
// Avatar Studio: reframe talking-head output (square MoDA → 9:16 / 16:9 …)
new MutationObserver(() => { const o = document.querySelector('#pop .talkout'); if (o && o.querySelector('video') && !o.parentElement.querySelector('.reframe')) reframeRow(o.parentElement, () => o.querySelector('video')?.getAttribute('src'), { name: 'talk', studio: 'avatar' }); }).observe(document.body, { childList: true, subtree: true });
/* =================== RADIO STUDIO =================== */
const RAD = { station: 'STUDIUS FM', tracks: [], host: '', xf: 3, epoch: Date.now(), buf: new Map() };
const isAudio = (p) => /\.(wav|mp3|ogg|flac|m4a|opus)$/i.test(p);
async function decodeUrl(u) { if (RAD.buf.has(u)) return RAD.buf.get(u); const ac = new OfflineAudioContext(2, 1, 44100); const b = await ac.decodeAudioData(await (await toBlob(u)).arrayBuffer()); RAD.buf.set(u, b); return b; }
function plan(bufs, xf) { let t = 0; return bufs.map((b, i) => { const st = t, f = Math.min(xf, b.duration / 3); t += b.duration - (i < bufs.length - 1 ? f : 0); return { st, dur: b.duration, f }; }); }
function schedule(ctx, bufs, P, from = 0, t0 = 0) { const nodes = []; bufs.forEach((b, i) => { const p = P[i], end = p.st + p.dur; if (end <= from) return;
const s = ctx.createBufferSource(); s.buffer = b; const g = ctx.createGain(); s.connect(g).connect(ctx.destination); const off = Math.max(0, from - p.st), at = t0 + Math.max(0, p.st - from);
const gv = (tt) => Math.min(1, i > 0 ? (tt - p.st) / p.f : 1, i < bufs.length - 1 ? (end - tt) / p.f : 1); const a0 = p.st + off;
g.gain.setValueAtTime(Math.max(0, gv(a0)), at); if (i > 0 && a0 < p.st + p.f) g.gain.linearRampToValueAtTime(1, t0 + p.st + p.f - from);
if (i < bufs.length - 1) { g.gain.setValueAtTime(1, Math.max(at, t0 + end - p.f - from)); g.gain.linearRampToValueAtTime(0, t0 + end - from); }
s.start(at, off); nodes.push(s); }); return nodes; }
async function mixJingle(voice, bed, len = 10) { // bed ducked under voice, fade out
const sr = 44100, v = voice ? await decodeUrl(voice) : null, b = bed ? await decodeUrl(bed) : null, dur = Math.max(v ? v.duration + 1.6 : 0, Math.min(b ? b.duration : 0, len)) || 4;
const ctx = new OfflineAudioContext(2, Math.ceil(dur * sr), sr);
if (b) { const s = ctx.createBufferSource(); s.buffer = b; const g = ctx.createGain(); s.connect(g).connect(ctx.destination); g.gain.setValueAtTime(.9, 0);
if (v) { g.gain.linearRampToValueAtTime(.22, .6); g.gain.setValueAtTime(.22, .6 + v.duration); g.gain.linearRampToValueAtTime(.9, 1.2 + v.duration); } g.gain.setValueAtTime(g.gain.value, Math.max(0, dur - 1.2)); g.gain.linearRampToValueAtTime(0, dur); s.start(0); }
if (v) { const s = ctx.createBufferSource(); s.buffer = v; const g = ctx.createGain(); g.gain.value = 1.1; s.connect(g).connect(ctx.destination); s.start(.6); }
return ctx.startRendering(); }
STUDIOS.push({ id: 'radio', cat: 'Audio', icon: '📻', name: 'Radio Studio', like: 'Sender & Playlist', real: 'API', accepts: ['audio'], build(el) {
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Sender bauen: Playlist · Jingles · Moderation · Export</span></div>
<div class="row"><input class="stn" aria-label="Sendername" value="${esc(RAD.station)}"><select class="host" aria-label="Moderator (Avatar)"></select><select class="xf" aria-label="Crossfade"><option value="0">kein Crossfade</option><option value="3" selected>Crossfade 3 s</option><option value="6">Crossfade 6 s</option></select></div>
<fieldset class="grp"><legend>Playlist</legend><div class="row"><button class="btn alt wsadd">📂 Aus Workspace</button><label class="btn alt">⬆ Audio<input type="file" accept="audio/*" multiple hidden class="up"></label><small class="tot mut"></small></div><div class="wspick"></div><ol class="pl"></ol></fieldset>
<fieldset class="grp"><legend>Jingle-Generator</legend><input class="jt" aria-label="Jingle-Text" placeholder="Jingle-Text"><div class="row"><select class="bed" aria-label="Musikbett"><option value="gen">Musikbett erzeugen (TangoFlux)</option><option value="track">1. Track als Bett</option><option value="none">ohne Musik</option></select><input class="bedp" aria-label="Musikbett-Prompt" value="upbeat radio station jingle, bright synth stinger, punchy drums"></div><div class="row"><button class="btn alt jgo">🎺 Jingle erzeugen</button></div></fieldset>
<fieldset class="grp"><legend>Moderation (Avatar als Host)</legend><div class="row"><select class="mtr" aria-label="Ansage vor Track"></select><button class="btn alt mgo">🎙 Ansage erzeugen</button></div><small class="mut">Der Host schreibt (LLM) und spricht (seine Stimme) eine kurze Ansage, die vor dem Track eingefügt wird.</small></fieldset>
<div class="row"><button class="btn play">▶ Abspielen</button><button class="btn alt live">📡 Live (pseudo)</button><button class="btn alt stop">■</button><span class="np mut"></span></div>
<div class="row"><button class="btn alt exp">⬇ Sendung exportieren (MP3 + Playlist)</button></div><div class="out"></div>
<div class="credit">Jingles: ${hf(TF)} + Avatar-Stimme · Moderation: ${hf(CHAT)} · Crossfade/Export lokal (WebAudio) · Pseudo-Live: <code>position = (jetzt − Epoch) mod Länge</code> · Export: <code>projects/radio/&lt;sender&gt;/</code> (MP3 + playlist.json + .m3u für Icecast/Liquidsoap)</div>`;
keep(el); const q = (s) => el.querySelector(s); let ctx = null, nodes = [], tick = null;
q('.jt').value = `${RAD.station} – dein Sender aus dem Bienenstock!`;
avOptions(q('.host'), '🎙 Host: Standardstimme').then(() => { q('.host').value = RAD.host; });
q('.host').onchange = () => RAD.host = q('.host').value; q('.stn').onchange = () => RAD.station = q('.stn').value.trim() || 'STUDIUS FM'; q('.xf').value = String(RAD.xf); q('.xf').onchange = () => RAD.xf = +q('.xf').value;
const hostAv = () => q('.host')._list?.find(a => a.id === q('.host').value) || { id: 'host', name: 'Host', voice: { description: 'energetic, warm German radio host, clear diction', language: 'German' } };
const render = async () => { const pl = q('.pl'); pl.innerHTML = RAD.tracks.map((t, i) => `<li data-i="${i}"><span class="tk ${t.type}">${t.type === 'jingle' ? '🎺' : t.type === 'talk' ? '🎙' : '🎵'}</span> ${esc(t.name)} <small class="mut">${t.dur ? t.dur.toFixed(1) + ' s' : ''}</small> <button class="ib" data-a="up" aria-label="hoch">↑</button><button class="ib" data-a="dn" aria-label="runter">↓</button><button class="ib" data-a="rm" aria-label="aus Playlist entfernen">✕</button></li>`).join('') || '<small class="mut">Leer – Tracks aus dem Workspace hinzufügen oder aus Music/Mastering senden.</small>';
q('.mtr').innerHTML = RAD.tracks.map((t, i) => t.type === 'track' ? `<option value="${i}">vor: ${esc(t.name)}</option>` : '').join('');
const tot = RAD.tracks.reduce((a, t) => a + (t.dur || 0), 0); q('.tot').textContent = `${RAD.tracks.length} Elemente · ${Math.floor(tot / 60)}:${String(Math.round(tot % 60)).padStart(2, '0')} min`; window.__radio = { station: RAD.station, n: RAD.tracks.length, tracks: RAD.tracks.map(t => [t.type, t.name, +(t.dur || 0).toFixed(1)]) }; };
const add = async (t, at) => { try { t.dur = (await decodeUrl(t.url)).duration; } catch (e) { setS(el, '⚠ ' + t.name + ': nicht dekodierbar', true); return; } at == null ? RAD.tracks.push(t) : RAD.tracks.splice(at, 0, t); render(); };
q('.pl').onclick = (e) => { const b = e.target.closest('[data-a]'); if (!b) return; const i = +b.closest('li').dataset.i, T = RAD.tracks, a = b.dataset.a;
if (a === 'rm') T.splice(i, 1); if (a === 'up' && i > 0) [T[i - 1], T[i]] = [T[i], T[i - 1]]; if (a === 'dn' && i < T.length - 1) [T[i + 1], T[i]] = [T[i], T[i + 1]]; render(); };
q('.up').onchange = async () => { for (const f of q('.up').files) await add({ type: 'track', name: f.name, url: URL.createObjectURL(f), blob: f }); };
q('.wsadd').onclick = async () => { const box = q('.wspick'); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); box.innerHTML = '<small class="mut">lade…</small>';
const fs = (await wsList('')).filter(f => isAudio(f.path) && !f.path.startsWith('.studius/')); window.__radioWs = fs.length;
box.innerHTML = fs.length ? `<div class="wsl">${fs.slice(0, 60).map(f => `<label><input type="checkbox" value="${esc(f.path)}"> ${esc(f.path)}</label>`).join('')}</div><button class="btn alt wsok">➕ Hinzufügen</button>` : '<small class="mut">Keine Audios im Workspace.</small>';
box.querySelector('.wsok')?.addEventListener('click', async () => { const sel = [...box.querySelectorAll('input:checked')].map(i => i.value); box.innerHTML = ''; for (const p of sel) await add({ type: p.includes('/jingles/') ? 'jingle' : 'track', name: p.split('/').pop(), url: wsFile(p), path: p }); setS(el, `✔ ${sel.length} aus Workspace`); }); };
q('.jgo').onclick = async (e) => { const b = e.target; b.disabled = true; const text = q('.jt').value.trim();
try { setS(el, 'Jingle: Stimme…'); const voice = text ? await Avatars.speak(hostAv(), text.slice(0, 200), { el, onStatus: m => setS(el, 'Jingle-Stimme: ' + stTxt(m)) }) : null;
let bed = null, mode = q('.bed').value; if (mode === 'gen') { setS(el, 'Jingle: Musikbett…'); bed = (await MODULES.music.actions.compose.run({ prompt: q('.bedp').value }, { status: m => setS(el, 'Musikbett: ' + stTxt(m)) })).url; } else if (mode === 'track') bed = RAD.tracks.find(t => t.type === 'track')?.url;
setS(el, 'Jingle: Mix (Ducking)…'); const buf = await mixJingle(voice, bed); const blob = toWav(buf), name = `${slug(RAD.station)}-jingle-${ts()}.wav`, u = URL.createObjectURL(blob);
RAD.buf.set(u, buf); await add({ type: 'jingle', name, url: u, blob }, 0); q('.out').innerHTML = `<audio controls src="${u}"></audio>`;
result(q('.out'), { kind: 'audio', mime: 'audio/wav', blob, url: u, name, path: `projects/radio/${slug(RAD.station)}/jingles/${name}`, studio: 'radio', prompt: text, model: 'Qwen3-TTS + TangoFlux (Mix lokal)' }); window.__jingle = { name, dur: buf.duration, bed: mode }; setS(el, `✔ Jingle ${buf.duration.toFixed(1)} s → Playlist (Position 1)`); badge(el, 'REAL'); }
catch (er) { setS(el, '⚠ ' + er.message, true); window.__jingle = { err: er.message }; } finally { b.disabled = false; } };
q('.mgo').onclick = async (e) => { const i = +q('.mtr').value, t = RAD.tracks[i]; if (!t) return setS(el, '⚠ Erst Tracks hinzufügen', true); const b = e.target; b.disabled = true; const av = hostAv();
try { setS(el, 'Moderation: Text…'); let txt = await llm(`${av.system ? 'System: ' + Avatars.persona(av) + '\n' : ''}Du bist Radiomoderator von "${RAD.station}". Schreibe EINE kurze, lockere Ansage auf Deutsch (max. 25 Wörter) für den nächsten Song "${t.name.replace(/\.\w+$/, '').replace(/[-_]/g, ' ')}". Nur die Ansage, ohne Anführungszeichen.`, { status: m => setS(el, 'Moderation: ' + stTxt(m)) });
txt = txt.replace(/^["„]|["“]$/g, '').split('\n').filter(Boolean)[0]?.slice(0, 220) || `Und jetzt auf ${RAD.station}: ${t.name}`;
setS(el, 'Moderation: Stimme…'); const u = await Avatars.speak(av, txt, { el, onStatus: m => setS(el, 'Moderation: ' + stTxt(m)) }); const name = `${slug(RAD.station)}-talk-${ts()}.wav`;
await add({ type: 'talk', name, url: u, text: txt }, i); q('.out').innerHTML = `<p class="mut">🎙 „${esc(txt)}“</p><audio controls src="${esc(u)}"></audio>`;
result(q('.out'), { kind: 'audio', url: u, name, path: `projects/radio/${slug(RAD.station)}/talk/${name}`, studio: 'radio', prompt: txt }); window.__talkRadio = { txt, i }; setS(el, '✔ Ansage eingefügt'); }
catch (er) { setS(el, '⚠ ' + er.message, true); window.__talkRadio = { err: er.message }; } finally { b.disabled = false; } };
const stop = () => { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; clearInterval(tick); q('.np').textContent = ''; };
const play = async (live) => { stop(); if (!RAD.tracks.length) return setS(el, '⚠ Playlist leer', true); setS(el, 'Lade Audio…'); const bufs = await Promise.all(RAD.tracks.map(t => decodeUrl(t.url))); const P = plan(bufs, RAD.xf), total = P.at(-1).st + P.at(-1).dur;
ctx ||= new AudioContext(); await ctx.resume(); const from = live ? ((Date.now() - RAD.epoch) / 1000) % total : 0, t0 = ctx.currentTime + .1; nodes = schedule(ctx, bufs, P, from, t0);
tick = setInterval(() => { const pos = from + ctx.currentTime - t0; if (pos > total) { stop(); if (live) play(true); return; } const i = P.findLastIndex(p => p.st <= pos); q('.np').textContent = `${live ? '📡 LIVE · ' : ''}▶ ${RAD.tracks[i]?.name || ''} · ${Math.floor(pos / 60)}:${String(Math.floor(pos % 60)).padStart(2, '0')} / ${Math.floor(total / 60)}:${String(Math.round(total % 60)).padStart(2, '0')}`; window.__radioNow = { i, pos: +pos.toFixed(1), live }; }, 250);
setS(el, live ? `📡 Pseudo-live ab ${from.toFixed(0)} s (Epoch ${new Date(RAD.epoch).toLocaleTimeString('de-DE')})` : '▶ Sendung läuft'); };
q('.play').onclick = () => play(false); q('.live').onclick = () => play(true); q('.stop').onclick = stop; el.__stop = stop;
q('.exp').onclick = async (e) => { if (!RAD.tracks.length) return setS(el, '⚠ Playlist leer', true); const b = e.target; b.disabled = true;
try { setS(el, 'Rendere Sendung…'); const bufs = await Promise.all(RAD.tracks.map(t => decodeUrl(t.url))); const P = plan(bufs, RAD.xf), total = P.at(-1).st + P.at(-1).dur; if (total > 1800) throw new Error('max. 30 min pro Export');
const oc = new OfflineAudioContext(2, Math.ceil(total * 44100), 44100); schedule(oc, bufs, P, 0, 0); const buf = await oc.startRendering();
setS(el, 'MP3-Encoding…'); const mp3 = await toMp3(buf, 192, p => setS(el, `MP3 ${Math.round(p * 100)} %`)); const st = slug(RAD.station), base = `projects/radio/${st}/`, name = `${st}-show-${ts()}.mp3`;
const pl = { type: 'studius.radio', v: 1, station: RAD.station, epoch: RAD.epoch, crossfade: RAD.xf, total: +total.toFixed(2), host: RAD.host || null, show: base + name,
items: RAD.tracks.map((t, i) => ({ type: t.type, name: t.name, path: t.path || null, text: t.text || null, start: +P[i].st.toFixed(2), duration: +P[i].dur.toFixed(2) })) };
const m3u = '#EXTM3U\n#PLAYLIST:' + RAD.station + '\n' + pl.items.map(it => `#EXTINF:${Math.round(it.duration)},${it.name}\n${it.path || it.name}`).join('\n') + '\n';
const u = URL.createObjectURL(mp3); q('.out').innerHTML = `<audio controls src="${u}"></audio><div class="row"><button class="btn alt dmp3">⬇ MP3</button><button class="btn alt dm3u">⬇ .m3u</button></div>`;
q('.dmp3').onclick = () => dl(mp3, name); q('.dm3u').onclick = () => dl(new Blob([m3u], { type: 'audio/x-mpegurl' }), st + '.m3u');
let saved = null; if (bucket()) { setS(el, 'Speichere im Workspace…'); for (const t of RAD.tracks) if (!t.path && t.blob) { const p = base + (t.type === 'jingle' ? 'jingles/' : 'tracks/') + t.name; await upload(p, t.blob, 'radio'); t.path = p; }
pl.items = RAD.tracks.map((t, i) => ({ ...pl.items[i], path: t.path || null })); await upload(base + name, mp3, 'radio'); await saveJson(base + 'playlist.json', pl, 'radio'); await upload(base + 'playlist.m3u', new Blob([m3u], { type: 'audio/x-mpegurl' }), 'radio'); saved = base; }
result(q('.out'), { kind: 'audio', mime: 'audio/mpeg', blob: mp3, url: u, name, path: base + name, studio: 'radio', prompt: RAD.station });
window.__radioExport = { total: +total.toFixed(1), bytes: mp3.size, saved, items: pl.items.length }; setS(el, `✔ Sendung ${Math.floor(total / 60)}:${String(Math.round(total % 60)).padStart(2, '0')} min · ${(mp3.size / 1e6).toFixed(1)} MB${saved ? ' · ' + saved : ''}`); badge(el, 'REAL'); }
catch (er) { setS(el, '⚠ ' + er.message, true); window.__radioExport = { err: er.message }; } finally { b.disabled = false; } };
el.__addAudio = (t) => add(t); render();
}, accept: async (el, a) => { await el.__addAudio({ type: /jingle/i.test(a.name || '') ? 'jingle' : 'track', name: a.name || 'audio.wav', url: a.blob ? URL.createObjectURL(a.blob) : a.url, blob: a.blob, path: a.path }); return true; } });
/* =================== SOCIAL / MARKETING STUDIO =================== */
const PLAT = { ig: { n: 'Instagram Post 4:5', w: 1080, h: 1350, tag: 'Instagram' }, sq: { n: 'Quadrat 1:1', w: 1080, h: 1080, tag: 'Instagram' }, story: { n: 'Story/Reel/TikTok 9:16', w: 1080, h: 1920, tag: 'TikTok' },
x: { n: 'X / Twitter 16:9', w: 1600, h: 900, tag: 'X' }, li: { n: 'LinkedIn 1.91:1', w: 1200, h: 627, tag: 'LinkedIn' }, yt: { n: 'YouTube Thumbnail', w: 1280, h: 720, tag: 'YouTube' } };
const CAPS = ['Instagram', 'TikTok', 'X', 'LinkedIn', 'YouTube'];
const SOC = { img: null, imgName: '', video: null, brief: 'Neuer Lofi-Track der STUDIUS-Bienen – jetzt im Radio', head: 'Neu: Honey Lofi', brand: { name: 'STUDIUS', handle: '@einswarm', c1: '#f2c94c', c2: '#0b0b0b', cta: 'Jetzt reinhören', link: '' }, plats: ['ig', 'story', 'x'], caps: {}, mock: {}, sched: null };
export function renderPost(img, P, { head, brand }) { // brand mockup for one platform → canvas
const c = document.createElement('canvas'); c.width = P.w; c.height = P.h; const x = c.getContext('2d'), s = Math.min(P.w, P.h) / 1080, tall = P.h / P.w > 1.2;
const g = x.createLinearGradient(0, 0, P.w, P.h); g.addColorStop(0, brand.c2); g.addColorStop(1, '#1a1406'); x.fillStyle = g; x.fillRect(0, 0, P.w, P.h);
const bar = 120 * s, imgH = tall ? P.h * .62 : P.h - bar, imgW = tall ? P.w : P.w * .6; if (img) cover(x, img, 0, 0, imgW, imgH);
x.fillStyle = brand.c1; x.fillRect(0, tall ? imgH : 0, tall ? P.w : 0, tall ? 10 * s : 0); if (!tall) x.fillRect(imgW, 0, 8 * s, P.h - bar);
x.fillStyle = '#fff'; x.textBaseline = 'top'; x.font = `800 ${(tall ? 92 : 64) * s}px ${brand.font || 'system-ui'}, sans-serif`; const tx = tall ? 60 * s : imgW + 40 * s, tw = tall ? P.w - 120 * s : P.w - imgW - 80 * s, ty = tall ? imgH + 60 * s : 60 * s;
wrap(x, head, tx, ty, tw, (tall ? 104 : 74) * s, 3);
x.fillStyle = brand.c1; x.fillRect(0, P.h - bar, P.w, bar); x.fillStyle = brand.c2; x.font = `700 ${46 * s}px ${brand.font || 'system-ui'}, sans-serif`; x.textBaseline = 'middle'; x.fillText(brand.name + ' ' + brand.handle, 40 * s, P.h - bar / 2);
const cta = brand.cta + ' →'; x.font = `800 ${40 * s}px ${brand.font || 'system-ui'}, sans-serif`; const cw = x.measureText(cta).width + 50 * s; x.fillStyle = brand.c2; x.beginPath(); x.roundRect(P.w - cw - 30 * s, P.h - bar + 22 * s, cw, bar - 44 * s, 30 * s); x.fill(); x.fillStyle = brand.c1; x.fillText(cta, P.w - cw - 5 * s, P.h - bar / 2);
return c; }
function parseCaps(t) { const out = {}; let cur = null; for (const line of t.split('\n')) { const m = line.match(/^\W*(Instagram|TikTok|X|Twitter|LinkedIn|YouTube)\W*[::]\s*(.*)$/i); if (m) { cur = /twitter/i.test(m[1]) ? 'X' : CAPS.find(c => c.toLowerCase() === m[1].toLowerCase()); out[cur] = m[2]; } else if (cur && line.trim()) out[cur] += '\n' + line.trim(); } return out; }
const icsDate = (d) => d.toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '');
STUDIOS.push({ id: 'social', cat: 'Community', icon: '📣', name: 'Social Studio', like: 'Post-Composer & Marketing', real: 'API', accepts: ['image', 'video', 'text'], build(el) {
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Post-Composer: Captions · Branding · Formate · Plan (STUDIUS postet nie selbst)</span></div>
<label class="fl">Briefing<textarea class="br" rows="2" aria-label="Briefing"></textarea></label><label class="fl">Headline<input class="hd" aria-label="Headline"></label>
<fieldset class="grp"><legend>Branding</legend><div class="row"><input class="bn" aria-label="Marke" style="width:30%"><input class="bh" aria-label="Handle" style="width:30%"><input type="color" class="c1" aria-label="Akzentfarbe"><input type="color" class="c2" aria-label="Grundfarbe"></div><div class="row"><input class="bc" aria-label="Call to Action" style="width:40%"><input class="bl" aria-label="Link (z. B. Shop)" placeholder="Link (Shop/Track)" style="width:55%"></div></fieldset>
<fieldset class="grp"><legend>Visual</legend><div class="row"><label class="btn alt">🖼 Bild<input type="file" accept="image/*" hidden class="ui"></label><button class="btn alt gi">✨ Bild aus Briefing</button><span class="imn mut">kein Bild</span></div><div class="vrow"></div></fieldset>
<fieldset class="grp"><legend>Formate</legend><div class="pls">${Object.entries(PLAT).map(([k, p]) => `<label><input type="checkbox" value="${k}"> ${p.n} <small class="mut">${p.w}×${p.h}</small></label>`).join('')}</div></fieldset>
<div class="row"><button class="btn cap">✍ Captions & Hashtags</button><button class="btn alt mk">🖼 Mockups rendern</button><button class="btn alt sva">💾 Kampagne speichern</button></div>
<div class="caps"></div><div class="mocks"></div>
<fieldset class="grp"><legend>Redaktionsplan</legend><div class="row"><input type="datetime-local" class="sd" aria-label="Termin"><select class="sp" aria-label="Plattform">${CAPS.map(c => `<option>${c}</option>`).join('')}</select><button class="btn alt sadd">➕ Einplanen</button><button class="btn alt ics">⬇ Kalender (.ics)</button></div><table class="sched"></table><small class="mut">Status „Freigegeben“ ist nur eine Markierung – gepostet wird manuell bzw. erst nach deiner ausdrücklichen Freigabe pro Post.</small></fieldset>
<div class="credit">Captions: ${hf(CHAT)} · Visual: ${hf(FLUX)} · Mockups & Formate lokal (Canvas), Video-Formate per Server-ffmpeg · gespeichert in <code>projects/social/</code></div>`;
keep(el); const q = (s) => el.querySelector(s); const B = SOC.brand; let img = null;
q('.br').value = SOC.brief; q('.hd').value = SOC.head; q('.bn').value = B.name; q('.bh').value = B.handle; q('.c1').value = B.c1; q('.c2').value = B.c2; q('.bc').value = B.cta; q('.bl').value = B.link;
el.querySelectorAll('.pls input').forEach(i => { i.checked = SOC.plats.includes(i.value); });
const read = () => { SOC.brief = q('.br').value.trim(); SOC.head = q('.hd').value.trim(); Object.assign(B, { name: q('.bn').value.trim(), handle: q('.bh').value.trim(), c1: q('.c1').value, c2: q('.c2').value, cta: q('.bc').value.trim(), link: q('.bl').value.trim() }); SOC.plats = [...el.querySelectorAll('.pls input:checked')].map(i => i.value); };
const setImg = async (blob, name) => { SOC.img = blob; SOC.imgName = name || 'visual'; img = await loadImg(URL.createObjectURL(blob)); q('.imn').textContent = '🖼 ' + SOC.imgName; };
const setVideo = (u, name) => { SOC.video = { url: u, name }; const v = q('.vrow'); v.innerHTML = `<video controls playsinline src="${esc(u)}" style="max-height:200px"></video>`; reframeRow(v, () => SOC.video.url, { name: name || 'social', studio: 'social', prompt: SOC.brief }); };
el.__setImg = setImg; el.__setVideo = setVideo; if (SOC.img) setImg(SOC.img, SOC.imgName); if (SOC.video) setVideo(SOC.video.url, SOC.video.name);
q('.ui').onchange = () => q('.ui').files[0] && setImg(q('.ui').files[0], q('.ui').files[0].name);
q('.gi').onclick = async (e) => { read(); e.target.disabled = true; try { const a = await MODULES.image.actions.generate.run({ prompt: `social media key visual, ${SOC.brief}, bold, clean composition, no text` }, { status: m => setS(el, 'Bild: ' + stTxt(m)) }); await setImg(await toBlob(a.url), a.name); setS(el, '✔ Visual erzeugt'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
const showCaps = () => { q('.caps').innerHTML = Object.keys(SOC.caps).length ? CAPS.filter(c => SOC.caps[c] != null).map(c => `<label class="fl">${c} <small class="mut cc" data-c="${c}"></small><textarea rows="3" data-c="${c}">${esc(SOC.caps[c])}</textarea></label>`).join('') : '';
const lim = { X: 280, Instagram: 2200, TikTok: 2200, LinkedIn: 3000, YouTube: 5000 }; const cnt = () => q('.caps').querySelectorAll('textarea').forEach(t => { SOC.caps[t.dataset.c] = t.value; const n = t.value.length, L = lim[t.dataset.c]; const s = q(`.cc[data-c="${t.dataset.c}"]`); s.textContent = `${n}/${L} · ${(t.value.match(/#\w+/g) || []).length} #`; s.style.color = n > L ? '#e66' : ''; });
q('.caps').oninput = cnt; keep(q('.caps')); cnt(); };
q('.cap').onclick = async (e) => { read(); e.target.disabled = true;
try { const t = await llm(`Du bist Social-Media-Manager der Marke ${B.name} (${B.handle}). Thema: ${SOC.brief}. Call-to-Action: ${B.cta}${B.link ? ' (' + B.link + ')' : ''}.
Schreibe je eine Caption auf Deutsch mit passenden Hashtags am Ende, genau in diesem Format (eine Zeile pro Plattform):
Instagram: <Caption, 2-3 Sätze, Emojis, 6-10 Hashtags>
TikTok: <kurz, Hook, 3-5 Hashtags>
X: <max. 240 Zeichen inkl. 2 Hashtags>
LinkedIn: <professionell, 2-3 Sätze, 3 Hashtags>
YouTube: <Titel-tauglicher Satz + 3 Hashtags>`, { status: m => setS(el, 'Captions: ' + stTxt(m)) });
let caps = parseCaps(t); if (Object.keys(caps).length < 2) caps = Object.fromEntries(CAPS.map(c => [c, t])); if (caps.X && caps.X.length > 280) caps.X = caps.X.slice(0, 277) + '…';
SOC.caps = caps; showCaps(); window.__social = { ...(window.__social || {}), caps: Object.keys(caps), sample: (caps.Instagram || '').slice(0, 160) };
result(q('.caps'), { kind: 'text', mime: 'text/plain', text: CAPS.filter(c => caps[c]).map(c => c + ': ' + caps[c]).join('\n\n'), name: `captions-${ts()}.txt`, path: `projects/social/${slug(SOC.head)}/captions.txt`, studio: 'social', prompt: SOC.brief }); setS(el, `✔ Captions für ${Object.keys(caps).length} Plattformen`); badge(el, 'REAL'); }
catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
q('.mk').onclick = async () => { read(); if (!SOC.plats.length) return setS(el, '⚠ Format wählen', true); SOC.mock = {}; const box = q('.mocks'); box.innerHTML = '<div class="mockg"></div>'; const g = box.firstChild;
for (const k of SOC.plats) { const c = renderPost(img, PLAT[k], { head: SOC.head, brand: B }); const blob = await canvasBlob(c); SOC.mock[k] = blob; const u = URL.createObjectURL(blob);
const fig = document.createElement('figure'); fig.innerHTML = `<img src="${u}" alt="${esc(PLAT[k].n)}"><figcaption>${esc(PLAT[k].n)} · ${PLAT[k].w}×${PLAT[k].h}</figcaption>`; g.append(fig);
result(fig, { kind: 'image', mime: 'image/png', blob, url: u, name: `${slug(SOC.head)}-${k}.png`, path: `projects/social/${slug(SOC.head)}/${k}-${PLAT[k].w}x${PLAT[k].h}.png`, studio: 'social', prompt: SOC.head }); }
window.__social = { ...(window.__social || {}), mock: SOC.plats.map(k => [k, PLAT[k].w, PLAT[k].h, SOC.mock[k].size]) }; setS(el, `✔ ${SOC.plats.length} Formate gerendert`); };
q('.sva').onclick = async (e) => { read(); e.target.disabled = true; try { const base = `projects/social/${slug(SOC.head)}/`; const files = [];
for (const [k, b] of Object.entries(SOC.mock)) { const p = `${base}${k}-${PLAT[k].w}x${PLAT[k].h}.png`; await upload(p, b, 'social'); files.push(p); }
if (SOC.img) { const p = base + 'visual.' + ((SOC.img.type || 'image/png').split('/')[1] || 'png').replace('jpeg', 'jpg'); await upload(p, SOC.img, 'social'); files.push(p); }
await saveJson(base + 'campaign.json', { type: 'studius.social', v: 1, brief: SOC.brief, head: SOC.head, brand: B, captions: SOC.caps, formats: Object.keys(SOC.mock), files, updated: Date.now() }, 'social');
window.__socialSaved = { base, files: files.length }; setS(el, `✔ Kampagne gespeichert: ${base} (${files.length} Dateien)`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
// schedule (stored in workspace; never posts)
const SP = 'projects/social/schedule.json'; const showSched = () => { const t = q('.sched'); t.innerHTML = (SOC.sched || []).length ? '<tr><th>Termin</th><th>Plattform</th><th>Post</th><th>Status</th></tr>' + SOC.sched.map((r, i) => `<tr><td>${esc(new Date(r.at).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' }))}</td><td>${esc(r.platform)}</td><td>${esc(r.head)}</td><td><button class="ib st" data-i="${i}" aria-label="Status umschalten">${r.status === 'freigegeben' ? '✅ Freigegeben' : '📝 Entwurf'}</button><button class="ib rm" data-i="${i}" aria-label="aus Plan entfernen">✕</button></td></tr>`).join('') : '<tr><td class="mut">Noch nichts geplant.</td></tr>'; window.__sched = (SOC.sched || []).map(r => [r.platform, r.status]); };
const saveSched = async () => { showSched(); if (bucket()) try { await saveJson(SP, { type: 'studius.schedule', v: 1, posts: SOC.sched }, 'social'); window.__schedSaved = SOC.sched.length; } catch (e) { setS(el, '⚠ ' + e.message, true); } };
(async () => { if (!SOC.sched) SOC.sched = (await wsJson(SP, { posts: [] })).posts || []; showSched(); })();
const d0 = new Date(Date.now() + 864e5); d0.setHours(18, 0, 0, 0); q('.sd').value = new Date(d0 - d0.getTimezoneOffset() * 6e4).toISOString().slice(0, 16);
q('.sadd').onclick = () => { read(); const pf = q('.sp').value; SOC.sched.push({ id: 'p' + Date.now().toString(36), at: new Date(q('.sd').value).getTime(), platform: pf, head: SOC.head, caption: SOC.caps[pf] || '', asset: `projects/social/${slug(SOC.head)}/`, status: 'entwurf' }); SOC.sched.sort((a, b) => a.at - b.at); saveSched(); };
q('.sched').onclick = (e) => { const b = e.target.closest('button'); if (!b) return; const i = +b.dataset.i; if (b.classList.contains('rm')) SOC.sched.splice(i, 1); else SOC.sched[i].status = SOC.sched[i].status === 'freigegeben' ? 'entwurf' : 'freigegeben'; saveSched(); };
q('.ics').onclick = () => { const ev = SOC.sched.map(r => `BEGIN:VEVENT\r\nUID:${r.id}@studius\r\nDTSTAMP:${icsDate(new Date())}\r\nDTSTART:${icsDate(new Date(r.at))}\r\nDURATION:PT15M\r\nSUMMARY:${(r.platform + ': ' + r.head).replace(/[,;]/g, ' ')} (${r.status})\r\nDESCRIPTION:${(r.caption || '').replace(/\n/g, '\\n').replace(/[,;]/g, ' ').slice(0, 900)}\r\nEND:VEVENT`).join('\r\n');
dl(new Blob([`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//STUDIUS//Social//DE\r\n${ev}\r\nEND:VCALENDAR\r\n`], { type: 'text/calendar' }), 'studius-redaktionsplan.ics'); };
if (SOC.caps && Object.keys(SOC.caps).length) showCaps();
}, accept: async (el, a) => { if (a.kind === 'video') { el.__setVideo(a.blob ? URL.createObjectURL(a.blob) : a.url, a.name); return true; }
if (a.kind === 'text') { const t = a.text ?? await (await toBlob(a.url)).text(); el.querySelector('.br').value = t.slice(0, 600); return true; }
const b = a.blob || await toBlob(a.url); await el.__setImg(b, a.name); if (a.prompt) el.querySelector('.hd').value ||= a.prompt.slice(0, 60); if (a.shop) { el.querySelector('.br').value = a.shop.brief; el.querySelector('.hd').value = a.shop.head; if (a.shop.link) el.querySelector('.bl').value = a.shop.link; } return true; } });
/* =================== SHOP STUDIO (Jenniisdriptees link-shop) =================== */
// Product types / pricing mirror the JDT design-studio domain (shared/domain.ts): base cost + shipping, margin, artist royalty, 19 % VAT, ,99 rounding.
const PT = { TEE: { l: 'T-Shirt', base: 1150, ship: 399, sizes: ['S', 'M', 'L', 'XL', '2XL'], colors: [['Schwarz', '#111111', 'BLK'], ['Weiß', '#f5f5f5', 'WHT'], ['Sand', '#d8c8a8', 'SND'], ['Navy', '#1f2a44', 'NVY']] },
HOD: { l: 'Hoodie', base: 2450, ship: 499, sizes: ['S', 'M', 'L', 'XL', '2XL'], colors: [['Schwarz', '#111111', 'BLK'], ['Grau meliert', '#9a9a9a', 'GRY'], ['Weiß', '#f5f5f5', 'WHT']] },
MUG: { l: 'Tasse 11oz', base: 650, ship: 499, sizes: ['11oz'], colors: [['Weiß', '#ffffff', 'WHT']] }, PST: { l: 'Poster', base: 900, ship: 599, sizes: ['A3', 'A2'], colors: [['Matt', '#ffffff', 'MAT']] },
STK: { l: 'Sticker', base: 250, ship: 199, sizes: ['7.5cm', '10cm'], colors: [['Weiß', '#ffffff', 'WHT']] } };
const LINES = { OWN: 'Eigene Produkte & Logos', ART: 'Artist-Merch', APP: 'App-/Agenten-Merch' };
const STAT = { entwurf: '📝 Entwurf', mockup: '🖼 Mockup', review: '🔎 Review', freigegeben: '✅ Freigegeben (Rob)' };
const slugCode = (s, m = 8) => (s || '').replace(/[äöüßÄÖÜ]/g, c => ({ ä: 'AE', ö: 'OE', ü: 'UE', ß: 'SS', Ä: 'AE', Ö: 'OE', Ü: 'UE' })[c]).toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, m) || 'X';
export function suggestPrice({ base, ship, margin, royalty = 0, vat = 19, inclShip = true }) { const share = Math.min(.9, (margin + royalty) / 100), cost = base + (inclShip ? ship : 0), net = Math.round(cost / (1 - share)), gross = Math.round(net * (1 + vat / 100)), sug = Math.ceil(gross / 100) * 100 - 1; return { cost, net, gross, sug, profit: Math.round(sug / (1 + vat / 100) - cost) }; }
const eur = (c) => (c / 100).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
function tee(x, w, h, col, hood) { x.fillStyle = col; x.strokeStyle = 'rgba(0,0,0,.25)'; x.lineWidth = 3; x.beginPath(); const cx = w / 2;
x.moveTo(cx - 120, 140); x.lineTo(cx - 250, 200); x.lineTo(cx - 330, 360); x.lineTo(cx - 240, 400); x.lineTo(cx - 200, 330); x.lineTo(cx - 200, h - 120); x.lineTo(cx + 200, h - 120); x.lineTo(cx + 200, 330); x.lineTo(cx + 240, 400); x.lineTo(cx + 330, 360); x.lineTo(cx + 250, 200); x.lineTo(cx + 120, 140);
if (hood) { x.quadraticCurveTo(cx + 120, 40, cx, 40); x.quadraticCurveTo(cx - 120, 40, cx - 120, 140); } else x.quadraticCurveTo(cx, 220, cx - 120, 140); x.closePath(); x.fill(); x.stroke();
if (hood) { x.fillStyle = 'rgba(0,0,0,.18)'; x.beginPath(); x.ellipse(cx, 150, 90, 60, 0, 0, 7); x.fill(); x.fillRect(cx - 110, h - 330, 220, 120); } }
export async function mockup(design, type, color) { const w = 900, h = 1000, c = document.createElement('canvas'); c.width = w; c.height = h; const x = c.getContext('2d');
const bg = x.createLinearGradient(0, 0, 0, h); bg.addColorStop(0, '#efe9dc'); bg.addColorStop(1, '#cfc6b2'); x.fillStyle = bg; x.fillRect(0, 0, w, h); x.fillStyle = 'rgba(0,0,0,.12)'; x.beginPath(); x.ellipse(w / 2, h - 90, 300, 30, 0, 0, 7); x.fill();
const img = design ? await loadImg(design) : null; const put = (X, Y, W, H) => { if (img) { x.save(); x.globalAlpha = .95; cover(x, img, X, Y, W, H); x.restore(); } };
if (type === 'TEE' || type === 'HOD') { tee(x, w, h, color, type === 'HOD'); put(w / 2 - 130, type === 'HOD' ? 290 : 260, 260, 300); }
else if (type === 'MUG') { x.fillStyle = '#fff'; x.strokeStyle = 'rgba(0,0,0,.2)'; x.lineWidth = 4; x.beginPath(); x.roundRect(220, 280, 380, 460, 30); x.fill(); x.stroke(); x.lineWidth = 40; x.strokeStyle = '#f4f4f4'; x.beginPath(); x.ellipse(620, 500, 90, 120, 0, -1.3, 1.3); x.stroke(); put(260, 360, 300, 280); }
else if (type === 'PST') { x.fillStyle = '#222'; x.fillRect(205, 105, 490, 690); x.fillStyle = '#fff'; x.fillRect(225, 125, 450, 650); put(255, 155, 390, 590); }
else { x.fillStyle = '#fff'; x.shadowColor = 'rgba(0,0,0,.25)'; x.shadowBlur = 20; x.beginPath(); x.arc(w / 2, 480, 290, 0, 7); x.fill(); x.shadowBlur = 0; if (img) { x.save(); x.beginPath(); x.arc(w / 2, 480, 262, 0, 7); x.clip(); cover(x, img, w / 2 - 262, 218, 524, 524); x.restore(); } }
return c; }
const SHOP = { design: null, designName: '', p: { title: 'Golden Bee Tee', line: 'OWN', artist: 'Jenni', type: 'TEE', colors: ['BLK', 'SND'], margin: 35, royalty: 0, inclShip: true, desc: '', tags: [], link: '', status: 'entwurf' }, mocks: {}, list: null };
STUDIOS.push({ id: 'shop', cat: 'Community', icon: '🛍', name: 'Shop Studio', like: 'Jenniisdriptees POD-Entwürfe', real: 'API', accepts: ['image', 'text'], build(el) {
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Produktentwürfe für Jenniisdriptees (Print-on-Demand) – keine Änderungen am echten Shop</span></div>
<fieldset class="grp"><legend>Motiv</legend><div class="row"><label class="btn alt">🖼 Motiv<input type="file" accept="image/*" hidden class="ui"></label><input class="gp" aria-label="Motiv-Prompt" value="golden honey bee emblem, bold vector streetwear graphic, drip style, isolated, flat colors"><button class="btn alt gi">✨ Motiv</button></div><span class="dn mut">kein Motiv</span></fieldset>
<fieldset class="grp"><legend>Artikel</legend><div class="row"><input class="ti" aria-label="Titel" style="width:45%"><select class="ln" aria-label="Linie">${Object.entries(LINES).map(([k, v]) => `<option value="${k}">${k} · ${v}</option>`).join('')}</select><input class="ar" aria-label="Künstler" style="width:20%"></div>
<div class="row"><select class="ty" aria-label="Produkttyp">${Object.entries(PT).map(([k, v]) => `<option value="${k}">${v.l}</option>`).join('')}</select><span class="cols"></span></div>
<div class="row"><label>Marge <input type="number" class="mg" min="0" max="80" style="width:60px"> %</label><label>Künstler <input type="number" class="ry" min="0" max="50" style="width:60px"> %</label><label><input type="checkbox" class="is"> Versand einpreisen</label></div><div class="price"></div>
<div class="row"><input class="lk" aria-label="Checkout-/Produktlink (JDT-Shop)" placeholder="Checkout-/Produktlink im JDT-Shop (optional)" style="width:100%"></div></fieldset>
<div class="row"><button class="btn mk">🖼 Mockups</button><button class="btn alt tx">✍ Beschreibung & Tags</button></div><div class="mocks"></div>
<label class="fl">Beschreibung<textarea class="ds" rows="4" aria-label="Beschreibung"></textarea></label><label class="fl">Tags (max. 13) <small class="tc mut"></small><input class="tg" aria-label="Tags"></label>
<div class="row"><span class="sts"></span><button class="btn alt nx">→ Nächster Status</button><button class="btn psv">💾 Entwurf speichern</button><button class="btn alt so" title="Mockup + Text an Social Studio">📣 An Social Studio</button></div>
<small class="mut">Freigabe-Workflow wie im JDT-Studio: Entwurf → Mockup → Review → <b>Freigabe durch Rob</b>. Veröffentlichen (Printify/Shop) passiert nur dort und nur nach Freigabe – STUDIUS ändert keinen Shop.</small>
<fieldset class="grp"><legend>Link-Shop (Workspace <code>projects/shop/products.json</code>)</legend><div class="grid"></div></fieldset>
<div class="credit">Motiv: ${hf(FLUX)} · Texte: ${hf(CHAT)} · Mockups & Preislogik lokal (JDT-Domänenmodell: Basis + Versand, Marge, Künstleranteil, 19 % MwSt, ,99)</div>`;
keep(el); const q = (s) => el.querySelector(s); const P = SHOP.p;
const fill = () => { q('.ti').value = P.title; q('.ln').value = P.line; q('.ar').value = P.artist; q('.ty').value = P.type; q('.mg').value = P.margin; q('.ry').value = P.royalty; q('.is').checked = P.inclShip; q('.ds').value = P.desc; q('.tg').value = P.tags.join(', '); q('.lk').value = P.link; cols(); price(); stat(); };
const read = () => { Object.assign(P, { title: q('.ti').value.trim(), line: q('.ln').value, artist: q('.ar').value.trim(), type: q('.ty').value, margin: +q('.mg').value || 0, royalty: +q('.ry').value || 0, inclShip: q('.is').checked, desc: q('.ds').value.trim(), link: q('.lk').value.trim(), tags: q('.tg').value.split(',').map(s => s.trim().replace(/^#/, '')).filter(Boolean).slice(0, 13) }); P.colors = [...el.querySelectorAll('.cols input:checked')].map(i => i.value); if (!P.colors.length) P.colors = [PT[P.type].colors[0][2]]; };
const cols = () => { const T = PT[q('.ty').value]; q('.cols').innerHTML = T.colors.map(([n, h, c]) => `<label title="${n}"><input type="checkbox" value="${c}" ${P.colors.includes(c) ? 'checked' : ''}><i class="sw" style="background:${h}"></i>${n}</label>`).join(''); };
const price = () => { read(); const T = PT[P.type], r = suggestPrice({ base: T.base, ship: T.ship, margin: P.margin, royalty: P.royalty, inclShip: P.inclShip }); P.price = r.sug; P.sku = `JDT-${P.line}-${P.type}-${slugCode(P.title)}-001`;
q('.price').innerHTML = `<b>${eur(r.sug)}</b> <small class="mut">inkl. 19 % MwSt · Kosten ${eur(r.cost)} · netto ${eur(r.net)} · Gewinn/Stk ${eur(r.profit)} · SKU ${esc(P.sku)}</small>`; q('.tc').textContent = `${P.tags.length}/13`; window.__shopPrice = { type: P.type, ...r, sku: P.sku }; };
const stat = () => { q('.sts').textContent = STAT[P.status]; q('.nx').disabled = P.status === 'freigegeben'; q('.nx').textContent = P.status === 'review' ? '✅ Freigabe durch Rob' : '→ Nächster Status'; };
el.addEventListener('input', (e) => { if (e.target.closest('.grp') && !e.target.matches('.gp,.ui')) price(); }); el.addEventListener('change', (e) => { if (e.target.matches('.ty')) { P.type = e.target.value; P.colors = [PT[P.type].colors[0][2]]; cols(); } price(); });
const setDesign = async (blob, name) => { SHOP.design = blob; SHOP.designName = name || 'design'; q('.dn').innerHTML = `<img src="${URL.createObjectURL(blob)}" alt="Motiv" style="height:60px;vertical-align:middle"> ${esc(SHOP.designName)}`; }; el.__setDesign = setDesign; if (SHOP.design) setDesign(SHOP.design, SHOP.designName);
q('.ui').onchange = () => q('.ui').files[0] && setDesign(q('.ui').files[0], q('.ui').files[0].name);
q('.gi').onclick = async (e) => { e.target.disabled = true; try { const a = await MODULES.image.actions.generate.run({ prompt: q('.gp').value }, { status: m => setS(el, 'Motiv: ' + stTxt(m)) }); await setDesign(await toBlob(a.url), a.name); setS(el, '✔ Motiv erzeugt'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
q('.mk').onclick = async () => { read(); if (!SHOP.design) return setS(el, '⚠ Erst Motiv wählen/erzeugen', true); const T = PT[P.type], du = URL.createObjectURL(SHOP.design), g = q('.mocks'); g.innerHTML = '<div class="mockg"></div>'; SHOP.mocks = {};
for (const code of P.colors) { const [n, hex] = T.colors.find(c => c[2] === code); const c = await mockup(du, P.type, hex), blob = await canvasBlob(c); SHOP.mocks[code] = blob; const u = URL.createObjectURL(blob);
const fig = document.createElement('figure'); fig.innerHTML = `<img src="${u}" alt="Mockup ${esc(T.l)} ${esc(n)}"><figcaption>${esc(T.l)} · ${esc(n)}</figcaption>`; g.firstChild.append(fig);
result(fig, { kind: 'image', mime: 'image/png', blob, url: u, name: `${slug(P.title)}-${P.type}-${code}.png`, path: `projects/shop/${slug(P.title)}/mockup-${P.type}-${code}.png`, studio: 'shop', prompt: P.title, shop: { brief: `${P.title} – ${T.l} von Jenniisdriptees, ${eur(P.price)}`, head: P.title, link: P.link } }); }
if (P.status === 'entwurf') P.status = 'mockup'; stat(); window.__shopMock = { type: P.type, colors: P.colors, n: Object.keys(SHOP.mocks).length }; setS(el, `✔ ${P.colors.length} Mockup(s)`); };
q('.tx').onclick = async (e) => { read(); e.target.disabled = true;
try { const t = await llm(`Du schreibst Produkttexte für die Streetwear-/Print-on-Demand-Marke Jenniisdriptees. Produkt: ${PT[P.type].l} "${P.title}" (Linie: ${LINES[P.line]}${P.artist ? ', Künstler: ' + P.artist : ''}). Motiv: ${q('.gp').value}.
Antworte genau so:
BESCHREIBUNG: <3-4 Sätze, Deutsch, verkaufsstark, Material-/Druckhinweis allgemein halten>
TAGS: <13 kurze Tags, kommagetrennt, ohne #>`, { status: m => setS(el, 'Text: ' + stTxt(m)) });
const d = (t.match(/BESCHREIBUNG\s*:\s*([\s\S]*?)(?:\n\s*TAGS|$)/i)?.[1] || t).trim(), tg = (t.match(/TAGS\s*:\s*(.*)/i)?.[1] || '').split(/[,;]/).map(s => s.trim().replace(/^#/, '')).filter(Boolean).slice(0, 13);
q('.ds').value = d; q('.tg').value = tg.join(', '); price(); window.__shopText = { len: d.length, tags: tg.length }; setS(el, `✔ Beschreibung + ${tg.length} Tags`); badge(el, 'REAL'); }
catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
q('.nx').onclick = () => { const o = Object.keys(STAT); if (P.status === 'review' && !confirm('Freigabe durch Rob für diesen Entwurf setzen? (Veröffentlicht nichts.)')) return; P.status = o[Math.min(o.length - 1, o.indexOf(P.status) + 1)]; if (P.status === 'freigegeben') P.approved = { by: 'Rob', at: Date.now() }; stat(); };
const PJ = 'projects/shop/products.json';
const grid = async (reload) => { if (reload || !SHOP.list) SHOP.list = (await wsJson(PJ, { products: [] })).products || []; const g = q('.grid');
g.innerHTML = SHOP.list.length ? SHOP.list.map(p => `<div class="pcard">${p.mockups?.[0] ? `<img loading="lazy" src="${esc(wsFile(p.mockups[0]))}" alt="${esc(p.title)}">` : ''}<b>${esc(p.title)}</b><small>${esc(PT[p.type]?.l || p.type)} · ${eur(p.price)} · ${STAT[p.status] || p.status}</small>${p.link ? `<a href="${esc(p.link)}" target="_blank" rel="noopener">Zum Shop ↗</a>` : '<small class="mut">kein Shop-Link</small>'}<button class="ib ld" data-id="${esc(p.id)}">✎ laden</button></div>`).join('') : '<small class="mut">Noch keine Produkte im Workspace.</small>';
window.__shopList = SHOP.list.map(p => [p.id, p.status, p.price]); };
q('.grid').onclick = (e) => { const b = e.target.closest('.ld'); if (!b) return; const p = SHOP.list.find(x => x.id === b.dataset.id); if (!p) return; Object.assign(P, structuredClone(p)); fill(); setS(el, 'Geladen: ' + p.title); };
q(".psv").onclick = async (e) => { read(); price(); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); e.target.disabled = true;
try { const id = P.id ||= slug(P.title) + '-' + P.type.toLowerCase(), base = `projects/shop/${slug(P.title)}/`, mocks = [];
if (SHOP.design) { const p = base + 'design.' + ((SHOP.design.type || 'image/png').split('/')[1] || 'png').replace('jpeg', 'jpg'); await upload(p, SHOP.design, 'shop'); P.design = p; }
for (const [code, b] of Object.entries(SHOP.mocks)) { const p = `${base}mockup-${P.type}-${code}.png`; await upload(p, b, 'shop'); mocks.push(p); } if (mocks.length) P.mockups = mocks;
const T = PT[P.type]; P.variants = P.colors.flatMap(c => T.sizes.map(s => `${P.sku}-${slugCode(c, 3)}-${slugCode(s, 4)}`)); P.updated = Date.now(); P.brand = 'Jenniisdriptees';
const list = (await wsJson(PJ, { products: [] })).products || []; const i = list.findIndex(x => x.id === id); i < 0 ? list.push(structuredClone(P)) : (list[i] = structuredClone(P));
await saveJson(PJ, { type: 'studius.shop', v: 1, brand: 'Jenniisdriptees', note: 'Entwürfe – Veröffentlichung nur nach Freigabe durch Rob im JDT-Studio/Printify', products: list }, 'shop'); SHOP.list = list; await grid();
window.__shopSaved = { id, mocks: mocks.length, variants: P.variants.length, status: P.status }; setS(el, `✔ Gespeichert: ${PJ} · ${P.variants.length} Varianten`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } };
q('.so').onclick = () => { const k = Object.keys(SHOP.mocks)[0]; if (!k) return setS(el, '⚠ Erst Mockups rendern', true); window.__bus.sendTo('social', { kind: 'image', blob: SHOP.mocks[k], name: `${slug(P.title)}-mockup.png`, studio: 'shop', prompt: P.title, shop: { brief: `${P.title} – neues ${PT[P.type].l} von Jenniisdriptees für ${eur(P.price)}. ${P.desc.slice(0, 200)}`, head: P.title, link: P.link } }); };
fill(); grid();
}, accept: async (el, a) => { if (a.kind === 'text') { el.querySelector('.ds').value = (a.text ?? await (await toBlob(a.url)).text()).slice(0, 1500); return true; } await el.__setDesign(a.blob || await toBlob(a.url), a.name); return true; } });
/* Module API for agents (Social/Shop templates) */
MODULES.social = { id: 'social', name: 'Social', backend: CHAT, inputs: [{ name: 'prompt', type: 'text' }], outputs: [{ kind: 'text' }],
actions: { captions: { desc: 'Schreibt Social-Media-Captions mit Hashtags (Instagram, TikTok, X, LinkedIn) zu einem Thema. Postet NICHTS', params: { prompt: 'string' }, run: async ({ prompt }, on = {}) => {
const t = await llm(`Schreibe Social-Media-Captions auf Deutsch zu: ${prompt}\nFormat, je eine Zeile:\nInstagram: …\nTikTok: …\nX: … (max. 240 Zeichen)\nLinkedIn: …\nJeweils mit passenden Hashtags.`, on); return { kind: 'text', mime: 'text/plain', text: t, name: `captions-${Date.now()}.txt`, studio: 'social', prompt }; } } } };
export { bucket, wsFile, toBlob, slug, ts, upload, wsList, wsJson, saveJson, llm, dl, canvasBlob, loadImg, cover, wrap, avOptions, PT, LINES, STAT, slugCode, eur, SOC, PLAT };