Changeset 0.18.1 (#80)

This commit is contained in:
2026-02-28 19:41:59 +00:00
parent e4a943b03e
commit a591b810a9
13 changed files with 1415 additions and 197 deletions

646
src/js/panels.js Normal file
View File

@@ -0,0 +1,646 @@
// ==========================================
// Chat Switchboard Panel Registry
// ==========================================
// Independent panel system replacing the hardcoded two-tab side panel.
// Each panel registers with name, DOM element, and lifecycle hooks.
// The registry owns all open/close/focus logic — individual panels
// never touch the <aside> container directly.
//
// Supports single-panel and dual-view modes. In dual mode the panel
// body splits into primary (left) + divider + secondary (right) via
// CSS grid. The split ratio is drag-adjustable.
//
// See DESIGN-0.18.1.md for full spec.
// ── Panel Registry ──────────────────────────
const PanelRegistry = {
_panels: {}, // { name: { element, label, onOpen, onClose, saveState, restoreState, actions, state } }
_active: null, // primary (left) panel name
_secondary: null, // secondary (right) panel name — null when not in dual mode
_dualMode: false,
_splitRatio: 0.5, // 01, fraction of space allocated to primary
_order: [], // registration order (for tab rendering + cycle)
/**
* Register a panel.
* @param {string} name — unique identifier (e.g. 'preview', 'notes')
* @param {object} opts
* @param {HTMLElement} opts.element — the .side-panel-page div
* @param {string} opts.label — display name for tab button
* @param {Function} [opts.onOpen] — called when panel becomes visible
* @param {Function} [opts.onClose] — called when panel is hidden
* @param {Function} [opts.saveState] — returns state snapshot before hiding
* @param {Function} [opts.restoreState]— receives state snapshot on re-show
* @param {Array} [opts.actions] — per-panel action button configs
* Each action: { id, icon, title, onClick, visible? }
*/
register(name, opts) {
if (this._panels[name]) {
console.warn(`[panels] panel "${name}" already registered, replacing`);
}
this._panels[name] = {
element: opts.element,
label: opts.label || name,
onOpen: opts.onOpen || null,
onClose: opts.onClose || null,
saveState: opts.saveState || null,
restoreState: opts.restoreState || null,
actions: opts.actions || [],
state: {},
};
if (!this._order.includes(name)) {
this._order.push(name);
}
this._renderLabel();
},
/**
* Open a panel (and the container if closed).
*
* Single mode: hides current active, shows requested panel.
* Dual mode:
* - Already visible (active or secondary): swap it to primary.
* - Not visible: replaces secondary panel.
*/
open(name) {
const panel = this._panels[name];
if (!panel) {
console.warn(`[panels] unknown panel: "${name}"`);
return;
}
const container = this._container();
if (!container) return;
if (this._dualMode) {
// Already primary — no-op
if (this._active === name) {
this._renderLabel();
this._renderActions();
return;
}
// Currently secondary — promote to primary, swap
if (this._secondary === name) {
const oldActive = this._active;
this._active = name;
this._secondary = oldActive;
this._applyDualLayout();
this._renderLabel();
this._renderActions();
return;
}
// New panel — replace secondary
if (this._secondary) this._hide(this._secondary);
this._show(name);
this._secondary = name;
this._applyDualLayout();
this._renderLabel();
this._renderActions();
return;
}
// ── Single mode ──
if (this._active && this._active !== name) {
this._hide(this._active);
}
container.classList.add('open');
this._show(name);
this._active = name;
this._showOverlay();
this._renderLabel();
this._renderActions();
},
/**
* Close a specific panel.
*
* Dual mode: closing either panel exits dual, keeping the other.
* Single mode: closes container.
*/
close(name) {
const panel = this._panels[name];
if (!panel) return;
if (this._dualMode) {
if (name === this._secondary) {
this._hide(this._secondary);
this._secondary = null;
this._exitDualLayout();
this._renderLabel();
this._renderActions();
return;
}
if (name === this._active) {
this._hide(this._active);
// Promote secondary to primary
this._active = this._secondary;
this._secondary = null;
this._exitDualLayout();
this._renderLabel();
this._renderActions();
return;
}
return; // not visible — nothing to close
}
// ── Single mode ──
if (this._active === name) {
this._hide(name);
this._active = null;
this._closeContainer();
}
},
/**
* Toggle: if this panel is visible, close it. Otherwise, open it.
*/
toggle(name) {
if (this.isOpen(name)) {
this.close(name);
} else {
this.open(name);
}
},
/**
* Close all panels and the container.
*/
closeAll() {
if (this._secondary) {
this._hide(this._secondary);
this._secondary = null;
}
if (this._active) {
this._hide(this._active);
this._active = null;
}
if (this._dualMode) this._exitDualLayout();
this._closeContainer();
},
/** Is a specific panel currently visible? */
isOpen(name) {
return this._active === name || this._secondary === name;
},
/** Is the panel container open at all? */
isContainerOpen() {
return this._container()?.classList.contains('open') || false;
},
/** Get the primary panel name (or null). */
active() {
return this._active;
},
/** Is dual-view mode active? */
isDual() {
return this._dualMode;
},
/**
* Toggle dual-view mode.
*
* Entering: picks the next registered panel as secondary. If
* container is closed, opens first two panels. Needs ≥ 2 panels.
* Exiting: hides secondary, keeps primary.
*/
toggleDual() {
if (this._dualMode) {
// Exit dual
if (this._secondary) this._hide(this._secondary);
this._secondary = null;
this._exitDualLayout();
this._renderLabel();
this._renderActions();
return;
}
// Enter dual — need at least 2 panels
if (this._order.length < 2) return;
const container = this._container();
if (!container) return;
// If container not open, open first panel as primary
if (!this._active) {
container.classList.add('open');
this._show(this._order[0]);
this._active = this._order[0];
}
// Pick secondary: first registered panel that isn't active
const secondary = this._order.find(n => n !== this._active);
if (!secondary) return;
this._show(secondary);
this._secondary = secondary;
this._dualMode = true;
this._applyDualLayout();
this._renderLabel();
this._renderActions();
},
/**
* Cycle to the next registered panel. If container is closed, open
* the first panel. Wraps around.
*
* In dual mode, cycles the secondary panel through non-primary panels.
*/
cycle() {
if (this._order.length === 0) return;
if (!this._active) {
this.open(this._order[0]);
return;
}
if (this._dualMode && this._secondary) {
// Cycle secondary through panels that aren't the primary
const others = this._order.filter(n => n !== this._active);
if (others.length < 2) return; // only one option, already showing
const idx = others.indexOf(this._secondary);
const next = others[(idx + 1) % others.length];
if (next === this._secondary) return;
this._hide(this._secondary);
this._show(next);
this._secondary = next;
this._applyDualLayout();
this._renderLabel();
this._renderActions();
return;
}
// Single mode: cycle active
const idx = this._order.indexOf(this._active);
const next = this._order[(idx + 1) % this._order.length];
this.open(next);
},
// ── Internal ────────────────────────────
_container() {
return document.getElementById('sidePanel');
},
_body() {
return document.getElementById('sidePanelBody');
},
/** Show a panel: set display, restore state, fire onOpen. */
_show(name) {
const panel = this._panels[name];
if (!panel) return;
panel.element.style.display = '';
// Restore state if previously saved
if (panel.restoreState && Object.keys(panel.state).length > 0) {
panel.restoreState(panel.state);
}
if (panel.onOpen) panel.onOpen();
},
/** Hide a panel: save state, call onClose, set display:none, clear grid placement. */
_hide(name) {
const panel = this._panels[name];
if (!panel) return;
if (panel.saveState) {
panel.state = panel.saveState() || {};
}
if (panel.onClose) panel.onClose();
panel.element.style.display = 'none';
panel.element.style.gridColumn = '';
},
/** Close the <aside> container. */
_closeContainer() {
const container = this._container();
if (!container) return;
container.classList.remove('open', 'fullscreen', 'dual-open');
container.style.width = '';
container.style.minWidth = '';
this._hideOverlay();
},
// ── Dual layout ─────────────────────────
/** Apply CSS grid layout for dual-view. */
_applyDualLayout() {
this._dualMode = true;
const body = this._body();
const container = this._container();
const divider = document.getElementById('sidePanelDivider');
if (!body || !container) return;
body.classList.add('dual');
container.classList.add('dual-open');
if (divider) divider.style.display = '';
// Assign grid columns: primary=1, divider=2, secondary=3
const primary = this._panels[this._active];
const secondary = this._panels[this._secondary];
if (primary) primary.element.style.gridColumn = '1';
if (secondary) secondary.element.style.gridColumn = '3';
this._applySplitRatio();
},
/** Remove dual layout, return to single-panel flexbox. */
_exitDualLayout() {
this._dualMode = false;
const body = this._body();
const container = this._container();
const divider = document.getElementById('sidePanelDivider');
if (body) {
body.classList.remove('dual');
body.style.gridTemplateColumns = '';
}
if (container) container.classList.remove('dual-open');
if (divider) divider.style.display = 'none';
// Clear grid-column on all panels
for (const name of this._order) {
const p = this._panels[name];
if (p) p.element.style.gridColumn = '';
}
},
/** Set grid-template-columns based on current _splitRatio. */
_applySplitRatio() {
const body = this._body();
if (!body || !this._dualMode) return;
const r = this._splitRatio;
body.style.gridTemplateColumns = `${r}fr 6px ${1 - r}fr`;
},
// ── Mobile overlay ──────────────────────
_isMobile() {
return window.innerWidth <= 768;
},
/** Show overlay behind panel on mobile (tap-to-close). */
_showOverlay() {
const ov = document.getElementById('sidePanelOverlay');
if (ov && this._isMobile()) ov.style.display = 'block';
},
/** Hide the mobile overlay. */
_hideOverlay() {
const ov = document.getElementById('sidePanelOverlay');
if (ov) ov.style.display = 'none';
},
// ── Tab and action rendering ────────────
/** Update the header label to show the active panel name. */
_renderLabel() {
const el = document.getElementById('sidePanelLabel');
if (!el) return;
if (this._active) {
const p = this._panels[this._active];
el.textContent = p ? p.label : '';
} else {
el.textContent = '';
}
// Update dual-view toggle button visibility
const dualBtn = document.getElementById('sidePanelDualBtn');
if (dualBtn) {
dualBtn.style.display = this._order.length >= 2 ? '' : 'none';
dualBtn.classList.toggle('active', this._dualMode);
}
},
/** Render per-panel action buttons for the primary (active) panel. */
_renderActions() {
const slot = document.getElementById('sidePanelPanelActions');
if (!slot) return;
if (!this._active) {
slot.innerHTML = '';
return;
}
const panel = this._panels[this._active];
slot.innerHTML = (panel.actions || [])
.filter(a => !a.visible || a.visible())
.map(a => `<button class="side-panel-action-btn" id="${a.id || ''}" onclick="${a.onClickName || ''}" title="${_escPanel(a.title || '')}">${a.icon || ''}</button>`)
.join('');
},
/** Refresh action button visibility (call after state changes). */
refreshActions() {
this._renderActions();
},
};
/** Minimal HTML escaping for panel labels/titles. */
function _escPanel(s) {
if (!s) return '';
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
// ── Side Panel Container (global operations) ──
function toggleSidePanelFullscreen() {
const panel = document.getElementById('sidePanel');
if (!panel) return;
panel.classList.toggle('fullscreen');
const btn = document.getElementById('sidePanelFullscreenBtn');
if (btn) {
const isFS = panel.classList.contains('fullscreen');
btn.title = isFS ? 'Exit fullscreen' : 'Toggle fullscreen';
btn.innerHTML = isFS
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/><line x1="14" y1="10" x2="21" y2="3"/><line x1="3" y1="21" x2="10" y2="14"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>';
}
}
// ── Side Panel Resize (outer edge) ──────────
function _initSidePanelResize() {
let startX, startW;
const panel = document.getElementById('sidePanel');
const handle = document.getElementById('sidePanelResize');
if (!handle || !panel) return;
handle.addEventListener('mousedown', (e) => {
if (panel.classList.contains('fullscreen')) return;
e.preventDefault();
startX = e.clientX;
startW = panel.getBoundingClientRect().width;
panel.style.transition = 'none';
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
const onMove = (e) => {
const delta = startX - e.clientX;
const minW = PanelRegistry.isDual() ? 480 : 280;
const newW = Math.max(minW, Math.min(window.innerWidth * 0.7, startW + delta));
panel.style.width = newW + 'px';
panel.style.minWidth = newW + 'px';
};
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
document.body.style.cursor = '';
document.body.style.userSelect = '';
panel.style.transition = '';
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
// ── Dual-View Divider Resize ────────────────
function _initDualDivider() {
const divider = document.getElementById('sidePanelDivider');
if (!divider) return;
divider.addEventListener('mousedown', (e) => {
if (!PanelRegistry.isDual()) return;
e.preventDefault();
const body = document.getElementById('sidePanelBody');
if (!body) return;
const bodyRect = body.getBoundingClientRect();
body.style.cursor = 'col-resize';
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
const onMove = (e) => {
const x = e.clientX - bodyRect.left;
const total = bodyRect.width - 6; // subtract divider width
const ratio = Math.max(0.2, Math.min(0.8, x / (total + 6)));
PanelRegistry._splitRatio = ratio;
PanelRegistry._applySplitRatio();
};
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
body.style.cursor = '';
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
// ── Mobile Swipe Navigation ─────────────────
function _initPanelSwipe() {
const body = document.getElementById('sidePanelBody');
if (!body) return;
let startX = 0;
let startY = 0;
let tracking = false;
body.addEventListener('touchstart', (e) => {
if (!PanelRegistry.isContainerOpen()) return;
if (PanelRegistry._order.length < 2) return;
// Only track single-finger swipes
if (e.touches.length !== 1) return;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
tracking = true;
}, { passive: true });
body.addEventListener('touchend', (e) => {
if (!tracking) return;
tracking = false;
const touch = e.changedTouches[0];
if (!touch) return;
const dx = touch.clientX - startX;
const dy = touch.clientY - startY;
// Require horizontal movement > 80px and more horizontal than vertical
if (Math.abs(dx) < 80 || Math.abs(dx) < Math.abs(dy) * 1.5) return;
if (dx > 0) {
// Swipe right → previous panel
_cyclePanelDirection(-1);
} else {
// Swipe left → next panel
_cyclePanelDirection(1);
}
}, { passive: true });
}
/**
* Cycle panels in a specific direction.
* direction: +1 = next, -1 = previous.
*/
function _cyclePanelDirection(direction) {
const order = PanelRegistry._order;
if (order.length < 2 || !PanelRegistry._active) return;
const idx = order.indexOf(PanelRegistry._active);
const next = order[(idx + direction + order.length) % order.length];
PanelRegistry.open(next);
}
// ── Responsive Resize Handler ───────────────
// Auto-exit dual mode when viewport shrinks below threshold.
function _initPanelResponsive() {
let wasWide = window.innerWidth > 768;
window.addEventListener('resize', () => {
const isWide = window.innerWidth > 768;
// Viewport shrank to mobile while dual was active → collapse
if (wasWide && !isWide && PanelRegistry.isDual()) {
PanelRegistry.toggleDual(); // exits dual, keeps primary
}
// Update overlay visibility: show on mobile if panel open, hide on desktop
if (PanelRegistry.isContainerOpen()) {
const ov = document.getElementById('sidePanelOverlay');
if (ov) {
ov.style.display = isWide ? 'none' : 'block';
}
}
wasWide = isWide;
});
}
// ── Panel Overlay (mobile tap-to-close) ─────
function _initPanelOverlay() {
const ov = document.getElementById('sidePanelOverlay');
if (!ov) return;
ov.addEventListener('click', () => {
PanelRegistry.closeAll();
});
}
// ── Legacy Compat (thin wrappers, remove after full migration) ──
function openSidePanel(tab) {
PanelRegistry.open(tab);
}
function closeSidePanel() {
PanelRegistry.closeAll();
}
function switchSidePanelTab(tab) {
PanelRegistry.open(tab);
}