initial commit: MD Editor with Tauri + React

This commit is contained in:
2026-06-18 21:46:20 +08:00
commit e05550f631
142 changed files with 39602 additions and 0 deletions

50
src/App.css Normal file
View File

@@ -0,0 +1,50 @@
.app {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.main-area {
display: flex;
flex: 1;
overflow: hidden;
min-height: 0;
}
.pane {
display: flex;
flex-direction: column;
overflow: hidden;
min-width: 0;
}
.pane.full {
flex: 1;
}
.pane.split {
flex: 1;
min-width: 0;
}
.split-divider {
width: 1px;
background: var(--divider);
flex-shrink: 0;
cursor: col-resize;
}
.editor-pane {
background: #1e1e1e;
}
.preview-pane {
background: #0d1117;
}
.pane-loading {
flex: 1;
width: 100%;
height: 100%;
}

135
src/App.tsx Normal file
View File

@@ -0,0 +1,135 @@
import { useState, useEffect, useMemo, lazy, Suspense } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { invoke } from "@tauri-apps/api/core";
import { ask } from "@tauri-apps/plugin-dialog";
import Toolbar, { ViewMode } from "./components/Toolbar";
import StatusBar from "./components/StatusBar";
import { useFile } from "./hooks/useFile";
import "./App.css";
const Editor = lazy(() => import("./components/Editor"));
const Preview = lazy(() => import("./components/Preview"));
const isMobile = () => window.innerWidth <= 768;
export default function App() {
const [viewMode, setViewMode] = useState<ViewMode>(isMobile() ? "preview" : "split");
const [_scrollRatio] = useState<number | null>(null);
const { fileState, setContent, newFile, openFile, saveFile, saveFileAs } = useFile();
// Receive file path at startup: Android intent (JavascriptInterface) or desktop CLI arg.
// Falls back to last opened file when no explicit path is provided.
useEffect(() => {
const androidOpener = (window as unknown as Record<string, unknown>).__FileOpener__ as
| { getPendingFile: () => string | null }
| undefined;
if (androidOpener) {
const uri = androidOpener.getPendingFile();
if (uri) { openFile(uri); return; }
}
const restoreLastFile = () => {
const last = localStorage.getItem("md-editor-last-file");
if (last) openFile(last);
};
invoke<string | null>("get_open_file_path").then((path) => {
if (path) openFile(path);
else restoreLastFile();
}).catch(restoreLastFile);
}, []);
// Intercept all close events (toolbar button, Alt+F4, taskbar) to check unsaved state
useEffect(() => {
const appWindow = getCurrentWindow();
const unlisten = appWindow.onCloseRequested(async (event) => {
event.preventDefault();
if (fileState.saved) {
await appWindow.destroy();
return;
}
const confirmed = await ask(
"当前文件有未保存的修改,确定要退出吗?",
{ title: "退出确认", kind: "warning" }
);
if (confirmed) await appWindow.destroy();
});
return () => { unlisten.then((fn) => fn()); };
}, [fileState.saved]);
// Listen for new file-open events while app is running
useEffect(() => {
const appWindow = getCurrentWindow();
const unlisten = appWindow.listen<string>("open-file", (event) => {
openFile(event.payload);
});
return () => { unlisten.then((fn) => fn()); };
}, [openFile]);
// Keyboard shortcuts
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.ctrlKey && !e.shiftKey && e.key === "n") { e.preventDefault(); newFile(); }
if (e.ctrlKey && !e.shiftKey && e.key === "o") { e.preventDefault(); openFile(); }
if (e.ctrlKey && !e.shiftKey && e.key === "s") { e.preventDefault(); saveFile(); }
if (e.ctrlKey && e.shiftKey && e.key === "S") { e.preventDefault(); saveFileAs(); }
if (e.ctrlKey && e.key === "p") {
e.preventDefault();
setViewMode((m) => m === "preview" ? "split" : "preview");
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [newFile, openFile, saveFile, saveFileAs]);
const stats = useMemo(() => {
const content = fileState.content;
return {
chars: content.length,
lines: content.split("\n").length,
words: content.trim() === "" ? 0 : content.trim().split(/\s+/).length,
};
}, [fileState.content]);
return (
<div className="app">
<Toolbar
fileName={fileState.name}
saved={fileState.saved}
viewMode={viewMode}
onViewModeChange={setViewMode}
onNew={newFile}
onOpen={() => openFile()}
onSave={saveFile}
onSaveAs={saveFileAs}
/>
<div className="main-area">
{(viewMode === "edit" || viewMode === "split") && (
<div className={`pane editor-pane ${viewMode === "split" ? "split" : "full"}`}>
<Suspense fallback={<div className="pane-loading" />}>
<Editor content={fileState.content} onChange={setContent} />
</Suspense>
</div>
)}
{viewMode === "split" && <div className="split-divider" />}
{(viewMode === "preview" || viewMode === "split") && (
<div className={`pane preview-pane ${viewMode === "split" ? "split" : "full"}`}>
<Suspense fallback={<div className="pane-loading" />}>
<Preview content={fileState.content} syncScrollFrom={_scrollRatio} />
</Suspense>
</div>
)}
</div>
<StatusBar
charCount={stats.chars}
lineCount={stats.lines}
wordCount={stats.words}
filePath={fileState.path}
/>
</div>
);
}

