// AI Notes Application
class AINotesApp {
constructor() {
this.notes = JSON.parse(localStorage.getItem('aiNotes') || '[]');
this.currentNote = null;
this.apiKey = localStorage.getItem('openrouterApiKey') || '';
this.selectedModel = localStorage.getItem('selectedModel') || '';
this.models = [];
this.init();
}
init() {
this.setupEventListeners();
this.renderNotesList();
this.loadSettings();
this.fetchModels();
this.createNewNote();
}
setupEventListeners() {
// Header buttons
document.getElementById('settingsBtn').addEventListener('click', () => this.showSettings());
document.getElementById('newNoteBtn').addEventListener('click', () => this.createNewNote());
// Note title and content
document.getElementById('noteTitle').addEventListener('input', () => this.saveCurrentNote());
document.getElementById('noteContent').addEventListener('input', () => this.handleContentChange());
// AI Dialog
document.getElementById('closeAiDialog').addEventListener('click', () => this.hideAiDialog());
document.getElementById('sendBtn').addEventListener('click', () => this.sendAiMessage());
document.getElementById('aiMessage').addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.sendAiMessage();
});
// Settings modal
document.getElementById('closeSettings').addEventListener('click', () => this.hideSettings());
document.getElementById('saveSettings').addEventListener('click', () => this.saveSettings());
// Global key listeners
document.addEventListener('keydown', (e) => this.handleKeydown(e));
// Auto-save
setInterval(() => this.saveCurrentNote(), 30000);
}
handleKeydown(e) {
// Space bar at line start triggers AI dialog
if (e.key === ' ' && e.target.id === 'noteContent') {
const cursorPos = e.target.selectionStart;
const text = e.target.value;
// Check if cursor is at the start of a line
const lineStart = text.lastIndexOf('\n', cursorPos - 1) + 1;
const isLineStart = cursorPos === lineStart || (cursorPos === 0 && text.length === 0);
if (isLineStart) {
e.preventDefault();
this.showAiDialog();
}
}
// Escape closes dialogs
if (e.key === 'Escape') {
this.hideAiDialog();
this.hideSettings();
}
}
handleContentChange() {
// Add visual indicator when at line start
const textarea = document.getElementById('noteContent');
const cursorPos = textarea.selectionStart;
const text = textarea.value;
// This will be handled by the keydown event for space bar
}
showAiDialog() {
const dialog = document.getElementById('aiDialog');
dialog.classList.remove('hidden');
dialog.classList.add('ai-dialog-enter');
// Fill in current settings
const apiKeyInput = document.getElementById('apiKeyInput');
const modelSelect = document.getElementById('modelSelect');
if (this.apiKey) apiKeyInput.value = this.apiKey;
if (this.selectedModel) modelSelect.value = this.selectedModel;
// Focus on message input
setTimeout(() => {
document.getElementById('aiMessage').focus();
}, 100);
}
hideAiDialog() {
const dialog = document.getElementById('aiDialog');
dialog.classList.add('ai-dialog-exit');
setTimeout(() => {
dialog.classList.add('hidden');
dialog.classList.remove('ai-dialog-exit');
document.getElementById('aiMessage').value = '';
document.getElementById('aiResponse').classList.add('hidden');
}, 300);
}
async sendAiMessage() {
const message = document.getElementById('aiMessage').value.trim();
const apiKey = document.getElementById('apiKeyInput').value.trim() || this.apiKey;
const model = document.getElementById('modelSelect').value.trim() || this.selectedModel;
if (!message) return;
if (!apiKey) {
alert('请输入 API Key');
return;
}
if (!model) {
alert('请选择模型');
return;
}
// Update global settings
this.apiKey = apiKey;
this.selectedModel = model;
localStorage.setItem('openrouterApiKey', apiKey);
localStorage.setItem('selectedModel', model);
const sendBtn = document.getElementById('sendBtn');
const responseDiv = document.getElementById('aiResponse');
sendBtn.disabled = true;
sendBtn.innerHTML = '
';
responseDiv.classList.remove('hidden');
responseDiv.innerHTML = '';
try {
const response = await this.callOpenRouter(apiKey, model, message);
await this.streamResponse(response, responseDiv);
// Convert markdown to HTML and insert into editor
const markdownHtml = marked.parse(response);
this.insertMarkdownIntoEditor(markdownHtml);
} catch (error) {
responseDiv.innerHTML = `错误: ${error.message}
`;
} finally {
sendBtn.disabled = false;
sendBtn.innerHTML = '';
feather.replace();
}
}
async callOpenRouter(apiKey, model, message) {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': window.location.origin,
'X-Title': 'AI Notes'
},
body: JSON.stringify({
model: model,
messages: [
{
role: 'user',
content: message
}
],
stream: true
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error?.message || `HTTP ${response.status}`);
}
return response;
}
async streamResponse(response, responseDiv) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
responseDiv.innerHTML = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n').filter(line => line.trim());
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
fullResponse += content;
responseDiv.innerHTML = `${marked.parse(fullResponse)}
`;
}
} catch (e) {
// Ignore parsing errors for keep-alive lines
}
}
}
}
return fullResponse;
}
insertMarkdownIntoEditor(htmlContent) {
const textarea = document.getElementById('noteContent');
const cursorPos = textarea.selectionStart;
const text = textarea.value;
// Find the start of the current line
const lineStart = text.lastIndexOf('\n', cursorPos - 1) + 1;
// Insert a newline and the AI response
const insertText = `\n\n${htmlContent}\n`;
const newText = text.substring(0, lineStart) + insertText + text.substring(cursorPos);
textarea.value = newText;
// Set cursor position after the inserted content
const newCursorPos = lineStart + insertText.length;
textarea.setSelectionRange(newCursorPos, newCursorPos);
textarea.focus();
this.saveCurrentNote();
}
async fetchModels() {
if (!this.apiKey) return;
try {
const response = await fetch('https://openrouter.ai/api/v1/models', {
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
this.models = data.data || [];
this.populateModelSelects();
}
} catch (error) {
console.warn('Failed to fetch models:', error);
}
}
populateModelSelects() {
const modelSelects = ['modelSelect', 'globalModelSelect'];
modelSelects.forEach(selectId => {
const select = document.getElementById(selectId);
if (!select) return;
// Clear existing options except the first one
while (select.children.length > 1) {
select.removeChild(select.lastChild);
}
// Add model options
this.models.forEach(model => {
const option = document.createElement('option');
option.value = model.id;
option.textContent = model.name || model.id;
if (model.id === this.selectedModel) {
option.selected = true;
}
select.appendChild(option);
});
});
}
createNewNote() {
const newNote = {
id: Date.now(),
title: '无标题笔记',
content: '',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
this.notes.unshift(newNote);
this.currentNote = newNote;
this.loadNoteToEditor(newNote);
this.renderNotesList();
this.saveNotes();
}
loadNoteToEditor(note) {
document.getElementById('noteTitle').value = note.title;
document.getElementById('noteContent').value = note.content;
}
saveCurrentNote() {
if (!this.currentNote) return;
this.currentNote.title = document.getElementById('noteTitle').value || '无标题笔记';
this.currentNote.content = document.getElementById('noteContent').value;
this.currentNote.updatedAt = new Date().toISOString();
// Update in notes array
const index = this.notes.findIndex(note => note.id === this.currentNote.id);
if (index !== -1) {
this.notes[index] = this.currentNote;
}
this.saveNotes();
this.renderNotesList();
}
loadNote(note) {
this.currentNote = note;
this.loadNoteToEditor(note);
}
deleteNote(noteId) {
if (confirm('确定要删除这个笔记吗?')) {
this.notes = this.notes.filter(note => note.id !== noteId);
if (this.currentNote?.id === noteId) {
this.createNewNote();
}
this.saveNotes();
this.renderNotesList();
}
}
saveNotes() {
localStorage.setItem('aiNotes', JSON.stringify(this.notes));
}
renderNotesList() {
const notesList = document.getElementById('notesList');
if (this.notes.length === 0) {
notesList.innerHTML = `
`;
feather.replace();
return;
}
notesList.innerHTML = this.notes.map(note => `
${this.escapeHtml(note.title)}
${this.escapeHtml(note.content.substring(0, 100))}${note.content.length > 100 ? '...' : ''}
${new Date(note.updatedAt).toLocaleDateString('zh-CN')}
`).join('');
feather.replace();
}
showSettings() {
document.getElementById('settingsModal').classList.remove('hidden');
document.getElementById('globalApiKey').value = this.apiKey;
document.getElementById('globalModelSelect').value = this.selectedModel;
}
hideSettings() {
document.getElementById('settingsModal').classList.add('hidden');
}
saveSettings() {
this.apiKey = document.getElementById('globalApiKey').value.trim();
this.selectedModel = document.getElementById('globalModelSelect').value;
localStorage.setItem('openrouterApiKey', this.apiKey);
localStorage.setItem('selectedModel', this.selectedModel);
if (this.apiKey) {
this.fetchModels();
}
this.hideSettings();
// Update the AI dialog if it's open
if (!document.getElementById('aiDialog').classList.contains('hidden')) {
document.getElementById('apiKeyInput').value = this.apiKey;
document.getElementById('modelSelect').value = this.selectedModel;
}
}
loadSettings() {
// This is handled in the constructor, but we can refresh the UI
if (this.apiKey) {
this.fetchModels();
}
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
// Initialize the app
const app = new AINotesApp();