Changeset 0.31.1 (#204)

Co-authored-by: Jeffrey Smith <jasafpro@gmail.com>
Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit is contained in:
2026-03-19 10:21:40 +00:00
committed by xcaliber
parent 071dea8904
commit 8364440081
17 changed files with 1186 additions and 339 deletions

View File

@@ -1,9 +1,9 @@
// ==========================================
// Chat Switchboard - ChatPane Component
// ==========================================
// v0.22.7: Mountable, self-contained chat pane instances.
// Replaces the hardcoded singleton pattern.
// ChatPane.primary is the backward-compat bridge.
// v0.31.1: Self-contained chat pane with optional standalone mode.
// When standalone: true, provides full chat functionality (streaming,
// model selector, history, channel creation) with zero external wiring.
//
// Exports: window.ChatPane
@@ -180,7 +180,6 @@ const ChatPane = {
'<div class="chat-pane-toolbar" id="' + pfx + 'Toolbar"></div>' +
'</div>';
container.appendChild(el);
// ChatPane.create expects element refs, not ID prefix
const instance = this.create({
id: pfx,
messagesEl: document.getElementById(pfx + 'ChatMessages'),
@@ -191,10 +190,256 @@ const ChatPane = {
channelId: opts.channelId || null,
standalone: opts.standalone !== false,
});
// v0.31.1: Standalone mode — self-contained chat with streaming
if (opts.standalone) {
_initStandalone(instance, pfx, opts);
}
return instance;
},
};
// ── Standalone Chat Logic ─────────────────────
// Absorbed from editor package v0.31.0. Provides full chat functionality
// (textarea, model selector, history, streaming, channel management)
// so that sw.chat(el, {standalone: true}) works with zero external wiring.
function _initStandalone(pane, pfx, opts) {
const headerEl = document.getElementById(pfx + 'ChatHeader');
const selectEl = document.getElementById(pfx + 'ChatSelect');
const newBtnEl = document.getElementById(pfx + 'ChatNewBtn');
const modelSelEl = document.getElementById(pfx + 'ModelSel');
const inputEl = pane.inputEl;
const sendBtn = pane.sendBtnEl;
if (!inputEl) return;
// Show header (chat-select + model-selector + new-chat button)
if (headerEl) headerEl.style.display = '';
// Show welcome
pane.showWelcome();
let _channelId = null, _messages = [], _sending = false, _abortController = null;
let _selectedModel = (typeof App !== 'undefined' && App.settings?.model) || '';
const _getContext = opts.getContext || null;
// ── Model Selector ──────────────────────
async function _initModelSelector() {
if (!modelSelEl) return;
if (typeof App === 'undefined') return;
if (!App.models?.length && typeof fetchModels === 'function') await fetchModels();
const models = App.models || [];
if (!models.length) return;
const sel = document.createElement('select');
sel.className = 'chat-pane-model-select';
sel.title = 'Select model';
models.forEach(function (m) {
if (m.hidden) return;
const opt = document.createElement('option');
opt.value = m.isPersona ? (m.personaId || m.id) : m.id;
opt.textContent = (m.isPersona ? '\ud83c\udfad ' : '') + (m.name || m.id);
if (m.id === _selectedModel || m.personaId === _selectedModel) opt.selected = true;
sel.appendChild(opt);
});
sel.addEventListener('change', function () { _selectedModel = sel.value; });
modelSelEl.innerHTML = '';
modelSelEl.appendChild(sel);
}
// ── Chat History ────────────────────────
async function _loadChatHistory() {
if (!selectEl || typeof API === 'undefined') return;
try {
const resp = await API.listChannels(1, 20, 'direct');
const channels = resp.data || resp || [];
selectEl.innerHTML = '<option value="">New conversation</option>';
channels.forEach(function (ch) {
const opt = document.createElement('option');
opt.value = ch.id;
opt.textContent = ch.title || 'Untitled';
if (ch.id === _channelId) opt.selected = true;
selectEl.appendChild(opt);
});
} catch (_) {}
}
if (selectEl) selectEl.addEventListener('change', function () {
selectEl.value ? _switchToChannel(selectEl.value) : _newChat();
});
if (newBtnEl) newBtnEl.addEventListener('click', _newChat);
async function _switchToChannel(channelId) {
_channelId = channelId;
_messages = [];
pane.clear();
pane.appendTyping();
try {
const resp = await API._get('/api/v1/channels/' + channelId + '/messages?page=1&per_page=100');
_messages = resp.data || resp || [];
pane.removeTyping();
_renderAllMessages();
} catch (e) {
pane.removeTyping();
_appendSystemMsg('Failed to load messages: ' + e.message);
}
}
function _newChat() {
_channelId = null;
_messages = [];
pane.showWelcome();
if (selectEl) selectEl.value = '';
}
// ── Textarea ────────────────────────────
const ta = document.createElement('textarea');
ta.placeholder = 'Type a message\u2026';
ta.rows = 1;
inputEl.appendChild(ta);
ta.addEventListener('input', function () {
ta.style.height = 'auto';
ta.style.height = Math.min(ta.scrollHeight, 160) + 'px';
});
// ── Send + Streaming ────────────────────
async function _sendMessage() {
const text = ta.value.trim();
if (!text || _sending) return;
_sending = true;
if (sendBtn) sendBtn.disabled = true;
ta.value = '';
ta.style.height = 'auto';
if (!_channelId) {
try {
const title = text.slice(0, 50) + (text.length > 50 ? '\u2026' : '');
const resp = await API.createChannel(title, _selectedModel, '', 'direct');
_channelId = resp.id;
_loadChatHistory();
} catch (e) {
_appendSystemMsg('Failed to create chat: ' + e.message);
_sending = false;
if (sendBtn) sendBtn.disabled = false;
return;
}
}
_messages.push({ role: 'user', content: text });
_renderAllMessages();
try {
_abortController = new AbortController();
let content = text;
if (_getContext) {
const ctx = _getContext();
if (ctx) content = text + '\n\n[Context: Currently editing ' + ctx.path + ']\n```\n' + ctx.content + '\n```';
}
const resp = await API.streamCompletion(_channelId, content, _selectedModel, _abortController.signal);
await _handleStream(resp);
} catch (e) {
if (e.name !== 'AbortError') _appendSystemMsg('Error: ' + e.message);
}
_abortController = null;
_sending = false;
if (sendBtn) sendBtn.disabled = false;
ta.focus();
}
if (sendBtn) sendBtn.addEventListener('click', _sendMessage);
ta.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); _sendMessage(); }
});
// ── Stream Handler ──────────────────────
async function _handleStream(response) {
const messagesEl = pane.messagesEl;
if (!messagesEl) return;
const div = document.createElement('div');
div.className = 'chat-msg chat-msg--assistant chat-msg--streaming';
const contentEl = document.createElement('div');
contentEl.className = 'chat-msg__content';
div.appendChild(contentEl);
messagesEl.appendChild(div);
let content = '';
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const delta = JSON.parse(data).choices?.[0]?.delta?.content;
if (delta) {
content += delta;
if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
contentEl.innerHTML = DOMPurify.sanitize(marked.parse(content));
} else {
contentEl.textContent = content;
}
pane.scrollToBottom();
}
} catch (_) {}
}
}
} catch (e) {
if (e.name !== 'AbortError') content += '\n\n**[Stream error: ' + e.message + ']**';
}
div.classList.remove('chat-msg--streaming');
_messages.push({ role: 'assistant', content: content });
}
// ── Message Rendering ───────────────────
function _renderAllMessages() {
if (!pane.messagesEl) return;
pane.messagesEl.innerHTML = '';
_messages.forEach(function (m) {
const div = document.createElement('div');
div.className = 'chat-msg chat-msg--' + m.role;
const c = document.createElement('div');
c.className = 'chat-msg__content';
if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
c.innerHTML = DOMPurify.sanitize(marked.parse(m.content || ''));
} else {
c.textContent = m.content || '';
}
div.appendChild(c);
pane.messagesEl.appendChild(div);
});
pane.scrollToBottom();
}
function _appendSystemMsg(text) {
const div = document.createElement('div');
div.className = 'chat-msg chat-msg--system';
div.innerHTML = '<div class="chat-msg__content" style="color:var(--danger,#f44336);font-size:12px;">' +
(typeof esc === 'function' ? esc(text) : text) + '</div>';
pane.messagesEl?.appendChild(div);
pane.scrollToBottom();
}
// ── Deferred Init ───────────────────────
function _deferredInit() { _initModelSelector(); _loadChatHistory(); }
if (typeof App !== 'undefined' && App.models?.length) _deferredInit();
else document.addEventListener('sb:ready', _deferredInit, { once: true });
}
// ── Exports ─────────────────────────────────
sb.ns('ChatPane', ChatPane);