29
src/components/Editor.css Normal file
View File

@@ -0,0 +1,29 @@
.editor-wrapper {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
height: 100%;
font-family: var(--font-ui);
}
.editor-container {
flex: 1;
height: 100%;
overflow: hidden;
}
.editor-container .cm-editor {
height: 100%;
}
.editor-container .cm-scroller,
.editor-container .cm-content,
.editor-container .cm-line {
font-family: var(--font-ui);
}
.editor-container .cm-tooltip,
.editor-container .cm-panel {
font-family: var(--font-ui);
}

161
src/components/Editor.tsx Normal file
View File

@@ -0,0 +1,161 @@
import { useEffect, useRef } from "react";
import {
EditorView, keymap, lineNumbers,
highlightActiveLine, highlightActiveLineGutter, drawSelection,
} from "@codemirror/view";
import { EditorState, Compartment } from "@codemirror/state";
import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";
import { syntaxHighlighting, defaultHighlightStyle, bracketMatching } from "@codemirror/language";
import { searchKeymap } from "@codemirror/search";
import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
import { useTheme } from "../context/ThemeContext";
import "./Editor.css";
interface EditorProps {
content: string;
onChange: (value: string) => void;
}
const UI_FONT = "var(--font-ui)";
const CODE_FONT = "var(--font-code)";
const darkTheme = EditorView.theme(
{
"&": {
height: "100%",
fontSize: "15px",
fontFamily: UI_FONT,
background: "#1e1e1e",
color: "#d4d4d4",
},
".cm-scroller": { overflow: "auto", lineHeight: "1.8", fontFamily: UI_FONT },
".cm-content": { padding: "16px", caretColor: "#aeafad", minHeight: "100%", fontFamily: UI_FONT },
".cm-line": { fontFamily: UI_FONT, padding: "0 4px" },
".cm-cursor": { borderLeftColor: "#aeafad" },
".cm-gutters": {
background: "#1e1e1e",
color: "#6e6e6e",
border: "none",
borderRight: "1px solid #3e3e42",
paddingRight: "8px",
fontFamily: CODE_FONT,
fontSize: "13px",
},
".cm-activeLineGutter": { background: "#2a2d2e", color: "#d4d4d4" },
".cm-activeLine": { background: "#2a2d2e" },
".cm-selectionBackground, ::selection": { background: "#264f78 !important" },
".cm-focused .cm-selectionBackground": { background: "#264f78" },
".cm-matchingBracket": { background: "#3b514d", outline: "1px solid #888" },
"&.cm-focused": { outline: "none" },
// 代码块内用等宽字体
".ͼ1 .tok-monospace, .cm-content code": { fontFamily: CODE_FONT },
},
{ dark: true }
);
const lightTheme = EditorView.theme(
{
"&": {
height: "100%",
fontSize: "15px",
fontFamily: UI_FONT,
background: "#ffffff",
color: "#1f1f1f",
},
".cm-scroller": { overflow: "auto", lineHeight: "1.8", fontFamily: UI_FONT },
".cm-content": { padding: "16px", caretColor: "#333", minHeight: "100%", fontFamily: UI_FONT },
".cm-line": { fontFamily: UI_FONT, padding: "0 4px" },
".cm-cursor": { borderLeftColor: "#333" },
".cm-gutters": {
background: "#f8f8f8",
color: "#aaaaaa",
border: "none",
borderRight: "1px solid #e0e0e0",
paddingRight: "8px",
fontFamily: CODE_FONT,
fontSize: "13px",
},
".cm-activeLineGutter": { background: "#eff1f7", color: "#333" },
".cm-activeLine": { background: "#eff1f7" },
".cm-selectionBackground, ::selection": { background: "#b5d5fb !important" },
".cm-focused .cm-selectionBackground": { background: "#b5d5fb" },
".cm-matchingBracket": { background: "#d8f0d8", outline: "1px solid #aaa" },
"&.cm-focused": { outline: "none" },
".ͼ1 .tok-monospace, .cm-content code": { fontFamily: CODE_FONT },
},
{ dark: false }
);
const themeCompartment = new Compartment();
export default function Editor({ content, onChange }: EditorProps) {
const { theme } = useTheme();
const containerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
useEffect(() => {
if (!containerRef.current) return;
const view = new EditorView({
state: EditorState.create({
doc: content,
extensions: [
lineNumbers(),
highlightActiveLine(),
highlightActiveLineGutter(),
drawSelection(),
bracketMatching(),
history(),
autocompletion(),
markdown({ base: markdownLanguage, codeLanguages: languages }),
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
keymap.of([
...defaultKeymap,
...historyKeymap,
...searchKeymap,
...completionKeymap,
indentWithTab,
]),
themeCompartment.of(darkTheme),
EditorView.updateListener.of((update) => {
if (update.docChanged) onChange(update.state.doc.toString());
}),
EditorView.lineWrapping,
],
}),
parent: containerRef.current,
});
viewRef.current = view;
return () => { view.destroy(); };
}, []);
// 动态切换编辑器主题
useEffect(() => {
const view = viewRef.current;
if (!view) return;
view.dispatch({
effects: themeCompartment.reconfigure(theme === "dark" ? darkTheme : lightTheme),
});
}, [theme]);
// 同步外部内容(打开文件等)
useEffect(() => {
const view = viewRef.current;
if (!view) return;
const currentDoc = view.state.doc.toString();
if (currentDoc !== content) {
view.dispatch({
changes: { from: 0, to: currentDoc.length, insert: content },
});
}
}, [content]);
return (
<div className="editor-wrapper">
<div ref={containerRef} className="editor-container" />
</div>
);
}

