Spaces:
Running
Running
创建一个在线的IOS笔记,支持笔记中行首按下空格键启动AI对话,对应位置弹出一个AI对话框,输入内容后按下enter,AI回复是流式输出的,输出的markdown文档渲染后添加到编辑区,AI需要设置apikey,模型是像openrouter请求的模型列表,输入后可以匹配模型
fc417df verified Download script.js from edwardwongasd/ios-notes-ai: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/edwardwongasd/ios-notes-ai/resolve/main/script.js
- Command line
-
hf download hf://spaces/edwardwongasd/ios-notes-ai/script.js
-
curl -L -o script.js https://huggingface.co/spaces/edwardwongasd/ios-notes-ai/resolve/main/script.js
15.4 kB
| // 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 = '<div class="typing-indicator"></div>'; | |
| responseDiv.classList.remove('hidden'); | |
| responseDiv.innerHTML = '<div class="typing-indicators"><div class="typing-indicator"></div><div class="typing-indicator"></div><div class="typing-indicator"></div></div>'; | |
| 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 = `<div class="text-red-500">错误: ${error.message}</div>`; | |
| } finally { | |
| sendBtn.disabled = false; | |
| sendBtn.innerHTML = '<i data-feather="send" class="w-4 h-4"></i>'; | |
| 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 = `<div class="markdown-content">${marked.parse(fullResponse)}</div>`; | |
| } | |
| } 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 = ` | |
| <div class="col-span-full text-center py-12"> | |
| <i data-feather="file-text" class="w-12 h-12 text-gray-300 mx-auto mb-4"></i> | |
| <p class="text-gray-500">还没有笔记,开始创建你的第一个笔记吧!</p> | |
| </div> | |
| `; | |
| feather.replace(); | |
| return; | |
| } | |
| notesList.innerHTML = this.notes.map(note => ` | |
| <div class="note-card bg-white rounded-xl p-4 border border-gray-200 cursor-pointer" onclick="app.loadNote(${note.id})"> | |
| <div class="flex items-start justify-between mb-3"> | |
| <h3 class="font-medium text-gray-800 truncate pr-2">${this.escapeHtml(note.title)}</h3> | |
| <button onclick="event.stopPropagation(); app.deleteNote(${note.id})" class="text-gray-400 hover:text-red-500 transition-colors"> | |
| <i data-feather="trash-2" class="w-4 h-4"></i> | |
| </button> | |
| </div> | |
| <p class="text-sm text-gray-600 line-clamp-3 mb-3">${this.escapeHtml(note.content.substring(0, 100))}${note.content.length > 100 ? '...' : ''}</p> | |
| <div class="text-xs text-gray-400"> | |
| ${new Date(note.updatedAt).toLocaleDateString('zh-CN')} | |
| </div> | |
| </div> | |
| `).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(); |