-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1641 lines (1559 loc) · 48.2 KB
/
Copy pathApp.tsx
File metadata and controls
1641 lines (1559 loc) · 48.2 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, {
useRef,
startTransition,
useDeferredValue,
useEffect,
useMemo,
useState,
} from "react";
import {
Alert,
Animated,
Easing,
Image,
KeyboardAvoidingView,
Keyboard,
LayoutAnimation,
Linking,
Modal,
NativeSyntheticEvent,
Platform,
Pressable,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
TextInput,
TextInputSelectionChangeEventData,
UIManager,
View,
} from "react-native";
import { StatusBar as ExpoStatusBar } from "expo-status-bar";
import * as DocumentPicker from "expo-document-picker";
import * as FileSystem from "expo-file-system/legacy";
import * as Print from "expo-print";
import * as Sharing from "expo-sharing";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { markdownToHtml, SimpleMarkdown } from "./src/components/SimpleMarkdown";
import { GUIDE_DOCUMENT_ID, LEGACY_BUNDLED_IDS, sampleDocuments } from "./src/data/sampleDocs";
import { palettes } from "./src/theme";
import type { Palette } from "./src/theme";
import type {
EditorMode,
MarkdownDocument,
RecentViewMode,
TabKey,
ThemeMode,
} from "./src/types";
const STORAGE_KEY = "tinymd-state-v1";
const DOCUMENTS_DIR = `${FileSystem.documentDirectory ?? ""}documents/`;
const EXPORTS_DIR = `${FileSystem.cacheDirectory ?? FileSystem.documentDirectory ?? ""}exports/`;
type ExportFormat = "md" | "pdf";
type PersistedState = {
documents: MarkdownDocument[];
selectedId: string;
themeMode: ThemeMode;
recentViewMode: RecentViewMode;
};
const APP_VERSION = "1.1.0";
const PROJECT_URL = "https://github.com/TTZW1001/TinyMD";
const GITHUB_MARK_URL = "https://github.githubassets.com/favicons/favicon-dark.png";
const CHANGELOG_ITEMS = [
"默认文档调整为《TinyMD使用指南》,首开内容更清晰。",
"进一步整理初始工作区,让成品状态更简洁。",
"继续优化阅读、编辑、导出与主题切换体验。",
"统一首发成品内容,适合直接安装开始使用。",
];
function migrateDocuments(docs: MarkdownDocument[]) {
const legacyIds = new Set(LEGACY_BUNDLED_IDS);
const bundledGuide = sampleDocuments[0];
const existingGuide = docs.find((doc) => doc.id === GUIDE_DOCUMENT_ID);
const userDocs = docs.filter((doc) => !doc.isBundled);
const hasGuide = docs.some((doc) => doc.id === GUIDE_DOCUMENT_ID);
const hasLegacyBundled = docs.some((doc) => legacyIds.has(doc.id));
if (!docs.length) {
return [...sampleDocuments];
}
if (!userDocs.length && (hasLegacyBundled || !hasGuide)) {
return [...sampleDocuments];
}
const preserved = docs.filter((doc) => !legacyIds.has(doc.id) && doc.id !== GUIDE_DOCUMENT_ID);
const nextDocs = [existingGuide ?? bundledGuide, ...preserved];
return nextDocs.length ? nextDocs : [...sampleDocuments];
}
function makeExcerpt(content: string) {
return content
.replace(/[#>*`\-\[\]]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 84);
}
function formatTime(iso: string) {
const date = new Date(iso);
const now = new Date();
const diffMinutes = Math.floor((now.getTime() - date.getTime()) / (60 * 1000));
if (diffMinutes < 1) return "刚刚";
if (diffMinutes < 60) return `${diffMinutes} 分钟前`;
const diffHours = Math.floor(diffMinutes / 60);
if (diffHours < 24) return `${diffHours} 小时前`;
return `${date.getMonth() + 1}/${date.getDate()}`;
}
function slugify(title: string) {
return title
.toLowerCase()
.replace(/\.md$/i, "")
.replace(/[^a-z0-9\u4e00-\u9fa5]+/gi, "-")
.replace(/^-+|-+$/g, "");
}
function normalizeImportedTitle(name: string) {
return name.toLowerCase().endsWith(".md") ? name : `${name}.md`;
}
function stripExtension(name: string) {
return name.replace(/\.[a-z0-9]+$/i, "");
}
function sanitizeFileName(name: string) {
const trimmed = name.trim().replace(/[\\/:*?"<>|]/g, "-");
return trimmed || "TinyMD 文档";
}
function normalizeTitleForCompare(value: string) {
return stripExtension(value)
.toLowerCase()
.replace(/\s+/g, "")
.replace(/[^\u4e00-\u9fa5a-z0-9]/gi, "");
}
function stripRedundantTitle(content: string, title: string) {
const lines = content.replace(/\r\n/g, "\n").split("\n");
const firstContentLine = lines.findIndex((line) => line.trim().length > 0);
if (firstContentLine === -1) return content;
const firstLine = lines[firstContentLine];
const heading = firstLine.match(/^(#{1,6})\s+(.+)$/);
if (!heading) return content;
const headingText = normalizeTitleForCompare(heading[2]);
const titleText = normalizeTitleForCompare(title);
if (!headingText || headingText !== titleText) return content;
lines.splice(firstContentLine, 1);
while (lines[firstContentLine] !== undefined && !lines[firstContentLine].trim()) {
lines.splice(firstContentLine, 1);
}
return lines.join("\n");
}
async function ensureDocsDir() {
if (!FileSystem.documentDirectory) return;
const info = await FileSystem.getInfoAsync(DOCUMENTS_DIR);
if (!info.exists) {
await FileSystem.makeDirectoryAsync(DOCUMENTS_DIR, { intermediates: true });
}
}
async function ensureExportsDir() {
const info = await FileSystem.getInfoAsync(EXPORTS_DIR);
if (!info.exists) {
await FileSystem.makeDirectoryAsync(EXPORTS_DIR, { intermediates: true });
}
}
export default function App() {
const [ready, setReady] = useState(false);
const [themeMode, setThemeMode] = useState<ThemeMode>("dark");
const [recentViewMode, setRecentViewMode] = useState<RecentViewMode>("list");
const [activeTab, setActiveTab] = useState<TabKey>("recent");
const [editorMode, setEditorMode] = useState<EditorMode>("rendered");
const [searchQuery, setSearchQuery] = useState("");
const [documents, setDocuments] = useState<MarkdownDocument[]>(sampleDocuments);
const [selectedId, setSelectedId] = useState(sampleDocuments[0]?.id ?? "");
const [draftContent, setDraftContent] = useState(sampleDocuments[0]?.content ?? "");
const [selection, setSelection] = useState({ start: 0, end: 0 });
const [exportOpen, setExportOpen] = useState(false);
const [exportName, setExportName] = useState(stripExtension(sampleDocuments[0]?.title ?? "TinyMD 文档"));
const [exportFormat, setExportFormat] = useState<ExportFormat>("md");
const [keyboardHeight, setKeyboardHeight] = useState(0);
const [manageDocId, setManageDocId] = useState("");
const [manageOpen, setManageOpen] = useState(false);
const [manageDocTitle, setManageDocTitle] = useState("");
const [renameOpen, setRenameOpen] = useState(false);
const [renameValue, setRenameValue] = useState("");
const themeFade = useRef(new Animated.Value(1)).current;
const deferredQuery = useDeferredValue(searchQuery);
const palette = palettes[themeMode];
const selectedDoc = documents.find((doc) => doc.id === selectedId) ?? documents[0];
const readerContent = selectedDoc ? stripRedundantTitle(draftContent, selectedDoc.title) : "";
const topInset = (Platform.OS === "android" ? StatusBar.currentHeight ?? 0 : 0) + 6;
useEffect(() => {
let mounted = true;
async function load() {
try {
await ensureDocsDir();
const raw = await AsyncStorage.getItem(STORAGE_KEY);
if (!raw) {
setReady(true);
return;
}
const persisted = JSON.parse(raw) as PersistedState;
if (!mounted) return;
const initialDocs = migrateDocuments(
persisted.documents?.length ? persisted.documents : sampleDocuments
);
const selectedDocId = initialDocs.some((doc) => doc.id === persisted.selectedId)
? persisted.selectedId
: initialDocs[0]?.id || "";
setDocuments(initialDocs);
setSelectedId(selectedDocId);
setDraftContent(
initialDocs.find((doc) => doc.id === selectedDocId)?.content ??
initialDocs[0]?.content ??
""
);
setExportName(stripExtension(selectedDocId ? (initialDocs.find((doc) => doc.id === selectedDocId)?.title ?? initialDocs[0]?.title ?? "TinyMD 文档") : initialDocs[0]?.title ?? "TinyMD 文档"));
setThemeMode(persisted.themeMode ?? "dark");
setRecentViewMode(persisted.recentViewMode ?? "list");
} catch (error) {
console.error("Failed to load TinyMD state", error);
} finally {
if (mounted) setReady(true);
}
}
load();
return () => {
mounted = false;
};
}, []);
useEffect(() => {
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const showEvent = Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow";
const hideEvent = Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide";
const showSub = Keyboard.addListener(showEvent, (event) => {
setKeyboardHeight(event.endCoordinates.height);
});
const hideSub = Keyboard.addListener(hideEvent, () => {
setKeyboardHeight(0);
});
return () => {
showSub.remove();
hideSub.remove();
};
}, []);
useEffect(() => {
if (!ready || !selectedDoc) return;
const payload: PersistedState = {
documents,
selectedId,
themeMode,
recentViewMode,
};
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(payload)).catch((error) => {
console.error("Failed to persist TinyMD state", error);
});
}, [documents, ready, recentViewMode, selectedDoc, selectedId, themeMode]);
useEffect(() => {
if (!selectedDoc) return;
setExportName(stripExtension(selectedDoc.title));
}, [selectedDoc?.id]);
useEffect(() => {
Animated.sequence([
Animated.timing(themeFade, {
toValue: 0.92,
duration: 100,
easing: Easing.out(Easing.quad),
useNativeDriver: true,
}),
Animated.timing(themeFade, {
toValue: 1,
duration: 180,
easing: Easing.out(Easing.quad),
useNativeDriver: true,
}),
]).start();
}, [themeMode, themeFade]);
const filteredDocs = useMemo(() => {
const query = deferredQuery.trim().toLowerCase();
if (!query) return documents;
return documents.filter((doc) => {
const haystack = `${doc.title}\n${doc.excerpt}\n${doc.content}`.toLowerCase();
return haystack.includes(query);
});
}, [deferredQuery, documents]);
function openDocument(doc: MarkdownDocument, nextTab: TabKey = "editor") {
setSelectedId(doc.id);
setDraftContent(doc.content);
setSelection({ start: 0, end: 0 });
setExportOpen(false);
startTransition(() => setActiveTab(nextTab));
}
function applyFormatting(kind: "h1" | "quote" | "ul" | "task" | "code" | "bold") {
const start = selection.start;
const end = selection.end;
const selectedText = draftContent.slice(start, end);
let nextText = draftContent;
let nextSelection = selection;
const insert = (value: string, cursorOffset?: number) => {
nextText = `${draftContent.slice(0, start)}${value}${draftContent.slice(end)}`;
const position = cursorOffset ?? value.length;
nextSelection = {
start: start + position,
end: start + position,
};
};
const wrapSelected = (prefix: string, suffix = "") => {
const content = selectedText || "内容";
const value = `${prefix}${content}${suffix}`;
nextText = `${draftContent.slice(0, start)}${value}${draftContent.slice(end)}`;
const innerStart = start + prefix.length;
const innerEnd = innerStart + content.length;
nextSelection = selectedText
? { start: innerStart, end: innerEnd }
: { start: innerStart, end: innerEnd };
};
const lineStart = draftContent.lastIndexOf("\n", start - 1) + 1;
const lineEndCandidate = draftContent.indexOf("\n", end);
const lineEnd = lineEndCandidate === -1 ? draftContent.length : lineEndCandidate;
const currentLine = draftContent.slice(lineStart, lineEnd);
const prefixLine = (prefix: string) => {
const updatedLine = currentLine.startsWith(prefix) ? currentLine : `${prefix}${currentLine}`;
nextText = `${draftContent.slice(0, lineStart)}${updatedLine}${draftContent.slice(lineEnd)}`;
nextSelection = {
start: lineStart + updatedLine.length,
end: lineStart + updatedLine.length,
};
};
switch (kind) {
case "h1":
prefixLine("# ");
break;
case "quote":
prefixLine("> ");
break;
case "ul":
prefixLine("- ");
break;
case "task":
prefixLine("- [ ] ");
break;
case "code":
if (selectedText) {
wrapSelected("```txt\n", "\n```");
} else {
insert("```txt\n代码\n```", 7);
}
break;
case "bold":
wrapSelected("**", "**");
break;
}
setDraftContent(nextText);
setSelection(nextSelection);
}
function handleSelectionChange(
event: NativeSyntheticEvent<TextInputSelectionChangeEventData>
) {
setSelection(event.nativeEvent.selection);
}
async function importDocument() {
try {
const result = await DocumentPicker.getDocumentAsync({
type: ["text/markdown", "text/plain"],
copyToCacheDirectory: true,
multiple: false,
});
if (result.canceled || !result.assets.length) {
return;
}
await ensureDocsDir();
const asset = result.assets[0];
const importedTitle = normalizeImportedTitle(asset.name || "imported.md");
const safeName = `${slugify(importedTitle) || "document"}-${Date.now()}.md`;
const targetUri = `${DOCUMENTS_DIR}${safeName}`;
const content = await FileSystem.readAsStringAsync(asset.uri, {
encoding: FileSystem.EncodingType.UTF8,
});
await FileSystem.copyAsync({
from: asset.uri,
to: targetUri,
});
const nextDoc: MarkdownDocument = {
id: `doc-${Date.now()}`,
title: importedTitle,
content,
excerpt: makeExcerpt(content),
updatedAt: new Date().toISOString(),
originalUri: asset.uri,
storageUri: targetUri,
};
setDocuments((current) => [nextDoc, ...current.filter((doc) => doc.id !== nextDoc.id)]);
openDocument(nextDoc);
} catch (error) {
console.error("Import failed", error);
Alert.alert("导入失败", "没有成功读取这个 Markdown 文件。");
}
}
async function saveDocument() {
if (!selectedDoc) return;
try {
await ensureDocsDir();
const storageUri =
selectedDoc.storageUri ||
`${DOCUMENTS_DIR}${slugify(selectedDoc.title) || "document"}-${selectedDoc.id}.md`;
await FileSystem.writeAsStringAsync(storageUri, draftContent, {
encoding: FileSystem.EncodingType.UTF8,
});
const updatedDoc: MarkdownDocument = {
...selectedDoc,
content: draftContent,
excerpt: makeExcerpt(draftContent),
updatedAt: new Date().toISOString(),
storageUri,
};
setDocuments((current) =>
current.map((doc) => (doc.id === updatedDoc.id ? updatedDoc : doc))
);
setEditorMode("rendered");
Alert.alert("已保存", "文档已保存到 TinyMD 本地目录。");
} catch (error) {
console.error("Save failed", error);
Alert.alert("保存失败", "当前文档没有成功写入本地目录。");
}
}
async function exportDocument() {
if (!selectedDoc) return;
try {
const latestContent = selectedDoc.id === selectedId ? draftContent : selectedDoc.content;
const safeBaseName = sanitizeFileName(exportName);
await ensureExportsDir();
let targetUri = `${EXPORTS_DIR}${safeBaseName}.md`;
let mimeType = "text/markdown";
if (exportFormat === "md") {
await FileSystem.writeAsStringAsync(targetUri, latestContent, {
encoding: FileSystem.EncodingType.UTF8,
});
} else {
const html = markdownToHtml(latestContent, {
background: palette.background,
text: palette.text,
muted: palette.textSoft,
border: palette.border,
accent: palette.primary,
panel: palette.panel,
title: safeBaseName,
});
const printResult = await Print.printToFileAsync({ html });
targetUri = `${EXPORTS_DIR}${safeBaseName}.pdf`;
mimeType = "application/pdf";
await FileSystem.copyAsync({
from: printResult.uri,
to: targetUri,
});
}
const available = await Sharing.isAvailableAsync();
if (!available) {
Alert.alert("已导出", `文件已保存到 ${exportFormat.toUpperCase()} 导出目录。`);
return;
}
await Sharing.shareAsync(targetUri, {
mimeType,
dialogTitle: "导出 TinyMD 文档",
});
setExportOpen(false);
} catch (error) {
console.error("Export failed", error);
Alert.alert("导出失败", "没有成功生成导出文件。");
}
}
function createBlankDocument() {
const baseTitle = `New Note ${documents.length + 1}.md`;
const nextDoc: MarkdownDocument = {
id: `doc-${Date.now()}`,
title: baseTitle,
content: "# 新文档\n\n从这里开始写。",
excerpt: "从这里开始写。",
updatedAt: new Date().toISOString(),
};
setDocuments((current) => [nextDoc, ...current]);
setEditorMode("source");
setExportName(stripExtension(baseTitle));
openDocument(nextDoc);
}
function promptManageDocument(doc: MarkdownDocument) {
setManageDocId(doc.id);
setManageDocTitle(doc.title);
setManageOpen(true);
}
async function deleteDocument(docId: string) {
const target = documents.find((doc) => doc.id === docId);
if (!target) return;
try {
if (target.storageUri) {
const info = await FileSystem.getInfoAsync(target.storageUri);
if (info.exists) {
await FileSystem.deleteAsync(target.storageUri, { idempotent: true });
}
}
const remaining = documents.filter((doc) => doc.id !== docId);
setDocuments(remaining.length ? remaining : sampleDocuments);
setManageOpen(false);
const nextDoc = remaining[0] ?? sampleDocuments[0];
if (nextDoc) {
openDocument(nextDoc, activeTab === "reader" ? "reader" : "recent");
}
setRenameOpen(false);
} catch (error) {
console.error("Delete failed", error);
Alert.alert("删除失败", "没有成功移除这个文件。");
}
}
async function renameDocument() {
const target = documents.find((doc) => doc.id === manageDocId);
const nextTitleBase = sanitizeFileName(renameValue);
if (!target || !nextTitleBase) return;
const nextTitle = nextTitleBase.toLowerCase().endsWith(".md")
? nextTitleBase
: `${nextTitleBase}.md`;
try {
let nextStorageUri = target.storageUri;
if (target.storageUri) {
const currentInfo = await FileSystem.getInfoAsync(target.storageUri);
if (currentInfo.exists) {
await ensureDocsDir();
nextStorageUri = `${DOCUMENTS_DIR}${slugify(nextTitle) || "document"}-${target.id}.md`;
if (nextStorageUri !== target.storageUri) {
await FileSystem.moveAsync({
from: target.storageUri,
to: nextStorageUri,
});
}
}
}
setDocuments((current) =>
current.map((doc) =>
doc.id === manageDocId
? {
...doc,
title: nextTitle,
updatedAt: new Date().toISOString(),
storageUri: nextStorageUri,
}
: doc
)
);
if (selectedId === manageDocId) {
setExportName(stripExtension(nextTitle));
}
setManageOpen(false);
setRenameOpen(false);
} catch (error) {
console.error("Rename failed", error);
Alert.alert("重命名失败", "没有成功更新这个文件名。");
}
}
const styles = useMemo(() => createStyles(palette, topInset), [palette, topInset]);
if (!ready) {
return (
<SafeAreaView style={[styles.app, styles.centered]}>
<StatusBar barStyle={themeMode === "dark" ? "light-content" : "dark-content"} />
<Text style={styles.loadingTitle}>TinyMD</Text>
<Text style={styles.loadingText}>正在载入文档与主题设置…</Text>
</SafeAreaView>
);
}
return (
<Animated.View style={[styles.app, { opacity: themeFade }]}>
<StatusBar barStyle={themeMode === "dark" ? "light-content" : "dark-content"} />
<ExpoStatusBar style={themeMode === "dark" ? "light" : "dark"} />
<View style={styles.header}>
<View>
<Text style={styles.headerTitle}>TinyMD</Text>
<Text style={styles.headerSubtitle}>轻量 Markdown 工作区</Text>
</View>
<View style={styles.headerActions}>
<ActionButton label="导入" onPress={importDocument} palette={palette} primary prominence="toolbar" />
<ActionButton label="新建" onPress={createBlankDocument} palette={palette} prominence="toolbar" />
</View>
</View>
<View style={styles.tabRow}>
{[
["recent", "最近"],
["editor", "编辑"],
["reader", "阅读"],
["settings", "设置"],
].map(([key, label]) => {
const current = key as TabKey;
const active = current === activeTab;
return (
<Pressable
key={key}
onPress={() => setActiveTab(current)}
style={[styles.tabButton, active && styles.tabButtonActive]}
>
<Text style={[styles.tabButtonText, active && styles.tabButtonTextActive]}>{label}</Text>
</Pressable>
);
})}
</View>
{activeTab === "recent" ? (
<ScrollView
style={styles.screen}
contentContainerStyle={styles.scrollContent}
showsVerticalScrollIndicator={false}
>
<View style={styles.toolbarRow}>
<TextInput
value={searchQuery}
onChangeText={setSearchQuery}
placeholder="搜索标题或内容"
placeholderTextColor={palette.textSoft}
style={styles.searchInput}
/>
<View style={styles.modeSwitch}>
<MiniToggle
label="列表"
active={recentViewMode === "list"}
onPress={() => setRecentViewMode("list")}
palette={palette}
/>
<MiniToggle
label="窗口"
active={recentViewMode === "preview"}
onPress={() => setRecentViewMode("preview")}
palette={palette}
/>
</View>
</View>
{recentViewMode === "list" ? (
<View style={styles.listColumn}>
{filteredDocs.map((doc) => (
<Pressable
key={doc.id}
onPress={() => openDocument(doc)}
onLongPress={() => promptManageDocument(doc)}
style={[
styles.docRow,
selectedId === doc.id && styles.docRowSelected,
]}
>
<View style={styles.docMark}>
<Text style={styles.docMarkText}>MD</Text>
</View>
<View style={styles.docCopy}>
<Text style={styles.docTitle} numberOfLines={1}>
{doc.title}
</Text>
<Text style={styles.docExcerpt} numberOfLines={2}>
{doc.excerpt}
</Text>
</View>
<Text style={styles.docTime}>{formatTime(doc.updatedAt)}</Text>
</Pressable>
))}
</View>
) : (
<View style={styles.previewGrid}>
{filteredDocs.map((doc) => (
<Pressable
key={doc.id}
onPress={() => openDocument(doc)}
onLongPress={() => promptManageDocument(doc)}
style={[
styles.previewCard,
selectedId === doc.id && styles.previewCardSelected,
]}
>
<Text style={styles.previewCardTitle} numberOfLines={2}>
{doc.title}
</Text>
<Text style={styles.previewCardText} numberOfLines={5}>
{doc.excerpt}
</Text>
<Text style={styles.previewCardTime}>{formatTime(doc.updatedAt)}</Text>
</Pressable>
))}
</View>
)}
</ScrollView>
) : null}
{activeTab === "editor" ? (
<KeyboardAvoidingView
style={styles.screen}
behavior={Platform.OS === "ios" ? "padding" : "height"}
keyboardVerticalOffset={topInset + 18}
>
<ScrollView
contentContainerStyle={[
styles.scrollContent,
editorMode === "source" && { paddingBottom: keyboardHeight + 28 },
]}
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="handled"
>
{selectedDoc ? (
<>
<View style={styles.docHeader}>
<View style={styles.docHeaderCopy}>
<Text style={styles.editorTitle}>{selectedDoc.title}</Text>
<Text style={styles.editorMeta}>
最后修改 {formatTime(selectedDoc.updatedAt)} · {selectedDoc.storageUri ? "本地已保存" : "示例文档"}
</Text>
</View>
<View style={styles.docHeaderActions}>
<MiniToggle
label="正文"
active={editorMode === "rendered"}
onPress={() => setEditorMode("rendered")}
palette={palette}
/>
<MiniToggle
label="源码"
active={editorMode === "source"}
onPress={() => setEditorMode("source")}
palette={palette}
/>
</View>
</View>
<View style={styles.formatRow}>
{([
["H1", "h1"],
["引用", "quote"],
["清单", "ul"],
["任务", "task"],
["代码", "code"],
["加粗", "bold"],
] as const).map(([label, kind]) => (
<Pressable
key={kind}
onPress={() => {
setEditorMode("source");
applyFormatting(kind);
}}
style={styles.formatButton}
>
<Text style={styles.formatButtonText}>{label}</Text>
</Pressable>
))}
</View>
<View style={styles.editorSurface}>
{editorMode === "rendered" ? (
<SimpleMarkdown
content={draftContent}
color={palette.text}
muted={palette.textSoft}
border={palette.border}
accent={palette.primary}
panel={palette.backgroundSoft}
/>
) : (
<TextInput
multiline
value={draftContent}
onChangeText={setDraftContent}
onSelectionChange={handleSelectionChange}
selection={selection}
style={styles.editorInput}
placeholder="开始写 Markdown…"
placeholderTextColor={palette.textSoft}
textAlignVertical="top"
/>
)}
</View>
<View style={styles.footerActions}>
<ActionButton label="保存" onPress={saveDocument} palette={palette} primary />
<ActionButton
label={exportOpen ? "收起导出" : "导出"}
onPress={() => setExportOpen((current) => !current)}
palette={palette}
/>
</View>
{exportOpen ? (
<View style={styles.exportCard}>
<Text style={styles.exportTitle}>导出文件</Text>
<TextInput
value={exportName}
onChangeText={setExportName}
placeholder="输入文件名"
placeholderTextColor={palette.textSoft}
style={styles.exportInput}
/>
<View style={styles.exportFormatRow}>
<MiniToggle
label="MD"
active={exportFormat === "md"}
onPress={() => setExportFormat("md")}
palette={palette}
/>
<MiniToggle
label="PDF"
active={exportFormat === "pdf"}
onPress={() => setExportFormat("pdf")}
palette={palette}
/>
</View>
<View style={styles.exportActions}>
<ActionButton label="取消" onPress={() => setExportOpen(false)} palette={palette} />
<ActionButton label="确认导出" onPress={exportDocument} palette={palette} primary />
</View>
</View>
) : null}
</>
) : (
<EmptyState
title="还没有打开文档"
body="先导入一个 Markdown 文件,或者新建一个空白文档。"
palette={palette}
/>
)}
</ScrollView>
</KeyboardAvoidingView>
) : null}
{activeTab === "reader" ? (
<ScrollView
style={styles.screen}
contentContainerStyle={styles.scrollContent}
showsVerticalScrollIndicator={false}
>
{selectedDoc ? (
<>
<View style={styles.readerSurface}>
<View style={styles.readerHeader}>
<Text style={styles.readerTitle}>{stripExtension(selectedDoc.title)}</Text>
<Text style={styles.readerMetaTitle}>{selectedDoc.title}</Text>
</View>
<SimpleMarkdown
content={readerContent}
color={palette.text}
muted={palette.textSoft}
border={palette.border}
accent={palette.primary}
panel={palette.backgroundSoft}
/>
</View>
</>
) : (
<EmptyState
title="没有可阅读的文档"
body="先在最近文件里选中一份文档。"
palette={palette}
/>
)}
</ScrollView>
) : null}
{activeTab === "settings" ? (
<ScrollView
style={styles.screen}
contentContainerStyle={styles.scrollContent}
showsVerticalScrollIndicator={false}
>
<View style={styles.settingsCard}>
<Text style={styles.settingsTitle}>主题模式</Text>
<View style={styles.themeGrid}>
{([
["light", "浅色", "白天整理与快速浏览"],
["dark", "夜间", "深底浅字,适合长时间阅读"],
["sepia", "Sepia", "更接近纸感的暖色底"],
] as const).map(([mode, label, body]) => {
const active = themeMode === mode;
return (
<Pressable
key={mode}
onPress={() => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setThemeMode(mode);
}}
style={[styles.themeCard, active && styles.themeCardActive]}
>
<Text style={[styles.themeCardTitle, active && styles.themeCardTitleActive]}>
{label}
</Text>
<Text style={[styles.themeCardText, active && styles.themeCardTextActive]}>{body}</Text>
</Pressable>
);
})}
</View>
</View>
<View style={styles.settingsCard}>
<Text style={styles.settingsTitle}>更新日志</Text>
<Text style={styles.versionText}>TinyMD {APP_VERSION}</Text>
<View style={styles.changelogList}>
{CHANGELOG_ITEMS.map((item) => (
<View key={item} style={styles.changelogItem}>
<Text style={styles.changelogBullet}>•</Text>
<Text style={styles.changelogText}>{item}</Text>
</View>
))}
</View>
</View>
<Pressable
style={styles.projectFooter}
onPress={() => Linking.openURL(PROJECT_URL).catch(() => undefined)}
>
<Image
source={{ uri: GITHUB_MARK_URL }}
style={styles.projectFooterIcon}
/>
<Text style={styles.projectFooterText}>Made by TTZW1001</Text>
</Pressable>
</ScrollView>
) : null}
<Modal
transparent
visible={manageOpen}
animationType="fade"
onRequestClose={() => setManageOpen(false)}
>
<View style={styles.modalScrim}>
<View style={styles.actionSheetCard}>
<Text style={styles.modalTitle}>{manageDocTitle}</Text>
<Text style={styles.modalSubtitle}>选择操作</Text>
<View style={styles.actionSheetActions}>
<Pressable
style={[styles.actionSheetButton, styles.actionSheetButtonPrimary]}
onPress={() => {
setRenameValue(stripExtension(manageDocTitle));
setManageOpen(false);
setRenameOpen(true);
}}
>
<Text style={styles.actionSheetButtonPrimaryText}>重命名</Text>
</Pressable>
<Pressable
style={styles.actionSheetButton}
onPress={() => deleteDocument(manageDocId)}
>
<Text style={styles.actionSheetButtonDangerText}>删除</Text>
</Pressable>
<Pressable
style={styles.actionSheetButton}
onPress={() => setManageOpen(false)}
>