feat: three-pane editor with rich preview, tables, images, and scroll sync
Some checks are pending
Test / test (macos-latest) (push) Waiting to run
Test / test (ubuntu-latest) (push) Waiting to run
Test / test (windows-latest) (push) Waiting to run

Add emoji + rich Markdown dual preview, MarkText-style tables, local/S3 images, settings UI, Electron 44, and update README.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hackrobot 2026-10-03 02:49:44 +08:00
parent de3ea81b91
commit 826f0bcf22
35 changed files with 7477 additions and 1669 deletions

View File

@ -180,11 +180,21 @@ const configuration: webpack.Configuration = {
hot: true,
headers: { 'Access-Control-Allow-Origin': '*' },
static: {
directory: path.join(webpackPaths.rootPath, 'public'),
publicPath: '/',
watch: {
ignored: /node_modules|[A-Z]:\\(DumpStack\.log\.tmp|pagefile\.sys|swapfile\.sys|System Volume Information)/,
},
},
historyApiFallback: {
verbose: true,
},
watchFiles: {
paths: ['src/**/*'],
options: {
ignored: /node_modules/,
},
},
setupMiddlewares(middlewares) {
console.log('Starting preload.js builder...');
const preloadProcess = spawn('npm', ['run', 'start:preload'], {

View File

@ -0,0 +1,5 @@
/**
* Dev bootstrap: load TypeScript main via tsx (works with Electron 34+ / Node 22+).
*/
require('tsx/cjs/api').register();
require('../src/main/main.ts');

View File

@ -1,6 +1,6 @@
# emojiTool
面向微信公众号、聊天框等**纯文本输入场景**的桌面 Markdown 工具:把 Markdown 转成带 Emoji / Unicode 装饰的纯文本,复制后可直接粘贴,不依赖 HTML/CSS 样式。
三栏桌面 Markdown 工具:左侧编辑、中间 **Emoji 纯文本预览**(微信/IM)、右侧 **长文富文本预览**。复制中间栏可直接粘贴到聊天框;右侧用于排版与发布预览。
- 产品名:**emojiTool**
- 窗口标题:emojiTool
@ -15,15 +15,18 @@
| 能力 | 说明 |
|------|------|
| Markdown 实时预览 | 左侧编辑、右侧预览,基于 `marked` 自定义 Renderer |
| 四套主题 A–D | 经典 / 青简 / 精简 / 聚焦,下拉切换 |
| 三栏联动 | 左编辑 / 中 Emoji 纯文本 / 右长文富文本;滚动按比例同步,语法与渲染对应 |
| Markdown 实时预览 | 基于 `marked`:中间栏自定义 Emoji Renderer,右侧栏 GFM 富文本 |
| 四套主题 A–D | 经典 / 青简 / 精简 / 聚焦;各预览栏独立切换主题与复制 |
| Emoji 装饰排版 | 标题边框、列表符号、任务勾选、引用、分隔线等用 Unicode/Emoji 呈现 |
| 一键复制 | 复制为纯文本(表格用全角字符网格,粘贴到微信/IM 仍可见结构) |
| 一键复制 | 中间栏复制纯文本(表格全角网格);右侧栏复制富文本 HTML |
| 可视化表格 | MarkText 风格插入/编辑表格,插入前可填单元格 |
| 本地图片 | 拖拽或右键选图插入;Markdown 使用标准 `images/xxx.png`;预览经本地协议显示 |
| 可选 S3 上传 | 设置中开启后,图片可上传到 MinIO/S3(默认端点可配) |
| 全局设置 | 页脚署名、S3 凭证与开关等,持久化到主进程配置 |
| 草稿自动保存 | 本地 `localStorage`(键:`emojitool.draft`) |
| 模板与片段 | 内置语法全览等模板;工具栏片段插入到**光标处** |
| 页脚开关 | 可关闭/编辑自动追加的署名 |
| 模板与片段 | 内置语法全览等模板;工具栏片段插入到光标处 |
| 左侧目录 | 解析 `#` 标题大纲,点击跳转 |
| 编辑模式 | MD 源码 / 普通编辑可切换 |
| 右键与快捷键 | MD 模式:右键插入;`Ctrl+B` 加粗、`Ctrl+I` 斜体、`Ctrl+K` 链接;`Ctrl+Enter` 复制;`Ctrl+S` 保存 |
| 外链菜单 | 异度世界 / mdemoji.com / 仓库 |
@ -38,33 +41,48 @@
- **引用**:`└─⚡`(多行各自成行)
- **分隔线**:`➖➖➖➖➖`
- **链接**:`🔗文案` + URL
- **图片**:纯文本 `🖼 说明:url`
- **图片**:纯文本 `🖼 说明:url`;长文栏正常渲染图片
- **表格**:全角字符网格(Theme B 为 pipe 风格)
## 技术栈
- **桌面**:Electron 26 + electron-builder
- **桌面**:Electron 44 + electron-builder 26
- **前端**:React 18、TypeScript、Ant Design 5、Sass Modules
- **Markdown**:marked
- **构建**:Webpack 5(ERB 配置)、electronmon 热重载
- **Markdown**:marked(Emoji 渲染 + 富文本双通道)
- **构建**:Webpack 5(ERB 配置)、electronmon + tsx 热重载主进程
## 目录结构
```
src/
├── main/ # Electron 主进程(窗口、菜单、自动更新)
├── main/ # Electron 主进程
│ ├── main.ts
│ ├── menu.ts
│ ├── preload.ts
│ ├── ipcHandlers.ts
│ ├── imageService.ts
│ ├── localImageProtocol.ts
│ ├── s3Upload.ts
│ ├── settingsStore.ts
│ └── util.ts
├── shared/ # 主进程/渲染进程共享类型
│ └── appSettings.ts
├── renderer/ # 渲染进程
│ ├── App.tsx # 布局与交互
│ ├── App.tsx # 三栏布局与交互
│ ├── App.module.scss
│ ├── index.ejs
│ ├── components/
│ │ └── EditorPane.tsx
│ │ ├── EditorPane.tsx
│ │ ├── SettingsModal.tsx
│ │ ├── TableInsertModal.tsx
│ │ ├── TableEditModal.tsx
│ │ └── TableEditorPanel.tsx
│ └── lib/
│ ├── emojiMarkdown.ts
│ ├── richMarkdown.ts
│ ├── mdTable.ts
│ ├── imageInsert.ts
│ ├── linkedScroll.ts
│ ├── themes.ts
│ ├── plainTable.ts
│ ├── toc.ts
@ -76,7 +94,7 @@ src/
## 开发
环境要求:Node.js ≥ 14,npm ≥ 7。
环境要求:Node.js ≥ 18,npm ≥ 9。
```bash
git checkout greenbook
@ -103,8 +121,9 @@ npm start
## 已知说明
- 包名 / `productName` 已统一为 **emojitool** / **emojiTool**。
- 暂无云同步、多窗口;草稿保存在本机。
- 复制优先 `innerText`,表格为全角字符网格(box / pipe / dots)。
- 草稿与设置保存在本机;S3 上传需在设置中自行配置。
- 图片写入 Markdown 为相对路径 `images/...` 或 `https://...`,不含专有协议。
- 三栏滚动按可视进度比例联动,长文档下源码与两侧预览位置大致对应。
## License

4131
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,7 @@
"url": "git+https://git.nomadro.cn/hackrobot/emojiTool.git"
},
"license": "MIT",
"type": "commonjs",
"author": {
"name": "hackrobot",
"email": "hackrobot@nomadro.cn",
@ -42,7 +43,7 @@
"package": "ts-node ./.erb/scripts/clean.js dist && npm run build && electron-builder build --publish never && npm run build:dll",
"rebuild": "electron-rebuild --parallel --types prod,dev,optional --module-dir release/app",
"start": "ts-node ./.erb/scripts/check-port-in-use.js && npm run start:renderer",
"start:main": "cross-env NODE_ENV=development electronmon -r ts-node/register/transpile-only .",
"start:main": "cross-env NODE_ENV=development electronmon -r tsx/cjs ./src/main/main.ts",
"start:preload": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.preload.dev.ts",
"start:renderer": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack serve --config ./.erb/configs/webpack.config.renderer.dev.ts",
"test": "jest"
@ -95,6 +96,7 @@
}
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1145.0",
"antd": "^5.17.2",
"electron-debug": "^3.2.0",
"electron-log": "^4.4.8",
@ -108,15 +110,15 @@
},
"devDependencies": {
"@electron-forge/publisher-github": "^7.4.0",
"@electron/notarize": "^2.1.0",
"@electron/rebuild": "^3.3.0",
"@electron/notarize": "^3.1.1",
"@electron/rebuild": "^4.2.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.11",
"@svgr/webpack": "^8.1.0",
"@teamsupercell/typings-for-css-modules-loader": "^2.5.2",
"@testing-library/jest-dom": "^6.1.3",
"@testing-library/react": "^14.0.0",
"@types/jest": "^29.5.5",
"@types/node": "20.6.2",
"@types/node": "^22.20.5",
"@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7",
"@types/react-test-renderer": "^18.0.1",
@ -132,9 +134,9 @@
"css-loader": "^6.8.1",
"css-minimizer-webpack-plugin": "^5.0.1",
"detect-port": "^1.5.1",
"electron": "^26.2.1",
"electron-builder": "^24.6.4",
"electron-devtools-installer": "^3.2.0",
"electron": "^44.5.1",
"electron-builder": "^26.15.3",
"electron-devtools-installer": "^4.0.0",
"electron-reload": "^2.0.0-alpha.1",
"electronmon": "^2.0.2",
"eslint": "^8.49.0",
@ -167,6 +169,7 @@
"ts-loader": "^9.4.4",
"ts-node": "^10.9.1",
"tsconfig-paths-webpack-plugin": "^4.1.0",
"tsx": "^4.23.15",
"typescript": "^5.2.2",
"url-loader": "^4.1.1",
"webpack": "^5.88.2",

1
public/.gitkeep Normal file
View File

@ -0,0 +1 @@

View File

@ -1,12 +1,12 @@
{
"name": "electron-react-boilerplate",
"version": "4.6.0",
"name": "emojitool",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "electron-react-boilerplate",
"version": "4.6.0",
"name": "emojitool",
"version": "1.0.0",
"hasInstallScript": true,
"license": "MIT"
}

View File

@ -0,0 +1,13 @@
import { buildImageMarkdown } from '../renderer/lib/imageInsert';
describe('buildImageMarkdown', () => {
it('builds image syntax', () => {
expect(buildImageMarkdown('截图', 'https://example.com/a.png')).toBe(
'![截图](https://example.com/a.png)\n',
);
});
it('escapes brackets in alt', () => {
expect(buildImageMarkdown('[a]', 'http://x')).toBe('![a](http://x)\n');
});
});

View File

@ -0,0 +1,38 @@
import {
buildMarkdownTable,
findTableAtOffset,
parseMarkdownTableBlock,
serializeMarkdownTable,
} from '../renderer/lib/mdTable';
describe('mdTable', () => {
it('builds a markdown table with header + body rows', () => {
const md = buildMarkdownTable(4, 3);
const lines = md.trim().split('\n');
expect(lines).toHaveLength(5); // header + sep + 3 body
expect(lines[0]).toBe('| 列1 | 列2 | 列3 |');
expect(lines[1]).toBe('| --- | --- | --- |');
});
it('round-trips parse and serialize', () => {
const src = `| A | B |
| :---: | ---: |
| 1 | 2 |
| 3 | 4 |
`;
const table = parseMarkdownTableBlock(src);
expect(table).not.toBeNull();
expect(table!.aligns).toEqual(['center', 'right']);
const again = serializeMarkdownTable(table!);
expect(parseMarkdownTableBlock(again)).toEqual(table);
});
it('finds table at cursor offset', () => {
const content = `hello\n\n| H1 | H2 |\n| --- | --- |\n| a | b |\n\nend`;
const offset = content.indexOf('| a |');
const found = findTableAtOffset(content, offset);
expect(found).not.toBeNull();
expect(found!.table.header).toEqual(['H1', 'H2']);
expect(found!.table.rows[0]).toEqual(['a', 'b']);
});
});

121
src/main/imageService.ts Normal file
View File

@ -0,0 +1,121 @@
import fs from 'fs';
import path from 'path';
import { app, dialog } from 'electron';
import { loadSettings } from './settingsStore';
import { uploadImageToS3 } from './s3Upload';
import { getImagesDir } from './localImageProtocol';
const IMAGE_EXT = new Set([
'png',
'jpg',
'jpeg',
'gif',
'webp',
'svg',
'bmp',
'ico',
]);
export function isImageFile(filePath: string): boolean {
const ext = path.extname(filePath).slice(1).toLowerCase();
return IMAGE_EXT.has(ext);
}
export function altFromFilename(filePath: string): string {
return path.basename(filePath, path.extname(filePath)) || '图片';
}
/** Safe filename for disk + Markdown URLs (no spaces / special chars). */
export function sanitizeImageFileName(filePathOrName: string): string {
const base = path.basename(filePathOrName);
const ext = path.extname(base).toLowerCase() || '.png';
const stem = path.basename(base, path.extname(base)) || 'image';
const safeStem = stem
.replace(/\s+/g, '-')
.replace(/[^\w.\u4e00-\u9fff-]+/g, '_')
.replace(/_+/g, '_')
.replace(/^[-_]+|[-_]+$/g, '')
.slice(0, 80);
const safeExt = /^\.(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(ext)
? ext.toLowerCase()
: '.png';
return `${safeStem || 'image'}${safeExt}`;
}
export async function pickImageFile(): Promise<{
canceled: boolean;
filePath?: string;
}> {
const result = await dialog.showOpenDialog({
title: '选择图片',
properties: ['openFile'],
filters: [
{
name: 'Images',
extensions: Array.from(IMAGE_EXT),
},
],
});
if (result.canceled || result.filePaths.length === 0) {
return { canceled: true };
}
const filePath = result.filePaths[0];
if (!isImageFile(filePath)) {
throw new Error('不支持的图片格式');
}
return { canceled: false, filePath };
}
/** Standard Markdown relative path — ASCII-safe, no spaces. */
async function copyToLocalAssets(filePath: string): Promise<string> {
const destDir = getImagesDir();
const fileName = `${Date.now()}-${sanitizeImageFileName(filePath)}`;
const dest = path.join(destDir, fileName);
fs.copyFileSync(filePath, dest);
return `images/${fileName}`;
}
function writeTempImage(name: string, data: Buffer): string {
const destDir = getImagesDir();
const fileName = `${Date.now()}-${sanitizeImageFileName(name || 'image.png')}`;
const dest = path.join(destDir, fileName);
fs.writeFileSync(dest, data);
return dest;
}
export async function processImageFile(filePath: string): Promise<{
url: string;
alt: string;
}> {
if (!fs.existsSync(filePath)) {
throw new Error('文件不存在');
}
if (!isImageFile(filePath)) {
throw new Error('不支持的图片格式');
}
const settings = loadSettings();
const alt = altFromFilename(filePath);
const hosting = settings.imageHosting;
if (hosting.enabled && hosting.uploadOnInsert) {
if (!hosting.accessKey || !hosting.secretKey) {
throw new Error('图床已开启但未配置密钥,请在「设置 → 图床」中填写');
}
const url = await uploadImageToS3(filePath, hosting);
return { url, alt };
}
const url = await copyToLocalAssets(filePath);
return { url, alt };
}
export async function processImageBuffer(payload: {
name: string;
mime: string;
data: ArrayBuffer | Buffer | Uint8Array;
}): Promise<{ url: string; alt: string }> {
const buf = Buffer.from(payload.data as ArrayBuffer);
const dest = writeTempImage(payload.name || 'image.png', buf);
return processImageFile(dest);
}

40
src/main/ipcHandlers.ts Normal file
View File

@ -0,0 +1,40 @@
import { ipcMain } from 'electron';
import type { AppSettings } from '../shared/appSettings';
import { pickImageFile, processImageBuffer, processImageFile } from './imageService';
import { loadSettings, saveSettings } from './settingsStore';
import { testS3Connection } from './s3Upload';
export function registerIpcHandlers(): void {
ipcMain.handle('settings:get', () => loadSettings());
ipcMain.handle('settings:save', (_event, settings: AppSettings) => {
saveSettings(settings);
return loadSettings();
});
ipcMain.handle('image:pick', () => pickImageFile());
ipcMain.handle('image:process', (_event, filePath: string) =>
processImageFile(filePath),
);
ipcMain.handle(
'image:process-buffer',
(
_event,
payload: { name: string; mime: string; data: ArrayBuffer },
) => processImageBuffer(payload),
);
ipcMain.handle('image:test-hosting', async (_event, settings: AppSettings) => {
try {
const msg = await testS3Connection(settings.imageHosting);
return { ok: true, message: msg };
} catch (err) {
return {
ok: false,
message: err instanceof Error ? err.message : String(err),
};
}
});
}

View File

@ -0,0 +1,149 @@
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import { app, protocol, net } from 'electron';
export const LOCAL_IMAGE_SCHEME = 'emojilocal';
/** Must be called before app.whenReady() */
export function registerLocalImageScheme(): void {
protocol.registerSchemesAsPrivileged([
{
scheme: LOCAL_IMAGE_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
bypassCSP: true,
stream: true,
corsEnabled: true,
},
},
]);
}
export function getImagesDir(): string {
const dir = path.join(app.getPath('userData'), 'images');
fs.mkdirSync(dir, { recursive: true });
return dir;
}
/** Build a renderer-safe URL for a file under userData/images */
export function toLocalImageUrl(absolutePath: string): string {
const fileName = path.basename(absolutePath);
return `${LOCAL_IMAGE_SCHEME}://images/${encodeURIComponent(fileName)}`;
}
function isAllowedLocalPath(resolved: string): boolean {
const appData = path.resolve(app.getPath('appData'));
const userData = path.resolve(app.getPath('userData'));
return (
resolved === userData ||
resolved.startsWith(userData + path.sep) ||
resolved === appData ||
resolved.startsWith(appData + path.sep)
);
}
function fileUrlToAbsolute(fileUrl: string): string | null {
try {
if (!/^file:/i.test(fileUrl)) return null;
const u = new URL(fileUrl);
let p = decodeURIComponent(u.pathname);
if (process.platform === 'win32' && p.startsWith('/')) {
p = p.slice(1);
}
return path.resolve(p);
} catch {
return null;
}
}
function resolveLocalImagePath(requestUrl: string): string | null {
try {
const parsed = new URL(requestUrl);
// emojilocal://images/xxx.png
if (parsed.hostname === 'images') {
const name = decodeURIComponent(parsed.pathname.replace(/^\//, ''));
if (!name || name.includes('..') || /[/\\]/.test(name)) {
return null;
}
const candidate = path.join(getImagesDir(), name);
if (fs.existsSync(candidate)) return candidate;
// Fallback: older Electron userData folder during early tests
const legacy = path.join(app.getPath('appData'), 'Electron', 'images', name);
if (fs.existsSync(legacy)) return legacy;
return null;
}
// emojilocal://file/<urlencoded-absolute-path>
if (parsed.hostname === 'file') {
const enc = parsed.pathname.replace(/^\//, '');
const abs = path.resolve(decodeURIComponent(enc));
if (!isAllowedLocalPath(abs)) return null;
return fs.existsSync(abs) ? abs : null;
}
} catch {
return null;
}
return null;
}
/** Call after app.whenReady() */
export function installLocalImageProtocol(): void {
protocol.handle(LOCAL_IMAGE_SCHEME, async (request) => {
const filePath = resolveLocalImagePath(request.url);
if (!filePath || !fs.existsSync(filePath)) {
return new Response('Not Found', { status: 404 });
}
return net.fetch(pathToFileURL(filePath).href);
});
}
/**
* Copy images from the old Electron userData folder into emojiTool/images.
*/
export function migrateLegacyImages(): number {
const destDir = getImagesDir();
const legacyDir = path.join(app.getPath('appData'), 'Electron', 'images');
if (!fs.existsSync(legacyDir)) return 0;
let copied = 0;
for (const name of fs.readdirSync(legacyDir)) {
const src = path.join(legacyDir, name);
const dest = path.join(destDir, name);
try {
if (!fs.statSync(src).isFile()) continue;
if (!fs.existsSync(dest)) {
fs.copyFileSync(src, dest);
copied += 1;
}
} catch {
// skip unreadable files
}
}
return copied;
}
/**
* Rewrite file:// image URLs so http:// renderer can load them via emojilocal://
*/
export function rewriteFileUrlsToLocalScheme(text: string): string {
return text.replace(/file:\/\/\/[^\s)"'\]]+/gi, (full) => {
const abs = fileUrlToAbsolute(full);
if (!abs || !isAllowedLocalPath(abs)) return full;
const imagesRoot = path.resolve(getImagesDir());
const legacyRoot = path.resolve(
path.join(app.getPath('appData'), 'Electron', 'images'),
);
if (
path.dirname(abs) === imagesRoot ||
path.dirname(abs) === legacyRoot
) {
return toLocalImageUrl(abs);
}
return `${LOCAL_IMAGE_SCHEME}://file/${encodeURIComponent(abs)}`;
});
}

View File

@ -13,6 +13,12 @@ import { app, BrowserWindow, shell } from 'electron';
import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import MenuBuilder from './menu';
import { registerIpcHandlers } from './ipcHandlers';
import {
installLocalImageProtocol,
migrateLegacyImages,
registerLocalImageScheme,
} from './localImageProtocol';
import { resolveHtmlPath } from './util';
class AppUpdater {
@ -28,6 +34,13 @@ class AppUpdater {
// electron: require(`${__dirname}/node_modules/electron`)
// });
// Avoid userData landing in ".../Electron" during `electronmon`/tsx dev.
app.setName('emojiTool');
if (!app.isPackaged) {
app.setPath('userData', path.join(app.getPath('appData'), 'emojiTool'));
}
registerLocalImageScheme();
let mainWindow: BrowserWindow | null = null;
@ -44,16 +57,21 @@ if (isDebug) {
}
const installExtensions = async () => {
const installer = require('electron-devtools-installer');
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
const extensions = ['REACT_DEVELOPER_TOOLS'];
return installer
.default(
extensions.map((name) => installer[name]),
try {
const installer = require('electron-devtools-installer');
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
const extensions = ['REACT_DEVELOPER_TOOLS'];
await installer.default(
extensions.map((name: string) => installer[name]),
forceDownload,
)
.catch(console.log);
);
} catch (err) {
// Chrome CRX format changes often break unzip-crx; skip quietly in dev.
console.warn(
'[devtools] React DevTools install skipped:',
err instanceof Error ? err.message : err,
);
}
};
const createWindow = async () => {
@ -71,9 +89,9 @@ const createWindow = async () => {
mainWindow = new BrowserWindow({
show: false,
width: 1280,
height: 800,
minWidth: 900,
width: 1560,
height: 860,
minWidth: 1100,
minHeight: 600,
title: 'emojiTool',
icon: getAssetPath('icon.png'),
@ -135,6 +153,12 @@ app.on('window-all-closed', () => {
app
.whenReady()
.then(() => {
installLocalImageProtocol();
const migrated = migrateLegacyImages();
if (migrated > 0) {
log.info(`[images] migrated ${migrated} file(s) from Electron/images`);
}
registerIpcHandlers();
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the

View File

@ -114,10 +114,15 @@ export default class MenuBuilder {
click: () => this.sendCommand('save-draft'),
},
{
label: '复制预览',
label: '复制纯文本预览',
accelerator: 'Command+Enter',
click: () => this.sendCommand('copy-preview'),
},
{
label: '复制长文 HTML',
accelerator: 'Shift+Command+Enter',
click: () => this.sendCommand('copy-article-html'),
},
{
label: '清空正文',
click: () => this.sendCommand('clear-content'),
@ -251,10 +256,15 @@ export default class MenuBuilder {
click: () => this.sendCommand('save-draft'),
},
{
label: '复制预览',
label: '复制纯文本预览',
accelerator: 'Ctrl+Enter',
click: () => this.sendCommand('copy-preview'),
},
{
label: '复制长文 HTML',
accelerator: 'Ctrl+Shift+Enter',
click: () => this.sendCommand('copy-article-html'),
},
{
label: '清空正文',
click: () => this.sendCommand('clear-content'),

View File

@ -1,7 +1,30 @@
/* eslint no-unused-vars: off */
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
import {
contextBridge,
ipcRenderer,
IpcRendererEvent,
webUtils,
} from 'electron';
import type { AppSettings } from '../shared/appSettings';
export type MenuCommand = 'copy-preview' | 'save-draft' | 'clear-content';
export type MenuCommand =
| 'copy-preview'
| 'copy-article-html'
| 'save-draft'
| 'clear-content';
type FileWithPath = File & { path?: string };
function resolveFilePath(file: File): string {
try {
const fromWebUtils = webUtils.getPathForFile(file);
if (fromWebUtils) return fromWebUtils;
} catch {
// ignore
}
// Fallback for older runtimes / non-native File
return (file as FileWithPath).path ?? '';
}
const electronHandler = {
ipcRenderer: {
@ -18,6 +41,37 @@ const electronHandler = {
};
},
},
getPathForFile(file: File): string {
return resolveFilePath(file);
},
settings: {
get(): Promise<AppSettings> {
return ipcRenderer.invoke('settings:get');
},
save(settings: AppSettings): Promise<AppSettings> {
return ipcRenderer.invoke('settings:save', settings);
},
},
image: {
pick(): Promise<{ canceled: boolean; filePath?: string }> {
return ipcRenderer.invoke('image:pick');
},
process(filePath: string): Promise<{ url: string; alt: string }> {
return ipcRenderer.invoke('image:process', filePath);
},
processBuffer(payload: {
name: string;
mime: string;
data: ArrayBuffer;
}): Promise<{ url: string; alt: string }> {
return ipcRenderer.invoke('image:process-buffer', payload);
},
testHosting(
settings: AppSettings,
): Promise<{ ok: boolean; message: string }> {
return ipcRenderer.invoke('image:test-hosting', settings);
},
},
};
contextBridge.exposeInMainWorld('electron', electronHandler);

73
src/main/s3Upload.ts Normal file
View File

@ -0,0 +1,73 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { S3Client, PutObjectCommand, HeadBucketCommand } from '@aws-sdk/client-s3';
import type { ImageHostingSettings } from '../shared/appSettings';
const MIME: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.bmp': 'image/bmp',
};
function guessMime(filePath: string): string {
return MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
}
function buildClient(cfg: ImageHostingSettings): S3Client {
return new S3Client({
endpoint: cfg.endpoint,
region: cfg.region || 'us-east-1',
credentials: {
accessKeyId: cfg.accessKey,
secretAccessKey: cfg.secretKey,
},
forcePathStyle: cfg.forcePathStyle,
});
}
function buildPublicUrl(cfg: ImageHostingSettings, key: string): string {
const base = cfg.publicBaseUrl.replace(/\/+$/, '');
const prefix = cfg.pathPrefix.replace(/^\/+|\/+$/g, '');
const objectKey = prefix ? `${prefix}/${key}` : key;
if (cfg.forcePathStyle) {
return `${base}/${cfg.bucket}/${objectKey}`;
}
return `${base}/${objectKey}`;
}
export async function uploadImageToS3(
filePath: string,
cfg: ImageHostingSettings,
): Promise<string> {
const client = buildClient(cfg);
const ext = path.extname(filePath) || '.png';
const key = `${Date.now()}-${crypto.randomBytes(4).toString('hex')}${ext}`;
const prefix = cfg.pathPrefix.replace(/^\/+|\/+$/g, '');
const objectKey = prefix ? `${prefix}/${key}` : key;
const body = fs.readFileSync(filePath);
await client.send(
new PutObjectCommand({
Bucket: cfg.bucket,
Key: objectKey,
Body: body,
ContentType: guessMime(filePath),
}),
);
return buildPublicUrl(cfg, key);
}
export async function testS3Connection(cfg: ImageHostingSettings): Promise<string> {
if (!cfg.accessKey || !cfg.secretKey) {
throw new Error('请填写 Access Key 与 Secret Key');
}
const client = buildClient(cfg);
await client.send(new HeadBucketCommand({ Bucket: cfg.bucket }));
return `已连接 bucket「${cfg.bucket}」`;
}

93
src/main/settingsStore.ts Normal file
View File

@ -0,0 +1,93 @@
import fs from 'fs';
import path from 'path';
import { app, safeStorage } from 'electron';
import {
DEFAULT_APP_SETTINGS,
mergeAppSettings,
type AppSettings,
} from '../shared/appSettings';
type StoredSettings = Omit<AppSettings, 'imageHosting'> & {
imageHosting: Omit<AppSettings['imageHosting'], 'secretKey'> & {
secretKeyEnc?: string;
};
};
let cached: AppSettings | null = null;
function settingsPath(): string {
return path.join(app.getPath('userData'), 'settings.json');
}
function encryptSecret(secret: string): string | undefined {
if (!secret) return undefined;
if (safeStorage.isEncryptionAvailable()) {
return safeStorage.encryptString(secret).toString('base64');
}
return Buffer.from(secret, 'utf8').toString('base64');
}
function decryptSecret(enc?: string): string {
if (!enc) return '';
try {
const buf = Buffer.from(enc, 'base64');
if (safeStorage.isEncryptionAvailable()) {
return safeStorage.decryptString(buf);
}
return buf.toString('utf8');
} catch {
return '';
}
}
function toStored(settings: AppSettings): StoredSettings {
const { secretKey, ...restHosting } = settings.imageHosting;
return {
...settings,
imageHosting: {
...restHosting,
secretKeyEnc: encryptSecret(secretKey),
},
};
}
function fromStored(raw: StoredSettings): AppSettings {
const { secretKeyEnc, ...restHosting } = raw.imageHosting;
return mergeAppSettings({
...raw,
imageHosting: {
...restHosting,
secretKey: decryptSecret(secretKeyEnc),
},
});
}
export function loadSettings(): AppSettings {
if (cached) return cached;
try {
const file = settingsPath();
if (!fs.existsSync(file)) {
cached = { ...DEFAULT_APP_SETTINGS };
return cached;
}
const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as StoredSettings;
cached = fromStored(parsed);
return cached;
} catch {
cached = { ...DEFAULT_APP_SETTINGS };
return cached;
}
}
export function saveSettings(settings: AppSettings): AppSettings {
const merged = mergeAppSettings(settings);
const dir = path.dirname(settingsPath());
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(settingsPath(), JSON.stringify(toStored(merged), null, 2), 'utf8');
cached = merged;
return merged;
}
export function getPublicSettings(): AppSettings {
return loadSettings();
}

View File

@ -53,8 +53,9 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
gap: 12px;
flex-shrink: 0;
flex-wrap: nowrap;
animation: riseIn 420ms ease both;
}
@ -63,6 +64,11 @@
align-items: center;
gap: 12px;
min-width: 0;
flex: 0 1 auto;
}
.brandText {
min-width: 0;
}
.brandMark {
@ -96,11 +102,33 @@
.actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
gap: 8px;
flex-wrap: nowrap;
flex-shrink: 0;
justify-content: flex-end;
}
.copyGroup {
display: inline-flex;
align-items: center;
gap: 8px;
margin-left: 4px;
padding-left: 10px;
border-left: 1px solid var(--line);
}
.copyArticleBtn {
background: #fff !important;
border-color: rgba(13, 148, 136, 0.45) !important;
color: var(--accent-deep) !important;
font-weight: 600;
&:hover:not(:disabled) {
border-color: var(--accent) !important;
color: var(--accent) !important;
}
}
.themeSwitch {
background: rgba(255, 255, 255, 0.7) !important;
}
@ -251,8 +279,8 @@
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1.12fr);
gap: 12px;
animation: riseIn 560ms ease both;
}
@ -273,11 +301,15 @@
background: var(--panel-solid);
}
.articlePane {
background: #fff;
}
.paneHeader {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
padding: 10px 12px 10px 16px;
border-bottom: 1px solid var(--line);
flex-shrink: 0;
gap: 10px;
@ -291,11 +323,29 @@
min-width: 0;
}
.paneHeaderActions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
margin-left: auto;
}
.paneThemeBtn {
background: rgba(255, 255, 255, 0.88) !important;
border-color: var(--line) !important;
color: var(--ink) !important;
font-size: 12px !important;
height: 28px !important;
padding: 0 10px !important;
}
.paneTitle {
font-size: 13px;
font-weight: 600;
letter-spacing: 0.02em;
color: var(--accent-deep);
flex-shrink: 0;
}
.paneMeta {
@ -409,6 +459,31 @@
min-height: 0;
display: flex;
flex-direction: column;
position: relative;
}
.editorWrapDragOver {
outline: 2px dashed rgba(13, 148, 136, 0.55);
outline-offset: -2px;
background: rgba(13, 148, 136, 0.04);
}
.editorWrapBusy {
opacity: 0.92;
}
.dropOverlay {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
place-items: center;
pointer-events: none;
background: rgba(13, 148, 136, 0.08);
color: var(--accent-deep);
font-size: 15px;
font-weight: 600;
letter-spacing: 0.02em;
}
.editorMarkdown .editor {
@ -435,6 +510,7 @@
flex: 1 !important;
min-height: 0 !important;
height: 100% !important;
overflow: auto !important;
resize: none !important;
border: none !important;
border-radius: 0 !important;
@ -540,6 +616,434 @@
}
}
.articleScroll {
flex: 1;
min-height: 0;
overflow: auto;
background:
radial-gradient(ellipse 80% 40% at 50% 0%, rgba(13, 148, 136, 0.05), transparent 70%),
linear-gradient(180deg, #fcfdfd 0%, #f7fafb 100%);
transition: background 220ms ease;
}
.articlePane[data-theme='B'] .articleScroll {
background:
radial-gradient(ellipse 70% 36% at 50% 0%, rgba(14, 116, 144, 0.06), transparent 70%),
linear-gradient(180deg, #fbfdfe 0%, #f3f8fa 100%);
}
.articlePane[data-theme='C'] .articleScroll {
background: #ffffff;
}
.articlePane[data-theme='D'] .articleScroll {
background:
radial-gradient(ellipse 80% 42% at 50% 0%, rgba(180, 83, 9, 0.06), transparent 68%),
linear-gradient(180deg, #fffdf9 0%, #faf6f0 100%);
}
.articleHtml {
--md-ink: #1c2430;
--md-muted: #64748b;
--md-accent: #0f766e;
--md-border: rgba(28, 36, 48, 0.1);
--md-code-bg: #f1f5f7;
--md-quote-bg: rgba(13, 148, 136, 0.06);
--md-h1-rule: rgba(15, 118, 110, 0.22);
--md-pre-bg: #1a2330;
--md-code-fg: #0f4c46;
max-width: 42rem;
margin: 0 auto;
padding: 28px 28px 40px;
color: var(--md-ink);
font-family:
'Source Han Sans SC',
'Noto Sans SC',
'PingFang SC',
'Segoe UI',
'Microsoft YaHei',
sans-serif;
font-size: 15.5px;
line-height: 1.85;
letter-spacing: 0.01em;
word-break: break-word;
user-select: text;
animation: fadeIn 220ms ease;
&[data-theme='B'] {
--md-accent: #0e7490;
--md-quote-bg: rgba(14, 116, 144, 0.06);
--md-h1-rule: rgba(14, 116, 144, 0.28);
--md-code-bg: #eef6f9;
--md-code-fg: #0c4a5c;
font-size: 15px;
line-height: 1.8;
}
&[data-theme='C'] {
--md-accent: #475569;
--md-muted: #94a3b8;
--md-quote-bg: #f8fafc;
--md-h1-rule: transparent;
--md-code-bg: #f1f5f9;
--md-code-fg: #334155;
--md-border: rgba(15, 23, 42, 0.08);
font-size: 15px;
line-height: 1.78;
max-width: 38rem;
}
&[data-theme='D'] {
--md-ink: #1c1917;
--md-muted: #78716c;
--md-accent: #b45309;
--md-quote-bg: rgba(180, 83, 9, 0.07);
--md-h1-rule: rgba(180, 83, 9, 0.35);
--md-code-bg: #faf5f0;
--md-code-fg: #7c2d12;
--md-border: rgba(28, 25, 23, 0.12);
--md-pre-bg: #1c1917;
font-size: 16px;
line-height: 1.9;
}
:global(h1),
:global(h2),
:global(h3),
:global(h4),
:global(h5),
:global(h6) {
color: var(--md-ink);
font-weight: 700;
line-height: 1.35;
letter-spacing: -0.01em;
margin: 1.55em 0 0.55em;
}
:global(h1) {
font-size: 1.85em;
margin-top: 0.2em;
padding-bottom: 0.35em;
border-bottom: 2px solid var(--md-h1-rule);
}
:global(h2) {
font-size: 1.4em;
padding-bottom: 0.28em;
border-bottom: 1px solid var(--md-border);
}
:global(h3) {
font-size: 1.18em;
color: #243044;
}
:global(h4) {
font-size: 1.05em;
}
:global(h5),
:global(h6) {
font-size: 0.95em;
color: var(--md-muted);
text-transform: none;
}
:global(p) {
margin: 0 0 1em;
}
:global(a) {
color: var(--md-accent);
text-decoration: underline;
text-decoration-thickness: 1px;
text-underline-offset: 3px;
transition: color 140ms ease;
&:hover {
filter: brightness(1.12);
}
}
:global(strong) {
font-weight: 700;
color: #152033;
}
:global(em) {
font-style: italic;
color: #334155;
}
:global(ul),
:global(ol) {
margin: 0 0 1em;
padding-left: 1.45em;
}
:global(li) {
margin: 0.28em 0;
}
:global(li > p) {
margin: 0.2em 0;
}
:global(li > ul),
:global(li > ol) {
margin: 0.25em 0 0.35em;
}
:global(blockquote) {
margin: 0 0 1.1em;
padding: 0.65em 1em 0.65em 1.05em;
border-left: 3.5px solid var(--md-accent);
background: var(--md-quote-bg);
border-radius: 0 10px 10px 0;
color: #3d4f63;
:global(p) {
margin: 0.35em 0;
}
:global(p:first-child) {
margin-top: 0;
}
:global(p:last-child) {
margin-bottom: 0;
}
}
:global(hr) {
border: none;
height: 1px;
margin: 1.6em 0;
background: linear-gradient(
90deg,
transparent,
var(--md-accent),
transparent
);
opacity: 0.45;
}
:global(code) {
font-family:
'Cascadia Code',
'JetBrains Mono',
'SF Mono',
Consolas,
monospace;
font-size: 0.88em;
padding: 0.15em 0.4em;
border-radius: 5px;
background: var(--md-code-bg);
color: var(--md-code-fg);
border: 1px solid color-mix(in srgb, var(--md-accent) 18%, transparent);
}
:global(pre) {
margin: 0 0 1.15em;
padding: 14px 16px;
overflow-x: auto;
border-radius: 12px;
background: var(--md-pre-bg);
border: 1px solid rgba(26, 35, 48, 0.85);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
:global(code) {
display: block;
padding: 0;
border: none;
background: transparent;
color: #e2e8f0;
font-size: 0.86em;
line-height: 1.65;
white-space: pre;
}
}
:global(img) {
max-width: 100%;
height: auto;
display: block;
margin: 1em auto;
border-radius: 10px;
box-shadow: 0 8px 28px rgba(26, 35, 48, 0.1);
}
:global(table) {
width: 100%;
border-collapse: collapse;
margin: 0 0 1.2em;
font-size: 0.94em;
overflow: hidden;
border-radius: 10px;
border: 1px solid var(--md-border);
}
:global(th),
:global(td) {
padding: 10px 14px;
border-bottom: 1px solid var(--md-border);
text-align: left;
vertical-align: top;
}
:global(th) {
background: color-mix(in srgb, var(--md-accent) 12%, transparent);
font-weight: 600;
color: var(--md-accent);
}
:global(tr:last-child td) {
border-bottom: none;
}
:global(tr:nth-child(even) td) {
background: rgba(244, 247, 248, 0.65);
}
:global(input[type='checkbox']) {
margin-right: 0.45em;
accent-color: var(--md-accent);
}
:global(.md-footer) {
margin-top: 2em;
padding-top: 1.1em;
border-top: 1px dashed var(--md-border);
color: var(--md-muted);
font-size: 0.9em;
line-height: 1.7;
}
/* B · 青简:书签感左侧强调 */
&[data-theme='B'] {
:global(h1) {
border-bottom: none;
padding-left: 0.7em;
border-left: 4px solid var(--md-accent);
padding-bottom: 0;
}
:global(h2) {
border-bottom: none;
padding-bottom: 0;
}
:global(blockquote) {
border-radius: 0;
border-left-width: 3px;
}
:global(pre) {
border-radius: 8px;
}
:global(table) {
border-radius: 6px;
}
}
/* C · 精简:少装饰 */
&[data-theme='C'] {
:global(h1),
:global(h2) {
border-bottom: none;
padding-bottom: 0;
font-weight: 600;
}
:global(h1) {
font-size: 1.65em;
}
:global(h2) {
font-size: 1.28em;
}
:global(blockquote) {
background: transparent;
border-left-width: 2px;
border-radius: 0;
padding-left: 0.85em;
}
:global(pre) {
border-radius: 6px;
box-shadow: none;
}
:global(img) {
border-radius: 4px;
box-shadow: none;
}
:global(table) {
border-radius: 0;
}
:global(th) {
background: transparent;
border-bottom: 2px solid var(--md-border);
}
:global(tr:nth-child(even) td) {
background: transparent;
}
:global(a) {
text-decoration-thickness: 1px;
}
}
/* D · 聚焦:双线标题 + 要点感 */
&[data-theme='D'] {
:global(h1) {
border-bottom-width: 3px;
border-bottom-style: double;
letter-spacing: 0.02em;
}
:global(h2) {
border-bottom: none;
padding-left: 0.55em;
border-left: 3px solid var(--md-accent);
padding-bottom: 0;
}
:global(h3) {
color: var(--md-accent);
}
:global(blockquote) {
border-left-width: 4px;
border-radius: 0 12px 12px 0;
}
:global(strong) {
color: #1c1917;
background: rgba(180, 83, 9, 0.1);
padding: 0 0.2em;
border-radius: 3px;
}
:global(ul) {
list-style: none;
padding-left: 1.1em;
:global(li::before) {
content: '→ ';
color: var(--md-accent);
font-weight: 600;
}
}
}
}
.emptyState {
height: 100%;
min-height: 240px;
@ -587,11 +1091,27 @@
}
}
@media (max-width: 1200px) {
.workspace {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
.articlePane {
grid-column: 1 / -1;
max-height: 42vh;
}
}
@media (max-width: 900px) {
.workspace {
grid-template-columns: 1fr;
}
.articlePane {
grid-column: auto;
max-height: none;
}
.header {
flex-direction: column;
align-items: flex-start;

View File

@ -22,9 +22,12 @@ import {
renderEmojiMarkdown,
type ThemeId,
} from './lib/emojiMarkdown';
import { renderRichMarkdown, toStandardImageMarkdown } from './lib/richMarkdown';
import { useLinkedScroll } from './lib/linkedScroll';
import { loadDraft, saveDraft, type EditorMode } from './lib/storage';
import { DEFAULT_TEMPLATE_CONTENT, SNIPPETS, TEMPLATES } from './lib/templates';
import EditorPane, { type EditorPaneHandle } from './components/EditorPane';
import SettingsModal from './components/SettingsModal';
import styles from './App.module.scss';
const { TextArea } = Input;
@ -47,28 +50,50 @@ const SNIPPET_ACTION_IDS: Record<string, string> = {
function App() {
const previewRef = useRef<HTMLDivElement>(null);
const articleRef = useRef<HTMLElement>(null);
const editorRef = useRef<EditorPaneHandle>(null);
const previewScrollRef = useRef<HTMLDivElement>(null);
const articleScrollRef = useRef<HTMLDivElement>(null);
const initial = useMemo(() => loadDraft(), []);
const initialContent = useMemo(
() => toStandardImageMarkdown(initial.content),
[initial.content],
);
const [content, setContent] = useState(initial.content);
const [content, setContent] = useState(initialContent);
const [appendFooter, setAppendFooter] = useState(initial.appendFooter);
const [footerText, setFooterText] = useState(initial.footerText);
const [themeId, setThemeId] = useState<ThemeId>(initial.themeId);
const [articleThemeId, setArticleThemeId] = useState<ThemeId>(
initial.articleThemeId,
);
const [editorMode, setEditorMode] = useState<EditorMode>(initial.editorMode);
const [tocOpen, setTocOpen] = useState(initial.tocOpen);
const [savedHint, setSavedHint] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [autosaveEnabled, setAutosaveEnabled] = useState(true);
const [previewHtml, setPreviewHtml] = useState(() =>
renderEmojiMarkdown(initial.content, {
renderEmojiMarkdown(initialContent, {
appendFooter: initial.appendFooter,
footerText: initial.footerText,
themeId: initial.themeId,
}),
);
const [articleHtml, setArticleHtml] = useState(() =>
renderRichMarkdown(initialContent, {
appendFooter: initial.appendFooter,
footerText: initial.footerText,
}),
);
const activeTheme = useMemo(
const plainTheme = useMemo(
() => THEME_LIST.find((t) => t.id === themeId) ?? THEME_LIST[0],
[themeId],
);
const articleTheme = useMemo(
() => THEME_LIST.find((t) => t.id === articleThemeId) ?? THEME_LIST[0],
[articleThemeId],
);
const charCount = content.length;
const hasContent = content.trim().length > 0;
@ -82,24 +107,57 @@ function App() {
themeId,
}),
);
setArticleHtml(
renderRichMarkdown(content, {
appendFooter,
footerText,
}),
);
}, PREVIEW_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [content, appendFooter, footerText, themeId]);
useEffect(() => {
window.electron?.settings
?.get()
.then((settings) => setAutosaveEnabled(settings.editor.autosave))
.catch(() => {});
}, []);
useEffect(() => {
if (!autosaveEnabled) return undefined;
const timer = window.setTimeout(() => {
saveDraft({
content,
appendFooter,
footerText,
themeId,
articleThemeId,
editorMode,
tocOpen,
});
setSavedHint(true);
}, SAVE_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [content, appendFooter, footerText, themeId, editorMode, tocOpen]);
}, [
content,
appendFooter,
footerText,
themeId,
articleThemeId,
editorMode,
tocOpen,
autosaveEnabled,
]);
useLinkedScroll(
() => [
editorRef.current?.getScrollElement() ?? null,
previewScrollRef.current,
articleScrollRef.current,
],
[hasContent, previewHtml, articleHtml, editorMode, tocOpen],
);
useEffect(() => {
if (!savedHint) return undefined;
@ -120,6 +178,35 @@ function App() {
}
}, [hasContent]);
const copyArticleHtml = useCallback(async () => {
if (!articleRef.current || !hasContent) {
message.warning('还没有可复制的内容');
return;
}
const html = articleRef.current.innerHTML;
const text = articleRef.current.innerText;
try {
if (typeof ClipboardItem !== 'undefined') {
await navigator.clipboard.write([
new ClipboardItem({
'text/html': new Blob([html], { type: 'text/html' }),
'text/plain': new Blob([text], { type: 'text/plain' }),
}),
]);
} else {
await navigator.clipboard.writeText(html);
}
message.success('已复制长文 HTML,可粘贴到富文本编辑器');
} catch {
try {
await navigator.clipboard.writeText(html);
message.success('已复制长文 HTML');
} catch {
message.error('复制失败,请检查剪贴板权限');
}
}
}, [hasContent]);
const clearContent = useCallback(() => {
if (!hasContent) {
setContent('');
@ -143,10 +230,16 @@ function App() {
message.success('已恢复默认页脚');
}, []);
const applyTheme = useCallback((next: ThemeId) => {
const applyPlainTheme = useCallback((next: ThemeId) => {
setThemeId(next);
const theme = THEME_LIST.find((item) => item.id === next);
message.success(`已切换:${theme?.name ?? next}`);
message.success(`纯文本主题:${theme?.name ?? next}`);
}, []);
const applyArticleTheme = useCallback((next: ThemeId) => {
setArticleThemeId(next);
const theme = THEME_LIST.find((item) => item.id === next);
message.success(`长文主题:${theme?.name ?? next}`);
}, []);
const applyTemplate = useCallback(
@ -191,12 +284,21 @@ function App() {
appendFooter,
footerText,
themeId,
articleThemeId,
editorMode,
tocOpen,
});
setSavedHint(true);
message.success('草稿已保存');
}, [content, appendFooter, footerText, themeId, editorMode, tocOpen]);
}, [
content,
appendFooter,
footerText,
themeId,
articleThemeId,
editorMode,
tocOpen,
]);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
@ -205,7 +307,11 @@ function App() {
if (event.key === 'Enter') {
event.preventDefault();
copyPreview();
if (event.shiftKey) {
copyArticleHtml();
} else {
copyPreview();
}
return;
}
if (event.key.toLowerCase() === 's') {
@ -224,27 +330,35 @@ function App() {
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [copyPreview, persistNow, editorMode]);
}, [copyPreview, copyArticleHtml, persistNow, editorMode]);
useEffect(() => {
const dispose = window.electron?.ipcRenderer?.onMenuCommand?.((command) => {
if (command === 'copy-preview') copyPreview();
else if (command === 'copy-article-html') copyArticleHtml();
else if (command === 'save-draft') persistNow();
else if (command === 'clear-content') clearContent();
});
return () => dispose?.();
}, [copyPreview, persistNow, clearContent]);
}, [copyPreview, copyArticleHtml, persistNow, clearContent]);
const themeItems: MenuProps['items'] = THEME_LIST.map((theme) => ({
key: theme.id,
label: (
<div className={styles.themeMenuItem}>
<strong>{theme.shortName}</strong>
<span>{theme.description}</span>
</div>
),
onClick: () => applyTheme(theme.id),
}));
const makeThemeItems = useCallback(
(onSelect: (id: ThemeId) => void): MenuProps['items'] =>
THEME_LIST.map((theme) => ({
key: theme.id,
label: (
<div className={styles.themeMenuItem}>
<strong>{theme.shortName}</strong>
<span>{theme.description}</span>
</div>
),
onClick: () => onSelect(theme.id),
})),
[],
);
const plainThemeItems = makeThemeItems(applyPlainTheme);
const articleThemeItems = makeThemeItems(applyArticleTheme);
const templateItems: MenuProps['items'] = TEMPLATES.map((item) => ({
key: item.id,
@ -255,8 +369,8 @@ function App() {
const hintText = savedHint
? '已自动保存'
: editorMode === 'markdown'
? `${activeTheme.name} · Enter 续列表 · Tab 缩进 · Ctrl+B/I/K`
: `${activeTheme.name} · 普通模式(片段已禁用)`;
? 'Enter 续列表 · Tab 缩进 · Ctrl+B/I/K · Ctrl+Enter 复制纯文本'
: '普通模式(片段已禁用)';
return (
<ConfigProvider
@ -276,27 +390,18 @@ function App() {
<div className={styles.brandMark} aria-hidden>
✦
</div>
<div>
<div className={styles.brandText}>
<h1 className={styles.title}>emojiTool</h1>
<p className={styles.subtitle}>
Markdown → 公众号友好纯文本 · mdemoji.com
编辑 · 纯文本 · 长文 · mdemoji.com
</p>
</div>
</div>
<div className={styles.actions}>
<Dropdown
menu={{
items: themeItems,
selectable: true,
selectedKeys: [themeId],
}}
placement="bottomRight"
>
<Button className={styles.themeSwitch}>
主题 · {activeTheme.shortName} ▾
</Button>
</Dropdown>
<Tooltip title="图床、编辑器等全局选项">
<Button onClick={() => setSettingsOpen(true)}>设置</Button>
</Tooltip>
<Dropdown menu={{ items: templateItems }} placement="bottomRight">
<Button>模板 ▾</Button>
@ -313,16 +418,6 @@ function App() {
<Button onClick={clearContent} disabled={!hasContent}>
清空
</Button>
<Tooltip title="Ctrl / ⌘ + Enter">
<Button
type="primary"
onClick={copyPreview}
disabled={!hasContent}
>
复制预览
</Button>
</Tooltip>
</div>
</header>
@ -362,10 +457,35 @@ function App() {
<section className={`${styles.pane} ${styles.previewPane}`}>
<div className={styles.paneHeader}>
<span className={styles.paneTitle}>公众号预览</span>
<span className={styles.paneMeta}>{activeTheme.name}</span>
<span className={styles.paneTitle}>纯文本预览</span>
<div className={styles.paneHeaderActions}>
<Dropdown
menu={{
items: plainThemeItems,
selectable: true,
selectedKeys: [themeId],
}}
placement="bottomRight"
>
<Button size="small" className={styles.paneThemeBtn}>
主题 · {plainTheme.shortName} ▾
</Button>
</Dropdown>
<Tooltip title="Ctrl / ⌘ + Enter">
<Button
type="primary"
size="small"
disabled={!hasContent}
onClick={() => {
void copyPreview();
}}
>
复制
</Button>
</Tooltip>
</div>
</div>
<div className={styles.previewScroll}>
<div className={styles.previewScroll} ref={previewScrollRef}>
{hasContent ? (
<div
ref={previewRef}
@ -375,13 +495,62 @@ function App() {
/>
) : (
<div className={styles.emptyState}>
<p className={styles.emptyTitle}>开始写一篇</p>
<p className={styles.emptyTitle}>纯文本效果</p>
<p className={styles.emptyDesc}>
{editorMode === 'markdown'
? '左侧用 Markdown 写作,右键可插入标题、任务、表格等。'
: '当前为普通编辑模式;切换回 MD 后可用右键与快捷键。'}
<br />
目录可跳转到标题;右侧即时预览主题排版。
面向微信公众号、评论区、聊天框等纯文本场景,复制后可直接粘贴。
</p>
</div>
)}
</div>
</section>
<section
className={`${styles.pane} ${styles.articlePane}`}
data-theme={articleThemeId}
>
<div className={styles.paneHeader}>
<span className={styles.paneTitle}>长文渲染</span>
<div className={styles.paneHeaderActions}>
<Dropdown
menu={{
items: articleThemeItems,
selectable: true,
selectedKeys: [articleThemeId],
}}
placement="bottomRight"
>
<Button size="small" className={styles.paneThemeBtn}>
主题 · {articleTheme.shortName} ▾
</Button>
</Dropdown>
<Tooltip title="Ctrl / ⌘ + Shift + Enter">
<Button
size="small"
className={styles.copyArticleBtn}
disabled={!hasContent}
onClick={() => {
void copyArticleHtml();
}}
>
复制
</Button>
</Tooltip>
</div>
</div>
<div className={styles.articleScroll} ref={articleScrollRef}>
{hasContent ? (
<article
ref={articleRef}
className={styles.articleHtml}
data-theme={articleThemeId}
aria-live="polite"
dangerouslySetInnerHTML={{ __html: articleHtml }}
/>
) : (
<div className={styles.emptyState}>
<p className={styles.emptyTitle}>长文预览</p>
<p className={styles.emptyDesc}>
本栏可单独切换主题;点「复制」粘贴到富文本编辑器。
</p>
</div>
)}
@ -405,8 +574,8 @@ function App() {
</label>
<p className={styles.footerHint}>
{appendFooter
? '开启后追加到预览末尾,可自由编辑文案'
: '已关闭,复制时不会带页脚'}
? '开启后追加到纯文本与长文预览末尾,可自由编辑文案'
: '已关闭,两栏预览与复制都不会带页脚'}
</p>
<Button
type="link"
@ -428,6 +597,12 @@ function App() {
aria-label="页脚文案"
/>
</section>
<SettingsModal
open={settingsOpen}
onClose={() => setSettingsOpen(false)}
onSaved={(settings) => setAutosaveEnabled(settings.editor.autosave)}
/>
</div>
</ConfigProvider>
);

View File

@ -1,12 +1,13 @@
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { Dropdown, Input, Segmented, Tooltip } from 'antd';
import { Dropdown, Input, Segmented, Tooltip, message } from 'antd';
import type { MenuProps } from 'antd';
import type { TextAreaRef } from 'antd/es/input/TextArea';
import {
@ -17,8 +18,12 @@ import {
insertBlockChunk,
type EditorAction,
} from '../lib/editorActions';
import { findTableAtOffset, type MdTable } from '../lib/mdTable';
import { buildImageMarkdown } from '../lib/imageInsert';
import type { EditorMode } from '../lib/storage';
import { offsetAtLine, parseToc } from '../lib/toc';
import TableInsertModal from './TableInsertModal';
import TableEditModal from './TableEditModal';
import styles from '../App.module.scss';
const { TextArea } = Input;
@ -27,6 +32,8 @@ export type EditorPaneHandle = {
runAction: (action: EditorAction) => void;
runActionById: (id: string) => boolean;
insertAtCursor: (chunk: string) => void;
openTableInsert: () => void;
getScrollElement: () => HTMLElement | null;
};
type Props = {
@ -53,6 +60,14 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
) {
const textareaRef = useRef<TextAreaRef>(null);
const [activeTocId, setActiveTocId] = useState<string | null>(null);
const [insertOpen, setInsertOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [editingTable, setEditingTable] = useState<MdTable | null>(null);
const [editRange, setEditRange] = useState<{ start: number; end: number } | null>(
null,
);
const [dragOver, setDragOver] = useState(false);
const [imageBusy, setImageBusy] = useState(false);
const getTextArea = () =>
textareaRef.current?.resizableTextArea?.textArea ?? null;
@ -84,15 +99,30 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
[focusAndSelect, onChange],
);
const runAction = useCallback(
(action: EditorAction) => {
const el = getTextArea();
const start = el?.selectionStart ?? content.length;
const end = el?.selectionEnd ?? content.length;
applyResult(applyEditorAction(content, start, end, action));
},
[applyResult, content],
);
const openTableInsert = useCallback(() => {
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再插入表格');
return;
}
setInsertOpen(true);
}, [mode]);
const openTableEdit = useCallback(() => {
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再编辑表格');
return;
}
const el = getTextArea();
const offset = el?.selectionStart ?? 0;
const found = findTableAtOffset(content, offset);
if (!found) {
message.warning('光标不在表格内,可先插入表格');
return;
}
setEditingTable(found.table);
setEditRange({ start: found.start, end: found.end });
setEditOpen(true);
}, [content, mode]);
const insertAtCursor = useCallback(
(chunk: string) => {
@ -104,14 +134,180 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
[applyResult, content],
);
const insertImagesFromPaths = useCallback(
async (paths: string[]) => {
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再插入图片');
return;
}
if (!window.electron?.image?.process) {
message.error('当前环境不支持图片处理');
return;
}
if (paths.length === 0) return;
setImageBusy(true);
let ok = 0;
try {
for (const filePath of paths) {
try {
const { url, alt } = await window.electron.image.process(filePath);
insertAtCursor(buildImageMarkdown(alt, url));
ok += 1;
} catch (err) {
message.error(
err instanceof Error ? err.message : '图片处理失败',
);
}
}
if (ok > 0) {
message.success(
ok === 1 ? '已插入图片' : `已插入 ${ok} 张图片`,
);
}
} finally {
setImageBusy(false);
}
},
[insertAtCursor, mode],
);
const insertImagesFromFiles = useCallback(
async (files: File[]) => {
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再插入图片');
return;
}
if (files.length === 0) return;
setImageBusy(true);
let ok = 0;
try {
for (const file of files) {
try {
let result: { url: string; alt: string } | null = null;
let filePath = '';
try {
filePath = window.electron?.getPathForFile?.(file) ?? '';
} catch {
filePath = '';
}
// Electron 26: File.path is available on native drag-drop
if (!filePath) {
filePath = (file as File & { path?: string }).path ?? '';
}
if (filePath && window.electron?.image?.process) {
result = await window.electron.image.process(filePath);
} else if (window.electron?.image?.processBuffer) {
const data = await file.arrayBuffer();
result = await window.electron.image.processBuffer({
name: file.name,
mime: file.type,
data,
});
} else {
throw new Error('当前环境不支持图片处理');
}
insertAtCursor(buildImageMarkdown(result.alt, result.url));
ok += 1;
} catch (err) {
message.error(
err instanceof Error ? err.message : '图片处理失败',
);
}
}
if (ok > 0) {
message.success(
ok === 1 ? '已插入图片' : `已插入 ${ok} 张图片`,
);
}
} finally {
setImageBusy(false);
}
},
[insertAtCursor, mode],
);
const pickAndInsertImage = useCallback(async () => {
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再插入图片');
return;
}
if (!window.electron?.image?.pick) {
message.error('当前环境不支持选择图片');
return;
}
const result = await window.electron.image.pick();
if (result.canceled || !result.filePath) return;
await insertImagesFromPaths([result.filePath]);
}, [insertImagesFromPaths, mode]);
const runAction = useCallback(
(action: EditorAction) => {
if (action.id === 'table') {
openTableInsert();
return;
}
if (action.id === 'image') {
void pickAndInsertImage();
return;
}
const el = getTextArea();
const start = el?.selectionStart ?? content.length;
const end = el?.selectionEnd ?? content.length;
applyResult(applyEditorAction(content, start, end, action));
},
[applyResult, content, openTableInsert, pickAndInsertImage],
);
const runActionById = useCallback(
(id: string) => {
if (id === 'table') {
openTableInsert();
return true;
}
if (id === 'image') {
void pickAndInsertImage();
return true;
}
const action = EDITOR_ACTIONS.find((item) => item.id === id);
if (!action) return false;
runAction(action);
return true;
},
[runAction],
[openTableInsert, pickAndInsertImage, runAction],
);
const confirmInsertTable = useCallback(
(markdown: string) => {
setInsertOpen(false);
insertAtCursor(markdown);
message.success('已插入表格');
},
[insertAtCursor],
);
const confirmEditTable = useCallback(
(markdown: string) => {
if (!editRange) {
setEditOpen(false);
return;
}
const next =
content.slice(0, editRange.start) +
markdown +
content.slice(editRange.end);
const cursor = editRange.start + markdown.length;
onChange(next);
setEditOpen(false);
setEditRange(null);
setEditingTable(null);
focusAndSelect(cursor, cursor);
message.success('表格已更新');
},
[content, editRange, focusAndSelect, onChange],
);
useImperativeHandle(
@ -120,10 +316,24 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
runAction,
runActionById,
insertAtCursor,
openTableInsert,
getScrollElement: () => getTextArea(),
}),
[runAction, runActionById, insertAtCursor],
[runAction, runActionById, insertAtCursor, openTableInsert],
);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const meta = event.ctrlKey || event.metaKey;
if (!meta || !event.shiftKey) return;
if (event.key.toLowerCase() !== 't') return;
event.preventDefault();
openTableInsert();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [openTableInsert]);
const jumpToHeading = useCallback(
(line: number, id: string) => {
setActiveTocId(id);
@ -161,6 +371,45 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
[applyResult, content, mode],
);
const onEditorDragOver = useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
if (mode !== 'markdown') return;
if (!Array.from(event.dataTransfer.types).includes('Files')) return;
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
setDragOver(true);
},
[mode],
);
const onEditorDragLeave = useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
if (event.currentTarget.contains(event.relatedTarget as Node)) return;
setDragOver(false);
},
[],
);
const onEditorDrop = useCallback(
async (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
setDragOver(false);
if (mode !== 'markdown') {
message.info('请先切换到 MD 模式再插入图片');
return;
}
const files = Array.from(event.dataTransfer.files).filter((f) =>
f.type.startsWith('image/'),
);
if (files.length === 0) {
message.warning('请拖入图片文件');
return;
}
await insertImagesFromFiles(files);
},
[insertImagesFromFiles, mode],
);
const contextItems: MenuProps['items'] = useMemo(() => {
const groups: Array<{
key: string;
@ -185,7 +434,7 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
{
key: 'insert',
label: '插入',
ids: ['table', 'codeblock', 'image'],
ids: ['codeblock', 'image'],
},
];
@ -206,8 +455,16 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
}),
});
});
items.push({ type: 'divider' });
items.push({
key: 'table-insert',
label: '插入表格…',
onClick: () => openTableInsert(),
});
return items;
}, [runAction]);
}, [openTableInsert, runAction]);
const isMarkdown = mode === 'markdown';
@ -229,6 +486,28 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
目录 {tocOpen ? '◂' : '▸'}
</button>
</Tooltip>
{isMarkdown && (
<Tooltip title="Ctrl+Shift+T · 可视化插入表格">
<button
type="button"
className={styles.tocToggle}
onClick={openTableInsert}
>
表格 +
</button>
</Tooltip>
)}
{isMarkdown && (
<Tooltip title="光标放在表格内可编辑">
<button
type="button"
className={styles.tocToggle}
onClick={openTableEdit}
>
编辑表格
</button>
</Tooltip>
)}
</div>
<div className={styles.paneHeaderRight}>
<Segmented
@ -282,8 +561,20 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
<div
className={`${styles.editorWrap} ${
isMarkdown ? styles.editorMarkdown : styles.editorPlain
} ${dragOver ? styles.editorWrapDragOver : ''} ${
imageBusy ? styles.editorWrapBusy : ''
}`}
onDragOver={onEditorDragOver}
onDragLeave={onEditorDragLeave}
onDrop={(e) => {
void onEditorDrop(e);
}}
>
{dragOver && (
<div className={styles.dropOverlay} aria-hidden>
松开以插入图片
</div>
)}
<TextArea
ref={textareaRef}
className={styles.editor}
@ -294,8 +585,8 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
isMarkdown
? `在此输入 Markdown…
右键插入 · Enter 续列表 · Tab 缩进
快捷键:Ctrl+B 加粗 · Ctrl+I 斜体 · Ctrl+K 链接`
拖入图片 · 右键插入 · Ctrl+Shift+T 表格
Enter 续列表 · Tab 缩进 · Ctrl+B/I/K`
: `普通文本编辑模式
适合自由写作;切换回 MD 后仍可一键转公众号预览`
@ -308,6 +599,27 @@ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
</div>
</Dropdown>
</div>
<TableInsertModal
open={insertOpen}
onCancel={() => setInsertOpen(false)}
onConfirm={confirmInsertTable}
/>
<TableEditModal
key={
editRange
? `edit-${editRange.start}-${editRange.end}`
: 'edit-closed'
}
open={editOpen}
initial={editingTable}
onCancel={() => {
setEditOpen(false);
setEditingTable(null);
setEditRange(null);
}}
onConfirm={confirmEditTable}
/>
</section>
);
});

View File

@ -0,0 +1,20 @@
.modal {
:global(.ant-modal-body) {
max-height: min(70vh, 560px);
overflow: auto;
}
}
.section {
display: flex;
flex-direction: column;
gap: 0;
padding-top: 4px;
}
.note {
margin: 8px 0 0;
font-size: 12px;
line-height: 1.6;
color: #5b6b7c;
}

View File

@ -0,0 +1,188 @@
import React, { useEffect, useState } from 'react';
import {
Button,
Form,
Input,
Modal,
Switch,
Tabs,
message,
} from 'antd';
import type { AppSettings } from '../../shared/appSettings';
import { DEFAULT_APP_SETTINGS, mergeAppSettings } from '../../shared/appSettings';
import styles from './SettingsModal.module.scss';
type Props = {
open: boolean;
onClose: () => void;
onSaved?: (settings: AppSettings) => void;
};
export default function SettingsModal({ open, onClose, onSaved }: Props) {
const [form] = Form.useForm<AppSettings>();
const [loading, setLoading] = useState(false);
const [testing, setTesting] = useState(false);
useEffect(() => {
if (!open) return;
const load = async () => {
try {
const settings =
(await window.electron?.settings?.get()) ?? DEFAULT_APP_SETTINGS;
form.setFieldsValue(settings);
} catch {
form.setFieldsValue(DEFAULT_APP_SETTINGS);
}
};
void load();
}, [open, form]);
const handleSave = async () => {
try {
setLoading(true);
const values = mergeAppSettings(form.getFieldsValue(true));
const saved = await window.electron?.settings?.save(values);
message.success('设置已保存');
onSaved?.(saved ?? values);
onClose();
} catch (err) {
message.error(err instanceof Error ? err.message : '保存失败');
} finally {
setLoading(false);
}
};
const handleTest = async () => {
try {
setTesting(true);
const values = mergeAppSettings(form.getFieldsValue(true));
const result = await window.electron?.image?.testHosting(values);
if (result?.ok) {
message.success(result.message);
} else {
message.error(result?.message ?? '连接失败');
}
} catch (err) {
message.error(err instanceof Error ? err.message : '连接失败');
} finally {
setTesting(false);
}
};
return (
<Modal
title="全局设置"
open={open}
onCancel={onClose}
destroyOnClose
centered
width={560}
footer={[
<Button key="cancel" onClick={onClose}>
取消
</Button>,
<Button key="save" type="primary" loading={loading} onClick={handleSave}>
保存
</Button>,
]}
className={styles.modal}
>
<Form form={form} layout="vertical" initialValues={DEFAULT_APP_SETTINGS}>
<Tabs
items={[
{
key: 'hosting',
label: '图床 (S3)',
children: (
<div className={styles.section}>
<Form.Item
name={['imageHosting', 'enabled']}
label="启用图床"
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
name={['imageHosting', 'uploadOnInsert']}
label="插入图片时自动上传"
valuePropName="checked"
extra="开启后,拖入/选择图片会上传到 S3 并插入公网 URL"
>
<Switch />
</Form.Item>
<Form.Item
name={['imageHosting', 'endpoint']}
label="Endpoint"
rules={[{ required: true, message: '必填' }]}
>
<Input placeholder="http://82.157.112.245:9000" />
</Form.Item>
<Form.Item name={['imageHosting', 'region']} label="Region">
<Input placeholder="us-east-1" />
</Form.Item>
<Form.Item
name={['imageHosting', 'bucket']}
label="Bucket"
rules={[{ required: true, message: '必填' }]}
>
<Input placeholder="emojitool" />
</Form.Item>
<Form.Item name={['imageHosting', 'accessKey']} label="Access Key">
<Input placeholder="MinIO / S3 Access Key" />
</Form.Item>
<Form.Item
name={['imageHosting', 'secretKey']}
label="Secret Key"
extra="仅保存在本机,不会写入仓库"
>
<Input.Password placeholder="Secret Key" />
</Form.Item>
<Form.Item
name={['imageHosting', 'publicBaseUrl']}
label="公网访问前缀"
extra="插入 Markdown 时使用的 URL 前缀"
>
<Input placeholder="http://82.157.112.245:9000" />
</Form.Item>
<Form.Item name={['imageHosting', 'pathPrefix']} label="路径前缀">
<Input placeholder="images" />
</Form.Item>
<Form.Item
name={['imageHosting', 'forcePathStyle']}
label="Path-Style 访问"
valuePropName="checked"
extra="MinIO 等自建 S3 通常需要开启"
>
<Switch />
</Form.Item>
<Button loading={testing} onClick={handleTest}>
测试连接
</Button>
</div>
),
},
{
key: 'editor',
label: '编辑器',
children: (
<div className={styles.section}>
<Form.Item
name={['editor', 'autosave']}
label="自动保存草稿"
valuePropName="checked"
>
<Switch />
</Form.Item>
<p className={styles.note}>
图片可拖入左侧编辑器;右键「图片」可选本地文件。开启图床后插入
https 公网地址;关闭图床则插入标准相对路径 images/文件名.png。
</p>
</div>
),
},
]}
/>
</Form>
</Modal>
);
}

View File

@ -0,0 +1,68 @@
import React, { useEffect, useState } from 'react';
import { Button, Modal } from 'antd';
import { serializeMarkdownTable, type MdTable } from '../lib/mdTable';
import TableEditorPanel from './TableEditorPanel';
import styles from './TableModals.module.scss';
type Props = {
open: boolean;
initial: MdTable | null;
onCancel: () => void;
onConfirm: (markdown: string) => void;
};
export default function TableEditModal({
open,
initial,
onCancel,
onConfirm,
}: Props) {
const [table, setTable] = useState<MdTable>(() => ({
header: [...(initial?.header ?? ['列1'])],
aligns: [...(initial?.aligns ?? [null])],
rows: (initial?.rows ?? [['']]).map((r) => [...r]),
}));
useEffect(() => {
if (!initial) return;
setTable({
header: [...initial.header],
aligns: [...initial.aligns],
rows: initial.rows.map((r) => [...r]),
});
}, [initial]);
if (!open) {
return null;
}
return (
<Modal
title="编辑表格"
open={open}
onCancel={onCancel}
destroyOnClose
centered
width={Math.min(920, 160 + table.header.length * 140)}
footer={[
<Button key="cancel" onClick={onCancel}>
取消
</Button>,
<Button
key="ok"
type="primary"
onClick={() => onConfirm(serializeMarkdownTable(table))}
>
确定
</Button>,
]}
className={styles.editModal}
>
<TableEditorPanel
table={table}
onChange={setTable}
hint="点击列标选择列对齐;单元格旁按钮可增删行列"
/>
</Modal>
);
}

View File

@ -0,0 +1,179 @@
import React, { useState } from 'react';
import { Button, Input, Segmented, Tooltip } from 'antd';
import {
addTableColumn,
addTableRow,
removeTableColumn,
removeTableRow,
setColumnAlign,
type CellAlign,
type MdTable,
} from '../lib/mdTable';
import styles from './TableModals.module.scss';
type Props = {
table: MdTable;
onChange: (table: MdTable) => void;
hint?: string;
};
export default function TableEditorPanel({ table, onChange, hint }: Props) {
const [activeCol, setActiveCol] = useState(0);
const alignValue: CellAlign = table.aligns[activeCol] ?? null;
const updateHeader = (col: number, value: string) => {
const header = [...table.header];
header[col] = value;
onChange({ ...table, header });
};
const updateCell = (row: number, col: number, value: string) => {
const rows = table.rows.map((r, ri) =>
ri === row ? r.map((c, ci) => (ci === col ? value : c)) : r,
);
onChange({ ...table, rows });
};
return (
<>
<div className={styles.editToolbar}>
<div className={styles.toolGroup}>
<Button size="small" onClick={() => onChange(addTableRow(table))}>
+ 行
</Button>
<Button
size="small"
disabled={table.rows.length <= 1}
onClick={() =>
onChange(removeTableRow(table, table.rows.length - 1))
}
>
− 行
</Button>
<Button size="small" onClick={() => onChange(addTableColumn(table))}>
+ 列
</Button>
<Button
size="small"
disabled={table.header.length <= 1}
onClick={() =>
onChange(removeTableColumn(table, table.header.length - 1))
}
>
− 列
</Button>
</div>
<div className={styles.toolGroup}>
<span className={styles.toolLabel}>列对齐</span>
<Segmented
size="small"
value={alignValue ?? 'left'}
onChange={(v) => {
const align =
v === 'center' || v === 'right' || v === 'left'
? (v as CellAlign)
: null;
onChange(setColumnAlign(table, activeCol, align));
}}
options={[
{ label: '左', value: 'left' },
{ label: '中', value: 'center' },
{ label: '右', value: 'right' },
]}
/>
</div>
</div>
<div className={styles.editScroll}>
<table className={styles.editTable}>
<thead>
<tr>
{table.header.map((cell, col) => (
<th key={`h-${col}`}>
<button
type="button"
className={`${styles.colHandle} ${
activeCol === col ? styles.colHandleActive : ''
}`}
onClick={() => setActiveCol(col)}
title="选择此列以设置对齐"
>
列 {col + 1}
</button>
<Input
value={cell}
onFocus={() => setActiveCol(col)}
onChange={(e) => updateHeader(col, e.target.value)}
placeholder={`列${col + 1}`}
/>
<div className={styles.colActions}>
<Tooltip title="在右侧插入列">
<button
type="button"
className={styles.iconBtn}
onClick={() => onChange(addTableColumn(table, col))}
>
+
</button>
</Tooltip>
<Tooltip title="删除此列">
<button
type="button"
className={styles.iconBtn}
disabled={table.header.length <= 1}
onClick={() => {
onChange(removeTableColumn(table, col));
setActiveCol(Math.max(0, col - 1));
}}
>
×
</button>
</Tooltip>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, ri) => (
<tr key={`r-${ri}`}>
{row.map((cell, ci) => (
<td key={`c-${ri}-${ci}`}>
<Input
value={cell}
onFocus={() => setActiveCol(ci)}
onChange={(e) => updateCell(ri, ci, e.target.value)}
placeholder="内容"
/>
</td>
))}
<td className={styles.rowActions}>
<Tooltip title="在下方插入行">
<button
type="button"
className={styles.iconBtn}
onClick={() => onChange(addTableRow(table, ri))}
>
+
</button>
</Tooltip>
<Tooltip title="删除此行">
<button
type="button"
className={styles.iconBtn}
disabled={table.rows.length <= 1}
onClick={() => onChange(removeTableRow(table, ri))}
>
×
</button>
</Tooltip>
</td>
</tr>
))}
</tbody>
</table>
</div>
{hint ? <p className={styles.hint}>{hint}</p> : null}
</>
);
}

View File

@ -0,0 +1,111 @@
import React, { useEffect, useState } from 'react';
import { Button, InputNumber, Modal } from 'antd';
import {
clampDim,
createEmptyTable,
resizeTable,
serializeMarkdownTable,
type MdTable,
} from '../lib/mdTable';
import TableEditorPanel from './TableEditorPanel';
import styles from './TableModals.module.scss';
type Props = {
open: boolean;
onCancel: () => void;
onConfirm: (markdown: string) => void;
};
const DEFAULT_ROWS = 4;
const DEFAULT_COLS = 3;
export default function TableInsertModal({ open, onCancel, onConfirm }: Props) {
const [rows, setRows] = useState(DEFAULT_ROWS);
const [cols, setCols] = useState(DEFAULT_COLS);
const [table, setTable] = useState<MdTable>(() =>
createEmptyTable(DEFAULT_ROWS, DEFAULT_COLS),
);
useEffect(() => {
if (open) {
setRows(DEFAULT_ROWS);
setCols(DEFAULT_COLS);
setTable(createEmptyTable(DEFAULT_ROWS, DEFAULT_COLS));
}
}, [open]);
const applyRows = (nextRows: number) => {
const clamped = clampDim(nextRows, 2, 20);
setRows(clamped);
setTable((prev) => resizeTable(prev, clamped, prev.header.length));
};
const applyCols = (nextCols: number) => {
const clamped = clampDim(nextCols, 1, 20);
setCols(clamped);
setTable((prev) => resizeTable(prev, prev.rows.length + 1, clamped));
};
const syncDimsFromTable = (next: MdTable) => {
setTable(next);
setRows(next.rows.length + 1);
setCols(next.header.length);
};
const handleOk = () => {
onConfirm(serializeMarkdownTable(table));
};
const colCount = table.header.length;
return (
<Modal
title="插入表格"
open={open}
onCancel={onCancel}
destroyOnClose
centered
width={Math.min(920, 160 + colCount * 140)}
footer={[
<Button key="cancel" onClick={onCancel}>
取消
</Button>,
<Button key="ok" type="primary" onClick={handleOk}>
确定
</Button>,
]}
className={styles.insertModal}
>
<div className={styles.insertBody}>
<div className={styles.dimRow}>
<label className={styles.dimField}>
<span>行</span>
<InputNumber
min={2}
max={20}
value={rows}
onChange={(v) => applyRows(clampDim(Number(v ?? DEFAULT_ROWS), 2, 20))}
controls
/>
</label>
<label className={styles.dimField}>
<span>列</span>
<InputNumber
min={1}
max={20}
value={cols}
onChange={(v) => applyCols(clampDim(Number(v ?? DEFAULT_COLS), 1, 20))}
controls
/>
</label>
</div>
<TableEditorPanel
table={table}
onChange={syncDimsFromTable}
hint={`${rows} 行 × ${cols} 列(含表头)· 在下方直接填写内容后确定 · Ctrl+Shift+T`}
/>
</div>
</Modal>
);
}

View File

@ -0,0 +1,189 @@
.insertModal {
:global(.ant-modal-title) {
text-align: center;
font-weight: 600;
}
:global(.ant-modal-body) {
padding-top: 8px;
}
}
.insertBody {
display: flex;
flex-direction: column;
gap: 16px;
padding: 4px 0 2px;
}
.dimRow {
display: flex;
justify-content: center;
gap: 28px;
}
.dimField {
display: inline-flex;
align-items: center;
gap: 10px;
margin: 0;
font-size: 14px;
color: #1a2330;
:global(.ant-input-number) {
width: 88px;
}
}
.gridPreview {
display: grid;
gap: 6px;
padding: 14px;
border-radius: 12px;
background:
linear-gradient(180deg, #f7fafb 0%, #eef3f5 100%);
border: 1px solid rgba(26, 35, 48, 0.08);
min-height: 120px;
max-height: 220px;
overflow: auto;
}
.gridCell {
aspect-ratio: 1.6 / 1;
min-height: 22px;
border-radius: 4px;
border: 1px solid rgba(15, 118, 110, 0.28);
background: rgba(255, 255, 255, 0.85);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
}
.hint {
margin: 0;
text-align: center;
font-size: 12px;
color: #5b6b7c;
}
.editModal {
:global(.ant-modal-body) {
padding-top: 8px;
}
}
.editToolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.toolGroup {
display: inline-flex;
align-items: center;
gap: 8px;
}
.toolLabel {
font-size: 12px;
color: #5b6b7c;
}
.editScroll {
overflow: auto;
max-height: min(52vh, 420px);
border: 1px solid rgba(26, 35, 48, 0.1);
border-radius: 12px;
background: #fbfcfd;
}
.editTable {
border-collapse: separate;
border-spacing: 0;
width: max-content;
min-width: 100%;
th,
td {
padding: 8px;
border-bottom: 1px solid rgba(26, 35, 48, 0.08);
border-right: 1px solid rgba(26, 35, 48, 0.06);
vertical-align: top;
min-width: 120px;
}
th {
background: rgba(13, 148, 136, 0.08);
position: sticky;
top: 0;
z-index: 1;
}
tr:last-child td {
border-bottom: none;
}
}
.colHandle {
appearance: none;
border: none;
background: transparent;
color: #0f766e;
font-size: 11px;
font-weight: 600;
cursor: pointer;
padding: 0 0 6px;
display: block;
width: 100%;
text-align: left;
&:hover {
color: #0d9488;
}
}
.colHandleActive {
color: #0d9488;
text-decoration: underline;
text-underline-offset: 2px;
}
.colActions,
.rowActions {
display: flex;
gap: 4px;
margin-top: 6px;
}
.rowActions {
min-width: 64px;
border-right: none !important;
background: transparent;
vertical-align: middle;
}
.iconBtn {
appearance: none;
width: 22px;
height: 22px;
border-radius: 6px;
border: 1px solid rgba(26, 35, 48, 0.12);
background: #fff;
color: #5b6b7c;
font-size: 13px;
line-height: 1;
cursor: pointer;
display: inline-grid;
place-items: center;
&:hover:not(:disabled) {
color: #0f766e;
border-color: rgba(13, 148, 136, 0.4);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
}

View File

@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta
http-equiv="Content-Security-Policy"
content="script-src 'self' 'unsafe-inline'"
content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: http: https: emojilocal: file:; connect-src 'self' http: https:; font-src 'self' data:"
/>
<title>emojiTool</title>
</head>

View File

@ -0,0 +1,29 @@
/** Build standard GFM image syntax. Encodes spaces/special chars in URL. */
export function buildImageMarkdown(alt: string, url: string): string {
const safeAlt = alt.replace(/[\[\]]/g, '').replace(/\s+/g, ' ').trim() || '图片';
const safeUrl = encodeMarkdownImageUrl(url);
return `![${safeAlt}](${safeUrl})\n`;
}
/** Encode path for use inside Markdown () — keep : / for http(s), encode the rest. */
export function encodeMarkdownImageUrl(url: string): string {
if (!url) return url;
if (/^https?:\/\//i.test(url)) {
try {
// Preserve already-valid absolute URLs; encode pathname if needed
const u = new URL(url);
u.pathname = u.pathname
.split('/')
.map((seg) => encodeURIComponent(decodeURIComponent(seg)))
.join('/');
return u.toString();
} catch {
return encodeURI(url);
}
}
// Relative like images/foo bar.png → images/foo%20bar.png
return url
.split('/')
.map((seg) => encodeURIComponent(seg))
.join('/');
}

View File

@ -0,0 +1,81 @@
import { useEffect, useRef } from 'react';
function scrollRatio(el: HTMLElement): number {
const max = el.scrollHeight - el.clientHeight;
if (max <= 0) return 0;
return el.scrollTop / max;
}
function applyRatio(el: HTMLElement, ratio: number): void {
const max = el.scrollHeight - el.clientHeight;
if (max <= 0) {
el.scrollTop = 0;
return;
}
const next = ratio * max;
if (Math.abs(el.scrollTop - next) < 1) return;
el.scrollTop = next;
}
/**
* Keep multiple scroll containers in sync by relative position (0–1).
* Re-resolves elements on each scroll so late-mounted nodes (textarea) stay linked.
*/
export function useLinkedScroll(
getElements: () => Array<HTMLElement | null | undefined>,
deps: unknown[] = [],
): void {
const getElementsRef = useRef(getElements);
getElementsRef.current = getElements;
const lockRef = useRef(false);
const rafRef = useRef(0);
useEffect(() => {
const listeners = new Map<HTMLElement, EventListener>();
const resolve = () =>
getElementsRef
.current()
.filter((el): el is HTMLElement => el != null);
const detach = () => {
listeners.forEach((handler, el) => {
el.removeEventListener('scroll', handler);
});
listeners.clear();
};
const attach = () => {
detach();
const elements = resolve();
for (const el of elements) {
const handler: EventListener = () => {
if (lockRef.current) return;
lockRef.current = true;
const ratio = scrollRatio(el);
for (const other of resolve()) {
if (other !== el) applyRatio(other, ratio);
}
cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
lockRef.current = false;
});
};
el.addEventListener('scroll', handler, { passive: true });
listeners.set(el, handler);
}
};
attach();
const t0 = window.setTimeout(attach, 0);
const t1 = window.setTimeout(attach, 100);
return () => {
window.clearTimeout(t0);
window.clearTimeout(t1);
cancelAnimationFrame(rafRef.current);
detach();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}

266
src/renderer/lib/mdTable.ts Normal file
View File

@ -0,0 +1,266 @@
/** GFM pipe-table helpers inspired by MarkText insert/edit flow. */
export type CellAlign = 'left' | 'center' | 'right' | null;
export type MdTable = {
header: string[];
aligns: CellAlign[];
rows: string[][];
};
export type TableRange = {
start: number;
end: number;
table: MdTable;
};
const MAX_DIM = 20;
const MIN_DIM = 1;
export function clampDim(n: number, min = MIN_DIM, max = MAX_DIM): number {
if (!Number.isFinite(n)) return min;
return Math.min(max, Math.max(min, Math.floor(n)));
}
function splitCells(line: string): string[] {
let t = line.trim();
if (t.startsWith('|')) t = t.slice(1);
if (t.endsWith('|')) t = t.slice(0, -1);
return t.split('|').map((c) => c.trim());
}
function isTableLine(line: string): boolean {
const t = line.trim();
if (!t || t.startsWith('```')) return false;
return t.includes('|');
}
function isSeparatorLine(line: string): boolean {
const cells = splitCells(line);
if (cells.length === 0) return false;
return cells.every((c) => /^:?-{3,}:?$/.test(c.replace(/\s/g, '')));
}
function parseAlign(cell: string): CellAlign {
const c = cell.replace(/\s/g, '');
if (/^:-+:$/.test(c)) return 'center';
if (/^-+:$/.test(c)) return 'right';
if (/^:-+$/.test(c)) return 'left';
return null;
}
function alignSep(align: CellAlign): string {
if (align === 'center') return ':---:';
if (align === 'right') return '---:';
if (align === 'left') return ':---';
return '---';
}
function padRow(cells: string[], cols: number): string[] {
const next = cells.slice(0, cols);
while (next.length < cols) next.push('');
return next;
}
export function createEmptyTable(rowCount: number, colCount: number): MdTable {
const rowsN = clampDim(rowCount);
const colsN = clampDim(colCount);
const header = Array.from({ length: colsN }, (_, i) => `列${i + 1}`);
const aligns: CellAlign[] = Array.from({ length: colsN }, () => null);
// rowCount includes header in MarkText dialog; body = rows - 1
const bodyCount = Math.max(1, rowsN - 1);
const rows = Array.from({ length: bodyCount }, () =>
Array.from({ length: colsN }, () => ''),
);
return { header, aligns, rows };
}
export function serializeMarkdownTable(table: MdTable): string {
const cols = Math.max(
table.header.length,
...table.rows.map((r) => r.length),
1,
);
const header = padRow(table.header, cols);
const aligns = padRow(
table.aligns.map((a) => a ?? ''),
cols,
).map((_, i) => table.aligns[i] ?? null);
const body = table.rows.map((r) => padRow(r, cols));
const headerLine = `| ${header.join(' | ')} |`;
const sepLine = `| ${aligns.map(alignSep).join(' | ')} |`;
const bodyLines = body.map((r) => `| ${r.join(' | ')} |`);
return [headerLine, sepLine, ...bodyLines].join('\n') + '\n';
}
export function parseMarkdownTableBlock(block: string): MdTable | null {
const lines = block
.replace(/\r\n/g, '\n')
.split('\n')
.map((l) => l.trimEnd())
.filter((l) => l.trim().length > 0);
if (lines.length < 2) return null;
if (!isSeparatorLine(lines[1])) return null;
const header = splitCells(lines[0]);
if (header.length === 0) return null;
const sepCells = splitCells(lines[1]);
const aligns: CellAlign[] = header.map((_, i) =>
parseAlign(sepCells[i] ?? '---'),
);
const rows = lines.slice(2).map((line) => padRow(splitCells(line), header.length));
return { header, aligns, rows };
}
/** Find the GFM table block that contains `offset` (or starts at cursor line). */
export function findTableAtOffset(
content: string,
offset: number,
): TableRange | null {
const normalized = content.replace(/\r\n/g, '\n');
const lines = normalized.split('\n');
const starts: number[] = [];
let pos = 0;
for (let i = 0; i < lines.length; i += 1) {
starts.push(pos);
pos += lines[i].length + 1;
}
let lineIndex = 0;
for (let i = 0; i < starts.length; i += 1) {
const lineStart = starts[i];
const lineEnd = lineStart + lines[i].length;
if (offset <= lineEnd || i === starts.length - 1) {
lineIndex = i;
if (offset >= lineStart) break;
}
if (offset >= lineStart && offset <= lineEnd + 1) {
lineIndex = i;
break;
}
}
// Clamp: if past last char, use last line
if (offset >= normalized.length) {
lineIndex = Math.max(0, lines.length - 1);
} else {
for (let i = 0; i < starts.length; i += 1) {
if (offset >= starts[i] && offset <= starts[i] + lines[i].length) {
lineIndex = i;
break;
}
if (offset === starts[i] + lines[i].length + 1 && i + 1 < lines.length) {
lineIndex = i + 1;
break;
}
}
}
if (!isTableLine(lines[lineIndex] ?? '')) return null;
let startLine = lineIndex;
while (startLine > 0 && isTableLine(lines[startLine - 1])) {
startLine -= 1;
}
let endLine = lineIndex;
while (endLine + 1 < lines.length && isTableLine(lines[endLine + 1])) {
endLine += 1;
}
const blockLines = lines.slice(startLine, endLine + 1);
// Need header + separator at minimum
if (blockLines.length < 2 || !isSeparatorLine(blockLines[1])) {
return null;
}
const table = parseMarkdownTableBlock(blockLines.join('\n'));
if (!table) return null;
const start = starts[startLine];
const lastLineStart = starts[endLine];
let end = lastLineStart + lines[endLine].length;
if (normalized[end] === '\n') end += 1;
return { start, end, table };
}
export function buildMarkdownTable(rowCount: number, colCount: number): string {
return serializeMarkdownTable(createEmptyTable(rowCount, colCount));
}
export function resizeTable(
table: MdTable,
rowCount: number,
colCount: number,
): MdTable {
const cols = clampDim(colCount);
const bodyRows = Math.max(1, clampDim(rowCount) - 1);
const header = padRow(
table.header.map((h, i) => h || `列${i + 1}`),
cols,
).map((h, i) => h || `列${i + 1}`);
const aligns: CellAlign[] = Array.from(
{ length: cols },
(_, i) => table.aligns[i] ?? null,
);
const rows: string[][] = [];
for (let r = 0; r < bodyRows; r += 1) {
const src = table.rows[r] ?? [];
rows.push(padRow(src, cols).map((c) => c));
}
return { header, aligns, rows };
}
export function addTableRow(table: MdTable, afterIndex?: number): MdTable {
const cols = table.header.length;
const empty = Array.from({ length: cols }, () => '');
const rows = [...table.rows];
const idx =
afterIndex === undefined
? rows.length
: Math.min(rows.length, Math.max(0, afterIndex + 1));
rows.splice(idx, 0, empty);
return { ...table, rows };
}
export function removeTableRow(table: MdTable, index: number): MdTable {
if (table.rows.length <= 1) return table;
const rows = table.rows.filter((_, i) => i !== index);
return { ...table, rows };
}
export function addTableColumn(table: MdTable, afterIndex?: number): MdTable {
const idx =
afterIndex === undefined
? table.header.length
: Math.min(table.header.length, Math.max(0, afterIndex + 1));
const header = [...table.header];
const aligns = [...table.aligns];
header.splice(idx, 0, `列${header.length + 1}`);
aligns.splice(idx, 0, null);
const rows = table.rows.map((row) => {
const next = [...row];
next.splice(idx, 0, '');
return next;
});
return { header, aligns, rows };
}
export function removeTableColumn(table: MdTable, index: number): MdTable {
if (table.header.length <= 1) return table;
const header = table.header.filter((_, i) => i !== index);
const aligns = table.aligns.filter((_, i) => i !== index);
const rows = table.rows.map((row) => row.filter((_, i) => i !== index));
return { header, aligns, rows };
}
export function setColumnAlign(
table: MdTable,
colIndex: number,
align: CellAlign,
): MdTable {
const aligns = [...table.aligns];
if (colIndex < 0 || colIndex >= aligns.length) return table;
aligns[colIndex] = align;
return { ...table, aligns };
}

View File

@ -0,0 +1,131 @@
import { Marked, Renderer } from 'marked';
/**
* Display-only: resolve local image hrefs for the article HTML preview.
* Does NOT change Markdown source — source stays standard GFM.
*/
export function resolveImageSrcForPreview(url: string): string {
if (!url) return url;
if (/^(https?:|data:)/i.test(url)) return url;
let decoded = url;
try {
decoded = decodeURI(url);
} catch {
decoded = url;
}
const rel = decoded.replace(/^\.\//, '');
if (/^images\//i.test(rel)) {
const name = rel.slice('images/'.length);
return `emojilocal://images/${encodeURIComponent(name)}`;
}
if (/^emojilocal:\/\/images\//i.test(url)) {
return url;
}
if (/^file:/i.test(url)) {
try {
const normalized = decodeURIComponent(url.replace(/^file:\/\/\//i, ''));
const parts = normalized.replace(/\\/g, '/').split('/');
const idx = parts.findIndex((p) => p.toLowerCase() === 'images');
if (idx >= 0 && parts[idx + 1]) {
return `emojilocal://images/${encodeURIComponent(parts[idx + 1])}`;
}
} catch {
// keep
}
}
return url;
}
/**
* Cleanup bad links → standard relative `images/name`.
* Also fixes paths with spaces (invalid in GFM parentheses) via percent-encoding.
*/
export function toStandardImageMarkdown(source: string): string {
// Allow spaces inside (...): broken inserts like images/foo bar.png
return source.replace(
/!\[([^\]]*)\]\(([^)\n]+)\)/g,
(_m, alt: string, url: string) => {
let next = url.trim();
const emo = /^emojilocal:\/\/images\/(.+)$/i.exec(next);
if (emo) {
next = `images/${decodeURIComponent(emo[1])}`;
} else if (/^file:/i.test(next)) {
try {
const normalized = decodeURIComponent(next.replace(/^file:\/\/\//i, ''));
const parts = normalized.replace(/\\/g, '/').split('/');
const idx = parts.findIndex((p) => p.toLowerCase() === 'images');
if (idx >= 0 && parts[idx + 1]) {
next = `images/${parts.slice(idx + 1).join('/')}`;
}
} catch {
// keep
}
} else {
try {
next = decodeURI(next);
} catch {
// keep
}
}
// GFM: spaces inside () break the image — encode path segments
if (!/^https?:\/\//i.test(next) && /[\s<>]/.test(next)) {
next = next
.split('/')
.map((seg) => encodeURIComponent(seg))
.join('/');
}
return `![${alt}](${next})`;
},
);
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function formatArticleFooter(footerText: string): string {
const lines = footerText.replace(/\r\n/g, '\n').split('\n');
const body = lines.map((line) => escapeHtml(line)).join('<br/>');
return `<footer class="md-footer">${body}</footer>`;
}
const renderer = new Renderer();
const defaultImage = renderer.image.bind(renderer);
renderer.image = (href, title, text) => {
// Only the HTML output is remapped for Electron preview; Markdown is untouched.
const nextHref = href ? resolveImageSrcForPreview(href) : href;
return defaultImage(nextHref, title, text);
};
const richMarked = new Marked({
gfm: true,
breaks: true,
renderer,
});
/** Standard GFM HTML for the long-form article pane. */
export function renderRichMarkdown(
source: string,
options?: {
appendFooter?: boolean;
footerText?: string;
},
): string {
const appendFooter = options?.appendFooter !== false;
const footerText = options?.footerText ?? '';
const bodyHtml = richMarked.parse(source) as string;
if (appendFooter && footerText.trim()) {
return bodyHtml + formatArticleFooter(footerText);
}
return bodyHtml;
}

View File

@ -12,7 +12,10 @@ export type DraftState = {
content: string;
appendFooter: boolean;
footerText: string;
/** Plain-text (emoji) preview theme */
themeId: ThemeId;
/** Long-form article preview theme */
articleThemeId: ThemeId;
editorMode: EditorMode;
tocOpen: boolean;
};
@ -24,6 +27,7 @@ const DEFAULT_DRAFT: DraftState = {
appendFooter: true,
footerText: DEFAULT_FOOTER_TEXT,
themeId: DEFAULT_THEME_ID,
articleThemeId: DEFAULT_THEME_ID,
editorMode: 'markdown',
tocOpen: true,
};
@ -38,6 +42,9 @@ export function loadDraft(): DraftState {
const themeId: ThemeId = isThemeId(parsed.themeId)
? parsed.themeId
: DEFAULT_THEME_ID;
const articleThemeId: ThemeId = isThemeId(parsed.articleThemeId)
? parsed.articleThemeId
: themeId;
const content =
typeof parsed.content === 'string'
? parsed.content
@ -53,6 +60,7 @@ export function loadDraft(): DraftState {
? parsed.footerText
: DEFAULT_FOOTER_TEXT,
themeId,
articleThemeId,
editorMode: parsed.editorMode === 'plain' ? 'plain' : 'markdown',
tocOpen: typeof parsed.tocOpen === 'boolean' ? parsed.tocOpen : true,
};

View File

@ -69,7 +69,7 @@ export const THEME_A: EmojiTheme = {
id: 'A',
name: '主题 A · 经典',
shortName: 'A 经典',
description: '圆角边框标题 + 序号 emoji,沿用原版风格',
description: '圆角边框标题 + 序号 emoji;长文为青绿经典排版',
listSymbol: '🔸',
orderedNumbers: [
'1️⃣',
@ -113,7 +113,7 @@ export const THEME_B: EmojiTheme = {
id: 'B',
name: '主题 B · 青简',
shortName: 'B 青简',
description: '书签框标题 + 圆圈序号,『代码』与经典一致',
description: '书签框标题 + 圆圈序号;长文为青简侧栏强调',
listSymbol: '▪️',
orderedNumbers: [
'①',
@ -157,7 +157,7 @@ export const THEME_C: EmojiTheme = {
id: 'C',
name: '主题 C · 精简',
shortName: 'C 精简',
description: '最少装饰的纯文本风,语法仍全部转换',
description: '最少装饰的纯文本风;长文为精简白底排版',
listSymbol: '•',
orderedNumbers: [
'1.',
@ -201,7 +201,7 @@ export const THEME_D: EmojiTheme = {
id: 'D',
name: '主题 D · 聚焦',
shortName: 'D 聚焦',
description: '双线框标题 + 箭头引导,适合要点清单',
description: '双线框标题 + 箭头引导;长文为暖色聚焦排版',
listSymbol: '👉',
orderedNumbers: [
'❶',

63
src/shared/appSettings.ts Normal file
View File

@ -0,0 +1,63 @@
/** Shared app settings shape (main + renderer). */
export type ImageHostingSettings = {
/** Master switch: upload to S3 when inserting images */
enabled: boolean;
/** When enabled, pick/drop uploads to S3; otherwise insert relative images/ path */
uploadOnInsert: boolean;
provider: 's3';
/** S3-compatible API endpoint, e.g. MinIO */
endpoint: string;
region: string;
bucket: string;
accessKey: string;
/** Stored encrypted in main process userData */
secretKey: string;
/** Public URL prefix for inserted markdown links */
publicBaseUrl: string;
/** Object key prefix inside bucket */
pathPrefix: string;
forcePathStyle: boolean;
};
export type EditorSettings = {
autosave: boolean;
};
export type AppSettings = {
imageHosting: ImageHostingSettings;
editor: EditorSettings;
};
/** Defaults for self-hosted MinIO/S3 — credentials must be filled in Settings. */
export const DEFAULT_APP_SETTINGS: AppSettings = {
imageHosting: {
enabled: false,
uploadOnInsert: true,
provider: 's3',
endpoint: 'http://82.157.112.245:9000',
region: 'us-east-1',
bucket: 'emojitool',
accessKey: '',
secretKey: '',
publicBaseUrl: 'http://82.157.112.245:9000',
pathPrefix: 'images',
forcePathStyle: true,
},
editor: {
autosave: true,
},
};
export function mergeAppSettings(partial?: Partial<AppSettings>): AppSettings {
return {
imageHosting: {
...DEFAULT_APP_SETTINGS.imageHosting,
...partial?.imageHosting,
},
editor: {
...DEFAULT_APP_SETTINGS.editor,
...partial?.editor,
},
};
}

1766
yarn.lock

File diff suppressed because it is too large Load Diff