Group duplicate effects and add loop variants

This commit is contained in:
Hermes Agent
2026-05-21 00:31:53 +02:00
parent 23391a2d3e
commit fda46887ed
5 changed files with 482 additions and 67 deletions

View File

@@ -1,7 +1,9 @@
(() => {
'use strict';
const STORAGE_KEY = 'arcana-fx-sets-v2';
// Bumped: v3 stores group ids (with optional variant id) instead of raw paths.
const STORAGE_KEY = 'arcana-fx-sets-v3';
const LEGACY_KEY = 'arcana-fx-sets-v2';
const els = {
grid: document.getElementById('grid'),
@@ -35,19 +37,22 @@
};
const state = {
effects: [],
byPath: new Map(),
groups: [],
groupsById: new Map(),
pathToGroup: new Map(), // legacy path -> { groupId, variantId }
categories: [],
activeCategory: 'all',
search: '',
busy: false,
streamOn: false,
active: [],
sets: loadSets(),
sets: [],
currentSetId: null,
lastVariantPerGroup: new Map(), // anti-immediate-repeat memory
};
if (!state.sets.length) state.sets = [{ id: uid(), name: 'Session Favorites', paths: [] }];
state.sets = loadSets();
if (!state.sets.length) state.sets = [{ id: uid(), name: 'Session Favorites', items: [] }];
state.currentSetId = state.sets[0].id;
function uid() { return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; }
@@ -64,14 +69,54 @@
}
function loadSets() {
// Prefer v3. If absent but v2 exists, migrate later (after groups load).
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
return Array.isArray(parsed) ? parsed.filter((s) => s && s.id && s.name && Array.isArray(s.paths)) : [];
} catch { return []; }
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
return parsed.filter((s) => s && s.id && s.name && Array.isArray(s.items));
}
}
} catch { /* fall through */ }
return [];
}
function saveSets() { localStorage.setItem(STORAGE_KEY, JSON.stringify(state.sets)); }
/**
* Migrate v2 (path-based) favourites to v3 (group/variant-based) using
* the path index from the freshly-loaded groups. Drops items that no
* longer resolve (effect was renamed or removed from the share).
*/
function migrateLegacySetsIfNeeded() {
if (state.sets.some((s) => s.items && s.items.length)) return; // already populated
if (localStorage.getItem(STORAGE_KEY)) return; // v3 already present
let legacy;
try {
const raw = localStorage.getItem(LEGACY_KEY);
if (!raw) return;
legacy = JSON.parse(raw);
} catch { return; }
if (!Array.isArray(legacy) || !legacy.length) return;
const migrated = legacy.map((s) => {
const items = Array.isArray(s.paths) ? s.paths
.map((p) => state.pathToGroup.get(p))
.filter(Boolean)
// de-dup: same group+variant pair shouldn't appear twice
.filter((ref, i, arr) => arr.findIndex((r) => r.groupId === ref.groupId && r.variantId === ref.variantId) === i)
: [];
return { id: s.id || uid(), name: s.name || 'Set', items };
}).filter((s) => s.name);
if (migrated.length) {
state.sets = migrated;
state.currentSetId = state.sets[0].id;
saveSets();
}
}
async function fetchJson(url, opts) {
const res = await fetch(url, opts);
const text = await res.text();
@@ -94,39 +139,68 @@
}).join('');
}
function visibleEffects() {
function groupMatches(group, q) {
if (!q) return true;
const variantNames = group.variants.map((v) => v.name).join(' ');
const variantPaths = group.variants.flatMap((v) => v.allPaths || []).join(' ');
const tagText = (group.tags || []).join(' ');
const haystack = `${group.name} ${group.category} ${tagText} ${variantNames} ${variantPaths}`
.replace(/[/.\\_-]+/g, ' ')
.toLowerCase();
return haystack.includes(q);
}
function visibleGroups() {
const q = state.search.trim().toLowerCase();
return state.effects.filter((e) => {
if (state.activeCategory !== 'all' && e.category !== state.activeCategory) return false;
if (!q) return true;
const haystack = `${e.name} ${e.category} ${e.type} ${e.path.replace(/[/.\\_-]+/g, ' ')}`.toLowerCase();
return haystack.includes(q);
return state.groups.filter((g) => {
if (state.activeCategory !== 'all' && g.category !== state.activeCategory) return false;
return groupMatches(g, q);
}).slice(0, 240);
}
function tile(effect, { inSetView = false } = {}) {
function groupInCurrentSet(groupId) {
const set = currentSet();
const inSet = set.paths.includes(effect.path);
return set.items.some((it) => it.groupId === groupId);
}
function variantsButtons(group) {
if (!group.hasNumberedVariants) return '';
const buttons = group.variants
.filter((v) => v.number != null)
.map((v) => `<button class="variant-btn" type="button" data-action="play-variant" data-variant="${escapeHtml(v.id)}" title="Play take ${v.number}">${v.number}</button>`)
.join('');
return `<div class="variant-row">${buttons}</div>`;
}
function tile(group, { inSetView = false } = {}) {
const inSet = groupInCurrentSet(group.id);
const variantTagText = group.hasNumberedVariants ? `${group.variantCount} takes` : null;
const tags = [
group.category,
group.isLoop ? 'LOOP' : null,
variantTagText,
].filter(Boolean);
const tagHtml = tags.map((t) => `<span class="tag${t === 'LOOP' ? ' tag-loop' : ''}">${escapeHtml(t)}</span>`).join('');
return `
<article class="tile" data-path="${escapeHtml(effect.path)}">
<button class="play-hit" type="button" data-action="play" title="Play ${escapeHtml(effect.name)}">
<div class="name">${escapeHtml(effect.name)}</div>
<div class="meta">
<span class="tag">${escapeHtml(effect.category)}</span>
<span class="tag">${escapeHtml(effect.type.toUpperCase())}</span>
</div>
<article class="tile${group.isLoop ? ' is-loop' : ''}" data-group-id="${escapeHtml(group.id)}">
<button class="play-hit" type="button" data-action="play" title="Play ${escapeHtml(group.name)}">
<div class="name">${escapeHtml(group.name)}${group.isLoop ? ' <span class="loop-glyph" aria-hidden="true">∞</span>' : ''}</div>
<div class="meta">${tagHtml}</div>
</button>
${variantsButtons(group)}
<div class="tile-actions">
${inSetView ? `<button class="mini danger" data-action="remove-set" type="button">Remove</button>` : `<button class="mini ${inSet ? 'ok' : ''}" data-action="toggle-set" type="button">${inSet ? 'In set' : '+ Set'}</button>`}
${inSetView
? `<button class="mini danger" data-action="remove-set" type="button">Remove</button>`
: `<button class="mini ${inSet ? 'ok' : ''}" data-action="toggle-set" type="button">${inSet ? 'In set' : '+ Set'}</button>`}
</div>
</article>`;
}
function renderGrid() {
const filtered = visibleEffects();
const filtered = visibleGroups();
els.empty.hidden = filtered.length !== 0;
els.countLabel.textContent = `${state.effects.length} effects · showing ${filtered.length}`;
els.grid.innerHTML = filtered.map((e) => tile(e)).join('');
els.countLabel.textContent = `${state.groups.length} sounds · showing ${filtered.length}`;
els.grid.innerHTML = filtered.map((g) => tile(g)).join('');
renderSet();
}
@@ -138,21 +212,23 @@
function renderSet() {
renderSetsSelect();
const set = currentSet();
const effects = set.paths.map((p) => state.byPath.get(p)).filter(Boolean);
const groups = set.items
.map((it) => state.groupsById.get(it.groupId))
.filter(Boolean);
els.setTitle.textContent = set.name;
els.setCount.textContent = `${effects.length} item${effects.length === 1 ? '' : 's'}`;
els.setEmpty.hidden = effects.length > 0;
els.setGrid.innerHTML = effects.map((e) => tile(e, { inSetView: true })).join('');
els.setCount.textContent = `${groups.length} item${groups.length === 1 ? '' : 's'}`;
els.setEmpty.hidden = groups.length > 0;
els.setGrid.innerHTML = groups.map((g) => tile(g, { inSetView: true })).join('');
}
function renderActive() {
els.nowCount.textContent = String(state.active.length);
els.activeEmpty.hidden = state.active.length > 0;
els.activeList.innerHTML = state.active.map((a) => `
<div class="active-row">
<div class="active-row${a.loop ? ' is-loop' : ''}">
<div>
<strong>${escapeHtml(a.name)}</strong>
<span>${escapeHtml(a.category)} · ${Math.round((a.ageMs || 0) / 1000)}s</span>
<strong>${escapeHtml(a.name)}${a.loop ? ' <span class="loop-glyph">∞</span>' : ''}</strong>
<span>${escapeHtml(a.category || '')} · ${Math.round((a.ageMs || 0) / 1000)}s${a.loop ? ' · looping' : ''}</span>
${a.error ? `<em>${escapeHtml(a.error)}</em>` : ''}
</div>
<button class="mini danger" data-stop-id="${escapeHtml(a.id)}">Stop</button>
@@ -166,32 +242,73 @@
} catch (err) { console.warn('config load failed', err); }
}
function indexGroups(groups) {
state.groups = groups;
state.groupsById = new Map(groups.map((g) => [g.id, g]));
state.pathToGroup = new Map();
for (const g of groups) {
for (const v of g.variants) {
for (const p of (v.allPaths || [])) {
state.pathToGroup.set(p, { groupId: g.id, variantId: v.id });
}
}
}
}
async function loadEffects({ force = false } = {}) {
setStatus('busy', force ? 'Rescanning library…' : 'Loading effects…');
try {
const data = await fetchJson(force ? '/api/effects?refresh=1' : '/api/effects');
state.effects = Array.isArray(data.effects) ? data.effects : [];
state.byPath = new Map(state.effects.map((e) => [e.path, e]));
indexGroups(Array.isArray(data.groups) ? data.groups : []);
state.categories = Array.isArray(data.categories) ? data.categories : [];
if (!state.categories.includes(state.activeCategory) && state.activeCategory !== 'all') state.activeCategory = 'all';
migrateLegacySetsIfNeeded();
renderCategories();
renderGrid();
setStatus('ok', `Ready — ${state.effects.length} effects`);
setStatus('ok', `Ready — ${state.groups.length} sounds (${data.count} files)`);
} catch (err) {
console.error(err);
setStatus('err', `Load failed: ${err.message}`);
}
}
async function play(effectPath) {
setStatus('busy', `Injecting — ${effectPath.split('/').pop()}`);
/**
* Picks a variant for a group, biased away from the last one played from
* the same group, so consecutive presses don't trigger the same take.
*/
function pickVariantForGroup(group) {
const variants = group.variants;
if (!variants.length) return null;
if (variants.length === 1) return variants[0];
const last = state.lastVariantPerGroup.get(group.id);
const pool = variants.filter((v) => v.id !== last);
const picked = pool[Math.floor(Math.random() * pool.length)] || variants[0];
state.lastVariantPerGroup.set(group.id, picked.id);
return picked;
}
async function playGroup(groupId, variantId) {
const group = state.groupsById.get(groupId);
if (!group) { setStatus('err', 'Group not found'); return; }
let chosenVariantId = variantId;
if (!chosenVariantId) {
const picked = pickVariantForGroup(group);
if (!picked) { setStatus('err', 'No variants'); return; }
chosenVariantId = picked.id;
} else {
state.lastVariantPerGroup.set(groupId, chosenVariantId);
}
const label = group.name + (group.isLoop ? ' (loop)' : '');
setStatus('busy', `Injecting — ${label}`);
try {
const res = await fetchJson('/api/play', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: effectPath }),
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ groupId, variantId: chosenVariantId }),
});
state.active = (res.stream && res.stream.active) || state.active;
renderActive();
setStatus('ok', `Injected — ${(res.injected && res.injected.name) || effectPath}`);
setStatus('ok', `Injected — ${(res.injected && res.injected.name) || label}`);
} catch (err) {
console.error(err);
setStatus('err', `Play failed: ${err.message}`);
@@ -242,17 +359,18 @@
} catch { /* status polling is best-effort */ }
}
function toggleSet(effectPath) {
function toggleSet(groupId) {
const set = currentSet();
const idx = set.paths.indexOf(effectPath);
if (idx >= 0) set.paths.splice(idx, 1); else set.paths.push(effectPath);
const idx = set.items.findIndex((it) => it.groupId === groupId);
if (idx >= 0) set.items.splice(idx, 1);
else set.items.push({ groupId });
saveSets();
renderGrid();
}
function removeFromSet(effectPath) {
function removeFromSet(groupId) {
const set = currentSet();
set.paths = set.paths.filter((p) => p !== effectPath);
set.items = set.items.filter((it) => it.groupId !== groupId);
saveSets();
renderGrid();
}
@@ -260,7 +378,7 @@
function newSet() {
const name = prompt('Set name?', 'New Encounter');
if (!name) return;
const set = { id: uid(), name: name.trim(), paths: [] };
const set = { id: uid(), name: name.trim(), items: [] };
state.sets.push(set);
state.currentSetId = set.id;
saveSets();
@@ -293,10 +411,13 @@
const action = e.target.closest('[data-action]');
const tileEl = e.target.closest('.tile');
if (!action || !tileEl) return;
const path = tileEl.dataset.path;
if (action.dataset.action === 'play') play(path);
if (action.dataset.action === 'toggle-set') toggleSet(path);
if (action.dataset.action === 'remove-set') removeFromSet(path);
const groupId = tileEl.dataset.groupId;
if (!groupId) return;
const a = action.dataset.action;
if (a === 'play') playGroup(groupId);
else if (a === 'play-variant') playGroup(groupId, action.dataset.variant);
else if (a === 'toggle-set') toggleSet(groupId);
else if (a === 'remove-set') removeFromSet(groupId);
}
els.grid.addEventListener('click', gridClick);