Add embeddable /embed widget and copy-paste snippet.

This commit is contained in:
b1rdmania
2025-12-18 20:58:35 +00:00
parent e33cd26238
commit d0be58296e
7 changed files with 631 additions and 2 deletions
+20
View File
@@ -16,6 +16,26 @@ MOTIF is a small experiment in **music-as-code**: treat MIDI as structural data,
Note: if the backend isnt deployed/configured for the demo environment, search/fetch wont work from the hosted URL. Run locally for the full experience.
## Use on your website (embed)
MOTIF includes an embeddable widget page at **`/embed`**. It generates audio in the users browser (no audio files needed).
Example:
```html
<iframe
src="https://YOUR_DOMAIN/embed?song=Hotel%20California"
width="420"
height="260"
style="border:0;border-radius:12px;overflow:hidden"
allow="autoplay"
></iframe>
```
### Embed parameters (v1)
- **`song`**: the query to load (e.g. `Hotel%20California`)\n+- **`volume`**: preview volume `0..1` (optional)\n+- **`motifVolume`**: motif volume `0..1` (optional)
Notes:\n- Autoplay is best-effort; iOS/Safari requires a user gesture before sound.\n
## Features
- **MIDI search** (currently BitMidi; additional sources optional)
+223
View File
@@ -0,0 +1,223 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>MOTIF Embed</title>
<style>
:root {
--bg: #0b0b0b;
--surface: #151515;
--border: #2a2a2a;
--text: #eaeaea;
--text-dim: #a0a0a0;
--accent: #00ff88;
--accent2: #ffaa44;
--radius: 10px;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
background:
radial-gradient(900px 420px at 50% -180px, rgba(0, 255, 136, 0.10), transparent 60%),
radial-gradient(900px 420px at 110% 20%, rgba(255, 170, 68, 0.08), transparent 55%),
var(--bg);
color: var(--text);
padding: 14px;
}
.card {
border: 1px solid var(--border);
background: rgba(21, 21, 21, 0.88);
border-radius: var(--radius);
box-shadow: 0 18px 80px rgba(0,0,0,0.55);
overflow: hidden;
}
header {
padding: 12px 12px 10px 12px;
border-bottom: 1px solid rgba(255,255,255,0.06);
display: flex;
align-items: center;
gap: 10px;
}
.dot {
width: 9px; height: 9px; border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 18px rgba(0,255,136,0.25);
}
h1 {
margin: 0;
font-size: 14px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.subtitle {
margin-left: auto;
color: var(--text-dim);
font-size: 12px;
}
main { padding: 12px; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
input[type="text"] {
flex: 1;
min-width: 160px;
background: rgba(0,0,0,0.25);
border: 1px solid var(--border);
color: var(--text);
border-radius: 10px;
padding: 10px 10px;
font-size: 16px; /* iOS zoom prevention */
}
button {
border-radius: 10px;
border: 1px solid var(--border);
background: #1b1b1b;
color: var(--text);
padding: 10px 12px;
font-family: inherit;
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, box-shadow 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: #444;
box-shadow: 0 10px 40px rgba(0,0,0,0.45);
}
button:disabled { opacity: 0.45; cursor: not-allowed; transform: none; box-shadow: none; }
button.primary {
background: var(--accent);
color: #000;
border-color: rgba(0,255,136,0.75);
font-weight: 800;
}
.status {
margin-top: 10px;
padding: 10px 12px;
border-left: 3px solid var(--accent);
background: rgba(0,0,0,0.22);
border-radius: 10px;
font-size: 12px;
color: var(--text-dim);
min-height: 18px;
}
.section {
margin-top: 12px;
border-top: 1px solid rgba(255,255,255,0.06);
padding-top: 12px;
}
.sectionTitle {
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text);
margin: 0 0 8px 0;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
@media (max-width: 440px) {
.controls { grid-template-columns: 1fr; }
}
.panel {
border: 1px solid rgba(255,255,255,0.08);
border-radius: 12px;
padding: 10px;
background: rgba(0,0,0,0.18);
}
.panel h2 {
margin: 0 0 6px 0;
font-size: 13px;
color: var(--accent);
}
.panel p {
margin: 0 0 10px 0;
color: var(--text-dim);
font-size: 12px;
}
.panel.motif h2 { color: var(--accent2); }
.btnRow { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.btnRow button { flex: 1; min-width: 110px; }
.sliderRow { display: flex; gap: 8px; align-items: center; margin-top: 8px; }
.sliderRow label { font-size: 12px; color: var(--text-dim); min-width: 52px; }
.sliderRow input[type="range"] { flex: 1; }
.footnote {
margin-top: 10px;
font-size: 11px;
color: rgba(255,255,255,0.55);
}
</style>
</head>
<body>
<div class="card">
<header>
<div class="dot"></div>
<h1>MOTIF</h1>
<div class="subtitle">Embed</div>
</header>
<main>
<div class="row">
<input id="songInput" type="text" placeholder="Song (e.g. Hotel California)" />
<button id="loadBtn" class="primary">Load</button>
<button id="nextBtn" disabled>Next</button>
</div>
<div id="status" class="status">Ready.</div>
<div class="section">
<p class="sectionTitle">Playback</p>
<div class="controls">
<div class="panel">
<h2>Preview</h2>
<p>Play the original MIDI (piano).</p>
<div class="btnRow">
<button id="previewPlayBtn" disabled class="primary">Play</button>
<button id="previewStopBtn" disabled>Stop</button>
</div>
<div class="sliderRow">
<label for="previewVol">Volume</label>
<input id="previewVol" type="range" min="0" max="1" step="0.01" value="0.8" />
</div>
</div>
<div class="panel motif">
<h2>Variation</h2>
<p>Generate a chiptune-ish Motif.</p>
<div class="btnRow">
<button id="motifPlayBtn" disabled class="primary">Generate &amp; Play</button>
<button id="motifStopBtn" disabled>Stop</button>
</div>
<div class="sliderRow">
<label for="motifVol">Volume</label>
<input id="motifVol" type="range" min="0" max="1" step="0.01" value="0.35" />
</div>
</div>
</div>
<div class="footnote">
Note: autoplay is best-effort; iOS/Safari requires a tap before sound.
</div>
</div>
</main>
</div>
<script type="module" src="/src/embed.ts"></script>
</body>
</html>
+70
View File
@@ -541,6 +541,55 @@
transition: width 0.1s linear;
}
/* Use on your website */
.embed-card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: calc(var(--spacing-unit) * 3);
box-shadow: var(--shadow-md);
}
.embed-row {
display: flex;
gap: calc(var(--spacing-unit) * 1.5);
align-items: flex-start;
flex-wrap: wrap;
}
.embed-row button {
flex-shrink: 0;
}
.codeblock {
flex: 1;
min-width: 260px;
margin: 0;
padding: calc(var(--spacing-unit) * 2);
border-radius: calc(var(--radius) + 2px);
background: rgba(0,0,0,0.35);
border: 1px solid rgba(255,255,255,0.08);
overflow: auto;
box-shadow: var(--shadow-sm);
}
.codeblock code {
font-size: 12px;
color: rgba(255,255,255,0.85);
white-space: pre;
}
.embed-hint {
margin-top: calc(var(--spacing-unit) * 1.5);
color: var(--color-text-dim);
font-size: 12px;
}
.embed-hint strong {
color: var(--color-text);
font-weight: 600;
}
.copy-toast {
margin-left: auto;
font-size: 12px;
color: rgba(0,255,136,0.85);
display: none;
}
.engine-selector {
margin-top: 10px;
font-size: 0.9em;
@@ -647,6 +696,27 @@
</div>
</div>
</div>
<div class="section" id="embedSection" style="display:none;">
<div class="section-header">
<h3 class="section-title">Use on your website</h3>
<p class="section-subtitle">Embed this generator as a widget.</p>
</div>
<div class="divider"></div>
<div class="embed-card">
<div class="embed-row">
<pre class="codeblock"><code id="embedCode">&lt;iframe src=&quot;...&quot;&gt;&lt;/iframe&gt;</code></pre>
<div style="display:flex; flex-direction:column; gap: calc(var(--spacing-unit) * 1.5);">
<button id="copyEmbedBtn" class="primary" type="button">Copy embed</button>
<span id="copyToast" class="copy-toast">Copied</span>
</div>
</div>
<div class="embed-hint">
<strong>Tip:</strong> iOS/Safari requires a tap before audio can start. Add <code>allow=&quot;autoplay&quot;</code> and expect a user gesture.
</div>
</div>
</div>
</div>
</div>
+242
View File
@@ -0,0 +1,242 @@
import { MIDIService } from './services/MIDIService';
import { MIDIParser } from './midi/MIDIParser';
import { SoundfontMIDIPlayer } from './synthesis/SoundfontMIDIPlayer';
import { MotifEngine } from './core/MotifEngine';
import type { NoteEvent } from './types';
type SearchResult = {
title: string;
midiUrl: string;
confidence: number;
};
function qs<T extends HTMLElement>(id: string): T {
const el = document.getElementById(id);
if (!el) throw new Error(`Missing element #${id}`);
return el as T;
}
function getParam(name: string): string | null {
return new URLSearchParams(window.location.search).get(name);
}
function setStatus(msg: string): void {
qs<HTMLElement>('status').textContent = msg;
}
function clamp01(v: number): number {
return Math.max(0, Math.min(1, v));
}
async function main(): Promise<void> {
const songInput = qs<HTMLInputElement>('songInput');
const loadBtn = qs<HTMLButtonElement>('loadBtn');
const nextBtn = qs<HTMLButtonElement>('nextBtn');
const previewPlayBtn = qs<HTMLButtonElement>('previewPlayBtn');
const previewStopBtn = qs<HTMLButtonElement>('previewStopBtn');
const previewVol = qs<HTMLInputElement>('previewVol');
const motifPlayBtn = qs<HTMLButtonElement>('motifPlayBtn');
const motifStopBtn = qs<HTMLButtonElement>('motifStopBtn');
const motifVol = qs<HTMLInputElement>('motifVol');
const midiService = new MIDIService();
const audioContext = new AudioContext();
const previewPlayer = new SoundfontMIDIPlayer(audioContext);
const motifEngine = new MotifEngine();
let results: SearchResult[] = [];
let selectedIndex = 0;
let currentEvents: NoteEvent[] | null = null;
let isMotifPlaying = false;
function disableAll(): void {
previewPlayBtn.disabled = true;
previewStopBtn.disabled = true;
motifPlayBtn.disabled = true;
motifStopBtn.disabled = true;
nextBtn.disabled = true;
}
function stopEverything(): void {
previewPlayer.stop();
motifEngine.stop();
previewPlayBtn.disabled = currentEvents === null;
previewStopBtn.disabled = true;
motifStopBtn.disabled = true;
isMotifPlaying = false;
}
async function loadIndex(index: number): Promise<void> {
if (index < 0 || index >= results.length) return;
selectedIndex = index;
const r = results[selectedIndex];
setStatus(`Loading: ${r.title}`);
disableAll();
try {
const midiBuffer = await midiService.fetchMIDI(r.midiUrl);
if (!midiBuffer) throw new Error('Fetch failed');
const events = MIDIParser.parseMIDI(midiBuffer);
currentEvents = events;
await previewPlayer.load(events);
previewPlayer.setVolume(clamp01(parseFloat(previewVol.value)));
setStatus(`Ready: ${r.title}`);
previewPlayBtn.disabled = false;
motifPlayBtn.disabled = false;
nextBtn.disabled = results.length <= 1;
} catch (e) {
currentEvents = null;
setStatus(`Load error: ${e instanceof Error ? e.message : 'Unknown error'}`);
}
}
async function doSearch(): Promise<void> {
const query = songInput.value.trim();
if (!query) return;
stopEverything();
disableAll();
setStatus('Searching…');
loadBtn.disabled = true;
try {
const r = await midiService.search(query);
results = r.map((x: any) => ({
title: x.title,
midiUrl: x.midiUrl,
confidence: x.confidence,
}));
if (results.length === 0) {
setStatus('No results found.');
return;
}
// Pick best by confidence (backend already sorts, but keep safe)
results.sort((a, b) => (b.confidence ?? 0) - (a.confidence ?? 0));
selectedIndex = 0;
setStatus(`Found ${results.length}. Loading best match…`);
await loadIndex(0);
} catch (e) {
setStatus(`Search error: ${e instanceof Error ? e.message : 'Unknown error'}`);
} finally {
loadBtn.disabled = false;
}
}
loadBtn.addEventListener('click', () => void doSearch());
songInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') void doSearch();
});
nextBtn.addEventListener('click', () => {
if (results.length <= 1) return;
const next = (selectedIndex + 1) % results.length;
void loadIndex(next);
});
previewVol.addEventListener('input', (e) => {
const v = clamp01(parseFloat((e.target as HTMLInputElement).value));
previewPlayer.setVolume(v);
});
motifVol.addEventListener('input', (e) => {
const v = clamp01(parseFloat((e.target as HTMLInputElement).value));
motifEngine.setVolume(v);
});
previewPlayBtn.addEventListener('click', async () => {
if (!currentEvents) return;
try {
motifEngine.stop();
isMotifPlaying = false;
await previewPlayer.play();
previewPlayBtn.disabled = true;
previewStopBtn.disabled = false;
motifStopBtn.disabled = true;
setStatus('Playing preview…');
} catch (e) {
setStatus(`Preview error: ${e instanceof Error ? e.message : 'Unknown error'}`);
}
});
previewStopBtn.addEventListener('click', () => {
previewPlayer.stop();
previewPlayBtn.disabled = currentEvents === null;
previewStopBtn.disabled = true;
setStatus('Preview stopped.');
});
motifPlayBtn.addEventListener('click', async () => {
if (!currentEvents) return;
try {
// Stop preview and generate variation
previewPlayer.stop();
previewPlayBtn.disabled = false;
previewStopBtn.disabled = true;
motifPlayBtn.disabled = true;
setStatus('Generating variation…');
await motifEngine.generateFromMIDI(currentEvents, 'procedural');
motifEngine.setVolume(clamp01(parseFloat(motifVol.value)));
await motifEngine.play();
isMotifPlaying = true;
motifStopBtn.disabled = false;
setStatus('Playing variation…');
} catch (e) {
motifPlayBtn.disabled = false;
setStatus(`Motif error: ${e instanceof Error ? e.message : 'Unknown error'}`);
}
});
motifStopBtn.addEventListener('click', () => {
motifEngine.stop();
isMotifPlaying = false;
motifStopBtn.disabled = true;
motifPlayBtn.disabled = currentEvents === null;
setStatus('Variation stopped.');
});
// Initialize from query params
const song = getParam('song');
const volume = getParam('volume');
const motifVolume = getParam('motifVolume');
if (volume) {
previewVol.value = String(clamp01(parseFloat(volume)));
previewPlayer.setVolume(parseFloat(previewVol.value));
}
if (motifVolume) {
motifVol.value = String(clamp01(parseFloat(motifVolume)));
}
if (song) {
songInput.value = song;
setStatus('Loading from URL…');
// best-effort: do not autoplay audio, just load the MIDI
void doSearch();
} else {
setStatus('Ready. Add ?song=Hotel%20California to auto-load.');
}
// Defensive: stop audio when the iframe/tab is hidden
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
stopEverything();
if (isMotifPlaying) {
motifPlayBtn.disabled = currentEvents === null;
}
}
});
}
void main();
+65 -2
View File
@@ -41,6 +41,12 @@ class MotifApp {
private nextResultBtn!: HTMLButtonElement;
// Embed snippet UI
private embedSection: HTMLElement | null = null;
private embedCodeEl: HTMLElement | null = null;
private copyEmbedBtn: HTMLButtonElement | null = null;
private copyToast: HTMLElement | null = null;
private searchResults: any[] = [];
private selectedResultIndex = 0;
private currentMIDI: { events: NoteEvent[], metadata: any } | null = null;
@@ -86,6 +92,12 @@ class MotifApp {
this.motifDuration = document.getElementById('motifDuration')!;
this.nextResultBtn = document.getElementById('nextResultBtn') as HTMLButtonElement;
// Optional embed UI (only present on main page)
this.embedSection = document.getElementById('embedSection');
this.embedCodeEl = document.getElementById('embedCode');
this.copyEmbedBtn = document.getElementById('copyEmbedBtn') as HTMLButtonElement | null;
this.copyToast = document.getElementById('copyToast');
}
private setupEventListeners(): void {
@@ -121,6 +133,9 @@ class MotifApp {
this.motifProgressBar.addEventListener('change', seekHandler);
this.nextResultBtn.addEventListener('click', () => this.handleNextResult());
// Embed snippet copy
this.copyEmbedBtn?.addEventListener('click', () => void this.copyEmbedSnippet());
}
private async handleSearch(): Promise<void> {
@@ -237,6 +252,8 @@ class MotifApp {
<strong>Tempo:</strong> ${metadata.tempo}bpm
`;
this.updateEmbedSnippet(result.title);
this.playerSection.classList.add('visible');
this.enablePlayerControls();
this.updateStatus('MIDI loaded. You can now preview or generate.');
@@ -279,8 +296,8 @@ class MotifApp {
this.motifBtn.disabled = true;
console.log('Calling generateFromMIDI with', this.currentMIDI.events.length, 'events');
// Use the current MIDI data directly in passthrough mode
await this.motifEngine.generateFromMIDI(this.currentMIDI.events, 'passthrough');
// Generate a variation using the procedural role-mapping mode
await this.motifEngine.generateFromMIDI(this.currentMIDI.events, 'procedural');
console.log('Calling motifEngine.play()');
await this.motifEngine.play();
@@ -375,6 +392,52 @@ class MotifApp {
private updateStatus(message: string): void {
this.status.textContent = message;
}
private updateEmbedSnippet(songTitle: string): void {
if (!this.embedSection || !this.embedCodeEl) return;
const origin = window.location.origin;
const url = `${origin}/embed?song=${encodeURIComponent(songTitle)}`;
const snippet = `<iframe\n src=\"${url}\"\n width=\"420\"\n height=\"260\"\n style=\"border:0;border-radius:12px;overflow:hidden\"\n allow=\"autoplay\"\n></iframe>`;
this.embedCodeEl.textContent = snippet;
this.embedSection.style.display = 'block';
if (this.copyToast) this.copyToast.style.display = 'none';
}
private async copyEmbedSnippet(): Promise<void> {
if (!this.embedCodeEl) return;
const text = this.embedCodeEl.textContent || '';
if (!text.trim()) return;
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
// Fallback
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.focus();
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
if (this.copyToast) {
this.copyToast.style.display = 'inline';
window.setTimeout(() => {
if (this.copyToast) this.copyToast.style.display = 'none';
}, 1200);
}
} catch {
this.updateStatus('Copy failed. Select the snippet and copy manually.');
}
}
}
// Make app globally available for onclick handlers
+4
View File
@@ -22,6 +22,10 @@
"src": "/health",
"dest": "server/src/server.ts"
},
{
"src": "/embed",
"dest": "/embed.html"
},
{ "handle": "filesystem" },
{
"src": "/(.*)",
+7
View File
@@ -1,4 +1,5 @@
import { defineConfig } from 'vite'
import { resolve } from 'node:path'
export default defineConfig({
server: {
@@ -7,5 +8,11 @@ export default defineConfig({
build: {
outDir: 'dist',
sourcemap: true,
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
embed: resolve(__dirname, 'embed.html'),
},
},
},
})