Initial commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+24
@@ -0,0 +1,24 @@
|
||||
import { useEffect } from 'react'
|
||||
import { Sidebar } from './components/sidebar/Sidebar'
|
||||
import { Editor } from './components/editor/Editor'
|
||||
import { useAppStore } from './stores/appStore'
|
||||
import { seedIfEmpty } from './db'
|
||||
|
||||
export default function App() {
|
||||
const { loadAll, theme } = useAppStore()
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-theme', theme)
|
||||
}, [theme])
|
||||
|
||||
useEffect(() => {
|
||||
seedIfEmpty().then(() => loadAll())
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-full overflow-hidden" style={{ background: 'var(--bg)' }}>
|
||||
<Sidebar />
|
||||
<Editor />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,359 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useEditor, EditorContent } from '@tiptap/react'
|
||||
import { BubbleMenu } from '@tiptap/extension-bubble-menu'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import Placeholder from '@tiptap/extension-placeholder'
|
||||
import Underline from '@tiptap/extension-underline'
|
||||
import TaskList from '@tiptap/extension-task-list'
|
||||
import TaskItem from '@tiptap/extension-task-item'
|
||||
import { Table } from '@tiptap/extension-table'
|
||||
import TableRow from '@tiptap/extension-table-row'
|
||||
import TableCell from '@tiptap/extension-table-cell'
|
||||
import TableHeader from '@tiptap/extension-table-header'
|
||||
import CharacterCount from '@tiptap/extension-character-count'
|
||||
import Typography from '@tiptap/extension-typography'
|
||||
import Link from '@tiptap/extension-link'
|
||||
import Highlight from '@tiptap/extension-highlight'
|
||||
import { TextStyle } from '@tiptap/extension-text-style'
|
||||
import {
|
||||
Bold, Italic, Underline as UnderlineIcon, Strikethrough, Code,
|
||||
Highlighter, List, ListOrdered, Quote,
|
||||
Heading1, Heading2, Heading3, Minus, CheckSquare, Table as TableIcon,
|
||||
Type,
|
||||
} from 'lucide-react'
|
||||
import { useAppStore } from '../../stores/appStore'
|
||||
import { countWords } from '../../lib/utils'
|
||||
|
||||
// Slash command items
|
||||
const SLASH_ITEMS = [
|
||||
{ label: '正文', desc: '普通段落', icon: <Type size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().setParagraph().run() },
|
||||
{ label: '标题 1', desc: '大标题', icon: <Heading1 size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().setHeading({ level: 1 }).run() },
|
||||
{ label: '标题 2', desc: '中标题', icon: <Heading2 size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().setHeading({ level: 2 }).run() },
|
||||
{ label: '标题 3', desc: '小标题', icon: <Heading3 size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().setHeading({ level: 3 }).run() },
|
||||
{ label: '无序列表', desc: '• 项目', icon: <List size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().toggleBulletList().run() },
|
||||
{ label: '有序列表', desc: '1. 项目', icon: <ListOrdered size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().toggleOrderedList().run() },
|
||||
{ label: '任务列表', desc: '☑ 待办', icon: <CheckSquare size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().toggleTaskList().run() },
|
||||
{ label: '引用', desc: '引用文本', icon: <Quote size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().toggleBlockquote().run() },
|
||||
{ label: '代码块', desc: '多行代码', icon: <Code size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().toggleCodeBlock().run() },
|
||||
{ label: '分割线', desc: '水平线', icon: <Minus size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().setHorizontalRule().run() },
|
||||
{ label: '表格', desc: '插入表格', icon: <TableIcon size={14} />, action: (e: ReturnType<typeof useEditor>) => e?.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() },
|
||||
]
|
||||
|
||||
type SlashItem = typeof SLASH_ITEMS[0]
|
||||
|
||||
function SlashMenu({ items, selectedIndex, onSelect }: {
|
||||
items: SlashItem[]
|
||||
selectedIndex: number
|
||||
onSelect: (item: SlashItem) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="slash-menu">
|
||||
{items.map((item, i) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className={`slash-menu-item ${i === selectedIndex ? 'active' : ''}`}
|
||||
onMouseDown={(e) => { e.preventDefault(); onSelect(item) }}
|
||||
>
|
||||
<div className="slash-menu-item-icon">{item.icon}</div>
|
||||
<div>
|
||||
<div className="slash-menu-item-label">{item.label}</div>
|
||||
<div className="slash-menu-item-desc">{item.desc}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Editor() {
|
||||
const { activeNoteId, notes, updateNote } = useAppStore()
|
||||
const activeNote = notes.find(n => n.id === activeNoteId)
|
||||
|
||||
const [title, setTitle] = useState(activeNote?.title ?? '')
|
||||
const [wordCount, setWordCount] = useState(0)
|
||||
const [saveStatus, setSaveStatus] = useState<'saved' | 'saving' | 'unsaved'>('saved')
|
||||
|
||||
const [slashOpen, setSlashOpen] = useState(false)
|
||||
const [slashQuery, setSlashQuery] = useState('')
|
||||
const [slashIndex, setSlashIndex] = useState(0)
|
||||
const [slashPos, setSlashPos] = useState({ top: 0, left: 0 })
|
||||
const slashStartPos = useRef<number | null>(null)
|
||||
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const titleTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const isLoadingRef = useRef(false)
|
||||
|
||||
const filteredSlash = SLASH_ITEMS.filter(item =>
|
||||
item.label.toLowerCase().includes(slashQuery.toLowerCase())
|
||||
)
|
||||
|
||||
const scheduleNoteSave = useCallback((content: string, wc: number) => {
|
||||
if (!activeNoteId || isLoadingRef.current) return
|
||||
setSaveStatus('unsaved')
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current)
|
||||
saveTimer.current = setTimeout(async () => {
|
||||
setSaveStatus('saving')
|
||||
await updateNote(activeNoteId, { content, wordCount: wc })
|
||||
setSaveStatus('saved')
|
||||
}, 1000)
|
||||
}, [activeNoteId, updateNote])
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Placeholder.configure({ placeholder: '开始写作,或输入 / 呼出命令菜单…' }),
|
||||
Underline,
|
||||
TaskList,
|
||||
TaskItem.configure({ nested: true }),
|
||||
Table.configure({ resizable: false }),
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableHeader,
|
||||
CharacterCount,
|
||||
Typography,
|
||||
Highlight.configure({ multicolor: false }),
|
||||
TextStyle,
|
||||
Link.configure({ openOnClick: false }),
|
||||
BubbleMenu.configure({ pluginKey: 'bubbleMenu' }),
|
||||
],
|
||||
content: activeNote?.content ? JSON.parse(activeNote.content) : '',
|
||||
onUpdate({ editor: ed }) {
|
||||
if (isLoadingRef.current) return
|
||||
const json = JSON.stringify(ed.getJSON())
|
||||
const text = ed.getText()
|
||||
const wc = countWords(text)
|
||||
setWordCount(wc)
|
||||
scheduleNoteSave(json, wc)
|
||||
checkSlashCommand(ed)
|
||||
},
|
||||
editorProps: {
|
||||
handleKeyDown(_view, event) {
|
||||
if (slashOpen) {
|
||||
if (event.key === 'ArrowDown') {
|
||||
setSlashIndex(i => (i + 1) % filteredSlash.length)
|
||||
return true
|
||||
}
|
||||
if (event.key === 'ArrowUp') {
|
||||
setSlashIndex(i => (i - 1 + filteredSlash.length) % filteredSlash.length)
|
||||
return true
|
||||
}
|
||||
if (event.key === 'Enter') {
|
||||
const item = filteredSlash[slashIndex]
|
||||
if (item && editor) executeSlash(item)
|
||||
return true
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
setSlashOpen(false)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
function checkSlashCommand(ed: NonNullable<ReturnType<typeof useEditor>>) {
|
||||
const { state } = ed
|
||||
const { selection } = state
|
||||
const { $from } = selection
|
||||
const textBefore = $from.nodeBefore?.text ?? ''
|
||||
const slashIdx = textBefore.lastIndexOf('/')
|
||||
|
||||
if (slashIdx >= 0) {
|
||||
const query = textBefore.slice(slashIdx + 1)
|
||||
if (!query.includes(' ')) {
|
||||
if (slashStartPos.current === null) {
|
||||
slashStartPos.current = $from.pos - textBefore.length + slashIdx
|
||||
}
|
||||
setSlashQuery(query)
|
||||
setSlashIndex(0)
|
||||
|
||||
const coords = ed.view.coordsAtPos($from.pos)
|
||||
const editorEl = ed.view.dom.closest('.editor-scroll')
|
||||
if (editorEl) {
|
||||
const rect = editorEl.getBoundingClientRect()
|
||||
setSlashPos({ top: coords.bottom - rect.top + 4, left: coords.left - rect.left })
|
||||
}
|
||||
setSlashOpen(true)
|
||||
return
|
||||
}
|
||||
}
|
||||
setSlashOpen(false)
|
||||
slashStartPos.current = null
|
||||
}
|
||||
|
||||
function executeSlash(item: SlashItem) {
|
||||
if (!editor) return
|
||||
const startPos = slashStartPos.current
|
||||
if (startPos !== null) {
|
||||
const { state, dispatch } = editor.view
|
||||
const { from } = state.selection
|
||||
const tr = state.tr.delete(startPos, from)
|
||||
dispatch(tr)
|
||||
}
|
||||
item.action(editor)
|
||||
setSlashOpen(false)
|
||||
slashStartPos.current = null
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!editor || !activeNote) return
|
||||
isLoadingRef.current = true
|
||||
const content = activeNote.content
|
||||
? JSON.parse(activeNote.content)
|
||||
: { type: 'doc', content: [{ type: 'paragraph' }] }
|
||||
editor.commands.setContent(content)
|
||||
setTitle(activeNote.title)
|
||||
setWordCount(activeNote.wordCount)
|
||||
setSaveStatus('saved')
|
||||
setSlashOpen(false)
|
||||
setTimeout(() => { isLoadingRef.current = false }, 100)
|
||||
}, [activeNoteId, editor])
|
||||
|
||||
const handleTitleChange = (val: string) => {
|
||||
setTitle(val)
|
||||
if (!activeNoteId) return
|
||||
if (titleTimer.current) clearTimeout(titleTimer.current)
|
||||
titleTimer.current = setTimeout(() => {
|
||||
updateNote(activeNoteId, { title: val })
|
||||
}, 500)
|
||||
}
|
||||
|
||||
if (!activeNote) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center" style={{ color: 'var(--text-faint)' }}>
|
||||
<div className="text-center">
|
||||
<div className="text-5xl mb-4 opacity-20">✏️</div>
|
||||
<p className="text-base">选择一篇笔记,或创建新笔记</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col min-w-0 h-full" style={{ background: 'var(--bg)' }}>
|
||||
{/* Title */}
|
||||
<div className="px-12 pt-10 pb-0 max-w-3xl mx-auto w-full">
|
||||
<input
|
||||
value={title}
|
||||
onChange={e => handleTitleChange(e.target.value)}
|
||||
placeholder="无标题"
|
||||
className="w-full bg-transparent outline-none text-3xl font-bold"
|
||||
style={{ color: 'var(--text)', letterSpacing: '-0.02em' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Floating bubble menu rendered via portal */}
|
||||
{editor && (
|
||||
<div
|
||||
id="bubble-menu-portal"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
zIndex: 100,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<FloatingToolbar editor={editor} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Editor scroll */}
|
||||
<div className="flex-1 overflow-y-auto editor-scroll relative px-12 pt-4 pb-4">
|
||||
<div className="max-w-3xl mx-auto w-full relative">
|
||||
<EditorContent editor={editor} />
|
||||
|
||||
{slashOpen && filteredSlash.length > 0 && (
|
||||
<div
|
||||
className="absolute z-50"
|
||||
style={{ top: slashPos.top, left: Math.max(0, slashPos.left) }}
|
||||
>
|
||||
<SlashMenu
|
||||
items={filteredSlash}
|
||||
selectedIndex={slashIndex}
|
||||
onSelect={executeSlash}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div
|
||||
className="flex items-center justify-between px-12 py-2 text-xs shrink-0"
|
||||
style={{
|
||||
borderTop: '1px solid var(--border)',
|
||||
color: 'var(--text-faint)',
|
||||
background: 'var(--bg)',
|
||||
}}
|
||||
>
|
||||
<span>{wordCount} 字</span>
|
||||
<span style={{ color: saveStatus === 'saved' ? 'var(--text-faint)' : 'var(--accent)' }}>
|
||||
{saveStatus === 'saving' ? '保存中…' : saveStatus === 'unsaved' ? '未保存' : '已自动保存'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FloatingToolbar({ editor }: { editor: NonNullable<ReturnType<typeof useEditor>> }) {
|
||||
const [visible, setVisible] = useState(false)
|
||||
const [pos, setPos] = useState({ top: 0, left: 0 })
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
const { state, view } = editor
|
||||
const { selection } = state
|
||||
if (selection.empty) { setVisible(false); return }
|
||||
const { from, to } = selection
|
||||
const start = view.coordsAtPos(from)
|
||||
const end = view.coordsAtPos(to)
|
||||
const top = Math.min(start.top, end.top) - 48
|
||||
const left = (start.left + end.left) / 2 - 100
|
||||
setPos({ top: Math.max(8, top), left: Math.max(8, left) })
|
||||
setVisible(true)
|
||||
}
|
||||
editor.on('selectionUpdate', update)
|
||||
editor.on('blur', () => setVisible(false))
|
||||
return () => {
|
||||
editor.off('selectionUpdate', update)
|
||||
}
|
||||
}, [editor])
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="floating-toolbar"
|
||||
style={{ position: 'fixed', top: pos.top, left: pos.left, pointerEvents: 'auto', zIndex: 100 }}
|
||||
>
|
||||
<ToolbarBtn title="粗体" active={editor.isActive('bold')} onClick={() => editor.chain().focus().toggleBold().run()}><Bold size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="斜体" active={editor.isActive('italic')} onClick={() => editor.chain().focus().toggleItalic().run()}><Italic size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="下划线" active={editor.isActive('underline')} onClick={() => editor.chain().focus().toggleUnderline().run()}><UnderlineIcon size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="删除线" active={editor.isActive('strike')} onClick={() => editor.chain().focus().toggleStrike().run()}><Strikethrough size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="行内代码" active={editor.isActive('code')} onClick={() => editor.chain().focus().toggleCode().run()}><Code size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="高亮" active={editor.isActive('highlight')} onClick={() => editor.chain().focus().toggleHighlight().run()}><Highlighter size={13} /></ToolbarBtn>
|
||||
<div className="toolbar-divider" />
|
||||
<ToolbarBtn title="H1" active={editor.isActive('heading', { level: 1 })} onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}><Heading1 size={13} /></ToolbarBtn>
|
||||
<ToolbarBtn title="H2" active={editor.isActive('heading', { level: 2 })} onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}><Heading2 size={13} /></ToolbarBtn>
|
||||
<div className="toolbar-divider" />
|
||||
<ToolbarBtn title="引用" active={editor.isActive('blockquote')} onClick={() => editor.chain().focus().toggleBlockquote().run()}><Quote size={13} /></ToolbarBtn>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ToolbarBtn({ children, active, title, onClick }: {
|
||||
children: React.ReactNode
|
||||
active: boolean
|
||||
title?: string
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
title={title}
|
||||
onMouseDown={(e) => { e.preventDefault(); onClick() }}
|
||||
className={`toolbar-btn ${active ? 'active' : ''}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import {
|
||||
Search, Plus, Star, FileText, Folder, FolderOpen,
|
||||
ChevronRight, ChevronDown,
|
||||
Trash2, Edit2, Moon, Sun, FolderPlus, Hash,
|
||||
} from 'lucide-react'
|
||||
import { useAppStore } from '../../stores/appStore'
|
||||
import { formatDate } from '../../lib/utils'
|
||||
import type { Folder as FolderType } from '../../db'
|
||||
|
||||
export function Sidebar() {
|
||||
const {
|
||||
notes, folders, activeNoteId, activeFolderId, searchQuery,
|
||||
theme, createNote, createFolder, deleteNote, deleteFolder,
|
||||
updateFolder, setActiveNote, setActiveFolder, setSearch,
|
||||
toggleTheme, filteredNotes,
|
||||
} = useAppStore()
|
||||
|
||||
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set())
|
||||
const [editingFolderId, setEditingFolderId] = useState<string | null>(null)
|
||||
const [newFolderName, setNewFolderName] = useState('')
|
||||
const [creatingFolder, setCreatingFolder] = useState(false)
|
||||
const [newFolderInput, setNewFolderInput] = useState('')
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
type: 'note' | 'folder'
|
||||
id: string
|
||||
x: number
|
||||
y: number
|
||||
} | null>(null)
|
||||
|
||||
const editInputRef = useRef<HTMLInputElement>(null)
|
||||
const newFolderRef = useRef<HTMLInputElement>(null)
|
||||
const displayed = filteredNotes()
|
||||
|
||||
useEffect(() => {
|
||||
if (editingFolderId && editInputRef.current) editInputRef.current.focus()
|
||||
}, [editingFolderId])
|
||||
|
||||
useEffect(() => {
|
||||
if (creatingFolder && newFolderRef.current) newFolderRef.current.focus()
|
||||
}, [creatingFolder])
|
||||
|
||||
useEffect(() => {
|
||||
const close = () => setContextMenu(null)
|
||||
window.addEventListener('click', close)
|
||||
return () => window.removeEventListener('click', close)
|
||||
}, [])
|
||||
|
||||
const toggleFolder = (id: string) => {
|
||||
setExpandedFolders(s => {
|
||||
const next = new Set(s)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleRenameFolder = async (id: string) => {
|
||||
if (!newFolderName.trim()) return
|
||||
await updateFolder(id, { name: newFolderName.trim() })
|
||||
setEditingFolderId(null)
|
||||
}
|
||||
|
||||
const handleCreateFolder = async () => {
|
||||
if (!newFolderInput.trim()) { setCreatingFolder(false); return }
|
||||
await createFolder(newFolderInput.trim())
|
||||
setNewFolderInput('')
|
||||
setCreatingFolder(false)
|
||||
}
|
||||
|
||||
const handleNewNote = async () => {
|
||||
const folderId = typeof activeFolderId === 'string' && activeFolderId !== 'all' && activeFolderId !== 'starred'
|
||||
? activeFolderId
|
||||
: null
|
||||
await createNote(folderId)
|
||||
}
|
||||
|
||||
const rootFolders = folders.filter(f => f.parentId === null)
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="flex flex-col h-full shrink-0 border-r"
|
||||
style={{
|
||||
width: 260,
|
||||
background: 'var(--bg-subtle)',
|
||||
borderColor: 'var(--border)',
|
||||
}}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3" style={{ borderBottom: '1px solid var(--border)' }}>
|
||||
<span className="font-semibold text-sm" style={{ color: 'var(--text)' }}>我的笔记</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<button onClick={toggleTheme} className="toolbar-btn" title={theme === 'light' ? '暗色模式' : '亮色模式'}>
|
||||
{theme === 'light' ? <Moon size={15} /> : <Sun size={15} />}
|
||||
</button>
|
||||
<button onClick={handleNewNote} className="toolbar-btn" title="新建笔记">
|
||||
<Plus size={15} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="px-3 py-2">
|
||||
<div
|
||||
className="flex items-center gap-2 rounded-lg px-3 py-1.5"
|
||||
style={{ background: 'var(--bg-muted)', border: '1px solid var(--border)' }}
|
||||
>
|
||||
<Search size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder="搜索笔记…"
|
||||
className="bg-transparent outline-none text-sm w-full"
|
||||
style={{ color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Nav shortcuts */}
|
||||
<nav className="px-2 space-y-0.5">
|
||||
<NavItem icon={<FileText size={14} />} label="所有笔记" count={notes.length} active={activeFolderId === 'all'} onClick={() => setActiveFolder('all')} />
|
||||
<NavItem icon={<Star size={14} />} label="收藏" count={notes.filter(n => n.starred).length} active={activeFolderId === 'starred'} onClick={() => setActiveFolder('starred')} />
|
||||
</nav>
|
||||
|
||||
{/* Folders section */}
|
||||
<div className="px-3 pt-3 pb-1 flex items-center justify-between">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-faint)' }}>文件夹</span>
|
||||
<button onClick={() => setCreatingFolder(true)} className="toolbar-btn" title="新建文件夹">
|
||||
<FolderPlus size={13} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="px-2 space-y-0.5">
|
||||
{rootFolders.map(folder => (
|
||||
<FolderItem
|
||||
key={folder.id}
|
||||
folder={folder}
|
||||
depth={0}
|
||||
expanded={expandedFolders.has(folder.id)}
|
||||
active={activeFolderId === folder.id}
|
||||
editing={editingFolderId === folder.id}
|
||||
editValue={newFolderName}
|
||||
editRef={editInputRef}
|
||||
onToggle={() => toggleFolder(folder.id)}
|
||||
onClick={() => setActiveFolder(folder.id)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
setContextMenu({ type: 'folder', id: folder.id, x: e.clientX, y: e.clientY })
|
||||
}}
|
||||
onEditChange={setNewFolderName}
|
||||
onEditBlur={() => handleRenameFolder(folder.id)}
|
||||
onEditKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleRenameFolder(folder.id)
|
||||
if (e.key === 'Escape') setEditingFolderId(null)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{creatingFolder && (
|
||||
<div className="flex items-center gap-2 px-2 py-1.5 rounded-lg" style={{ background: 'var(--bg-muted)' }}>
|
||||
<Folder size={14} style={{ color: 'var(--accent)' }} />
|
||||
<input
|
||||
ref={newFolderRef}
|
||||
value={newFolderInput}
|
||||
onChange={e => setNewFolderInput(e.target.value)}
|
||||
onBlur={handleCreateFolder}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleCreateFolder()
|
||||
if (e.key === 'Escape') { setCreatingFolder(false); setNewFolderInput('') }
|
||||
}}
|
||||
placeholder="文件夹名称"
|
||||
className="bg-transparent outline-none text-sm flex-1"
|
||||
style={{ color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Note list */}
|
||||
<div className="flex-1 overflow-y-auto mt-2" style={{ borderTop: '1px solid var(--border)' }}>
|
||||
<div className="px-3 py-2 flex items-center sticky top-0 z-10" style={{ background: 'var(--bg-subtle)' }}>
|
||||
<span className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-faint)' }}>
|
||||
笔记{displayed.length > 0 ? ` (${displayed.length})` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="px-2 pb-3 space-y-0.5">
|
||||
{displayed.length === 0 && (
|
||||
<div className="text-center py-8" style={{ color: 'var(--text-faint)' }}>
|
||||
<FileText size={24} className="mx-auto mb-2 opacity-40" />
|
||||
<p className="text-xs">暂无笔记</p>
|
||||
</div>
|
||||
)}
|
||||
{displayed.map(note => (
|
||||
<div
|
||||
key={note.id}
|
||||
className="px-2 py-2 rounded-lg cursor-pointer"
|
||||
style={{
|
||||
background: activeNoteId === note.id ? 'var(--accent-subtle)' : 'transparent',
|
||||
borderLeft: activeNoteId === note.id ? '2px solid var(--accent)' : '2px solid transparent',
|
||||
}}
|
||||
onClick={() => setActiveNote(note.id)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
setContextMenu({ type: 'note', id: note.id, x: e.clientX, y: e.clientY })
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{note.starred && <Star size={11} style={{ color: '#f59e0b', flexShrink: 0 }} fill="currentColor" />}
|
||||
<span className="text-sm font-medium truncate" style={{ color: activeNoteId === note.id ? 'var(--accent)' : 'var(--text)' }}>
|
||||
{note.title || '无标题笔记'}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-xs shrink-0 mt-0.5" style={{ color: 'var(--text-faint)' }}>{formatDate(note.updatedAt)}</span>
|
||||
</div>
|
||||
{note.tags.length > 0 && (
|
||||
<div className="flex gap-1 mt-1 flex-wrap">
|
||||
{note.tags.slice(0, 3).map(tag => (
|
||||
<span key={tag} className="inline-flex items-center gap-0.5 text-xs px-1.5 py-0.5 rounded-full" style={{ background: 'var(--bg-muted)', color: 'var(--text-muted)' }}>
|
||||
<Hash size={9} />{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Context menu */}
|
||||
{contextMenu && (
|
||||
<div
|
||||
className="fixed z-50 rounded-lg py-1 shadow-xl"
|
||||
style={{ top: contextMenu.y, left: contextMenu.x, background: 'var(--bg)', border: '1px solid var(--border)', minWidth: 160 }}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
{contextMenu.type === 'folder' && (
|
||||
<>
|
||||
<CtxItem icon={<Edit2 size={13} />} label="重命名" onClick={() => {
|
||||
const f = folders.find(f => f.id === contextMenu.id)
|
||||
if (f) { setNewFolderName(f.name); setEditingFolderId(contextMenu.id) }
|
||||
setContextMenu(null)
|
||||
}} />
|
||||
<CtxItem icon={<Trash2 size={13} />} label="删除文件夹" danger onClick={async () => { await deleteFolder(contextMenu.id); setContextMenu(null) }} />
|
||||
</>
|
||||
)}
|
||||
{contextMenu.type === 'note' && (
|
||||
<CtxItem icon={<Trash2 size={13} />} label="删除笔记" danger onClick={async () => { await deleteNote(contextMenu.id); setContextMenu(null) }} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function NavItem({ icon, label, count, active, onClick }: { icon: React.ReactNode; label: string; count?: number; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button onClick={onClick} className="w-full flex items-center gap-2 px-2 py-1.5 rounded-lg text-sm text-left transition-colors"
|
||||
style={{ background: active ? 'var(--accent-subtle)' : 'transparent', color: active ? 'var(--accent)' : 'var(--text-muted)', fontWeight: active ? 500 : 400 }}>
|
||||
{icon}
|
||||
<span className="flex-1">{label}</span>
|
||||
{(count !== undefined && count > 0) && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded-full" style={{ background: 'var(--bg-muted)', color: 'var(--text-faint)' }}>{count}</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderItem({ folder, depth, expanded, active, editing, editValue, editRef, onToggle, onClick, onContextMenu, onEditChange, onEditBlur, onEditKeyDown }: {
|
||||
folder: FolderType; depth: number; expanded: boolean; active: boolean; editing: boolean
|
||||
editValue: string; editRef: React.RefObject<HTMLInputElement | null>
|
||||
onToggle: () => void; onClick: () => void; onContextMenu: (e: React.MouseEvent) => void
|
||||
onEditChange: (v: string) => void; onEditBlur: () => void; onEditKeyDown: (e: React.KeyboardEvent) => void
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-1.5 py-1.5 rounded-lg cursor-pointer text-sm"
|
||||
style={{ paddingLeft: 8 + depth * 16, background: active ? 'var(--accent-subtle)' : 'transparent', color: active ? 'var(--accent)' : 'var(--text-muted)' }}
|
||||
onClick={onClick}
|
||||
onContextMenu={onContextMenu}
|
||||
>
|
||||
<button onClick={e => { e.stopPropagation(); onToggle() }} className="toolbar-btn" style={{ width: 16, height: 16, flexShrink: 0 }}>
|
||||
{expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
|
||||
</button>
|
||||
{expanded
|
||||
? <FolderOpen size={14} style={{ color: 'var(--accent)', flexShrink: 0 }} />
|
||||
: <Folder size={14} style={{ color: 'var(--text-muted)', flexShrink: 0 }} />}
|
||||
{editing ? (
|
||||
<input ref={editRef} value={editValue} onChange={e => onEditChange(e.target.value)} onBlur={onEditBlur} onKeyDown={onEditKeyDown}
|
||||
className="bg-transparent outline-none flex-1 text-sm" style={{ color: 'var(--text)' }} onClick={e => e.stopPropagation()} />
|
||||
) : (
|
||||
<span className="flex-1 truncate" style={{ fontWeight: active ? 500 : 400 }}>{folder.name}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CtxItem({ icon, label, danger, onClick }: { icon: React.ReactNode; label: string; danger?: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button onClick={onClick} className="w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left"
|
||||
style={{ color: danger ? '#ef4444' : 'var(--text)' }}
|
||||
onMouseEnter={e => (e.currentTarget.style.background = 'var(--bg-muted)')}
|
||||
onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}>
|
||||
{icon}{label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import Dexie, { type Table } from 'dexie'
|
||||
|
||||
export interface Note {
|
||||
id: string
|
||||
title: string
|
||||
content: string
|
||||
folderId: string | null
|
||||
tags: string[]
|
||||
starred: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
wordCount: number
|
||||
}
|
||||
|
||||
export interface Folder {
|
||||
id: string
|
||||
name: string
|
||||
parentId: string | null
|
||||
order: number
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string
|
||||
name: string
|
||||
color: string
|
||||
}
|
||||
|
||||
class NotesDB extends Dexie {
|
||||
notes!: Table<Note>
|
||||
folders!: Table<Folder>
|
||||
tags!: Table<Tag>
|
||||
|
||||
constructor() {
|
||||
super('notesapp')
|
||||
this.version(1).stores({
|
||||
notes: 'id, folderId, starred, updatedAt, createdAt, *tags',
|
||||
folders: 'id, parentId, order',
|
||||
tags: 'id, name',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const db = new NotesDB()
|
||||
|
||||
export async function seedIfEmpty() {
|
||||
const count = await db.notes.count()
|
||||
if (count > 0) return
|
||||
|
||||
const folderId1 = crypto.randomUUID()
|
||||
const folderId2 = crypto.randomUUID()
|
||||
const now = Date.now()
|
||||
|
||||
await db.folders.bulkAdd([
|
||||
{ id: folderId1, name: '工作', parentId: null, order: 0, createdAt: now },
|
||||
{ id: folderId2, name: '个人', parentId: null, order: 1, createdAt: now },
|
||||
])
|
||||
|
||||
await db.notes.bulkAdd([
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
title: '欢迎使用笔记应用',
|
||||
content: JSON.stringify({
|
||||
type: 'doc',
|
||||
content: [
|
||||
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: '欢迎使用 ✨' }] },
|
||||
{ type: 'paragraph', content: [{ type: 'text', text: '这是一款基于 Vite + React + TipTap 构建的现代笔记应用。' }] },
|
||||
{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: '功能特性' }] },
|
||||
{ type: 'bulletList', content: [
|
||||
{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: '支持富文本编辑(标题、列表、代码块、引用等)' }] }] },
|
||||
{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: '输入 / 呼出斜杠命令菜单' }] }] },
|
||||
{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: '选中文字查看浮动工具栏' }] }] },
|
||||
{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: '自动保存到 IndexedDB' }] }] },
|
||||
{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: '文件夹分类管理' }] }] },
|
||||
]},
|
||||
{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: '代码示例' }] },
|
||||
{ type: 'codeBlock', attrs: { language: 'typescript' }, content: [{ type: 'text', text: 'const hello = "Hello, World!"\nconsole.log(hello)' }] },
|
||||
{ type: 'blockquote', content: [{ type: 'paragraph', content: [{ type: 'text', text: '好记性不如烂笔头。开始记录你的想法吧!' }] }] },
|
||||
],
|
||||
}),
|
||||
folderId: null,
|
||||
tags: ['入门'],
|
||||
starred: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
wordCount: 80,
|
||||
},
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
title: '项目计划',
|
||||
content: JSON.stringify({
|
||||
type: 'doc',
|
||||
content: [
|
||||
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: '项目计划' }] },
|
||||
{ type: 'taskList', content: [
|
||||
{ type: 'taskItem', attrs: { checked: true }, content: [{ type: 'paragraph', content: [{ type: 'text', text: '需求分析' }] }] },
|
||||
{ type: 'taskItem', attrs: { checked: true }, content: [{ type: 'paragraph', content: [{ type: 'text', text: '技术选型' }] }] },
|
||||
{ type: 'taskItem', attrs: { checked: false }, content: [{ type: 'paragraph', content: [{ type: 'text', text: '开发实现' }] }] },
|
||||
{ type: 'taskItem', attrs: { checked: false }, content: [{ type: 'paragraph', content: [{ type: 'text', text: '测试上线' }] }] },
|
||||
]},
|
||||
],
|
||||
}),
|
||||
folderId: folderId1,
|
||||
tags: ['工作', '计划'],
|
||||
starred: false,
|
||||
createdAt: now - 86400000,
|
||||
updatedAt: now - 3600000,
|
||||
wordCount: 30,
|
||||
},
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
title: '读书笔记',
|
||||
content: JSON.stringify({
|
||||
type: 'doc',
|
||||
content: [
|
||||
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: '读书笔记' }] },
|
||||
{ type: 'paragraph', content: [{ type: 'text', text: '今天读了《深度工作》,记录几点感想:' }] },
|
||||
{ type: 'blockquote', content: [{ type: 'paragraph', content: [{ type: 'text', text: '深度工作是指在无干扰的专注状态下完成认知要求高的工作。' }] }] },
|
||||
],
|
||||
}),
|
||||
folderId: folderId2,
|
||||
tags: ['阅读'],
|
||||
starred: false,
|
||||
createdAt: now - 172800000,
|
||||
updatedAt: now - 172800000,
|
||||
wordCount: 45,
|
||||
},
|
||||
])
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--bg: #ffffff;
|
||||
--bg-subtle: #f8f9fa;
|
||||
--bg-muted: #f1f3f5;
|
||||
--border: #e9ecef;
|
||||
--text: #1a1a2e;
|
||||
--text-muted: #6c757d;
|
||||
--text-faint: #adb5bd;
|
||||
--accent: #6366f1;
|
||||
--accent-hover: #4f46e5;
|
||||
--accent-subtle: #eef2ff;
|
||||
}
|
||||
|
||||
[data-theme="dark"] {
|
||||
--bg: #0f0f13;
|
||||
--bg-subtle: #17171f;
|
||||
--bg-muted: #1e1e28;
|
||||
--border: #2a2a38;
|
||||
--text: #e8e8f0;
|
||||
--text-muted: #8888a8;
|
||||
--text-faint: #4a4a68;
|
||||
--accent: #818cf8;
|
||||
--accent-hover: #a5b4fc;
|
||||
--accent-subtle: #1e1b4b;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
overflow: hidden;
|
||||
height: 100vh;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
text-align: left;
|
||||
border: none;
|
||||
min-height: unset;
|
||||
flex-direction: row;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── TipTap editor ── */
|
||||
.ProseMirror {
|
||||
outline: none;
|
||||
min-height: 60vh;
|
||||
padding-bottom: 120px;
|
||||
font-size: 16px;
|
||||
line-height: 1.8;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ProseMirror p { margin: 0 0 0.75em; }
|
||||
.ProseMirror p:last-child { margin-bottom: 0; }
|
||||
.ProseMirror h1 { font-size: 1.9em; font-weight: 700; margin: 1.2em 0 0.4em; line-height: 1.2; }
|
||||
.ProseMirror h2 { font-size: 1.45em; font-weight: 600; margin: 1.1em 0 0.4em; }
|
||||
.ProseMirror h3 { font-size: 1.2em; font-weight: 600; margin: 1em 0 0.35em; }
|
||||
.ProseMirror h4 { font-size: 1.05em; font-weight: 600; margin: 0.9em 0 0.3em; }
|
||||
|
||||
.ProseMirror ul, .ProseMirror ol { padding-left: 1.4em; margin: 0.5em 0; }
|
||||
.ProseMirror li { margin: 0.2em 0; }
|
||||
|
||||
.ProseMirror blockquote {
|
||||
border-left: 3px solid var(--accent);
|
||||
padding-left: 1em;
|
||||
margin: 0.75em 0;
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.ProseMirror code {
|
||||
background: var(--bg-muted);
|
||||
border-radius: 4px;
|
||||
padding: 0.15em 0.4em;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
font-size: 0.875em;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.ProseMirror pre {
|
||||
background: var(--bg-muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 1em 1.2em;
|
||||
margin: 0.75em 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.ProseMirror pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
color: var(--text);
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
.ProseMirror hr {
|
||||
border: none;
|
||||
border-top: 1px solid var(--border);
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
|
||||
.ProseMirror a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
|
||||
|
||||
.ProseMirror mark {
|
||||
background: #fef08a;
|
||||
color: #1a1a1a;
|
||||
border-radius: 2px;
|
||||
padding: 0.1em 0.15em;
|
||||
}
|
||||
[data-theme="dark"] .ProseMirror mark { background: #713f12; color: #fef9c3; }
|
||||
|
||||
/* Task list */
|
||||
.ProseMirror ul[data-type="taskList"] { list-style: none; padding-left: 0.25em; }
|
||||
.ProseMirror ul[data-type="taskList"] li { display: flex; align-items: flex-start; gap: 0.5em; }
|
||||
.ProseMirror ul[data-type="taskList"] li > label { flex-shrink: 0; margin-top: 0.35em; cursor: pointer; }
|
||||
.ProseMirror ul[data-type="taskList"] li > div { flex: 1; }
|
||||
.ProseMirror ul[data-type="taskList"] li[data-checked="true"] > div {
|
||||
text-decoration: line-through;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* Table */
|
||||
.ProseMirror table { border-collapse: collapse; width: 100%; margin: 0.75em 0; font-size: 0.9em; }
|
||||
.ProseMirror th, .ProseMirror td { border: 1px solid var(--border); padding: 0.5em 0.75em; text-align: left; }
|
||||
.ProseMirror th { background: var(--bg-muted); font-weight: 600; }
|
||||
|
||||
/* Placeholder */
|
||||
.ProseMirror p.is-editor-empty:first-child::before {
|
||||
content: attr(data-placeholder);
|
||||
color: var(--text-faint);
|
||||
pointer-events: none;
|
||||
float: left;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
/* Slash command menu */
|
||||
.slash-menu {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.14);
|
||||
overflow: hidden;
|
||||
width: 260px;
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.slash-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75em;
|
||||
padding: 0.55em 0.85em;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.slash-menu-item:hover, .slash-menu-item.active { background: var(--bg-muted); }
|
||||
|
||||
.slash-menu-item-icon {
|
||||
width: 30px; height: 30px;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: var(--bg-subtle);
|
||||
border-radius: 6px;
|
||||
flex-shrink: 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.slash-menu-item-label { font-size: 0.88em; font-weight: 500; color: var(--text); }
|
||||
.slash-menu-item-desc { font-size: 0.76em; color: var(--text-muted); }
|
||||
|
||||
/* Floating toolbar */
|
||||
.floating-toolbar {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.12);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.toolbar-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 28px; height: 28px;
|
||||
border-radius: 5px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
transition: background 0.1s, color 0.1s;
|
||||
}
|
||||
.toolbar-btn:hover { background: var(--bg-muted); color: var(--text); }
|
||||
.toolbar-btn.active { background: var(--accent-subtle); color: var(--accent); }
|
||||
.toolbar-divider { width: 1px; height: 16px; background: var(--border); margin: 0 2px; }
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar { width: 5px; height: 5px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--text-faint); }
|
||||
@@ -0,0 +1,32 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function generateId() {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
export function formatDate(timestamp: number) {
|
||||
const d = new Date(timestamp)
|
||||
const now = new Date()
|
||||
const diff = now.getTime() - d.getTime()
|
||||
const days = Math.floor(diff / 86400000)
|
||||
if (days === 0) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
if (days === 1) return '昨天'
|
||||
if (days < 7) return `${days} 天前`
|
||||
return d.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
|
||||
}
|
||||
|
||||
export function countWords(text: string) {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return 0
|
||||
const chineseChars = (trimmed.match(/[一-龥]/g) || []).length
|
||||
const englishWords = trimmed
|
||||
.replace(/[一-龥]/g, '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean).length
|
||||
return chineseChars + englishWords
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,149 @@
|
||||
import { create } from 'zustand'
|
||||
import { db, type Note, type Folder } from '../db'
|
||||
import { generateId } from '../lib/utils'
|
||||
|
||||
interface AppState {
|
||||
notes: Note[]
|
||||
folders: Folder[]
|
||||
activeNoteId: string | null
|
||||
activeFolderId: string | null | 'all' | 'starred'
|
||||
searchQuery: string
|
||||
theme: 'light' | 'dark'
|
||||
|
||||
// actions
|
||||
loadAll: () => Promise<void>
|
||||
createNote: (folderId?: string | null) => Promise<string>
|
||||
updateNote: (id: string, patch: Partial<Note>) => Promise<void>
|
||||
deleteNote: (id: string) => Promise<void>
|
||||
toggleStar: (id: string) => Promise<void>
|
||||
|
||||
createFolder: (name: string, parentId?: string | null) => Promise<string>
|
||||
updateFolder: (id: string, patch: Partial<Folder>) => Promise<void>
|
||||
deleteFolder: (id: string) => Promise<void>
|
||||
|
||||
setActiveNote: (id: string | null) => void
|
||||
setActiveFolder: (id: string | null | 'all' | 'starred') => void
|
||||
setSearch: (q: string) => void
|
||||
toggleTheme: () => void
|
||||
|
||||
filteredNotes: () => Note[]
|
||||
}
|
||||
|
||||
export const useAppStore = create<AppState>((set, get) => ({
|
||||
notes: [],
|
||||
folders: [],
|
||||
activeNoteId: null,
|
||||
activeFolderId: 'all',
|
||||
searchQuery: '',
|
||||
theme: (localStorage.getItem('theme') as 'light' | 'dark') || 'light',
|
||||
|
||||
loadAll: async () => {
|
||||
const [notes, folders] = await Promise.all([
|
||||
db.notes.orderBy('updatedAt').reverse().toArray(),
|
||||
db.folders.orderBy('order').toArray(),
|
||||
])
|
||||
set({ notes, folders })
|
||||
if (notes.length > 0 && !get().activeNoteId) {
|
||||
set({ activeNoteId: notes[0].id })
|
||||
}
|
||||
},
|
||||
|
||||
createNote: async (folderId = null) => {
|
||||
const id = generateId()
|
||||
const now = Date.now()
|
||||
const note: Note = {
|
||||
id,
|
||||
title: '无标题笔记',
|
||||
content: JSON.stringify({ type: 'doc', content: [{ type: 'paragraph' }] }),
|
||||
folderId: folderId ?? get().activeFolderId as string | null,
|
||||
tags: [],
|
||||
starred: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
wordCount: 0,
|
||||
}
|
||||
await db.notes.add(note)
|
||||
set(s => ({ notes: [note, ...s.notes], activeNoteId: id }))
|
||||
return id
|
||||
},
|
||||
|
||||
updateNote: async (id, patch) => {
|
||||
const now = Date.now()
|
||||
await db.notes.update(id, { ...patch, updatedAt: now })
|
||||
set(s => ({
|
||||
notes: s.notes.map(n =>
|
||||
n.id === id ? { ...n, ...patch, updatedAt: now } : n
|
||||
).sort((a, b) => b.updatedAt - a.updatedAt),
|
||||
}))
|
||||
},
|
||||
|
||||
deleteNote: async (id) => {
|
||||
await db.notes.delete(id)
|
||||
set(s => {
|
||||
const notes = s.notes.filter(n => n.id !== id)
|
||||
const activeNoteId = s.activeNoteId === id ? (notes[0]?.id ?? null) : s.activeNoteId
|
||||
return { notes, activeNoteId }
|
||||
})
|
||||
},
|
||||
|
||||
toggleStar: async (id) => {
|
||||
const note = get().notes.find(n => n.id === id)
|
||||
if (!note) return
|
||||
await get().updateNote(id, { starred: !note.starred })
|
||||
},
|
||||
|
||||
createFolder: async (name, parentId = null) => {
|
||||
const id = generateId()
|
||||
const order = get().folders.filter(f => f.parentId === parentId).length
|
||||
const folder: Folder = { id, name, parentId, order, createdAt: Date.now() }
|
||||
await db.folders.add(folder)
|
||||
set(s => ({ folders: [...s.folders, folder] }))
|
||||
return id
|
||||
},
|
||||
|
||||
updateFolder: async (id, patch) => {
|
||||
await db.folders.update(id, patch)
|
||||
set(s => ({ folders: s.folders.map(f => f.id === id ? { ...f, ...patch } : f) }))
|
||||
},
|
||||
|
||||
deleteFolder: async (id) => {
|
||||
const childIds = get().folders.filter(f => f.parentId === id).map(f => f.id)
|
||||
for (const cid of childIds) await get().deleteFolder(cid)
|
||||
await db.folders.delete(id)
|
||||
const notesToMove = get().notes.filter(n => n.folderId === id)
|
||||
for (const n of notesToMove) await get().updateNote(n.id, { folderId: null })
|
||||
set(s => ({ folders: s.folders.filter(f => f.id !== id) }))
|
||||
},
|
||||
|
||||
setActiveNote: (id) => set({ activeNoteId: id }),
|
||||
setActiveFolder: (id) => set({ activeFolderId: id }),
|
||||
setSearch: (q) => set({ searchQuery: q }),
|
||||
|
||||
toggleTheme: () => {
|
||||
const next = get().theme === 'light' ? 'dark' : 'light'
|
||||
localStorage.setItem('theme', next)
|
||||
document.documentElement.setAttribute('data-theme', next)
|
||||
set({ theme: next })
|
||||
},
|
||||
|
||||
filteredNotes: () => {
|
||||
const { notes, activeFolderId, searchQuery } = get()
|
||||
let result = notes
|
||||
|
||||
if (activeFolderId === 'starred') {
|
||||
result = result.filter(n => n.starred)
|
||||
} else if (activeFolderId !== 'all' && activeFolderId !== null) {
|
||||
result = result.filter(n => n.folderId === activeFolderId)
|
||||
}
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
const q = searchQuery.toLowerCase()
|
||||
result = result.filter(n =>
|
||||
n.title.toLowerCase().includes(q) ||
|
||||
n.tags.some(t => t.toLowerCase().includes(q))
|
||||
)
|
||||
}
|
||||
|
||||
return result
|
||||
},
|
||||
}))
|
||||
Reference in New Issue
Block a user