forked from aabacada/CloudNav-abcd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
2752 lines (2475 loc) · 116 KB
/
App.tsx
File metadata and controls
2752 lines (2475 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
Search, Plus, Upload, Moon, Sun, Menu,
Trash2, Edit2, Loader2, Cloud, CheckCircle2, AlertCircle,
Pin, Settings, Lock, CloudCog, Github, GitFork, GripVertical, Save, CheckSquare, LogOut, ExternalLink, X
} from 'lucide-react';
import {
DndContext,
DragEndEvent,
closestCenter,
closestCorners,
PointerSensor,
useSensor,
useSensors,
KeyboardSensor,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
rectSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { LinkItem, Category, DEFAULT_CATEGORIES, INITIAL_LINKS, WebDavConfig, AIConfig, SearchMode, ExternalSearchSource, SearchConfig } from './types';
import { parseBookmarks } from './services/bookmarkParser';
import Icon from './components/Icon';
import LinkModal from './components/LinkModal';
import AuthModal from './components/AuthModal';
import CategoryManagerModal from './components/CategoryManagerModal';
import BackupModal from './components/BackupModal';
import CategoryAuthModal from './components/CategoryAuthModal';
import ImportModal from './components/ImportModal';
import SettingsModal from './components/SettingsModal';
import SearchConfigModal from './components/SearchConfigModal';
import ContextMenu from './components/ContextMenu';
import QRCodeModal from './components/QRCodeModal';
// --- 配置项 ---
// 项目核心仓库地址
const GITHUB_REPO_URL = 'https://github.com/aabacada/CloudNav-abcd';
const LOCAL_STORAGE_KEY = 'cloudnav_data_cache';
const AUTH_KEY = 'cloudnav_auth_token';
const WEBDAV_CONFIG_KEY = 'cloudnav_webdav_config';
const AI_CONFIG_KEY = 'cloudnav_ai_config';
const SEARCH_CONFIG_KEY = 'cloudnav_search_config';
function App() {
// --- State ---
const [links, setLinks] = useState<LinkItem[]>([]);
const [categories, setCategories] = useState<Category[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string>('all');
const [searchQuery, setSearchQuery] = useState('');
const [darkMode, setDarkMode] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(false);
// Search Mode State
const [searchMode, setSearchMode] = useState<SearchMode>('external');
const [externalSearchSources, setExternalSearchSources] = useState<ExternalSearchSource[]>([]);
const [isLoadingSearchConfig, setIsLoadingSearchConfig] = useState(true);
// Category Security State
const [unlockedCategoryIds, setUnlockedCategoryIds] = useState<Set<string>>(new Set());
// WebDAV Config State
const [webDavConfig, setWebDavConfig] = useState<WebDavConfig>({
url: '',
username: '',
password: '',
enabled: false
});
// AI Config State
const [aiConfig, setAiConfig] = useState<AIConfig>(() => {
const saved = localStorage.getItem(AI_CONFIG_KEY);
if (saved) {
try {
return JSON.parse(saved);
} catch (e) {}
}
return {
provider: 'gemini',
apiKey: process.env.API_KEY || '',
baseUrl: '',
model: 'gemini-2.5-flash'
};
});
// Site Settings State
const [siteSettings, setSiteSettings] = useState(() => {
const saved = localStorage.getItem('cloudnav_site_settings');
if (saved) {
try {
return JSON.parse(saved);
} catch (e) {}
}
return {
title: 'CloudNav - 我的导航',
navTitle: 'CloudNav',
favicon: '',
cardStyle: 'detailed' as const,
passwordExpiryDays: 7
};
});
// Modals
const [isModalOpen, setIsModalOpen] = useState(false);
const [isAuthOpen, setIsAuthOpen] = useState(false);
const [isCatManagerOpen, setIsCatManagerOpen] = useState(false);
const [isBackupModalOpen, setIsBackupModalOpen] = useState(false);
const [isImportModalOpen, setIsImportModalOpen] = useState(false);
const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
const [isSearchConfigModalOpen, setIsSearchConfigModalOpen] = useState(false);
const [catAuthModalData, setCatAuthModalData] = useState<Category | null>(null);
const [editingLink, setEditingLink] = useState<LinkItem | undefined>(undefined);
// State for data pre-filled from Bookmarklet
const [prefillLink, setPrefillLink] = useState<Partial<LinkItem> | undefined>(undefined);
// Sync State
const [syncStatus, setSyncStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const [authToken, setAuthToken] = useState<string>('');
const [requiresAuth, setRequiresAuth] = useState<boolean | null>(null); // null表示未检查,true表示需要认证,false表示不需要
const [isCheckingAuth, setIsCheckingAuth] = useState(true);
// Sort State
const [isSortingMode, setIsSortingMode] = useState<string | null>(null); // 存储正在排序的分类ID,null表示不在排序模式
const [isSortingPinned, setIsSortingPinned] = useState(false); // 是否正在排序置顶链接
// Batch Edit State
const [isBatchEditMode, setIsBatchEditMode] = useState(false); // 是否处于批量编辑模式
const [selectedLinks, setSelectedLinks] = useState<Set<string>>(new Set()); // 选中的链接ID集合
// Context Menu State
const [contextMenu, setContextMenu] = useState<{
isOpen: boolean;
position: { x: number; y: number };
link: LinkItem | null;
}>({
isOpen: false,
position: { x: 0, y: 0 },
link: null
});
// QR Code Modal State
const [qrCodeModal, setQrCodeModal] = useState<{
isOpen: boolean;
url: string;
title: string;
}>({
isOpen: false,
url: '',
title: ''
});
// Mobile Search State
const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
// Category Action Auth State
const [categoryActionAuth, setCategoryActionAuth] = useState<{
isOpen: boolean;
action: 'edit' | 'delete';
categoryId: string;
categoryName: string;
}>({
isOpen: false,
action: 'edit',
categoryId: '',
categoryName: ''
});
// --- Helpers & Sync Logic ---
const loadFromLocal = () => {
const stored = localStorage.getItem(LOCAL_STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
let loadedCategories = parsed.categories || DEFAULT_CATEGORIES;
// 确保"常用推荐"分类始终存在,并确保它是第一个分类
if (!loadedCategories.some(c => c.id === 'common')) {
loadedCategories = [
{ id: 'common', name: '常用推荐', icon: 'Star' },
...loadedCategories
];
} else {
// 如果"常用推荐"分类已存在,确保它是第一个分类
const commonIndex = loadedCategories.findIndex(c => c.id === 'common');
if (commonIndex > 0) {
const commonCategory = loadedCategories[commonIndex];
loadedCategories = [
commonCategory,
...loadedCategories.slice(0, commonIndex),
...loadedCategories.slice(commonIndex + 1)
];
}
}
// 检查是否有链接的categoryId不存在于当前分类中,将这些链接移动到"常用推荐"
const validCategoryIds = new Set(loadedCategories.map(c => c.id));
let loadedLinks = parsed.links || INITIAL_LINKS;
loadedLinks = loadedLinks.map(link => {
if (!validCategoryIds.has(link.categoryId)) {
return { ...link, categoryId: 'common' };
}
return link;
});
setLinks(loadedLinks);
setCategories(loadedCategories);
} catch (e) {
setLinks(INITIAL_LINKS);
setCategories(DEFAULT_CATEGORIES);
}
} else {
setLinks(INITIAL_LINKS);
setCategories(DEFAULT_CATEGORIES);
}
};
const syncToCloud = async (newLinks: LinkItem[], newCategories: Category[], token: string) => {
setSyncStatus('saving');
try {
const response = await fetch('/api/storage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-password': token
},
body: JSON.stringify({ links: newLinks, categories: newCategories })
});
if (response.status === 401) {
// 检查是否是密码过期
try {
const errorData = await response.json();
if (errorData.error && errorData.error.includes('过期')) {
alert('您的密码已过期,请重新登录');
}
} catch (e) {
// 如果无法解析错误信息,使用默认提示
console.error('Failed to parse error response', e);
}
setAuthToken('');
localStorage.removeItem(AUTH_KEY);
setIsAuthOpen(true);
setSyncStatus('error');
return false;
}
if (!response.ok) throw new Error('Network response was not ok');
setSyncStatus('saved');
setTimeout(() => setSyncStatus('idle'), 2000);
return true;
} catch (error) {
console.error("Sync failed", error);
setSyncStatus('error');
return false;
}
};
const updateData = (newLinks: LinkItem[], newCategories: Category[]) => {
// 1. Optimistic UI Update
setLinks(newLinks);
setCategories(newCategories);
// 2. Save to Local Cache
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify({ links: newLinks, categories: newCategories }));
// 3. Sync to Cloud (if authenticated)
if (authToken) {
syncToCloud(newLinks, newCategories, authToken);
}
};
// --- Context Menu Functions ---
const handleContextMenu = (event: React.MouseEvent, link: LinkItem) => {
event.preventDefault();
event.stopPropagation();
// 在批量编辑模式下禁用右键菜单
if (isBatchEditMode) return;
setContextMenu({
isOpen: true,
position: { x: event.clientX, y: event.clientY },
link: link
});
};
const closeContextMenu = () => {
setContextMenu({
isOpen: false,
position: { x: 0, y: 0 },
link: null
});
};
const copyLinkToClipboard = () => {
if (!contextMenu.link) return;
navigator.clipboard.writeText(contextMenu.link.url)
.then(() => {
// 可以添加一个短暂的提示
console.log('链接已复制到剪贴板');
})
.catch(err => {
console.error('复制链接失败:', err);
});
closeContextMenu();
};
const showQRCode = () => {
if (!contextMenu.link) return;
setQrCodeModal({
isOpen: true,
url: contextMenu.link.url,
title: contextMenu.link.title
});
closeContextMenu();
};
const editLinkFromContextMenu = () => {
if (!contextMenu.link) return;
setEditingLink(contextMenu.link);
setIsModalOpen(true);
closeContextMenu();
};
const deleteLinkFromContextMenu = () => {
if (!contextMenu.link) return;
if (window.confirm(`确定要删除"${contextMenu.link.title}"吗?`)) {
const newLinks = links.filter(link => link.id !== contextMenu.link!.id);
updateData(newLinks, categories);
}
closeContextMenu();
};
const togglePinFromContextMenu = () => {
if (!contextMenu.link) return;
const linkToToggle = links.find(l => l.id === contextMenu.link!.id);
if (!linkToToggle) return;
// 如果是设置为置顶,则设置pinnedOrder为当前置顶链接数量
// 如果是取消置顶,则清除pinnedOrder
const updated = links.map(l => {
if (l.id === contextMenu.link!.id) {
const isPinned = !l.pinned;
return {
...l,
pinned: isPinned,
pinnedOrder: isPinned ? links.filter(link => link.pinned).length : undefined
};
}
return l;
});
updateData(updated, categories);
closeContextMenu();
};
// 加载链接图标缓存
const loadLinkIcons = async (linksToLoad: LinkItem[]) => {
if (!authToken) return; // 只有在已登录状态下才加载图标缓存
const updatedLinks = [...linksToLoad];
const domainsToFetch: string[] = [];
// 收集所有链接的域名(包括已有图标的链接)
for (const link of updatedLinks) {
if (link.url) {
try {
let domain = link.url;
if (!link.url.startsWith('http://') && !link.url.startsWith('https://')) {
domain = 'https://' + link.url;
}
if (domain.startsWith('http://') || domain.startsWith('https://')) {
const urlObj = new URL(domain);
domain = urlObj.hostname;
domainsToFetch.push(domain);
}
} catch (e) {
console.error("Failed to parse URL for icon loading", e);
}
}
}
// 批量获取图标
if (domainsToFetch.length > 0) {
const iconPromises = domainsToFetch.map(async (domain) => {
try {
const response = await fetch(`/api/storage?getConfig=favicon&domain=${encodeURIComponent(domain)}`);
if (response.ok) {
const data = await response.json();
if (data.cached && data.icon) {
return { domain, icon: data.icon };
}
}
} catch (error) {
console.log(`Failed to fetch cached icon for ${domain}`, error);
}
return null;
});
const iconResults = await Promise.all(iconPromises);
// 更新链接的图标
iconResults.forEach(result => {
if (result) {
const linkToUpdate = updatedLinks.find(link => {
if (!link.url) return false;
try {
let domain = link.url;
if (!link.url.startsWith('http://') && !link.url.startsWith('https://')) {
domain = 'https://' + link.url;
}
if (domain.startsWith('http://') || domain.startsWith('https://')) {
const urlObj = new URL(domain);
return urlObj.hostname === result.domain;
}
} catch (e) {
return false;
}
return false;
});
if (linkToUpdate) {
// 只有当链接没有图标,或者当前图标是faviconextractor.com生成的,或者缓存中的图标是自定义图标时才更新
if (!linkToUpdate.icon ||
linkToUpdate.icon.includes('faviconextractor.com') ||
!result.icon.includes('faviconextractor.com')) {
linkToUpdate.icon = result.icon;
}
}
}
});
// 更新状态
setLinks(updatedLinks);
}
};
// --- Effects ---
useEffect(() => {
// Theme init
if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
setDarkMode(true);
document.documentElement.classList.add('dark');
}
// Load Token and check expiry
const savedToken = localStorage.getItem(AUTH_KEY);
const lastLoginTime = localStorage.getItem('lastLoginTime');
if (savedToken) {
const currentTime = Date.now();
if (lastLoginTime) {
const lastLogin = parseInt(lastLoginTime);
const timeDiff = currentTime - lastLogin;
const expiryDays = siteSettings.passwordExpiryDays || 7;
const expiryTimeMs = expiryDays > 0 ? expiryDays * 24 * 60 * 60 * 1000 : 0;
if (expiryTimeMs > 0 && timeDiff > expiryTimeMs) {
localStorage.removeItem(AUTH_KEY);
localStorage.removeItem('lastLoginTime');
setAuthToken(null);
} else {
setAuthToken(savedToken);
}
} else {
setAuthToken(savedToken);
}
}
// Load WebDAV Config
const savedWebDav = localStorage.getItem(WEBDAV_CONFIG_KEY);
if (savedWebDav) {
try {
setWebDavConfig(JSON.parse(savedWebDav));
} catch (e) {}
}
// Handle URL Params for Bookmarklet (Add Link)
const urlParams = new URLSearchParams(window.location.search);
const addUrl = urlParams.get('add_url');
if (addUrl) {
const addTitle = urlParams.get('add_title') || '';
// Clean URL params to avoid re-triggering on refresh
window.history.replaceState({}, '', window.location.pathname);
setPrefillLink({
title: addTitle,
url: addUrl,
categoryId: 'common' // Default, Modal will handle selection
});
setEditingLink(undefined);
setIsModalOpen(true);
}
// Initial Data Fetch
const initData = async () => {
// 首先检查是否需要认证
try {
const authRes = await fetch('/api/storage?checkAuth=true');
if (authRes.ok) {
const authData = await authRes.json();
setRequiresAuth(authData.requiresAuth);
// 如果需要认证但用户未登录,则不获取数据
if (authData.requiresAuth && !savedToken) {
setIsCheckingAuth(false);
setIsAuthOpen(true);
return;
}
}
} catch (e) {
console.warn("Failed to check auth requirement.", e);
}
// 获取数据
let hasCloudData = false;
try {
const res = await fetch('/api/storage', {
headers: authToken ? { 'x-auth-password': authToken } : {}
});
if (res.ok) {
const data = await res.json();
if (data.links && data.links.length > 0) {
setLinks(data.links);
setCategories(data.categories || DEFAULT_CATEGORIES);
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(data));
// 加载链接图标缓存
loadLinkIcons(data.links);
hasCloudData = true;
}
} else if (res.status === 401) {
// 如果返回401,可能是密码过期,清除本地token并要求重新登录
const errorData = await res.json();
if (errorData.error && errorData.error.includes('过期')) {
setAuthToken(null);
localStorage.removeItem(AUTH_KEY);
setIsAuthOpen(true);
setIsCheckingAuth(false);
return;
}
}
} catch (e) {
console.warn("Failed to fetch from cloud, falling back to local.", e);
}
// 无论是否有云端数据,都尝试从KV空间加载搜索配置和网站配置
try {
const searchConfigRes = await fetch('/api/storage?getConfig=search');
if (searchConfigRes.ok) {
const searchConfigData = await searchConfigRes.json();
// 检查搜索配置是否有效(包含必要的字段)
if (searchConfigData && (searchConfigData.mode || searchConfigData.externalSources || searchConfigData.selectedSource)) {
setSearchMode(searchConfigData.mode || 'external');
setExternalSearchSources(searchConfigData.externalSources || []);
// 加载已保存的选中搜索源
if (searchConfigData.selectedSource) {
setSelectedSearchSource(searchConfigData.selectedSource);
}
}
}
// 获取网站配置(包括密码过期时间设置)
const websiteConfigRes = await fetch('/api/storage?getConfig=website');
if (websiteConfigRes.ok) {
const websiteConfigData = await websiteConfigRes.json();
if (websiteConfigData) {
setSiteSettings(prev => ({
...prev,
title: websiteConfigData.title || prev.title,
navTitle: websiteConfigData.navTitle || prev.navTitle,
favicon: websiteConfigData.favicon || prev.favicon,
cardStyle: websiteConfigData.cardStyle || prev.cardStyle,
passwordExpiryDays: websiteConfigData.passwordExpiryDays !== undefined ? websiteConfigData.passwordExpiryDays : prev.passwordExpiryDays
}));
}
}
} catch (e) {
console.warn("Failed to fetch configs from KV.", e);
}
// 如果有云端数据,则不需要加载本地数据
if (hasCloudData) {
setIsCheckingAuth(false);
return;
}
// 如果没有云端数据,则加载本地数据
loadFromLocal();
// 如果从KV空间加载搜索配置失败,直接使用默认配置(不使用localStorage回退)
setSearchMode('external');
setExternalSearchSources([
{
id: 'bing',
name: '必应',
url: 'https://www.bing.com/search?q={query}',
icon: 'Search',
enabled: true,
createdAt: Date.now()
},
{
id: 'google',
name: 'Google',
url: 'https://www.google.com/search?q={query}',
icon: 'Search',
enabled: true,
createdAt: Date.now()
},
{
id: 'baidu',
name: '百度',
url: 'https://www.baidu.com/s?wd={query}',
icon: 'Globe',
enabled: true,
createdAt: Date.now()
},
{
id: 'sogou',
name: '搜狗',
url: 'https://www.sogou.com/web?query={query}',
icon: 'Globe',
enabled: true,
createdAt: Date.now()
},
{
id: 'yandex',
name: 'Yandex',
url: 'https://yandex.com/search/?text={query}',
icon: 'Globe',
enabled: true,
createdAt: Date.now()
},
{
id: 'github',
name: 'GitHub',
url: 'https://github.com/search?q={query}',
icon: 'Github',
enabled: true,
createdAt: Date.now()
},
{
id: 'linuxdo',
name: 'Linux.do',
url: 'https://linux.do/search?q={query}',
icon: 'Terminal',
enabled: true,
createdAt: Date.now()
},
{
id: 'bilibili',
name: 'B站',
url: 'https://search.bilibili.com/all?keyword={query}',
icon: 'Play',
enabled: true,
createdAt: Date.now()
},
{
id: 'youtube',
name: 'YouTube',
url: 'https://www.youtube.com/results?search_query={query}',
icon: 'Video',
enabled: true,
createdAt: Date.now()
},
{
id: 'wikipedia',
name: '维基',
url: 'https://zh.wikipedia.org/wiki/Special:Search?search={query}',
icon: 'BookOpen',
enabled: true,
createdAt: Date.now()
}
]);
setIsLoadingSearchConfig(false);
setIsCheckingAuth(false);
};
initData();
}, []);
// Update page title and favicon when site settings change
useEffect(() => {
if (siteSettings.title) {
document.title = siteSettings.title;
}
if (siteSettings.favicon) {
// Remove existing favicon links
const existingFavicons = document.querySelectorAll('link[rel="icon"]');
existingFavicons.forEach(favicon => favicon.remove());
// Add new favicon
const favicon = document.createElement('link');
favicon.rel = 'icon';
favicon.href = siteSettings.favicon;
document.head.appendChild(favicon);
}
}, [siteSettings.title, siteSettings.favicon]);
const toggleTheme = () => {
const newMode = !darkMode;
setDarkMode(newMode);
if (newMode) {
document.documentElement.classList.add('dark');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.classList.remove('dark');
localStorage.setItem('theme', 'light');
}
};
// 视图模式切换处理函数
const handleViewModeChange = (cardStyle: 'detailed' | 'simple') => {
const newSiteSettings = { ...siteSettings, cardStyle };
setSiteSettings(newSiteSettings);
localStorage.setItem('cloudnav_site_settings', JSON.stringify(newSiteSettings));
};
// --- Batch Edit Functions ---
const toggleBatchEditMode = () => {
setIsBatchEditMode(!isBatchEditMode);
setSelectedLinks(new Set()); // 退出批量编辑模式时清空选中项
};
const toggleLinkSelection = (linkId: string) => {
setSelectedLinks(prev => {
const newSet = new Set(prev);
if (newSet.has(linkId)) {
newSet.delete(linkId);
} else {
newSet.add(linkId);
}
return newSet;
});
};
const handleBatchDelete = () => {
if (!authToken) { setIsAuthOpen(true); return; }
if (selectedLinks.size === 0) {
alert('请先选择要删除的链接');
return;
}
if (confirm(`确定要删除选中的 ${selectedLinks.size} 个链接吗?`)) {
const newLinks = links.filter(link => !selectedLinks.has(link.id));
updateData(newLinks, categories);
setSelectedLinks(new Set());
setIsBatchEditMode(false);
}
};
const handleBatchMove = (targetCategoryId: string) => {
if (!authToken) { setIsAuthOpen(true); return; }
if (selectedLinks.size === 0) {
alert('请先选择要移动的链接');
return;
}
const newLinks = links.map(link =>
selectedLinks.has(link.id) ? { ...link, categoryId: targetCategoryId } : link
);
updateData(newLinks, categories);
setSelectedLinks(new Set());
setIsBatchEditMode(false);
};
const handleSelectAll = () => {
// 获取当前显示的所有链接ID
const currentLinkIds = displayedLinks.map(link => link.id);
// 如果已选中的链接数量等于当前显示的链接数量,则取消全选
if (selectedLinks.size === currentLinkIds.length && currentLinkIds.every(id => selectedLinks.has(id))) {
setSelectedLinks(new Set());
} else {
// 否则全选当前显示的所有链接
setSelectedLinks(new Set(currentLinkIds));
}
};
// --- Actions ---
const handleLogin = async (password: string): Promise<boolean> => {
try {
// 首先验证密码
const authResponse = await fetch('/api/storage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-password': password
},
body: JSON.stringify({ authOnly: true }) // 只用于验证密码,不更新数据
});
if (authResponse.ok) {
setAuthToken(password);
localStorage.setItem(AUTH_KEY, password);
setIsAuthOpen(false);
setSyncStatus('saved');
// 登录成功后,获取网站配置(包括密码过期时间设置)
try {
const websiteConfigRes = await fetch('/api/storage?getConfig=website');
if (websiteConfigRes.ok) {
const websiteConfigData = await websiteConfigRes.json();
if (websiteConfigData) {
setSiteSettings(prev => ({
...prev,
title: websiteConfigData.title || prev.title,
navTitle: websiteConfigData.navTitle || prev.navTitle,
favicon: websiteConfigData.favicon || prev.favicon,
cardStyle: websiteConfigData.cardStyle || prev.cardStyle,
passwordExpiryDays: websiteConfigData.passwordExpiryDays !== undefined ? websiteConfigData.passwordExpiryDays : prev.passwordExpiryDays
}));
}
}
} catch (e) {
console.warn("Failed to fetch website config after login.", e);
}
// 检查密码是否过期
const lastLoginTime = localStorage.getItem('lastLoginTime');
const currentTime = Date.now();
if (lastLoginTime) {
const lastLogin = parseInt(lastLoginTime);
const timeDiff = currentTime - lastLogin;
const expiryTimeMs = (siteSettings.passwordExpiryDays || 7) > 0 ? (siteSettings.passwordExpiryDays || 7) * 24 * 60 * 60 * 1000 : 0;
if (expiryTimeMs > 0 && timeDiff > expiryTimeMs) {
setAuthToken(null);
localStorage.removeItem(AUTH_KEY);
setIsAuthOpen(true);
alert('您的密码已过期,请重新登录');
return false;
}
}
localStorage.setItem('lastLoginTime', currentTime.toString());
// 登录成功后,从服务器获取数据
try {
const res = await fetch('/api/storage');
if (res.ok) {
const data = await res.json();
// 如果服务器有数据,使用服务器数据
if (data.links && data.links.length > 0) {
setLinks(data.links);
setCategories(data.categories || DEFAULT_CATEGORIES);
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(data));
// 加载链接图标缓存
loadLinkIcons(data.links);
} else {
// 如果服务器没有数据,使用本地数据
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify({ links, categories }));
// 并将本地数据同步到服务器
syncToCloud(links, categories, password);
// 加载链接图标缓存
loadLinkIcons(links);
}
}
} catch (e) {
console.warn("Failed to fetch data after login.", e);
loadFromLocal();
// 尝试将本地数据同步到服务器
syncToCloud(links, categories, password);
}
// 登录成功后,从KV空间加载AI配置
try {
const aiConfigRes = await fetch('/api/storage?getConfig=ai');
if (aiConfigRes.ok) {
const aiConfigData = await aiConfigRes.json();
if (aiConfigData && Object.keys(aiConfigData).length > 0) {
setAiConfig(aiConfigData);
localStorage.setItem(AI_CONFIG_KEY, JSON.stringify(aiConfigData));
}
}
} catch (e) {
console.warn("Failed to fetch AI config after login.", e);
}
return true;
}
return false;
} catch (e) {
return false;
}
};
const handleLogout = () => {
setAuthToken(null);
localStorage.removeItem(AUTH_KEY);
setSyncStatus('offline');
// 退出后重新加载本地数据
loadFromLocal();
};
// 分类操作密码验证处理函数
const handleCategoryActionAuth = async (password: string): Promise<boolean> => {
try {
// 验证密码
const authResponse = await fetch('/api/storage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-password': password
},
body: JSON.stringify({ authOnly: true })
});
return authResponse.ok;
} catch (error) {
console.error('Category action auth error:', error);
return false;
}
};
// 打开分类操作验证弹窗
const openCategoryActionAuth = (action: 'edit' | 'delete', categoryId: string, categoryName: string) => {
setCategoryActionAuth({
isOpen: true,
action,
categoryId,
categoryName
});
};
// 关闭分类操作验证弹窗
const closeCategoryActionAuth = () => {
setCategoryActionAuth({
isOpen: false,
action: 'edit',
categoryId: '',
categoryName: ''
});
};
const handleImportConfirm = (newLinks: LinkItem[], newCategories: Category[]) => {
// Merge categories: Avoid duplicate names/IDs
const mergedCategories = [...categories];
// 确保"常用推荐"分类始终存在
if (!mergedCategories.some(c => c.id === 'common')) {
mergedCategories.push({ id: 'common', name: '常用推荐', icon: 'Star' });
}
newCategories.forEach(nc => {
if (!mergedCategories.some(c => c.id === nc.id || c.name === nc.name)) {
mergedCategories.push(nc);
}
});
const mergedLinks = [...links, ...newLinks];
updateData(mergedLinks, mergedCategories);
setIsImportModalOpen(false);
alert(`成功导入 ${newLinks.length} 个新书签!`);
};
const handleAddLink = (data: Omit<LinkItem, 'id' | 'createdAt'>) => {
if (!authToken) { setIsAuthOpen(true); return; }
// 处理URL,确保有协议前缀
let processedUrl = data.url;
if (processedUrl && !processedUrl.startsWith('http://') && !processedUrl.startsWith('https://')) {
processedUrl = 'https://' + processedUrl;
}
// 获取当前分类下的所有链接(不包括置顶链接)
const categoryLinks = links.filter(link =>
!link.pinned && (data.categoryId === 'all' || link.categoryId === data.categoryId)