// Simulator in the Menu (host builds only, which serve the simulated rig at /sim/).
//
// Wide screens: the rig opens beside the UI, the controller on the left and the rig on the right, with a divider to
// resize them. Narrow screens (phones): the controller and the rig are two full-width pages; swipe left and right,
// or tap the pager at the bottom, to switch. Both stay loaded either way, so the rig's bars keep running. Pop out
// moves the rig to its own window. Whether it is open, its width and the page shown are remembered in this browser.
(function () {
'use strict';
const KEY = 'ledController.simSplit';
const MIN_W = 320;
const NARROW = 900; // below this: two pages to swipe between, not side by side
const LOCK_PX = 10; // movement before a touch counts as a swipe or a scroll
const DRAG_CLASS = 'sim-swipe-dragging';
// What the pane shows: the rig, or the preset editor (the pattern gallery) in the same pane
const VIEWS = { rig: '/sim/', presets: '/sim/gallery' };
let pane = null;
let frame = null;
let pager = null;
let width = 0;
let page = 0; // swipe mode: 0 the controller, 1 the rig
let view = 'rig';
function load() {
try {
return JSON.parse(localStorage.getItem(KEY)) || {};
} catch (_e) {
return {};
}
}
function save(state) {
try {
localStorage.setItem(KEY, JSON.stringify(Object.assign(load(), state)));
} catch (_e) {
// storage unavailable: the split lasts for this page only
}
}
function isOpen() {
return pane !== null;
}
function swipeMode() {
return window.innerWidth < NARROW;
}
function clampWidth(w) {
const max = Math.max(MIN_W, window.innerWidth - MIN_W);
return Math.round(Math.min(max, Math.max(MIN_W, w)));
}
function applyWidth(w) {
width = clampWidth(w);
document.documentElement.style.setProperty('--sim-pane-w', `${width}px`);
}
function setDrag(px) {
document.documentElement.style.setProperty('--sim-drag', `${Math.round(px)}px`);
}
// Show the rig or the preset editor in the pane. Switching unloads the other page (its bars power off)
function setView(v) {
view = v === 'presets' ? 'presets' : 'rig';
if (frame && frame.dataset.view !== view) {
frame.dataset.view = view;
frame.src = VIEWS[view];
}
if (pane) {
pane.querySelectorAll('.sim-pane-tabs button').forEach((b) =>
b.setAttribute('aria-pressed', String(b.dataset.view === view)));
}
save({ view });
}
function setPage(p) {
page = p ? 1 : 0;
document.documentElement.style.setProperty('--sim-page', String(page));
setDrag(0);
if (pager) {
pager.querySelectorAll('button').forEach((b, i) => b.setAttribute('aria-pressed', String(i === page)));
}
if (pane) {
// The page that is off screen is out of the tab order and hidden from screen readers
pane.inert = swipeMode() && page === 0;
const app = document.querySelector('.app-container');
if (app) {
app.inert = swipeMode() && page === 1;
}
}
save({ page });
}
// Side by side or two pages, from the window's width (a phone turned sideways can switch)
function layout() {
if (!pane) {
return;
}
const swipe = swipeMode();
document.body.classList.toggle('sim-split', !swipe);
document.body.classList.toggle('sim-swipe', swipe);
if (!swipe) {
applyWidth(width || load().width || window.innerWidth * 0.45);
}
setPage(page);
}
function popOut() {
const win = window.open(VIEWS[view], 'led-simulator', 'popup,width=1200,height=800');
if (!win) {
// Pop-ups blocked: keep the simulator here
alert('The browser blocked the simulator window. Allow pop-ups for this site, or open /sim/ in a new tab.');
return;
}
// Only one page runs the rig: the new window takes it over, so the pane closes
close();
}
/* ---- swiping between the two pages ---- */
// Touches that belong to something else: sliders and fields, sideways scrollers, open dialogs, and the rig's
// canvas while its room is being edited (a drag there moves a bar)
function ownsTouch(target, doc) {
const el = target && target.nodeType === 1 ? target : target && target.parentElement;
if (!el) {
return false;
}
if (el.closest('input, textarea, select, [contenteditable="true"], [data-no-swipe], .sim-pane-divider')) {
return true;
}
if (doc.querySelector('.modal.active, dialog[open]')) {
return true;
}
if (doc.body.classList.contains('editing') && el.closest('canvas')) {
return true;
}
const win = doc.defaultView;
for (let n = el; n && n !== doc.body; n = n.parentElement) {
const ox = win.getComputedStyle(n).overflowX;
if ((ox === 'auto' || ox === 'scroll') && n.scrollWidth > n.clientWidth + 2) {
return true;
}
}
return false;
}
function attachSwipe(doc) {
let start = null;
doc.addEventListener('touchstart', (ev) => {
start = null;
if (!document.body.classList.contains('sim-swipe') || ev.touches.length !== 1) {
return;
}
if (ownsTouch(ev.target, doc)) {
return;
}
const t = ev.touches[0];
start = { x: t.clientX, y: t.clientY, at: performance.now(), lock: null, dx: 0 };
}, { passive: true });
doc.addEventListener('touchmove', (ev) => {
if (!start || ev.touches.length !== 1) {
return;
}
const t = ev.touches[0];
const dx = t.clientX - start.x;
const dy = t.clientY - start.y;
if (!start.lock) {
if (Math.abs(dx) < LOCK_PX && Math.abs(dy) < LOCK_PX) {
return;
}
start.lock = Math.abs(dx) > Math.abs(dy) * 1.5 ? 'x' : 'y';
if (start.lock === 'x') {
document.body.classList.add(DRAG_CLASS);
}
}
if (start.lock !== 'x') {
return; // a scroll: leave it to the page
}
ev.preventDefault();
// The pages follow the finger; past the first or last page they resist
const past = (page === 0 && dx > 0) || (page === 1 && dx < 0);
start.dx = dx;
setDrag(past ? dx / 4 : dx);
}, { passive: false });
const end = () => {
if (!start) {
return;
}
const s = start;
start = null;
if (s.lock !== 'x') {
return;
}
document.body.classList.remove(DRAG_CLASS);
const fast = Math.abs(s.dx) / Math.max(1, performance.now() - s.at) > 0.5; // px per ms: a flick
const far = Math.abs(s.dx) > window.innerWidth * 0.25;
if ((far || fast) && s.dx < 0 && page === 0) {
setPage(1);
} else if ((far || fast) && s.dx > 0 && page === 1) {
setPage(0);
} else {
setPage(page); // not far enough: back where it was
}
};
doc.addEventListener('touchend', end);
doc.addEventListener('touchcancel', end);
}
/* ---- the pane ---- */
function build() {
pane = document.createElement('div');
pane.id = 'sim-pane';
pane.className = 'sim-pane';
pane.innerHTML =
'
' +
'
' +
'
' +
'' +
'' +
'
' +
'' +
'
';
pane.querySelectorAll('.sim-pane-tabs button').forEach((b) => {
b.setAttribute('aria-pressed', String(b.dataset.view === view));
b.addEventListener('click', () => setView(b.dataset.view));
});
// Swipes that start in the rig (same origin, so its document can be listened to)
frame = pane.querySelector('iframe');
frame.dataset.view = view;
frame.src = VIEWS[view];
frame.addEventListener('load', () => {
try {
attachSwipe(frame.contentDocument);
} catch (_e) {
// not reachable: swipe from the pane's bar or the pager instead
}
});
const divider = pane.querySelector('.sim-pane-divider');
divider.addEventListener('pointerdown', (ev) => {
ev.preventDefault();
divider.setPointerCapture(ev.pointerId);
document.body.classList.add('sim-split-dragging'); // the iframe would swallow the pointer
const move = (e) => applyWidth(window.innerWidth - e.clientX);
const up = () => {
divider.removeEventListener('pointermove', move);
divider.removeEventListener('pointerup', up);
divider.removeEventListener('pointercancel', up);
document.body.classList.remove('sim-split-dragging');
save({ width });
};
divider.addEventListener('pointermove', move);
divider.addEventListener('pointerup', up);
divider.addEventListener('pointercancel', up);
});
divider.addEventListener('keydown', (ev) => {
const step = ev.shiftKey ? 80 : 20;
if (ev.key === 'ArrowLeft' || ev.key === 'ArrowRight') {
ev.preventDefault();
applyWidth(width + (ev.key === 'ArrowLeft' ? step : -step));
save({ width });
}
});
divider.tabIndex = 0;
document.body.appendChild(pane);
pager = document.createElement('div');
pager.className = 'sim-pager';
pager.setAttribute('role', 'group');
pager.setAttribute('aria-label', 'Show the controller or the simulator (or swipe)');
pager.innerHTML =
'' +
'';
pager.querySelectorAll('button').forEach((b, i) => b.addEventListener('click', () => setPage(i)));
document.body.appendChild(pager);
}
function open(which) {
if (which) {
view = which === 'presets' ? 'presets' : 'rig';
}
if (!pane) {
build();
width = load().width || 0;
// On a phone, opening the rig shows it. Opening the preset editor leaves the controller on screen
page = swipeMode() && view === 'rig' ? 1 : 0;
} else {
setView(view);
}
save({ open: true });
layout();
syncMenu();
window.dispatchEvent(new Event('resize')); // the UI lays out for its new width
}
function close() {
if (pane) {
pane.remove(); // the iframe goes with it: its bars power off
pane = null;
frame = null;
}
if (pager) {
pager.remove();
pager = null;
}
const app = document.querySelector('.app-container');
if (app) {
app.inert = false;
}
document.body.classList.remove('sim-split', 'sim-swipe', DRAG_CLASS);
document.documentElement.style.setProperty('--sim-page', '0');
setDrag(0);
save({ open: false });
syncMenu();
window.dispatchEvent(new Event('resize'));
}
// The Menu item: open it; once open, side by side it closes it, on a phone it shows its page
function toggle() {
if (!isOpen()) {
open();
} else if (swipeMode()) {
setPage(page === 1 ? 0 : 1);
} else {
close();
}
}
// The Menu's Preset editor entry: open the pane on the presets, or switch the open pane to them
function openPresets() {
if (!isOpen()) {
open('presets');
return;
}
setView('presets'); // the controller stays on screen; on a phone the pager switches to it
}
const paneItems = []; // the Menu's Pop out and Close entries
function addMenuEntries() {
// A header button for the Menu item to forward to, as the other entries do (help.js)
const headerActions = document.querySelector('.header-actions');
const settingsBtn = document.getElementById('settings-btn');
const btn = document.createElement('button');
btn.className = 'btn btn-secondary edit-mode-only';
btn.id = 'sim-btn';
btn.textContent = 'Simulator';
btn.addEventListener('click', toggle);
if (headerActions) {
headerActions.insertBefore(btn, settingsBtn && settingsBtn.parentNode === headerActions ? settingsBtn : null);
}
const menu = document.getElementById('main-menu-dropdown');
if (menu) {
const item = document.createElement('button');
item.type = 'button';
item.className = 'edit-mode-only';
item.dataset.target = 'sim-btn';
item.textContent = 'Simulator';
const settingsItem = menu.querySelector('[data-target="settings-btn"]');
menu.insertBefore(item, settingsItem);
const presetsReal = document.createElement('button');
presetsReal.id = 'sim-presets-btn';
presetsReal.hidden = true;
presetsReal.addEventListener('click', openPresets);
document.body.appendChild(presetsReal);
const presetsItem = document.createElement('button');
presetsItem.type = 'button';
presetsItem.className = 'edit-mode-only';
presetsItem.dataset.target = 'sim-presets-btn';
presetsItem.textContent = 'Preset editor';
menu.insertBefore(presetsItem, settingsItem);
// Pop out and Close: in the Menu only while the pane is open (syncMenu). The menu forwards its clicks to
// the real buttons with these ids (help.js)
for (const [label, id, action] of [
['Pop out ↗', 'sim-popout-btn', popOut],
['Close simulator', 'sim-close-btn', close],
]) {
const real = document.createElement('button');
real.id = id;
real.hidden = true;
real.addEventListener('click', action);
document.body.appendChild(real);
const entry = document.createElement('button');
entry.type = 'button';
entry.className = 'sim-pane-item';
entry.dataset.target = id;
entry.textContent = label;
entry.style.display = 'none';
menu.insertBefore(entry, settingsItem);
paneItems.push(entry);
}
}
}
// The pane's Menu entries show while it is open. An inline display wins over the menu's own rules
function syncMenu() {
for (const entry of paneItems) {
entry.style.display = isOpen() ? '' : 'none';
}
}
async function init() {
let ok = false;
try {
const r = await fetch('/sim/api/config', { cache: 'no-store' });
ok = r.ok;
} catch (_e) {
ok = false;
}
if (!ok) {
return; // the board: no simulator
}
addMenuEntries();
attachSwipe(document); // swipes that start on the controller's page
const saved = load();
view = saved.view === 'presets' ? 'presets' : 'rig';
if (saved.open) {
build();
width = saved.width || 0;
page = saved.page ? 1 : 0;
layout();
}
syncMenu();
window.addEventListener('resize', layout);
}
window.simSplit = { open, close, popOut, setPage, setView };
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();