337 lines
13 KiB
JavaScript
337 lines
13 KiB
JavaScript
// ============================================================
|
|
// APP.JS — Core utilities, tabs, model selector, helpers
|
|
// ============================================================
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
|
|
// --- TAB NAVIGATION ---
|
|
function activateTab(tabName) {
|
|
var btn = document.querySelector('.tab-btn[data-tab="' + tabName + '"]');
|
|
if (!btn || btn.classList.contains('hidden')) return false;
|
|
document.querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
|
|
document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
|
|
btn.classList.add('active');
|
|
var tabEl = document.getElementById(tabName + '-tab');
|
|
if (tabEl) tabEl.classList.add('active');
|
|
window.location.hash = tabName;
|
|
document.dispatchEvent(new CustomEvent('tabChanged', { detail: { tab: tabName } }));
|
|
return true;
|
|
}
|
|
|
|
document.querySelectorAll('.tab-btn').forEach(function(btn) {
|
|
btn.addEventListener('click', function() {
|
|
activateTab(btn.getAttribute('data-tab'));
|
|
});
|
|
});
|
|
|
|
// Restore tab from URL hash on load
|
|
var hash = window.location.hash.replace('#', '');
|
|
if (!hash || !activateTab(hash)) {
|
|
activateTab('encounter'); // default
|
|
}
|
|
|
|
// --- MODEL SELECTOR ---
|
|
var modelSelect = document.getElementById('global-model-select');
|
|
var costBadge = document.getElementById('model-cost-badge');
|
|
window._currentModels = [];
|
|
window._currentProvider = 'openrouter';
|
|
|
|
fetch('/api/models')
|
|
.then(function(r) { return r.json(); })
|
|
.then(function(data) {
|
|
window._currentModels = data.models || [];
|
|
window._currentProvider = data.provider || 'openrouter';
|
|
|
|
var categories = { free: '🆓 Free', fast: '⚡ Fast & Cheap', smart: '🧠 Smart', premium: '👑 Premium' };
|
|
|
|
function buildModelOptions(selectEl) {
|
|
selectEl.innerHTML = '';
|
|
var grouped = {};
|
|
window._currentModels.forEach(function(m) {
|
|
var cat = m.category || 'smart';
|
|
if (!grouped[cat]) grouped[cat] = [];
|
|
grouped[cat].push(m);
|
|
});
|
|
Object.keys(categories).forEach(function(cat) {
|
|
if (!grouped[cat] || grouped[cat].length === 0) return;
|
|
var optgroup = document.createElement('optgroup');
|
|
optgroup.label = categories[cat];
|
|
grouped[cat].forEach(function(m) {
|
|
var opt = document.createElement('option');
|
|
opt.value = m.id;
|
|
opt.textContent = m.name + ' (' + m.cost + ')';
|
|
optgroup.appendChild(opt);
|
|
});
|
|
selectEl.appendChild(optgroup);
|
|
});
|
|
}
|
|
|
|
if (modelSelect && window._currentModels.length > 0) {
|
|
buildModelOptions(modelSelect);
|
|
if (costBadge) costBadge.textContent = window._currentProvider.toUpperCase() + ' | ' + window._currentModels[0].cost;
|
|
}
|
|
|
|
// Populate all per-tab model selectors
|
|
document.querySelectorAll('.tab-model-select').forEach(function(sel) {
|
|
buildModelOptions(sel);
|
|
});
|
|
})
|
|
.catch(function(err) { console.warn('Models load failed:', err); });
|
|
|
|
if (modelSelect) {
|
|
modelSelect.addEventListener('change', function() {
|
|
var m = window._currentModels.find(function(x) { return x.id === modelSelect.value; });
|
|
if (m && costBadge) costBadge.textContent = window._currentProvider.toUpperCase() + ' | ' + m.cost;
|
|
showToast('Model: ' + modelSelect.value.split('/').pop(), 'info');
|
|
});
|
|
}
|
|
|
|
console.log('✅ App.js DOM ready');
|
|
|
|
}); // end DOMContentLoaded
|
|
|
|
// ============================================================
|
|
// GLOBAL FUNCTIONS (must be outside DOMContentLoaded)
|
|
// ============================================================
|
|
|
|
function getSelectedModel() {
|
|
// Prefer the active tab's own model selector if present
|
|
var activeTab = document.querySelector('.tab-content.active');
|
|
if (activeTab) {
|
|
var tabSel = activeTab.querySelector('.tab-model-select');
|
|
if (tabSel && tabSel.value) return tabSel.value;
|
|
}
|
|
var sel = document.getElementById('global-model-select');
|
|
return sel ? sel.value : 'google/gemini-2.5-flash';
|
|
}
|
|
|
|
function showLoading(text) {
|
|
var overlay = document.getElementById('loading-overlay');
|
|
var textEl = document.getElementById('loading-text');
|
|
if (textEl) textEl.textContent = text || 'Processing...';
|
|
if (overlay) { overlay.style.display = 'flex'; overlay.className = overlay.className.replace('hidden', '').trim(); }
|
|
}
|
|
|
|
function hideLoading() {
|
|
var overlay = document.getElementById('loading-overlay');
|
|
if (overlay) overlay.style.display = 'none';
|
|
}
|
|
|
|
function showToast(message, type) {
|
|
var container = document.getElementById('toast-container');
|
|
if (!container) { console.log('Toast:', type, message); return; }
|
|
var toast = document.createElement('div');
|
|
toast.className = 'toast toast-' + (type || 'success');
|
|
var icon = type === 'error' ? 'exclamation-circle' : type === 'info' ? 'info-circle' : 'check-circle';
|
|
toast.innerHTML = '<i class="fas fa-' + icon + '"></i> ' + message;
|
|
container.appendChild(toast);
|
|
setTimeout(function() { toast.remove(); }, 3500);
|
|
}
|
|
|
|
function copyText(elementId) {
|
|
var el = document.getElementById(elementId);
|
|
if (!el) return;
|
|
var text = el.innerText || el.textContent || '';
|
|
if (!text.trim()) { showToast('Nothing to copy', 'error'); return; }
|
|
|
|
// Try modern clipboard API (requires HTTPS or localhost)
|
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
navigator.clipboard.writeText(text).then(function() {
|
|
showToast('Copied!', 'success');
|
|
}).catch(function(err) {
|
|
// Fallback: select + execCommand
|
|
try {
|
|
var range = document.createRange();
|
|
range.selectNodeContents(el);
|
|
window.getSelection().removeAllRanges();
|
|
window.getSelection().addRange(range);
|
|
var ok = document.execCommand('copy');
|
|
window.getSelection().removeAllRanges();
|
|
showToast(ok ? 'Copied!' : 'Copy failed — please select text manually', ok ? 'success' : 'error');
|
|
} catch (e) {
|
|
showToast('Copy not supported in this browser', 'error');
|
|
}
|
|
});
|
|
} else {
|
|
// No clipboard API — use execCommand directly
|
|
try {
|
|
var range = document.createRange();
|
|
range.selectNodeContents(el);
|
|
window.getSelection().removeAllRanges();
|
|
window.getSelection().addRange(range);
|
|
var ok = document.execCommand('copy');
|
|
window.getSelection().removeAllRanges();
|
|
showToast(ok ? 'Copied!' : 'Copy failed — please select text manually', ok ? 'success' : 'error');
|
|
} catch (e) {
|
|
showToast('Copy not supported in this browser', 'error');
|
|
}
|
|
}
|
|
}
|
|
|
|
// Speak / Stop
|
|
var currentlyReadingId = null;
|
|
var currentAudio = null;
|
|
|
|
function speakText(elementId) {
|
|
if (currentlyReadingId === elementId) { stopReading(); return; }
|
|
stopReading();
|
|
var el = document.getElementById(elementId);
|
|
if (!el) return;
|
|
var text = (el.innerText || el.textContent).trim();
|
|
if (!text) { showToast('Nothing to read', 'error'); return; }
|
|
if (!('speechSynthesis' in window)) { showToast('TTS not supported', 'error'); return; }
|
|
window.speechSynthesis.cancel();
|
|
var utter = new SpeechSynthesisUtterance(text);
|
|
utter.rate = 0.9;
|
|
utter.onend = function() { stopReading(); };
|
|
utter.onerror = function() { stopReading(); };
|
|
currentlyReadingId = elementId;
|
|
var btn = findReadButton(elementId);
|
|
if (btn) { btn.classList.add('btn-reading'); btn.innerHTML = '<i class="fas fa-stop"></i> Stop'; }
|
|
window.speechSynthesis.speak(utter);
|
|
showToast('Reading — click Stop to end', 'info');
|
|
}
|
|
|
|
function stopReading() {
|
|
if ('speechSynthesis' in window) window.speechSynthesis.cancel();
|
|
if (currentAudio) { currentAudio.pause(); currentAudio = null; }
|
|
if (currentlyReadingId) {
|
|
var btn = findReadButton(currentlyReadingId);
|
|
if (btn) { btn.classList.remove('btn-reading'); btn.innerHTML = '<i class="fas fa-volume-high"></i> Read'; }
|
|
currentlyReadingId = null;
|
|
}
|
|
}
|
|
|
|
function findReadButton(elementId) {
|
|
var el = document.getElementById(elementId);
|
|
if (!el) return null;
|
|
var card = el.closest('.output-card') || el.closest('.card');
|
|
if (!card) return null;
|
|
var buttons = card.querySelectorAll('button');
|
|
for (var i = 0; i < buttons.length; i++) {
|
|
var oc = buttons[i].getAttribute('onclick') || '';
|
|
if (oc.indexOf('speakText') !== -1 && oc.indexOf(elementId) !== -1) return buttons[i];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Timer
|
|
function createTimer(el) {
|
|
var s = 0, iv = null;
|
|
return {
|
|
start: function() { s = 0; this.update(); var self = this; iv = setInterval(function() { s++; self.update(); }, 1000); },
|
|
stop: function() { if (iv) { clearInterval(iv); iv = null; } return s; },
|
|
update: function() { el.textContent = String(Math.floor(s / 60)).padStart(2, '0') + ':' + String(s % 60).padStart(2, '0'); }
|
|
};
|
|
}
|
|
|
|
// Audio Recorder
|
|
function AudioRecorder() { this.mediaRecorder = null; this.chunks = []; this.stream = null; }
|
|
AudioRecorder.prototype.start = function() {
|
|
var self = this; self.chunks = [];
|
|
return navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } })
|
|
.then(function(stream) {
|
|
self.stream = stream;
|
|
var mime = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/webm';
|
|
self.mediaRecorder = new MediaRecorder(stream, { mimeType: mime });
|
|
self.mediaRecorder.ondataavailable = function(e) { if (e.data.size > 0) self.chunks.push(e.data); };
|
|
self.mediaRecorder.start(1000);
|
|
});
|
|
};
|
|
AudioRecorder.prototype.stop = function() {
|
|
var self = this;
|
|
return new Promise(function(resolve) {
|
|
if (!self.mediaRecorder || self.mediaRecorder.state === 'inactive') { resolve(null); return; }
|
|
self.mediaRecorder.onstop = function() {
|
|
var blob = new Blob(self.chunks, { type: self.mediaRecorder.mimeType });
|
|
if (self.stream) self.stream.getTracks().forEach(function(t) { t.stop(); });
|
|
resolve(blob);
|
|
};
|
|
self.mediaRecorder.stop();
|
|
});
|
|
};
|
|
|
|
function transcribeAudio(blob) {
|
|
var formData = new FormData();
|
|
formData.append('audio', blob, 'audio.webm');
|
|
return fetch('/api/transcribe', {
|
|
method: 'POST',
|
|
headers: { 'Authorization': 'Bearer ' + (window.AUTH_TOKEN || localStorage.getItem('ped_scribe_token') || '') },
|
|
body: formData
|
|
}).then(function(r) { return r.json(); });
|
|
}
|
|
|
|
function refineDocument(outputElementId, inputElementId) {
|
|
var doc = document.getElementById(outputElementId);
|
|
var input = document.getElementById(inputElementId);
|
|
if (!doc || !input) return;
|
|
var docText = doc.innerText.trim();
|
|
var instructions = input.value.trim();
|
|
if (!docText) { showToast('No document', 'error'); return; }
|
|
if (!instructions) { showToast('Enter instructions', 'error'); return; }
|
|
showLoading('Refining...');
|
|
fetch('/api/refine', {
|
|
method: 'POST', headers: getAuthHeaders(),
|
|
body: JSON.stringify({ currentDocument: docText, instructions: instructions, model: getSelectedModel() })
|
|
})
|
|
.then(function(r) { return r.json(); })
|
|
.then(function(data) {
|
|
hideLoading();
|
|
if (data.success) { doc.textContent = data.refined; input.value = ''; showToast('Refined!', 'success'); }
|
|
else showToast(data.error || 'Failed', 'error');
|
|
})
|
|
.catch(function(err) { hideLoading(); showToast(err.message, 'error'); });
|
|
}
|
|
|
|
function shortenDocument(outputElementId) {
|
|
var doc = document.getElementById(outputElementId);
|
|
if (!doc) return;
|
|
var text = doc.innerText.trim();
|
|
if (!text) { showToast('No document', 'error'); return; }
|
|
showLoading('Shortening...');
|
|
fetch('/api/shorten', {
|
|
method: 'POST', headers: getAuthHeaders(),
|
|
body: JSON.stringify({ document: text, model: getSelectedModel() })
|
|
})
|
|
.then(function(r) { return r.json(); })
|
|
.then(function(data) {
|
|
hideLoading();
|
|
if (data.success) { doc.textContent = data.shortened; showToast('Shortened!', 'success'); }
|
|
else showToast(data.error || 'Failed', 'error');
|
|
})
|
|
.catch(function(err) { hideLoading(); showToast(err.message, 'error'); });
|
|
}
|
|
|
|
function exportToNextcloud(elementId, docType) {
|
|
var el = document.getElementById(elementId);
|
|
if (!el) return;
|
|
var text = el.innerText.trim();
|
|
if (!text) { showToast('Nothing to export', 'error'); return; }
|
|
fetch('/api/nextcloud/export', {
|
|
method: 'POST', headers: getAuthHeaders(),
|
|
body: JSON.stringify({ content: text, filename: docType + '-' + Date.now(), type: docType })
|
|
})
|
|
.then(function(r) { return r.json(); })
|
|
.then(function(data) {
|
|
if (data.success) showToast(data.message, 'success');
|
|
else showToast(data.error || 'Export failed', 'error');
|
|
})
|
|
.catch(function() { showToast('Nextcloud not connected', 'error'); });
|
|
}
|
|
|
|
function createSpeechRecognition() {
|
|
if (!(window.SpeechRecognition || window.webkitSpeechRecognition)) return null;
|
|
var SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
var rec = new SR();
|
|
rec.continuous = true;
|
|
rec.interimResults = true;
|
|
rec.lang = 'en-US';
|
|
return rec;
|
|
}
|
|
|
|
// PWA Service Worker
|
|
if ('serviceWorker' in navigator) {
|
|
navigator.serviceWorker.register('/sw.js').catch(function() {});
|
|
}
|
|
|
|
console.log('✅ App.js loaded');
|