feat: polish editor UX, menus, and markdown rendering
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

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hackrobot 2026-10-02 07:27:17 +08:00
parent f13ac764e7
commit de3ea81b91
19 changed files with 746 additions and 383 deletions

View File

@ -16,29 +16,30 @@
| 能力 | 说明 | | 能力 | 说明 |
|------|------| |------|------|
| Markdown 实时预览 | 左侧编辑、右侧预览,基于 `marked` 自定义 Renderer | | Markdown 实时预览 | 左侧编辑、右侧预览,基于 `marked` 自定义 Renderer |
| 四套主题 A–D | 经典 / 青简 / 精简 / 聚焦,下拉切换 |
| Emoji 装饰排版 | 标题边框、列表符号、任务勾选、引用、分隔线等用 Unicode/Emoji 呈现 | | Emoji 装饰排版 | 标题边框、列表符号、任务勾选、引用、分隔线等用 Unicode/Emoji 呈现 |
| 一键复制 | 复制为纯文本(表格用字符边框,粘贴到微信/IM 仍可见结构) | | 一键复制 | 复制为纯文本(表格用全角字符网格,粘贴到微信/IM 仍可见结构) |
| 草稿自动保存 | 本地 `localStorage` 持久化正文与页脚开关 | | 草稿自动保存 | 本地 `localStorage`(键:`emojitool.draft`) |
| 模板与片段 | 内置公众号短文/任务清单等模板,工具栏可插入标题、列表等片段 | | 模板与片段 | 内置语法全览等模板;工具栏片段插入到**光标处** |
| 页脚开关 | 可关闭/编辑自动追加的署名 | | 页脚开关 | 可关闭/编辑自动追加的署名 |
| 左侧目录 | 解析 `#` 标题大纲,点击跳转 | | 左侧目录 | 解析 `#` 标题大纲,点击跳转 |
| 编辑模式 | MD 源码 / 普通编辑可切换(参考 [MarkText](https://github.com/marktext/marktext) 源码体验) | | 编辑模式 | MD 源码 / 普通编辑可切换 |
| 右键插入 | MD 模式下右键插入标题、任务、表格、代码块等 | | 右键与快捷键 | MD 模式:右键插入;`Ctrl+B` 加粗、`Ctrl+I` 斜体、`Ctrl+K` 链接;`Ctrl+Enter` 复制;`Ctrl+S` 保存 |
| 外链菜单 | 「公众号: 异度世界」「mdemoji.com」 | | 外链菜单 | 异度世界 / mdemoji.com / 仓库 |
### Markdown 装饰规则(摘要) ### Markdown 装饰规则(摘要 · 主题 A)
- **H1**:`╭──╮` 边框 + `📢` 标题 - **H1**:`╭──╮` 边框 + `📢` 标题
- **H2 / H3**:前缀 `📝` - **H2**:前缀 `📝`;**H3**:`📎`;**H4**:`▪️`
- **无序列表**:`🔸`,嵌套用 `┊` - **无序列表**:`🔸`,嵌套用 `┊`
- **有序列表**:`1️⃣` … `🔟` - **有序列表**:`1️⃣` … `🔟`
- **任务列表**:`✅` / `⬜` - **任务列表**:`✅` / `⬜`
- **行内代码**:`『…』` - **行内代码**:`『…』`
- **引用**:`└─⚡` - **引用**:`└─⚡`(多行各自成行)
- **分隔线**:`➖➖➖➖➖` - **分隔线**:`➖➖➖➖➖`
- **链接**:`🔗文案` + URL - **链接**:`🔗文案` + URL
- **图片**:固定宽度约 `300px` - **图片**:纯文本 `🖼 说明:url`
- **表格**:表头标注 `📊 表格 📊` - **表格**:全角字符网格(Theme B 为 pipe 风格)
## 技术栈 ## 技术栈
@ -58,36 +59,31 @@ src/
│ └── util.ts │ └── util.ts
├── renderer/ # 渲染进程 ├── renderer/ # 渲染进程
│ ├── App.tsx # 布局与交互 │ ├── App.tsx # 布局与交互
│ ├── App.module.scss # Ink & Leaf 视觉 │ ├── App.module.scss
│ ├── index.ejs │ ├── index.ejs
│ ├── components/
│ │ └── EditorPane.tsx
│ └── lib/ │ └── lib/
│ ├── emojiMarkdown.ts # Markdown → Emoji 纯文本 │ ├── emojiMarkdown.ts
│ ├── themes.ts │ ├── themes.ts
│ ├── toc.ts # 标题目录 │ ├── plainTable.ts
│ ├── editorActions.ts # 右键插入动作 │ ├── toc.ts
│ ├── editorActions.ts
│ ├── storage.ts │ ├── storage.ts
│ └── templates.ts │ └── templates.ts
│ └── components/
│ └── EditorPane.tsx # 左侧目录 + 编辑器
└── __tests__/ └── __tests__/
``` ```
业务逻辑:渲染规则在 `lib/emojiMarkdown.ts`,交互在 `App.tsx`。
## 开发 ## 开发
环境要求:Node.js ≥ 14,npm ≥ 7。 环境要求:Node.js ≥ 14,npm ≥ 7。
```bash ```bash
# 建议使用主开发分支
git checkout greenbook git checkout greenbook
npm install npm install
npm start npm start
``` ```
常用脚本:
| 命令 | 说明 | | 命令 | 说明 |
|------|------| |------|------|
| `npm start` | 启动开发环境 | | `npm start` | 启动开发环境 |
@ -100,15 +96,15 @@ npm start
| 分支 | 说明 | | 分支 | 说明 |
|------|------| |------|------|
| **`greenbook`** | 当前最新业务分支,含 emoji 编辑器主体功能 | | **`greenbook`** | 当前最新业务分支 |
| `main` | 接近 ERB 初始脚手架,明显落后于 `greenbook` | | `main` | 接近 ERB 初始脚手架,明显落后于 `greenbook` |
| `feature/emoji` | 历史旁支,已被 `greenbook` 覆盖 | | `feature/emoji` | 历史旁支,已被 `greenbook` 覆盖 |
## 已知说明 ## 已知说明
- 包名 / `productName` 已统一为 **emojitool** / **emojiTool**。 - 包名 / `productName` 已统一为 **emojitool** / **emojiTool**。
- 暂无云同步、多窗口;草稿保存在本机 `localStorage`(键:`emojitool.draft`)。 - 暂无云同步、多窗口;草稿保存在本机。
- 提供 A–D 四套纯文本主题,复制优先 `innerText`,表格为全角字符网格。 - 复制优先 `innerText`,表格为全角字符网格(box / pipe / dots)。
## License ## License

View File

@ -0,0 +1,63 @@
import {
applyEditorAction,
EDITOR_ACTIONS,
handleMarkdownEnter,
handleMarkdownTab,
} from '../renderer/lib/editorActions';
describe('editorActions', () => {
const bold = EDITOR_ACTIONS.find((a) => a.id === 'bold')!;
const link = EDITOR_ACTIONS.find((a) => a.id === 'link')!;
const h2 = EDITOR_ACTIONS.find((a) => a.id === 'h2')!;
const ul = EDITOR_ACTIONS.find((a) => a.id === 'ul')!;
it('wraps selection for bold', () => {
const result = applyEditorAction('hello', 0, 5, bold);
expect(result.next).toBe('**hello**');
expect(result.selectionStart).toBe(2);
expect(result.selectionEnd).toBe(7);
});
it('selects URL after link insert', () => {
const result = applyEditorAction('', 0, 0, link);
expect(result.next).toContain('](https://example.com)');
expect(result.next.slice(result.selectionStart, result.selectionEnd)).toBe(
'https://example.com',
);
});
it('prefixes current line for headings', () => {
const result = applyEditorAction('abc\ntitle\nxyz', 5, 5, h2);
expect(result.next).toBe('abc\n## title\nxyz');
});
it('inserts block list with newline boundary', () => {
const result = applyEditorAction('para', 4, 4, ul);
expect(result.next.startsWith('para\n- ')).toBe(true);
});
it('continues unordered list on Enter', () => {
const src = '- item';
const result = handleMarkdownEnter(src, src.length, src.length);
expect(result?.next).toBe('- item\n- ');
});
it('exits empty list item on Enter', () => {
const src = '- ';
const result = handleMarkdownEnter(src, 2, 2);
expect(result?.next).toBe('');
});
it('increments ordered list on Enter', () => {
const src = '1. first';
const result = handleMarkdownEnter(src, src.length, src.length);
expect(result?.next).toBe('1. first\n2. ');
});
it('indents and outdents with Tab', () => {
const indented = handleMarkdownTab('- a', 3, 3, false);
expect(indented?.next).toBe(' - a');
const out = handleMarkdownTab(' - a', 5, 5, true);
expect(out?.next).toBe('- a');
});
});

View File

@ -9,7 +9,7 @@
* `./src/main.js` using webpack. This gives us some performance wins. * `./src/main.js` using webpack. This gives us some performance wins.
*/ */
import path from 'path'; import path from 'path';
import { app, BrowserWindow, shell, ipcMain } from 'electron'; import { app, BrowserWindow, shell } from 'electron';
import { autoUpdater } from 'electron-updater'; import { autoUpdater } from 'electron-updater';
import log from 'electron-log'; import log from 'electron-log';
import MenuBuilder from './menu'; import MenuBuilder from './menu';
@ -31,12 +31,6 @@ class AppUpdater {
let mainWindow: BrowserWindow | null = null; let mainWindow: BrowserWindow | null = null;
ipcMain.on('ipc-example', async (event, arg) => {
const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
console.log(msgTemplate(arg));
event.reply('ipc-example', msgTemplate('pong'));
});
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support'); const sourceMapSupport = require('source-map-support');
sourceMapSupport.install(); sourceMapSupport.install();

View File

@ -37,13 +37,22 @@ export default class MenuBuilder {
return menu; return menu;
} }
setupDevelopmentEnvironment(): void { sendCommand(command: string): void {
this.mainWindow.webContents.on('context-menu', (_, props) => { this.mainWindow.webContents.send('menu-command', command);
const { x, y } = props; }
setupDevelopmentEnvironment(): void {
this.mainWindow.webContents.on('context-menu', (event, props) => {
// Let the Markdown editor handle its own context menu
if (props.isEditable) {
return;
}
event.preventDefault();
const { x, y } = props;
Menu.buildFromTemplate([ Menu.buildFromTemplate([
{ {
label: 'Inspect element', label: '检查元素',
click: () => { click: () => {
this.mainWindow.webContents.inspectElement(x, y); this.mainWindow.webContents.inspectElement(x, y);
}, },
@ -61,7 +70,7 @@ export default class MenuBuilder {
selector: 'orderFrontStandardAboutPanel:', selector: 'orderFrontStandardAboutPanel:',
}, },
{ type: 'separator' }, { type: 'separator' },
{ label: 'Services', submenu: [] }, { label: '服务', submenu: [] },
{ type: 'separator' }, { type: 'separator' },
{ {
label: '隐藏 emojiTool', label: '隐藏 emojiTool',
@ -85,40 +94,55 @@ export default class MenuBuilder {
], ],
}; };
const subMenuEdit: DarwinMenuItemConstructorOptions = { const subMenuEdit: DarwinMenuItemConstructorOptions = {
label: 'Edit', label: '编辑',
submenu: [ submenu: [
{ label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, { label: '撤销', accelerator: 'Command+Z', selector: 'undo:' },
{ label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { label: '重做', accelerator: 'Shift+Command+Z', selector: 'redo:' },
{ type: 'separator' }, { type: 'separator' },
{ label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, { label: '剪切', accelerator: 'Command+X', selector: 'cut:' },
{ label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, { label: '复制', accelerator: 'Command+C', selector: 'copy:' },
{ label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, { label: '粘贴', accelerator: 'Command+V', selector: 'paste:' },
{ {
label: 'Select All', label: '全选',
accelerator: 'Command+A', accelerator: 'Command+A',
selector: 'selectAll:', selector: 'selectAll:',
}, },
{ type: 'separator' },
{
label: '保存草稿',
accelerator: 'Command+S',
click: () => this.sendCommand('save-draft'),
},
{
label: '复制预览',
accelerator: 'Command+Enter',
click: () => this.sendCommand('copy-preview'),
},
{
label: '清空正文',
click: () => this.sendCommand('clear-content'),
},
], ],
}; };
const subMenuViewDev: MenuItemConstructorOptions = { const subMenuViewDev: MenuItemConstructorOptions = {
label: 'View', label: '视图',
submenu: [ submenu: [
{ {
label: 'Reload', label: '重新加载',
accelerator: 'Command+R', accelerator: 'Command+R',
click: () => { click: () => {
this.mainWindow.webContents.reload(); this.mainWindow.webContents.reload();
}, },
}, },
{ {
label: 'Toggle Full Screen', label: '全屏',
accelerator: 'Ctrl+Command+F', accelerator: 'Ctrl+Command+F',
click: () => { click: () => {
this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
}, },
}, },
{ {
label: 'Toggle Developer Tools', label: '开发者工具',
accelerator: 'Alt+Command+I', accelerator: 'Alt+Command+I',
click: () => { click: () => {
this.mainWindow.webContents.toggleDevTools(); this.mainWindow.webContents.toggleDevTools();
@ -127,10 +151,10 @@ export default class MenuBuilder {
], ],
}; };
const subMenuViewProd: MenuItemConstructorOptions = { const subMenuViewProd: MenuItemConstructorOptions = {
label: 'View', label: '视图',
submenu: [ submenu: [
{ {
label: 'Toggle Full Screen', label: '全屏',
accelerator: 'Ctrl+Command+F', accelerator: 'Ctrl+Command+F',
click: () => { click: () => {
this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
@ -139,16 +163,16 @@ export default class MenuBuilder {
], ],
}; };
const subMenuWindow: DarwinMenuItemConstructorOptions = { const subMenuWindow: DarwinMenuItemConstructorOptions = {
label: 'Window', label: '窗口',
submenu: [ submenu: [
{ {
label: 'Minimize', label: '最小化',
accelerator: 'Command+M', accelerator: 'Command+M',
selector: 'performMiniaturize:', selector: 'performMiniaturize:',
}, },
{ label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, { label: '关闭', accelerator: 'Command+W', selector: 'performClose:' },
{ type: 'separator' }, { type: 'separator' },
{ label: 'Bring All to Front', selector: 'arrangeInFront:' }, { label: '前置全部窗口', selector: 'arrangeInFront:' },
], ],
}; };
const subMenuHelp: MenuItemConstructorOptions = { const subMenuHelp: MenuItemConstructorOptions = {
@ -166,6 +190,12 @@ export default class MenuBuilder {
shell.openExternal('https://mdemoji.com'); shell.openExternal('https://mdemoji.com');
}, },
}, },
{
label: '仓库 emojiTool',
click() {
shell.openExternal('https://git.nomadro.cn/hackrobot/emojiTool');
},
},
], ],
}; };
@ -178,99 +208,85 @@ export default class MenuBuilder {
return [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp]; return [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp];
} }
buildDefaultTemplate() { buildDefaultTemplate(): MenuItemConstructorOptions[] {
const templateDefault = [ const isDev =
// { process.env.NODE_ENV === 'development' ||
// label: '&File', process.env.DEBUG_PROD === 'true';
// submenu: [
// { const viewSubmenu: MenuItemConstructorOptions[] = [
// label: '&Open',
// accelerator: 'Ctrl+O',
// },
// {
// label: '&Close',
// accelerator: 'Ctrl+W',
// click: () => {
// this.mainWindow.close();
// },
// },
// ],
// },
// {
// label: '&View',
// submenu:
// process.env.NODE_ENV === 'development' ||
// process.env.DEBUG_PROD === 'true'
// ? [
// {
// label: '&Reload',
// accelerator: 'Ctrl+R',
// click: () => {
// this.mainWindow.webContents.reload();
// },
// },
// {
// label: 'Toggle &Full Screen',
// accelerator: 'F11',
// click: () => {
// this.mainWindow.setFullScreen(
// !this.mainWindow.isFullScreen(),
// );
// },
// },
// {
// label: 'Toggle &Developer Tools',
// accelerator: 'Alt+Ctrl+I',
// click: () => {
// this.mainWindow.webContents.toggleDevTools();
// },
// },
// ]
// : [
// {
// label: 'Toggle &Full Screen',
// accelerator: 'F11',
// click: () => {
// this.mainWindow.setFullScreen(
// !this.mainWindow.isFullScreen(),
// );
// },
// },
// ],
// },
// {
// label: 'Help',
// submenu: [
// {
// label: 'Learn More',
// click() {
// shell.openExternal('https://electronjs.org');
// },
// },
// {
// label: 'Documentation',
// click() {
// shell.openExternal(
// 'https://github.com/electron/electron/tree/main/docs#readme',
// );
// },
// },
// {
// label: 'Community Discussions',
// click() {
// shell.openExternal('https://www.electronjs.org/community');
// },
// },
// {
// label: 'Search Issues',
// click() {
// shell.openExternal('https://github.com/electron/electron/issues');
// },
// },
// ],
// },
{ {
label: '菜单', label: '全屏',
accelerator: 'F11',
click: () => {
this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
},
},
];
if (isDev) {
viewSubmenu.unshift(
{
label: '重新加载',
accelerator: 'Ctrl+R',
click: () => {
this.mainWindow.webContents.reload();
},
},
{
label: '开发者工具',
accelerator: 'Alt+Ctrl+I',
click: () => {
this.mainWindow.webContents.toggleDevTools();
},
},
);
}
return [
{
label: '文件',
submenu: [
{
label: '保存草稿',
accelerator: 'Ctrl+S',
click: () => this.sendCommand('save-draft'),
},
{
label: '复制预览',
accelerator: 'Ctrl+Enter',
click: () => this.sendCommand('copy-preview'),
},
{
label: '清空正文',
click: () => this.sendCommand('clear-content'),
},
{ type: 'separator' },
{
label: '退出',
accelerator: 'Alt+F4',
click: () => {
this.mainWindow.close();
},
},
],
},
{
label: '编辑',
submenu: [
{ label: '撤销', role: 'undo' },
{ label: '重做', role: 'redo' },
{ type: 'separator' },
{ label: '剪切', role: 'cut' },
{ label: '复制', role: 'copy' },
{ label: '粘贴', role: 'paste' },
{ label: '全选', role: 'selectAll' },
],
},
{
label: '视图',
submenu: viewSubmenu,
},
{
label: '帮助',
submenu: [ submenu: [
{ {
label: '公众号: 异度世界', label: '公众号: 异度世界',
@ -284,10 +300,14 @@ export default class MenuBuilder {
shell.openExternal('https://mdemoji.com'); shell.openExternal('https://mdemoji.com');
}, },
}, },
{
label: '仓库 emojiTool',
click() {
shell.openExternal('https://git.nomadro.cn/hackrobot/emojiTool');
},
},
], ],
}, },
]; ];
return templateDefault;
} }
} }

View File

@ -1,25 +1,21 @@
// Disable no-unused-vars, broken for spread args
/* eslint no-unused-vars: off */ /* eslint no-unused-vars: off */
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron'; import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
export type Channels = 'ipc-example'; export type MenuCommand = 'copy-preview' | 'save-draft' | 'clear-content';
const electronHandler = { const electronHandler = {
ipcRenderer: { ipcRenderer: {
sendMessage(channel: Channels, ...args: unknown[]) { onMenuCommand(callback: (command: MenuCommand) => void) {
ipcRenderer.send(channel, ...args); const subscription = (
}, _event: IpcRendererEvent,
on(channel: Channels, func: (...args: unknown[]) => void) { command: MenuCommand,
const subscription = (_event: IpcRendererEvent, ...args: unknown[]) => ) => {
func(...args); callback(command);
ipcRenderer.on(channel, subscription); };
ipcRenderer.on('menu-command', subscription);
return () => { return () => {
ipcRenderer.removeListener(channel, subscription); ipcRenderer.removeListener('menu-command', subscription);
}; };
},
once(channel: Channels, func: (...args: unknown[]) => void) {
ipcRenderer.once(channel, (_event, ...args) => func(...args));
}, },
}, },
}; };

View File

@ -136,6 +136,8 @@
color: var(--muted); color: var(--muted);
font-size: 12px; font-size: 12px;
flex-shrink: 0; flex-shrink: 0;
cursor: pointer;
margin: 0;
} }
.footerPanel { .footerPanel {
@ -210,17 +212,32 @@
transition: transition:
background 160ms ease, background 160ms ease,
border-color 160ms ease, border-color 160ms ease,
transform 160ms ease; transform 160ms ease,
opacity 160ms ease;
&:hover { &:hover:not(:disabled) {
background: #fff; background: #fff;
border-color: rgba(13, 148, 136, 0.45); border-color: rgba(13, 148, 136, 0.45);
transform: translateY(-1px); transform: translateY(-1px);
} }
&:active { &:active:not(:disabled) {
transform: translateY(0); transform: translateY(0);
} }
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.snippetBarPlain {
opacity: 0.85;
} }
.saveHint { .saveHint {
@ -276,9 +293,8 @@
.paneTitle { .paneTitle {
font-size: 13px; font-size: 13px;
font-weight: 650; font-weight: 600;
letter-spacing: 0.04em; letter-spacing: 0.02em;
text-transform: uppercase;
color: var(--accent-deep); color: var(--accent-deep);
} }
@ -302,6 +318,11 @@
color: var(--accent-deep); color: var(--accent-deep);
border-color: rgba(13, 148, 136, 0.4); border-color: rgba(13, 148, 136, 0.4);
} }
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
} }
.editorPane { .editorPane {
@ -326,9 +347,8 @@
.tocTitle { .tocTitle {
font-size: 11px; font-size: 11px;
font-weight: 650; font-weight: 600;
letter-spacing: 0.08em; letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted); color: var(--muted);
padding: 0 6px 8px; padding: 0 6px 8px;
} }
@ -451,6 +471,14 @@
user-select: text; user-select: text;
animation: fadeIn 220ms ease; animation: fadeIn 220ms ease;
> :global(div) {
margin: 0 0 0.65em;
}
> :global(div:last-child) {
margin-bottom: 0;
}
:global(img) { :global(img) {
max-width: 100%; max-width: 100%;
height: auto; height: auto;
@ -528,7 +556,7 @@
.emptyTitle { .emptyTitle {
margin: 0 0 8px; margin: 0 0 8px;
font-size: 18px; font-size: 18px;
font-weight: 650; font-weight: 600;
color: var(--ink); color: var(--ink);
} }

View File

@ -1 +0,0 @@
/* Legacy global styles replaced by App.module.scss */

View File

@ -24,16 +24,30 @@ import {
} from './lib/emojiMarkdown'; } from './lib/emojiMarkdown';
import { loadDraft, saveDraft, type EditorMode } from './lib/storage'; import { loadDraft, saveDraft, type EditorMode } from './lib/storage';
import { DEFAULT_TEMPLATE_CONTENT, SNIPPETS, TEMPLATES } from './lib/templates'; import { DEFAULT_TEMPLATE_CONTENT, SNIPPETS, TEMPLATES } from './lib/templates';
import { EDITOR_ACTIONS, applyEditorAction } from './lib/editorActions'; import EditorPane, { type EditorPaneHandle } from './components/EditorPane';
import EditorPane from './components/EditorPane';
import styles from './App.module.scss'; import styles from './App.module.scss';
const { TextArea } = Input; const { TextArea } = Input;
const SAVE_DEBOUNCE_MS = 400; const SAVE_DEBOUNCE_MS = 400;
const PREVIEW_DEBOUNCE_MS = 120;
/** Snippet bar id → editor action id */
const SNIPPET_ACTION_IDS: Record<string, string> = {
h1: 'h1',
h2: 'h2',
ul: 'ul',
task: 'task',
hr: 'hr',
link: 'link',
quote: 'quote',
table: 'table',
// `code` keeps its combined inline+fence snippet via insertAtCursor
};
function App() { function App() {
const previewRef = useRef<HTMLDivElement>(null); const previewRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<EditorPaneHandle>(null);
const initial = useMemo(() => loadDraft(), []); const initial = useMemo(() => loadDraft(), []);
const [content, setContent] = useState(initial.content); const [content, setContent] = useState(initial.content);
@ -43,25 +57,35 @@ function App() {
const [editorMode, setEditorMode] = useState<EditorMode>(initial.editorMode); const [editorMode, setEditorMode] = useState<EditorMode>(initial.editorMode);
const [tocOpen, setTocOpen] = useState(initial.tocOpen); const [tocOpen, setTocOpen] = useState(initial.tocOpen);
const [savedHint, setSavedHint] = useState(false); const [savedHint, setSavedHint] = useState(false);
const [previewHtml, setPreviewHtml] = useState(() =>
renderEmojiMarkdown(initial.content, {
appendFooter: initial.appendFooter,
footerText: initial.footerText,
themeId: initial.themeId,
}),
);
const activeTheme = useMemo( const activeTheme = useMemo(
() => THEME_LIST.find((t) => t.id === themeId) ?? THEME_LIST[0], () => THEME_LIST.find((t) => t.id === themeId) ?? THEME_LIST[0],
[themeId], [themeId],
); );
const previewHtml = useMemo(
() =>
renderEmojiMarkdown(content, {
appendFooter,
footerText,
themeId,
}),
[content, appendFooter, footerText, themeId],
);
const charCount = content.length; const charCount = content.length;
const hasContent = content.trim().length > 0; const hasContent = content.trim().length > 0;
useEffect(() => {
const timer = window.setTimeout(() => {
setPreviewHtml(
renderEmojiMarkdown(content, {
appendFooter,
footerText,
themeId,
}),
);
}, PREVIEW_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [content, appendFooter, footerText, themeId]);
useEffect(() => { useEffect(() => {
const timer = window.setTimeout(() => { const timer = window.setTimeout(() => {
saveDraft({ saveDraft({
@ -127,28 +151,38 @@ function App() {
const applyTemplate = useCallback( const applyTemplate = useCallback(
(templateContent: string, label?: string) => { (templateContent: string, label?: string) => {
setContent(templateContent); const doApply = () => {
message.success(label ? `已填入「${label}」` : '已填入模板'); setContent(templateContent);
message.success(label ? `已填入「${label}」` : '已填入模板');
};
if (hasContent && content !== templateContent) {
Modal.confirm({
title: '用模板覆盖当前内容?',
content: '当前正文将被替换,主题与页脚设置会保留。',
okText: '覆盖',
cancelText: '取消',
onOk: doApply,
});
return;
}
doApply();
}, },
[], [content, hasContent],
); );
const insertSnippet = useCallback( const insertSnippet = useCallback(
(snippet: string) => { (snippetId: string, insert: string) => {
const action = EDITOR_ACTIONS.find((item) => item.insert === snippet); if (editorMode === 'plain') {
if (action) { message.info('请先切换到 MD 模式再插入片段');
const result = applyEditorAction(
content,
content.length,
content.length,
action,
);
setContent(result.next);
return; return;
} }
setContent((prev) => `${prev}${snippet}`); const actionId = SNIPPET_ACTION_IDS[snippetId];
if (actionId && editorRef.current?.runActionById(actionId)) {
return;
}
editorRef.current?.insertAtCursor(insert);
}, },
[content], [editorMode],
); );
const persistNow = useCallback(() => { const persistNow = useCallback(() => {
@ -172,24 +206,34 @@ function App() {
if (event.key === 'Enter') { if (event.key === 'Enter') {
event.preventDefault(); event.preventDefault();
copyPreview(); copyPreview();
} else if (event.key.toLowerCase() === 's') { return;
}
if (event.key.toLowerCase() === 's') {
event.preventDefault(); event.preventDefault();
persistNow(); persistNow();
} else if (event.key.toLowerCase() === 'b' && editorMode === 'markdown') { return;
// MarkText-like bold shortcut when not in plain mode
event.preventDefault();
const bold = EDITOR_ACTIONS.find((item) => item.id === 'bold');
if (!bold) return;
const el = document.activeElement as HTMLTextAreaElement | null;
const start = el?.selectionStart ?? content.length;
const end = el?.selectionEnd ?? content.length;
const result = applyEditorAction(content, start, end, bold);
setContent(result.next);
} }
if (editorMode !== 'markdown') return;
const key = event.key.toLowerCase();
const actionId =
key === 'b' ? 'bold' : key === 'i' ? 'italic' : key === 'k' ? 'link' : null;
if (!actionId) return;
event.preventDefault();
editorRef.current?.runActionById(actionId);
}; };
window.addEventListener('keydown', onKeyDown); window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown);
}, [copyPreview, persistNow, editorMode, content]); }, [copyPreview, persistNow, editorMode]);
useEffect(() => {
const dispose = window.electron?.ipcRenderer?.onMenuCommand?.((command) => {
if (command === 'copy-preview') copyPreview();
else if (command === 'save-draft') persistNow();
else if (command === 'clear-content') clearContent();
});
return () => dispose?.();
}, [copyPreview, persistNow, clearContent]);
const themeItems: MenuProps['items'] = THEME_LIST.map((theme) => ({ const themeItems: MenuProps['items'] = THEME_LIST.map((theme) => ({
key: theme.id, key: theme.id,
@ -208,6 +252,12 @@ function App() {
onClick: () => applyTemplate(item.content, item.label), onClick: () => applyTemplate(item.content, item.label),
})); }));
const hintText = savedHint
? '已自动保存'
: editorMode === 'markdown'
? `${activeTheme.name} · Enter 续列表 · Tab 缩进 · Ctrl+B/I/K`
: `${activeTheme.name} · 普通模式(片段已禁用)`;
return ( return (
<ConfigProvider <ConfigProvider
theme={{ theme={{
@ -229,7 +279,7 @@ function App() {
<div> <div>
<h1 className={styles.title}>emojiTool</h1> <h1 className={styles.title}>emojiTool</h1>
<p className={styles.subtitle}> <p className={styles.subtitle}>
Markdown → 公众号友好纯文本 · nomadro.com Markdown → 公众号友好纯文本 · mdemoji.com
</p> </p>
</div> </div>
</div> </div>
@ -276,27 +326,31 @@ function App() {
</div> </div>
</header> </header>
<div className={styles.snippetBar}> <div
className={`${styles.snippetBar} ${
editorMode === 'plain' ? styles.snippetBarPlain : ''
}`}
>
<span className={styles.snippetLabel}>插入</span> <span className={styles.snippetLabel}>插入</span>
{SNIPPETS.map((snippet) => ( {SNIPPETS.map((snippet) => (
<button <button
key={snippet.id} key={snippet.id}
type="button" type="button"
className={styles.snippetBtn} className={styles.snippetBtn}
onClick={() => insertSnippet(snippet.insert)} disabled={editorMode === 'plain'}
onClick={() => insertSnippet(snippet.id, snippet.insert)}
> >
{snippet.label} {snippet.label}
</button> </button>
))} ))}
<span className={styles.saveHint}> <span className={styles.saveHint} aria-live="polite">
{savedHint {hintText}
? '已自动保存'
: `${activeTheme.name} · 右键可插入样式`}
</span> </span>
</div> </div>
<main className={styles.workspace}> <main className={styles.workspace}>
<EditorPane <EditorPane
ref={editorRef}
content={content} content={content}
onChange={setContent} onChange={setContent}
mode={editorMode} mode={editorMode}
@ -316,13 +370,16 @@ function App() {
<div <div
ref={previewRef} ref={previewRef}
className={styles.previewHtml} className={styles.previewHtml}
aria-live="polite"
dangerouslySetInnerHTML={{ __html: previewHtml }} dangerouslySetInnerHTML={{ __html: previewHtml }}
/> />
) : ( ) : (
<div className={styles.emptyState}> <div className={styles.emptyState}>
<p className={styles.emptyTitle}>开始写一篇</p> <p className={styles.emptyTitle}>开始写一篇</p>
<p className={styles.emptyDesc}> <p className={styles.emptyDesc}>
左侧可切换 MD / 普通编辑,右键插入任务、表格等。 {editorMode === 'markdown'
? '左侧用 Markdown 写作,右键可插入标题、任务、表格等。'
: '当前为普通编辑模式;切换回 MD 后可用右键与快捷键。'}
<br /> <br />
目录可跳转到标题;右侧即时预览主题排版。 目录可跳转到标题;右侧即时预览主题排版。
</p> </p>
@ -338,14 +395,14 @@ function App() {
}`} }`}
> >
<div className={styles.footerPanelHead}> <div className={styles.footerPanelHead}>
<div className={styles.footerToggle}> <label className={styles.footerToggle}>
<span>页脚署名</span> <span>页脚署名</span>
<Switch <Switch
size="small" size="small"
checked={appendFooter} checked={appendFooter}
onChange={setAppendFooter} onChange={setAppendFooter}
/> />
</div> </label>
<p className={styles.footerHint}> <p className={styles.footerHint}>
{appendFooter {appendFooter
? '开启后追加到预览末尾,可自由编辑文案' ? '开启后追加到预览末尾,可自由编辑文案'
@ -368,6 +425,7 @@ function App() {
autoSize={{ minRows: 2, maxRows: 4 }} autoSize={{ minRows: 2, maxRows: 4 }}
placeholder="编辑页脚文案…" placeholder="编辑页脚文案…"
spellCheck={false} spellCheck={false}
aria-label="页脚文案"
/> />
</section> </section>
</div> </div>

View File

@ -1,18 +1,33 @@
import React, { useCallback, useMemo, useRef, useState } from 'react'; import React, {
forwardRef,
useCallback,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { Dropdown, Input, Segmented, Tooltip } from 'antd'; import { Dropdown, Input, Segmented, Tooltip } from 'antd';
import type { MenuProps } from 'antd'; import type { MenuProps } from 'antd';
import type { TextAreaRef } from 'antd/es/input/TextArea'; import type { TextAreaRef } from 'antd/es/input/TextArea';
import { import {
EDITOR_ACTIONS, EDITOR_ACTIONS,
applyEditorAction, applyEditorAction,
handleMarkdownEnter,
handleMarkdownTab,
insertBlockChunk,
type EditorAction, type EditorAction,
} from '../lib/editorActions'; } from '../lib/editorActions';
import type { EditorMode } from '../lib/storage';
import { offsetAtLine, parseToc } from '../lib/toc'; import { offsetAtLine, parseToc } from '../lib/toc';
import styles from '../App.module.scss'; import styles from '../App.module.scss';
const { TextArea } = Input; const { TextArea } = Input;
export type EditorMode = 'markdown' | 'plain'; export type EditorPaneHandle = {
runAction: (action: EditorAction) => void;
runActionById: (id: string) => boolean;
insertAtCursor: (chunk: string) => void;
};
type Props = { type Props = {
content: string; content: string;
@ -24,15 +39,18 @@ type Props = {
charCount: number; charCount: number;
}; };
export default function EditorPane({ const EditorPane = forwardRef<EditorPaneHandle, Props>(function EditorPane(
content, {
onChange, content,
mode, onChange,
onModeChange, mode,
tocOpen, onModeChange,
onTocOpenChange, tocOpen,
charCount, onTocOpenChange,
}: Props) { charCount,
},
ref,
) {
const textareaRef = useRef<TextAreaRef>(null); const textareaRef = useRef<TextAreaRef>(null);
const [activeTocId, setActiveTocId] = useState<string | null>(null); const [activeTocId, setActiveTocId] = useState<string | null>(null);
@ -47,24 +65,63 @@ export default function EditorPane({
if (!el) return; if (!el) return;
el.focus(); el.focus();
el.setSelectionRange(start, end); el.setSelectionRange(start, end);
// Keep caret roughly in view const style = window.getComputedStyle(el);
const lineHeight = 24; const lineHeight =
parseFloat(style.lineHeight) ||
parseFloat(style.fontSize) * 1.7 ||
24;
const before = el.value.slice(0, start); const before = el.value.slice(0, start);
const line = before.split('\n').length - 1; const line = before.split('\n').length - 1;
el.scrollTop = Math.max(0, line * lineHeight - el.clientHeight / 3); el.scrollTop = Math.max(0, line * lineHeight - el.clientHeight / 3);
}); });
}, []); }, []);
const applyResult = useCallback(
(result: { next: string; selectionStart: number; selectionEnd: number }) => {
onChange(result.next);
focusAndSelect(result.selectionStart, result.selectionEnd);
},
[focusAndSelect, onChange],
);
const runAction = useCallback( const runAction = useCallback(
(action: EditorAction) => { (action: EditorAction) => {
const el = getTextArea(); const el = getTextArea();
const start = el?.selectionStart ?? content.length; const start = el?.selectionStart ?? content.length;
const end = el?.selectionEnd ?? content.length; const end = el?.selectionEnd ?? content.length;
const result = applyEditorAction(content, start, end, action); applyResult(applyEditorAction(content, start, end, action));
onChange(result.next);
focusAndSelect(result.selectionStart, result.selectionEnd);
}, },
[content, focusAndSelect, onChange], [applyResult, content],
);
const insertAtCursor = useCallback(
(chunk: string) => {
const el = getTextArea();
const start = el?.selectionStart ?? content.length;
const end = el?.selectionEnd ?? content.length;
applyResult(insertBlockChunk(content, start, end, chunk));
},
[applyResult, content],
);
const runActionById = useCallback(
(id: string) => {
const action = EDITOR_ACTIONS.find((item) => item.id === id);
if (!action) return false;
runAction(action);
return true;
},
[runAction],
);
useImperativeHandle(
ref,
() => ({
runAction,
runActionById,
insertAtCursor,
}),
[runAction, runActionById, insertAtCursor],
); );
const jumpToHeading = useCallback( const jumpToHeading = useCallback(
@ -77,6 +134,33 @@ export default function EditorPane({
[content, focusAndSelect], [content, focusAndSelect],
); );
const onEditorKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (mode !== 'markdown') return;
const el = event.currentTarget;
const start = el.selectionStart;
const end = el.selectionEnd;
if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
const result = handleMarkdownEnter(content, start, end);
if (result) {
event.preventDefault();
applyResult(result);
}
return;
}
if (event.key === 'Tab') {
event.preventDefault();
const result = handleMarkdownTab(content, start, end, event.shiftKey);
if (result) {
applyResult(result);
}
}
},
[applyResult, content, mode],
);
const contextItems: MenuProps['items'] = useMemo(() => { const contextItems: MenuProps['items'] = useMemo(() => {
const groups: Array<{ const groups: Array<{
key: string; key: string;
@ -139,6 +223,8 @@ export default function EditorPane({
type="button" type="button"
className={styles.tocToggle} className={styles.tocToggle}
onClick={() => onTocOpenChange(!tocOpen)} onClick={() => onTocOpenChange(!tocOpen)}
aria-expanded={tocOpen}
aria-label={tocOpen ? '收起目录' : '展开目录'}
> >
目录 {tocOpen ? '◂' : '▸'} 目录 {tocOpen ? '◂' : '▸'}
</button> </button>
@ -162,7 +248,7 @@ export default function EditorPane({
<div className={styles.editorBody}> <div className={styles.editorBody}>
{tocOpen && ( {tocOpen && (
<aside className={styles.tocPanel}> <aside className={styles.tocPanel} aria-label="标题大纲">
<div className={styles.tocTitle}>大纲</div> <div className={styles.tocTitle}>大纲</div>
{toc.length === 0 ? ( {toc.length === 0 ? (
<p className={styles.tocEmpty}>暂无标题,用 # 写一级标题</p> <p className={styles.tocEmpty}>暂无标题,用 # 写一级标题</p>
@ -203,18 +289,20 @@ export default function EditorPane({
className={styles.editor} className={styles.editor}
value={content} value={content}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
onKeyDown={onEditorKeyDown}
placeholder={ placeholder={
isMarkdown isMarkdown
? `在此输入 Markdown… ? `在此输入 Markdown…
右键可插入标题 / 任务 / 表格 / 代码块等 右键插入 · Enter 续列表 · Tab 缩进
参考 MarkText 的源码编辑体验` 快捷键:Ctrl+B 加粗 · Ctrl+I 斜体 · Ctrl+K 链接`
: `普通文本编辑模式 : `普通文本编辑模式
适合自由写作;切换回 MD 后仍可一键转公众号预览` 适合自由写作;切换回 MD 后仍可一键转公众号预览`
} }
autoFocus autoFocus
spellCheck={mode === 'plain'} spellCheck={mode === 'plain'}
aria-label={isMarkdown ? 'Markdown 编辑器' : '普通文本编辑器'}
style={{ height: '100%', resize: 'none' }} style={{ height: '100%', resize: 'none' }}
/> />
</div> </div>
@ -222,4 +310,6 @@ export default function EditorPane({
</div> </div>
</section> </section>
); );
} });
export default EditorPane;

View File

@ -1,3 +0,0 @@
export default {
navigationBarTitleText: '异度星球'
}

View File

@ -1,67 +0,0 @@
import { Component } from "react";
// import Taro from "@tarojs/taro";
// import {
// View,
// Text,
// Image,
// Button,
// Input,
// Editor,
// Textarea,
// } from "@tarojs/components";
import "./index.scss";
// import { AtTabBar } from "taro-ui";
import React, { useCallback, useEffect, useState } from "react";
// import { AtGrid } from "taro-ui";
// import { Swiper, SwiperItem } from "@tarojs/components";
// import { AtCard } from "taro-ui";
// import { AtImagePicker } from "taro-ui";
// import { AtButton } from "taro-ui";
// import { AtSearchBar } from "taro-ui";
// import { Picker } from "@tarojs/components";
// import { AtList, AtListItem } from "taro-ui";
// import { AtNavBar } from "taro-ui";
// import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
// import { AtToast } from "taro-ui";
// import { AtIcon } from "taro-ui";
// 局部改造 (不是全局)
import { Marked } from "marked";
const marked = new Marked([
{
breaks: true, // 是否回车换行
highlight(code, lang) {
// 语法高亮
let val = code;
if (lang) {
val = hljs.highlight(lang, code).value;
} else {
val = hljs.highlightAuto(code).value;
}
return val;
},
},
]);
const OriginMark = (props) => {
const [markText, setmarkText] = useState(null);
useEffect(() => {
if (props.markText) {
setmarkText(props.markText);
}
}, [props.markText]);
return (
<div className="OriginMark">
{!!markText && (
<div
className="OriginMark-mark"
dangerouslySetInnerHTML={{ __html: marked.parse(markText) }}
></div>
)}
</div>
);
};
export default OriginMark;

View File

@ -1,3 +0,0 @@
.OriginMark-mark{
padding: 20px;
}

View File

@ -1,15 +1,6 @@
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import App from './App'; import App from './App';
// "nodemon": "nodemon --watch src --ext tsx,js,json,scss,css --exec \"yarn start\""
const container = document.getElementById('root') as HTMLElement; const container = document.getElementById('root') as HTMLElement;
const root = createRoot(container); const root = createRoot(container);
root.render(<App />); root.render(<App />);
// calling IPC exposed from preload script
window.electron.ipcRenderer.once('ipc-example', (arg) => {
// eslint-disable-next-line no-console
console.log(arg);
});
window.electron.ipcRenderer.sendMessage('ipc-example', ['ping']);

View File

@ -4,8 +4,12 @@ export type EditorAction = {
group: 'heading' | 'block' | 'inline' | 'insert'; group: 'heading' | 'block' | 'inline' | 'insert';
/** If set, wrap selected text (or placeholder) */ /** If set, wrap selected text (or placeholder) */
wrap?: { before: string; after: string; placeholder?: string }; wrap?: { before: string; after: string; placeholder?: string };
/** Heading: prefix current line instead of mid-line wrap */
linePrefix?: string;
/** If set, insert raw markdown at cursor */ /** If set, insert raw markdown at cursor */
insert?: string; insert?: string;
/** After wrap, select this suffix inside `after` (e.g. link URL) */
selectInAfter?: { match: string };
}; };
export const EDITOR_ACTIONS: EditorAction[] = [ export const EDITOR_ACTIONS: EditorAction[] = [
@ -13,24 +17,28 @@ export const EDITOR_ACTIONS: EditorAction[] = [
id: 'h1', id: 'h1',
label: '一级标题', label: '一级标题',
group: 'heading', group: 'heading',
linePrefix: '# ',
wrap: { before: '# ', after: '', placeholder: '标题' }, wrap: { before: '# ', after: '', placeholder: '标题' },
}, },
{ {
id: 'h2', id: 'h2',
label: '二级标题', label: '二级标题',
group: 'heading', group: 'heading',
linePrefix: '## ',
wrap: { before: '## ', after: '', placeholder: '小标题' }, wrap: { before: '## ', after: '', placeholder: '小标题' },
}, },
{ {
id: 'h3', id: 'h3',
label: '三级标题', label: '三级标题',
group: 'heading', group: 'heading',
linePrefix: '### ',
wrap: { before: '### ', after: '', placeholder: '小节标题' }, wrap: { before: '### ', after: '', placeholder: '小节标题' },
}, },
{ {
id: 'h4', id: 'h4',
label: '四级标题', label: '四级标题',
group: 'heading', group: 'heading',
linePrefix: '#### ',
wrap: { before: '#### ', after: '', placeholder: '四级标题' }, wrap: { before: '#### ', after: '', placeholder: '四级标题' },
}, },
{ {
@ -66,55 +74,56 @@ export const EDITOR_ACTIONS: EditorAction[] = [
after: '](https://example.com)', after: '](https://example.com)',
placeholder: '链接文案', placeholder: '链接文案',
}, },
selectInAfter: { match: 'https://example.com' },
}, },
{ {
id: 'ul', id: 'ul',
label: '无序列表', label: '无序列表',
group: 'block', group: 'block',
insert: '\n- 列表项\n- 列表项\n', insert: '- 列表项\n- 列表项\n',
}, },
{ {
id: 'ol', id: 'ol',
label: '有序列表', label: '有序列表',
group: 'block', group: 'block',
insert: '\n1. 第一项\n2. 第二项\n', insert: '1. 第一项\n2. 第二项\n',
}, },
{ {
id: 'task', id: 'task',
label: '任务列表', label: '任务列表',
group: 'block', group: 'block',
insert: '\n- [ ] 待办事项\n- [x] 已完成\n', insert: '- [ ] 待办事项\n- [x] 已完成\n',
}, },
{ {
id: 'quote', id: 'quote',
label: '引用', label: '引用',
group: 'block', group: 'block',
insert: '\n> 这里是一句引用\n', insert: '> 这里是一句引用\n',
}, },
{ {
id: 'hr', id: 'hr',
label: '分隔线', label: '分隔线',
group: 'block', group: 'block',
insert: '\n---\n', insert: '---\n',
}, },
{ {
id: 'table', id: 'table',
label: '表格', label: '表格',
group: 'insert', group: 'insert',
insert: insert:
'\n| 列1 | 列2 | 列3 |\n| --- | --- | --- |\n| A | B | C |\n| D | E | F |\n', '| 列1 | 列2 | 列3 |\n| --- | --- | --- |\n| A | B | C |\n| D | E | F |\n',
}, },
{ {
id: 'codeblock', id: 'codeblock',
label: '代码块', label: '代码块',
group: 'insert', group: 'insert',
insert: '\n```js\nconsole.log("hello")\n```\n', insert: '```js\nconsole.log("hello")\n```\n',
}, },
{ {
id: 'image', id: 'image',
label: '图片', label: '图片',
group: 'insert', group: 'insert',
insert: '\n![图片说明](https://example.com/image.png)\n', insert: '![图片说明](https://example.com/image.png)\n',
}, },
]; ];
@ -124,20 +133,100 @@ export type ApplyResult = {
selectionEnd: number; selectionEnd: number;
}; };
function lineBounds(content: string, offset: number): { start: number; end: number } {
const start = content.lastIndexOf('\n', offset - 1) + 1;
const nextNl = content.indexOf('\n', offset);
const end = nextNl === -1 ? content.length : nextNl;
return { start, end };
}
const HEADING_PREFIX_RE = /^(#{1,6})\s+/;
function applyLinePrefix(
content: string,
selectionStart: number,
selectionEnd: number,
prefix: string,
placeholder: string,
): ApplyResult {
const { start, end } = lineBounds(content, selectionStart);
const line = content.slice(start, end);
const stripped = line.replace(HEADING_PREFIX_RE, '');
const body =
selectionStart !== selectionEnd
? content.slice(selectionStart, selectionEnd)
: stripped.trim().length > 0
? stripped
: placeholder;
const nextLine = `${prefix}${body}`;
const next = content.slice(0, start) + nextLine + content.slice(end);
const selStart = start + prefix.length;
return {
next,
selectionStart: selStart,
selectionEnd: selStart + body.length,
};
}
/** Ensure block inserts sit on their own line(s). */
export function insertBlockChunk(
content: string,
selectionStart: number,
selectionEnd: number,
chunk: string,
): ApplyResult {
const before = content.slice(0, selectionStart);
const after = content.slice(selectionEnd);
let prefix = '';
let suffix = '';
if (before.length > 0 && !before.endsWith('\n')) {
prefix = '\n';
}
if (after.length > 0 && !chunk.endsWith('\n') && !after.startsWith('\n')) {
suffix = '\n';
}
const inserted = `${prefix}${chunk}${suffix}`;
const next = before + inserted + after;
const cursor = before.length + inserted.length;
return { next, selectionStart: cursor, selectionEnd: cursor };
}
export function applyEditorAction( export function applyEditorAction(
content: string, content: string,
selectionStart: number, selectionStart: number,
selectionEnd: number, selectionEnd: number,
action: EditorAction, action: EditorAction,
): ApplyResult { ): ApplyResult {
const selected = content.slice(selectionStart, selectionEnd); if (action.linePrefix) {
return applyLinePrefix(
content,
selectionStart,
selectionEnd,
action.linePrefix,
action.wrap?.placeholder ?? '标题',
);
}
if (action.wrap) { if (action.wrap) {
const { before, after, placeholder = '' } = action.wrap; const { before, after, placeholder = '' } = action.wrap;
const selected = content.slice(selectionStart, selectionEnd);
const inner = selected || placeholder; const inner = selected || placeholder;
const inserted = `${before}${inner}${after}`; const inserted = `${before}${inner}${after}`;
const next = const next =
content.slice(0, selectionStart) + inserted + content.slice(selectionEnd); content.slice(0, selectionStart) + inserted + content.slice(selectionEnd);
if (action.selectInAfter?.match) {
const url = action.selectInAfter.match;
const urlOffset = inserted.lastIndexOf(url);
if (urlOffset >= 0) {
return {
next,
selectionStart: selectionStart + urlOffset,
selectionEnd: selectionStart + urlOffset + url.length,
};
}
}
if (selected) { if (selected) {
return { return {
next, next,
@ -153,8 +242,106 @@ export function applyEditorAction(
} }
const chunk = action.insert ?? ''; const chunk = action.insert ?? '';
const next = if (!chunk) {
content.slice(0, selectionStart) + chunk + content.slice(selectionEnd); return {
const cursor = selectionStart + chunk.length; next: content,
return { next, selectionStart: cursor, selectionEnd: cursor }; selectionStart,
selectionEnd,
};
}
return insertBlockChunk(content, selectionStart, selectionEnd, chunk);
}
/** Match list / task / quote line prefixes for Enter / Tab handling */
export const LIST_LINE_RE =
/^(\s*)([-*+]|\d+\.)(\s+)(?:(\[[ xX]\])(\s+))?(.*)$/;
export const QUOTE_LINE_RE = /^(\s*)>(\s?)(.*)$/;
export function handleMarkdownEnter(
content: string,
selectionStart: number,
selectionEnd: number,
): ApplyResult | null {
if (selectionStart !== selectionEnd) return null;
const { start, end } = lineBounds(content, selectionStart);
const line = content.slice(start, end);
const listMatch = LIST_LINE_RE.exec(line);
if (listMatch) {
const [, indent, marker, space, checkbox, boxSpace = '', rest] = listMatch;
const isEmptyItem = rest.trim().length === 0;
if (isEmptyItem) {
// Exit list: clear marker on current line
const next = content.slice(0, start) + indent + content.slice(end);
const cursor = start + indent.length;
return { next, selectionStart: cursor, selectionEnd: cursor };
}
let nextMarker = marker;
const ol = /^(\d+)\.$/.exec(marker);
if (ol) {
nextMarker = `${Number(ol[1]) + 1}.`;
}
const checkboxPart = checkbox ? `[ ]${boxSpace || ' '}` : '';
const continuation = `\n${indent}${nextMarker}${space}${checkboxPart}`;
const next =
content.slice(0, selectionStart) +
continuation +
content.slice(selectionEnd);
const cursor = selectionStart + continuation.length;
return { next, selectionStart: cursor, selectionEnd: cursor };
}
const quoteMatch = QUOTE_LINE_RE.exec(line);
if (quoteMatch) {
const [, indent, space, rest] = quoteMatch;
if (rest.trim().length === 0) {
const next = content.slice(0, start) + indent + content.slice(end);
const cursor = start + indent.length;
return { next, selectionStart: cursor, selectionEnd: cursor };
}
const continuation = `\n${indent}>${space || ' '}`;
const next =
content.slice(0, selectionStart) +
continuation +
content.slice(selectionEnd);
const cursor = selectionStart + continuation.length;
return { next, selectionStart: cursor, selectionEnd: cursor };
}
return null;
}
export function handleMarkdownTab(
content: string,
selectionStart: number,
selectionEnd: number,
shift: boolean,
): ApplyResult | null {
const { start, end } = lineBounds(content, selectionStart);
const line = content.slice(start, end);
if (shift) {
if (!line.startsWith(' ') && !line.startsWith('\t')) {
return null;
}
const stripped = line.startsWith('\t')
? line.slice(1)
: line.slice(2);
const next = content.slice(0, start) + stripped + content.slice(end);
const delta = line.length - stripped.length;
return {
next,
selectionStart: Math.max(start, selectionStart - delta),
selectionEnd: Math.max(start, selectionEnd - delta),
};
}
const indented = ` ${line}`;
const next = content.slice(0, start) + indented + content.slice(end);
return {
next,
selectionStart: selectionStart + 2,
selectionEnd: selectionEnd + 2,
};
} }

View File

@ -31,15 +31,7 @@ function cleanUrl(href: string): string | null {
function isTaskItem(theme: EmojiTheme, value: string): boolean { function isTaskItem(theme: EmojiTheme, value: string): boolean {
return ( return (
value.includes(`${theme.listSymbol}${theme.taskUnchecked}`) || value.includes(`${theme.listSymbol}${theme.taskUnchecked}`) ||
value.includes(`${theme.listSymbol}${theme.taskChecked}`) || value.includes(`${theme.listSymbol}${theme.taskChecked}`)
value.includes('🔸⬜') ||
value.includes('🔸✅') ||
value.includes('▪️◻') ||
value.includes('▪️☑️') ||
value.includes('•○') ||
value.includes('•✓') ||
value.includes('👉▢') ||
value.includes('👉✔')
); );
} }
@ -63,19 +55,22 @@ function createRenderer(theme: EmojiTheme): Renderer {
.map((item) => item.trim()) .map((item) => item.trim())
.filter((item) => item.length > 0); .filter((item) => item.length > 0);
const topped = texts.filter((item) => item.includes(listSymbol)); let orderedIndex = 0;
return texts return texts
.map((value) => { .map((value) => {
const task = isTaskItem(theme, value); const task = isTaskItem(theme, value);
if (value.includes(listSymbol)) { if (value.includes(listSymbol)) {
const prefix = let prefix: string;
type === 'ol' if (type === 'ol') {
? `${theme.orderedNumbers[topped.indexOf(value)] ?? theme.fallbackOrdered} ` prefix = `${theme.orderedNumbers[orderedIndex] ?? `${orderedIndex + 1}.`} `;
: task orderedIndex += 1;
? '' } else if (task) {
: listSymbol; prefix = '';
} else {
prefix = listSymbol;
}
return `<div>${prefix}${value.replace(listSymbol, '')}</div>`; return `<div>${prefix}${value.replace(listSymbol, '')}</div>`;
} }
@ -112,9 +107,17 @@ function createRenderer(theme: EmojiTheme): Renderer {
renderer.del = (text) => theme.del(text); renderer.del = (text) => theme.del(text);
renderer.blockquote = (quote) => { renderer.blockquote = (quote) => {
const match = /<div>(.*?)<\/div>/.exec(quote); const lines = quote
const content = match ? match[1] : quote.replace(/<\/?div>/g, ''); .replace(/<\/?div>/g, '\n')
return theme.blockquote(content); .replace(/<br\s*\/?>/gi, '\n')
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
if (lines.length === 0) {
return theme.blockquote('');
}
return lines.map((line) => theme.blockquote(line)).join('');
}; };
// Plain-text tables for WeChat / IM paste (HTML borders do not survive copy) // Plain-text tables for WeChat / IM paste (HTML borders do not survive copy)
@ -142,17 +145,12 @@ function createRenderer(theme: EmojiTheme): Renderer {
return renderer; return renderer;
} }
const markedCache = new Map<ThemeId, Marked>();
function getMarked(themeId: ThemeId): Marked { function getMarked(themeId: ThemeId): Marked {
// Rebuild each call so table/theme helper updates always apply return new Marked({
const instance = new Marked({
breaks: true, breaks: true,
gfm: true, gfm: true,
renderer: createRenderer(resolveTheme(themeId)), renderer: createRenderer(resolveTheme(themeId)),
}); });
markedCache.set(themeId, instance);
return instance;
} }
export const DEFAULT_FOOTER_TEXT = `➖➖➖➖➖ export const DEFAULT_FOOTER_TEXT = `➖➖➖➖➖
@ -184,7 +182,7 @@ export function renderEmojiMarkdown(
const themeId = options?.themeId ?? DEFAULT_THEME_ID; const themeId = options?.themeId ?? DEFAULT_THEME_ID;
const bodyHtml = getMarked(themeId).parse(source) as string; const bodyHtml = getMarked(themeId).parse(source) as string;
if (appendFooter && source.length >= 10 && footerText.trim()) { if (appendFooter && footerText.trim()) {
return bodyHtml + formatFooterHtml(footerText); return bodyHtml + formatFooterHtml(footerText);
} }
return bodyHtml; return bodyHtml;

View File

@ -130,9 +130,24 @@ function buildFullwidthBox(matrix: string[][], widths: number[]): string[] {
return lines; return lines;
} }
/** Pipe style: fullwidth cells, divider only under header (no outer top/bottom box) */
function buildPipeRows(matrix: string[][], widths: number[]): string[] { function buildPipeRows(matrix: string[][], widths: number[]): string[] {
// Also fullwidth for Theme B — same alignment guarantee const renderRow = (row: string[]) =>
return buildFullwidthBox(matrix, widths); FW_V +
row.map((cell, col) => padEndFullwidth(cell, widths[col])).join(FW_V) +
FW_V;
const divider =
FW_V + widths.map((w) => fwRule(w)).join(FW_V) + FW_V;
const lines: string[] = [];
matrix.forEach((row, index) => {
lines.push(renderRow(row));
if (index === 0 && matrix.length > 1) {
lines.push(divider);
}
});
return lines;
} }
function buildDotsRows(matrix: string[][], widths: number[]): string[] { function buildDotsRows(matrix: string[][], widths: number[]): string[] {
@ -180,8 +195,9 @@ export function formatPlainTable(
let body: string[]; let body: string[];
if (style === 'dots') { if (style === 'dots') {
body = buildDotsRows(matrix, widths); body = buildDotsRows(matrix, widths);
} else if (style === 'pipe') {
body = buildPipeRows(matrix, widths);
} else { } else {
// box + pipe → same fullwidth grid (Theme A/B/D)
body = buildFullwidthBox(matrix, widths); body = buildFullwidthBox(matrix, widths);
} }

View File

@ -39,7 +39,7 @@ export function loadDraft(): DraftState {
? parsed.themeId ? parsed.themeId
: DEFAULT_THEME_ID; : DEFAULT_THEME_ID;
const content = const content =
typeof parsed.content === 'string' && parsed.content.length > 0 typeof parsed.content === 'string'
? parsed.content ? parsed.content
: DEFAULT_TEMPLATE_CONTENT; : DEFAULT_TEMPLATE_CONTENT;
return { return {

View File

@ -67,7 +67,7 @@ export const SHOWCASE_TEMPLATE: TemplateItem = {
## 图片 ## 图片
![示例图片](https://via.placeholder.com/300x160.png?text=emoji) ![示例图片](https://example.com/cover.png)
## 代码块 ## 代码块
@ -164,29 +164,29 @@ export const TEMPLATES: TemplateItem[] = [
export const DEFAULT_TEMPLATE_CONTENT = SHOWCASE_TEMPLATE.content; export const DEFAULT_TEMPLATE_CONTENT = SHOWCASE_TEMPLATE.content;
export const SNIPPETS: SnippetItem[] = [ export const SNIPPETS: SnippetItem[] = [
{ id: 'h1', label: 'H1', insert: '\n# 标题\n' }, { id: 'h1', label: 'H1', insert: '# 标题\n' },
{ id: 'h2', label: 'H2', insert: '\n## 小标题\n' }, { id: 'h2', label: 'H2', insert: '## 小标题\n' },
{ id: 'ul', label: '列表', insert: '\n- 第一项\n- 第二项\n' }, { id: 'ul', label: '列表', insert: '- 第一项\n- 第二项\n' },
{ {
id: 'task', id: 'task',
label: '任务', label: '任务',
insert: '\n- [ ] 待办事项\n- [x] 已完成\n', insert: '- [ ] 待办事项\n- [x] 已完成\n',
}, },
{ id: 'hr', label: '分隔', insert: '\n---\n' }, { id: 'hr', label: '分隔', insert: '---\n' },
{ {
id: 'link', id: 'link',
label: '链接', label: '链接',
insert: '\n[链接文案](https://example.com)\n', insert: '[链接文案](https://example.com)\n',
}, },
{ id: 'quote', label: '引用', insert: '\n> 这里是一句引用\n' }, { id: 'quote', label: '引用', insert: '> 这里是一句引用\n' },
{ {
id: 'code', id: 'code',
label: '代码', label: '代码',
insert: '\n`行内代码`\n\n```js\nconsole.log(1)\n```\n', insert: '`行内代码`\n\n```js\nconsole.log(1)\n```\n',
}, },
{ {
id: 'table', id: 'table',
label: '表格', label: '表格',
insert: '\n| 列1 | 列2 |\n| --- | --- |\n| A | B |\n', insert: '| 列1 | 列2 |\n| --- | --- |\n| A | B |\n',
}, },
]; ];

View File

@ -87,9 +87,9 @@ export const THEME_A: EmojiTheme = {
taskChecked: '✅', taskChecked: '✅',
taskUnchecked: '⬜', taskUnchecked: '⬜',
heading1: frameTitleA, heading1: frameTitleA,
heading2: (text) => `<div>📝${text}</div>\n`, heading2: (text) => `<div>📝 ${text}</div>\n`,
heading3: (text) => `<div>📝${text}</div>\n`, heading3: (text) => `<div>📎 ${text}</div>\n`,
heading4: (text) => `<div>▪️${text}</div>\n`, heading4: (text) => `<div>▪️ ${text}</div>\n`,
hr: '➖➖➖➖➖\n', hr: '➖➖➖➖➖\n',
codespan: (text) => `『${text}』`, codespan: (text) => `『${text}』`,
codeblock: (code, language) => codeblock: (code, language) =>