View File

@@ -37,6 +37,41 @@ const Switchboard = {
const sw = Object.create(null);
// ── Flyout Positioning Helper ──────────────────────
// Escapes overflow:hidden/auto ancestors by switching to position:fixed.
function _hasClippingAncestor(el) {
let node = el.parentElement;
while (node && node !== document.body) {
const ov = getComputedStyle(node).overflow;
if (ov === 'hidden' || ov === 'auto' || ov === 'scroll') return true;
node = node.parentElement;
}
return false;
}
function _positionFlyout(flyoutEl, anchorEl, position) {
if (!_hasClippingAncestor(flyoutEl)) {
flyoutEl.removeAttribute('data-fixed');
flyoutEl.style.top = '';
flyoutEl.style.right = '';
flyoutEl.style.bottom = '';
flyoutEl.style.left = '';
return;
}
flyoutEl.setAttribute('data-fixed', '');
const rect = anchorEl.getBoundingClientRect();
flyoutEl.style.left = '';
if (position === 'up') {
flyoutEl.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
flyoutEl.style.top = '';
} else {
flyoutEl.style.top = (rect.bottom + 4) + 'px';
flyoutEl.style.bottom = '';
}
flyoutEl.style.right = Math.max(0, window.innerWidth - rect.right) + 'px';
}
// ── Identity ─────────────────────────────────────────
Object.defineProperty(sw, 'user', {
@@ -265,7 +300,7 @@ const Switchboard = {
const result = {
el: wrap,
flyoutEl: flyout,
open() { flyout.classList.add('open'); _open = true; },
open() { _positionFlyout(flyout, anchor, pos); flyout.classList.add('open'); _open = true; },
close() { flyout.classList.remove('open'); _open = false; },
toggle() { _open ? result.close() : result.open(); },
isOpen() { return _open; },
@@ -762,6 +797,7 @@ const Switchboard = {
const _opts = Object.assign({
user: window.__USER__ || null,
handlers: _defaultMenuHandlers,
_positionFn: _positionFlyout,
}, opts || {});
const instance = UserMenu.mount(container, _opts);
if (!UserMenu.primary) UserMenu.primary = instance;

View File

@@ -156,7 +156,7 @@ UserMenu.mount = function (container, opts) {
'</div>' +
'<span id="' + pfx + 'userName" class="sb-label"' + (_opts.compact ? ' style="display:none"' : '') + '>User</span>' +
'</button>' +
'<div id="' + pfx + 'userFlyout" class="user-flyout">' +
'<div id="' + pfx + 'userFlyout" class="sw-menu-flyout" data-position="' + flyout + '">' +
'<button id="' + pfx + 'menuSettings" class="flyout-item">' +
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.32 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>' +
'<span>Settings</span>' +
@@ -182,6 +182,16 @@ UserMenu.mount = function (container, opts) {
container.appendChild(el);
const instance = this.create({ id: pfx });
// Wire fixed-positioning for flyouts inside overflow-clipped containers
if (_opts._positionFn) {
const _origOpen = instance.open.bind(instance);
instance.open = function () {
_opts._positionFn(instance.flyoutEl, instance.btnEl, flyout);
_origOpen();
};
}
instance.bind(_opts.handlers || {});
if (_opts.user) {