715 lines
28 KiB
HTML
715 lines
28 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>PB + Microsoft Graph</title>
|
|
<script src="https://cdn.tailwindcss.com"></script>
|
|
<script>
|
|
tailwind.config = {
|
|
theme: {
|
|
extend: {
|
|
colors: {
|
|
primary: '#4c51bf',
|
|
secondary: '#5b21b6',
|
|
}
|
|
}
|
|
}
|
|
}
|
|
</script>
|
|
</head>
|
|
<body class="min-h-screen bg-gradient-to-br from-primary to-secondary p-4 sm:p-8 flex justify-center items-center font-sans relative">
|
|
<!-- Top-right display name -->
|
|
<div id="userDisplay" class="hidden absolute top-4 right-4 text-white text-sm font-semibold drop-shadow">
|
|
<span id="userDisplayName"></span>
|
|
</div>
|
|
|
|
<!-- Bottom-left email -->
|
|
<div id="userEmail" class="hidden absolute bottom-4 left-4 text-white text-sm drop-shadow">
|
|
<span id="userEmailValue"></span>
|
|
</div>
|
|
|
|
<!-- Bottom-right version -->
|
|
<div class="absolute bottom-4 right-4 text-white/80 text-xs drop-shadow">
|
|
v1.0.0-alpha3
|
|
</div>
|
|
|
|
<!-- Login Container -->
|
|
<div id="loginContainer" class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-8">
|
|
<div class="text-center mb-8">
|
|
<h1 class="text-4xl font-bold text-gray-800 mb-2">PB + Microsoft Graph</h1>
|
|
<p class="text-gray-600">Sign in with Microsoft</p>
|
|
</div>
|
|
|
|
<div class="space-y-6">
|
|
<p class="text-gray-700 text-center">Sign in with your Microsoft account</p>
|
|
<button type="button" id="loginBtn" class="w-full py-3 px-4 bg-gradient-to-br from-primary to-secondary text-white font-semibold rounded-lg hover:opacity-95 transition-opacity shadow-lg hover:shadow-xl">
|
|
Login with Microsoft
|
|
</button>
|
|
</div>
|
|
|
|
<div id="loginError" class="hidden mt-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm"></div>
|
|
</div>
|
|
|
|
<!-- Note + Audio Container -->
|
|
<div id="noteContainer" class="hidden bg-white rounded-2xl shadow-2xl max-w-xl w-full p-8 space-y-6">
|
|
<div class="flex items-center justify-between">
|
|
<h2 class="text-2xl font-bold text-gray-800">New Note</h2>
|
|
<span id="graphStatus" class="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600">Graph: checking…</span>
|
|
</div>
|
|
<div class="space-y-4">
|
|
<div>
|
|
<label for="noteTitle" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
|
|
<input type="text" id="noteTitle" class="w-full rounded-lg border border-gray-300 p-3 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="Enter note title (optional)">
|
|
</div>
|
|
<div class="flex items-center justify-between">
|
|
<label class="block text-sm font-medium text-gray-700">Note Text</label>
|
|
<button id="voiceBtn" class="flex items-center gap-2 px-3 py-1 rounded bg-purple-600 text-white text-sm font-semibold hover:bg-purple-700 transition-colors" title="Click to speak">
|
|
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
|
|
<path fill-rule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clip-rule="evenodd" />
|
|
</svg>
|
|
<span id="voiceBtnText">Speak</span>
|
|
</button>
|
|
</div>
|
|
<textarea id="noteText" rows="4" class="w-full rounded-lg border border-gray-300 p-3 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="Type your note or click 'Speak' to dictate..."></textarea>
|
|
<div id="voiceStatus" class="hidden text-xs text-gray-600 flex items-center gap-2">
|
|
<span class="inline-block w-2 h-2 bg-red-600 rounded-full animate-pulse"></span>
|
|
<span id="voiceStatusText">Listening...</span>
|
|
</div>
|
|
</div>
|
|
<div class="space-y-2">
|
|
<div class="flex items-center gap-3">
|
|
<button id="recordBtn" class="px-4 py-2 rounded bg-primary text-white font-semibold disabled:opacity-50">Record Audio</button>
|
|
<button id="stopBtn" class="px-4 py-2 rounded bg-gray-200 text-gray-800 font-semibold disabled:opacity-50" disabled>Stop</button>
|
|
<button id="testMicBtn" class="px-4 py-2 rounded bg-blue-600 text-white font-semibold text-sm">Test Mic</button>
|
|
<a id="clearAudioLink" href="#" class="text-sm text-gray-600 underline hidden">Clear audio</a>
|
|
</div>
|
|
<audio id="audioPreview" controls class="hidden w-full"></audio>
|
|
<div id="recordStatus" class="text-xs text-gray-500">No audio recorded.</div>
|
|
<div id="micTestResults" class="hidden p-3 bg-blue-50 border border-blue-200 rounded text-xs space-y-1">
|
|
<div><strong>Mic Test Results:</strong></div>
|
|
<div>Peak Level: <span id="micPeakLevel">0</span>%</div>
|
|
<div>Average Level: <span id="micAvgLevel">0</span>%</div>
|
|
<div>Status: <span id="micStatus">Testing...</span></div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center gap-3">
|
|
<button id="submitNoteBtn" class="px-4 py-2 rounded bg-secondary text-white font-semibold">Submit Note</button>
|
|
<div id="submitStatus" class="text-sm text-gray-600"></div>
|
|
</div>
|
|
<hr class="my-4"/>
|
|
<div class="space-y-2">
|
|
<div class="flex items-center gap-3">
|
|
<button id="loadLastBtn" class="px-4 py-2 rounded bg-gray-800 text-white font-semibold">Load Last Note</button>
|
|
<span id="loadStatus" class="text-sm text-gray-600"></span>
|
|
</div>
|
|
<div id="lastNote" class="hidden space-y-2">
|
|
<div class="text-sm text-gray-700"><strong>Note:</strong> <span id="lastNoteText"></span></div>
|
|
<details class="text-xs text-gray-500">
|
|
<summary class="cursor-pointer select-none">Show raw note content</summary>
|
|
<pre id="lastNoteRaw" class="mt-2 p-2 bg-gray-50 border border-gray-200 rounded overflow-x-auto"></pre>
|
|
</details>
|
|
<audio id="lastNoteAudio" controls class="w-full"></audio>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script src="https://cdn.jsdelivr.net/npm/pocketbase/dist/pocketbase.umd.js"></script>
|
|
<script>
|
|
const APP_VERSION = '1.0.0-alpha3';
|
|
console.log(`App version: ${APP_VERSION}`);
|
|
// Initialize PocketBase client
|
|
const pb = new PocketBase('https://pocketbase.ccllc.pro');
|
|
|
|
// Collections (from .env in scaffold)
|
|
const NOTES_COLLECTION = 'Notes';
|
|
const ATTACHMENTS_COLLECTION = 'Attachments';
|
|
const ATTACHMENTS_FILE_FIELD = 'file';
|
|
const ATTACHMENTS_PBID_FIELD = 'pb_id';
|
|
const NOTE_BODY_HTML_FIELD = 'body_html';
|
|
const NOTE_BODY_PLAIN_FIELD = 'body_plain';
|
|
const NOTE_USERNAME_FIELD = 'Username';
|
|
let displayNameCache = 'Unknown User';
|
|
let userEmailCache = '';
|
|
let mediaRecorder = null;
|
|
let recordedChunks = [];
|
|
let recordedBlob = null;
|
|
let recognition = null;
|
|
let isRecognizing = false;
|
|
|
|
// --- Voice Recognition Setup ---
|
|
let voiceStartPosition = 0; // Track where voice input started
|
|
let lastInterimLength = 0; // Track interim text length
|
|
|
|
function setupVoiceRecognition() {
|
|
// Check for Web Speech API support
|
|
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
if (!SpeechRecognition) {
|
|
console.warn('Web Speech API not supported in this browser');
|
|
document.getElementById('voiceBtn').disabled = true;
|
|
document.getElementById('voiceBtn').title = 'Speech recognition not supported';
|
|
return null;
|
|
}
|
|
|
|
recognition = new SpeechRecognition();
|
|
recognition.continuous = true;
|
|
recognition.interimResults = true;
|
|
recognition.lang = 'en-US';
|
|
|
|
recognition.onstart = () => {
|
|
isRecognizing = true;
|
|
const noteTextArea = document.getElementById('noteText');
|
|
voiceStartPosition = noteTextArea.value.length; // Remember where we started
|
|
lastInterimLength = 0;
|
|
document.getElementById('voiceStatus').classList.remove('hidden');
|
|
document.getElementById('voiceBtn').classList.add('bg-red-600', 'hover:bg-red-700');
|
|
document.getElementById('voiceBtn').classList.remove('bg-purple-600', 'hover:bg-purple-700');
|
|
document.getElementById('voiceBtnText').textContent = 'Stop';
|
|
};
|
|
|
|
recognition.onresult = (event) => {
|
|
const noteTextArea = document.getElementById('noteText');
|
|
let finalTranscript = '';
|
|
let interimTranscript = '';
|
|
|
|
// Build transcript from all results
|
|
for (let i = 0; i < event.results.length; i++) {
|
|
const transcript = event.results[i][0].transcript;
|
|
if (event.results[i].isFinal) {
|
|
finalTranscript += transcript + ' ';
|
|
} else {
|
|
interimTranscript += transcript;
|
|
}
|
|
}
|
|
|
|
// Remove the previous interim text (if any) and add new text
|
|
const baseText = noteTextArea.value.substring(0, voiceStartPosition);
|
|
noteTextArea.value = baseText + finalTranscript + interimTranscript;
|
|
|
|
// Update status
|
|
document.getElementById('voiceStatusText').textContent =
|
|
interimTranscript ? `Listening: "${interimTranscript}"` : 'Listening...';
|
|
|
|
// Move cursor to end
|
|
noteTextArea.scrollTop = noteTextArea.scrollHeight;
|
|
};
|
|
|
|
recognition.onerror = (event) => {
|
|
console.error('Speech recognition error:', event.error);
|
|
let errorMsg = 'Error: ';
|
|
switch(event.error) {
|
|
case 'no-speech':
|
|
errorMsg += 'No speech detected. Try again.';
|
|
break;
|
|
case 'audio-capture':
|
|
errorMsg += 'No microphone found.';
|
|
break;
|
|
case 'not-allowed':
|
|
errorMsg += 'Microphone permission denied.';
|
|
break;
|
|
default:
|
|
errorMsg += event.error;
|
|
}
|
|
document.getElementById('voiceStatusText').textContent = errorMsg;
|
|
setTimeout(() => stopVoiceRecognition(), 2000);
|
|
};
|
|
|
|
recognition.onend = () => {
|
|
if (isRecognizing) {
|
|
// If we're still supposed to be recognizing, restart
|
|
try {
|
|
recognition.start();
|
|
} catch (e) {
|
|
console.log('Recognition ended:', e);
|
|
stopVoiceRecognition();
|
|
}
|
|
}
|
|
};
|
|
|
|
return recognition;
|
|
}
|
|
|
|
function startVoiceRecognition() {
|
|
if (!recognition) {
|
|
recognition = setupVoiceRecognition();
|
|
if (!recognition) return;
|
|
}
|
|
|
|
// Capture the current text length as the starting position
|
|
const noteTextArea = document.getElementById('noteText');
|
|
voiceStartPosition = noteTextArea.value.length;
|
|
lastInterimLength = 0;
|
|
|
|
try {
|
|
recognition.start();
|
|
} catch (e) {
|
|
console.log('Recognition already started or error:', e);
|
|
}
|
|
}
|
|
|
|
function stopVoiceRecognition() {
|
|
isRecognizing = false;
|
|
if (recognition) {
|
|
try {
|
|
recognition.stop();
|
|
} catch (e) {
|
|
console.log('Error stopping recognition:', e);
|
|
}
|
|
}
|
|
document.getElementById('voiceStatus').classList.add('hidden');
|
|
document.getElementById('voiceBtn').classList.remove('bg-red-600', 'hover:bg-red-700');
|
|
document.getElementById('voiceBtn').classList.add('bg-purple-600', 'hover:bg-purple-700');
|
|
document.getElementById('voiceBtnText').textContent = 'Speak';
|
|
}
|
|
|
|
// Voice button click handler
|
|
document.getElementById('voiceBtn').addEventListener('click', () => {
|
|
if (isRecognizing) {
|
|
stopVoiceRecognition();
|
|
} else {
|
|
startVoiceRecognition();
|
|
}
|
|
});
|
|
|
|
// --- Rich text helpers (TipTap-style JSON) ---
|
|
function tiptapDocFromText(text) {
|
|
const safe = (text || '').replace(/\r\n|\r|\n/g, '\n');
|
|
const lines = safe.split('\n');
|
|
const content = lines.map(line => ({
|
|
type: 'paragraph',
|
|
content: line ? [{ type: 'text', text: line }] : []
|
|
}));
|
|
return { type: 'doc', content };
|
|
}
|
|
|
|
function tiptapToPlainText(doc) {
|
|
if (!doc) return '';
|
|
try {
|
|
const parts = [];
|
|
const walk = (node) => {
|
|
if (!node) return;
|
|
if (Array.isArray(node)) {
|
|
node.forEach(walk);
|
|
return;
|
|
}
|
|
if (node.type === 'text' && node.text) {
|
|
parts.push(node.text);
|
|
return;
|
|
}
|
|
if (node.type === 'hardBreak') {
|
|
parts.push('\n');
|
|
return;
|
|
}
|
|
if (node.content) {
|
|
let beforeLen = parts.length;
|
|
walk(node.content);
|
|
// Add newline between block nodes
|
|
const blockTypes = ['paragraph', 'heading', 'blockquote', 'codeBlock'];
|
|
if (blockTypes.includes(node.type) && parts.length !== beforeLen) {
|
|
parts.push('\n');
|
|
}
|
|
}
|
|
};
|
|
walk(doc);
|
|
return parts.join('').replace(/\n{3,}/g, '\n\n').trim();
|
|
} catch (e) {
|
|
return typeof doc === 'string' ? doc : JSON.stringify(doc);
|
|
}
|
|
}
|
|
|
|
// --- HTML helpers for PocketBase editor fields ---
|
|
function plainTextToHTML(text) {
|
|
const safe = (text || '').replace(/\r\n|\r|\n/g, '\n');
|
|
const lines = safe.split('\n');
|
|
// Wrap each line in <p>, preserve blank lines
|
|
const html = lines.map(line => `<p>${escapeHtml(line)}</p>`).join('');
|
|
return html;
|
|
}
|
|
|
|
function escapeHtml(str) {
|
|
return String(str)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
function htmlToPlainText(html) {
|
|
try {
|
|
const div = document.createElement('div');
|
|
div.innerHTML = html || '';
|
|
return (div.innerText || '').trim();
|
|
} catch {
|
|
return html || '';
|
|
}
|
|
}
|
|
|
|
// Update auth UI based on login state
|
|
function updateAuthUI() {
|
|
const loginContainer = document.getElementById('loginContainer');
|
|
const userDisplay = document.getElementById('userDisplay');
|
|
const userEmail = document.getElementById('userEmail');
|
|
if (pb.authStore.isValid) {
|
|
loginContainer.classList.add('hidden');
|
|
userDisplay.classList.remove('hidden');
|
|
userEmail.classList.remove('hidden');
|
|
document.getElementById('noteContainer').classList.remove('hidden');
|
|
} else {
|
|
loginContainer.classList.remove('hidden');
|
|
userDisplay.classList.add('hidden');
|
|
userEmail.classList.add('hidden');
|
|
document.getElementById('loginError').classList.add('hidden');
|
|
document.getElementById('noteContainer').classList.add('hidden');
|
|
}
|
|
}
|
|
|
|
// Check for tokens and log success
|
|
async function checkTokens() {
|
|
const pbToken = pb.authStore.token;
|
|
|
|
if (!pbToken) {
|
|
console.log('❌ No PocketBase token found');
|
|
return;
|
|
}
|
|
|
|
console.log('✓ PocketBase token:', pbToken ? '(present)' : '(missing)');
|
|
|
|
try {
|
|
const healthResp = await fetch('/health');
|
|
const health = await healthResp.json();
|
|
if (health.ok) {
|
|
console.log('✓ Backend health check passed');
|
|
}
|
|
const graphBadge = document.getElementById('graphStatus');
|
|
const graphResp = await fetch('/api/graph/status');
|
|
if (graphResp.ok) {
|
|
const gs = await graphResp.json();
|
|
graphBadge.textContent = `Graph: active (exp ${new Date(gs.expiresOnISO).toLocaleTimeString()})`;
|
|
graphBadge.className = 'text-xs px-2 py-1 rounded bg-green-100 text-green-700';
|
|
console.log('✓ Graph token active');
|
|
} else {
|
|
graphBadge.textContent = 'Graph: error';
|
|
graphBadge.className = 'text-xs px-2 py-1 rounded bg-red-100 text-red-700';
|
|
console.log('❌ Graph token status failed');
|
|
}
|
|
} catch (error) {
|
|
console.error('❌ Failed to check backend:', error.message);
|
|
const graphBadge = document.getElementById('graphStatus');
|
|
graphBadge.textContent = 'Graph: error';
|
|
graphBadge.className = 'text-xs px-2 py-1 rounded bg-red-100 text-red-700';
|
|
}
|
|
}
|
|
|
|
async function ensureUserLogged() {
|
|
// If already have a valid token, just refresh to get model details
|
|
if (pb.authStore.isValid && pb.authStore.token) {
|
|
try {
|
|
const refresh = await pb.collection('Users').authRefresh();
|
|
const record = refresh?.record || pb.authStore.record || pb.authStore.model;
|
|
const meta = refresh?.meta || {};
|
|
const model = pb.authStore.model;
|
|
const displayName = record?.name || model?.name || meta?.name || record?.email || model?.email || meta?.email || 'Unknown User';
|
|
const email = record?.email || model?.email || meta?.email || '(no email)';
|
|
displayNameCache = displayName;
|
|
userEmailCache = email;
|
|
document.getElementById('userDisplayName').textContent = displayName;
|
|
document.getElementById('userEmailValue').textContent = email;
|
|
console.log('User record:', record);
|
|
console.log('User meta:', meta);
|
|
console.log('Auth store model:', model);
|
|
console.log(`User display name: ${displayName}`);
|
|
console.log(`User email: ${email}`);
|
|
console.log('PB token:', pb.authStore.token ? '(present)' : '(missing)');
|
|
updateAuthUI();
|
|
await checkTokens();
|
|
return true;
|
|
} catch (e) {
|
|
console.warn('Existing token invalid, clearing and reauth needed', e);
|
|
pb.authStore.clear();
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Handle login button click
|
|
document.getElementById('loginBtn').addEventListener('click', async (e) => {
|
|
e.preventDefault();
|
|
const loginBtn = document.getElementById('loginBtn');
|
|
const loginError = document.getElementById('loginError');
|
|
|
|
loginBtn.disabled = true;
|
|
loginBtn.textContent = 'Checking session...';
|
|
loginError.classList.add('hidden');
|
|
|
|
// If we already have a valid token, just use it
|
|
const hadToken = await ensureUserLogged();
|
|
if (hadToken) {
|
|
loginBtn.disabled = false;
|
|
loginBtn.textContent = 'Login with Microsoft';
|
|
return;
|
|
}
|
|
|
|
// Otherwise perform OAuth
|
|
loginBtn.textContent = 'Logging in...';
|
|
try {
|
|
const authData = await pb.collection('Users').authWithOAuth2({ provider: 'microsoft' });
|
|
console.log('✓ Logged in with Microsoft');
|
|
const record = authData?.record || pb.authStore.record || pb.authStore.model;
|
|
const meta = authData?.meta || {};
|
|
const model = pb.authStore.model;
|
|
const displayName = record?.name || model?.name || meta?.name || record?.email || model?.email || meta?.email || 'Unknown User';
|
|
const email = record?.email || model?.email || meta?.email || '(no email)';
|
|
displayNameCache = displayName;
|
|
userEmailCache = email;
|
|
document.getElementById('userDisplayName').textContent = displayName;
|
|
document.getElementById('userEmailValue').textContent = email;
|
|
console.log('User record:', record);
|
|
console.log('User meta:', meta);
|
|
console.log('Auth store model:', model);
|
|
console.log(`User display name: ${displayName}`);
|
|
console.log(`User email: ${email}`);
|
|
console.log('PB token:', pb.authStore.token ? '(present)' : '(missing)');
|
|
updateAuthUI();
|
|
await checkTokens();
|
|
} catch (error) {
|
|
console.error(error);
|
|
loginError.textContent = `Login failed: ${error.message}`;
|
|
loginError.classList.remove('hidden');
|
|
} finally {
|
|
loginBtn.disabled = false;
|
|
loginBtn.textContent = 'Login with Microsoft';
|
|
}
|
|
});
|
|
|
|
// Initial auth UI update
|
|
updateAuthUI();
|
|
|
|
// If already logged in, use existing token
|
|
if (pb.authStore.isValid && pb.authStore.token) {
|
|
ensureUserLogged();
|
|
}
|
|
|
|
// --- Audio recording setup ---
|
|
async function setupRecorder() {
|
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
audio: {
|
|
autoGainControl: true
|
|
}
|
|
});
|
|
recordedChunks = [];
|
|
recordedBlob = null;
|
|
mediaRecorder = new MediaRecorder(stream);
|
|
mediaRecorder.ondataavailable = (e) => {
|
|
if (e.data && e.data.size > 0) recordedChunks.push(e.data);
|
|
};
|
|
mediaRecorder.onstop = () => {
|
|
recordedBlob = new Blob(recordedChunks, { type: mediaRecorder.mimeType });
|
|
const audioEl = document.getElementById('audioPreview');
|
|
audioEl.src = URL.createObjectURL(recordedBlob);
|
|
audioEl.volume = 1.0;
|
|
audioEl.classList.remove('hidden');
|
|
document.getElementById('clearAudioLink').classList.remove('hidden');
|
|
document.getElementById('recordStatus').textContent = `Audio recorded (${mediaRecorder.mimeType}).`;
|
|
};
|
|
}
|
|
|
|
async function startRecording() {
|
|
if (!mediaRecorder) await setupRecorder();
|
|
recordedChunks = [];
|
|
recordedBlob = null;
|
|
mediaRecorder.start();
|
|
document.getElementById('recordStatus').textContent = 'Recording…';
|
|
document.getElementById('recordBtn').disabled = true;
|
|
document.getElementById('stopBtn').disabled = false;
|
|
}
|
|
|
|
function stopRecording() {
|
|
if (mediaRecorder && mediaRecorder.state === 'recording') {
|
|
mediaRecorder.stop();
|
|
document.getElementById('recordBtn').disabled = false;
|
|
document.getElementById('stopBtn').disabled = true;
|
|
}
|
|
}
|
|
|
|
function clearAudio() {
|
|
recordedChunks = [];
|
|
recordedBlob = null;
|
|
const audioEl = document.getElementById('audioPreview');
|
|
audioEl.src = '';
|
|
audioEl.classList.add('hidden');
|
|
document.getElementById('clearAudioLink').classList.add('hidden');
|
|
document.getElementById('recordStatus').textContent = 'No audio recorded.';
|
|
}
|
|
|
|
document.getElementById('recordBtn').addEventListener('click', startRecording);
|
|
document.getElementById('stopBtn').addEventListener('click', stopRecording);
|
|
document.getElementById('clearAudioLink').addEventListener('click', (e) => { e.preventDefault(); clearAudio(); });
|
|
|
|
// --- Test mic input levels ---
|
|
async function testMicrophone() {
|
|
const resultsDiv = document.getElementById('micTestResults');
|
|
resultsDiv.classList.remove('hidden');
|
|
document.getElementById('micStatus').textContent = 'Testing... speak normally';
|
|
|
|
try {
|
|
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
const recorder = new MediaRecorder(stream);
|
|
let testChunks = [];
|
|
|
|
recorder.ondataavailable = (e) => {
|
|
if (e.data.size > 0) testChunks.push(e.data);
|
|
};
|
|
|
|
recorder.onstop = () => {
|
|
stream.getTracks().forEach(track => track.stop());
|
|
|
|
const totalSize = testChunks.reduce((sum, chunk) => sum + chunk.size, 0);
|
|
// Rough estimation: 16kHz, 16-bit, mono = 32KB per second of audio
|
|
// Expected for good audio is ~30-60KB for 2 seconds
|
|
const estimatedLevel = Math.min(100, Math.round((totalSize / 32000) * 100));
|
|
|
|
document.getElementById('micPeakLevel').textContent = estimatedLevel;
|
|
document.getElementById('micAvgLevel').textContent = totalSize + ' bytes';
|
|
|
|
if (totalSize < 10000) {
|
|
document.getElementById('micStatus').textContent = '⚠️ Very low - check mic or volume';
|
|
} else if (totalSize < 25000) {
|
|
document.getElementById('micStatus').textContent = '⚠️ Low - increase mic gain or speak louder';
|
|
} else if (totalSize > 80000) {
|
|
document.getElementById('micStatus').textContent = '⚠️ Too loud - may distort';
|
|
} else {
|
|
document.getElementById('micStatus').textContent = '✓ Good level';
|
|
}
|
|
};
|
|
|
|
recorder.start();
|
|
setTimeout(() => recorder.stop(), 2000);
|
|
} catch (e) {
|
|
document.getElementById('micStatus').textContent = `Error: ${e.message}`;
|
|
console.error('Mic test error:', e);
|
|
}
|
|
}
|
|
|
|
document.getElementById('testMicBtn').addEventListener('click', testMicrophone);
|
|
|
|
// --- Submit note ---
|
|
async function submitNote() {
|
|
const statusEl = document.getElementById('submitStatus');
|
|
statusEl.textContent = '';
|
|
const noteText = document.getElementById('noteText').value.trim();
|
|
let noteTitle = document.getElementById('noteTitle').value.trim();
|
|
if (!pb.authStore.isValid) {
|
|
statusEl.textContent = 'Not authenticated.';
|
|
return;
|
|
}
|
|
if (!noteText) {
|
|
statusEl.textContent = 'Please enter note text.';
|
|
return;
|
|
}
|
|
|
|
// Generate title if empty: "Untitled: first 4 words..."
|
|
if (!noteTitle) {
|
|
const words = noteText.split(/\s+/).filter(w => w.length > 0);
|
|
const firstFour = words.slice(0, 4).join(' ');
|
|
noteTitle = 'Untitled: ' + (firstFour || 'note');
|
|
}
|
|
|
|
try {
|
|
// Create note record with display name, email, and title
|
|
const noteRecord = await pb.collection(NOTES_COLLECTION).create({
|
|
[NOTE_BODY_HTML_FIELD]: plainTextToHTML(noteText),
|
|
[NOTE_BODY_PLAIN_FIELD]: noteText,
|
|
[NOTE_USERNAME_FIELD]: displayNameCache,
|
|
email: userEmailCache,
|
|
title: noteTitle,
|
|
userId: pb.authStore.model?.id || pb.authStore.record?.id,
|
|
});
|
|
let attachmentRecord = null;
|
|
if (recordedBlob) {
|
|
const file = new File([recordedBlob], 'note-audio.webm', { type: recordedBlob.type || 'audio/webm' });
|
|
const fd = new FormData();
|
|
fd.append(ATTACHMENTS_FILE_FIELD, file);
|
|
fd.append(ATTACHMENTS_PBID_FIELD, noteRecord.id);
|
|
attachmentRecord = await pb.collection(ATTACHMENTS_COLLECTION).create(fd);
|
|
}
|
|
statusEl.textContent = `Saved note ${noteRecord.id}` + (attachmentRecord ? ` with audio ${attachmentRecord.id}` : '');
|
|
clearAudio();
|
|
document.getElementById('noteText').value = '';
|
|
document.getElementById('noteTitle').value = '';
|
|
} catch (e) {
|
|
console.error(e);
|
|
statusEl.textContent = `Error saving: ${e.message}`;
|
|
}
|
|
}
|
|
|
|
document.getElementById('submitNoteBtn').addEventListener('click', submitNote);
|
|
|
|
// --- Load last note and attachment ---
|
|
async function loadLastNote() {
|
|
const loadStatus = document.getElementById('loadStatus');
|
|
const lastNoteBox = document.getElementById('lastNote');
|
|
loadStatus.textContent = '';
|
|
lastNoteBox.classList.add('hidden');
|
|
try {
|
|
const notes = await pb.collection(NOTES_COLLECTION).getList(1, 1, { sort: '-created' });
|
|
if (!notes.items.length) {
|
|
loadStatus.textContent = 'No notes found.';
|
|
return;
|
|
}
|
|
const note = notes.items[0];
|
|
function extractPlain(r) {
|
|
// Try actual schema fields in order
|
|
const candidates = [
|
|
r[NOTE_BODY_PLAIN_FIELD],
|
|
r[NOTE_BODY_HTML_FIELD],
|
|
r.note,
|
|
r.content,
|
|
r.body,
|
|
];
|
|
for (const c of candidates) {
|
|
if (c === undefined || c === null) continue;
|
|
if (typeof c === 'string' && c.trim()) return c;
|
|
if (typeof c === 'object') {
|
|
const maybe = tiptapToPlainText(c);
|
|
if (maybe && maybe.trim()) return maybe;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
let plain = extractPlain(note);
|
|
// If `plain` is HTML, convert to text
|
|
if (plain && /<\/?[a-z]/i.test(plain)) {
|
|
plain = htmlToPlainText(plain);
|
|
}
|
|
document.getElementById('lastNoteText').textContent = plain || '(empty)';
|
|
// Show raw for debugging
|
|
const rawEl = document.getElementById('lastNoteRaw');
|
|
rawEl.textContent = JSON.stringify({ body_html: note[NOTE_BODY_HTML_FIELD], body_plain: note[NOTE_BODY_PLAIN_FIELD], Username: note[NOTE_USERNAME_FIELD] }, null, 2);
|
|
// Find attachment by pb_id
|
|
const atts = await pb.collection(ATTACHMENTS_COLLECTION).getList(1, 1, {
|
|
sort: '-created',
|
|
filter: `${ATTACHMENTS_PBID_FIELD} = "${note.id}"`,
|
|
});
|
|
if (atts.items.length) {
|
|
const att = atts.items[0];
|
|
const url = pb.files.getUrl(att, att[ATTACHMENTS_FILE_FIELD]);
|
|
const lastAudio = document.getElementById('lastNoteAudio');
|
|
lastAudio.src = url;
|
|
lastAudio.volume = 1.0;
|
|
} else {
|
|
document.getElementById('lastNoteAudio').src = '';
|
|
}
|
|
lastNoteBox.classList.remove('hidden');
|
|
loadStatus.textContent = 'Loaded.';
|
|
} catch (e) {
|
|
console.error(e);
|
|
loadStatus.textContent = `Error: ${e.message}`;
|
|
}
|
|
}
|
|
|
|
document.getElementById('loadLastBtn').addEventListener('click', loadLastNote);
|
|
</script>
|
|
</body>
|
|
</html>
|