128
src/components/Preview.css Normal file
View File

@@ -0,0 +1,128 @@
.preview-wrapper {
flex: 1;
height: 100%;
overflow-y: auto;
transition: background 0.2s;
user-select: text;
}
[data-theme="dark"] .preview-wrapper,
.preview-wrapper[data-theme="dark"] {
background: #0d1117;
}
[data-theme="light"] .preview-wrapper,
.preview-wrapper[data-theme="light"] {
background: #ffffff;
}
.preview-content {
max-width: 860px;
margin: 0 auto;
padding: 32px 40px;
box-sizing: border-box;
font-family: var(--font-ui);
}
/* ─── 深色模式覆盖 ────────────────────────────────── */
.markdown-body[data-color-mode="dark"] {
background-color: transparent !important;
color: #e6edf3;
}
.markdown-body[data-color-mode="dark"] pre {
background-color: #161b22 !important;
}
.markdown-body[data-color-mode="dark"] code:not(pre code) {
background-color: rgba(110, 118, 129, 0.2) !important;
color: #e6edf3;
}
.markdown-body[data-color-mode="dark"] blockquote {
border-left-color: #30363d;
color: #8b949e;
}
.markdown-body[data-color-mode="dark"] table tr {
border-top-color: #30363d;
background-color: transparent;
}
.markdown-body[data-color-mode="dark"] table tr:nth-child(2n) {
background-color: rgba(255, 255, 255, 0.03);
}
.markdown-body[data-color-mode="dark"] table td,
.markdown-body[data-color-mode="dark"] table th {
border-color: #30363d;
}
.markdown-body[data-color-mode="dark"] hr {
border-color: #21262d;
}
.markdown-body[data-color-mode="dark"] h1,
.markdown-body[data-color-mode="dark"] h2 {
border-bottom-color: #21262d;
}
.markdown-body[data-color-mode="dark"] a {
color: #58a6ff;
}
/* ─── 深色模式 highlight.js 覆盖 ─────────────────── */
.markdown-body[data-color-mode="dark"] .hljs {
background: #161b22;
color: #c9d1d9;
}
.markdown-body[data-color-mode="dark"] .hljs-keyword,
.markdown-body[data-color-mode="dark"] .hljs-selector-tag { color: #ff7b72; }
.markdown-body[data-color-mode="dark"] .hljs-string,
.markdown-body[data-color-mode="dark"] .hljs-attr { color: #a5d6ff; }
.markdown-body[data-color-mode="dark"] .hljs-comment { color: #8b949e; }
.markdown-body[data-color-mode="dark"] .hljs-number,
.markdown-body[data-color-mode="dark"] .hljs-literal { color: #79c0ff; }
.markdown-body[data-color-mode="dark"] .hljs-title,
.markdown-body[data-color-mode="dark"] .hljs-function { color: #d2a8ff; }
.markdown-body[data-color-mode="dark"] .hljs-type,
.markdown-body[data-color-mode="dark"] .hljs-built_in { color: #ffa657; }
/* ─── 浅色模式 ────────────────────────────────────── */
.markdown-body[data-color-mode="light"] {
background-color: transparent !important;
color: #1f2328;
}
/* ─── 统一选中高亮颜色 ───────────────────────────── */
.preview-wrapper *::selection {
background: #3390ff;
color: #ffffff;
}
[data-theme="dark"] .preview-wrapper *::selection,
.preview-wrapper[data-theme="dark"] *::selection {
background: #264f78;
color: #e6edf3;
}
/* ─── 通用字体覆盖 ───────────────────────────────── */
.markdown-body {
font-family: var(--font-ui) !important;
}
.markdown-body code,
.markdown-body pre,
.markdown-body pre code,
.markdown-body .hljs,
.markdown-body tt,
.markdown-body kbd,
.markdown-body samp {
font-family: var(--font-code) !important;
}

View File

@@ -0,0 +1,33 @@
import { useEffect, useRef, useMemo } from "react";
import { renderMarkdown } from "../lib/markdown";
import { useTheme } from "../context/ThemeContext";
import "github-markdown-css/github-markdown.css";
import "highlight.js/styles/github.css";
import "./Preview.css";
interface PreviewProps {
content: string;
syncScrollFrom?: number | null;
}
export default function Preview({ content, syncScrollFrom }: PreviewProps) {
const { theme } = useTheme();
const containerRef = useRef<HTMLDivElement>(null);
const html = useMemo(() => renderMarkdown(content), [content]);
useEffect(() => {
if (syncScrollFrom == null || !containerRef.current) return;
const el = containerRef.current;
el.scrollTop = syncScrollFrom * (el.scrollHeight - el.clientHeight);
}, [syncScrollFrom]);
return (
<div className="preview-wrapper" ref={containerRef} data-theme={theme}>
<div
className="markdown-body preview-content"
data-color-mode={theme}
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
);
}

View File

@@ -0,0 +1,40 @@
.statusbar {
display: flex;
align-items: center;
justify-content: space-between;
height: 24px;
background: var(--bg-statusbar);
padding: 0 12px;
flex-shrink: 0;
font-size: 11px;
color: rgba(255, 255, 255, 0.9);
font-family: var(--font-ui);
}
.sb-right {
display: flex;
align-items: center;
gap: 16px;
}
.sb-item {
white-space: nowrap;
}
.sb-path {
overflow: hidden;
text-overflow: ellipsis;
max-width: 400px;
}
.sb-badge {
background: rgba(255, 255, 255, 0.18);
padding: 1px 7px;
border-radius: 3px;
}
@media (max-width: 768px) {
.statusbar {
display: none;
}
}

View File

@@ -0,0 +1,22 @@
import "./StatusBar.css";
interface StatusBarProps {
charCount: number;
lineCount: number;
wordCount: number;
filePath: string | null;
}
export default function StatusBar({ charCount, lineCount, wordCount, filePath }: StatusBarProps) {
return (
<div className="statusbar">
<span className="sb-item sb-path">{filePath ?? "未命名"}</span>
<div className="sb-right">
<span className="sb-item">{lineCount}</span>
<span className="sb-item">{wordCount}</span>
<span className="sb-item">{charCount}</span>
<span className="sb-item sb-badge">Markdown</span>
</div>
</div>
);
}

281
src/components/Toolbar.css Normal file
View File

@@ -0,0 +1,281 @@
.toolbar {
display: flex;
align-items: center;
height: 40px;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-color);
padding: 0 8px;
gap: 8px;
flex-shrink: 0;
transition: background 0.2s, border-color 0.2s;
-webkit-app-region: drag;
}
.toolbar-left,
.toolbar-right {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
position: relative;
z-index: 2;
-webkit-app-region: no-drag;
}
.toolbar-center {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
min-width: 0;
overflow: hidden;
}
.app-logo {
display: flex;
align-items: center;
padding: 0 4px;
}
.toolbar-group {
display: flex;
align-items: center;
gap: 1px;
padding-left: 6px;
border-left: 1px solid var(--border-color);
}
.tb-btn {
display: flex;
align-items: center;
gap: 4px;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
color: var(--text-secondary);
transition: background 0.15s, color 0.15s;
white-space: nowrap;
-webkit-app-region: no-drag;
}
.tb-btn:hover {
background: var(--dropdown-item-hover);
color: var(--text-primary);
}
.tb-icon-btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 5px;
color: var(--text-secondary);
transition: background 0.15s, color 0.15s;
-webkit-app-region: no-drag;
}
.tb-icon-btn:hover,
.tb-icon-btn.active {
background: var(--dropdown-item-hover);
color: var(--text-primary);
}
.file-name {
font-size: 13px;
color: var(--text-secondary);
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 12px;
-webkit-app-region: drag;
cursor: default;
}
.file-name.unsaved {
color: var(--accent);
}
/* ─── 视图切换 ───────────────────────────────────── */
.view-toggle {
display: flex;
align-items: center;
background: var(--view-btn-bg);
border-radius: 6px;
padding: 2px;
gap: 1px;
-webkit-app-region: no-drag;
}
.view-btn {
display: flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border-radius: 4px;
font-size: 12px;
color: var(--text-muted);
transition: background 0.15s, color 0.15s;
-webkit-app-region: no-drag;
}
.view-btn:hover {
color: var(--text-secondary);
background: var(--dropdown-item-hover);
}
.view-btn.active {
background: var(--accent);
color: #fff;
}
/* ─── 更多菜单 ────────────────────────────────────── */
.more-menu-wrap {
position: relative;
z-index: 3;
-webkit-app-region: no-drag;
}
.dropdown-menu {
position: absolute;
top: calc(100% + 6px);
right: 0;
min-width: 200px;
background: var(--bg-dropdown);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 4px;
box-shadow: var(--dropdown-shadow);
z-index: 1000;
animation: dropdownFadeIn 0.1s ease;
}
@keyframes dropdownFadeIn {
from { opacity: 0; transform: translateY(-4px); }
to { opacity: 1; transform: translateY(0); }
}
.dropdown-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 7px 10px;
border-radius: 5px;
font-size: 13px;
color: var(--text-primary);
text-align: left;
transition: background 0.1s;
-webkit-app-region: no-drag;
}
.dropdown-item:hover {
background: var(--dropdown-item-hover);
}
.dropdown-shortcut {
margin-left: auto;
font-size: 11px;
color: var(--text-muted);
font-family: var(--font-ui);
}
.dropdown-separator {
height: 1px;
background: var(--border-color);
margin: 4px 6px;
}
.dropdown-version {
padding: 5px 10px;
font-size: 11px;
color: var(--text-muted);
text-align: center;
}
/* ─── 窗口控制 ────────────────────────────────────── */
.window-controls {
display: flex;
align-items: center;
gap: 2px;
margin-left: 6px;
-webkit-app-region: no-drag;
}
.wc-btn {
width: 12px;
height: 12px;
padding: 6px;
border-radius: 50%;
border: none;
cursor: pointer;
background-clip: content-box;
box-sizing: content-box;
transition: filter 0.15s, transform 0.1s;
-webkit-app-region: no-drag;
flex-shrink: 0;
}
.wc-btn:hover {
filter: brightness(1.25);
transform: scale(1.1);
}
.wc-btn:active {
transform: scale(0.95);
}
.wc-btn.minimize { background: #f5a623; }
.wc-btn.maximize { background: #27c93f; }
.wc-btn.close { background: #ff5f57; }
/* ─── 手机响应式 ─────────────────────────────────── */
@media (max-width: 768px) {
.toolbar {
height: 48px;
padding: 0 6px;
gap: 4px;
-webkit-app-region: unset;
}
/* 隐藏 macOS 风格窗口控制按钮 */
.window-controls {
display: none;
}
/* 隐藏分屏按钮(手机屏太窄) */
.view-btn-split {
display: none;
}
/* 隐藏按钮文字标签,只保留图标 */
.tb-btn span,
.view-btn-label {
display: none;
}
/* 隐藏新建 / 保存 / 另存为,只保留打开(⋮ 菜单已包含全部操作) */
.tb-btn-new,
.tb-btn-save,
.tb-btn-saveas {
display: none;
}
/* 加大触摸目标高度 */
.tb-btn,
.view-btn,
.tb-icon-btn {
min-height: 40px;
padding: 8px 10px;
}
.file-name {
font-size: 12px;
padding: 0 6px;
}
.view-toggle {
padding: 3px;
}
}

250
src/components/Toolbar.tsx Normal file
View File

@@ -0,0 +1,250 @@
import { useRef, useState, useEffect } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { invoke } from "@tauri-apps/api/core";
import { useTheme } from "../context/ThemeContext";
import "./Toolbar.css";
export type ViewMode = "edit" | "split" | "preview";
interface ToolbarProps {
fileName: string;
saved: boolean;
viewMode: ViewMode;
onViewModeChange: (mode: ViewMode) => void;
onNew: () => void;
onOpen: () => void;
onSave: () => void;
onSaveAs: () => void;
}
export default function Toolbar({
fileName,
saved,
viewMode,
onViewModeChange,
onNew,
onOpen,
onSave,
onSaveAs,
}: ToolbarProps) {
const { theme, toggleTheme } = useTheme();
const [menuOpen, setMenuOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!menuOpen) return;
const handleClick = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
setMenuOpen(false);
}
};
const timer = window.setTimeout(() => {
document.addEventListener("click", handleClick);
}, 0);
return () => {
window.clearTimeout(timer);
document.removeEventListener("click", handleClick);
};
}, [menuOpen]);
const handleMenuAction = (action: () => void) => {
setMenuOpen(false);
action();
};
const runWindowAction = (action: () => Promise<void>) => {
action().catch((err) => console.error("窗口操作失败:", err));
};
return (
<div className="toolbar" data-tauri-drag-region>
{/* 左区 — 无 data-tauri-drag-region依靠 CSS no-drag 覆盖 */}
<div className="toolbar-left">
<div className="app-logo">
<img src="/logo.svg" alt="MD Editor" width={18} height={18} />
</div>
<div className="toolbar-group">
<button type="button" className="tb-btn tb-btn-new" onClick={onNew} title="新建 (Ctrl+N)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14,2 14,8 20,8" />
<line x1="12" y1="18" x2="12" y2="12" /><line x1="9" y1="15" x2="15" y2="15" />
</svg>
<span></span>
</button>
<button className="tb-btn" onClick={onOpen} title="打开 (Ctrl+O)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
</svg>
<span></span>
</button>
<button className="tb-btn tb-btn-save" onClick={onSave} title="保存 (Ctrl+S)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
<polyline points="17,21 17,13 7,13 7,21" /><polyline points="7,3 7,8 15,8" />
</svg>
<span></span>
</button>
<button className="tb-btn tb-btn-saveas" onClick={onSaveAs} title="另存为 (Ctrl+Shift+S)">
<span></span>
</button>
</div>
</div>
<div className="toolbar-center">
<span
className={`file-name ${saved ? "" : "unsaved"}`}
data-tauri-drag-region
>
{saved ? "" : "● "}{fileName}
</span>
</div>
<div className="toolbar-right">
<div className="view-toggle">
<button className={`view-btn ${viewMode === "edit" ? "active" : ""}`} onClick={() => onViewModeChange("edit")} title="仅编辑">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<polyline points="16,18 22,12 16,6" /><polyline points="8,6 2,12 8,18" />
</svg>
<span className="view-btn-label"></span>
</button>
<button className={`view-btn view-btn-split ${viewMode === "split" ? "active" : ""}`} onClick={() => onViewModeChange("split")} title="分屏视图">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="3" y="3" width="18" height="18" rx="2" /><line x1="12" y1="3" x2="12" y2="21" />
</svg>
<span className="view-btn-label"></span>
</button>
<button className={`view-btn ${viewMode === "preview" ? "active" : ""}`} onClick={() => onViewModeChange("preview")} title="仅预览">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" />
</svg>
<span className="view-btn-label"></span>
</button>
</div>
{/* 三点更多菜单 */}
<div className="more-menu-wrap" ref={menuRef}>
<button
type="button"
className={`tb-icon-btn ${menuOpen ? "active" : ""}`}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setMenuOpen((v) => !v);
}}
title="更多选项"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<circle cx="12" cy="5" r="2" />
<circle cx="12" cy="12" r="2" />
<circle cx="12" cy="19" r="2" />
</svg>
</button>
{menuOpen && (
<div className="dropdown-menu">
<button className="dropdown-item" onClick={() => handleMenuAction(toggleTheme)}>
{theme === "dark" ? (
<>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
</>
) : (
<>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
</>
)}
</button>
<div className="dropdown-separator" />
<button className="dropdown-item" onClick={() => handleMenuAction(onNew)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14,2 14,8 20,8" />
</svg>
<span className="dropdown-shortcut">Ctrl+N</span>
</button>
<button className="dropdown-item" onClick={() => handleMenuAction(onOpen)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
</svg>
<span className="dropdown-shortcut">Ctrl+O</span>
</button>
<button className="dropdown-item" onClick={() => handleMenuAction(onSave)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
<polyline points="17,21 17,13 7,13 7,21" /><polyline points="7,3 7,8 15,8" />
</svg>
<span className="dropdown-shortcut">Ctrl+S</span>
</button>
<button className="dropdown-item" onClick={() => handleMenuAction(onSaveAs)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
<polyline points="17,21 17,13 7,13 7,21" /><polyline points="7,3 7,8 15,8" />
</svg>
<span className="dropdown-shortcut">Ctrl+Shift+S</span>
</button>
<div className="dropdown-separator" />
<button
className="dropdown-item"
onClick={() =>
handleMenuAction(() => {
invoke<string>("register_file_associations")
.then((msg) => alert(msg))
.catch((e) => alert("注册失败: " + e));
})
}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14,2 14,8 20,8" />
<line x1="12" y1="18" x2="12" y2="12" /><line x1="9" y1="15" x2="15" y2="15" />
</svg>
</button>
<div className="dropdown-separator" />
<div className="dropdown-version">MD v0.1.0</div>
</div>
)}
</div>
<div className="window-controls">
<button
type="button"
className="wc-btn minimize"
onMouseDown={(e) => e.stopPropagation()}
onClick={() => runWindowAction(() => getCurrentWindow().minimize())}
title="最小化"
/>
<button
type="button"
className="wc-btn maximize"
onMouseDown={(e) => e.stopPropagation()}
onClick={() => runWindowAction(() => getCurrentWindow().toggleMaximize())}
title="最大化"
/>
<button
type="button"
className="wc-btn close"
onMouseDown={(e) => e.stopPropagation()}
onClick={() => runWindowAction(() => getCurrentWindow().close())}
title="关闭"
/>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,34 @@
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
export type Theme = "dark" | "light";
interface ThemeContextValue {
theme: Theme;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue>({
theme: "dark",
toggleTheme: () => {},
});
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>(() => {
return (localStorage.getItem("md-editor-theme") as Theme) ?? "dark";
});
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("md-editor-theme", theme);
}, [theme]);
const toggleTheme = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);

227
src/hooks/useFile.ts Normal file
View File

@@ -0,0 +1,227 @@
import { useState, useCallback, useRef, useEffect } from "react";
import { open, save, ask } from "@tauri-apps/plugin-dialog";
import { invoke } from "@tauri-apps/api/core";
import { readTextFile as pluginReadFile, watch } from "@tauri-apps/plugin-fs";
import { getCurrentWindow } from "@tauri-apps/api/window";
const readTextFile = (path: string): Promise<string> =>
path.startsWith("content://")
? pluginReadFile(path)
: invoke<string>("read_text_file", { path });
const writeTextFile = (path: string, content: string) => invoke<void>("write_text_file", { path, content });
const LAST_FILE_KEY = "md-editor-last-file";
export interface FileState {
path: string | null;
content: string;
saved: boolean;
name: string;
}
const DEFAULT_CONTENT = `# 欢迎使用 MD 编辑器
一款轻量级 Markdown 编辑器,支持 GitHub 风格预览。
## 功能特性
- **分屏视图** — 左侧编辑,右侧实时预览
- **GitHub 风格** Markdown 渲染,思源宋体排版
- **代码高亮** 支持多种编程语言
- **明暗模式** 点击右上角 ⋮ 切换主题
- **文件操作** — 打开、保存、另存为
## 快捷键
| 操作 | 快捷键 |
|------|--------|
| 新建文件 | \`Ctrl+N\` |
| 打开文件 | \`Ctrl+O\` |
| 保存 | \`Ctrl+S\` |
| 另存为 | \`Ctrl+Shift+S\` |
| 切换预览 | \`Ctrl+P\` |
## 代码示例
\`\`\`typescript
function greet(name: string): string {
return \`你好,\${name}\`;
}
console.log(greet("世界"));
\`\`\`
> 开始编辑此文档,或打开一个 \`.md\` 文件以开始使用。
`;
export function useFile() {
const [fileState, setFileState] = useState<FileState>({
path: null,
content: DEFAULT_CONTENT,
saved: true,
name: "未命名.md",
});
// Refs to avoid stale closures in watcher callback
const fileStateRef = useRef(fileState);
const unwatchRef = useRef<(() => void) | null>(null);
// Suppress watcher events triggered by the app's own save
const isSavingRef = useRef(false);
useEffect(() => {
fileStateRef.current = fileState;
}, [fileState]);
// Cleanup watcher on unmount
useEffect(() => {
return () => { unwatchRef.current?.(); };
}, []);
const updateTitle = useCallback(async (name: string, saved: boolean) => {
const appWindow = getCurrentWindow();
await appWindow.setTitle(`${saved ? "" : "● "}${name} — MD 编辑器`);
}, []);
const startWatcher = useCallback(async (path: string) => {
if (path.startsWith("content://")) return;
unwatchRef.current?.();
unwatchRef.current = null;
try {
const unwatch = await watch(
path,
async () => {
if (isSavingRef.current) return;
const current = fileStateRef.current;
if (!current.path) return;
try {
const newContent = await readTextFile(current.path);
if (current.saved) {
setFileState((prev) => ({ ...prev, content: newContent, saved: true }));
} else {
const reload = await ask(
"文件已在外部被修改,是否重新加载?\n当前未保存的更改将会丢失。",
{ title: "文件已更改", kind: "warning" }
);
if (reload) {
const name = current.path.split(/[\\/]/).pop() ?? "未命名.md";
setFileState((prev) => ({ ...prev, content: newContent, saved: true, name }));
await updateTitle(name, true);
}
}
} catch (e) {
console.error("重新加载文件失败:", e);
}
},
{ delayMs: 300 }
);
unwatchRef.current = unwatch;
} catch (e) {
console.error("文件监听启动失败:", e);
}
}, [updateTitle]);
const setContent = useCallback(
(content: string) => {
setFileState((prev) => {
const newSaved = content === prev.content ? prev.saved : false;
if (!newSaved && prev.saved) updateTitle(prev.name, false);
return { ...prev, content, saved: newSaved };
});
},
[updateTitle]
);
const newFile = useCallback(() => {
unwatchRef.current?.();
unwatchRef.current = null;
setFileState({ path: null, content: "", saved: true, name: "未命名.md" });
updateTitle("未命名.md", true);
}, [updateTitle]);
const openFile = useCallback(
async (filePath?: string) => {
try {
let path = filePath;
if (!path) {
const selected = await open({
filters: [{ name: "Markdown 文件", extensions: ["md", "markdown", "txt"] }],
multiple: false,
});
if (!selected) return;
path = selected as string;
}
const content = await readTextFile(path);
const name = path.split(/[\\/]/).pop() ?? "未命名.md";
setFileState({ path, content, saved: true, name });
await updateTitle(name, true);
localStorage.setItem(LAST_FILE_KEY, path);
await startWatcher(path);
} catch (e) {
console.error("打开文件失败:", e);
if (filePath) localStorage.removeItem(LAST_FILE_KEY);
}
},
[updateTitle, startWatcher]
);
const saveFile = useCallback(async () => {
try {
let path = fileState.path;
if (!path) {
const selected = await save({
filters: [{ name: "Markdown 文件", extensions: ["md", "markdown"] }],
defaultPath: fileState.name,
});
if (!selected) return;
path = selected;
}
isSavingRef.current = true;
await writeTextFile(path, fileState.content);
// Give the watcher time to fire and be suppressed before clearing the flag
setTimeout(() => { isSavingRef.current = false; }, 500);
const name = path.split(/[\\/]/).pop() ?? "未命名.md";
setFileState((prev) => ({ ...prev, path, saved: true, name }));
await updateTitle(name, true);
localStorage.setItem(LAST_FILE_KEY, path);
// Watch the new path if saving for the first time
if (path !== fileStateRef.current.path) {
await startWatcher(path);
}
} catch (e) {
console.error("保存文件失败:", e);
isSavingRef.current = false;
}
}, [fileState, updateTitle, startWatcher]);
const saveFileAs = useCallback(async () => {
try {
const selected = await save({
filters: [{ name: "Markdown 文件", extensions: ["md", "markdown"] }],
defaultPath: fileState.name,
});
if (!selected) return;
isSavingRef.current = true;
await writeTextFile(selected, fileState.content);
setTimeout(() => { isSavingRef.current = false; }, 500);
const name = selected.split(/[\\/]/).pop() ?? "未命名.md";
setFileState((prev) => ({ ...prev, path: selected, saved: true, name }));
await updateTitle(name, true);
localStorage.setItem(LAST_FILE_KEY, selected);
await startWatcher(selected);
} catch (e) {
console.error("另存为失败:", e);
isSavingRef.current = false;
}
}, [fileState, updateTitle, startWatcher]);
return { fileState, setContent, newFile, openFile, saveFile, saveFileAs };
}

64
src/lib/markdown.ts Normal file
View File

@@ -0,0 +1,64 @@
import { Marked } from "marked";
import { markedHighlight } from "marked-highlight";
import hljs from "highlight.js/lib/core";
import javascript from "highlight.js/lib/languages/javascript";
import typescript from "highlight.js/lib/languages/typescript";
import python from "highlight.js/lib/languages/python";
import bash from "highlight.js/lib/languages/bash";
import css from "highlight.js/lib/languages/css";
import xml from "highlight.js/lib/languages/xml";
import json from "highlight.js/lib/languages/json";
import rust from "highlight.js/lib/languages/rust";
import go from "highlight.js/lib/languages/go";
import java from "highlight.js/lib/languages/java";
import cpp from "highlight.js/lib/languages/cpp";
import sql from "highlight.js/lib/languages/sql";
import yaml from "highlight.js/lib/languages/yaml";
import markdown from "highlight.js/lib/languages/markdown";
import plaintext from "highlight.js/lib/languages/plaintext";
hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("js", javascript);
hljs.registerLanguage("typescript", typescript);
hljs.registerLanguage("ts", typescript);
hljs.registerLanguage("python", python);
hljs.registerLanguage("py", python);
hljs.registerLanguage("bash", bash);
hljs.registerLanguage("sh", bash);
hljs.registerLanguage("shell", bash);
hljs.registerLanguage("css", css);
hljs.registerLanguage("html", xml);
hljs.registerLanguage("xml", xml);
hljs.registerLanguage("json", json);
hljs.registerLanguage("rust", rust);
hljs.registerLanguage("go", go);
hljs.registerLanguage("java", java);
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("sql", sql);
hljs.registerLanguage("yaml", yaml);
hljs.registerLanguage("yml", yaml);
hljs.registerLanguage("markdown", markdown);
hljs.registerLanguage("md", markdown);
hljs.registerLanguage("plaintext", plaintext);
hljs.registerLanguage("text", plaintext);
const marked = new Marked(
markedHighlight({
emptyLangClass: "hljs",
langPrefix: "hljs language-",
highlight(code, lang) {
const language = hljs.getLanguage(lang) ? lang : "plaintext";
return hljs.highlight(code, { language }).value;
},
})
);
marked.setOptions({
gfm: true,
breaks: true,
});
export function renderMarkdown(source: string): string {
return marked.parse(source) as string;
}

15
src/main.tsx Normal file
View File

@@ -0,0 +1,15 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "./context/ThemeContext";
import "./styles/fonts.css";
import "./styles/font-vars.css";
import "./styles/global.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</React.StrictMode>
);

15
src/styles/font-vars.css Normal file
View File

@@ -0,0 +1,15 @@
:root,
[data-theme="dark"],
[data-theme="light"] {
--font-ui: "Source Han Serif SC", "Noto Serif CJK SC", "STSong", "SimSun", serif;
--font-code: var(--font-ui);
--fontStack-sansSerif: var(--font-ui);
--fontStack-monospace: var(--font-ui);
}
/* github-markdown-css 在 .markdown-body 作用域内重新定义了这两个变量,
需要在同等级覆盖,否则 :root 定义会被其同名变量遮蔽 */
.markdown-body {
--fontStack-sansSerif: var(--font-ui);
--fontStack-monospace: var(--font-ui);
}

7
src/styles/fonts.css Normal file
View File

@@ -0,0 +1,7 @@
@font-face {
font-family: "Source Han Serif SC";
src: url("/fonts/SourceHanSerifSC-VF.woff2") format("woff2");
font-weight: 200 900;
font-style: normal;
font-display: swap;
}

111
src/styles/global.css Normal file
View File

@@ -0,0 +1,111 @@
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* ─── 暗色主题(默认) ───────────────────────────── */
:root,
[data-theme="dark"] {
--bg-primary: #1e1e1e;
--bg-secondary: #252526;
--bg-toolbar: #2d2d2d;
--bg-statusbar: #007acc;
--bg-dropdown: #2d2d2d;
--border-color: #3e3e42;
--text-primary: #d4d4d4;
--text-secondary: #9d9d9d;
--text-muted: #6e6e6e;
--accent: #007acc;
--accent-hover: #1a8ad4;
--scrollbar-thumb: #424242;
--scrollbar-track: #1e1e1e;
--divider: #454545;
--editor-bg: #1e1e1e;
--preview-bg: #0d1117;
--dropdown-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
--dropdown-item-hover: rgba(255, 255, 255, 0.08);
--view-btn-bg: #1e1e1e;
}
/* ─── 浅色主题 ───────────────────────────────────── */
[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--bg-toolbar: #f3f3f3;
--bg-statusbar: #007acc;
--bg-dropdown: #ffffff;
--border-color: #e4e4e4;
--text-primary: #1f1f1f;
--text-secondary: #555555;
--text-muted: #999999;
--accent: #0078d4;
--accent-hover: #106ebe;
--scrollbar-thumb: #c8c8c8;
--scrollbar-track: #f0f0f0;
--divider: #e0e0e0;
--editor-bg: #ffffff;
--preview-bg: #ffffff;
--dropdown-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
--dropdown-item-hover: rgba(0, 0, 0, 0.05);
--view-btn-bg: #e8e8e8;
}
html,
body,
#root {
height: 100%;
width: 100%;
overflow: hidden;
}
/* Android safe-area: push content below system status bar */
html {
padding-top: env(safe-area-inset-top);
padding-bottom: env(safe-area-inset-bottom);
background: var(--bg-toolbar);
}
body {
font-family: var(--font-ui);
background: var(--bg-primary);
color: var(--text-primary);
user-select: none;
transition: background 0.2s, color 0.2s;
}
.app,
.app button,
.app input,
.app textarea,
.app select {
font-family: var(--font-ui);
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--scrollbar-track);
}
::-webkit-scrollbar-thumb {
background: var(--scrollbar-thumb);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
button {
cursor: pointer;
border: none;
background: none;
color: inherit;
font-family: inherit;
}