feat: faster, correct preset editor; default presets use their own pattern

- Editing a preset can change its pattern (the dropdown was disabled).
- on, off and rainbow are built-in patterns and are always listed, so the
  editor no longer falls back to the first pattern (aurora) for them.
- The editor loads the pattern names once and only the selected pattern's
  definition (new GET /patterns/names and GET /patterns/<name>).
- A shared GET cache (fetch_cache.js) reuses profile, palette, zone, preset,
  group and pattern lookups; any write clears it and entries expire at 30 s.
- The seeded rainbow preset uses the rainbow pattern.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Sonnet 5.5 committed 2026-11-10 01:46:11 +13:00
1 parent d4118072f6
commit 38162d4b89
9 files changed
+189 -81

No files matched your search

+81 -73
View File
@@ -62,7 +62,24 @@ const getCurrentProfileData = async () => {
}
};
const getCurrentProfilePaletteColors = async () => {
// Share one request among callers in a burst (opening the editor asks for the same data several
// times); the result is reused for ttlMs so a later change is still picked up.
const dedupeFetch = (fn, ttlMs) => {
let pending = null;
let doneAt = 0;
return () => {
if (pending && (doneAt === 0 || Date.now() - doneAt < ttlMs)) return pending;
doneAt = 0;
pending = fn();
pending.then(
() => { doneAt = Date.now(); },
() => { pending = null; },
);
return pending;
};
};
const getCurrentProfilePaletteColors = dedupeFetch(async () => {
const profileData = await getCurrentProfileData();
const profile = profileData && profileData.profile;
const paletteId = profile && (profile.palette_id || profile.paletteId);
@@ -75,7 +92,7 @@ const getCurrentProfilePaletteColors = async () => {
} catch (_) {
return [];
}
};
}, 2000);
const resolveColorsWithPaletteRefs = (colors, paletteRefs, paletteColors) => {
const baseColors = Array.isArray(colors) ? colors : [];
@@ -768,21 +785,19 @@ document.addEventListener('DOMContentLoaded', () => {
// Update color section visibility based on pattern
updateColorSectionVisibility();
// Make name and pattern read-only when editing (not when creating new)
// Name is read-only when editing (not when creating new); the pattern can be changed
const isEditing = currentEditId !== null;
presetNameInput.disabled = isEditing;
presetPatternInput.disabled = isEditing;
presetPatternInput.disabled = false;
if (isEditing) {
presetNameInput.style.backgroundColor = '#2a2a2a';
presetNameInput.style.cursor = 'not-allowed';
presetPatternInput.style.backgroundColor = '#2a2a2a';
presetPatternInput.style.cursor = 'not-allowed';
} else {
presetNameInput.style.backgroundColor = '';
presetNameInput.style.cursor = '';
presetPatternInput.style.backgroundColor = '';
presetPatternInput.style.cursor = '';
}
presetPatternInput.style.backgroundColor = '';
presetPatternInput.style.cursor = '';
// Get pattern config to map descriptive names back to n keys
const patternConfig = cachedPatterns && cachedPatterns[patternName];
@@ -1004,59 +1019,58 @@ document.addEventListener('DOMContentLoaded', () => {
return payload;
};
const normalizePatternMap = (raw) => {
if (!raw) return {};
if (typeof raw === 'object' && !Array.isArray(raw)) {
// Support wrapped payloads like { patterns: {...} }.
if (raw.patterns && typeof raw.patterns === 'object' && !Array.isArray(raw.patterns)) {
return raw.patterns;
}
return raw;
}
if (Array.isArray(raw)) {
// Support list payloads like [{name: "blink", ...}, ...].
return raw.reduce((acc, item, idx) => {
if (item && typeof item === 'object') {
const name = item.name || item.id || String(idx);
acc[String(name)] = item;
}
return acc;
}, {});
}
return {};
// The pattern names are fetched once per page and each pattern's definition only when it is
// selected (cachedPatterns[name]). patterns.js fires "patternsChanged" after it creates or edits
// a pattern, which drops both caches.
let patternNamesPromise = null;
const definitionRequests = new Map();
document.addEventListener('patternsChanged', () => {
patternNamesPromise = null;
cachedPatterns = {};
definitionRequests.clear();
});
const fetchPatternNames = () => {
if (patternNamesPromise) return patternNamesPromise;
const promise = (async () => {
const response = await fetch('/patterns/names', { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('patterns unavailable');
const names = await response.json();
if (!Array.isArray(names) || !names.length) throw new Error('no patterns');
return names;
})();
patternNamesPromise = promise;
promise.catch(() => {
if (patternNamesPromise === promise) patternNamesPromise = null;
});
return promise;
};
const loadPatterns = async () => {
// Load one pattern's definition into cachedPatterns (once); resolves when it is available
const ensurePatternConfig = (patternName) => {
const name = String(patternName || '').trim();
if (!name || cachedPatterns[name]) return Promise.resolve();
if (!definitionRequests.has(name)) {
const request = fetch(`/patterns/${encodeURIComponent(name)}`, { headers: { Accept: 'application/json' } })
.then((response) => (response.ok ? response.json() : {}))
.then((config) => {
cachedPatterns[name] = config && typeof config === 'object' ? config : {};
})
.catch(() => {
definitionRequests.delete(name);
});
definitionRequests.set(name, request);
}
return definitionRequests.get(name);
};
// want: the pattern to select (a preset's own); defaults to the current selection
const loadPatterns = async (want) => {
if (!presetPatternInput) {
return;
}
try {
// Load pattern definitions from pattern.json
let patternsPayload = null;
let response = await fetch('/patterns/definitions', {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (response.ok) {
patternsPayload = await response.json();
}
let normalized = normalizePatternMap(patternsPayload);
if (!Object.keys(normalized).length) {
// Fallback when definitions route is unavailable or returns an empty map.
response = await fetch('/patterns', {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
return;
}
patternsPayload = await response.json();
normalized = normalizePatternMap(patternsPayload);
}
cachedPatterns = normalized;
const entries = Object.keys(cachedPatterns);
const desiredPattern = presetPatternInput.value;
const entries = await fetchPatternNames();
const desiredPattern = want || presetPatternInput.value;
presetPatternInput.innerHTML = '<option value="">Pattern</option>';
entries.forEach((patternName) => {
const option = document.createElement('option');
@@ -1064,22 +1078,15 @@ document.addEventListener('DOMContentLoaded', () => {
option.textContent = patternName;
presetPatternInput.appendChild(option);
});
if (desiredPattern && cachedPatterns[desiredPattern]) {
presetPatternInput.value = desiredPattern;
} else if (entries.length > 0) {
let defaultPattern = entries[0];
for (const patternName of entries) {
const config = cachedPatterns[patternName];
const hasMapping = config && Object.keys(config).some((key) => {
return typeof key === 'string' && key.startsWith('n');
});
if (hasMapping) {
defaultPattern = patternName;
break;
}
}
presetPatternInput.value = defaultPattern;
if (desiredPattern && !entries.includes(desiredPattern)) {
// A preset's pattern that has no definition must still show (and keep) its own value
const option = document.createElement('option');
option.value = desiredPattern;
option.textContent = desiredPattern;
presetPatternInput.appendChild(option);
}
presetPatternInput.value = desiredPattern || entries[0];
await ensurePatternConfig(presetPatternInput.value);
updatePresetNLabels(presetPatternInput.value);
} catch (error) {
console.warn('Failed to load patterns:', error);
@@ -1194,7 +1201,7 @@ document.addEventListener('DOMContentLoaded', () => {
editButton.addEventListener('click', async () => {
currentEditId = presetId;
currentEditTabId = null;
await loadPatterns();
await loadPatterns(preset && preset.pattern);
const paletteColors = await getCurrentProfilePaletteColors();
const presetForEditor = {
...(preset || {}),
@@ -1563,7 +1570,8 @@ document.addEventListener('DOMContentLoaded', () => {
presetEditorCloseButton.addEventListener('click', closeEditor);
}
if (presetPatternInput) {
presetPatternInput.addEventListener('change', () => {
presetPatternInput.addEventListener('change', async () => {
await ensurePatternConfig(presetPatternInput.value);
updatePresetNLabels(presetPatternInput.value);
// Update color section visibility
updateColorSectionVisibility();
@@ -1838,7 +1846,7 @@ document.addEventListener('DOMContentLoaded', () => {
const { presetId, preset, zoneId } = event.detail;
currentEditId = presetId;
currentEditTabId = zoneId || null;
await loadPatterns();
await loadPatterns(preset && preset.pattern);
const paletteColors = await getCurrentProfilePaletteColors();
setFormValues({
...(preset || {}),