Initial commit

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
MikiVL 2026-05-02 14:36:32 +08:00
commit 45871ac481
22 changed files with 6755 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

22
eslint.config.js Normal file
View File

@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>program1</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

5240
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

71
package.json Normal file
View File

@ -0,0 +1,71 @@
{
"name": "program1",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tooltip": "^1.2.8",
"@tiptap/extension-bubble-menu": "^3.22.5",
"@tiptap/extension-character-count": "^3.22.5",
"@tiptap/extension-code-block-lowlight": "^3.22.5",
"@tiptap/extension-color": "^3.22.5",
"@tiptap/extension-highlight": "^3.22.5",
"@tiptap/extension-image": "^3.22.5",
"@tiptap/extension-link": "^3.22.5",
"@tiptap/extension-placeholder": "^3.22.5",
"@tiptap/extension-strike": "^3.22.5",
"@tiptap/extension-subscript": "^3.22.5",
"@tiptap/extension-superscript": "^3.22.5",
"@tiptap/extension-table": "^3.22.5",
"@tiptap/extension-table-cell": "^3.22.5",
"@tiptap/extension-table-header": "^3.22.5",
"@tiptap/extension-table-row": "^3.22.5",
"@tiptap/extension-task-item": "^3.22.5",
"@tiptap/extension-task-list": "^3.22.5",
"@tiptap/extension-text-style": "^3.22.5",
"@tiptap/extension-typography": "^3.22.5",
"@tiptap/extension-underline": "^3.22.5",
"@tiptap/react": "^3.22.5",
"@tiptap/starter-kit": "^3.22.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dexie": "^4.4.2",
"framer-motion": "^12.38.0",
"lowlight": "^3.3.0",
"lucide-react": "^1.14.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"tailwind-merge": "^3.5.0",
"zustand": "^5.0.12"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.2.4",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"autoprefixer": "^10.5.0",
"eslint": "^10.2.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"postcss": "^8.5.13",
"tailwindcss": "^4.2.4",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.10"
}
}

1
public/favicon.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
public/icons.svg Normal file
View File

@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

24
src/App.tsx Normal file
View File

@ -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>
)
}

BIN
src/assets/hero.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

1
src/assets/vite.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -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>
)
}

View File

@ -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
src/db/index.ts Normal file
View File

@ -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
src/index.css Normal file
View File

@ -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); }

32
src/lib/utils.ts Normal file
View File

@ -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
}

10
src/main.tsx Normal file
View File

@ -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>,
)

149
src/stores/appStore.ts Normal file
View File

@ -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
},
}))

25
tsconfig.app.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

24
tsconfig.node.json Normal file
View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

7
vite.config.ts Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
})