feat: 小银 Markdown 编辑器 v2.6.1 源码
纯本地 Windows Markdown 编辑器(Electron + Tauri 双栈): - 实时预览、多标签 / 多窗口两种打开方式 - 查找高亮、大纲、侧栏面板 - 右键复制全文 / 打开目录、常用快捷键 - 不联网、不登录、不收集任何数据 仓库化时做的处理: - 路径脱敏:README 与 tools/mklink.js 里写死的 C:\Users\<用户名> 改为 %USERPROFILE% / process.env.USERPROFILE,换机器即可用(原文件含个人目录名) - 补 .gitignore(node_modules / dist / src-tauri/target / Tauri 自动生成的 gen/schemas) - 补 MIT LICENSE(与 package.json 的 license 字段一致)
This commit is contained in:
commit
66bad58593
37 files changed
+11319
No files matched your search
+12
@@ -0,0 +1,12 @@
|
|||||||
|
# ── 依赖与构建产物(都能重新生成)──
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
src-tauri/target/
|
||||||
|
|
||||||
|
# Tauri 自动生成的 ACL schema:`tauri dev/build` 会重建,不入库
|
||||||
|
src-tauri/gen/schemas/
|
||||||
|
|
||||||
|
# ── 编辑器/系统杂项 ──
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 小银
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# 小银 Markdown
|
||||||
|
|
||||||
|
一个纯本地的 Windows Markdown 编辑器。左边写、右边看,不联外网、不登录、不收集任何东西。
|
||||||
|
|
||||||
|
## 装在哪(示例)
|
||||||
|
|
||||||
|
- 程序:`%USERPROFILE%\Apps\XiaoyinMarkdown\XiaoyinMarkdown.exe`
|
||||||
|
- 桌面快捷方式:`小银Markdown`(双击即可)
|
||||||
|
|
||||||
|
## 功能
|
||||||
|
|
||||||
|
- **两种打开方式**:「标签」模式=一个窗口内多标签切换;「独立窗口」模式=每个文档一个窗口。点工具栏「标签 / 窗口」按钮即可切换,偏好会记住,重启后仍然生效
|
||||||
|
- **切换时自动迁移**:从独立窗口切到标签 → 所有窗口里的文档合并进一个窗口的多个标签;从标签切到独立窗口 → 每个标签拆成一个独立窗口。未保存的正文、滚动位置、光标位置都会跟着过去,不会丢失
|
||||||
|
- **右键打开**:文件树中右键「在新标签打开」或「在新窗口打开」——具体行为按当前记住的模式走;菜单「文件 → 在新窗口打开」快捷键 `Ctrl+Shift+N`
|
||||||
|
- **左侧文件目录**:列出当前文件夹里的 Markdown / 文本文件;**单击只选中,双击才打开**(文件夹也是双击展开),跟资源管理器的习惯一致;当前打开的文件高亮,会记住上次打开的文件夹
|
||||||
|
- **文件条目操作**:文件树里右键「复制文件」=调用 Windows 原生复制(`Ctrl+C`),剪贴板里是**文件本身**,到资源管理器或微信等地方 `Ctrl+V` 能粘贴出文件副本;另有「复制文件内容」(正文文本)、「复制文件名」「复制完整路径」「在资源管理器中显示」
|
||||||
|
- 实现说明:Electron 45 的 clipboard API 没有写文件的能力,所以通过 `koffi` 直接调用 Win32 `SetClipboardData(CF_HDROP)`,效果等同于在资源管理器里选中文件按 `Ctrl+C`
|
||||||
|
- **右侧章节大纲**:按 `#` 标题自动生成章节树,点一条跳到对应位置;随编辑实时更新,滚动时自动高亮当前章节
|
||||||
|
- **两个开关标识**:「目录」紧挨在「编辑 / 分栏 / 阅读」切换按钮之前,「大纲」在它的右侧;样式统一,亮=展开、灭=收起,关掉随时能再打开,状态会记住
|
||||||
|
- **面板宽度可拖拽**:目录右缘、大纲左缘各有一条分隔条,拖动即可调整宽度(有最小宽度限制);宽度自动记住,重启后保持
|
||||||
|
- **查找**:`Ctrl+F` 查找条,`Enter`/`Shift+Enter` 上下切换;**右侧预览正文里所有命中都会加黄色背景标记**,当前命中橙色并自动滚到可视区,编辑内容变化时标记实时恢复,关闭查找自动清除
|
||||||
|
- **实时预览**:编辑 / 分栏 / 阅读三种模式,分栏宽度可拖动
|
||||||
|
- **拖进来就打开**:把 `.md` 文件拖进窗口直接打开;把**文件夹**拖进来,左侧列出该目录
|
||||||
|
- **右键菜单**:复制全文、打开当前文件所在文件夹、剪切 / 复制 / 粘贴 / 全选 / 撤销 / 重做
|
||||||
|
- **文件操作**:新建、打开、保存、另存为、打开文件夹,关窗时会提示未保存
|
||||||
|
- **查找**:带匹配计数和上下跳转
|
||||||
|
- **深色 / 浅色**主题,字号缩放
|
||||||
|
- **渲染支持**:标题、粗体斜体删除线、行内代码、代码块、引用、有序无序与嵌套列表、任务列表、表格(含对齐)、分割线、链接、图片
|
||||||
|
- 状态栏显示字数、字符数、光标行列;保留原文件的换行符(CRLF / LF)
|
||||||
|
- 渲染前会转义 HTML,预览里的链接用系统默认浏览器打开
|
||||||
|
|
||||||
|
## 快捷键
|
||||||
|
|
||||||
|
| 操作 | 快捷键 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新建 / 打开 | `Ctrl+N` / `Ctrl+O` |
|
||||||
|
| 保存 / 另存为 | `Ctrl+S` / `Ctrl+Shift+S` |
|
||||||
|
| 撤销 / 重做 | `Ctrl+Z` / `Ctrl+Y` |
|
||||||
|
| 剪切 / 复制 / 粘贴 / 全选 | `Ctrl+X` / `C` / `V` / `A` |
|
||||||
|
| 查找 | `Ctrl+F` |
|
||||||
|
| 复制全文 | `Ctrl+Shift+C` |
|
||||||
|
| 打开文件夹 | `Ctrl+Shift+K` |
|
||||||
|
| 在新窗口打开当前文档 | `Ctrl+Shift+N` |
|
||||||
|
| 显示 / 隐藏文件目录 | `Ctrl+Shift+B` |
|
||||||
|
| 显示 / 隐藏章节大纲 | `Ctrl+Shift+T` |
|
||||||
|
| 复制文件树中选中项(文件本身) | `Ctrl+C`(焦点在条目上) |
|
||||||
|
| 在资源管理器中显示当前文件 | `Ctrl+Shift+O` |
|
||||||
|
| 编辑 / 分栏 / 阅读 | `Ctrl+1` / `Ctrl+2` / `Ctrl+3` |
|
||||||
|
| 深色浅色切换 | `Ctrl+Shift+L` |
|
||||||
|
| 放大 / 缩小 / 还原 | `Ctrl+Shift+=` / `Ctrl+Shift+-` / `Ctrl+0` |
|
||||||
|
| 全屏 / 开发者工具 | `F11` / `F12` |
|
||||||
|
|
||||||
|
编辑区里还有两个顺手的细节:`Tab` 插入缩进;在列表项末尾按回车会自动续上下一条标记。
|
||||||
|
|
||||||
|
## 自己改代码
|
||||||
|
|
||||||
|
源码在本目录。目录结构:
|
||||||
|
|
||||||
|
```
|
||||||
|
md-editor/
|
||||||
|
├─ src/
|
||||||
|
│ ├─ main.js 主进程:窗口、菜单快捷键、文件读写、对话框
|
||||||
|
│ ├─ preload.js 安全桥接(contextIsolation 开启)
|
||||||
|
│ └─ renderer/
|
||||||
|
│ ├─ index.html 界面结构
|
||||||
|
│ ├─ style.css 样式与两套主题
|
||||||
|
│ ├─ markdown.js 自写的 Markdown 渲染引擎(零依赖)
|
||||||
|
│ └─ app.js 交互逻辑
|
||||||
|
├─ tools/ 自测与打包辅助脚本(不参与发布)
|
||||||
|
└─ build/icon.ico 应用图标
|
||||||
|
```
|
||||||
|
|
||||||
|
开发调试:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
跑一遍功能自测(31 项,覆盖渲染用例、打开保存、撤销粘贴、查找、模式切换、文件树展开与打开):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/test.js
|
||||||
|
```
|
||||||
|
|
||||||
|
单独验证真实拖放链路(用 CDP 注入系统级拖放事件,确认能取到路径并打开文件/文件夹):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/dragtest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证侧栏启动行为与记忆恢复(记住文件夹、收起状态持久化):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/sidetest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证章节目录(生成、开关、跳转定位、实时更新、状态记忆):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/outlinetest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证文件树复制(右键复制文件名/路径/内容、Ctrl+C、按钮位置):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/copytest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证标签页、独立窗口偏好、右键打开方式(21 项):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/multitest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证真实主进程能否创建多个独立窗口:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node tools/wintest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证模式切换时的双向迁移(多窗口合并成标签、标签拆成多窗口,11 项):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/migrationtest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证关闭窗口时主进程不抛异常:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/closetest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
验证目录/大纲宽度拖拽与记忆(14 项):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron tools/paneltest.js
|
||||||
|
```
|
||||||
|
|
||||||
|
重新打包 exe:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx electron-packager . XiaoyinMarkdown --platform=win32 --arch=x64 --out=dist ^
|
||||||
|
--overwrite --asar --icon=build/icon.ico --ignore="^/dist" --ignore="^/tools" --ignore="^/build"
|
||||||
|
```
|
||||||
|
|
||||||
|
打包完成后把 `dist\XiaoyinMarkdown-win32-x64` 整个目录拷到 `%USERPROFILE%\Apps\XiaoyinMarkdown` 覆盖即可(exe 依赖同目录的 dll,不能只拷 exe)。
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
- 未做代码签名,首次运行 Windows SmartScreen 可能提示"未知发布者",选"仍要运行"即可。
|
||||||
|
- 程序只读写你主动打开或保存的文件,不联网(预览里的链接除外,会交给系统浏览器)。
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 147 KiB |
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"name": "xiaoyin-markdown-editor",
|
||||||
|
"productName": "XiaoyinMarkdown",
|
||||||
|
"version": "2.6.1",
|
||||||
|
"description": "轻量本地 Markdown 编辑器:实时预览、多标签/多窗口、查找高亮、右键复制全文/打开目录、常用快捷键",
|
||||||
|
"main": "src/main.js",
|
||||||
|
"author": "小银",
|
||||||
|
"license": "MIT",
|
||||||
|
"scripts": {
|
||||||
|
"start": "electron .",
|
||||||
|
"pack": "electron-packager . XiaoyinMarkdown --platform=win32 --arch=x64 --out=dist --overwrite --asar --app-version=1.0.0",
|
||||||
|
"installer": "electron-builder --win nsis --x64"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@electron/packager": "^20.3.0",
|
||||||
|
"@tauri-apps/cli": "^2.12.6",
|
||||||
|
"electron": "45.4.1",
|
||||||
|
"windows-shortcuts": "^0.1.6"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"koffi": "^3.3.8"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"appId": "com.xiaoyin.markdown",
|
||||||
|
"productName": "XiaoyinMarkdown",
|
||||||
|
"electronDist": "node_modules/electron/dist",
|
||||||
|
"directories": {
|
||||||
|
"output": "release"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"src/**/*",
|
||||||
|
"package.json",
|
||||||
|
"!tools/**",
|
||||||
|
"!build/**",
|
||||||
|
"!release/**",
|
||||||
|
"!dist/**",
|
||||||
|
"!.cache/**",
|
||||||
|
"!.workbuddy/**",
|
||||||
|
"!shot-*.png",
|
||||||
|
"!README.md"
|
||||||
|
],
|
||||||
|
"asarUnpack": [
|
||||||
|
"**/node_modules/koffi/**"
|
||||||
|
],
|
||||||
|
"win": {
|
||||||
|
"target": [
|
||||||
|
"nsis"
|
||||||
|
],
|
||||||
|
"icon": "build/icon.ico"
|
||||||
|
},
|
||||||
|
"nsis": {
|
||||||
|
"oneClick": false,
|
||||||
|
"perMachine": false,
|
||||||
|
"allowToChangeInstallationDirectory": true,
|
||||||
|
"artifactName": "XiaoyinMarkdown-Setup-${version}.exe",
|
||||||
|
"shortcutName": "小银 Markdown",
|
||||||
|
"createDesktopShortcut": true,
|
||||||
|
"createStartMenuShortcut": true,
|
||||||
|
"uninstallDisplayName": "小银 Markdown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+5089
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
|||||||
|
[package]
|
||||||
|
name = "xiaoyin-markdown"
|
||||||
|
version = "2.6.1"
|
||||||
|
description = "小银 Markdown —— 轻量本地 Markdown 编辑器"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tauri = { version = "2", features = [] }
|
||||||
|
tauri-plugin-dialog = "2"
|
||||||
|
tauri-plugin-single-instance = "2"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
clipboard-win = "5"
|
||||||
|
windows-sys = { version = "0.61", features = [
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_System_DataExchange",
|
||||||
|
"Win32_System_Memory",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_UI_WindowsAndMessaging"
|
||||||
|
] }
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
opt-level = "s"
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
strip = true
|
||||||
|
panic = "abort"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
tauri_build::build();
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "default",
|
||||||
|
"description": "小银 Markdown 全部窗口的默认权限",
|
||||||
|
"windows": ["*"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-set-title",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:window:allow-destroy",
|
||||||
|
"core:window:allow-hide",
|
||||||
|
"core:window:allow-show",
|
||||||
|
"core:window:allow-set-focus",
|
||||||
|
"dialog:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
@@ -0,0 +1,502 @@
|
|||||||
|
// 小银 Markdown —— Tauri 2 后端
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent};
|
||||||
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
|
const MD_EXTS: [&str; 6] = ["md", "markdown", "mdown", "mkd", "mdwn", "txt"];
|
||||||
|
|
||||||
|
/* ---------------- 数据结构 ---------------- */
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Entry {
|
||||||
|
name: String,
|
||||||
|
path: String,
|
||||||
|
is_dir: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DocResult {
|
||||||
|
ok: bool,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
canceled: Option<bool>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
path: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
name: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
text: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
eol: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DocResult {
|
||||||
|
fn ok(path: &Path, text: String, eol: String) -> Self {
|
||||||
|
DocResult {
|
||||||
|
ok: true,
|
||||||
|
canceled: None,
|
||||||
|
path: Some(path.to_string_lossy().to_string()),
|
||||||
|
name: Some(path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default()),
|
||||||
|
text: Some(text),
|
||||||
|
eol: Some(eol),
|
||||||
|
error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn canceled() -> Self {
|
||||||
|
DocResult { ok: false, canceled: Some(true), path: None, name: None, text: None, eol: None, error: None }
|
||||||
|
}
|
||||||
|
fn err(msg: String) -> Self {
|
||||||
|
DocResult { ok: false, canceled: None, path: None, name: None, text: None, eol: None, error: Some(msg) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DirResult {
|
||||||
|
ok: bool,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
canceled: Option<bool>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
path: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
name: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
entries: Option<Vec<Entry>>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 工具函数 ---------------- */
|
||||||
|
|
||||||
|
fn smart_read(path: &Path) -> Result<(String, String), String> {
|
||||||
|
let bytes = fs::read(path).map_err(|e| e.to_string())?;
|
||||||
|
let mut text = String::from_utf8_lossy(&bytes).to_string();
|
||||||
|
if let Some(stripped) = text.clone().strip_prefix('\u{feff}') {
|
||||||
|
text = stripped.to_string();
|
||||||
|
}
|
||||||
|
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" }.to_string();
|
||||||
|
let text = text.replace("\r\n", "\n").replace('\r', "\n");
|
||||||
|
Ok((text, eol))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn smart_write(path: &Path, content: &str, eol: &str) -> Result<(), String> {
|
||||||
|
let text = if eol == "\r\n" { content.replace('\n', "\r\n") } else { content.to_string() };
|
||||||
|
fs::write(path, text).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_md_file(name: &str) -> bool {
|
||||||
|
Path::new(name)
|
||||||
|
.extension()
|
||||||
|
.map(|e| e.to_string_lossy().to_lowercase())
|
||||||
|
.map(|e| MD_EXTS.contains(&e.as_str()))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_dir(path: &Path) -> Result<Vec<Entry>, String> {
|
||||||
|
let mut dirs: Vec<Entry> = Vec::new();
|
||||||
|
let mut files: Vec<Entry> = Vec::new();
|
||||||
|
for e in fs::read_dir(path).map_err(|e| e.to_string())? {
|
||||||
|
let Ok(e) = e else { continue };
|
||||||
|
let name = e.file_name().to_string_lossy().to_string();
|
||||||
|
if name.starts_with('.') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(ft) = e.file_type() else { continue };
|
||||||
|
let is_dir = ft.is_dir();
|
||||||
|
if !is_dir && !is_md_file(&name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let full = e.path().to_string_lossy().to_string();
|
||||||
|
let entry = Entry { name, path: full, is_dir };
|
||||||
|
if is_dir {
|
||||||
|
dirs.push(entry);
|
||||||
|
} else {
|
||||||
|
files.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dirs.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||||
|
files.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||||
|
dirs.extend(files);
|
||||||
|
Ok(dirs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path_of(fp: tauri_plugin_dialog::FilePath) -> Option<PathBuf> {
|
||||||
|
match fp {
|
||||||
|
tauri_plugin_dialog::FilePath::Path(p) => Some(p),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 文件命令 ---------------- */
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn read_text_file(path: String) -> DocResult {
|
||||||
|
let p = PathBuf::from(&path);
|
||||||
|
match smart_read(&p) {
|
||||||
|
Ok((text, eol)) => DocResult::ok(&p, text, eol),
|
||||||
|
Err(e) => DocResult::err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn write_text_file(path: String, content: String, eol: String) -> DocResult {
|
||||||
|
let p = PathBuf::from(&path);
|
||||||
|
match smart_write(&p, &content, &eol) {
|
||||||
|
Ok(_) => DocResult::ok(&p, String::new(), eol),
|
||||||
|
Err(e) => DocResult::err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_file_dialog(window: tauri::WebviewWindow) -> DocResult {
|
||||||
|
let picked = window
|
||||||
|
.dialog()
|
||||||
|
.file()
|
||||||
|
.add_filter("Markdown", &["md", "markdown", "mdown", "mkd", "mdwn", "txt"])
|
||||||
|
.add_filter("所有文件", &["*"])
|
||||||
|
.set_title("打开 Markdown 文件")
|
||||||
|
.blocking_pick_file();
|
||||||
|
let Some(fp) = picked else { return DocResult::canceled() };
|
||||||
|
let Some(p) = path_of(fp) else { return DocResult::canceled() };
|
||||||
|
match smart_read(&p) {
|
||||||
|
Ok((text, eol)) => DocResult::ok(&p, text, eol),
|
||||||
|
Err(e) => DocResult::err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn save_file(
|
||||||
|
window: tauri::WebviewWindow,
|
||||||
|
content: String,
|
||||||
|
save_as: bool,
|
||||||
|
eol: String,
|
||||||
|
current_path: Option<String>,
|
||||||
|
) -> DocResult {
|
||||||
|
let mut target: Option<PathBuf> = current_path.as_ref().map(PathBuf::from);
|
||||||
|
|
||||||
|
if target.is_none() || save_as || !Path::new(target.as_ref().unwrap()).exists() {
|
||||||
|
let default_path = current_path.clone().map(PathBuf::from).unwrap_or_else(|| {
|
||||||
|
let doc = window
|
||||||
|
.app_handle()
|
||||||
|
.path()
|
||||||
|
.document_dir()
|
||||||
|
.unwrap_or_else(|_| PathBuf::from("."));
|
||||||
|
doc.join("未命名.md")
|
||||||
|
});
|
||||||
|
let picked = window
|
||||||
|
.dialog()
|
||||||
|
.file()
|
||||||
|
.add_filter("Markdown", &["md"])
|
||||||
|
.add_filter("纯文本", &["txt"])
|
||||||
|
.add_filter("所有文件", &["*"])
|
||||||
|
.set_file_name(default_path.to_string_lossy().as_ref())
|
||||||
|
.set_title(if save_as { "另存为" } else { "保存" })
|
||||||
|
.blocking_save_file();
|
||||||
|
let Some(fp) = picked else { return DocResult::canceled() };
|
||||||
|
let Some(p) = path_of(fp) else { return DocResult::canceled() };
|
||||||
|
target = Some(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
let p = target.unwrap();
|
||||||
|
match smart_write(&p, &content, &eol) {
|
||||||
|
Ok(_) => DocResult::ok(&p, String::new(), eol),
|
||||||
|
Err(e) => DocResult::err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_dir_dialog(window: tauri::WebviewWindow) -> DirResult {
|
||||||
|
let picked = window.dialog().file().set_title("选择文件夹").blocking_pick_folder();
|
||||||
|
let Some(fp) = picked else {
|
||||||
|
return DirResult { ok: false, canceled: Some(true), path: None, name: None, entries: None, error: None };
|
||||||
|
};
|
||||||
|
let Some(p) = path_of(fp) else {
|
||||||
|
return DirResult { ok: false, canceled: Some(true), path: None, name: None, entries: None, error: None };
|
||||||
|
};
|
||||||
|
match list_dir(&p) {
|
||||||
|
Ok(entries) => DirResult {
|
||||||
|
ok: true,
|
||||||
|
canceled: None,
|
||||||
|
path: Some(p.to_string_lossy().to_string()),
|
||||||
|
name: Some(p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default()),
|
||||||
|
entries: Some(entries),
|
||||||
|
error: None,
|
||||||
|
},
|
||||||
|
Err(e) => DirResult { ok: false, canceled: None, path: None, name: None, entries: None, error: Some(e) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn read_dir(path: String) -> DirResult {
|
||||||
|
let p = PathBuf::from(&path);
|
||||||
|
match list_dir(&p) {
|
||||||
|
Ok(entries) => DirResult {
|
||||||
|
ok: true,
|
||||||
|
canceled: None,
|
||||||
|
path: Some(p.to_string_lossy().to_string()),
|
||||||
|
name: Some(p.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default()),
|
||||||
|
entries: Some(entries),
|
||||||
|
error: None,
|
||||||
|
},
|
||||||
|
Err(e) => DirResult { ok: false, canceled: None, path: None, name: None, entries: None, error: Some(e) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 剪贴板 ---------------- */
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn copy_file_to_clipboard(path: String) -> Result<(), String> {
|
||||||
|
// 手写 CF_HDROP:DROPFILES 头 + 双 \0 结尾的 UTF-16 路径列表
|
||||||
|
use windows_sys::Win32::System::DataExchange::{CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData};
|
||||||
|
use windows_sys::Win32::System::Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE, GMEM_ZEROINIT};
|
||||||
|
use windows_sys::Win32::UI::Shell::DROPFILES;
|
||||||
|
|
||||||
|
const CF_HDROP: u32 = 15;
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
if OpenClipboard(std::ptr::null_mut()) == 0 {
|
||||||
|
return Err("无法打开剪贴板".into());
|
||||||
|
}
|
||||||
|
if EmptyClipboard() == 0 {
|
||||||
|
CloseClipboard();
|
||||||
|
return Err("无法清空剪贴板".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut wide: Vec<u16> = path.encode_utf16().collect();
|
||||||
|
wide.push(0); // 路径自身的 \0 终止符
|
||||||
|
|
||||||
|
let header_size = std::mem::size_of::<DROPFILES>();
|
||||||
|
let list_bytes = (wide.len() + 1) * 2; // +1 是列表级双 \0 结束符
|
||||||
|
let total = header_size + list_bytes;
|
||||||
|
|
||||||
|
let h = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, total);
|
||||||
|
if h.is_null() {
|
||||||
|
CloseClipboard();
|
||||||
|
return Err("内存分配失败".into());
|
||||||
|
}
|
||||||
|
let locked = GlobalLock(h);
|
||||||
|
if locked.is_null() {
|
||||||
|
CloseClipboard();
|
||||||
|
return Err("内存锁定失败".into());
|
||||||
|
}
|
||||||
|
let df = locked as *mut DROPFILES;
|
||||||
|
(*df).pFiles = header_size as u32;
|
||||||
|
(*df).fWide = 1; // UTF-16
|
||||||
|
let dst = (locked as *mut u8).add(header_size);
|
||||||
|
std::ptr::copy_nonoverlapping(wide.as_ptr() as *const u8, dst, wide.len() * 2);
|
||||||
|
GlobalUnlock(h);
|
||||||
|
|
||||||
|
if SetClipboardData(CF_HDROP, h).is_null() {
|
||||||
|
CloseClipboard();
|
||||||
|
return Err("写入剪贴板失败".into());
|
||||||
|
}
|
||||||
|
CloseClipboard();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn read_clipboard_text() -> String {
|
||||||
|
use clipboard_win::formats;
|
||||||
|
use clipboard_win::get_clipboard;
|
||||||
|
get_clipboard(formats::Unicode).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn write_clipboard_text(text: String) -> Result<(), String> {
|
||||||
|
use clipboard_win::formats;
|
||||||
|
use clipboard_win::set_clipboard;
|
||||||
|
set_clipboard(formats::Unicode, text).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 系统 ---------------- */
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn reveal_in_explorer(path: String) -> Result<(), String> {
|
||||||
|
let p = PathBuf::from(&path);
|
||||||
|
if p.is_file() {
|
||||||
|
std::process::Command::new("explorer")
|
||||||
|
.arg(format!("/select,{}", p.to_string_lossy()))
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
} else {
|
||||||
|
std::process::Command::new("explorer")
|
||||||
|
.arg(&p)
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_external(url: String) -> Result<(), String> {
|
||||||
|
if !url.starts_with("http://") && !url.starts_with("https://") {
|
||||||
|
return Err("仅允许打开 http/https 链接".into());
|
||||||
|
}
|
||||||
|
std::process::Command::new("explorer")
|
||||||
|
.arg(&url)
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn message_box(window: tauri::WebviewWindow, title: String, message: String, detail: Option<String>) -> i32 {
|
||||||
|
use tauri_plugin_dialog::{MessageDialogButtons, MessageDialogKind};
|
||||||
|
let text = match &detail {
|
||||||
|
Some(d) if !d.is_empty() => format!("{}\n{}", message, d),
|
||||||
|
_ => message.clone(),
|
||||||
|
};
|
||||||
|
let _ = window
|
||||||
|
.dialog()
|
||||||
|
.message(text)
|
||||||
|
.title(&title)
|
||||||
|
.kind(MessageDialogKind::Info)
|
||||||
|
.buttons(MessageDialogButtons::Ok)
|
||||||
|
.blocking_show();
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 多窗口 ---------------- */
|
||||||
|
|
||||||
|
fn next_window_label(app: &AppHandle) -> String {
|
||||||
|
let mut i = 1;
|
||||||
|
let existing = app.webview_windows();
|
||||||
|
loop {
|
||||||
|
let label = format!("win-{}", i);
|
||||||
|
if !existing.contains_key(&label) {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_doc_window(app: &AppHandle, doc: Option<serde_json::Value>) -> Result<String, String> {
|
||||||
|
let label = next_window_label(app);
|
||||||
|
let win = WebviewWindowBuilder::new(app, &label, WebviewUrl::App("index.html".into()))
|
||||||
|
.title("未命名 — 小银 Markdown")
|
||||||
|
.inner_size(1380.0, 880.0)
|
||||||
|
.min_inner_size(860.0, 520.0)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if let Some(d) = doc {
|
||||||
|
let _ = win.emit("mig:adopt-doc", d);
|
||||||
|
}
|
||||||
|
Ok(label)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_new_window(app: AppHandle, path: Option<String>) -> Result<String, String> {
|
||||||
|
let doc = match &path {
|
||||||
|
Some(p) => {
|
||||||
|
let pb = PathBuf::from(p);
|
||||||
|
match smart_read(&pb) {
|
||||||
|
Ok((text, eol)) => Some(serde_json::json!({
|
||||||
|
"path": p, "name": pb.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(),
|
||||||
|
"text": text, "eol": eol
|
||||||
|
})),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
create_doc_window(&app, doc)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn force_close(window: tauri::WebviewWindow) {
|
||||||
|
window.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn get_window_count(app: AppHandle) -> usize {
|
||||||
|
app.webview_windows().len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 模式迁移:前端先通过事件收集各窗口文档,再调用这里执行窗口增删 */
|
||||||
|
#[tauri::command]
|
||||||
|
fn migrate_apply(app: AppHandle, mode: String, docs: Vec<serde_json::Value>, keep_label: String) -> Result<(), String> {
|
||||||
|
let old_labels: Vec<String> = app.webview_windows().keys().cloned().collect();
|
||||||
|
|
||||||
|
match mode.as_str() {
|
||||||
|
"tabs" => {
|
||||||
|
// 全部合并进保留窗口
|
||||||
|
if let Some(win) = app.get_webview_window(&keep_label) {
|
||||||
|
let _ = win.emit("mig:adopt-tabs", serde_json::json!({ "docs": docs }));
|
||||||
|
}
|
||||||
|
for l in old_labels.iter() {
|
||||||
|
if l != &keep_label {
|
||||||
|
if let Some(w) = app.get_webview_window(l) {
|
||||||
|
w.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"windows" => {
|
||||||
|
// 每份文档一个新窗口
|
||||||
|
for d in docs.iter() {
|
||||||
|
let label = create_doc_window(&app, Some(d.clone()))?;
|
||||||
|
let _ = label;
|
||||||
|
}
|
||||||
|
for l in old_labels.iter() {
|
||||||
|
if let Some(w) = app.get_webview_window(l) {
|
||||||
|
w.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Err(format!("未知模式 {}", mode)),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 入口 ---------------- */
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
tauri::Builder::default()
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
|
||||||
|
if let Some(win) = app.get_webview_window("main") {
|
||||||
|
let _ = win.set_focus();
|
||||||
|
if let Some(path) = argv.iter().nth(1) {
|
||||||
|
let p = PathBuf::from(path);
|
||||||
|
if p.is_file() {
|
||||||
|
let _ = win.emit("open-external", p.to_string_lossy().to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
read_text_file,
|
||||||
|
write_text_file,
|
||||||
|
open_file_dialog,
|
||||||
|
save_file,
|
||||||
|
open_dir_dialog,
|
||||||
|
read_dir,
|
||||||
|
copy_file_to_clipboard,
|
||||||
|
read_clipboard_text,
|
||||||
|
write_clipboard_text,
|
||||||
|
reveal_in_explorer,
|
||||||
|
open_external,
|
||||||
|
message_box,
|
||||||
|
open_new_window,
|
||||||
|
force_close,
|
||||||
|
get_window_count,
|
||||||
|
migrate_apply
|
||||||
|
])
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
// 交给前端确认(未保存提示)
|
||||||
|
api.prevent_close();
|
||||||
|
let _ = window.emit("close-confirm", window.label());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while running tauri application");
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"productName": "XiaoyinMarkdown",
|
||||||
|
"version": "2.6.1",
|
||||||
|
"identifier": "com.xiaoyin.markdown",
|
||||||
|
"build": {
|
||||||
|
"frontendDist": "../src/renderer"
|
||||||
|
},
|
||||||
|
"app": {
|
||||||
|
"withGlobalTauri": true,
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"label": "main",
|
||||||
|
"title": "未命名 — 小银 Markdown",
|
||||||
|
"width": 1380,
|
||||||
|
"height": 880,
|
||||||
|
"minWidth": 860,
|
||||||
|
"minHeight": 520,
|
||||||
|
"dragDropEnabled": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": {
|
||||||
|
"csp": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"active": true,
|
||||||
|
"targets": ["nsis"],
|
||||||
|
"icon": ["icons/icon.ico"],
|
||||||
|
"fileAssociations": [
|
||||||
|
{
|
||||||
|
"ext": ["md", "markdown", "mdown", "mkd", "mdwn"],
|
||||||
|
"name": "XiaoyinMarkdown.Document",
|
||||||
|
"description": "Markdown 文档 — 小银 Markdown",
|
||||||
|
"role": "Editor"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ext": ["txt"],
|
||||||
|
"name": "XiaoyinMarkdown.Text",
|
||||||
|
"description": "文本文档 — 小银 Markdown",
|
||||||
|
"role": "Editor"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"windows": {
|
||||||
|
"webviewInstallMode": {
|
||||||
|
"type": "downloadBootstrapper"
|
||||||
|
},
|
||||||
|
"nsis": {
|
||||||
|
"installMode": "currentUser",
|
||||||
|
"languages": ["SimpChinese"],
|
||||||
|
"displayLanguageSelector": false,
|
||||||
|
"installerIcon": "icons/icon.ico",
|
||||||
|
"uninstallerIcon": "icons/icon.ico"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/* Windows 原生文件剪贴板:通过 Win32 CF_HDROP 把文件对象放进系统剪贴板,
|
||||||
|
效果等同于在资源管理器里选中文件按 Ctrl+C(可以在别处 Ctrl+V 粘出文件副本)。
|
||||||
|
Electron 45 的 clipboard API 没有 writeBuffer,只能走 Win32。 */
|
||||||
|
let api = null;
|
||||||
|
|
||||||
|
function makeHdrop(paths) {
|
||||||
|
const header = Buffer.alloc(20);
|
||||||
|
header.writeUInt32LE(20, 0); // pFiles:文件列表相对结构头的偏移
|
||||||
|
// pt(8 字节) 与 fNC(4 字节) 留 0
|
||||||
|
header.writeUInt32LE(1, 16); // fWide = TRUE(UTF-16LE 路径)
|
||||||
|
const parts = paths.map((p) => Buffer.from(String(p) + '\0', 'utf16le'));
|
||||||
|
return Buffer.concat([header, ...parts, Buffer.from([0, 0])]); // 双 \0 结束
|
||||||
|
}
|
||||||
|
|
||||||
|
function getApi() {
|
||||||
|
if (api) return api;
|
||||||
|
const koffi = require('koffi');
|
||||||
|
const user32 = koffi.load('user32.dll');
|
||||||
|
const kernel32 = koffi.load('kernel32.dll');
|
||||||
|
|
||||||
|
const OpenClipboard = user32.func('bool OpenClipboard(void* hWnd)');
|
||||||
|
const EmptyClipboard = user32.func('bool EmptyClipboard()');
|
||||||
|
const SetClipboardData = user32.func('void* SetClipboardData(unsigned int uFormat, void* hMem)');
|
||||||
|
const CloseClipboard = user32.func('bool CloseClipboard()');
|
||||||
|
const IsClipboardFormatAvailable = user32.func('bool IsClipboardFormatAvailable(unsigned int format)');
|
||||||
|
const GlobalAlloc = kernel32.func('void* GlobalAlloc(unsigned int uFlags, size_t dwBytes)');
|
||||||
|
const GlobalLock = kernel32.func('void* GlobalLock(void* hMem)');
|
||||||
|
const GlobalUnlock = kernel32.func('bool GlobalUnlock(void* hMem)');
|
||||||
|
const RtlMoveMemory = kernel32.func('void RtlMoveMemory(void* dst, void* src, size_t len)');
|
||||||
|
|
||||||
|
function setFiles(paths) {
|
||||||
|
const data = makeHdrop(paths);
|
||||||
|
const h = GlobalAlloc(0x0002, data.length); // GMEM_MOVEABLE
|
||||||
|
if (!h) throw new Error('内存分配失败');
|
||||||
|
const p = GlobalLock(h);
|
||||||
|
RtlMoveMemory(p, koffi.as(data, 'void*'), data.length);
|
||||||
|
GlobalUnlock(h);
|
||||||
|
|
||||||
|
if (!OpenClipboard(null)) throw new Error('无法打开剪贴板');
|
||||||
|
try {
|
||||||
|
EmptyClipboard();
|
||||||
|
if (!SetClipboardData(15, h)) throw new Error('写入剪贴板失败'); // CF_HDROP
|
||||||
|
} finally {
|
||||||
|
CloseClipboard();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasFiles() {
|
||||||
|
return !!IsClipboardFormatAvailable(15);
|
||||||
|
}
|
||||||
|
|
||||||
|
api = { setFiles, hasFiles };
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
setFiles: (paths) => getApi().setFiles(paths),
|
||||||
|
hasFiles: () => getApi().hasFiles()
|
||||||
|
};
|
||||||
+594
@@ -0,0 +1,594 @@
|
|||||||
|
/*
|
||||||
|
* 小银 Markdown 编辑器 —— 主进程
|
||||||
|
* 负责:多窗口管理、菜单与快捷键、文件读写、系统对话框、剪贴板、资源管理器联动
|
||||||
|
*
|
||||||
|
* 两种打开方式:
|
||||||
|
* tabs —— 一个窗口内用标签页打开多个文档
|
||||||
|
* windows —— 每个文档开一个独立窗口
|
||||||
|
* 偏好保存在 userData/prefs.json,切换后广播给所有窗口。
|
||||||
|
*/
|
||||||
|
const { app, BrowserWindow, ipcMain, dialog, Menu, shell, clipboard } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
|
const windows = new Map(); // webContents.id -> state { win, path, dirty, pendingClose, closing }
|
||||||
|
const pendingAdopt = new Map(); // webContents.id -> 待装载的文档(窗口拆分时用)
|
||||||
|
let openMode = 'tabs';
|
||||||
|
|
||||||
|
const prefsFile = () => path.join(app.getPath('userData'), 'prefs.json');
|
||||||
|
function loadPrefs() {
|
||||||
|
try {
|
||||||
|
const p = JSON.parse(fs.readFileSync(prefsFile(), 'utf8'));
|
||||||
|
if (p.openMode === 'tabs' || p.openMode === 'windows') openMode = p.openMode;
|
||||||
|
} catch (_) { /* 首次运行,用默认 */ }
|
||||||
|
}
|
||||||
|
function savePrefs() {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(prefsFile()), { recursive: true });
|
||||||
|
fs.writeFileSync(prefsFile(), JSON.stringify({ openMode }), 'utf8');
|
||||||
|
} catch (_) { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function stateOf(sender) {
|
||||||
|
return sender && sender.id != null ? windows.get(sender.id) : null;
|
||||||
|
}
|
||||||
|
function focusedState() {
|
||||||
|
const win = BrowserWindow.getFocusedWindow();
|
||||||
|
if (win && windows.has(win.webContents.id)) return windows.get(win.webContents.id);
|
||||||
|
const first = windows.values().next();
|
||||||
|
return first.done ? null : first.value;
|
||||||
|
}
|
||||||
|
function sendTo(state, channel, ...args) {
|
||||||
|
if (state && state.win && !state.win.isDestroyed()) state.win.webContents.send(channel, ...args);
|
||||||
|
}
|
||||||
|
function primaryState() {
|
||||||
|
const first = windows.values().next();
|
||||||
|
return first.done ? null : first.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 窗口 ------------------------------ */
|
||||||
|
|
||||||
|
/* 窗口图标(标题栏左上角 / 任务栏):打包版取安装目录 resources 下的 app-win.ico,开发环境取源码树 */
|
||||||
|
const appIconPath = app.isPackaged
|
||||||
|
? path.join(process.resourcesPath, 'app-win.ico')
|
||||||
|
: path.join(__dirname, 'resources', 'app.ico');
|
||||||
|
|
||||||
|
function createWindow(filePath) {
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1380,
|
||||||
|
height: 880,
|
||||||
|
minWidth: 860,
|
||||||
|
minHeight: 520,
|
||||||
|
show: false,
|
||||||
|
backgroundColor: '#ffffff',
|
||||||
|
autoHideMenuBar: true,
|
||||||
|
icon: appIconPath, // 标题栏左上角 / 任务栏图标(保留)
|
||||||
|
webPreferences: {
|
||||||
|
preload: path.join(__dirname, 'preload.js'),
|
||||||
|
contextIsolation: true,
|
||||||
|
nodeIntegration: false,
|
||||||
|
spellcheck: false,
|
||||||
|
sandbox: false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const wcId = win.webContents.id;
|
||||||
|
const state = { win, path: filePath || null, dirty: false, pendingClose: false, closing: false };
|
||||||
|
windows.set(wcId, state);
|
||||||
|
|
||||||
|
win.loadFile(path.join(__dirname, 'renderer', 'index.html'));
|
||||||
|
win.once('ready-to-show', () => win.show());
|
||||||
|
win.webContents.on('did-finish-load', () => {
|
||||||
|
updateTitle(state);
|
||||||
|
sendTo(state, 'cmd', 'open-mode', openMode);
|
||||||
|
if (pendingAdopt.has(win.webContents.id)) {
|
||||||
|
// 标签拆成独立窗口:装载该窗口分到的那一份文档
|
||||||
|
sendTo(state, 'cmd', 'adopt-doc', pendingAdopt.get(win.webContents.id));
|
||||||
|
pendingAdopt.delete(win.webContents.id);
|
||||||
|
} else if (filePath) {
|
||||||
|
const r = readPathQuiet(filePath);
|
||||||
|
if (r.ok) sendTo(state, 'cmd', 'file-opened', r);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
win.webContents.on('will-navigate', (e) => e.preventDefault());
|
||||||
|
win.webContents.setWindowOpenHandler(({ url }) => {
|
||||||
|
if (/^(https?|mailto):/i.test(url)) shell.openExternal(url);
|
||||||
|
return { action: 'deny' };
|
||||||
|
});
|
||||||
|
|
||||||
|
win.on('close', (e) => {
|
||||||
|
if (state.closing || !state.dirty) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const choice = dialog.showMessageBoxSync(win, {
|
||||||
|
type: 'warning',
|
||||||
|
buttons: ['保存并退出', '不保存直接退出', '取消'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 2,
|
||||||
|
noLink: true,
|
||||||
|
title: '未保存的修改',
|
||||||
|
message: '「' + (state.path ? path.basename(state.path) : '未命名') + '」还有未保存的修改',
|
||||||
|
detail: '是否先保存再退出?'
|
||||||
|
});
|
||||||
|
if (choice === 2) return;
|
||||||
|
if (choice === 1) { state.closing = true; win.close(); return; }
|
||||||
|
state.pendingClose = true;
|
||||||
|
sendTo(state, 'cmd', 'save');
|
||||||
|
});
|
||||||
|
|
||||||
|
// closed 触发时 webContents 已销毁,不能再读 win.webContents.id
|
||||||
|
win.on('closed', () => {
|
||||||
|
windows.delete(wcId);
|
||||||
|
pendingAdopt.delete(wcId);
|
||||||
|
});
|
||||||
|
return win;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPathQuiet(p) {
|
||||||
|
try {
|
||||||
|
const { text, eol } = readFileSmart(p);
|
||||||
|
return { ok: true, path: p, name: path.basename(p), text, eol };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, error: String(err.message || err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 菜单 ------------------------------ */
|
||||||
|
|
||||||
|
function buildMenu() {
|
||||||
|
const template = [
|
||||||
|
{
|
||||||
|
label: '文件',
|
||||||
|
submenu: [
|
||||||
|
{ label: '新建', accelerator: 'CmdOrCtrl+N', click: () => sendTo(focusedState(), 'cmd', 'new') },
|
||||||
|
{ label: '打开…', accelerator: 'CmdOrCtrl+O', click: () => sendTo(focusedState(), 'cmd', 'open') },
|
||||||
|
{ label: '在新窗口打开', accelerator: 'CmdOrCtrl+Shift+N', click: () => sendTo(focusedState(), 'cmd', 'newWindow') },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '保存', accelerator: 'CmdOrCtrl+S', click: () => sendTo(focusedState(), 'cmd', 'save') },
|
||||||
|
{ label: '另存为…', accelerator: 'CmdOrCtrl+Shift+S', click: () => sendTo(focusedState(), 'cmd', 'saveAs') },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '打开文件夹…', accelerator: 'CmdOrCtrl+Shift+K', click: () => sendTo(focusedState(), 'cmd', 'openFolder') },
|
||||||
|
{ label: '在资源管理器中显示当前文件', accelerator: 'CmdOrCtrl+Shift+O', click: () => sendTo(focusedState(), 'cmd', 'openDir') },
|
||||||
|
{ label: '复制全文', accelerator: 'CmdOrCtrl+Shift+C', click: () => sendTo(focusedState(), 'cmd', 'copyAll') },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '退出', accelerator: 'Alt+F4', role: 'quit' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '编辑',
|
||||||
|
submenu: [
|
||||||
|
{ label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
|
||||||
|
{ label: '重做', accelerator: 'CmdOrCtrl+Y', role: 'redo' },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
|
||||||
|
{ label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
|
||||||
|
{ label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
|
||||||
|
{ label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectAll' },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '查找', accelerator: 'CmdOrCtrl+F', click: () => sendTo(focusedState(), 'cmd', 'find') }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '视图',
|
||||||
|
submenu: [
|
||||||
|
{ label: '编辑模式', accelerator: 'CmdOrCtrl+1', click: () => sendTo(focusedState(), 'cmd', 'mode', 'edit') },
|
||||||
|
{ label: '分栏模式', accelerator: 'CmdOrCtrl+2', click: () => sendTo(focusedState(), 'cmd', 'mode', 'split') },
|
||||||
|
{ label: '阅读模式', accelerator: 'CmdOrCtrl+3', click: () => sendTo(focusedState(), 'cmd', 'mode', 'read') },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: '文档打开方式',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: '标签页(多窗口)', type: 'radio', checked: openMode === 'tabs',
|
||||||
|
click: () => setOpenMode('tabs')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '独立窗口', type: 'radio', checked: openMode === 'windows',
|
||||||
|
click: () => setOpenMode('windows')
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '显示 / 隐藏文件目录', accelerator: 'CmdOrCtrl+Shift+B', click: () => sendTo(focusedState(), 'cmd', 'tree') },
|
||||||
|
{ label: '显示 / 隐藏章节大纲', accelerator: 'CmdOrCtrl+Shift+T', click: () => sendTo(focusedState(), 'cmd', 'outline') },
|
||||||
|
{ label: '切换深色/浅色', accelerator: 'CmdOrCtrl+Shift+L', click: () => sendTo(focusedState(), 'cmd', 'theme') },
|
||||||
|
{ label: '放大', accelerator: 'CmdOrCtrl+Shift+=', click: () => sendTo(focusedState(), 'cmd', 'zoom', 1) },
|
||||||
|
{ label: '缩小', accelerator: 'CmdOrCtrl+Shift+-', click: () => sendTo(focusedState(), 'cmd', 'zoom', -1) },
|
||||||
|
{ label: '实际大小', accelerator: 'CmdOrCtrl+0', click: () => sendTo(focusedState(), 'cmd', 'zoom', 0) },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
|
||||||
|
{ label: '全屏', accelerator: 'F11', role: 'togglefullscreen' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 让某个窗口把它的所有标签文档交出来(带未保存内容) */
|
||||||
|
function collectDocsFrom(state) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let done = false;
|
||||||
|
const timer = setTimeout(() => finish([]), 2500);
|
||||||
|
function finish(docs) {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
ipcMain.removeListener('docs:exported', handler);
|
||||||
|
resolve(docs);
|
||||||
|
}
|
||||||
|
function handler(e, payload) {
|
||||||
|
if (!state || e.sender.id !== state.win.webContents.id) return;
|
||||||
|
finish(Array.isArray(payload && payload.docs) ? payload.docs : []);
|
||||||
|
}
|
||||||
|
ipcMain.on('docs:exported', handler);
|
||||||
|
sendTo(state, 'cmd', 'export-docs');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function dedupeDocs(docs) {
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const d of docs) {
|
||||||
|
if (d.path && seen.has(d.path)) continue;
|
||||||
|
if (d.path) seen.add(d.path);
|
||||||
|
out.push(d);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeForMigration(state) {
|
||||||
|
if (!state || state.win.isDestroyed()) return;
|
||||||
|
state.closing = true; // 内容已收集,跳过未保存确认
|
||||||
|
state.win.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 切换模式时做双向迁移:
|
||||||
|
windows → tabs:把各窗口的文档并到一个窗口的多标签
|
||||||
|
tabs → windows:把标签拆成多个独立窗口 */
|
||||||
|
async function setOpenMode(mode) {
|
||||||
|
if (mode !== 'tabs' && mode !== 'windows') return;
|
||||||
|
if (mode === openMode) { buildMenu(); return; }
|
||||||
|
|
||||||
|
const states = [...windows.values()].filter((s) => s.win && !s.win.isDestroyed());
|
||||||
|
const allDocs = [];
|
||||||
|
for (const st of states) {
|
||||||
|
const docs = await collectDocsFrom(st);
|
||||||
|
allDocs.push(...docs);
|
||||||
|
}
|
||||||
|
let docs = dedupeDocs(allDocs);
|
||||||
|
if (!docs.length) docs.push({ path: null, name: null, text: '', eol: '\n', dirty: false, lastSaved: '' });
|
||||||
|
|
||||||
|
openMode = mode;
|
||||||
|
savePrefs();
|
||||||
|
buildMenu();
|
||||||
|
|
||||||
|
if (mode === 'tabs') {
|
||||||
|
const primary = states[0] || null;
|
||||||
|
for (const st of states.slice(1)) closeForMigration(st);
|
||||||
|
if (!primary) { createWindow(); return; }
|
||||||
|
sendTo(primary, 'cmd', 'open-mode', 'tabs');
|
||||||
|
sendTo(primary, 'cmd', 'adopt-tabs', docs);
|
||||||
|
} else {
|
||||||
|
for (const d of docs) {
|
||||||
|
const win = createWindow();
|
||||||
|
pendingAdopt.set(win.webContents.id, d);
|
||||||
|
}
|
||||||
|
for (const st of states) closeForMigration(st);
|
||||||
|
for (const st of windows.values()) sendTo(st, 'cmd', 'open-mode', 'windows');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ IPC ------------------------------ */
|
||||||
|
|
||||||
|
function readFileSmart(p) {
|
||||||
|
const buf = fs.readFileSync(p);
|
||||||
|
let text = buf.toString('utf8');
|
||||||
|
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // BOM
|
||||||
|
const eol = /\r\n/.test(text) ? '\r\n' : '\n';
|
||||||
|
text = text.replace(/\r\n?/g, '\n');
|
||||||
|
return { text, eol };
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPathInternal(p, state) {
|
||||||
|
try {
|
||||||
|
const { text, eol } = readFileSmart(p);
|
||||||
|
if (state) { state.path = p; state.dirty = false; updateTitle(state); }
|
||||||
|
return { ok: true, path: p, name: path.basename(p), text, eol };
|
||||||
|
} catch (err) {
|
||||||
|
const st = state || focusedState();
|
||||||
|
dialog.showMessageBoxSync(st ? st.win : null, {
|
||||||
|
type: 'error', title: '打开失败', message: '无法读取该文件', detail: String(err.message || err), buttons: ['好']
|
||||||
|
});
|
||||||
|
return { ok: false, error: String(err.message || err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('file:open', async (e) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
const r = await dialog.showOpenDialog(state ? state.win : null, {
|
||||||
|
title: '打开 Markdown 文件',
|
||||||
|
properties: ['openFile'],
|
||||||
|
filters: [
|
||||||
|
{ name: 'Markdown', extensions: ['md', 'markdown', 'mdown', 'mkd', 'mdwn', 'txt'] },
|
||||||
|
{ name: '所有文件', extensions: ['*'] }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
if (r.canceled || !r.filePaths.length) return { ok: false, canceled: true };
|
||||||
|
return openPathInternal(r.filePaths[0], state);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('file:openPath', async (e, p) => openPathInternal(p, stateOf(e.sender) || focusedState()));
|
||||||
|
|
||||||
|
/* 新窗口打开(右键菜单 / 菜单命令都走这里) */
|
||||||
|
ipcMain.handle('window:openPath', async (_e, p) => {
|
||||||
|
if (!p) return { ok: false };
|
||||||
|
try {
|
||||||
|
if (!fs.statSync(p).isFile()) return { ok: false };
|
||||||
|
} catch (_) { return { ok: false }; }
|
||||||
|
createWindow(p);
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('window:new', async () => {
|
||||||
|
createWindow();
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('app:getOpenMode', async () => openMode);
|
||||||
|
ipcMain.handle('app:setOpenMode', async (_e, mode) => {
|
||||||
|
await setOpenMode(mode);
|
||||||
|
return { ok: true, mode: openMode };
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------------------- 文件夹浏览 ---------------------- */
|
||||||
|
|
||||||
|
const MD_EXT = /\.(md|markdown|mdown|mkd|mdwn|txt)$/i;
|
||||||
|
const SKIP_DIRS = new Set(['node_modules', '$RECYCLE.BIN', 'System Volume Information']);
|
||||||
|
|
||||||
|
function listDir(dir) {
|
||||||
|
const entries = [];
|
||||||
|
let items;
|
||||||
|
try { items = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return entries; }
|
||||||
|
|
||||||
|
for (const d of items) {
|
||||||
|
if (d.name.startsWith('.')) continue;
|
||||||
|
if (SKIP_DIRS.has(d.name)) continue;
|
||||||
|
|
||||||
|
const full = path.join(dir, d.name);
|
||||||
|
let isDir = d.isDirectory();
|
||||||
|
if (!isDir && !d.isFile()) {
|
||||||
|
try { isDir = fs.statSync(full).isDirectory(); } catch (_) { continue; }
|
||||||
|
}
|
||||||
|
if (!isDir && !MD_EXT.test(d.name)) continue;
|
||||||
|
entries.push({ name: d.name, path: full, isDir });
|
||||||
|
}
|
||||||
|
entries.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function dirInfo(p) {
|
||||||
|
return { ok: true, path: p, name: path.basename(p) || p, entries: listDir(p) };
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('dir:open', async (e) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
const r = await dialog.showOpenDialog(state ? state.win : null, {
|
||||||
|
title: '打开文件夹', properties: ['openDirectory']
|
||||||
|
});
|
||||||
|
if (r.canceled || !r.filePaths.length) return { ok: false, canceled: true };
|
||||||
|
return dirInfo(r.filePaths[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => {
|
||||||
|
try { if (!fs.statSync(p).isDirectory()) return { ok: false }; } catch (_) { return { ok: false }; }
|
||||||
|
return dirInfo(p);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('file:save', async (e, payload) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
const { content, saveAs, eol } = payload;
|
||||||
|
let target = state && state.path;
|
||||||
|
|
||||||
|
if (!target || saveAs) {
|
||||||
|
const r = await dialog.showSaveDialog(state ? state.win : null, {
|
||||||
|
title: saveAs ? '另存为' : '保存',
|
||||||
|
defaultPath: target || path.join(app.getPath('documents'), '未命名.md'),
|
||||||
|
filters: [
|
||||||
|
{ name: 'Markdown', extensions: ['md'] },
|
||||||
|
{ name: '纯文本', extensions: ['txt'] },
|
||||||
|
{ name: '所有文件', extensions: ['*'] }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
if (r.canceled || !r.filePath) return { ok: false, canceled: true };
|
||||||
|
target = r.filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let text = content;
|
||||||
|
if (eol === '\r\n') text = text.replace(/\r?\n/g, '\r\n');
|
||||||
|
await fs.promises.writeFile(target, text, 'utf8');
|
||||||
|
if (state) { state.path = target; state.dirty = false; updateTitle(state); }
|
||||||
|
return { ok: true, path: target, name: path.basename(target) };
|
||||||
|
} catch (err) {
|
||||||
|
dialog.showMessageBoxSync(state ? state.win : null, {
|
||||||
|
type: 'error', title: '保存失败', message: '写入文件时出错', detail: String(err.message || err), buttons: ['好']
|
||||||
|
});
|
||||||
|
return { ok: false, error: String(err.message || err) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('file:reveal', async (e) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
const target = state && state.path;
|
||||||
|
if (!target) {
|
||||||
|
dialog.showMessageBoxSync(state ? state.win : null, {
|
||||||
|
type: 'info', title: '提示', message: '当前文件还没有保存到磁盘',
|
||||||
|
detail: '请先保存文件,之后即可打开它所在的文件夹。', buttons: ['好']
|
||||||
|
});
|
||||||
|
return { ok: false };
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(target)) {
|
||||||
|
dialog.showMessageBoxSync(state ? state.win : null, {
|
||||||
|
type: 'warning', title: '提示', message: '文件已不存在', detail: target, buttons: ['好']
|
||||||
|
});
|
||||||
|
return { ok: false };
|
||||||
|
}
|
||||||
|
shell.showItemInFolder(target);
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('clip:read', () => clipboard.readText());
|
||||||
|
ipcMain.handle('clip:write', (_e, text) => { clipboard.writeText(String(text ?? '')); return true; });
|
||||||
|
|
||||||
|
const nativeClip = require('./clipboard-native');
|
||||||
|
ipcMain.handle('file:copyFile', async (_e, paths) => {
|
||||||
|
try {
|
||||||
|
const list = (Array.isArray(paths) ? paths : [paths]).filter((p) => p && fs.existsSync(p));
|
||||||
|
if (!list.length) return { ok: false, error: '文件不存在' };
|
||||||
|
nativeClip.setFiles(list);
|
||||||
|
return { ok: true, count: list.length };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, error: String(err.message || err) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('file:readText', async (_e, p) => {
|
||||||
|
try { return { ok: true, text: readFileSmart(p).text }; } catch (_) { return { ok: false }; }
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('file:revealPath', async (_e, p) => {
|
||||||
|
try {
|
||||||
|
if (!p || !fs.existsSync(p)) return { ok: false, error: '文件不存在' };
|
||||||
|
const err = await shell.openPath(path.dirname(p));
|
||||||
|
if (!err) return { ok: true };
|
||||||
|
shell.showItemInFolder(p);
|
||||||
|
return { ok: true, fallback: true };
|
||||||
|
} catch (err) {
|
||||||
|
try { shell.showItemInFolder(p); return { ok: true, fallback: true }; }
|
||||||
|
catch (_) { return { ok: false, error: String(err.message || err) }; }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('shell:openExternal', (_e, url) => {
|
||||||
|
const u = String(url || '');
|
||||||
|
if (/^(https?|mailto):/i.test(u)) shell.openExternal(u);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
/* 拖放:作用于收到事件的那个窗口 */
|
||||||
|
ipcMain.on('file:drop', (e, p) => {
|
||||||
|
if (!p) return;
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
let isDir = false;
|
||||||
|
try { isDir = fs.statSync(p).isDirectory(); } catch (_) { return; }
|
||||||
|
|
||||||
|
if (isDir) {
|
||||||
|
sendTo(state, 'cmd', 'dir-opened', dirInfo(p));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const r = openPathInternal(p, state);
|
||||||
|
if (r.ok) sendTo(state, 'cmd', 'file-opened', r);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.on('file:droppedText', (e, payload) => {
|
||||||
|
sendTo(stateOf(e.sender) || focusedState(), 'cmd', 'dropped-text', {
|
||||||
|
name: payload && payload.name, text: (payload && payload.text) || ''
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('ui:message', async (e, opts) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
const r = await dialog.showMessageBox(state ? state.win : null, {
|
||||||
|
type: opts.type || 'info',
|
||||||
|
title: opts.title || '提示',
|
||||||
|
message: opts.message || '',
|
||||||
|
detail: opts.detail || '',
|
||||||
|
buttons: opts.buttons || ['好'],
|
||||||
|
noLink: true,
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: (opts.buttons || ['好']).length - 1
|
||||||
|
});
|
||||||
|
return r.response;
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.on('app:setDirty', (e, d) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
if (state) { state.dirty = !!d; updateTitle(state); }
|
||||||
|
});
|
||||||
|
|
||||||
|
/* 切标签 / 迁移后,渲染进程把当前激活的文档路径同步给主进程,
|
||||||
|
这样窗口标题和「保存=覆盖原文件」才不会错位 */
|
||||||
|
ipcMain.on('doc:syncPath', (e, p) => {
|
||||||
|
const state = stateOf(e.sender);
|
||||||
|
if (!state) return;
|
||||||
|
state.path = p || null;
|
||||||
|
updateTitle(state);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.on('win:setTitle', (e) => updateTitle(stateOf(e.sender) || focusedState()));
|
||||||
|
|
||||||
|
ipcMain.on('save:finished', (e, ok) => {
|
||||||
|
const state = stateOf(e.sender) || focusedState();
|
||||||
|
if (!state) return;
|
||||||
|
if (state.pendingClose && ok) {
|
||||||
|
state.pendingClose = false;
|
||||||
|
state.closing = true;
|
||||||
|
state.win.close();
|
||||||
|
} else if (!ok) {
|
||||||
|
state.pendingClose = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function updateTitle(state) {
|
||||||
|
if (!state || !state.win || state.win.isDestroyed()) return;
|
||||||
|
const name = state.path ? path.basename(state.path) : '未命名';
|
||||||
|
state.win.setTitle(`${state.dirty ? '● ' : ''}${name} — 小银 Markdown`);
|
||||||
|
state.win.setDocumentEdited(state.dirty);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 生命周期 ------------------------------ */
|
||||||
|
|
||||||
|
const gotLock = app.requestSingleInstanceLock();
|
||||||
|
if (!gotLock) {
|
||||||
|
app.quit();
|
||||||
|
} else {
|
||||||
|
app.on('second-instance', (_e, argv) => {
|
||||||
|
const arg = argv.find((a) => /\.(md|markdown|txt|mdown|mkd)$/i.test(a));
|
||||||
|
if (arg) {
|
||||||
|
if (openMode === 'windows') {
|
||||||
|
createWindow(arg);
|
||||||
|
} else {
|
||||||
|
const state = primaryState();
|
||||||
|
if (state) {
|
||||||
|
if (state.win.isMinimized()) state.win.restore();
|
||||||
|
state.win.focus();
|
||||||
|
sendTo(state, 'cmd', 'open-external', arg);
|
||||||
|
} else {
|
||||||
|
createWindow(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const state = primaryState();
|
||||||
|
if (state) {
|
||||||
|
if (state.win.isMinimized()) state.win.restore();
|
||||||
|
state.win.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.whenReady().then(() => {
|
||||||
|
loadPrefs();
|
||||||
|
buildMenu();
|
||||||
|
const arg = process.argv.find((a) => /\.(md|markdown|txt|mdown|mkd)$/i.test(a));
|
||||||
|
createWindow(arg || null);
|
||||||
|
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.on('window-all-closed', () => app.quit());
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 供迁移测试直接驱动 */
|
||||||
|
module.exports = {
|
||||||
|
windows,
|
||||||
|
setOpenMode,
|
||||||
|
getOpenMode: () => openMode
|
||||||
|
};
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
const { contextBridge, ipcRenderer, webUtils } = require('electron');
|
||||||
|
|
||||||
|
contextBridge.exposeInMainWorld('api', {
|
||||||
|
open: () => ipcRenderer.invoke('file:open'),
|
||||||
|
openPath: (p) => ipcRenderer.invoke('file:openPath', p),
|
||||||
|
save: (payload) => ipcRenderer.invoke('file:save', payload),
|
||||||
|
reveal: () => ipcRenderer.invoke('file:reveal'),
|
||||||
|
revealPath: (p) => ipcRenderer.invoke('file:revealPath', p),
|
||||||
|
copyFile: (p) => ipcRenderer.invoke('file:copyFile', p),
|
||||||
|
readFileText: (p) => ipcRenderer.invoke('file:readText', p),
|
||||||
|
readClipboard: () => ipcRenderer.invoke('clip:read'),
|
||||||
|
writeClipboard: (t) => ipcRenderer.invoke('clip:write', t),
|
||||||
|
openExternal: (url) => ipcRenderer.invoke('shell:openExternal', url),
|
||||||
|
dirOpen: () => ipcRenderer.invoke('dir:open'),
|
||||||
|
dirRead: (p) => ipcRenderer.invoke('dir:read', p),
|
||||||
|
openNewWindow: (p) => ipcRenderer.invoke('window:openPath', p),
|
||||||
|
newWindow: () => ipcRenderer.invoke('window:new'),
|
||||||
|
getOpenMode: () => ipcRenderer.invoke('app:getOpenMode'),
|
||||||
|
setOpenMode: (mode) => ipcRenderer.invoke('app:setOpenMode', mode),
|
||||||
|
exportDocs: (payload) => ipcRenderer.send('docs:exported', payload),
|
||||||
|
syncDoc: (p) => ipcRenderer.send('doc:syncPath', p),
|
||||||
|
setDirty: (d) => ipcRenderer.send('app:setDirty', d),
|
||||||
|
message: (o) => ipcRenderer.invoke('ui:message', o),
|
||||||
|
saveFinished: (ok) => ipcRenderer.send('save:finished', ok),
|
||||||
|
onCommand: (cb) => ipcRenderer.on('cmd', (_e, name, payload) => cb(name, payload))
|
||||||
|
});
|
||||||
|
|
||||||
|
/* 拖放:在 preload 上下文里取真实路径(Electron 32+ 已移除 File.path) */
|
||||||
|
window.addEventListener('dragover', (e) => { e.preventDefault(); });
|
||||||
|
|
||||||
|
window.addEventListener('drop', (e) => {
|
||||||
|
const dt = e.dataTransfer;
|
||||||
|
if (!dt) return;
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const files = dt.files ? Array.from(dt.files) : [];
|
||||||
|
if (!files.length) return;
|
||||||
|
|
||||||
|
// 逐个尝试取真实路径;取到第一个就送去开(文件或文件夹都行)
|
||||||
|
for (const file of files) {
|
||||||
|
let realPath = null;
|
||||||
|
try {
|
||||||
|
realPath = webUtils.getPathForFile(file);
|
||||||
|
} catch (_) { /* 拿不到就换兜底 */ }
|
||||||
|
|
||||||
|
if (realPath) {
|
||||||
|
ipcRenderer.send('file:drop', realPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兜底:完全拿不到路径时,按普通文件读取内容(目录会失败,忽略)
|
||||||
|
const first = files[0];
|
||||||
|
if (typeof first.text === 'function') {
|
||||||
|
first.text()
|
||||||
|
.then((text) => ipcRenderer.send('file:droppedText', { name: first.name, text }))
|
||||||
|
.catch(() => { /* 目录或不可读文件,忽略 */ });
|
||||||
|
}
|
||||||
|
});
|
||||||
+1494
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN" data-theme="light">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta http-equiv="Content-Security-Policy"
|
||||||
|
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: file: https: http:; font-src 'self' data:;">
|
||||||
|
<title>小银 Markdown</title>
|
||||||
|
<link rel="stylesheet" href="style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="app">
|
||||||
|
|
||||||
|
<!-- 工具栏 -->
|
||||||
|
<header class="toolbar">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="brand-name">小银 Markdown</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tb-sep"></div>
|
||||||
|
|
||||||
|
<div class="tb-group">
|
||||||
|
<button class="tb-btn" id="btn-new" title="新建 (Ctrl+N)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M9 1H4a1 1 0 00-1 1v12a1 1 0 001 1h8a1 1 0 001-1V5L9 1zm0 1.5L11.5 5H9V2.5z"/></svg>
|
||||||
|
<span>新建</span>
|
||||||
|
</button>
|
||||||
|
<button class="tb-btn" id="btn-open" title="打开文件 (Ctrl+O)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
|
||||||
|
<span>打开</span>
|
||||||
|
</button>
|
||||||
|
<button class="tb-btn primary" id="btn-save" title="保存 (Ctrl+S)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M2 2h9l3 3v9a1 1 0 01-1 1H3a1 1 0 01-1-1V2zm2 0v4h7V2H4zm1 7h6v5H5V9z"/></svg>
|
||||||
|
<span>保存</span>
|
||||||
|
</button>
|
||||||
|
<button class="tb-btn" id="btn-saveas" title="另存为 (Ctrl+Shift+S)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M8 1v7m0 0L5.5 5.5M8 8l2.5-2.5M2 10v3a1 1 0 001 1h10a1 1 0 001-1v-3"/></svg>
|
||||||
|
<span>另存为</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tb-sep"></div>
|
||||||
|
|
||||||
|
<div class="tb-group">
|
||||||
|
<button class="tb-icon" id="btn-undo" title="撤销 (Ctrl+Z)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M6 3.5L2 7l4 3.5V8h4a3 3 0 010 6H5v1.5h5a4.5 4.5 0 000-9H6V3.5z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-icon" id="btn-redo" title="重做 (Ctrl+Y)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M10 3.5L14 7l-4 3.5V8H6a3 3 0 000 6h4v1.5H6a4.5 4.5 0 010-9h4V3.5z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-icon" id="btn-find" title="查找 (Ctrl+F)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M6.5 1a5.5 5.5 0 014.2 9.05l4.1 4.1-1.05 1.05-4.1-4.1A5.5 5.5 0 116.5 1zm0 1.5a4 4 0 100 8 4 4 0 000-8z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-icon" id="btn-copyall" title="复制全文 (Ctrl+Shift+C)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M5 1h7a1 1 0 011 1v9h-1.5V2.5H5V1zM3 3.5h7a1 1 0 011 1V14a1 1 0 01-1 1H3a1 1 0 01-1-1V4.5a1 1 0 011-1z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-icon" id="btn-dir" title="打开文件所在文件夹 (Ctrl+Shift+O)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="spacer"></div>
|
||||||
|
|
||||||
|
<button class="tb-btn toggle" id="btn-tree" title="显示 / 隐藏文件目录 (Ctrl+Shift+B)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3.2l1.4 1.8H14a1 1 0 011 1v1.2H1.5V3.5zM1.5 7.2H15v5.3a1 1 0 01-1 1H2.5a1 1 0 01-1-1V7.2z"/></svg>
|
||||||
|
<span>目录</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="seg" id="mode-seg">
|
||||||
|
<button data-mode="edit" title="编辑模式 (Ctrl+1)">编辑</button>
|
||||||
|
<button data-mode="split" class="active" title="分栏模式 (Ctrl+2)">分栏</button>
|
||||||
|
<button data-mode="read" title="阅读模式 (Ctrl+3)">阅读</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button class="tb-btn toggle" id="btn-outline" title="显示 / 隐藏章节大纲 (Ctrl+Shift+T)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M2 3.2h1.8v1.3H2V3.2zm3.4 0H14v1.3H5.4V3.2zM2 7.35h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4V7.35zM2 11.5h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4v-1.3z"/></svg>
|
||||||
|
<span>大纲</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button class="tb-btn" id="btn-openmode" title="文档打开方式:标签页 / 独立窗口(点击切换)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M1.5 2.5h13v11h-13z" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M5 2.5v11M2.5 5h1.8M2.5 8h1.8M2.5 11h1.8" stroke="currentColor" stroke-width="1.2"/></svg>
|
||||||
|
<span id="openmode-label">标签</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button class="tb-icon" id="btn-theme" title="切换深色/浅色 (Ctrl+Shift+L)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M8 1a7 7 0 100 14A7 7 0 008 1zm0 1.5v11a5.5 5.5 0 010-11z"/></svg>
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- 标签栏(标签页模式下显示) -->
|
||||||
|
<div class="tabbar" id="tabbar"></div>
|
||||||
|
|
||||||
|
<!-- 查找条 -->
|
||||||
|
<div class="findbar" id="findbar" hidden>
|
||||||
|
<input type="text" id="find-input" placeholder="查找内容…" spellcheck="false">
|
||||||
|
<span class="find-count" id="find-count"></span>
|
||||||
|
<button id="find-prev" title="上一个 (Shift+Enter)">↑</button>
|
||||||
|
<button id="find-next" title="下一个 (Enter)">↓</button>
|
||||||
|
<button id="find-close" title="关闭 (Esc)">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 工作区 -->
|
||||||
|
<main class="workspace" id="workspace" data-mode="split">
|
||||||
|
<aside class="sidebar" id="sidebar" hidden>
|
||||||
|
<div class="panel-head">
|
||||||
|
<svg class="panel-ico" viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3.2l1.4 1.8H14a1 1 0 011 1v1.2H1.5V3.5zM1.5 7.2H15v5.3a1 1 0 01-1 1H2.5a1 1 0 01-1-1V7.2z"/></svg>
|
||||||
|
<span class="panel-title" id="sb-title">目录</span>
|
||||||
|
<span class="panel-actions">
|
||||||
|
<button class="sb-btn" id="sb-pick" title="选择文件夹 (Ctrl+Shift+K)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M1.5 3.5A1.5 1.5 0 013 2h3l1.5 2H14a1 1 0 011 1v7a1 1 0 01-1 1H2a1 1 0 01-1-1V3.5z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="sb-btn" id="sb-close" title="隐藏文件目录 (Ctrl+Shift+B)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M3.4 2.6L8 7.2l4.6-4.6 1.1 1.1L9.1 8.3l4.6 4.6-1.1 1.1L8 9.4l-4.6 4.6-1.1-1.1 4.6-4.6-4.6-4.6z"/></svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="sb-body" id="sb-body"></div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="vsplitter" id="sb-splitter" title="拖动调整目录宽度"></div>
|
||||||
|
|
||||||
|
<section class="pane editor-pane" id="editor-pane">
|
||||||
|
<div class="editor-wrap">
|
||||||
|
<div class="editor-hl" id="editor-hl" aria-hidden="true"></div>
|
||||||
|
<textarea id="editor" spellcheck="false" autocomplete="off"
|
||||||
|
placeholder="在这里写 Markdown… 也可以把 .md 文件直接拖进窗口。"></textarea>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="splitter" id="splitter" title="拖动调整宽度"></div>
|
||||||
|
|
||||||
|
<section class="pane preview-pane" id="preview-pane">
|
||||||
|
<article class="markdown-body" id="preview"></article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="vsplitter" id="ol-splitter" title="拖动调整大纲宽度"></div>
|
||||||
|
|
||||||
|
<aside class="outline" id="outline">
|
||||||
|
<div class="panel-head">
|
||||||
|
<svg class="panel-ico" viewBox="0 0 16 16"><path d="M2 3.2h1.8v1.3H2V3.2zm3.4 0H14v1.3H5.4V3.2zM2 7.35h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4V7.35zM2 11.5h1.8v1.3H2v-1.3zm3.4 0H14v1.3H5.4v-1.3z"/></svg>
|
||||||
|
<span class="panel-title">章节大纲</span>
|
||||||
|
<span class="ol-count" id="ol-count">0</span>
|
||||||
|
<button class="sb-btn" id="ol-close" title="隐藏章节大纲 (Ctrl+Shift+T)">
|
||||||
|
<svg viewBox="0 0 16 16"><path d="M3.4 2.6L8 7.2l4.6-4.6 1.1 1.1L9.1 8.3l4.6 4.6-1.1 1.1L8 9.4l-4.6 4.6-1.1-1.1 4.6-4.6-4.6-4.6z"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="ol-body" id="ol-body"></div>
|
||||||
|
</aside>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 状态栏 -->
|
||||||
|
<footer class="statusbar">
|
||||||
|
<div class="st-left">
|
||||||
|
<span class="st-file" id="st-file">未命名</span>
|
||||||
|
<span class="st-dirty" id="st-dirty" hidden>未保存</span>
|
||||||
|
</div>
|
||||||
|
<div class="st-right">
|
||||||
|
<span id="st-words">0 字</span>
|
||||||
|
<span class="st-div">|</span>
|
||||||
|
<span id="st-chars">0 字符</span>
|
||||||
|
<span class="st-div">|</span>
|
||||||
|
<span id="st-cursor">第 1 行, 第 1 列</span>
|
||||||
|
<span class="st-div">|</span>
|
||||||
|
<span>UTF-8</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- 右键菜单 -->
|
||||||
|
<div class="ctx-menu" id="ctxmenu" hidden></div>
|
||||||
|
<div class="toast" id="toast" hidden></div>
|
||||||
|
<div class="drop-hint" id="drop-hint" hidden><div>松开鼠标:文件直接打开,文件夹列出目录</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="markdown.js"></script>
|
||||||
|
<script src="tauri-bridge.js"></script>
|
||||||
|
<script src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
/*
|
||||||
|
* 轻量 Markdown 渲染引擎(零依赖,纯本地)
|
||||||
|
* 支持:标题 / 粗体 / 斜体 / 删除线 / 行内代码 / 代码块 / 引用 / 有序无序列表 /
|
||||||
|
* 嵌套列表 / 任务列表 / 表格(含对齐)/ 分割线 / 链接 / 图片 / 自动链接
|
||||||
|
* 所有原始 HTML 均被转义,避免脚本注入。
|
||||||
|
*/
|
||||||
|
(function (global) {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const ESC_MAP = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||||
|
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
|
||||||
|
|
||||||
|
function safeUrl(u) {
|
||||||
|
const t = String(u).trim();
|
||||||
|
const flat = t.replace(/[\s\u0000-\u001f]/g, '');
|
||||||
|
if (/^(javascript|vbscript|data):/i.test(flat)) return '#';
|
||||||
|
return escapeHtml(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
const PH = '\u0000';
|
||||||
|
|
||||||
|
/* ------------------------- 行内渲染 ------------------------- */
|
||||||
|
function renderInline(text) {
|
||||||
|
let s = escapeHtml(text);
|
||||||
|
const slots = [];
|
||||||
|
const put = (html) => { slots.push(html); return PH + (slots.length - 1) + PH; };
|
||||||
|
|
||||||
|
// 行内代码(先摘出来,避免内部语法被解析)
|
||||||
|
s = s.replace(/(`+)([\s\S]*?)\1/g, (_m, _t, code) => put('<code>' + code.replace(/^ | $/g, '') + '</code>'));
|
||||||
|
|
||||||
|
// 图片
|
||||||
|
s = s.replace(/!\[([^\]]*)\]\(\s*([^\s)]+)\s*\)/g,
|
||||||
|
(_m, alt, src) => put('<img src="' + safeUrl(src) + '" alt="' + alt + '" loading="lazy">'));
|
||||||
|
|
||||||
|
// 链接
|
||||||
|
s = s.replace(/\[([^\]]+)\]\(\s*([^\s)]+)\s*\)/g,
|
||||||
|
(_m, label, href) => put('<a href="' + safeUrl(href) + '" title="' + href + '">' + label + '</a>'));
|
||||||
|
|
||||||
|
// 裸链接
|
||||||
|
s = s.replace(/(^|[\s(])(https?:\/\/[^\s<)\]]+)/g,
|
||||||
|
(_m, pre, url) => pre + put('<a href="' + safeUrl(url) + '">' + url + '</a>'));
|
||||||
|
|
||||||
|
// 强调
|
||||||
|
s = s.replace(/\*\*\*([^*\n]+)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||||
|
s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
|
||||||
|
s = s.replace(/(^|[^\w_])__([^_\n]+)__/g, '$1<strong>$2</strong>');
|
||||||
|
s = s.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
|
||||||
|
s = s.replace(/(^|[^\w_])_([^_\n]+)_/g, '$1<em>$2</em>');
|
||||||
|
s = s.replace(/~~([^~\n]+)~~/g, '<del>$1</del>');
|
||||||
|
|
||||||
|
// 还原占位符
|
||||||
|
s = s.replace(/\u0000(\d+)\u0000/g, (_m, i) => slots[Number(i)]);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
function inlineWithBreaks(text) {
|
||||||
|
return renderInline(text).replace(/\n/g, '<br>');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------- 块级解析 ------------------------- */
|
||||||
|
const RE_FENCE = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)\s*$/;
|
||||||
|
const RE_HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
|
||||||
|
const RE_HR = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
|
||||||
|
const RE_QUOTE = /^\s{0,3}>\s?/;
|
||||||
|
const RE_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])(\s+)(.*)$/;
|
||||||
|
const RE_TASK = /^\[([ xX])\]\s+/;
|
||||||
|
|
||||||
|
function isTableSep(line) {
|
||||||
|
if (!line || !line.includes('|')) return false;
|
||||||
|
const cells = splitRow(line);
|
||||||
|
return cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(c.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitRow(line) {
|
||||||
|
let s = line.trim();
|
||||||
|
if (s.startsWith('|')) s = s.slice(1);
|
||||||
|
if (s.endsWith('|')) s = s.slice(0, -1);
|
||||||
|
return s.split('|').map((c) => c.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBlocks(lines, base) {
|
||||||
|
base = base || 0;
|
||||||
|
const out = [];
|
||||||
|
let i = 0;
|
||||||
|
|
||||||
|
while (i < lines.length) {
|
||||||
|
const line = lines[i];
|
||||||
|
|
||||||
|
// 空行
|
||||||
|
if (/^\s*$/.test(line)) { i++; continue; }
|
||||||
|
|
||||||
|
// 代码块
|
||||||
|
let m = RE_FENCE.exec(line);
|
||||||
|
if (m) {
|
||||||
|
const fenceChar = m[2][0];
|
||||||
|
const fenceLen = m[2].length;
|
||||||
|
const lang = m[3] || '';
|
||||||
|
const closer = new RegExp('^\\s*' + (fenceChar === '`' ? '`' : '~') + '{' + fenceLen + ',}\\s*$');
|
||||||
|
const buf = [];
|
||||||
|
i++;
|
||||||
|
while (i < lines.length && !closer.test(lines[i])) { buf.push(lines[i]); i++; }
|
||||||
|
i++; // 跳过闭合行
|
||||||
|
out.push(
|
||||||
|
'<div class="code-wrap">' +
|
||||||
|
(lang ? '<span class="code-lang">' + escapeHtml(lang) + '</span>' : '') +
|
||||||
|
'<pre><code>' + escapeHtml(buf.join('\n')) + '</code></pre></div>'
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分割线
|
||||||
|
if (RE_HR.test(line)) { out.push('<hr>'); i++; continue; }
|
||||||
|
|
||||||
|
// 标题(带原始行号,供大纲跳转用)
|
||||||
|
m = RE_HEADING.exec(line);
|
||||||
|
if (m) {
|
||||||
|
const lv = m[1].length;
|
||||||
|
out.push('<h' + lv + ' data-line="' + (base + i) + '">' + renderInline(m[2]) + '</h' + lv + '>');
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 引用
|
||||||
|
if (RE_QUOTE.test(line)) {
|
||||||
|
const buf = [];
|
||||||
|
const startAt = i;
|
||||||
|
while (i < lines.length && RE_QUOTE.test(lines[i])) {
|
||||||
|
buf.push(lines[i].replace(RE_QUOTE, ''));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
out.push('<blockquote>' + parseBlocks(buf, base + startAt) + '</blockquote>');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 表格
|
||||||
|
if (line.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1])) {
|
||||||
|
const head = splitRow(line);
|
||||||
|
const aligns = splitRow(lines[i + 1]).map((c) => {
|
||||||
|
const t = c.trim();
|
||||||
|
if (/^:-+:$/.test(t)) return 'center';
|
||||||
|
if (/^:-+$/.test(t)) return 'left';
|
||||||
|
if (/^-+:$/.test(t)) return 'right';
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
i += 2;
|
||||||
|
const rows = [];
|
||||||
|
while (i < lines.length && lines[i].includes('|') && !/^\s*$/.test(lines[i])) {
|
||||||
|
rows.push(splitRow(lines[i]));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
const cell = (tag, txt, idx) => {
|
||||||
|
const al = aligns[idx] ? ' style="text-align:' + aligns[idx] + '"' : '';
|
||||||
|
return '<' + tag + al + '>' + renderInline(txt) + '</' + tag + '>';
|
||||||
|
};
|
||||||
|
let html = '<div class="table-wrap"><table><thead><tr>';
|
||||||
|
head.forEach((c, idx) => { html += cell('th', c, idx); });
|
||||||
|
html += '</tr></thead><tbody>';
|
||||||
|
rows.forEach((r) => {
|
||||||
|
html += '<tr>';
|
||||||
|
for (let k = 0; k < head.length; k++) html += cell('td', r[k] == null ? '' : r[k], k);
|
||||||
|
html += '</tr>';
|
||||||
|
});
|
||||||
|
html += '</tbody></table></div>';
|
||||||
|
out.push(html);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 列表
|
||||||
|
if (RE_ITEM.test(line)) {
|
||||||
|
const r = parseList(lines, i, base);
|
||||||
|
out.push(r.html);
|
||||||
|
i = r.next;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 段落
|
||||||
|
const buf = [];
|
||||||
|
while (i < lines.length && !/^\s*$/.test(lines[i])) {
|
||||||
|
const l = lines[i];
|
||||||
|
if (RE_FENCE.test(l) || RE_HEADING.test(l) || RE_HR.test(l) || RE_QUOTE.test(l) || RE_ITEM.test(l)) break;
|
||||||
|
if (l.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1])) break;
|
||||||
|
buf.push(l);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (buf.length) out.push('<p>' + inlineWithBreaks(buf.join('\n')) + '</p>');
|
||||||
|
else i++; // 防死循环
|
||||||
|
}
|
||||||
|
|
||||||
|
return out.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseList(lines, start, base) {
|
||||||
|
base = base || 0;
|
||||||
|
const m0 = RE_ITEM.exec(lines[start]);
|
||||||
|
const baseIndent = m0[1].length;
|
||||||
|
const ordered = /\d/.test(m0[2]);
|
||||||
|
const startNum = ordered ? parseInt(m0[2], 10) : 1;
|
||||||
|
|
||||||
|
const items = [];
|
||||||
|
let i = start;
|
||||||
|
|
||||||
|
while (i < lines.length) {
|
||||||
|
const m = RE_ITEM.exec(lines[i]);
|
||||||
|
if (!m || m[1].length !== baseIndent || (/\d/.test(m[2])) !== ordered) break;
|
||||||
|
|
||||||
|
const contentIndent = m[1].length + m[2].length + m[3].length;
|
||||||
|
const content = m[4];
|
||||||
|
i++;
|
||||||
|
|
||||||
|
// 收集该列表项的后续行(子内容)
|
||||||
|
const children = [];
|
||||||
|
let childStart = -1;
|
||||||
|
while (i < lines.length) {
|
||||||
|
const l = lines[i];
|
||||||
|
if (/^\s*$/.test(l)) {
|
||||||
|
let j = i;
|
||||||
|
while (j < lines.length && /^\s*$/.test(lines[j])) j++;
|
||||||
|
if (j < lines.length) {
|
||||||
|
const ind = lines[j].match(/^[ \t]*/)[0].length;
|
||||||
|
if (ind >= contentIndent || (RE_ITEM.test(lines[j]) && ind > baseIndent)) {
|
||||||
|
if (childStart < 0) childStart = i;
|
||||||
|
for (let k = i; k < j; k++) children.push('');
|
||||||
|
i = j;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const ind = l.match(/^[ \t]*/)[0].length;
|
||||||
|
if (ind >= contentIndent) {
|
||||||
|
if (childStart < 0) childStart = i;
|
||||||
|
children.push(l.slice(Math.min(ind, contentIndent)));
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ind > baseIndent) {
|
||||||
|
if (childStart < 0) childStart = i;
|
||||||
|
children.push(l.trim());
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
items.push({ content, children, childStart });
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = ordered
|
||||||
|
? '<ol' + (startNum !== 1 ? ' start="' + startNum + '"' : '') + '>'
|
||||||
|
: '<ul>';
|
||||||
|
|
||||||
|
for (const it of items) {
|
||||||
|
let inner;
|
||||||
|
let cls = '';
|
||||||
|
const task = RE_TASK.exec(it.content);
|
||||||
|
if (task) {
|
||||||
|
const checked = task[1].toLowerCase() === 'x';
|
||||||
|
inner = '<input type="checkbox" disabled' + (checked ? ' checked' : '') + '> ' +
|
||||||
|
renderInline(it.content.replace(RE_TASK, ''));
|
||||||
|
cls = ' class="task-item"';
|
||||||
|
} else {
|
||||||
|
inner = renderInline(it.content);
|
||||||
|
}
|
||||||
|
html += '<li' + cls + '>' + inner;
|
||||||
|
if (it.children.length) {
|
||||||
|
html += parseBlocks(it.children, base + (it.childStart >= 0 ? it.childStart : 0));
|
||||||
|
}
|
||||||
|
html += '</li>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += ordered ? '</ol>' : '</ul>';
|
||||||
|
return { html, next: i };
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(md) {
|
||||||
|
const lines = String(md == null ? '' : md).replace(/\r\n?/g, '\n').split('\n');
|
||||||
|
return parseBlocks(lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------- 统计信息 ------------------------- */
|
||||||
|
function stats(md) {
|
||||||
|
const text = String(md || '');
|
||||||
|
const cjk = (text.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g) || []).length;
|
||||||
|
const words = (text.replace(/[\u4e00-\u9fa5\u3040-\u30ff]/g, ' ').match(/[A-Za-z0-9_'’-]+/g) || []).length;
|
||||||
|
const lines = text.split('\n').length;
|
||||||
|
const headings = (text.match(/^\s{0,3}#{1,6}\s+\S/gm) || []).length;
|
||||||
|
return { chars: text.length, words: cjk + words, lines, headings };
|
||||||
|
}
|
||||||
|
|
||||||
|
global.MD = { render, stats, escapeHtml };
|
||||||
|
})(window);
|
||||||
@@ -0,0 +1,795 @@
|
|||||||
|
/* ============ 主题变量 ============ */
|
||||||
|
:root {
|
||||||
|
--bg: #ffffff;
|
||||||
|
--bg-soft: #f7f8fa;
|
||||||
|
--bg-toolbar: #fbfbfc;
|
||||||
|
--bg-hover: #eef1f5;
|
||||||
|
--bg-active: #e3e9f2;
|
||||||
|
--border: #e4e7ec;
|
||||||
|
--border-strong: #d3d8e0;
|
||||||
|
--text: #1f2329;
|
||||||
|
--text-dim: #6b7280;
|
||||||
|
--text-faint: #9aa1ac;
|
||||||
|
--accent: #2f6feb;
|
||||||
|
--accent-soft: #e8f0ff;
|
||||||
|
--accent-text: #ffffff;
|
||||||
|
--danger: #d14343;
|
||||||
|
--code-bg: #f2f4f7;
|
||||||
|
--code-block-bg: #f6f8fa;
|
||||||
|
--quote-bar: #d0d7e2;
|
||||||
|
--shadow: 0 8px 28px rgba(15, 23, 42, .14);
|
||||||
|
--shadow-sm: 0 1px 2px rgba(15, 23, 42, .06);
|
||||||
|
--font-ui: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||||
|
--font-mono: "Cascadia Code", "JetBrains Mono", Consolas, "Courier New", monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] {
|
||||||
|
--bg: #1b1c1f;
|
||||||
|
--bg-soft: #202226;
|
||||||
|
--bg-toolbar: #1e2024;
|
||||||
|
--bg-hover: #2a2d33;
|
||||||
|
--bg-active: #32363d;
|
||||||
|
--border: #2e3238;
|
||||||
|
--border-strong: #3b4048;
|
||||||
|
--text: #e6e8ec;
|
||||||
|
--text-dim: #9aa3ae;
|
||||||
|
--text-faint: #6f7782;
|
||||||
|
--accent: #4f8ef7;
|
||||||
|
--accent-soft: #1e2c44;
|
||||||
|
--accent-text: #ffffff;
|
||||||
|
--danger: #ef6b6b;
|
||||||
|
--code-bg: #262a30;
|
||||||
|
--code-block-bg: #22252a;
|
||||||
|
--quote-bar: #3d434c;
|
||||||
|
--shadow: 0 8px 28px rgba(0, 0, 0, .5);
|
||||||
|
--shadow-sm: 0 1px 2px rgba(0, 0, 0, .3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============ 基础 ============ */
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: var(--font-ui);
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--bg);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: inherit;
|
||||||
|
color: inherit;
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============ 工具栏 ============ */
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
height: 50px;
|
||||||
|
flex: 0 0 50px;
|
||||||
|
padding: 0 10px;
|
||||||
|
background: var(--bg-toolbar);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding-right: 8px;
|
||||||
|
margin-right: 4px;
|
||||||
|
-webkit-app-region: drag;
|
||||||
|
}
|
||||||
|
.brand-name {
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tb-group { display: flex; align-items: center; gap: 2px; }
|
||||||
|
|
||||||
|
.tb-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 9px;
|
||||||
|
border-radius: 7px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
transition: background .12s, color .12s;
|
||||||
|
}
|
||||||
|
.tb-btn svg { width: 15px; height: 15px; fill: currentColor; }
|
||||||
|
.tb-btn span { font-size: 12.5px; }
|
||||||
|
.tb-btn:hover { background: var(--bg-hover); color: var(--text); }
|
||||||
|
.tb-btn:active { background: var(--bg-active); }
|
||||||
|
.tb-btn.on { background: var(--accent-soft); color: var(--accent); }
|
||||||
|
.tb-btn.primary { color: var(--accent); }
|
||||||
|
.tb-btn.primary:hover { background: var(--accent-soft); }
|
||||||
|
|
||||||
|
.tb-icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 30px; height: 30px;
|
||||||
|
border-radius: 7px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
transition: background .12s, color .12s;
|
||||||
|
}
|
||||||
|
.tb-icon svg { width: 15px; height: 15px; fill: currentColor; }
|
||||||
|
.tb-icon:hover { background: var(--bg-hover); color: var(--text); }
|
||||||
|
.tb-icon:active { background: var(--bg-active); }
|
||||||
|
.tb-icon.disabled { opacity: .35; pointer-events: none; }
|
||||||
|
|
||||||
|
.tb-sep {
|
||||||
|
width: 1px;
|
||||||
|
height: 20px;
|
||||||
|
margin: 0 4px;
|
||||||
|
background: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.spacer { flex: 1; }
|
||||||
|
|
||||||
|
/* 分段控件 */
|
||||||
|
.seg {
|
||||||
|
display: flex;
|
||||||
|
padding: 2px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.seg button {
|
||||||
|
height: 24px;
|
||||||
|
padding: 0 11px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
transition: background .12s, color .12s;
|
||||||
|
}
|
||||||
|
.seg button:hover { color: var(--text); }
|
||||||
|
.seg button.active {
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 600;
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .seg button.active { background: var(--bg-active); }
|
||||||
|
|
||||||
|
/* ============ 标签栏 ============ */
|
||||||
|
.tabbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
flex: 0 0 32px;
|
||||||
|
height: 32px;
|
||||||
|
overflow-x: auto;
|
||||||
|
overflow-y: hidden;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.tabbar[hidden] { display: none; }
|
||||||
|
.tabbar::-webkit-scrollbar { height: 5px; }
|
||||||
|
.tabbar::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 3px; }
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
min-width: 118px;
|
||||||
|
max-width: 230px;
|
||||||
|
padding: 0 8px 0 12px;
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
border-top: 2px solid transparent;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.tab:hover { background: var(--bg-hover); }
|
||||||
|
.tab.active {
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
border-top-color: var(--accent);
|
||||||
|
}
|
||||||
|
.tab .tab-name {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tab .tab-dot {
|
||||||
|
flex: 0 0 6px;
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
.tab.dirty .tab-dot { opacity: 1; }
|
||||||
|
.tab .tab-close {
|
||||||
|
flex: 0 0 16px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: var(--text-faint);
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.tab .tab-close:hover { background: var(--bg-active); color: var(--text); }
|
||||||
|
.tab .tab-close svg { width: 9px; height: 9px; fill: currentColor; }
|
||||||
|
|
||||||
|
/* ============ 查找条 ============ */
|
||||||
|
.findbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.findbar[hidden] { display: none; }
|
||||||
|
.findbar input {
|
||||||
|
flex: 1;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: var(--font-ui);
|
||||||
|
font-size: 12.5px;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.findbar input:focus { border-color: var(--accent); }
|
||||||
|
.find-count { font-size: 11.5px; color: var(--text-faint); min-width: 62px; }
|
||||||
|
.findbar button {
|
||||||
|
width: 26px; height: 26px;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.findbar button:hover { background: var(--bg-hover); color: var(--text); }
|
||||||
|
|
||||||
|
/* ============ 工作区 ============ */
|
||||||
|
.workspace {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pane {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============ 文件树侧栏 ============ */
|
||||||
|
.sidebar {
|
||||||
|
flex: 0 0 232px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border-left: 1px solid var(--border);
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.sidebar[hidden] { display: none; }
|
||||||
|
|
||||||
|
/* 面板头部(文件目录 / 章节大纲 共用,保证视觉统一) */
|
||||||
|
.panel-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
flex: 0 0 34px;
|
||||||
|
padding: 0 6px 0 12px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.panel-ico {
|
||||||
|
flex: 0 0 13px;
|
||||||
|
width: 13px;
|
||||||
|
height: 13px;
|
||||||
|
fill: var(--text-faint);
|
||||||
|
}
|
||||||
|
.panel-title {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-dim);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.panel-actions { display: flex; gap: 2px; flex: 0 0 auto; margin-left: auto; }
|
||||||
|
.sb-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 24px; height: 24px;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--text-faint);
|
||||||
|
}
|
||||||
|
.sb-btn svg { width: 13px; height: 13px; fill: currentColor; }
|
||||||
|
.sb-btn:hover { background: var(--bg-hover); color: var(--text); }
|
||||||
|
|
||||||
|
.sb-body {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
padding: 6px 0 24px;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.tree-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
height: 26px;
|
||||||
|
padding-right: 8px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text);
|
||||||
|
white-space: nowrap;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.tree-row:hover { background: var(--bg-hover); }
|
||||||
|
.tree-row:focus { outline: none; background: var(--bg-active); }
|
||||||
|
.tree-row:focus.active { background: var(--accent-soft); }
|
||||||
|
.tree-row.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
|
||||||
|
.tree-row .twisty {
|
||||||
|
flex: 0 0 12px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 9px;
|
||||||
|
line-height: 1;
|
||||||
|
color: var(--text-faint);
|
||||||
|
}
|
||||||
|
.tree-row.is-dir .tree-name { font-weight: 500; }
|
||||||
|
.tree-row .tree-name { overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.tree-empty { padding: 5px 12px 5px 30px; font-size: 11.5px; color: var(--text-faint); }
|
||||||
|
.sb-tip {
|
||||||
|
padding: 26px 16px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.7;
|
||||||
|
color: var(--text-faint);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.sb-tip-sub { margin-top: 6px; font-size: 11.5px; color: var(--text-faint); opacity: .85; }.sb-pick-btn {
|
||||||
|
margin-top: 14px;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 16px;
|
||||||
|
border-radius: 7px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-text);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.sb-pick-btn:hover { filter: brightness(1.06); }
|
||||||
|
.sb-pick-btn:active { filter: brightness(.94); }
|
||||||
|
|
||||||
|
/* ============ 章节大纲 ============ */
|
||||||
|
.outline {
|
||||||
|
flex: 0 0 210px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border-left: 1px solid var(--border);
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.outline[hidden] { display: none; }
|
||||||
|
|
||||||
|
.ol-count {
|
||||||
|
margin-left: auto;
|
||||||
|
padding: 1px 7px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--bg-hover);
|
||||||
|
font-size: 10.5px;
|
||||||
|
color: var(--text-faint);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ol-body {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
padding: 6px 0 24px;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.ol-item {
|
||||||
|
padding: 4px 10px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: var(--text-dim);
|
||||||
|
border-left: 2px solid transparent;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.ol-item:hover { background: var(--bg-hover); color: var(--text); }
|
||||||
|
.ol-item.active {
|
||||||
|
color: var(--accent);
|
||||||
|
border-left-color: var(--accent);
|
||||||
|
background: var(--accent-soft);
|
||||||
|
}
|
||||||
|
.ol-item[data-level="1"] { color: var(--text); font-weight: 600; }
|
||||||
|
.ol-item[data-level="1"].active { color: var(--accent); }
|
||||||
|
.ol-empty {
|
||||||
|
padding: 22px 14px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.7;
|
||||||
|
color: var(--text-faint);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-pane { flex: 1; position: relative; }
|
||||||
|
|
||||||
|
/* 编辑器查找高亮叠加层:文字透明只显示 mark 背景,随编辑器滚动 */
|
||||||
|
.editor-wrap {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.editor-hl {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
padding: 18px 22px;
|
||||||
|
color: transparent;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 13.5px;
|
||||||
|
line-height: 1.7;
|
||||||
|
tab-size: 4;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-wrap: break-word;
|
||||||
|
overflow: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.editor-hl mark {
|
||||||
|
background: rgba(255, 193, 7, .32);
|
||||||
|
color: transparent;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
.editor-hl mark.find-hit-active {
|
||||||
|
background: rgba(255, 159, 10, .55);
|
||||||
|
}
|
||||||
|
|
||||||
|
#editor {
|
||||||
|
flex: 1;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
padding: 18px 22px;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
resize: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 13.5px;
|
||||||
|
line-height: 1.7;
|
||||||
|
tab-size: 4;
|
||||||
|
overflow-y: auto;
|
||||||
|
user-select: text;
|
||||||
|
caret-color: var(--accent);
|
||||||
|
}
|
||||||
|
#editor::placeholder { color: var(--text-faint); }
|
||||||
|
|
||||||
|
.splitter {
|
||||||
|
flex: 0 0 1px;
|
||||||
|
background: var(--border);
|
||||||
|
cursor: col-resize;
|
||||||
|
position: relative;
|
||||||
|
transition: background .15s;
|
||||||
|
}
|
||||||
|
.splitter::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: 0; bottom: 0;
|
||||||
|
left: -3px; right: -3px;
|
||||||
|
}
|
||||||
|
.splitter:hover, .splitter.dragging { background: var(--accent); }
|
||||||
|
|
||||||
|
/* 侧栏 / 大纲的可拖拽分隔条 */
|
||||||
|
.vsplitter {
|
||||||
|
flex: 0 0 1px;
|
||||||
|
background: var(--border);
|
||||||
|
cursor: col-resize;
|
||||||
|
position: relative;
|
||||||
|
transition: background .15s;
|
||||||
|
}
|
||||||
|
.vsplitter::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: 0; bottom: 0;
|
||||||
|
left: -3px; right: -3px;
|
||||||
|
}
|
||||||
|
.vsplitter:hover, .vsplitter.dragging { background: var(--accent); }
|
||||||
|
.vsplitter[hidden] { display: none; }
|
||||||
|
|
||||||
|
.preview-pane {
|
||||||
|
flex: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 模式切换 */
|
||||||
|
.workspace[data-mode="edit"] .preview-pane,
|
||||||
|
.workspace[data-mode="edit"] .splitter { display: none; }
|
||||||
|
.workspace[data-mode="read"] .editor-pane,
|
||||||
|
.workspace[data-mode="read"] .splitter { display: none; }
|
||||||
|
|
||||||
|
/* ============ 预览排版 ============ */
|
||||||
|
|
||||||
|
/* 查找:正文关键字背景标记 */
|
||||||
|
#preview mark.find-hit {
|
||||||
|
background: rgba(255, 193, 7, .45);
|
||||||
|
color: inherit;
|
||||||
|
padding: 0 1px;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
#preview mark.find-hit.find-hit-active {
|
||||||
|
background: #ff9f0a;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.markdown-body {
|
||||||
|
height: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 34px 46px 120px;
|
||||||
|
max-width: 900px;
|
||||||
|
margin: 0 auto;
|
||||||
|
font-size: 14.5px;
|
||||||
|
line-height: 1.78;
|
||||||
|
color: var(--text);
|
||||||
|
user-select: text;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > *:first-child { margin-top: 0; }
|
||||||
|
|
||||||
|
.markdown-body h1, .markdown-body h2, .markdown-body h3,
|
||||||
|
.markdown-body h4, .markdown-body h5, .markdown-body h6 {
|
||||||
|
margin: 1.6em 0 .6em;
|
||||||
|
font-weight: 650;
|
||||||
|
line-height: 1.35;
|
||||||
|
scroll-margin-top: 20px;
|
||||||
|
}
|
||||||
|
.markdown-body h1 { font-size: 1.9em; padding-bottom: .3em; border-bottom: 1px solid var(--border); }
|
||||||
|
.markdown-body h2 { font-size: 1.5em; padding-bottom: .25em; border-bottom: 1px solid var(--border); }
|
||||||
|
.markdown-body h3 { font-size: 1.24em; }
|
||||||
|
.markdown-body h4 { font-size: 1.08em; }
|
||||||
|
.markdown-body h5 { font-size: 1em; }
|
||||||
|
.markdown-body h6 { font-size: .94em; color: var(--text-dim); }
|
||||||
|
|
||||||
|
.markdown-body p { margin: .85em 0; }
|
||||||
|
|
||||||
|
.markdown-body a {
|
||||||
|
color: var(--accent);
|
||||||
|
text-decoration: none;
|
||||||
|
border-bottom: 1px solid transparent;
|
||||||
|
}
|
||||||
|
.markdown-body a:hover { border-bottom-color: currentColor; }
|
||||||
|
|
||||||
|
.markdown-body strong { font-weight: 650; }
|
||||||
|
.markdown-body em { font-style: italic; }
|
||||||
|
.markdown-body del { color: var(--text-faint); }
|
||||||
|
|
||||||
|
.markdown-body code {
|
||||||
|
padding: .16em .4em;
|
||||||
|
border-radius: 5px;
|
||||||
|
background: var(--code-bg);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: .88em;
|
||||||
|
color: #b5446e;
|
||||||
|
}
|
||||||
|
html[data-theme="dark"] .markdown-body code { color: #f0a1c0; }
|
||||||
|
|
||||||
|
.code-wrap {
|
||||||
|
position: relative;
|
||||||
|
margin: 1em 0;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--code-block-bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.code-wrap pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 14px 16px;
|
||||||
|
overflow-x: auto;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 12.8px;
|
||||||
|
line-height: 1.65;
|
||||||
|
}
|
||||||
|
.code-wrap pre code {
|
||||||
|
padding: 0;
|
||||||
|
background: none;
|
||||||
|
color: var(--text);
|
||||||
|
font-size: inherit;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
.code-lang {
|
||||||
|
position: absolute;
|
||||||
|
top: 6px; right: 10px;
|
||||||
|
font-size: 10.5px;
|
||||||
|
letter-spacing: .04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--text-faint);
|
||||||
|
font-family: var(--font-ui);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body blockquote {
|
||||||
|
margin: 1em 0;
|
||||||
|
padding: .2em 1em;
|
||||||
|
border-left: 3px solid var(--quote-bar);
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
.markdown-body blockquote > *:first-child { margin-top: .4em; }
|
||||||
|
.markdown-body blockquote > *:last-child { margin-bottom: .4em; }
|
||||||
|
|
||||||
|
.markdown-body ul, .markdown-body ol { margin: .7em 0; padding-left: 1.7em; }
|
||||||
|
.markdown-body li { margin: .3em 0; }
|
||||||
|
.markdown-body li > ul, .markdown-body li > ol { margin: .3em 0; }
|
||||||
|
.markdown-body li.task-item { list-style: none; margin-left: -1.35em; }
|
||||||
|
.markdown-body li.task-item input { margin-right: .45em; vertical-align: 1px; accent-color: var(--accent); }
|
||||||
|
|
||||||
|
.markdown-body hr {
|
||||||
|
height: 1px;
|
||||||
|
margin: 1.8em 0;
|
||||||
|
border: none;
|
||||||
|
background: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-wrap { overflow-x: auto; margin: 1.1em 0; }
|
||||||
|
.markdown-body table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
font-size: .95em;
|
||||||
|
}
|
||||||
|
.markdown-body th, .markdown-body td {
|
||||||
|
padding: 7px 13px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.markdown-body th {
|
||||||
|
background: var(--bg-soft);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.markdown-body tbody tr:nth-child(2n) { background: color-mix(in srgb, var(--bg-soft) 60%, transparent); }
|
||||||
|
|
||||||
|
.markdown-body img {
|
||||||
|
max-width: 100%;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin: .4em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============ 状态栏 ============ */
|
||||||
|
.statusbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex: 0 0 26px;
|
||||||
|
height: 26px;
|
||||||
|
padding: 0 12px;
|
||||||
|
background: var(--bg-toolbar);
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--text-faint);
|
||||||
|
}
|
||||||
|
.st-left, .st-right { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.st-file { color: var(--text-dim); max-width: 46vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.st-dirty {
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent);
|
||||||
|
font-size: 10.5px;
|
||||||
|
}
|
||||||
|
.st-div { color: var(--border-strong); }
|
||||||
|
|
||||||
|
/* ============ 右键菜单 ============ */
|
||||||
|
.ctx-menu {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 900;
|
||||||
|
min-width: 200px;
|
||||||
|
padding: 5px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
.ctx-menu[hidden] { display: none; }
|
||||||
|
.ctx-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 24px;
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--text);
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.ctx-item:hover { background: var(--accent); color: var(--accent-text); }
|
||||||
|
.ctx-item .kbd { font-size: 11px; color: var(--text-faint); }
|
||||||
|
.ctx-item:hover .kbd { color: rgba(255, 255, 255, .8); }
|
||||||
|
.ctx-item.disabled { color: var(--text-faint); pointer-events: none; }
|
||||||
|
.ctx-sep { height: 1px; margin: 4px 6px; background: var(--border); }
|
||||||
|
|
||||||
|
/* ============ 提示 ============ */
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
left: 50%;
|
||||||
|
bottom: 46px;
|
||||||
|
transform: translateX(-50%) translateY(8px);
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(28, 32, 38, .92);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 12.5px;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity .18s, transform .18s;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 950;
|
||||||
|
}
|
||||||
|
.toast[hidden] { display: none; }
|
||||||
|
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||||
|
|
||||||
|
.drop-hint {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 990;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||||
|
border: 2px dashed var(--accent);
|
||||||
|
backdrop-filter: blur(1px);
|
||||||
|
}
|
||||||
|
.drop-hint[hidden] { display: none; }
|
||||||
|
.drop-hint div {
|
||||||
|
padding: 10px 22px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--bg);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 滚动条 */
|
||||||
|
::-webkit-scrollbar { width: 11px; height: 11px; }
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: color-mix(in srgb, var(--text-faint) 42%, transparent);
|
||||||
|
border: 3px solid transparent;
|
||||||
|
background-clip: content-box;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb:hover { background: color-mix(in srgb, var(--text-faint) 70%, transparent); background-clip: content-box; }
|
||||||
|
::-webkit-scrollbar-track { background: transparent; }
|
||||||
|
|
||||||
|
/* 拖动分栏时禁止选中 */
|
||||||
|
body.resizing { cursor: col-resize; }
|
||||||
|
body.resizing #editor, body.resizing .markdown-body { pointer-events: none; }
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
/* Tauri 桥接层:替代 Electron preload,向 app.js 提供同形状的 window.api */
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const T = window.__TAURI__;
|
||||||
|
if (!T) { console.error('Tauri API 未注入'); return; }
|
||||||
|
const invoke = T.core.invoke;
|
||||||
|
const listen = T.event.listen;
|
||||||
|
const cur = T.window.getCurrentWindow();
|
||||||
|
|
||||||
|
/* ---------- 标题状态(等价原主进程窗口状态) ---------- */
|
||||||
|
const titleState = { path: null, dirty: false };
|
||||||
|
function baseName(p) {
|
||||||
|
if (!p) return null;
|
||||||
|
return String(p).replace(/[\\/]+$/, '').split(/[\\/]/).pop() || null;
|
||||||
|
}
|
||||||
|
function updateTitle() {
|
||||||
|
const t = (titleState.dirty ? '● ' : '') + (baseName(titleState.path) || '未命名') + ' — 小银 Markdown';
|
||||||
|
cur.setTitle(t).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 模态对话框(支持任意按钮数组,返回按钮索引) ---------- */
|
||||||
|
function modalDialog(o) {
|
||||||
|
const buttons = Array.isArray(o.buttons) && o.buttons.length ? o.buttons : ['好'];
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:99999;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif;';
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.style.cssText = 'background:#fff;color:#222;border-radius:12px;padding:22px 24px 18px;max-width:440px;box-shadow:0 18px 60px rgba(0,0,0,.3);font-size:13.5px;';
|
||||||
|
const msg = document.createElement('div');
|
||||||
|
msg.style.cssText = 'font-weight:700;font-size:15px;margin-bottom:6px;';
|
||||||
|
msg.textContent = o.message || '';
|
||||||
|
box.appendChild(msg);
|
||||||
|
if (o.detail) {
|
||||||
|
const d = document.createElement('div');
|
||||||
|
d.style.cssText = 'opacity:.7;margin-bottom:14px;line-height:1.5;';
|
||||||
|
d.textContent = o.detail;
|
||||||
|
box.appendChild(d);
|
||||||
|
}
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.style.cssText = 'display:flex;gap:8px;justify-content:flex-end;';
|
||||||
|
buttons.forEach((label, i) => {
|
||||||
|
const b = document.createElement('button');
|
||||||
|
b.textContent = label;
|
||||||
|
const primary = i === buttons.length - 1;
|
||||||
|
b.style.cssText = 'padding:7px 16px;border-radius:8px;border:1px solid #c9cdd4;cursor:pointer;font-size:13px;background:' +
|
||||||
|
(primary ? '#3b7bf6;color:#fff;border-color:#3b7bf6;' : 'transparent;color:inherit;');
|
||||||
|
b.addEventListener('click', () => { overlay.remove(); resolve(i); });
|
||||||
|
row.appendChild(b);
|
||||||
|
});
|
||||||
|
box.appendChild(row);
|
||||||
|
overlay.appendChild(box);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 命令 / 关闭 / 导出 处理器注册表 ---------- */
|
||||||
|
const cmdHandlers = [];
|
||||||
|
const closeHandlers = [];
|
||||||
|
let exportHandler = null;
|
||||||
|
function fire(name, payload) {
|
||||||
|
cmdHandlers.forEach((cb) => { try { cb(name, payload); } catch (err) { console.error(err); } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 迁移:广播收集所有窗口的文档 ---------- */
|
||||||
|
function collectAllDocs() {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const replies = [];
|
||||||
|
let un = null;
|
||||||
|
listen('mig:docs', (e) => {
|
||||||
|
if (e.payload && Array.isArray(e.payload.docs)) replies.push(e.payload.docs);
|
||||||
|
}).then((u) => { un = u; });
|
||||||
|
T.event.emit('mig:request', { from: cur.label });
|
||||||
|
const start = Date.now();
|
||||||
|
const tick = () => {
|
||||||
|
if (Date.now() - start >= 2200 || un) {
|
||||||
|
if (un) un();
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const docs of replies) {
|
||||||
|
for (const d of docs) {
|
||||||
|
if (d.path && seen.has(d.path)) continue;
|
||||||
|
if (d.path) seen.add(d.path);
|
||||||
|
out.push(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!out.length) out.push({ path: null, name: null, text: '', eol: '\n', dirty: false, lastSaved: '' });
|
||||||
|
resolve(out);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTimeout(tick, 120);
|
||||||
|
};
|
||||||
|
setTimeout(tick, 600);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 对外 API(与 Electron preload 同形状) ---------- */
|
||||||
|
window.api = {
|
||||||
|
open: () => invoke('open_file_dialog'),
|
||||||
|
openPath: (p) => invoke('read_text_file', { path: p }),
|
||||||
|
save: async (payload) => {
|
||||||
|
const r = await invoke('save_file', {
|
||||||
|
content: payload.content,
|
||||||
|
saveAs: !!payload.saveAs,
|
||||||
|
eol: payload.eol || '\n',
|
||||||
|
currentPath: titleState.path
|
||||||
|
});
|
||||||
|
if (r && r.ok && r.path) {
|
||||||
|
titleState.path = r.path;
|
||||||
|
titleState.dirty = false;
|
||||||
|
updateTitle();
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
},
|
||||||
|
reveal: () => (titleState.path ? invoke('reveal_in_explorer', { path: titleState.path }) : Promise.resolve({ ok: false })),
|
||||||
|
revealPath: (p) => invoke('reveal_in_explorer', { path: p }),
|
||||||
|
copyFile: (p) => invoke('copy_file_to_clipboard', { path: p }),
|
||||||
|
readFileText: (p) => invoke('read_text_file', { path: p }),
|
||||||
|
readClipboard: () => invoke('read_clipboard_text'),
|
||||||
|
writeClipboard: (t) => invoke('write_clipboard_text', { text: t }),
|
||||||
|
openExternal: (url) => invoke('open_external', { url }),
|
||||||
|
dirOpen: () => invoke('open_dir_dialog'),
|
||||||
|
dirRead: (p) => invoke('read_dir', { path: p }),
|
||||||
|
openNewWindow: (p) => invoke('open_new_window', { path: p }),
|
||||||
|
newWindow: () => invoke('open_new_window', { path: null }),
|
||||||
|
closeWindow: () => invoke('force_close'),
|
||||||
|
getOpenMode: async () => ({ mode: localStorage.getItem('md-editor-open-mode') || 'tabs' }),
|
||||||
|
setOpenMode: async (mode) => {
|
||||||
|
const docs = await collectAllDocs();
|
||||||
|
await invoke('migrate_apply', { mode, docs, keepLabel: cur.label });
|
||||||
|
return { ok: true, mode };
|
||||||
|
},
|
||||||
|
setDirty: (d) => { titleState.dirty = !!d; updateTitle(); },
|
||||||
|
syncDoc: (p) => {
|
||||||
|
titleState.path = p || null;
|
||||||
|
updateTitle();
|
||||||
|
},
|
||||||
|
message: (o) => modalDialog(o),
|
||||||
|
saveFinished: () => {},
|
||||||
|
exportDocs: () => {},
|
||||||
|
onCommand: (cb) => cmdHandlers.push(cb),
|
||||||
|
onCloseConfirm: (cb) => closeHandlers.push(cb),
|
||||||
|
onExport: (cb) => { exportHandler = cb; }
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- 事件接线 ---------- */
|
||||||
|
listen('mig:adopt-tabs', (e) => fire('adopt-tabs', e.payload && e.payload.docs));
|
||||||
|
listen('mig:adopt-doc', (e) => fire('adopt-doc', e.payload));
|
||||||
|
listen('open-external', (e) => fire('open-external', e.payload));
|
||||||
|
listen('init-file', (e) => fire('file-opened', e.payload));
|
||||||
|
listen('close-confirm', () => closeHandlers.forEach((cb) => { try { cb(cur.label); } catch (err) { console.error(err); } }));
|
||||||
|
listen('mig:request', () => {
|
||||||
|
if (exportHandler) {
|
||||||
|
try {
|
||||||
|
const docs = exportHandler();
|
||||||
|
T.event.emit('mig:docs', { from: cur.label, docs });
|
||||||
|
} catch (err) { console.error(err); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- 拖放(Tauri 系统级,拿得到真实路径) ---------- */
|
||||||
|
cur.onDragDropEvent((e) => {
|
||||||
|
const p = e.payload;
|
||||||
|
if (p.type === 'drop' && Array.isArray(p.paths) && p.paths.length) {
|
||||||
|
fire('dropped-path', p.paths[0]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- 文本拖放兜底(HTML5) ---------- */
|
||||||
|
window.addEventListener('dragover', (e) => { e.preventDefault(); });
|
||||||
|
window.addEventListener('drop', (e) => {
|
||||||
|
const dt = e.dataTransfer;
|
||||||
|
if (!dt) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const text = dt.getData && dt.getData('text/plain');
|
||||||
|
if (text) fire('dropped-text', { name: null, text });
|
||||||
|
});
|
||||||
|
})();
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
@@ -0,0 +1,35 @@
|
|||||||
|
/* 验证关闭窗口时主进程不抛异常 */
|
||||||
|
process.on('uncaughtException', (e) => {
|
||||||
|
console.log('UNCAUGHT:', e.message);
|
||||||
|
process.exit(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
const { app, BrowserWindow } = require('electron');
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
require('../src/main.js');
|
||||||
|
// 阻止 window-all-closed 自动退出,便于关闭后继续检查
|
||||||
|
app.removeAllListeners('window-all-closed');
|
||||||
|
|
||||||
|
let errors = [];
|
||||||
|
process.on('uncaughtException', (e) => errors.push(e.message));
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
await wait(1400);
|
||||||
|
const wins = BrowserWindow.getAllWindows();
|
||||||
|
console.log('打开窗口数:', wins.length);
|
||||||
|
|
||||||
|
// 连续开关多个窗口,覆盖正常关闭和迁移式关闭
|
||||||
|
const w2 = new BrowserWindow({ show: false, webPreferences: { offscreen: true } });
|
||||||
|
w2.close();
|
||||||
|
await wait(300);
|
||||||
|
|
||||||
|
for (const w of wins) w.close();
|
||||||
|
await wait(1000);
|
||||||
|
|
||||||
|
if (errors.length) {
|
||||||
|
console.log('FAIL 主进程异常:', errors.join(' | '));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('PASS 关闭窗口无主进程异常');
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/* 验证:文件树右键复制(文件名/路径/内容)+ 聚焦后 Ctrl+C + 按钮位置 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
const nativeClip = require('../src/clipboard-native');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'copytest-'));
|
||||||
|
const mdFile = path.join(tmp, '交易日历业务交接文档.md');
|
||||||
|
const mdText = '# 交易日历业务交接文档\n\n## 业务概览\n\n正文内容。\n';
|
||||||
|
fs.writeFileSync(mdFile, mdText, 'utf8');
|
||||||
|
fs.mkdirSync(path.join(tmp, '子目录'));
|
||||||
|
fs.writeFileSync(path.join(tmp, '另一个.md'), '# 另一个\n', 'utf8');
|
||||||
|
|
||||||
|
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }))
|
||||||
|
.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
|
||||||
|
|
||||||
|
let clipboard = '';
|
||||||
|
let lastRevealed = '';
|
||||||
|
let lastCopiedFile = '';
|
||||||
|
ipcMain.handle('clip:read', () => clipboard);
|
||||||
|
ipcMain.handle('clip:write', (_e, text) => { clipboard = String(text ?? ''); return true; });
|
||||||
|
ipcMain.handle('file:readText', async (_e, p) => {
|
||||||
|
try { return { ok: true, text: fs.readFileSync(p, 'utf8') }; } catch (_) { return { ok: false }; }
|
||||||
|
});
|
||||||
|
ipcMain.handle('file:copyFile', async (_e, p) => {
|
||||||
|
const list = (Array.isArray(p) ? p : [p]).filter((x) => x && fs.existsSync(x));
|
||||||
|
nativeClip.setFiles(list);
|
||||||
|
lastCopiedFile = p || '';
|
||||||
|
return { ok: true, count: list.length };
|
||||||
|
});
|
||||||
|
ipcMain.handle('file:revealPath', async (_e, p) => { lastRevealed = p || ''; return { ok: true }; });
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('file:reveal', async () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1400, height: 880, show: true,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
await js(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1200);
|
||||||
|
|
||||||
|
/* 1. 按钮位置 */
|
||||||
|
const pos = await js(`(() => {
|
||||||
|
const btns = [...document.querySelectorAll('.toolbar button')];
|
||||||
|
const tree = document.getElementById('btn-tree');
|
||||||
|
const outline = document.getElementById('btn-outline');
|
||||||
|
const segBtn = document.querySelector('#mode-seg button');
|
||||||
|
return {
|
||||||
|
beforeSeg: btns.indexOf(tree) < btns.indexOf(segBtn),
|
||||||
|
adjacent: btns.indexOf(segBtn) - btns.indexOf(tree) === 1,
|
||||||
|
sameClass: tree.className === outline.className,
|
||||||
|
treeText: tree.textContent.trim(), outlineText: outline.textContent.trim()
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('「目录」按钮紧挨在编辑/分栏/阅读之前', pos.beforeSeg === true && pos.adjacent === true, JSON.stringify(pos));
|
||||||
|
check('两个开关样式类名一致', pos.sameClass === true, pos.treeClass || '');
|
||||||
|
check('按钮文字为 目录 / 大纲', pos.treeText === '目录' && pos.outlineText === '大纲', pos.treeText + ' / ' + pos.outlineText);
|
||||||
|
|
||||||
|
/* 2. 打开文件夹,准备文件树 */
|
||||||
|
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
|
||||||
|
await wait(400);
|
||||||
|
|
||||||
|
const rightClick = async (pathSuffix, menuText) => js(`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
|
||||||
|
const row = rows.find(r => r.dataset.path.endsWith(${JSON.stringify(pathSuffix)}));
|
||||||
|
if (!row) return { error: 'row not found' };
|
||||||
|
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
|
||||||
|
const menu = document.getElementById('ctxmenu');
|
||||||
|
const items = [...menu.querySelectorAll('.ctx-item')].map(i => i.textContent);
|
||||||
|
const target = [...menu.querySelectorAll('.ctx-item')].find(i => {
|
||||||
|
const lab = i.querySelector('span');
|
||||||
|
return lab && lab.textContent === ${JSON.stringify(menuText)};
|
||||||
|
});
|
||||||
|
if (!target) return { error: 'menu item not found', items };
|
||||||
|
target.click();
|
||||||
|
return { items };
|
||||||
|
})()`);
|
||||||
|
|
||||||
|
/* 3. 右键复制文件名 */
|
||||||
|
await rightClick('交易日历业务交接文档.md', '复制文件名');
|
||||||
|
await wait(200);
|
||||||
|
check('右键复制文件名', clipboard === '交易日历业务交接文档.md', clipboard);
|
||||||
|
|
||||||
|
/* 4. 右键复制完整路径 */
|
||||||
|
await rightClick('交易日历业务交接文档.md', '复制完整路径');
|
||||||
|
await wait(200);
|
||||||
|
check('右键复制完整路径', clipboard === mdFile, clipboard);
|
||||||
|
|
||||||
|
/* 5. 右键复制文件内容 */
|
||||||
|
await rightClick('交易日历业务交接文档.md', '复制文件内容');
|
||||||
|
await wait(250);
|
||||||
|
check('右键复制文件内容', clipboard === mdText, JSON.stringify(clipboard).slice(0, 60));
|
||||||
|
|
||||||
|
/* 6. 右键复制文件本身(Windows 文件对象) */
|
||||||
|
await rightClick('交易日历业务交接文档.md', '复制文件');
|
||||||
|
await wait(250);
|
||||||
|
check('右键复制文件本身', lastCopiedFile === mdFile, lastCopiedFile);
|
||||||
|
check('系统剪贴板含文件列表 CF_HDROP', nativeClip.hasFiles() === true);
|
||||||
|
|
||||||
|
/* 7. 右键在资源管理器中显示:路径必须真的传过去 */
|
||||||
|
await rightClick('交易日历业务交接文档.md', '在资源管理器中显示');
|
||||||
|
await wait(200);
|
||||||
|
check('资源管理器显示:路径参数正确传递', lastRevealed === mdFile, lastRevealed);
|
||||||
|
|
||||||
|
/* 8. 右键菜单内容齐全、目录项禁用复制内容 */
|
||||||
|
const menuInfo = await js(`(() => {
|
||||||
|
const row = [...document.querySelectorAll('#sb-body .tree-row.is-dir')][0];
|
||||||
|
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
|
||||||
|
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
|
||||||
|
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
|
||||||
|
return {
|
||||||
|
labels: items.map(lab),
|
||||||
|
contentDisabled: items.find(i => lab(i) === '复制文件内容').classList.contains('disabled')
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('右键菜单五项齐全', ['复制文件', '复制文件内容', '复制文件名', '复制完整路径', '在资源管理器中显示'].every(x => menuInfo.labels.includes(x)), JSON.stringify(menuInfo.labels));
|
||||||
|
check('目录项禁用复制文件内容', menuInfo.contentDisabled === true);
|
||||||
|
|
||||||
|
/* 9. 聚焦 + Ctrl+C 复制文件 */
|
||||||
|
const kbd = await js(`(() => {
|
||||||
|
document.getElementById('ctxmenu').hidden = true;
|
||||||
|
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('另一个.md'));
|
||||||
|
row.focus();
|
||||||
|
const focused = document.activeElement === row;
|
||||||
|
row.dispatchEvent(new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }));
|
||||||
|
return { focused };
|
||||||
|
})()`);
|
||||||
|
await wait(250);
|
||||||
|
check('文件树条目可聚焦', kbd.focused === true);
|
||||||
|
check('Ctrl+C 复制文件本身', lastCopiedFile === path.join(tmp, '另一个.md'), lastCopiedFile);
|
||||||
|
check('Ctrl+C 后剪贴板仍是文件列表', nativeClip.hasFiles() === true);
|
||||||
|
|
||||||
|
/* 8. 普通编辑区 Ctrl+C 不受影响 */
|
||||||
|
await js(`(() => {
|
||||||
|
const ed = document.getElementById('editor');
|
||||||
|
ed.value = 'EDITOR TEXT';
|
||||||
|
ed.focus();
|
||||||
|
ed.setSelectionRange(0, 5);
|
||||||
|
ed.dispatchEvent(new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }));
|
||||||
|
})()`);
|
||||||
|
await wait(250);
|
||||||
|
check('编辑区 Ctrl+C 不误触文件树复制', clipboard !== 'EDITOR TEXT', clipboard);
|
||||||
|
|
||||||
|
console.log('\n==== 文件树复制测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
const img = await win.webContents.capturePage();
|
||||||
|
fs.writeFileSync(path.join(__dirname, '..', 'shot-copy.png'), img.toPNG());
|
||||||
|
console.log('screenshot saved');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/* 用 CDP 模拟真实系统拖放,验证 preload 能否取到路径并打开 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
const log = (...a) => console.log(...a);
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'dragtest-'));
|
||||||
|
const file = path.join(tmp, '拖进来的文件.md');
|
||||||
|
const dir = path.join(tmp, '文档库');
|
||||||
|
fs.writeFileSync(file, '# 拖进来的\n\n内容是 **拖放** 打开的。\n', 'utf8');
|
||||||
|
fs.mkdirSync(dir);
|
||||||
|
fs.writeFileSync(path.join(dir, '第一篇.md'), '# 第一篇\n', 'utf8');
|
||||||
|
fs.writeFileSync(path.join(dir, '第二篇.md'), '# 第二篇\n', 'utf8');
|
||||||
|
|
||||||
|
// 真实主进程逻辑(复刻 main.js 的两条通路)
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => {
|
||||||
|
return { ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' };
|
||||||
|
});
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => {
|
||||||
|
const entries = fs.readdirSync(p, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(p, d.name), isDir: d.isDirectory() }));
|
||||||
|
return { ok: true, path: p, name: path.basename(p), entries };
|
||||||
|
});
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('clip:read', () => '');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
// 复刻 main.js 里 file:drop 的分支(文件 → 打开;目录 → 文件树)
|
||||||
|
ipcMain.on('file:drop', (_e, p) => {
|
||||||
|
const win = BrowserWindow.getAllWindows()[0];
|
||||||
|
let isDir = false;
|
||||||
|
try { isDir = fs.statSync(p).isDirectory(); } catch (_) { return; }
|
||||||
|
if (isDir) {
|
||||||
|
const entries = fs.readdirSync(p, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(p, d.name), isDir: d.isDirectory() }));
|
||||||
|
win.webContents.send('cmd', 'dir-opened', { ok: true, path: p, name: path.basename(p), entries });
|
||||||
|
} else {
|
||||||
|
win.webContents.send('cmd', 'file-opened', {
|
||||||
|
ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1280, height: 820, show: true,
|
||||||
|
webPreferences: {
|
||||||
|
preload: path.join(__dirname, '..', 'src', 'preload.js'),
|
||||||
|
contextIsolation: true,
|
||||||
|
nodeIntegration: false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
win.focus();
|
||||||
|
await new Promise((r) => setTimeout(r, 800));
|
||||||
|
|
||||||
|
const dbg = win.webContents.debugger;
|
||||||
|
dbg.attach('1.3');
|
||||||
|
|
||||||
|
const dragDrop = async (absolutePath, x, y) => {
|
||||||
|
const data = { items: [], files: [absolutePath], dragOperationsMask: 1 };
|
||||||
|
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'dragEnter', x, y, data });
|
||||||
|
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'dragOver', x, y, data });
|
||||||
|
await dbg.sendCommand('Input.dispatchDragEvent', { type: 'drop', x, y, data });
|
||||||
|
};
|
||||||
|
|
||||||
|
const js = (code) => win.webContents.executeJavaScript(code);
|
||||||
|
let pass = 0;
|
||||||
|
let fail = 0;
|
||||||
|
const check = (name, ok, extra) => {
|
||||||
|
if (ok) { pass++; log('PASS ' + name); } else { fail++; log('FAIL ' + name + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- 拖入单个 .md 文件 ----
|
||||||
|
try {
|
||||||
|
await dragDrop(file, 400, 380);
|
||||||
|
await new Promise((r) => setTimeout(r, 900));
|
||||||
|
const s = await js(`({ v: editor.value, name: document.getElementById('st-file').textContent, sb: !document.getElementById('sidebar').hidden, rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r=>r.querySelector('.tree-name').textContent) })`);
|
||||||
|
check('拖入文件:取到真实路径并打开', s.v.indexOf('拖放') >= 0, s.name);
|
||||||
|
check('拖入文件:状态栏文件名正确', s.name === '拖进来的文件.md', s.name);
|
||||||
|
check('拖入文件:自动列出所在目录', s.sb === true && s.rows.includes('文档库'), JSON.stringify(s.rows));
|
||||||
|
} catch (e) {
|
||||||
|
check('拖入文件(CDP 未支持 files 参数)', false, e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 拖入文件夹 ----
|
||||||
|
try {
|
||||||
|
await dragDrop(dir, 400, 380);
|
||||||
|
await new Promise((r) => setTimeout(r, 900));
|
||||||
|
const s = await js(`({ title: document.getElementById('sb-title').textContent, rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r=>r.querySelector('.tree-name').textContent) })`);
|
||||||
|
check('拖入文件夹:侧栏标题为该文件夹', s.title === '文档库', s.title);
|
||||||
|
check('拖入文件夹:列出里面的 md', s.rows.includes('第一篇.md') && s.rows.includes('第二篇.md'), JSON.stringify(s.rows));
|
||||||
|
} catch (e) {
|
||||||
|
check('拖入文件夹(CDP 未支持 files 参数)', false, e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('\n==== 拖放测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
/* 验证:查找时预览正文的关键字背景标记与当前命中高亮 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
ipcMain.handle('clip:read', () => '');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.handle('app:getOpenMode', async () => ({ mode: 'tabs' }));
|
||||||
|
ipcMain.handle('app:setOpenMode', async () => ({ ok: true }));
|
||||||
|
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {}); ipcMain.on('docs:exported', () => {});
|
||||||
|
ipcMain.on('doc:syncPath', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1400, height: 900, show: true,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
await js(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1800);
|
||||||
|
|
||||||
|
/* 1. 输入关键字,预览出现标记 */
|
||||||
|
const r1 = await js(`(async () => {
|
||||||
|
editor.value = '# 标题\\n\\n银色是银色的银,银币也很银。\\n\\n- 银在列表里\\n\\n**银** 在加粗里。';
|
||||||
|
editor.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
await new Promise(r => setTimeout(r, 250));
|
||||||
|
document.getElementById('btn-find').click();
|
||||||
|
await new Promise(r => setTimeout(r, 150));
|
||||||
|
const inp = document.getElementById('find-input');
|
||||||
|
inp.value = '银';
|
||||||
|
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
await new Promise(r => setTimeout(r, 200));
|
||||||
|
return {
|
||||||
|
total: document.querySelectorAll('#preview mark.find-hit').length,
|
||||||
|
active: document.querySelectorAll('#preview mark.find-hit.find-hit-active').length,
|
||||||
|
count: document.getElementById('find-count').textContent
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('预览正文出现 7 处关键字标记', r1.total === 7, JSON.stringify(r1));
|
||||||
|
check('当前命中有一个且仅一个', r1.active === 1, JSON.stringify(r1));
|
||||||
|
check('计数显示正常', r1.count.indexOf('7') >= 0, r1.count);
|
||||||
|
|
||||||
|
/* 1b. 编辑器叠加层同步高亮 */
|
||||||
|
const r1b = await js(`(() => ({
|
||||||
|
marks: document.querySelectorAll('#editor-hl mark').length,
|
||||||
|
active: document.querySelectorAll('#editor-hl mark.find-hit-active').length
|
||||||
|
}))()`);
|
||||||
|
check('编辑器叠加层出现 7 处标记', r1b.marks === 7, JSON.stringify(r1b));
|
||||||
|
check('编辑器层当前命中唯一', r1b.active === 1, JSON.stringify(r1b));
|
||||||
|
|
||||||
|
/* 1c. 编辑模式(无预览)下叠加层仍然高亮 */
|
||||||
|
const r1c = await js(`(async () => {
|
||||||
|
document.querySelector('.seg button[data-mode="edit"]').click();
|
||||||
|
await new Promise(r => setTimeout(r, 150));
|
||||||
|
const inEdit = document.getElementById('workspace').dataset.mode;
|
||||||
|
const marks = document.querySelectorAll('#editor-hl mark').length;
|
||||||
|
document.querySelector('.seg button[data-mode="split"]').click();
|
||||||
|
await new Promise(r => setTimeout(r, 150));
|
||||||
|
return { inEdit, marks };
|
||||||
|
})()`);
|
||||||
|
check('编辑模式下叠加层保持标记', r1c.inEdit === 'edit' && r1c.marks === 7, JSON.stringify(r1c));
|
||||||
|
|
||||||
|
/* 2. 下一处:active 移动 */
|
||||||
|
const r2 = await js(`(() => {
|
||||||
|
document.getElementById('find-next').click();
|
||||||
|
return {
|
||||||
|
actives: [...document.querySelectorAll('#preview mark.find-hit-active')].map(m => m.textContent),
|
||||||
|
idx: document.getElementById('find-count').textContent
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('下一处后当前命中唯一', r2.actives.length === 1, JSON.stringify(r2));
|
||||||
|
check('计数推进到 2 / 7', r2.idx.indexOf('2 /') >= 0, r2.idx);
|
||||||
|
|
||||||
|
/* 3. 编辑内容后(renderNow 重建 DOM)标记恢复 */
|
||||||
|
const r3 = await js(`(async () => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(editor.value.length, editor.value.length);
|
||||||
|
document.execCommand('insertText', false, '\\n新增一行也带银字。');
|
||||||
|
await new Promise(r => setTimeout(r, 350));
|
||||||
|
return { total: document.querySelectorAll('#preview mark.find-hit').length };
|
||||||
|
})()`);
|
||||||
|
check('编辑重渲染后标记自动恢复', r3.total === 8, JSON.stringify(r3));
|
||||||
|
|
||||||
|
/* 4. 关闭查找,标记清除 */
|
||||||
|
const r4 = await js(`(() => {
|
||||||
|
document.getElementById('find-close').click();
|
||||||
|
return {
|
||||||
|
preview: document.querySelectorAll('#preview mark.find-hit').length,
|
||||||
|
editor: document.querySelectorAll('#editor-hl mark').length
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('关闭查找后标记全部清除', r4.preview === 0, JSON.stringify(r4));
|
||||||
|
check('编辑器叠加层同时清空', r4.editor === 0, JSON.stringify(r4));
|
||||||
|
|
||||||
|
/* 5. 再次查找(新关键字),标记正常 */
|
||||||
|
const r5 = await js(`(async () => {
|
||||||
|
document.getElementById('btn-find').click();
|
||||||
|
const inp = document.getElementById('find-input');
|
||||||
|
inp.value = '标题';
|
||||||
|
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
await new Promise(r => setTimeout(r, 200));
|
||||||
|
return {
|
||||||
|
total: document.querySelectorAll('#preview mark.find-hit').length,
|
||||||
|
text: [...document.querySelectorAll('#preview mark.find-hit')].map(m => m.textContent)
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('新关键字标记正常', r5.total === 1 && r5.text[0] === '标题', JSON.stringify(r5));
|
||||||
|
|
||||||
|
/* 6. 换回完整文本输入框内容,普通正文无残留 mark */
|
||||||
|
const r6 = await js(`(() => {
|
||||||
|
document.getElementById('find-close').click();
|
||||||
|
return { marks: document.querySelectorAll('#preview mark').length };
|
||||||
|
})()`);
|
||||||
|
check('正文中无任何 mark 残留', r6.marks === 0, JSON.stringify(r6));
|
||||||
|
|
||||||
|
console.log('\n==== 预览查找高亮测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/* 生成应用图标:渲染 SVG 风格图形 → PNG 多尺寸 → 打包为 .ico */
|
||||||
|
const { app, BrowserWindow, nativeImage } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
|
const HTML = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
|
||||||
|
html,body{margin:0;width:512px;height:512px;background:transparent;overflow:hidden}
|
||||||
|
.wrap{width:512px;height:512px;display:flex;align-items:center;justify-content:center}
|
||||||
|
.box{width:452px;height:452px;border-radius:106px;position:relative;overflow:hidden;
|
||||||
|
background:linear-gradient(145deg,#5B8CFF 0%,#6A5AF9 46%,#9B4DF7 100%);
|
||||||
|
box-shadow:inset 0 -18px 44px rgba(10,10,60,.22), inset 0 16px 34px rgba(255,255,255,.24);
|
||||||
|
display:flex;align-items:center;justify-content:center}
|
||||||
|
.box::before{content:'';position:absolute;inset:0;
|
||||||
|
background:radial-gradient(130% 95% at 16% 6%, rgba(255,255,255,.30), transparent 55%)}
|
||||||
|
/* 四个字母排成紧凑 2×2:列宽取同列较宽者,字母在各自格子内居中 → 上下左右全部对齐 */
|
||||||
|
.mark{display:grid;grid-template-columns:repeat(2, auto);column-gap:22px;row-gap:0;
|
||||||
|
align-items:center;justify-items:center;position:relative;z-index:2;color:#fff;
|
||||||
|
font-family:"Segoe UI","Microsoft YaHei",sans-serif;
|
||||||
|
text-shadow:0 8px 26px rgba(18,18,72,.32)}
|
||||||
|
.mark i{font-style:normal;font-weight:750;font-size:148px;line-height:1;display:block}
|
||||||
|
</style></head><body><div class="wrap"><div class="box">
|
||||||
|
<div class="mark"><i>X</i><i>Y</i><i>M</i><i>D</i></div>
|
||||||
|
</div></div></body></html>`;
|
||||||
|
|
||||||
|
function buildIco(pngs) {
|
||||||
|
const count = pngs.length;
|
||||||
|
const header = Buffer.alloc(6);
|
||||||
|
header.writeUInt16LE(0, 0);
|
||||||
|
header.writeUInt16LE(1, 2);
|
||||||
|
header.writeUInt16LE(count, 4);
|
||||||
|
let offset = 6 + count * 16;
|
||||||
|
const entries = [];
|
||||||
|
const datas = [];
|
||||||
|
for (const p of pngs) {
|
||||||
|
const e = Buffer.alloc(16);
|
||||||
|
e[0] = p.size >= 256 ? 0 : p.size;
|
||||||
|
e[1] = p.size >= 256 ? 0 : p.size;
|
||||||
|
e[2] = 0;
|
||||||
|
e[3] = 0;
|
||||||
|
e.writeUInt16LE(1, 4);
|
||||||
|
e.writeUInt16LE(32, 6);
|
||||||
|
e.writeUInt32LE(p.buf.length, 8);
|
||||||
|
e.writeUInt32LE(offset, 12);
|
||||||
|
offset += p.buf.length;
|
||||||
|
entries.push(e);
|
||||||
|
datas.push(p.buf);
|
||||||
|
}
|
||||||
|
return Buffer.concat([header, ...entries, ...datas]);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 512, height: 512, show: false, frame: false, transparent: true,
|
||||||
|
backgroundColor: '#00000000',
|
||||||
|
webPreferences: { offscreen: false }
|
||||||
|
});
|
||||||
|
await win.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(HTML));
|
||||||
|
await new Promise((r) => setTimeout(r, 900));
|
||||||
|
|
||||||
|
const img = await win.webContents.capturePage();
|
||||||
|
const sizes = [16, 24, 32, 48, 64, 128, 256];
|
||||||
|
const pngs = sizes.map((size) => ({
|
||||||
|
size,
|
||||||
|
buf: img.resize({ width: size, height: size, quality: 'best' }).toPNG()
|
||||||
|
}));
|
||||||
|
|
||||||
|
const outDir = path.join(__dirname, '..', 'build');
|
||||||
|
fs.mkdirSync(outDir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(outDir, 'icon.ico'), buildIco(pngs));
|
||||||
|
fs.writeFileSync(path.join(outDir, 'icon.png'), img.resize({ width: 512, height: 512, quality: 'best' }).toPNG());
|
||||||
|
console.log('icon written:', path.join(outDir, 'icon.ico'), fs.statSync(path.join(outDir, 'icon.ico')).size, 'bytes');
|
||||||
|
app.exit(0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/* 直接驱动真实 main.js:验证标签↔独立窗口双向迁移 */
|
||||||
|
const { app, BrowserWindow } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
const main = require('../src/main.js');
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-'));
|
||||||
|
const docs = ['A.md', 'B.md', 'C.md'].map((n) => {
|
||||||
|
const p = path.join(tmp, n);
|
||||||
|
fs.writeFileSync(p, '# ' + n + '\n\n内容 ' + n + '\n', 'utf8');
|
||||||
|
return { path: p, name: n, text: '# ' + n + '\n\n内容 ' + n + '\n', eol: '\n' };
|
||||||
|
});
|
||||||
|
|
||||||
|
await wait(1200);
|
||||||
|
let wins = BrowserWindow.getAllWindows();
|
||||||
|
await wins[0].webContents.executeJavaScript(`localStorage.clear()`);
|
||||||
|
await wins[0].webContents.reload();
|
||||||
|
await wait(1200);
|
||||||
|
check('启动后 1 个窗口', wins.length === 1, String(wins.length));
|
||||||
|
|
||||||
|
// 在标签模式下打开 3 个文档
|
||||||
|
for (const d of docs) {
|
||||||
|
wins[0].webContents.send('cmd', 'file-opened', Object.assign({ ok: true }, d));
|
||||||
|
await wait(300);
|
||||||
|
}
|
||||||
|
const tabCount = await wins[0].webContents.executeJavaScript(`document.querySelectorAll('#tabbar .tab').length`);
|
||||||
|
check('标签模式有 3 个标签(欢迎 + A + B)', tabCount >= 3, String(tabCount));
|
||||||
|
check('标题显示最后打开的文件', wins[0].getTitle().indexOf('C.md') >= 0, wins[0].getTitle());
|
||||||
|
|
||||||
|
// 切到 A 标签,标题应跟着变(同步给主进程)
|
||||||
|
await wins[0].webContents.executeJavaScript(`document.querySelectorAll('#tabbar .tab')[1].click()`);
|
||||||
|
await wait(500);
|
||||||
|
check('切换标签后标题变成 A.md', wins[0].getTitle().indexOf('A.md') >= 0, wins[0].getTitle());
|
||||||
|
|
||||||
|
/* ---- 标签 → 独立窗口:应拆成多个窗口 ---- */
|
||||||
|
await main.setOpenMode('windows');
|
||||||
|
await wait(3200);
|
||||||
|
wins = BrowserWindow.getAllWindows();
|
||||||
|
check('切成独立窗口模式后拆成多个窗口', wins.length >= 3, String(wins.length));
|
||||||
|
|
||||||
|
let allHidden = true;
|
||||||
|
let foundDoc = false;
|
||||||
|
for (const w of wins) {
|
||||||
|
try {
|
||||||
|
const info = await w.webContents.executeJavaScript(`({
|
||||||
|
hidden: document.getElementById('tabbar').hidden,
|
||||||
|
val: editor.value.slice(0, 30)
|
||||||
|
})`);
|
||||||
|
if (!info.hidden) allHidden = false;
|
||||||
|
if (info.val.indexOf('内容') >= 0) foundDoc = true;
|
||||||
|
} catch (_) { /* 已关闭 */ }
|
||||||
|
}
|
||||||
|
check('拆分后各窗口标签栏隐藏', allHidden === true);
|
||||||
|
check('拆分后文档内容被带过去', foundDoc === true);
|
||||||
|
check('主进程模式为 windows', main.getOpenMode() === 'windows');
|
||||||
|
|
||||||
|
/* ---- 独立窗口 → 标签:应合并成一个窗口 ---- */
|
||||||
|
await main.setOpenMode('tabs');
|
||||||
|
await wait(3500);
|
||||||
|
wins = BrowserWindow.getAllWindows();
|
||||||
|
check('切成标签模式后合并为 1 个窗口', wins.length === 1, String(wins.length));
|
||||||
|
|
||||||
|
if (wins.length === 1) {
|
||||||
|
const merged = await wins[0].webContents.executeJavaScript(`(() => ({
|
||||||
|
hidden: document.getElementById('tabbar').hidden,
|
||||||
|
n: document.querySelectorAll('#tabbar .tab').length,
|
||||||
|
names: [...document.querySelectorAll('#tabbar .tab-name')].map(e => e.textContent)
|
||||||
|
}))()`);
|
||||||
|
check('合并后标签栏可见', merged.hidden === false);
|
||||||
|
check('合并后保留全部 4 个标签(含空白欢迎页)', merged.n === 4, JSON.stringify(merged.names));
|
||||||
|
check('合并后标签名正确', ['A.md', 'B.md', 'C.md'].every((n) => merged.names.includes(n)), JSON.stringify(merged.names));
|
||||||
|
}
|
||||||
|
check('主进程模式为 tabs', main.getOpenMode() === 'tabs');
|
||||||
|
|
||||||
|
/* ---- 保存必须直接覆盖原文件,而不是弹另存为 ---- */
|
||||||
|
if (wins.length === 1) {
|
||||||
|
const before = fs.readFileSync(docs[0].path, 'utf8');
|
||||||
|
await wins[0].webContents.executeJavaScript(`(() => {
|
||||||
|
// 确保激活的是 A.md 标签
|
||||||
|
const idx = [...document.querySelectorAll('#tabbar .tab-name')].findIndex(e => e.textContent === 'A.md');
|
||||||
|
if (idx >= 0) document.querySelectorAll('#tabbar .tab')[idx].click();
|
||||||
|
})()`);
|
||||||
|
await wait(500);
|
||||||
|
await wins[0].webContents.executeJavaScript(`(() => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(editor.value.length, editor.value.length);
|
||||||
|
document.execCommand('insertText', false, '\\n保存覆盖验证标记');
|
||||||
|
})()`);
|
||||||
|
await wait(250);
|
||||||
|
wins[0].webContents.send('cmd', 'save');
|
||||||
|
await wait(900);
|
||||||
|
const after = fs.readFileSync(docs[0].path, 'utf8');
|
||||||
|
check('保存直接覆盖原文件(A.md 内容已更新)', after.indexOf('保存覆盖验证标记') >= 0, after.slice(-60));
|
||||||
|
check('覆盖前原内容仍保留', before.indexOf('内容 A.md') >= 0);
|
||||||
|
const title = wins[0].getTitle();
|
||||||
|
check('保存后标题仍是 A.md', title.indexOf('A.md') >= 0, title);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n==== 模式迁移测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
const ws = require('windows-shortcuts');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// 用 USERPROFILE 而不是写死某个人的目录 —— 换机器/换用户名都能直接用。
|
||||||
|
const home = process.env.USERPROFILE || process.env.HOME;
|
||||||
|
const appDir = path.join(home, 'Apps', 'XiaoyinMarkdown');
|
||||||
|
const target = path.join(appDir, 'XiaoyinMarkdown.exe');
|
||||||
|
const workingDir = appDir;
|
||||||
|
const lnk = path.join(home, 'Desktop', '小银Markdown.lnk');
|
||||||
|
|
||||||
|
ws.create(
|
||||||
|
lnk,
|
||||||
|
{ target, workingDir, icon: target, iconIndex: 0, desc: '小银 Markdown 编辑器', runStyle: 1 },
|
||||||
|
(err) => {
|
||||||
|
if (err) {
|
||||||
|
console.log('ERR', err.message);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
ws.query(lnk, (e, d) => {
|
||||||
|
console.log(e ? 'QUERY ERR ' + e.message : JSON.stringify(d, null, 2));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
/* 生成 Windows .lnk 快捷方式(纯字节拼装,不依赖 COM) */
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
function buildLnk({ target, workdir, icon, desc, args }) {
|
||||||
|
const isUnicode = true;
|
||||||
|
|
||||||
|
// ---- StringData ----
|
||||||
|
const strings = [];
|
||||||
|
const pushStr = (s) => {
|
||||||
|
if (s == null) return 0;
|
||||||
|
const chars = isUnicode ? 2 : 1;
|
||||||
|
const buf = Buffer.alloc(2 + s.length * chars);
|
||||||
|
buf.writeUInt16LE(s.length, 0);
|
||||||
|
if (isUnicode) buf.write(s, 2, 'utf16le');
|
||||||
|
else buf.write(s, 2, 'latin1');
|
||||||
|
strings.push(buf);
|
||||||
|
return 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
let flags = 0x00000002 /* HasLinkInfo */ | 0x00000004 /* HasName */;
|
||||||
|
const parts = [];
|
||||||
|
parts.push(pushStr(desc ? desc : null)); // NAME_STRING
|
||||||
|
if (target) { flags |= 0x00000008; parts.push(pushStr(null)); } // RELATIVE_PATH 占位(用 target)
|
||||||
|
if (workdir) { flags |= 0x00000010; parts.push(pushStr(workdir)); }
|
||||||
|
if (args) { flags |= 0x00000020; parts.push(pushStr(args)); }
|
||||||
|
if (icon) { flags |= 0x00000040; parts.push(pushStr(icon)); }
|
||||||
|
if (isUnicode) flags |= 0x00000080;
|
||||||
|
|
||||||
|
// 重新按顺序构建(NAME, RELATIVE_PATH, WORKING_DIR, ARGUMENTS, ICON)
|
||||||
|
strings.length = 0;
|
||||||
|
const seq = [];
|
||||||
|
const add = (s) => {
|
||||||
|
const buf = Buffer.alloc(2 + String(s).length * 2);
|
||||||
|
buf.writeUInt16LE(String(s).length, 0);
|
||||||
|
buf.write(String(s), 2, 'utf16le');
|
||||||
|
seq.push(buf);
|
||||||
|
};
|
||||||
|
if (desc) add(desc);
|
||||||
|
if (target) add(target); // RELATIVE_PATH
|
||||||
|
if (workdir) add(workdir);
|
||||||
|
if (args) add(args);
|
||||||
|
if (icon) add(icon);
|
||||||
|
const stringData = Buffer.concat(seq);
|
||||||
|
|
||||||
|
// ---- LinkInfo ----
|
||||||
|
const volumeLabel = Buffer.from([0x00]); // 空卷标
|
||||||
|
const volumeIdHeader = Buffer.alloc(16);
|
||||||
|
volumeIdHeader.writeUInt32LE(16 + volumeLabel.length, 0); // VolumeIDSize
|
||||||
|
volumeIdHeader.writeUInt32LE(3, 4); // DRIVE_FIXED
|
||||||
|
volumeIdHeader.writeUInt32LE(0x12345678, 8); // DriveSerialNumber
|
||||||
|
volumeIdHeader.writeUInt32LE(0x10, 12); // VolumeLabelOffset
|
||||||
|
const volumeId = Buffer.concat([volumeIdHeader, volumeLabel]);
|
||||||
|
|
||||||
|
const localBaseAnsi = Buffer.from(target + '\0', 'latin1');
|
||||||
|
const suffixAnsi = Buffer.from([0x00]);
|
||||||
|
const localBaseUni = Buffer.from(target + '\0', 'utf16le');
|
||||||
|
const suffixUni = Buffer.from([0x00, 0x00]);
|
||||||
|
|
||||||
|
const headerSize = 0x24;
|
||||||
|
const volumeIdOffset = headerSize;
|
||||||
|
const localBaseOffset = volumeIdOffset + volumeId.length;
|
||||||
|
const suffixOffset = localBaseOffset + localBaseAnsi.length;
|
||||||
|
const localBaseUniOffset = suffixOffset + suffixAnsi.length;
|
||||||
|
const suffixUniOffset = localBaseUniOffset + localBaseUni.length;
|
||||||
|
const linkInfoSize = suffixUniOffset + suffixUni.length;
|
||||||
|
|
||||||
|
const li = Buffer.alloc(headerSize);
|
||||||
|
li.writeUInt32LE(linkInfoSize, 0);
|
||||||
|
li.writeUInt32LE(headerSize, 4);
|
||||||
|
li.writeUInt32LE(0x00000001, 8); // VolumeIDAndLocalBasePath
|
||||||
|
li.writeUInt32LE(volumeIdOffset, 12);
|
||||||
|
li.writeUInt32LE(localBaseOffset, 16);
|
||||||
|
li.writeUInt32LE(0, 20); // CommonNetworkRelativeLinkOffset
|
||||||
|
li.writeUInt32LE(suffixOffset, 24);
|
||||||
|
li.writeUInt32LE(localBaseUniOffset, 28);
|
||||||
|
li.writeUInt32LE(suffixUniOffset, 32);
|
||||||
|
|
||||||
|
const linkInfo = Buffer.concat([li, volumeId, localBaseAnsi, suffixAnsi, localBaseUni, suffixUni]);
|
||||||
|
|
||||||
|
// ---- Header (76 bytes) ----
|
||||||
|
const h = Buffer.alloc(76);
|
||||||
|
h.writeUInt32LE(0x4c, 0);
|
||||||
|
// LinkCLSID {00021401-0000-0000-C000-000000000046}
|
||||||
|
Buffer.from('0114020000000000c000000000000046', 'hex').copy(h, 4);
|
||||||
|
h.writeUInt32LE(flags, 20);
|
||||||
|
h.writeUInt32LE(0x20, 24); // FILE_ATTRIBUTE_ARCHIVE
|
||||||
|
// 28 CreationTime / 36 AccessTime / 44 WriteTime 均留 0
|
||||||
|
h.writeUInt32LE(0, 52); // FileSize
|
||||||
|
h.writeUInt32LE(0, 56); // IconIndex
|
||||||
|
h.writeUInt32LE(1, 60); // ShowCommand = SW_SHOWNORMAL
|
||||||
|
h.writeUInt16LE(0, 64); // HotKey
|
||||||
|
h.writeUInt16LE(0, 66); // Reserved1
|
||||||
|
h.writeUInt32LE(0, 68); // Reserved2
|
||||||
|
h.writeUInt32LE(0, 72); // Reserved3
|
||||||
|
|
||||||
|
return Buffer.concat([h, linkInfo, stringData, Buffer.alloc(4)]); // 末尾 TerminalBlock
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = (process.argv[2] || '').replace(/\//g, '\\');
|
||||||
|
const out = process.argv[3];
|
||||||
|
if (!target || !out) {
|
||||||
|
console.error('usage: node tools/mklnk.js <target.exe> <out.lnk>');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const buf = buildLnk({
|
||||||
|
target,
|
||||||
|
workdir: path.dirname(target),
|
||||||
|
icon: target + ',0',
|
||||||
|
desc: '小银 Markdown 编辑器'
|
||||||
|
});
|
||||||
|
fs.writeFileSync(out, buf);
|
||||||
|
console.log('written', out, buf.length, 'bytes');
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
/* 验证:标签页、独立窗口偏好、右键打开方式、状态保留 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'multitest-'));
|
||||||
|
const a = path.join(tmp, 'A文档.md');
|
||||||
|
const b = path.join(tmp, 'B文档.md');
|
||||||
|
fs.writeFileSync(a, '# A 文档\n\n这是 A。\n', 'utf8');
|
||||||
|
fs.writeFileSync(b, '# B 文档\n\n这是 B。\n', 'utf8');
|
||||||
|
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
|
||||||
|
|
||||||
|
let forcedMode = 'tabs';
|
||||||
|
let lastNewWindow = '';
|
||||||
|
let lastNewBlank = 0;
|
||||||
|
let lastSetMode = '';
|
||||||
|
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('file:readText', async (_e, p) => ({ ok: true, text: fs.readFileSync(p, 'utf8') }));
|
||||||
|
ipcMain.handle('file:copyFile', async () => ({ ok: true }));
|
||||||
|
ipcMain.handle('file:revealPath', async () => ({ ok: true }));
|
||||||
|
ipcMain.handle('clip:read', () => '');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.handle('app:getOpenMode', async () => ({ mode: forcedMode }));
|
||||||
|
ipcMain.handle('app:setOpenMode', async (_e, m) => { lastSetMode = m; forcedMode = m; return { ok: true }; });
|
||||||
|
ipcMain.handle('window:openPath', async (_e, p) => { lastNewWindow = p || ''; return { ok: true }; });
|
||||||
|
ipcMain.handle('window:new', async () => { lastNewBlank++; return { ok: true }; });
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
ipcMain.on('file:drop', () => {});
|
||||||
|
ipcMain.on('file:droppedText', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1400, height: 880, show: true,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
await js(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1300);
|
||||||
|
|
||||||
|
/* 1. 初始标签 */
|
||||||
|
const init = await js(`(() => ({
|
||||||
|
visible: !document.getElementById('tabbar').hidden,
|
||||||
|
n: document.querySelectorAll('#tabbar .tab').length,
|
||||||
|
label: document.getElementById('openmode-label').textContent
|
||||||
|
}))()`);
|
||||||
|
check('默认标签栏可见且有 1 个标签', init.visible === true && init.n === 1, JSON.stringify(init));
|
||||||
|
check('按钮显示「标签」', init.label === '标签', init.label);
|
||||||
|
|
||||||
|
/* 2. 打开两个文件 → 两个新标签 */
|
||||||
|
win.webContents.send('cmd', 'file-opened', { ok: true, path: a, name: 'A文档.md', text: fs.readFileSync(a, 'utf8'), eol: '\n' });
|
||||||
|
await wait(300);
|
||||||
|
win.webContents.send('cmd', 'file-opened', { ok: true, path: b, name: 'B文档.md', text: fs.readFileSync(b, 'utf8'), eol: '\n' });
|
||||||
|
await wait(400);
|
||||||
|
const two = await js(`(() => ({
|
||||||
|
n: document.querySelectorAll('#tabbar .tab').length,
|
||||||
|
active: document.querySelector('#tabbar .tab.active .tab-name').textContent,
|
||||||
|
val: editor.value.slice(0, 6),
|
||||||
|
names: [...document.querySelectorAll('#tabbar .tab-name')].map(e => e.textContent)
|
||||||
|
}))()`);
|
||||||
|
check('打开两个文件得到 3 个标签', two.n === 3, JSON.stringify(two.names));
|
||||||
|
check('当前标签是最后打开的文件', two.active === 'B文档.md', two.active);
|
||||||
|
check('编辑区显示当前标签内容', two.val.indexOf('B 文档') >= 0, two.val);
|
||||||
|
|
||||||
|
/* 3. 切换标签,各自状态保留 */
|
||||||
|
await js(`(() => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(editor.value.length, editor.value.length);
|
||||||
|
document.execCommand('insertText', false, '\\nB 的修改');
|
||||||
|
})()`);
|
||||||
|
await wait(250);
|
||||||
|
await js(`document.querySelectorAll('#tabbar .tab')[1].click()`);
|
||||||
|
await wait(350);
|
||||||
|
const switched = await js(`(() => ({
|
||||||
|
active: document.querySelector('#tabbar .tab.active .tab-name').textContent,
|
||||||
|
val: editor.value.slice(0, 6)
|
||||||
|
}))()`);
|
||||||
|
check('点标签切到 A 文档', switched.active === 'A文档.md' && switched.val.indexOf('A 文档') >= 0, JSON.stringify(switched));
|
||||||
|
|
||||||
|
await js(`document.querySelectorAll('#tabbar .tab')[2].click()`);
|
||||||
|
await wait(350);
|
||||||
|
const back = await js(`editor.value.includes('B 的修改')`);
|
||||||
|
check('切回后 B 的修改还在', back === true);
|
||||||
|
|
||||||
|
/* 4. 重复打开同一文件不新增标签 */
|
||||||
|
win.webContents.send('cmd', 'file-opened', { ok: true, path: a, name: 'A文档.md', text: fs.readFileSync(a, 'utf8'), eol: '\n' });
|
||||||
|
await wait(350);
|
||||||
|
const dup = await js(`document.querySelectorAll('#tabbar .tab').length`);
|
||||||
|
check('重复打开同一文件不新建标签', dup === 3, String(dup));
|
||||||
|
|
||||||
|
/* 5. 关闭标签 */
|
||||||
|
await js(`document.querySelectorAll('#tabbar .tab-close')[2].click()`);
|
||||||
|
await wait(400);
|
||||||
|
const closed = await js(`(() => ({ n: document.querySelectorAll('#tabbar .tab').length, active: document.querySelector('#tabbar .tab.active .tab-name').textContent }))()`);
|
||||||
|
check('关闭标签后数量减 1', closed.n === 2, JSON.stringify(closed));
|
||||||
|
check('关闭后切到相邻标签', ['A文档.md', '未命名'].includes(closed.active), closed.active);
|
||||||
|
|
||||||
|
/* 6. 切换到独立窗口模式 */
|
||||||
|
const modeInfo = await js(`(async () => {
|
||||||
|
document.getElementById('btn-openmode').click();
|
||||||
|
await new Promise(r => setTimeout(r, 350));
|
||||||
|
return {
|
||||||
|
hidden: document.getElementById('tabbar').hidden,
|
||||||
|
label: document.getElementById('openmode-label').textContent,
|
||||||
|
ls: localStorage.getItem('md-editor-open-mode')
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('切到窗口模式后标签栏隐藏', modeInfo.hidden === true, JSON.stringify(modeInfo));
|
||||||
|
check('按钮文字变为「窗口」', modeInfo.label === '窗口', modeInfo.label);
|
||||||
|
check('模式写入本地存储', modeInfo.ls === 'windows', modeInfo.ls);
|
||||||
|
check('模式同步到主进程', lastSetMode === 'windows', lastSetMode);
|
||||||
|
|
||||||
|
/* 7. 窗口模式下右键显示「在新窗口打开」,且真的走新窗口 */
|
||||||
|
const ctxWin = await js(`(() => {
|
||||||
|
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('A文档.md'));
|
||||||
|
if (!row) return { err: 'no row' };
|
||||||
|
const p = row.dataset.path;
|
||||||
|
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
|
||||||
|
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
|
||||||
|
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
|
||||||
|
const first = items[0] ? lab(items[0]) : '';
|
||||||
|
const target = items.find(i => lab(i) === '在新窗口打开');
|
||||||
|
if (target) target.click();
|
||||||
|
return { first, exists: !!target, path: p };
|
||||||
|
})()`).catch(async () => {
|
||||||
|
// executeJavaScript 里不能引用 win,重来一次
|
||||||
|
return js(`(() => {
|
||||||
|
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('A文档.md'));
|
||||||
|
if (!row) return { err: 'no row' };
|
||||||
|
const p = row.dataset.path;
|
||||||
|
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
|
||||||
|
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
|
||||||
|
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
|
||||||
|
const first = items[0] ? lab(items[0]) : '';
|
||||||
|
const target = items.find(i => lab(i) === '在新窗口打开');
|
||||||
|
if (target) target.click();
|
||||||
|
return { first, exists: !!target, path: p };
|
||||||
|
})()`);
|
||||||
|
});
|
||||||
|
await wait(350);
|
||||||
|
check('窗口模式右键首项是「在新窗口打开」', ctxWin.first === '在新窗口打开', JSON.stringify(ctxWin));
|
||||||
|
check('右键触发了独立窗口打开', lastNewWindow === a, lastNewWindow);
|
||||||
|
|
||||||
|
/* 8. 切回标签模式,右键变「在新标签打开」 */
|
||||||
|
await js(`document.getElementById('btn-openmode').click()`);
|
||||||
|
await wait(350);
|
||||||
|
const ctxTab = await js(`(() => {
|
||||||
|
const row = [...document.querySelectorAll('#sb-body .tree-row')].find(r => r.dataset.path.endsWith('B文档.md'));
|
||||||
|
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 260, clientY: 200 }));
|
||||||
|
const items = [...document.querySelectorAll('#ctxmenu .ctx-item')];
|
||||||
|
const lab = (i) => { const s = i.querySelector('span'); return s ? s.textContent : ''; };
|
||||||
|
const first = items[0] ? lab(items[0]) : '';
|
||||||
|
const target = items.find(i => lab(i) === '在新标签打开');
|
||||||
|
if (target) target.click();
|
||||||
|
return { first, exists: !!target };
|
||||||
|
})()`);
|
||||||
|
await wait(450);
|
||||||
|
check('标签模式右键首项是「在新标签打开」', ctxTab.first === '在新标签打开', JSON.stringify(ctxTab));
|
||||||
|
const afterCtx = await js(`(() => ({ n: document.querySelectorAll('#tabbar .tab').length, val: editor.value.slice(0,6) }))()`);
|
||||||
|
check('右键在新标签打开生效', afterCtx.val.indexOf('B 文档') >= 0, JSON.stringify(afterCtx));
|
||||||
|
|
||||||
|
/* 9. 重启后保持模式 */
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1300);
|
||||||
|
const kept = await js(`(() => ({
|
||||||
|
hidden: document.getElementById('tabbar').hidden,
|
||||||
|
label: document.getElementById('openmode-label').textContent,
|
||||||
|
tabs: document.querySelectorAll('#tabbar .tab').length
|
||||||
|
}))()`);
|
||||||
|
check('重启后保持标签模式', kept.hidden === false && kept.label === '标签', JSON.stringify(kept));
|
||||||
|
check('重启后有欢迎标签', kept.tabs === 1, String(kept.tabs));
|
||||||
|
|
||||||
|
/* 9.5 关闭欢迎页后,下次启动不再显示 */
|
||||||
|
const hadWelcome = await js(`editor.value.indexOf('欢迎使用') >= 0`);
|
||||||
|
await js(`document.querySelectorAll('#tabbar .tab-close')[0].click()`);
|
||||||
|
await wait(450);
|
||||||
|
const flag = await js(`localStorage.getItem('md-editor-welcome-closed')`);
|
||||||
|
check('初始打开的是欢迎页', hadWelcome === true);
|
||||||
|
check('关闭欢迎页后写入标记', flag === '1', flag);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1300);
|
||||||
|
const afterClose = await js(`(() => ({
|
||||||
|
tabs: document.querySelectorAll('#tabbar .tab').length,
|
||||||
|
name: (document.querySelector('#tabbar .tab-name') || {}).textContent || '',
|
||||||
|
val: editor.value
|
||||||
|
}))()`);
|
||||||
|
check('重启后不再显示欢迎页', afterClose.val.indexOf('欢迎使用') < 0, JSON.stringify(afterClose.val.slice(0, 20)));
|
||||||
|
check('重启后是空白未命名标签', afterClose.tabs === 1 && afterClose.name === '未命名' && afterClose.val === '', JSON.stringify({ name: afterClose.name, len: afterClose.val.length }));
|
||||||
|
|
||||||
|
/* 10. 主进程偏好为 windows 时启动即窗口模式 */
|
||||||
|
forcedMode = 'windows';
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1300);
|
||||||
|
const fromMain = await js(`(() => ({
|
||||||
|
hidden: document.getElementById('tabbar').hidden,
|
||||||
|
label: document.getElementById('openmode-label').textContent
|
||||||
|
}))()`);
|
||||||
|
check('主进程偏好为窗口时启动即窗口模式', fromMain.hidden === true && fromMain.label === '窗口', JSON.stringify(fromMain));
|
||||||
|
|
||||||
|
console.log('\n==== 多窗口/标签测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
/* 验证章节目录:生成、开关、跳转、随编辑更新、状态记忆 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async () => ({ ok: false }));
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('clip:read', () => '');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1360, height: 860, show: true,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
await win.webContents.executeJavaScript(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await new Promise((r) => setTimeout(r, 1800));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
// 清掉上次遗留的偏好,保证从"全新用户"状态开始
|
||||||
|
await js(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1200);
|
||||||
|
|
||||||
|
/* 1. 默认显示且能生成大纲 */
|
||||||
|
const init = await js(`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('.ol-item')];
|
||||||
|
const heads = [...preview.querySelectorAll('h1,h2,h3,h4,h5,h6')];
|
||||||
|
return {
|
||||||
|
visible: !document.getElementById('outline').hidden,
|
||||||
|
count: rows.length,
|
||||||
|
heads: heads.length,
|
||||||
|
label: document.getElementById('ol-count').textContent,
|
||||||
|
btnOn: document.getElementById('btn-outline').classList.contains('on'),
|
||||||
|
first: rows[0] ? rows[0].textContent : '',
|
||||||
|
levels: rows.slice(0, 4).map(r => r.dataset.level)
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('默认显示章节目录', init.visible === true);
|
||||||
|
check('大纲条数等于标题数', init.count > 0 && init.count === init.heads, init.count + ' vs ' + init.heads);
|
||||||
|
check('计数徽标同步', init.label === String(init.count), init.label);
|
||||||
|
check('右上角按钮为开启态', init.btnOn === true);
|
||||||
|
check('首条是欢迎标题', init.first.indexOf('欢迎使用') >= 0, init.first);
|
||||||
|
check('层级信息正确', init.levels[0] === '1', JSON.stringify(init.levels));
|
||||||
|
|
||||||
|
/* 2. 关闭按钮 */
|
||||||
|
const closed = await js(`(() => {
|
||||||
|
document.getElementById('ol-close').click();
|
||||||
|
return { hidden: document.getElementById('outline').hidden, on: document.getElementById('btn-outline').classList.contains('on'), ls: localStorage.getItem('md-editor-outline') };
|
||||||
|
})()`);
|
||||||
|
check('点关闭后大纲隐藏', closed.hidden === true);
|
||||||
|
check('关闭后按钮取消高亮', closed.on === false);
|
||||||
|
check('关闭状态被记住', closed.ls === '0', closed.ls);
|
||||||
|
|
||||||
|
/* 3. 用右上角按钮再打开 */
|
||||||
|
const reopened = await js(`(() => {
|
||||||
|
document.getElementById('btn-outline').click();
|
||||||
|
return { hidden: document.getElementById('outline').hidden, on: document.getElementById('btn-outline').classList.contains('on'), rows: document.querySelectorAll('.ol-item').length };
|
||||||
|
})()`);
|
||||||
|
check('右上角按钮可重新打开', reopened.hidden === false && reopened.on === true);
|
||||||
|
check('重新打开后条目仍在', reopened.rows === init.count, String(reopened.rows));
|
||||||
|
|
||||||
|
/* 4. 快捷键 / 菜单命令切换 */
|
||||||
|
win.webContents.send('cmd', 'outline');
|
||||||
|
await wait(200);
|
||||||
|
const byCmd = await js(`document.getElementById('outline').hidden`);
|
||||||
|
check('菜单命令可切换大纲', byCmd === true);
|
||||||
|
win.webContents.send('cmd', 'outline');
|
||||||
|
await wait(200);
|
||||||
|
const byCmd2 = await js(`document.getElementById('outline').hidden`);
|
||||||
|
check('再切一次恢复显示', byCmd2 === false);
|
||||||
|
|
||||||
|
/* 5. 点击大纲跳转 */
|
||||||
|
const jump = await js(`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('.ol-item')];
|
||||||
|
const heads = [...preview.querySelectorAll('h1,h2,h3,h4,h5,h6')];
|
||||||
|
const target = rows[2];
|
||||||
|
const expectLine = Number(heads[2].dataset.line);
|
||||||
|
target.click();
|
||||||
|
return { expectLine, activeIdx: rows.indexOf(document.querySelector('.ol-item.active')) };
|
||||||
|
})()`);
|
||||||
|
await wait(700);
|
||||||
|
const jumped = await js(`(() => {
|
||||||
|
const pos = editor.selectionStart;
|
||||||
|
const line = editor.value.slice(0, pos).split('\\n').length - 1;
|
||||||
|
return { line, active: [...document.querySelectorAll('.ol-item')].findIndex(r => r.classList.contains('active')), pTop: preview.scrollTop };
|
||||||
|
})()`);
|
||||||
|
check('点击大纲定位到源码对应行', jumped.line === jump.expectLine, jumped.line + ' vs ' + jump.expectLine);
|
||||||
|
check('点击后大纲高亮该项', jumped.active === 2, String(jumped.active));
|
||||||
|
check('阅读区同步滚动', jumped.pTop > 0 || jump.expectLine === 0, String(jumped.pTop));
|
||||||
|
|
||||||
|
/* 6. 编辑内容后大纲实时更新 */
|
||||||
|
const updated = await js(`(async () => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(editor.value.length, editor.value.length);
|
||||||
|
document.execCommand('insertText', false, '\\n\\n## 新增的一个章节\\n\\n正文\\n\\n### 三级小节\\n');
|
||||||
|
await new Promise(r => setTimeout(r, 350));
|
||||||
|
const rows = [...document.querySelectorAll('.ol-item')];
|
||||||
|
return { count: rows.length, last: rows[rows.length - 1].textContent, hasNew: rows.some(r => r.textContent === '新增的一个章节') };
|
||||||
|
})()`);
|
||||||
|
check('新增标题后大纲自动更新', updated.hasNew === true && updated.count === init.count + 2, JSON.stringify(updated));
|
||||||
|
check('三级标题也被收录', updated.last === '三级小节', updated.last);
|
||||||
|
|
||||||
|
/* 7. 无标题文档显示空提示 */
|
||||||
|
const empty = await js(`(async () => {
|
||||||
|
editor.value = '只有正文,没有任何标题。\\n';
|
||||||
|
editor.dispatchEvent(new Event('input'));
|
||||||
|
await new Promise(r => setTimeout(r, 350));
|
||||||
|
return { rows: document.querySelectorAll('.ol-item').length, tip: document.querySelector('.ol-empty') ? document.querySelector('.ol-empty').textContent : '', label: document.getElementById('ol-count').textContent };
|
||||||
|
})()`);
|
||||||
|
check('无标题时给出空提示', empty.rows === 0 && empty.tip.length > 0, empty.tip);
|
||||||
|
check('无标题时计数为 0', empty.label === '0');
|
||||||
|
|
||||||
|
/* 8. 重启后保持隐藏状态 */
|
||||||
|
await js(`document.getElementById('ol-close').click()`);
|
||||||
|
await wait(200);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1100);
|
||||||
|
const kept = await js(`({ hidden: document.getElementById('outline').hidden, rows: document.querySelectorAll('.ol-item').length })`);
|
||||||
|
check('重启后保持上次的显示状态', kept.hidden === true, String(kept.hidden));
|
||||||
|
check('重启后大纲仍能生成', kept.rows > 0, String(kept.rows));
|
||||||
|
|
||||||
|
console.log('\n==== 章节目录测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
/* 验证:目录/大纲宽度可拖拽、写入本地存储、重启恢复、分隔条跟随面板显隐 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'paneltest-'));
|
||||||
|
fs.writeFileSync(path.join(tmp, '文档.md'), '# 文档\n\n正文。\n', 'utf8');
|
||||||
|
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
|
||||||
|
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('file:readText', async (_e, p) => ({ ok: true, text: fs.readFileSync(p, 'utf8') }));
|
||||||
|
ipcMain.handle('file:copyFile', async () => ({ ok: true }));
|
||||||
|
ipcMain.handle('file:revealPath', async () => ({ ok: true }));
|
||||||
|
ipcMain.handle('clip:read', () => ''); ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true })); ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.handle('app:getOpenMode', async () => ({ mode: 'tabs' }));
|
||||||
|
ipcMain.handle('app:setOpenMode', async () => ({ ok: true }));
|
||||||
|
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {}); ipcMain.on('docs:exported', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1440, height: 900, show: true,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
await js(`localStorage.clear(); localStorage.setItem('md-editor-dir', ${JSON.stringify(tmp)});`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1400);
|
||||||
|
|
||||||
|
/* 1. 初始宽度与分隔条存在 */
|
||||||
|
const init = await js(`(() => ({
|
||||||
|
sb: document.getElementById('sidebar').getBoundingClientRect().width,
|
||||||
|
ol: document.getElementById('outline').getBoundingClientRect().width,
|
||||||
|
sbSp: !document.getElementById('sb-splitter').hidden,
|
||||||
|
olSp: !document.getElementById('ol-splitter').hidden
|
||||||
|
}))()`);
|
||||||
|
check('分隔条存在且可见', init.sbSp === true && init.olSp === true, JSON.stringify(init));
|
||||||
|
check('目录初始宽度约 232', Math.abs(init.sb - 232) < 4, String(init.sb));
|
||||||
|
check('大纲初始宽度约 210', Math.abs(init.ol - 210) < 4, String(init.ol));
|
||||||
|
|
||||||
|
/* 2. 拖拽目录变宽 */
|
||||||
|
const sbDrag = await js(`(() => {
|
||||||
|
const before = document.getElementById('sidebar').getBoundingClientRect().width;
|
||||||
|
const sp = document.getElementById('sb-splitter');
|
||||||
|
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: before + 6 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: before + 146 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
|
||||||
|
const after = document.getElementById('sidebar').getBoundingClientRect().width;
|
||||||
|
return { before, after, saved: localStorage.getItem('md-editor-sb-w') };
|
||||||
|
})()`);
|
||||||
|
check('拖拽后目录变宽约 150px', Math.abs(sbDrag.after - sbDrag.before - 140) < 25, JSON.stringify(sbDrag));
|
||||||
|
check('目录宽度写入本地存储', !!sbDrag.saved && Math.abs(Number(sbDrag.saved) - sbDrag.after) < 3, sbDrag.saved);
|
||||||
|
|
||||||
|
/* 3. 拖拽大纲变宽(分隔条在大纲左边缘,向左拖 = 变宽) */
|
||||||
|
const olDrag = await js(`(() => {
|
||||||
|
const ol = document.getElementById('outline');
|
||||||
|
const before = ol.getBoundingClientRect().width;
|
||||||
|
const left = ol.getBoundingClientRect().left;
|
||||||
|
const sp = document.getElementById('ol-splitter');
|
||||||
|
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: left + 2 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: left - 98 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
|
||||||
|
const after = ol.getBoundingClientRect().width;
|
||||||
|
return { before, after, saved: localStorage.getItem('md-editor-ol-w') };
|
||||||
|
})()`);
|
||||||
|
check('拖拽后大纲变宽约 100px', Math.abs(olDrag.after - olDrag.before - 98) < 20, JSON.stringify(olDrag));
|
||||||
|
check('大纲宽度写入本地存储', !!olDrag.saved && Math.abs(Number(olDrag.saved) - olDrag.after) < 3, olDrag.saved);
|
||||||
|
|
||||||
|
/* 4. 重启后宽度恢复 */
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1400);
|
||||||
|
const kept = await js(`(() => ({
|
||||||
|
sb: document.getElementById('sidebar').getBoundingClientRect().width,
|
||||||
|
ol: document.getElementById('outline').getBoundingClientRect().width
|
||||||
|
}))()`);
|
||||||
|
check('重启后目录宽度恢复', Math.abs(kept.sb - sbDrag.after) < 4, JSON.stringify(kept));
|
||||||
|
check('重启后大纲宽度恢复', Math.abs(kept.ol - olDrag.after) < 4, JSON.stringify(kept));
|
||||||
|
|
||||||
|
/* 5. 最小宽度限制(放在恢复验证之后,避免覆盖已保存的宽度) */
|
||||||
|
const minTest = await js(`(() => {
|
||||||
|
document.getElementById('sb-splitter').dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: 300 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 2 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
|
||||||
|
return document.getElementById('sidebar').getBoundingClientRect().width;
|
||||||
|
})()`);
|
||||||
|
check('目录宽度不会被拖到小于 180', minTest >= 180 && minTest < 220, String(minTest));
|
||||||
|
|
||||||
|
/* 6. 关闭面板时分隔条跟随隐藏 */
|
||||||
|
await js(`document.getElementById('sb-close').click()`);
|
||||||
|
await wait(200);
|
||||||
|
const sbHidden = await js(`document.getElementById('sb-splitter').hidden`);
|
||||||
|
check('目录隐藏时分隔条跟随隐藏', sbHidden === true);
|
||||||
|
await js(`document.getElementById('ol-close').click()`);
|
||||||
|
await wait(200);
|
||||||
|
const olHidden = await js(`document.getElementById('ol-splitter').hidden`);
|
||||||
|
check('大纲隐藏时分隔条跟随隐藏', olHidden === true);
|
||||||
|
|
||||||
|
/* 7. 重新打开时分隔条恢复,宽度仍是记住的值 */
|
||||||
|
await js(`(() => {
|
||||||
|
localStorage.setItem('md-editor-sb', '0');
|
||||||
|
document.getElementById('btn-tree').click();
|
||||||
|
})()`);
|
||||||
|
await wait(250);
|
||||||
|
await js(`document.getElementById('btn-outline').click()`);
|
||||||
|
await wait(250);
|
||||||
|
const reopened = await js(`(() => ({
|
||||||
|
sbSp: !document.getElementById('sb-splitter').hidden,
|
||||||
|
olSp: !document.getElementById('ol-splitter').hidden,
|
||||||
|
sb: document.getElementById('sidebar').getBoundingClientRect().width,
|
||||||
|
ol: document.getElementById('outline').getBoundingClientRect().width
|
||||||
|
}))()`);
|
||||||
|
check('重新打开后分隔条恢复', reopened.sbSp === true && reopened.olSp === true, JSON.stringify(reopened));
|
||||||
|
const savedNow = await js(`({ sb: localStorage.getItem('md-editor-sb-w'), ol: localStorage.getItem('md-editor-ol-w') })`);
|
||||||
|
check('重新打开后宽度与保存值一致',
|
||||||
|
Math.abs(reopened.sb - Number(savedNow.sb)) < 4 && Math.abs(reopened.ol - Number(savedNow.ol)) < 4,
|
||||||
|
JSON.stringify({ reopened, savedNow }));
|
||||||
|
|
||||||
|
/* 8. 编辑/预览分栏比例记忆 */
|
||||||
|
const splitDrag = await js(`(() => {
|
||||||
|
const ws = document.getElementById('workspace');
|
||||||
|
const rect = ws.getBoundingClientRect();
|
||||||
|
const sp = document.getElementById('splitter');
|
||||||
|
const before = document.getElementById('editor-pane').getBoundingClientRect().width;
|
||||||
|
sp.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: rect.left + before }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: rect.left + rect.width * 0.62 }));
|
||||||
|
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
|
||||||
|
const after = document.getElementById('editor-pane').getBoundingClientRect().width;
|
||||||
|
return { before, after, pct: localStorage.getItem('md-editor-split-pct') };
|
||||||
|
})()`);
|
||||||
|
check('拖拽分栏后比例写入存储', !!splitDrag.pct && Math.abs(Number(splitDrag.pct) - 0.62) < 0.05, JSON.stringify(splitDrag));
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1400);
|
||||||
|
const splitKept = await js(`document.getElementById('editor-pane').getBoundingClientRect().width / document.getElementById('workspace').getBoundingClientRect().width`);
|
||||||
|
check('重启后分栏比例恢复', Math.abs(splitKept - 0.62) < 0.03, String(splitKept));
|
||||||
|
|
||||||
|
console.log('\n==== 面板宽度测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
const theme = process.env.SHOT_THEME || 'light';
|
||||||
|
const out = process.env.SHOT_OUT || path.join(__dirname, '..', 'shot.png');
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shotdir-'));
|
||||||
|
const mk = (n, c) => fs.writeFileSync(path.join(tmp, n), c, 'utf8');
|
||||||
|
mk('产品需求说明.md', '# 产品需求说明\n\n## 目标\n\n做一个**纯本地**的 Markdown 编辑器。\n\n- 实时预览\n- 右键复制全文\n- 拖进来就打开\n\n> 不联网,不登录。\n');
|
||||||
|
mk('API 设计.md', '# API\n');
|
||||||
|
mk('更新日志.md', '# 更新日志\n');
|
||||||
|
mk('readme.txt', 'txt\n');
|
||||||
|
fs.mkdirSync(path.join(tmp, '草稿'));
|
||||||
|
fs.writeFileSync(path.join(tmp, '草稿', '想法.md'), '# 想法\n', 'utf8');
|
||||||
|
|
||||||
|
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
|
||||||
|
.filter(d => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map(d => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }))
|
||||||
|
.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
|
||||||
|
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: list() }));
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false }));
|
||||||
|
ipcMain.handle('clip:read', () => ''); ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true })); ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.on('app:setDirty', () => {}); ipcMain.on('win:setTitle', () => {}); ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({ width: 1380, height: 880, show: true, backgroundColor: '#fff',
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false } });
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
await win.webContents.executeJavaScript(`localStorage.setItem('md-editor-theme', ${JSON.stringify(theme)}); document.documentElement.dataset.theme = ${JSON.stringify(theme)};`);
|
||||||
|
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
|
||||||
|
await new Promise(r => setTimeout(r, 500));
|
||||||
|
win.webContents.send('cmd', 'file-opened', { ok: true, path: path.join(tmp, '产品需求说明.md'), name: '产品需求说明.md', text: fs.readFileSync(path.join(tmp, '产品需求说明.md'), 'utf8'), eol: '\n' });
|
||||||
|
await new Promise(r => setTimeout(r, 1400));
|
||||||
|
const img = await win.webContents.capturePage();
|
||||||
|
fs.writeFileSync(out, img.toPNG());
|
||||||
|
console.log('saved', out);
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/* 验证:启动即显示侧栏、空态引导、记住上次文件夹 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const check = (n, ok, extra) => {
|
||||||
|
if (ok) { pass++; console.log('PASS ' + n); }
|
||||||
|
else { fail++; console.log('FAIL ' + n + (extra ? ' → ' + extra : '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sidetest-'));
|
||||||
|
fs.writeFileSync(path.join(tmp, '一篇.md'), '# 一篇\n', 'utf8');
|
||||||
|
fs.writeFileSync(path.join(tmp, '二篇.md'), '# 二篇\n', 'utf8');
|
||||||
|
|
||||||
|
const list = () => fs.readdirSync(tmp, { withFileTypes: true })
|
||||||
|
.filter((d) => !d.name.startsWith('.') && (d.isDirectory() || /\.(md|txt)$/i.test(d.name)))
|
||||||
|
.map((d) => ({ name: d.name, path: path.join(tmp, d.name), isDir: d.isDirectory() }));
|
||||||
|
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), text: fs.readFileSync(p, 'utf8'), eol: '\n' }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => {
|
||||||
|
if (!fs.existsSync(p)) return { ok: false };
|
||||||
|
return { ok: true, path: p, name: path.basename(p), entries: list() };
|
||||||
|
});
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('clip:read', () => '');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1280, height: 820, show: false,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
const js = (c) => win.webContents.executeJavaScript(c);
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
await wait(700);
|
||||||
|
|
||||||
|
// 1. 清空记忆后重新加载 = 首次启动
|
||||||
|
await js(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1100);
|
||||||
|
const first = await js(`({
|
||||||
|
visible: !document.getElementById('sidebar').hidden,
|
||||||
|
hasBtn: !!document.querySelector('.sb-pick-btn'),
|
||||||
|
title: document.getElementById('sb-title').textContent,
|
||||||
|
hasTree: document.querySelectorAll('#sb-body .tree-row').length
|
||||||
|
})`);
|
||||||
|
check('首次启动显示左侧目录(空态引导)', first.visible === true, JSON.stringify(first));
|
||||||
|
check('空态有「选择文件夹」按钮', first.hasBtn === true);
|
||||||
|
check('无文件夹时不渲染空条目', first.hasTree === 0);
|
||||||
|
check('面板标题为「目录」', first.title === '目录', first.title);
|
||||||
|
|
||||||
|
// 2. 打开文件夹后记录到本地
|
||||||
|
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmp, name: path.basename(tmp), entries: list() });
|
||||||
|
await wait(400);
|
||||||
|
const after = await js(`({ saved: localStorage.getItem('md-editor-dir'), rows: document.querySelectorAll('#sb-body .tree-row').length, title: document.getElementById('sb-title').textContent })`);
|
||||||
|
check('打开文件夹后写入记忆', after.saved === tmp, after.saved);
|
||||||
|
check('文件树列出两个文件', after.rows === 2, String(after.rows));
|
||||||
|
check('侧栏标题为文件夹名', after.title === path.basename(tmp), after.title);
|
||||||
|
|
||||||
|
// 3. 重启后自动恢复上次文件夹
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1100);
|
||||||
|
const restored = await js(`({
|
||||||
|
visible: !document.getElementById('sidebar').hidden,
|
||||||
|
title: document.getElementById('sb-title').textContent,
|
||||||
|
rows: [...document.querySelectorAll('#sb-body .tree-row')].map(r => r.querySelector('.tree-name').textContent)
|
||||||
|
})`);
|
||||||
|
check('重启后自动恢复上次文件夹', restored.visible === true && restored.rows.length === 2, JSON.stringify(restored));
|
||||||
|
check('恢复后标题正确', restored.title === path.basename(tmp));
|
||||||
|
|
||||||
|
// 4. 收起后下次启动保持收起
|
||||||
|
await js(`document.getElementById('sb-close').click()`);
|
||||||
|
await wait(200);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await wait(1100);
|
||||||
|
const kept = await js(`!document.getElementById('sidebar').hidden`);
|
||||||
|
check('用户收起后重启仍保持收起', kept === false, String(kept));
|
||||||
|
|
||||||
|
// 5. 工具栏按钮再次唤出
|
||||||
|
await js(`document.getElementById('btn-tree').click()`);
|
||||||
|
await wait(400);
|
||||||
|
const shown = await js(`({ hidden: document.getElementById('sidebar').hidden, rows: document.querySelectorAll('#sb-body .tree-row').length })`);
|
||||||
|
check('工具栏可重新唤出文件树', shown.hidden === false && shown.rows === 2, JSON.stringify(shown));
|
||||||
|
|
||||||
|
console.log('\n==== 侧栏测试:通过 ' + pass + ',失败 ' + fail + ' ====');
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
app.exit(fail ? 1 : 0);
|
||||||
|
});
|
||||||
+245
@@ -0,0 +1,245 @@
|
|||||||
|
/* 自测脚本:跑真实渲染进程逻辑,验证打开/编辑/保存/撤销/渲染/查找 */
|
||||||
|
const { app, BrowserWindow, ipcMain } = require('electron');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
function check(name, ok, extra) {
|
||||||
|
results.push({ name, ok: !!ok, extra });
|
||||||
|
console.log((ok ? 'PASS ' : 'FAIL ') + name + (extra ? ' → ' + extra : ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
app.whenReady().then(async () => {
|
||||||
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mdtest-'));
|
||||||
|
const tmpFile = path.join(tmpDir, '测试文档.md');
|
||||||
|
const sample = '# 标题一\n\n**粗体** 正文\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n- [x] 完成\n';
|
||||||
|
fs.writeFileSync(tmpFile, sample, 'utf8');
|
||||||
|
fs.mkdirSync(path.join(tmpDir, 'sub'));
|
||||||
|
fs.writeFileSync(path.join(tmpDir, 'sub', 'c.md'), '# 子文件\n\n内容\n', 'utf8');
|
||||||
|
fs.writeFileSync(path.join(tmpDir, '其他.txt'), 'hello\n', 'utf8');
|
||||||
|
fs.writeFileSync(path.join(tmpDir, 'pic.png'), 'not markdown\n', 'utf8');
|
||||||
|
|
||||||
|
// 模拟主进程的保存 handler
|
||||||
|
ipcMain.handle('file:save', async (_e, p) => {
|
||||||
|
let target = p.__target || tmpFile;
|
||||||
|
await fs.promises.writeFile(target, p.content, 'utf8');
|
||||||
|
return { ok: true, path: target, name: path.basename(target) };
|
||||||
|
});
|
||||||
|
ipcMain.handle('file:openPath', async (_e, p) => {
|
||||||
|
const text = fs.readFileSync(p, 'utf8');
|
||||||
|
return { ok: true, path: p, name: path.basename(p), text, eol: '\n' };
|
||||||
|
});
|
||||||
|
ipcMain.handle('clip:read', () => 'PASTED');
|
||||||
|
ipcMain.handle('clip:write', () => true);
|
||||||
|
ipcMain.handle('file:reveal', () => ({ ok: true }));
|
||||||
|
ipcMain.handle('ui:message', () => 0);
|
||||||
|
ipcMain.handle('shell:openExternal', () => true);
|
||||||
|
|
||||||
|
// 目录读取(与 main.js 的 listDir 保持同样的过滤规则)
|
||||||
|
const MD_RE = /\.(md|markdown|mdown|mkd|mdwn|txt)$/i;
|
||||||
|
const listDir = (dir) => {
|
||||||
|
const entries = [];
|
||||||
|
for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
if (d.name.startsWith('.') || d.name === 'node_modules') continue;
|
||||||
|
const full = path.join(dir, d.name);
|
||||||
|
const isDir = d.isDirectory();
|
||||||
|
if (!isDir && !MD_RE.test(d.name)) continue;
|
||||||
|
entries.push({ name: d.name, path: full, isDir });
|
||||||
|
}
|
||||||
|
entries.sort((a, b) => (Number(b.isDir) - Number(a.isDir)) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
|
||||||
|
return entries;
|
||||||
|
};
|
||||||
|
ipcMain.handle('dir:open', async () => ({ ok: false, canceled: true }));
|
||||||
|
ipcMain.handle('dir:read', async (_e, p) => ({ ok: true, path: p, name: path.basename(p), entries: listDir(p) }));
|
||||||
|
ipcMain.on('app:setDirty', () => {});
|
||||||
|
ipcMain.on('win:setTitle', () => {});
|
||||||
|
ipcMain.on('save:finished', () => {});
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: 1300, height: 860, show: false,
|
||||||
|
webPreferences: { preload: path.join(__dirname, '..', 'src', 'preload.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false }
|
||||||
|
});
|
||||||
|
await win.loadFile(path.join(__dirname, '..', 'src', 'renderer', 'index.html'));
|
||||||
|
await win.webContents.executeJavaScript(`localStorage.clear()`);
|
||||||
|
await win.webContents.reload();
|
||||||
|
await new Promise((r) => setTimeout(r, 900));
|
||||||
|
const js = (code) => win.webContents.executeJavaScript(code);
|
||||||
|
|
||||||
|
/* 1. 初始状态 */
|
||||||
|
const init = await js(`({ val: editor.value.length, h1: !!preview.querySelector('h1'), table: !!preview.querySelector('table'), dirty: !document.getElementById('st-dirty').hidden })`);
|
||||||
|
check('初始渲染:有 h1 与表格', init.h1 && init.table, JSON.stringify(init));
|
||||||
|
check('初始不标记未保存', init.dirty === false);
|
||||||
|
|
||||||
|
/* 2. 打开文件(走真实 cmd 通道) */
|
||||||
|
win.webContents.send('cmd', 'file-opened', { ok: true, path: tmpFile, name: '测试文档.md', text: sample, eol: '\n' });
|
||||||
|
await new Promise((r) => setTimeout(r, 400));
|
||||||
|
const opened = await js(`({ v: editor.value === ${JSON.stringify(sample)}, name: document.getElementById('st-file').textContent, dirty: !document.getElementById('st-dirty').hidden })`);
|
||||||
|
check('打开文件后编辑区内容正确', opened.v);
|
||||||
|
check('状态栏文件名更新', opened.name === '测试文档.md', opened.name);
|
||||||
|
check('打开后为已保存状态', opened.dirty === false);
|
||||||
|
|
||||||
|
/* 3. 编辑 → dirty */
|
||||||
|
await js(`(() => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(editor.value.length, editor.value.length);
|
||||||
|
document.execCommand('insertText', false, '\\n\\n新增一行 **内容**');
|
||||||
|
})()`);
|
||||||
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
|
const edited = await js(`({ dirty: !document.getElementById('st-dirty').hidden, hasNew: editor.value.includes('新增一行'), bold: !!preview.querySelector('strong') })`);
|
||||||
|
check('输入后标记未保存', edited.dirty === true);
|
||||||
|
check('插入文本成功', edited.hasNew === true);
|
||||||
|
check('预览同步出现粗体', edited.bold === true);
|
||||||
|
|
||||||
|
/* 4. 保存 */
|
||||||
|
await js(`document.getElementById('btn-save').click()`);
|
||||||
|
await new Promise((r) => setTimeout(r, 600));
|
||||||
|
const saved = fs.readFileSync(tmpFile, 'utf8');
|
||||||
|
const afterSave = await js(`!document.getElementById('st-dirty').hidden`);
|
||||||
|
check('保存后磁盘内容已更新', saved.includes('新增一行'), saved.length + ' bytes');
|
||||||
|
check('保存后清除未保存标记', afterSave === false);
|
||||||
|
|
||||||
|
/* 5. 撤销 / 重做 */
|
||||||
|
const undo = await js(`(() => {
|
||||||
|
const before = editor.value;
|
||||||
|
editor.focus();
|
||||||
|
const ok1 = document.execCommand('undo');
|
||||||
|
const afterUndo = editor.value;
|
||||||
|
const ok2 = document.execCommand('redo');
|
||||||
|
return { ok1, ok2, changed: afterUndo !== before, restored: editor.value === before };
|
||||||
|
})()`);
|
||||||
|
check('撤销生效(内容发生变化)', undo.changed === true, JSON.stringify(undo));
|
||||||
|
check('重做恢复内容', undo.restored === true);
|
||||||
|
|
||||||
|
/* 6. 粘贴(读剪贴板 → insertText) */
|
||||||
|
const paste = await js(`(async () => {
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(0, 0);
|
||||||
|
const t = await api.readClipboard();
|
||||||
|
document.execCommand('insertText', false, t);
|
||||||
|
return editor.value.startsWith('PASTED');
|
||||||
|
})()`);
|
||||||
|
check('粘贴插入到光标处', paste === true);
|
||||||
|
|
||||||
|
/* 7. 复制全文 */
|
||||||
|
const copyAll = await js(`(async () => {
|
||||||
|
await document.getElementById('btn-copyall').click();
|
||||||
|
await new Promise(r => setTimeout(r, 100));
|
||||||
|
return document.getElementById('toast').textContent;
|
||||||
|
})()`);
|
||||||
|
check('复制全文有提示反馈', /已复制全文/.test(copyAll), copyAll);
|
||||||
|
|
||||||
|
/* 8. 查找 */
|
||||||
|
const find = await js(`(async () => {
|
||||||
|
document.getElementById('btn-find').click();
|
||||||
|
const inp = document.getElementById('find-input');
|
||||||
|
inp.value = '标题';
|
||||||
|
inp.dispatchEvent(new Event('input'));
|
||||||
|
await new Promise(r => setTimeout(r, 100));
|
||||||
|
return { count: document.getElementById('find-count').textContent, sel: editor.selectionStart, selEnd: editor.selectionEnd };
|
||||||
|
})()`);
|
||||||
|
check('查找定位并显示计数', find.selEnd > find.sel, JSON.stringify(find));
|
||||||
|
|
||||||
|
/* 9. 模式切换 */
|
||||||
|
const modes = await js(`(() => {
|
||||||
|
const ws = document.getElementById('workspace');
|
||||||
|
document.querySelector('#mode-seg button[data-mode="read"]').click();
|
||||||
|
const a = ws.dataset.mode;
|
||||||
|
document.querySelector('#mode-seg button[data-mode="split"]').click();
|
||||||
|
return { a, b: ws.dataset.mode };
|
||||||
|
})()`);
|
||||||
|
check('模式切换正常', modes.a === 'read' && modes.b === 'split', JSON.stringify(modes));
|
||||||
|
|
||||||
|
/* 10. 文件夹树 */
|
||||||
|
win.webContents.send('cmd', 'dir-opened', { ok: true, path: tmpDir, name: path.basename(tmpDir), entries: listDir(tmpDir) });
|
||||||
|
await new Promise((r) => setTimeout(r, 400));
|
||||||
|
const tree = await js(`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
|
||||||
|
return {
|
||||||
|
visible: !document.getElementById('sidebar').hidden,
|
||||||
|
names: rows.map(r => r.querySelector('.tree-name').textContent),
|
||||||
|
dirs: rows.filter(r => r.classList.contains('is-dir')).length,
|
||||||
|
pngFiltered: !rows.some(r => r.querySelector('.tree-name').textContent.includes('pic.png'))
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
check('拖入文件夹后侧栏显示', tree.visible === true);
|
||||||
|
check('文件树列出文件与子目录', tree.names.includes('测试文档.md') && tree.names.includes('sub') && tree.dirs === 1, JSON.stringify(tree.names));
|
||||||
|
check('非 Markdown 文件被过滤', tree.pngFiltered === true);
|
||||||
|
|
||||||
|
/* 11. 展开子目录 */
|
||||||
|
await js(`(() => {
|
||||||
|
const r = [...document.querySelectorAll('.tree-row.is-dir')].find(x => x.dataset.path.endsWith('sub'));
|
||||||
|
if (r) r.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
|
||||||
|
})()`);
|
||||||
|
await new Promise((r) => setTimeout(r, 500));
|
||||||
|
const sub = await js(`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('#sb-body .tree-row')];
|
||||||
|
return { hasC: rows.some(r => r.dataset.path.endsWith('c.md')) };
|
||||||
|
})()`);
|
||||||
|
check('双击子目录可展开', sub.hasC === true, JSON.stringify(sub));
|
||||||
|
|
||||||
|
/* 12. 单击不切换,双击才打开文件 */
|
||||||
|
const beforeSingle = await js(`editor.value`);
|
||||||
|
const single = await js(`(() => {
|
||||||
|
const r = [...document.querySelectorAll('#sb-body .tree-row')].find(x => x.dataset.path.endsWith('c.md'));
|
||||||
|
if (!r) return false;
|
||||||
|
r.click();
|
||||||
|
return document.activeElement === r;
|
||||||
|
})()`);
|
||||||
|
await new Promise((r) => setTimeout(r, 350));
|
||||||
|
const afterSingle = await js(`editor.value`);
|
||||||
|
check('单击文件只选中不切换文档', single === true && afterSingle === beforeSingle, JSON.stringify(single));
|
||||||
|
|
||||||
|
await js(`(() => {
|
||||||
|
const r = [...document.querySelectorAll('#sb-body .tree-row')].find(x => x.dataset.path.endsWith('c.md'));
|
||||||
|
if (r) r.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
|
||||||
|
})()`);
|
||||||
|
await new Promise((r) => setTimeout(r, 700));
|
||||||
|
const byTree = await js(`(() => {
|
||||||
|
const act = document.querySelector('#sb-body .tree-row.active');
|
||||||
|
return { v: editor.value.indexOf('子文件') >= 0, name: document.getElementById('st-file').textContent, active: act ? act.dataset.path : '' };
|
||||||
|
})()`);
|
||||||
|
check('双击文件树打开文件', byTree.v === true, byTree.name);
|
||||||
|
check('树中高亮当前文件', String(byTree.active).endsWith('c.md'), byTree.active);
|
||||||
|
|
||||||
|
/* 13. 收起侧栏 */
|
||||||
|
const collapsed = await js(`(() => {
|
||||||
|
document.getElementById('sb-close').click();
|
||||||
|
const hidden1 = document.getElementById('sidebar').hidden;
|
||||||
|
document.getElementById('btn-tree').click();
|
||||||
|
return { hidden1, hidden2: document.getElementById('sidebar').hidden };
|
||||||
|
})()`);
|
||||||
|
check('侧栏可收起再展开', collapsed.hidden1 === true && collapsed.hidden2 === false, JSON.stringify(collapsed));
|
||||||
|
|
||||||
|
/* 10. 渲染引擎边界用例 */
|
||||||
|
const r = await js(`(() => {
|
||||||
|
const cases = {
|
||||||
|
code: MD.render('\\u0060\\u0060\\u0060py\\nprint(1)\\n\\u0060\\u0060\\u0060'),
|
||||||
|
nested: MD.render('- a\\n - b\\n - c'),
|
||||||
|
quote: MD.render('> 引用\\n> 第二行'),
|
||||||
|
hr: MD.render('---'),
|
||||||
|
xss: MD.render('<script>alert(1)</script>'),
|
||||||
|
tableAlign: MD.render('|a|b|\\n|:--|--:|\\n|1|2|'),
|
||||||
|
task: MD.render('- [x] done'),
|
||||||
|
escape: MD.render('a & b < c')
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
code: cases.code.includes('print(1)') && cases.code.includes('<pre>'),
|
||||||
|
nested: (cases.nested.match(/<ul>/g) || []).length === 3 && cases.nested.includes('<li>c</li>'),
|
||||||
|
quote: cases.quote.includes('<blockquote>'),
|
||||||
|
hr: cases.hr.includes('<hr>'),
|
||||||
|
xss: !cases.xss.includes('<script>') && cases.xss.includes('<script>'),
|
||||||
|
tableAlign: cases.tableAlign.includes('text-align:left'),
|
||||||
|
task: cases.task.includes('type="checkbox"') && cases.task.includes('checked'),
|
||||||
|
escape: cases.escape.includes('a & b < c')
|
||||||
|
};
|
||||||
|
})()`);
|
||||||
|
Object.keys(r).forEach((k) => check('渲染用例 ' + k, r[k]));
|
||||||
|
|
||||||
|
const failed = results.filter((x) => !x.ok);
|
||||||
|
console.log('\n==== 共 ' + results.length + ' 项,失败 ' + failed.length + ' 项 ====');
|
||||||
|
if (failed.length) console.log(failed.map((f) => f.name).join(', '));
|
||||||
|
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
app.exit(failed.length ? 1 : 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/* 用远程调试端口驱动真实 app,验证主进程确实能开出多个独立窗口 */
|
||||||
|
const { spawn } = require('node:child_process');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
|
const root = path.join(__dirname, '..');
|
||||||
|
const electron = path.join(root, 'node_modules', 'electron', 'dist', 'electron.exe');
|
||||||
|
const port = 9333;
|
||||||
|
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const target = path.join(root, 'README.md');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const env = { ...process.env };
|
||||||
|
delete env.ELECTRON_RUN_AS_NODE;
|
||||||
|
delete env.ELECTRON_NO_ATTACH_CONSOLE;
|
||||||
|
|
||||||
|
const child = spawn(electron, ['--remote-debugging-port=' + port, '.'], {
|
||||||
|
cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false
|
||||||
|
});
|
||||||
|
let err = '';
|
||||||
|
child.stderr.on('data', (d) => { err += d.toString(); });
|
||||||
|
|
||||||
|
let ok = false;
|
||||||
|
try {
|
||||||
|
await wait(3500);
|
||||||
|
const before = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
|
||||||
|
const pagesBefore = before.filter((p) => p.type === 'page');
|
||||||
|
console.log('窗口数(启动后):', pagesBefore.length);
|
||||||
|
|
||||||
|
if (pagesBefore.length) {
|
||||||
|
const page = pagesBefore[0];
|
||||||
|
const ws = new WebSocket(page.webSocketDebuggerUrl);
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
ws.onopen = resolve;
|
||||||
|
ws.onerror = reject;
|
||||||
|
});
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
id: 1,
|
||||||
|
method: 'Runtime.evaluate',
|
||||||
|
params: { expression: `api.openNewWindow(${JSON.stringify(target)})`, awaitPromise: true }
|
||||||
|
}));
|
||||||
|
await wait(400);
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
await wait(2500);
|
||||||
|
const after = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
|
||||||
|
const pagesAfter = after.filter((p) => p.type === 'page');
|
||||||
|
console.log('窗口数(新窗口打开后):', pagesAfter.length);
|
||||||
|
console.log('新窗口标题:', pagesAfter.map((p) => p.title).join(' | '));
|
||||||
|
ok = pagesAfter.length > pagesBefore.length;
|
||||||
|
console.log(ok ? 'PASS 主进程成功创建独立窗口' : 'FAIL 没有创建新窗口');
|
||||||
|
} catch (e) {
|
||||||
|
console.log('ERR:', e.message);
|
||||||
|
if (err) console.log('APP STDERR:', err.slice(0, 500));
|
||||||
|
} finally {
|
||||||
|
try { child.kill(); } catch (_) {}
|
||||||
|
setTimeout(() => process.exit(ok ? 0 : 1), 300);
|
||||||
|
}
|
||||||
|
})();
|
||||||
Reference in new issue
Block a user