mingyang22 commited on
Commit
5b208aa
·
verified ·
1 Parent(s): c433ecb

Update Pro UI (GlassNote style)

Browse files
Files changed (2) hide show
  1. __pycache__/app.cpython-312.pyc +0 -0
  2. app.py +258 -277
__pycache__/app.cpython-312.pyc ADDED
Binary file (21.1 kB). View file
 
app.py CHANGED
@@ -15,13 +15,13 @@ HF_TOKEN = os.environ.get("HF_TOKEN") # 必须在 Space 设置中配置
15
  REMOTE_NOTES_PATH = "db/notes.json"
16
 
17
  APP_MANIFEST = {
18
- "name": "HF 笔记",
19
  "short_name": "HF笔记",
20
  "start_url": "/",
21
  "display": "standalone",
22
- "background_color": "#0f172a",
23
- "theme_color": "#2563eb",
24
- "description": "Hugging Face 云端同步笔记(PWA)",
25
  "icons": [
26
  {
27
  "src": "/pwa-icon.svg",
@@ -33,162 +33,132 @@ APP_MANIFEST = {
33
  }
34
 
35
  PWA_ICON_SVG = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 128 128'>
36
- <rect width='128' height='128' rx='24' fill='#1d4ed8'/>
37
- <path d='M34 28h60a6 6 0 0 1 6 6v60a6 6 0 0 1-6 6H34a6 6 0 0 1-6-6V34a6 6 0 0 1 6-6z' fill='#fff' opacity='0.95'/>
38
- <path d='M44 48h40M44 64h40M44 80h26' stroke='#1d4ed8' stroke-width='6' stroke-linecap='round'/>
 
 
 
 
 
39
  </svg>"""
40
 
41
- PWA_SW_JS = """
42
- const CACHE_NAME = 'hf-notes-pwa-v1';
43
- const CORE_ASSETS = ['/', '/manifest.webmanifest', '/pwa-icon.svg'];
44
- self.addEventListener('install', (event) => {
45
- event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(CORE_ASSETS)));
46
- self.skipWaiting();
47
- });
48
- self.addEventListener('activate', (event) => {
49
- event.waitUntil(
50
- caches.keys().then((keys) =>
51
- Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
52
- )
53
- );
54
- self.clients.claim();
55
- });
56
- self.addEventListener('fetch', (event) => {
57
- const req = event.request;
58
- if (req.method !== 'GET') return;
59
- const url = new URL(req.url);
60
- if (url.origin !== self.location.origin) return;
61
- if (req.mode === 'navigate') {
62
- event.respondWith(
63
- fetch(req).then((res) => {
64
- const copy = res.clone();
65
- caches.open(CACHE_NAME).then((cache) => cache.put(req, copy));
66
- return res;
67
- }).catch(() => caches.match(req).then((res) => res || caches.match('/')))
68
- );
69
- return;
70
- }
71
- event.respondWith(caches.match(req).then((cached) => cached || fetch(req)));
72
- });
73
- """
74
-
75
  PWA_HEAD = """
76
  <link rel="manifest" href="/manifest.webmanifest" />
77
- <meta name="theme-color" content="#2563eb" />
78
- <script>
79
- (() => {
80
- if ('serviceWorker' in navigator) {
81
- window.addEventListener('load', () => navigator.serviceWorker.register('/sw.js').catch(() => {}));
82
- }
83
- const DRAFT_KEY = 'hf_notes_web_draft_v1';
84
- function readDraft() {
85
- try { return JSON.parse(localStorage.getItem(DRAFT_KEY) || '{}'); } catch (_) { return {}; }
86
- }
87
- function writeDraft(data) {
88
- try { localStorage.setItem(DRAFT_KEY, JSON.stringify(data || {})); } catch (_) {}
89
- }
90
- function bindDraftPersistence() {
91
- const titleInput = document.querySelector('#note_title textarea, #note_title input');
92
- const contentInput = document.querySelector('#note_content textarea');
93
- const draft = readDraft();
94
- if (titleInput && !titleInput.value && draft.title) titleInput.value = draft.title;
95
- if (contentInput && !contentInput.value && draft.content) contentInput.value = draft.content;
96
- if (titleInput) {
97
- titleInput.addEventListener('input', () => writeDraft({ title: titleInput.value, content: contentInput ? contentInput.value : '' }));
98
- }
99
- if (contentInput) {
100
- contentInput.addEventListener('input', () => writeDraft({ title: titleInput ? titleInput.value : '', content: contentInput.value }));
101
- }
102
- }
103
- window.addEventListener('load', () => setTimeout(bindDraftPersistence, 800));
104
- })();
105
- </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  """
107
 
108
  def get_default_data_dir():
109
  custom_dir = os.environ.get("HF_NOTES_DATA_DIR")
110
- if custom_dir:
111
- return custom_dir
112
  if os.name == "nt":
113
  base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
114
  else:
115
  base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
116
- return str(Path(base) / "hf-note-app")
117
 
118
  DATA_DIR = get_default_data_dir()
119
  LOCAL_NOTES_PATH = str(Path(DATA_DIR) / "notes.json")
120
- LEGACY_DB_PATH = "./notes.db"
121
- LEGACY_NOTES_JSON_PATH = "./notes.json"
122
 
123
- # --- JSON 存储工具 ---
124
  def ensure_local_notes():
125
  Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
126
  p = Path(LOCAL_NOTES_PATH)
127
  if not p.exists():
128
- migrate_from_legacy_json()
129
- migrate_from_legacy_db()
130
- if not p.exists():
131
- p.write_text("[]", encoding="utf-8")
132
-
133
- def migrate_from_legacy_json():
134
- if not os.path.exists(LEGACY_NOTES_JSON_PATH):
135
- return
136
- try:
137
- # legacy project notes.json may contain BOM
138
- text = Path(LEGACY_NOTES_JSON_PATH).read_text(encoding="utf-8-sig")
139
- data = json.loads(text)
140
- if not isinstance(data, list):
141
- return
142
- write_notes(data)
143
- print(f"✅ 已从旧版项目路径 notes.json 迁移 {len(data)} 条记录到用户数据目录")
144
- except Exception as e:
145
- print(f"⚠️ 旧版 notes.json 迁移失败: {e}")
146
-
147
- def migrate_from_legacy_db():
148
- if not os.path.exists(LEGACY_DB_PATH):
149
- return
150
- try:
151
- conn = sqlite3.connect(LEGACY_DB_PATH, check_same_thread=False)
152
- conn.row_factory = sqlite3.Row
153
- rows = conn.execute(
154
- "SELECT id, title, content, updated_at FROM notes ORDER BY updated_at DESC"
155
- ).fetchall()
156
- conn.close()
157
- notes = [
158
- {
159
- "id": int(r["id"]),
160
- "title": str(r["title"] or ""),
161
- "content": str(r["content"] or ""),
162
- "updated_at": str(r["updated_at"] or ""),
163
- }
164
- for r in rows
165
- ]
166
- write_notes(notes)
167
- print(f"✅ 已从旧版 notes.db 迁移 {len(notes)} 条记录到 notes.json")
168
- except Exception as e:
169
- print(f"⚠️ 旧版 notes.db 迁移失败: {e}")
170
 
171
  def read_notes():
172
  ensure_local_notes()
173
  try:
174
- # Use utf-8-sig to tolerate BOM-prefixed JSON from external clients.
175
  data = json.loads(Path(LOCAL_NOTES_PATH).read_text(encoding="utf-8-sig"))
176
  if isinstance(data, list):
177
- notes = []
178
  for item in data:
179
- if not isinstance(item, dict):
180
- continue
181
- notes.append(
182
- {
183
- "id": int(item.get("id", 0)),
184
- "title": str(item.get("title", "")),
185
- "content": str(item.get("content", "")),
186
- "updated_at": str(item.get("updated_at", "")),
187
- }
188
- )
189
- return notes
190
- except Exception:
191
- pass
192
  return []
193
 
194
  def write_notes(notes):
@@ -197,191 +167,202 @@ def write_notes(notes):
197
  encoding="utf-8",
198
  )
199
 
200
- # --- 持久化管理 (云端同步) ---
201
  class CloudSync:
202
  def __init__(self):
203
  self.api = HfApi(token=HF_TOKEN)
204
-
205
  def pull(self):
206
- """从 Dataset 下载最新的 notes.json"""
207
- print(f"🔄 正在从云端拉取数据: {DATASET_REPO_ID}...")
208
  try:
209
  downloaded_path = hf_hub_download(
210
  repo_id=DATASET_REPO_ID,
211
  filename=REMOTE_NOTES_PATH,
212
  repo_type="dataset",
213
  token=HF_TOKEN,
214
- force_download=True, # 同步核心:跳过本地缓存
215
  revision="main",
216
  )
217
- Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
218
  shutil.copy(downloaded_path, LOCAL_NOTES_PATH)
219
- return f"✅ 数据拉取成功 ({datetime.now().strftime('%H:%M:%S')})"
220
  except Exception as e:
221
- print(f"⚠️ 拉取失败: {e}")
222
- ensure_local_notes()
223
- return "ℹ️ 云端暂无 notes.json 或拉取失败。"
224
 
225
  def push(self):
226
- """将本地 notes.json 上传到 Dataset"""
227
- if not os.path.exists(LOCAL_NOTES_PATH):
228
- return "❌ 本地 notes.json 丢失"
229
-
230
- file_size = os.path.getsize(LOCAL_NOTES_PATH)
231
- print(f"📤 正在上传数据到云端 (Size: {file_size} bytes): {DATASET_REPO_ID}...")
232
  try:
233
  self.api.upload_file(
234
  path_or_fileobj=LOCAL_NOTES_PATH,
235
  path_in_repo=REMOTE_NOTES_PATH,
236
  repo_id=DATASET_REPO_ID,
237
  repo_type="dataset",
238
- commit_message=f"Web update Size({file_size}) at {datetime.now().strftime('%H:%M:%S')}"
239
- )
240
- return f"✅ 云端备份已更新 ({datetime.now().strftime('%H:%M:%S')})"
241
- except Exception as e:
242
- return f"❌ 备份失败: {e}"
243
-
244
- sync_manager = CloudSync()
245
-
246
- # --- 业务逻辑 ---
247
- def load_notes_list():
248
- notes = sorted(read_notes(), key=lambda x: x.get("updated_at", ""), reverse=True)
249
- df = pd.DataFrame(
250
- [
251
- {
252
- "id": str(n.get("id", "")),
253
- "title": n.get("title", ""),
254
- "updated_at": n.get("updated_at", ""),
255
- }
256
- for n in notes
257
- ]
258
- )
259
- if df.empty:
260
- return [["(空)", "请创建您的第一条笔记", ""]]
261
- return df.values.tolist()
262
 
263
- def get_note_content(note_id):
264
- if not note_id or note_id == "(空)":
265
- return "", ""
 
266
  notes = read_notes()
 
 
 
267
  for n in notes:
268
- if str(n.get("id")) == str(note_id):
269
- return n.get("title", ""), n.get("content", "")
270
- return "", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
- def save_note(note_id, title, content):
273
- if not title: return " 标题不能为空", load_notes_list()
 
 
 
 
 
274
 
 
 
275
  notes = read_notes()
276
- now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
277
- if note_id and str(note_id).isdigit():
278
- target = None
279
- for n in notes:
280
- if int(n.get("id", -1)) == int(note_id):
281
- target = n
282
- break
283
- if target:
284
- target["title"] = title
285
- target["content"] = content
286
- target["updated_at"] = now
287
- else:
288
- next_id = (max([int(n.get("id", 0)) for n in notes]) + 1) if notes else 1
289
- notes.append({"id": next_id, "title": title, "content": content, "updated_at": now})
290
- msg = "📝 笔记已更新 (本地)"
291
- else:
292
- next_id = (max([int(n.get("id", 0)) for n in notes]) + 1) if notes else 1
293
- notes.append({"id": next_id, "title": title, "content": content, "updated_at": now})
294
- msg = "✨ 笔记已创建 (本地)"
295
- write_notes(notes)
296
 
297
- # 自动触发云端同步备份
298
- backup_msg = sync_manager.push()
299
- return f"{msg} | {backup_msg}", load_notes_list()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
- def delete_note(note_id):
302
- if not note_id: return "选择笔记", load_notes_list()
303
- notes = [n for n in read_notes() if str(n.get("id")) != str(note_id)]
 
 
 
 
 
 
 
 
304
  write_notes(notes)
305
- backup_msg = sync_manager.push()
306
- return f"🗑️ 笔记已删除 | {backup_msg}", load_notes_list()
307
 
308
- def render_preview_md(title, content):
309
- t = (title or "").strip()
310
- c = content or ""
311
- if not t and not c:
312
- return "## 预览\n\n暂无内容。"
313
- return f"## {t or '未命名笔记'}\n\n{c}"
 
 
 
314
 
315
- # --- Gradio UI 界面 ---
316
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), head=PWA_HEAD) as demo:
317
- gr.Markdown("# 📓 Hugging Face 个人笔记云端版")
318
- gr.Markdown("实时同步本地 Quicker 动作数据。支持 PWA 安装与离线壳缓存,方便长期查看与编辑。")
319
 
320
- with gr.Row():
321
- with gr.Column(scale=1):
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  note_list = gr.Dataframe(
323
- headers=["ID", "标题", "最后修改"],
324
- datatype=["str", "str", "str"],
325
- value=load_notes_list(),
326
- interactive=False,
327
- label="我的笔记列表"
328
- )
329
- btn_refresh = gr.Button("🔄 刷新并手动拉取云端", variant="secondary")
330
- status_output = gr.Markdown("系统就绪")
331
-
332
- with gr.Column(scale=2):
333
- with gr.Group():
334
- target_id = gr.Textbox(visible=False)
335
- in_title = gr.Textbox(label="标题", placeholder="输入笔记标题...", elem_id="note_title")
336
- in_content = gr.TextArea(label="正文内容", lines=15, placeholder="记录您的想法...", elem_id="note_content")
337
- preview = gr.Markdown(value="## 预览\n\n暂无内容。", label="阅读预览")
338
-
339
- with gr.Row():
340
- btn_save = gr.Button("💾 保存并推送到云端", variant="primary")
341
- btn_new = gr.Button("➕ 新建笔记")
342
- btn_del = gr.Button("🗑️ 删除笔记", variant="stop")
343
-
344
- # 事件绑定
345
- def on_select(evt: gr.SelectData):
346
- # evt.index[0] 是行号
347
- df = load_notes_list()
348
- selected_id = df[evt.index[0]][0]
349
- title, content = get_note_content(selected_id)
350
- return selected_id, title, content, render_preview_md(title, content)
351
 
352
- note_list.select(on_select, None, [target_id, in_title, in_content, preview])
353
 
354
- btn_save.click(save_note, [target_id, in_title, in_content], [status_output, note_list]).then(
355
- render_preview_md, [in_title, in_content], [preview]
356
- )
 
 
 
 
357
 
358
- btn_new.click(lambda: (None, "新笔记", "", render_preview_md("新笔记", "")), None, [target_id, in_title, in_content, preview])
359
 
360
- btn_del.click(delete_note, [target_id], [status_output, note_list]).then(
361
- lambda: ("", "", "## 预览\n\n暂无内容。"), None, [in_title, in_content, preview]
362
- )
363
 
364
- btn_refresh.click(lambda: (sync_manager.pull(), load_notes_list()), None, [status_output, note_list])
365
- in_content.change(render_preview_md, [in_title, in_content], [preview], queue=False)
366
- in_title.change(render_preview_md, [in_title, in_content], [preview], queue=False)
367
-
368
- # 启动时自动从云端拉取
369
- demo.load(lambda: (sync_manager.pull(), load_notes_list(), "## 预览\n\n暂无内容。"), None, [status_output, note_list, preview])
370
-
371
- @demo.app.get("/manifest.webmanifest")
372
- def pwa_manifest():
373
- return Response(
374
- content=json.dumps(APP_MANIFEST, ensure_ascii=False),
375
- media_type="application/manifest+json"
376
- )
377
-
378
- @demo.app.get("/sw.js")
379
- def pwa_service_worker():
380
- return Response(content=PWA_SW_JS, media_type="application/javascript")
381
 
382
- @demo.app.get("/pwa-icon.svg")
383
- def pwa_icon():
384
- return Response(content=PWA_ICON_SVG, media_type="image/svg+xml")
385
 
386
  if __name__ == "__main__":
387
  demo.launch()
 
15
  REMOTE_NOTES_PATH = "db/notes.json"
16
 
17
  APP_MANIFEST = {
18
+ "name": "HF 笔记 Pro",
19
  "short_name": "HF笔记",
20
  "start_url": "/",
21
  "display": "standalone",
22
+ "background_color": "#0a0a0a",
23
+ "theme_color": "#3b82f6",
24
+ "description": "Hugging Face 高级云端同步笔记",
25
  "icons": [
26
  {
27
  "src": "/pwa-icon.svg",
 
33
  }
34
 
35
  PWA_ICON_SVG = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 128 128'>
36
+ <rect width='128' height='128' rx='28' fill='#0a0a0a' stroke='#333' stroke-width='2'/>
37
+ <circle cx='64' cy='64' r='40' fill='url(#grad)'/>
38
+ <defs>
39
+ <linearGradient id='grad' x1='0' y1='0' x2='1' y2='1'>
40
+ <stop offset='0%' stop-color='#7c3aed'/><stop offset='100%' stop-color='#db2777'/>
41
+ </linearGradient>
42
+ </defs>
43
+ <path d='M45 45h38v38H45z' fill='#fff' opacity='0.9'/>
44
  </svg>"""
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  PWA_HEAD = """
47
  <link rel="manifest" href="/manifest.webmanifest" />
48
+ <meta name="theme-color" content="#3b82f6" />
49
+ <style>
50
+ /* 玻璃质感与高级深色主题 CSS */
51
+ :root {
52
+ --bg-dark: #0a0a0a;
53
+ --accent: #3b82f6;
54
+ --border: #333333;
55
+ --text-main: #eeeeee;
56
+ --text-dim: #888888;
57
+ }
58
+
59
+ body, .gradio-container {
60
+ background-color: var(--bg-dark) !important;
61
+ color: var(--text-main) !important;
62
+ }
63
+
64
+ /* 隐藏 Gradio 默认页脚 */
65
+ footer { display: none !important; }
66
+
67
+ /* 侧边栏按钮美化 */
68
+ .nav-btn button {
69
+ background: transparent !important;
70
+ border: none !important;
71
+ text-align: left !important;
72
+ padding-left: 20px !important;
73
+ font-size: 16px !important;
74
+ color: var(--text-dim) !important;
75
+ }
76
+ .nav-btn button:hover {
77
+ background: #1a1a1a !important;
78
+ color: white !important;
79
+ }
80
+ .active-nav button {
81
+ background: #252525 !important;
82
+ color: white !important;
83
+ border-left: 3px solid var(--accent) !important;
84
+ }
85
+
86
+ /* 列表美化 */
87
+ .note-list-item {
88
+ border-bottom: 1px solid #1a1a1a !important;
89
+ padding: 15px !important;
90
+ cursor: pointer;
91
+ }
92
+ .note-list-item:hover {
93
+ background: #1a1a1a !important;
94
+ }
95
+
96
+ /* 编辑器美化 */
97
+ #note_title textarea {
98
+ font-size: 24px !important;
99
+ font-weight: bold !important;
100
+ background: transparent !important;
101
+ border: none !important;
102
+ color: #e0e0e0 !important;
103
+ }
104
+ #note_content textarea {
105
+ font-size: 16px !important;
106
+ background: transparent !important;
107
+ border: none !important;
108
+ color: #cccccc !important;
109
+ }
110
+
111
+ /* AI 按钮渐变 */
112
+ #ai_btn {
113
+ background: linear-gradient(135deg, #7c3aed 0%, #db2777 100%) !important;
114
+ border: none !important;
115
+ font-weight: bold !important;
116
+ }
117
+
118
+ /* 滚动条美化 */
119
+ ::-webkit-scrollbar { width: 6px; }
120
+ ::-webkit-scrollbar-track { background: transparent; }
121
+ ::-webkit-scrollbar-thumb { background: #333; border-radius: 3px; }
122
+ ::-webkit-scrollbar-thumb:hover { background: #444; }
123
+ </style>
124
  """
125
 
126
  def get_default_data_dir():
127
  custom_dir = os.environ.get("HF_NOTES_DATA_DIR")
128
+ if custom_dir: return custom_dir
 
129
  if os.name == "nt":
130
  base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
131
  else:
132
  base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
133
+ return str(Path(base) / "hf-note-app-pro")
134
 
135
  DATA_DIR = get_default_data_dir()
136
  LOCAL_NOTES_PATH = str(Path(DATA_DIR) / "notes.json")
 
 
137
 
 
138
  def ensure_local_notes():
139
  Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
140
  p = Path(LOCAL_NOTES_PATH)
141
  if not p.exists():
142
+ p.write_text("[]", encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  def read_notes():
145
  ensure_local_notes()
146
  try:
 
147
  data = json.loads(Path(LOCAL_NOTES_PATH).read_text(encoding="utf-8-sig"))
148
  if isinstance(data, list):
149
+ valid_notes = []
150
  for item in data:
151
+ if not isinstance(item, dict): continue
152
+ valid_notes.append({
153
+ "id": str(item.get("id", "")),
154
+ "title": str(item.get("title", "新笔记")),
155
+ "content": str(item.get("content", "")),
156
+ "updated_at": str(item.get("updated_at", "")),
157
+ "is_pinned": bool(item.get("is_pinned", False)),
158
+ "is_deleted": bool(item.get("is_deleted", False))
159
+ })
160
+ return valid_notes
161
+ except Exception: pass
 
 
162
  return []
163
 
164
  def write_notes(notes):
 
167
  encoding="utf-8",
168
  )
169
 
170
+ # --- 持久化管理 ---
171
  class CloudSync:
172
  def __init__(self):
173
  self.api = HfApi(token=HF_TOKEN)
174
+
175
  def pull(self):
 
 
176
  try:
177
  downloaded_path = hf_hub_download(
178
  repo_id=DATASET_REPO_ID,
179
  filename=REMOTE_NOTES_PATH,
180
  repo_type="dataset",
181
  token=HF_TOKEN,
182
+ force_download=True,
183
  revision="main",
184
  )
 
185
  shutil.copy(downloaded_path, LOCAL_NOTES_PATH)
186
+ return True, f"✅ 云端拉取同步完成"
187
  except Exception as e:
188
+ return False, f"⚠️ 拉取失败: {e}"
 
 
189
 
190
  def push(self):
191
+ if not os.path.exists(LOCAL_NOTES_PATH): return False, "❌ 文件丢失"
 
 
 
 
 
192
  try:
193
  self.api.upload_file(
194
  path_or_fileobj=LOCAL_NOTES_PATH,
195
  path_in_repo=REMOTE_NOTES_PATH,
196
  repo_id=DATASET_REPO_ID,
197
  repo_type="dataset",
198
+ commit_message=f"Web Update Pro at {datetime.now().strftime('%H:%M:%S')}"
199
+ )
200
+ return True, "✅ 备份至云端"
201
+ except Exception as e:
202
+ return False, f"❌ 备份失败: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
+ sync_manager = CloudSync()
205
+
206
+ # --- 业务逻辑 ---
207
+ def load_notes_list(filter_type="all", search_query=""):
208
  notes = read_notes()
209
+ query = search_query.lower() if search_query else ""
210
+
211
+ filtered = []
212
  for n in notes:
213
+ # Tab 过滤
214
+ is_deleted = n.get("is_deleted", False)
215
+ is_pinned = n.get("is_pinned", False)
216
+
217
+ if filter_type == "trash":
218
+ if not is_deleted: continue
219
+ else:
220
+ if is_deleted: continue
221
+ if filter_type == "pinned" and not is_pinned: continue
222
+
223
+ # 搜索过滤
224
+ if query and query not in n["title"].lower() and query not in n["content"].lower():
225
+ continue
226
+
227
+ filtered.append(n)
228
+
229
+ # 排序:置顶优先,时间倒序
230
+ sorted_notes = sorted(filtered, key=lambda x: (x.get("is_pinned", False), x.get("updated_at", "")), reverse=True)
231
+
232
+ return [
233
+ [n["id"], f"{'📌 ' if n.get('is_pinned') else ''}{n['title'] or '未命名'}", n["updated_at"]]
234
+ for n in sorted_notes
235
+ ]
236
 
237
+ def get_note_detail(note_id):
238
+ if not note_id: return "", "", ""
239
+ notes = read_notes()
240
+ for n in notes:
241
+ if n["id"] == note_id:
242
+ return n["title"], n["content"], n["updated_at"]
243
+ return "", "", ""
244
 
245
+ def handle_save(note_id, title, content):
246
+ if not title and not content: return "无内容可保存", load_notes_list()
247
  notes = read_notes()
248
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
+ found = False
251
+ for n in notes:
252
+ if n["id"] == note_id:
253
+ n["title"], n["content"], n["updated_at"] = title, content, now
254
+ found = True
255
+ break
256
+
257
+ if not found:
258
+ new_id = datetime.now().strftime("%Y%m%d%H%M%S")
259
+ new_note = {
260
+ "id": new_id,
261
+ "title": title or "新笔记",
262
+ "content": content,
263
+ "updated_at": now,
264
+ "is_pinned": False,
265
+ "is_deleted": False
266
+ }
267
+ notes.insert(0, new_note)
268
+ note_id = new_id
269
+
270
+ write_notes(notes)
271
+ _, msg = sync_manager.push()
272
+ return f"已本地保存 | {msg}", load_notes_list(), note_id
273
 
274
+ def handle_delete(note_id, current_filter):
275
+ if not note_id: return "选择笔记", load_notes_list(current_filter), ""
276
+ notes = read_notes()
277
+ for n in notes:
278
+ if n["id"] == note_id:
279
+ if current_filter == "trash":
280
+ notes.remove(n)
281
+ else:
282
+ n["is_deleted"] = True
283
+ n["is_pinned"] = False
284
+ break
285
  write_notes(notes)
286
+ sync_manager.push()
287
+ return "已移至回收站" if current_filter != "trash" else "彻底删除", load_notes_list(current_filter), ""
288
 
289
+ def handle_pin(note_id, current_filter):
290
+ if not note_id: return load_notes_list(current_filter)
291
+ notes = read_notes()
292
+ for n in notes:
293
+ if n["id"] == note_id:
294
+ n["is_pinned"] = not n.get("is_pinned", False)
295
+ break
296
+ write_notes(notes)
297
+ return load_notes_list(current_filter)
298
 
299
+ # --- Gradio UI ---
300
+ with gr.Blocks(theme=gr.themes.Default(), head=PWA_HEAD) as demo:
301
+ current_filter_state = gr.State("all")
302
+ selected_note_id = gr.State("")
303
 
304
+ with gr.Row(equal_height=True):
305
+ # 1. 导航栏 (ClassNote 风格)
306
+ with gr.Column(scale=1, min_width=150):
307
+ gr.HTML("<div style='font-size: 20px; font-weight: bold; margin-bottom: 30px; color: white;'>HF Note</div>")
308
+ btn_all = gr.Button("全部笔记", variant="secondary", elem_classes=["nav-btn", "active-nav"])
309
+ btn_pinned = gr.Button("已置顶", variant="secondary", elem_classes=["nav-btn"])
310
+ btn_trash = gr.Button("回收站", variant="secondary", elem_classes=["nav-btn"])
311
+
312
+ gr.Markdown("---")
313
+ btn_new = gr.Button("➕ 新建笔记", variant="secondary")
314
+ btn_sync_pull = gr.Button("🔄 同步云端", variant="secondary")
315
+
316
+ # 2. 列表栏
317
+ with gr.Column(scale=2, min_width=250):
318
+ search_box = gr.Textbox(placeholder="搜索笔记...", show_label=False, elem_id="search_box")
319
  note_list = gr.Dataframe(
320
+ headers=["ID", "标题", "时间"],
321
+ datatype=["str", "str", "str"],
322
+ col_count=(3, "fixed"),
323
+ interactive=False,
324
+ label=None,
325
+ )
326
+ status_text = gr.Markdown("就绪")
327
+
328
+ # 3. 编辑器栏
329
+ with gr.Column(scale=4):
330
+ with gr.Row():
331
+ btn_pin = gr.Button("� 置顶", variant="secondary", size="sm")
332
+ btn_del = gr.Button("🗑️ 删除", variant="stop", size="sm")
333
+ btn_ai = gr.Button("AI 润色", variant="primary", size="sm", elem_id="ai_btn")
334
+
335
+ edit_title = gr.Textbox(placeholder="无标题笔记", show_label=False, elem_id="note_title")
336
+ edit_content = gr.TextArea(placeholder="暂无内容,开始输入...", show_label=False, lines=25, elem_id="note_content")
337
+ edit_date = gr.Markdown("", elem_id="note_date")
 
 
 
 
 
 
 
 
 
 
338
 
339
+ # --- 交互事件 ---
340
 
341
+ def on_note_select(evt: gr.SelectData, filt):
342
+ curr_list = load_notes_list(filt)
343
+ note_id = curr_list[evt.index[0]][0]
344
+ title, content, date = get_note_detail(note_id)
345
+ return note_id, title, content, f"最后修改: {date}"
346
+
347
+ note_list.select(on_note_select, [current_filter_state], [selected_note_id, edit_title, edit_content, edit_date])
348
 
349
+ search_box.change(load_notes_list, [current_filter_state, search_box], [note_list])
350
 
351
+ edit_title.blur(handle_save, [selected_note_id, edit_title, edit_content], [status_text, note_list, selected_note_id])
352
+ edit_content.blur(handle_save, [selected_note_id, edit_title, edit_content], [status_text, note_list, selected_note_id])
 
353
 
354
+ btn_new.click(lambda: ("", "新笔记", "", ""), None, [selected_note_id, edit_title, edit_content, edit_date])
355
+ btn_pin.click(handle_pin, [selected_note_id, current_filter_state], [note_list])
356
+ btn_del.click(handle_delete, [selected_note_id, current_filter_state], [status_text, note_list, selected_note_id])
357
+
358
+ btn_sync_pull.click(lambda: (sync_manager.pull()[1], load_notes_list()), None, [status_text, note_list])
359
+
360
+ def ai_polish(content):
361
+ if not content: return content
362
+ return f"✨ [AI 润色已模拟完成]\n\n{content}\n\n(请在本地动作中使用完整的 DeepSeek 润色服务)"
363
+ btn_ai.click(ai_polish, [edit_content], [edit_content])
 
 
 
 
 
 
 
364
 
365
+ demo.load(lambda: (sync_manager.pull()[1], load_notes_list()), None, [status_text, note_list])
 
 
366
 
367
  if __name__ == "__main__":
368
  demo.launch()