diff --git a/README.md b/README.md index 9dc621d..ad7d6e7 100644 --- a/README.md +++ b/README.md @@ -16,29 +16,30 @@ | 能力 | 说明 | |------|------| | Markdown 实时预览 | 左侧编辑、右侧预览,基于 `marked` 自定义 Renderer | +| 四套主题 A–D | 经典 / 青简 / 精简 / 聚焦,下拉切换 | | Emoji 装饰排版 | 标题边框、列表符号、任务勾选、引用、分隔线等用 Unicode/Emoji 呈现 | -| 一键复制 | 复制为纯文本(表格用字符边框,粘贴到微信/IM 仍可见结构) | -| 草稿自动保存 | 本地 `localStorage` 持久化正文与页脚开关 | -| 模板与片段 | 内置公众号短文/任务清单等模板,工具栏可插入标题、列表等片段 | +| 一键复制 | 复制为纯文本(表格用全角字符网格,粘贴到微信/IM 仍可见结构) | +| 草稿自动保存 | 本地 `localStorage`(键:`emojitool.draft`) | +| 模板与片段 | 内置语法全览等模板;工具栏片段插入到**光标处** | | 页脚开关 | 可关闭/编辑自动追加的署名 | | 左侧目录 | 解析 `#` 标题大纲,点击跳转 | -| 编辑模式 | MD 源码 / 普通编辑可切换(参考 [MarkText](https://github.com/marktext/marktext) 源码体验) | -| 右键插入 | MD 模式下右键插入标题、任务、表格、代码块等 | -| 外链菜单 | 「公众号: 异度世界」「mdemoji.com」 | +| 编辑模式 | MD 源码 / 普通编辑可切换 | +| 右键与快捷键 | MD 模式:右键插入;`Ctrl+B` 加粗、`Ctrl+I` 斜体、`Ctrl+K` 链接;`Ctrl+Enter` 复制;`Ctrl+S` 保存 | +| 外链菜单 | 异度世界 / mdemoji.com / 仓库 | -### Markdown 装饰规则(摘要) +### Markdown 装饰规则(摘要 · 主题 A) - **H1**:`╭──╮` 边框 + `📢` 标题 -- **H2 / H3**:前缀 `📝` +- **H2**:前缀 `📝`;**H3**:`📎`;**H4**:`▪️` - **无序列表**:`🔸`,嵌套用 `┊` - **有序列表**:`1️⃣` … `🔟` - **任务列表**:`✅` / `⬜` - **行内代码**:`『…』` -- **引用**:`└─⚡` +- **引用**:`└─⚡`(多行各自成行) - **分隔线**:`➖➖➖➖➖` - **链接**:`🔗文案` + URL -- **图片**:固定宽度约 `300px` -- **表格**:表头标注 `📊 表格 📊` +- **图片**:纯文本 `🖼 说明:url` +- **表格**:全角字符网格(Theme B 为 pipe 风格) ## 技术栈 @@ -58,36 +59,31 @@ src/ │ └── util.ts ├── renderer/ # 渲染进程 │ ├── App.tsx # 布局与交互 -│ ├── App.module.scss # Ink & Leaf 视觉 +│ ├── App.module.scss │ ├── index.ejs +│ ├── components/ +│ │ └── EditorPane.tsx │ └── lib/ -│ ├── emojiMarkdown.ts # Markdown → Emoji 纯文本 +│ ├── emojiMarkdown.ts │ ├── themes.ts -│ ├── toc.ts # 标题目录 -│ ├── editorActions.ts # 右键插入动作 +│ ├── plainTable.ts +│ ├── toc.ts +│ ├── editorActions.ts │ ├── storage.ts │ └── templates.ts -│ └── components/ -│ └── EditorPane.tsx # 左侧目录 + 编辑器 └── __tests__/ ``` -业务逻辑:渲染规则在 `lib/emojiMarkdown.ts`,交互在 `App.tsx`。 - ## 开发 环境要求:Node.js ≥ 14,npm ≥ 7。 ```bash -# 建议使用主开发分支 git checkout greenbook - npm install npm start ``` -常用脚本: - | 命令 | 说明 | |------|------| | `npm start` | 启动开发环境 | @@ -100,15 +96,15 @@ npm start | 分支 | 说明 | |------|------| -| **`greenbook`** | 当前最新业务分支,含 emoji 编辑器主体功能 | +| **`greenbook`** | 当前最新业务分支 | | `main` | 接近 ERB 初始脚手架,明显落后于 `greenbook` | | `feature/emoji` | 历史旁支,已被 `greenbook` 覆盖 | ## 已知说明 - 包名 / `productName` 已统一为 **emojitool** / **emojiTool**。 -- 暂无云同步、多窗口;草稿保存在本机 `localStorage`(键:`emojitool.draft`)。 -- 提供 A–D 四套纯文本主题,复制优先 `innerText`,表格为全角字符网格。 +- 暂无云同步、多窗口;草稿保存在本机。 +- 复制优先 `innerText`,表格为全角字符网格(box / pipe / dots)。 ## License diff --git a/src/__tests__/editorActions.test.ts b/src/__tests__/editorActions.test.ts new file mode 100644 index 0000000..3297cb7 --- /dev/null +++ b/src/__tests__/editorActions.test.ts @@ -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'); + }); +}); diff --git a/src/main/main.ts b/src/main/main.ts index c37cde1..9557baf 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -9,7 +9,7 @@ * `./src/main.js` using webpack. This gives us some performance wins. */ import path from 'path'; -import { app, BrowserWindow, shell, ipcMain } from 'electron'; +import { app, BrowserWindow, shell } from 'electron'; import { autoUpdater } from 'electron-updater'; import log from 'electron-log'; import MenuBuilder from './menu'; @@ -31,12 +31,6 @@ class AppUpdater { 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') { const sourceMapSupport = require('source-map-support'); sourceMapSupport.install(); diff --git a/src/main/menu.ts b/src/main/menu.ts index f6279c6..35a3f2c 100644 --- a/src/main/menu.ts +++ b/src/main/menu.ts @@ -37,13 +37,22 @@ export default class MenuBuilder { return menu; } - setupDevelopmentEnvironment(): void { - this.mainWindow.webContents.on('context-menu', (_, props) => { - const { x, y } = props; + sendCommand(command: string): void { + this.mainWindow.webContents.send('menu-command', command); + } + 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([ { - label: 'Inspect element', + label: '检查元素', click: () => { this.mainWindow.webContents.inspectElement(x, y); }, @@ -61,7 +70,7 @@ export default class MenuBuilder { selector: 'orderFrontStandardAboutPanel:', }, { type: 'separator' }, - { label: 'Services', submenu: [] }, + { label: '服务', submenu: [] }, { type: 'separator' }, { label: '隐藏 emojiTool', @@ -85,40 +94,55 @@ export default class MenuBuilder { ], }; const subMenuEdit: DarwinMenuItemConstructorOptions = { - label: 'Edit', + label: '编辑', submenu: [ - { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, - { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, + { label: '撤销', accelerator: 'Command+Z', selector: 'undo:' }, + { label: '重做', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { type: 'separator' }, - { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, - { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, - { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, + { label: '剪切', accelerator: 'Command+X', selector: 'cut:' }, + { label: '复制', accelerator: 'Command+C', selector: 'copy:' }, + { label: '粘贴', accelerator: 'Command+V', selector: 'paste:' }, { - label: 'Select All', + label: '全选', accelerator: 'Command+A', 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 = { - label: 'View', + label: '视图', submenu: [ { - label: 'Reload', + label: '重新加载', accelerator: 'Command+R', click: () => { this.mainWindow.webContents.reload(); }, }, { - label: 'Toggle Full Screen', + label: '全屏', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); }, }, { - label: 'Toggle Developer Tools', + label: '开发者工具', accelerator: 'Alt+Command+I', click: () => { this.mainWindow.webContents.toggleDevTools(); @@ -127,10 +151,10 @@ export default class MenuBuilder { ], }; const subMenuViewProd: MenuItemConstructorOptions = { - label: 'View', + label: '视图', submenu: [ { - label: 'Toggle Full Screen', + label: '全屏', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); @@ -139,16 +163,16 @@ export default class MenuBuilder { ], }; const subMenuWindow: DarwinMenuItemConstructorOptions = { - label: 'Window', + label: '窗口', submenu: [ { - label: 'Minimize', + label: '最小化', accelerator: 'Command+M', selector: 'performMiniaturize:', }, - { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, + { label: '关闭', accelerator: 'Command+W', selector: 'performClose:' }, { type: 'separator' }, - { label: 'Bring All to Front', selector: 'arrangeInFront:' }, + { label: '前置全部窗口', selector: 'arrangeInFront:' }, ], }; const subMenuHelp: MenuItemConstructorOptions = { @@ -166,6 +190,12 @@ export default class MenuBuilder { 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]; } - buildDefaultTemplate() { - const templateDefault = [ - // { - // label: '&File', - // submenu: [ - // { - // 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'); - // }, - // }, - // ], - // }, + buildDefaultTemplate(): MenuItemConstructorOptions[] { + const isDev = + process.env.NODE_ENV === 'development' || + process.env.DEBUG_PROD === 'true'; + + const viewSubmenu: MenuItemConstructorOptions[] = [ { - 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: [ { label: '公众号: 异度世界', @@ -284,10 +300,14 @@ export default class MenuBuilder { shell.openExternal('https://mdemoji.com'); }, }, + { + label: '仓库 emojiTool', + click() { + shell.openExternal('https://git.nomadro.cn/hackrobot/emojiTool'); + }, + }, ], }, ]; - - return templateDefault; } } diff --git a/src/main/preload.ts b/src/main/preload.ts index 9133a79..3bb09b1 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -1,25 +1,21 @@ -// Disable no-unused-vars, broken for spread args /* eslint no-unused-vars: off */ import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron'; -export type Channels = 'ipc-example'; +export type MenuCommand = 'copy-preview' | 'save-draft' | 'clear-content'; const electronHandler = { ipcRenderer: { - sendMessage(channel: Channels, ...args: unknown[]) { - ipcRenderer.send(channel, ...args); - }, - on(channel: Channels, func: (...args: unknown[]) => void) { - const subscription = (_event: IpcRendererEvent, ...args: unknown[]) => - func(...args); - ipcRenderer.on(channel, subscription); - - return () => { - ipcRenderer.removeListener(channel, subscription); + onMenuCommand(callback: (command: MenuCommand) => void) { + const subscription = ( + _event: IpcRendererEvent, + command: MenuCommand, + ) => { + callback(command); + }; + ipcRenderer.on('menu-command', subscription); + return () => { + ipcRenderer.removeListener('menu-command', subscription); }; - }, - once(channel: Channels, func: (...args: unknown[]) => void) { - ipcRenderer.once(channel, (_event, ...args) => func(...args)); }, }, }; diff --git a/src/renderer/App.module.scss b/src/renderer/App.module.scss index 1367543..b39cce9 100644 --- a/src/renderer/App.module.scss +++ b/src/renderer/App.module.scss @@ -136,6 +136,8 @@ color: var(--muted); font-size: 12px; flex-shrink: 0; + cursor: pointer; + margin: 0; } .footerPanel { @@ -210,17 +212,32 @@ transition: background 160ms ease, border-color 160ms ease, - transform 160ms ease; + transform 160ms ease, + opacity 160ms ease; - &:hover { + &:hover:not(:disabled) { background: #fff; border-color: rgba(13, 148, 136, 0.45); transform: translateY(-1px); } - &:active { + &:active:not(:disabled) { 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 { @@ -276,9 +293,8 @@ .paneTitle { font-size: 13px; - font-weight: 650; - letter-spacing: 0.04em; - text-transform: uppercase; + font-weight: 600; + letter-spacing: 0.02em; color: var(--accent-deep); } @@ -302,6 +318,11 @@ color: var(--accent-deep); border-color: rgba(13, 148, 136, 0.4); } + + &:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + } } .editorPane { @@ -326,9 +347,8 @@ .tocTitle { font-size: 11px; - font-weight: 650; - letter-spacing: 0.08em; - text-transform: uppercase; + font-weight: 600; + letter-spacing: 0.04em; color: var(--muted); padding: 0 6px 8px; } @@ -451,6 +471,14 @@ user-select: text; animation: fadeIn 220ms ease; + > :global(div) { + margin: 0 0 0.65em; + } + + > :global(div:last-child) { + margin-bottom: 0; + } + :global(img) { max-width: 100%; height: auto; @@ -528,7 +556,7 @@ .emptyTitle { margin: 0 0 8px; font-size: 18px; - font-weight: 650; + font-weight: 600; color: var(--ink); } diff --git a/src/renderer/App.scss b/src/renderer/App.scss deleted file mode 100644 index fc1e835..0000000 --- a/src/renderer/App.scss +++ /dev/null @@ -1 +0,0 @@ -/* Legacy global styles replaced by App.module.scss */ diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 8b3630f..7e4b5a1 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -24,16 +24,30 @@ import { } from './lib/emojiMarkdown'; import { loadDraft, saveDraft, type EditorMode } from './lib/storage'; import { DEFAULT_TEMPLATE_CONTENT, SNIPPETS, TEMPLATES } from './lib/templates'; -import { EDITOR_ACTIONS, applyEditorAction } from './lib/editorActions'; -import EditorPane from './components/EditorPane'; +import EditorPane, { type EditorPaneHandle } from './components/EditorPane'; import styles from './App.module.scss'; const { TextArea } = Input; const SAVE_DEBOUNCE_MS = 400; +const PREVIEW_DEBOUNCE_MS = 120; + +/** Snippet bar id → editor action id */ +const SNIPPET_ACTION_IDS: Record = { + 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() { const previewRef = useRef(null); + const editorRef = useRef(null); const initial = useMemo(() => loadDraft(), []); const [content, setContent] = useState(initial.content); @@ -43,25 +57,35 @@ function App() { const [editorMode, setEditorMode] = useState(initial.editorMode); const [tocOpen, setTocOpen] = useState(initial.tocOpen); const [savedHint, setSavedHint] = useState(false); + const [previewHtml, setPreviewHtml] = useState(() => + renderEmojiMarkdown(initial.content, { + appendFooter: initial.appendFooter, + footerText: initial.footerText, + themeId: initial.themeId, + }), + ); const activeTheme = useMemo( () => THEME_LIST.find((t) => t.id === themeId) ?? THEME_LIST[0], [themeId], ); - const previewHtml = useMemo( - () => - renderEmojiMarkdown(content, { - appendFooter, - footerText, - themeId, - }), - [content, appendFooter, footerText, themeId], - ); - const charCount = content.length; 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(() => { const timer = window.setTimeout(() => { saveDraft({ @@ -127,28 +151,38 @@ function App() { const applyTemplate = useCallback( (templateContent: string, label?: string) => { - setContent(templateContent); - message.success(label ? `已填入「${label}」` : '已填入模板'); + const doApply = () => { + 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( - (snippet: string) => { - const action = EDITOR_ACTIONS.find((item) => item.insert === snippet); - if (action) { - const result = applyEditorAction( - content, - content.length, - content.length, - action, - ); - setContent(result.next); + (snippetId: string, insert: string) => { + if (editorMode === 'plain') { + message.info('请先切换到 MD 模式再插入片段'); 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(() => { @@ -172,24 +206,34 @@ function App() { if (event.key === 'Enter') { event.preventDefault(); copyPreview(); - } else if (event.key.toLowerCase() === 's') { + return; + } + if (event.key.toLowerCase() === 's') { event.preventDefault(); persistNow(); - } else if (event.key.toLowerCase() === 'b' && editorMode === 'markdown') { - // 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); + return; } + 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); 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) => ({ key: theme.id, @@ -208,6 +252,12 @@ function App() { onClick: () => applyTemplate(item.content, item.label), })); + const hintText = savedHint + ? '已自动保存' + : editorMode === 'markdown' + ? `${activeTheme.name} · Enter 续列表 · Tab 缩进 · Ctrl+B/I/K` + : `${activeTheme.name} · 普通模式(片段已禁用)`; + return (

emojiTool

- Markdown → 公众号友好纯文本 · nomadro.com + Markdown → 公众号友好纯文本 · mdemoji.com

@@ -276,27 +326,31 @@ function App() { -
+
插入 {SNIPPETS.map((snippet) => ( ))} - - {savedHint - ? '已自动保存' - : `${activeTheme.name} · 右键可插入样式`} + + {hintText}
) : (

开始写一篇

- 左侧可切换 MD / 普通编辑,右键插入任务、表格等。 + {editorMode === 'markdown' + ? '左侧用 Markdown 写作,右键可插入标题、任务、表格等。' + : '当前为普通编辑模式;切换回 MD 后可用右键与快捷键。'}
目录可跳转到标题;右侧即时预览主题排版。

@@ -338,14 +395,14 @@ function App() { }`} >
-
+
+

{appendFooter ? '开启后追加到预览末尾,可自由编辑文案' @@ -368,6 +425,7 @@ function App() { autoSize={{ minRows: 2, maxRows: 4 }} placeholder="编辑页脚文案…" spellCheck={false} + aria-label="页脚文案" />

diff --git a/src/renderer/components/EditorPane.tsx b/src/renderer/components/EditorPane.tsx index 2a40f62..4134ebe 100644 --- a/src/renderer/components/EditorPane.tsx +++ b/src/renderer/components/EditorPane.tsx @@ -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 type { MenuProps } from 'antd'; import type { TextAreaRef } from 'antd/es/input/TextArea'; import { EDITOR_ACTIONS, applyEditorAction, + handleMarkdownEnter, + handleMarkdownTab, + insertBlockChunk, type EditorAction, } from '../lib/editorActions'; +import type { EditorMode } from '../lib/storage'; import { offsetAtLine, parseToc } from '../lib/toc'; import styles from '../App.module.scss'; 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 = { content: string; @@ -24,15 +39,18 @@ type Props = { charCount: number; }; -export default function EditorPane({ - content, - onChange, - mode, - onModeChange, - tocOpen, - onTocOpenChange, - charCount, -}: Props) { +const EditorPane = forwardRef(function EditorPane( + { + content, + onChange, + mode, + onModeChange, + tocOpen, + onTocOpenChange, + charCount, + }, + ref, +) { const textareaRef = useRef(null); const [activeTocId, setActiveTocId] = useState(null); @@ -47,24 +65,63 @@ export default function EditorPane({ if (!el) return; el.focus(); el.setSelectionRange(start, end); - // Keep caret roughly in view - const lineHeight = 24; + const style = window.getComputedStyle(el); + const lineHeight = + parseFloat(style.lineHeight) || + parseFloat(style.fontSize) * 1.7 || + 24; const before = el.value.slice(0, start); const line = before.split('\n').length - 1; 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( (action: EditorAction) => { const el = getTextArea(); const start = el?.selectionStart ?? content.length; const end = el?.selectionEnd ?? content.length; - const result = applyEditorAction(content, start, end, action); - onChange(result.next); - focusAndSelect(result.selectionStart, result.selectionEnd); + applyResult(applyEditorAction(content, start, end, action)); }, - [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( @@ -77,6 +134,33 @@ export default function EditorPane({ [content, focusAndSelect], ); + const onEditorKeyDown = useCallback( + (event: React.KeyboardEvent) => { + 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 groups: Array<{ key: string; @@ -139,6 +223,8 @@ export default function EditorPane({ type="button" className={styles.tocToggle} onClick={() => onTocOpenChange(!tocOpen)} + aria-expanded={tocOpen} + aria-label={tocOpen ? '收起目录' : '展开目录'} > 目录 {tocOpen ? '◂' : '▸'} @@ -162,7 +248,7 @@ export default function EditorPane({
{tocOpen && ( -
@@ -222,4 +310,6 @@ export default function EditorPane({
); -} +}); + +export default EditorPane; diff --git a/src/renderer/conpoments/OriginMark/index.config.js b/src/renderer/conpoments/OriginMark/index.config.js deleted file mode 100644 index e17eab8..0000000 --- a/src/renderer/conpoments/OriginMark/index.config.js +++ /dev/null @@ -1,3 +0,0 @@ -export default { - navigationBarTitleText: '异度星球' -} diff --git a/src/renderer/conpoments/OriginMark/index.jsx b/src/renderer/conpoments/OriginMark/index.jsx deleted file mode 100644 index 9813bee..0000000 --- a/src/renderer/conpoments/OriginMark/index.jsx +++ /dev/null @@ -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 ( -
- {!!markText && ( -
- )} -
- ); -}; - -export default OriginMark; diff --git a/src/renderer/conpoments/OriginMark/index.scss b/src/renderer/conpoments/OriginMark/index.scss deleted file mode 100644 index 6c04e91..0000000 --- a/src/renderer/conpoments/OriginMark/index.scss +++ /dev/null @@ -1,3 +0,0 @@ -.OriginMark-mark{ - padding: 20px; -} \ No newline at end of file diff --git a/src/renderer/index.tsx b/src/renderer/index.tsx index 90223aa..f8afd7c 100644 --- a/src/renderer/index.tsx +++ b/src/renderer/index.tsx @@ -1,15 +1,6 @@ import { createRoot } from 'react-dom/client'; 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 root = createRoot(container); root.render(); - -// 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']); diff --git a/src/renderer/lib/editorActions.ts b/src/renderer/lib/editorActions.ts index ef3fea8..3161c54 100644 --- a/src/renderer/lib/editorActions.ts +++ b/src/renderer/lib/editorActions.ts @@ -4,8 +4,12 @@ export type EditorAction = { group: 'heading' | 'block' | 'inline' | 'insert'; /** If set, wrap selected text (or placeholder) */ 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 */ insert?: string; + /** After wrap, select this suffix inside `after` (e.g. link URL) */ + selectInAfter?: { match: string }; }; export const EDITOR_ACTIONS: EditorAction[] = [ @@ -13,24 +17,28 @@ export const EDITOR_ACTIONS: EditorAction[] = [ id: 'h1', label: '一级标题', group: 'heading', + linePrefix: '# ', wrap: { before: '# ', after: '', placeholder: '标题' }, }, { id: 'h2', label: '二级标题', group: 'heading', + linePrefix: '## ', wrap: { before: '## ', after: '', placeholder: '小标题' }, }, { id: 'h3', label: '三级标题', group: 'heading', + linePrefix: '### ', wrap: { before: '### ', after: '', placeholder: '小节标题' }, }, { id: 'h4', label: '四级标题', group: 'heading', + linePrefix: '#### ', wrap: { before: '#### ', after: '', placeholder: '四级标题' }, }, { @@ -66,55 +74,56 @@ export const EDITOR_ACTIONS: EditorAction[] = [ after: '](https://example.com)', placeholder: '链接文案', }, + selectInAfter: { match: 'https://example.com' }, }, { id: 'ul', label: '无序列表', group: 'block', - insert: '\n- 列表项\n- 列表项\n', + insert: '- 列表项\n- 列表项\n', }, { id: 'ol', label: '有序列表', group: 'block', - insert: '\n1. 第一项\n2. 第二项\n', + insert: '1. 第一项\n2. 第二项\n', }, { id: 'task', label: '任务列表', group: 'block', - insert: '\n- [ ] 待办事项\n- [x] 已完成\n', + insert: '- [ ] 待办事项\n- [x] 已完成\n', }, { id: 'quote', label: '引用', group: 'block', - insert: '\n> 这里是一句引用\n', + insert: '> 这里是一句引用\n', }, { id: 'hr', label: '分隔线', group: 'block', - insert: '\n---\n', + insert: '---\n', }, { id: 'table', label: '表格', group: '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', label: '代码块', group: 'insert', - insert: '\n```js\nconsole.log("hello")\n```\n', + insert: '```js\nconsole.log("hello")\n```\n', }, { id: 'image', label: '图片', 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; }; +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( content: string, selectionStart: number, selectionEnd: number, action: EditorAction, ): ApplyResult { - const selected = content.slice(selectionStart, selectionEnd); + if (action.linePrefix) { + return applyLinePrefix( + content, + selectionStart, + selectionEnd, + action.linePrefix, + action.wrap?.placeholder ?? '标题', + ); + } if (action.wrap) { const { before, after, placeholder = '' } = action.wrap; + const selected = content.slice(selectionStart, selectionEnd); const inner = selected || placeholder; const inserted = `${before}${inner}${after}`; const next = 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) { return { next, @@ -153,8 +242,106 @@ export function applyEditorAction( } const chunk = action.insert ?? ''; - const next = - content.slice(0, selectionStart) + chunk + content.slice(selectionEnd); - const cursor = selectionStart + chunk.length; - return { next, selectionStart: cursor, selectionEnd: cursor }; + if (!chunk) { + return { + next: content, + 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, + }; } diff --git a/src/renderer/lib/emojiMarkdown.ts b/src/renderer/lib/emojiMarkdown.ts index 1f16704..c2c0bd6 100644 --- a/src/renderer/lib/emojiMarkdown.ts +++ b/src/renderer/lib/emojiMarkdown.ts @@ -31,15 +31,7 @@ function cleanUrl(href: string): string | null { function isTaskItem(theme: EmojiTheme, value: string): boolean { return ( value.includes(`${theme.listSymbol}${theme.taskUnchecked}`) || - value.includes(`${theme.listSymbol}${theme.taskChecked}`) || - value.includes('🔸⬜') || - value.includes('🔸✅') || - value.includes('▪️◻') || - value.includes('▪️☑️') || - value.includes('•○') || - value.includes('•✓') || - value.includes('👉▢') || - value.includes('👉✔') + value.includes(`${theme.listSymbol}${theme.taskChecked}`) ); } @@ -63,19 +55,22 @@ function createRenderer(theme: EmojiTheme): Renderer { .map((item) => item.trim()) .filter((item) => item.length > 0); - const topped = texts.filter((item) => item.includes(listSymbol)); + let orderedIndex = 0; return texts .map((value) => { const task = isTaskItem(theme, value); if (value.includes(listSymbol)) { - const prefix = - type === 'ol' - ? `${theme.orderedNumbers[topped.indexOf(value)] ?? theme.fallbackOrdered} ` - : task - ? '' - : listSymbol; + let prefix: string; + if (type === 'ol') { + prefix = `${theme.orderedNumbers[orderedIndex] ?? `${orderedIndex + 1}.`} `; + orderedIndex += 1; + } else if (task) { + prefix = ''; + } else { + prefix = listSymbol; + } return `
${prefix}${value.replace(listSymbol, '')}
`; } @@ -112,9 +107,17 @@ function createRenderer(theme: EmojiTheme): Renderer { renderer.del = (text) => theme.del(text); renderer.blockquote = (quote) => { - const match = /
(.*?)<\/div>/.exec(quote); - const content = match ? match[1] : quote.replace(/<\/?div>/g, ''); - return theme.blockquote(content); + const lines = quote + .replace(/<\/?div>/g, '\n') + .replace(//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) @@ -142,17 +145,12 @@ function createRenderer(theme: EmojiTheme): Renderer { return renderer; } -const markedCache = new Map(); - function getMarked(themeId: ThemeId): Marked { - // Rebuild each call so table/theme helper updates always apply - const instance = new Marked({ + return new Marked({ breaks: true, gfm: true, renderer: createRenderer(resolveTheme(themeId)), }); - markedCache.set(themeId, instance); - return instance; } export const DEFAULT_FOOTER_TEXT = `➖➖➖➖➖ @@ -184,7 +182,7 @@ export function renderEmojiMarkdown( const themeId = options?.themeId ?? DEFAULT_THEME_ID; 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; diff --git a/src/renderer/lib/plainTable.ts b/src/renderer/lib/plainTable.ts index 74c6f79..e0e76ba 100644 --- a/src/renderer/lib/plainTable.ts +++ b/src/renderer/lib/plainTable.ts @@ -130,9 +130,24 @@ function buildFullwidthBox(matrix: string[][], widths: number[]): string[] { return lines; } +/** Pipe style: fullwidth cells, divider only under header (no outer top/bottom box) */ function buildPipeRows(matrix: string[][], widths: number[]): string[] { - // Also fullwidth for Theme B — same alignment guarantee - return buildFullwidthBox(matrix, widths); + const renderRow = (row: string[]) => + 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[] { @@ -180,8 +195,9 @@ export function formatPlainTable( let body: string[]; if (style === 'dots') { body = buildDotsRows(matrix, widths); + } else if (style === 'pipe') { + body = buildPipeRows(matrix, widths); } else { - // box + pipe → same fullwidth grid (Theme A/B/D) body = buildFullwidthBox(matrix, widths); } diff --git a/src/renderer/lib/storage.ts b/src/renderer/lib/storage.ts index 03a9de8..f523648 100644 --- a/src/renderer/lib/storage.ts +++ b/src/renderer/lib/storage.ts @@ -39,7 +39,7 @@ export function loadDraft(): DraftState { ? parsed.themeId : DEFAULT_THEME_ID; const content = - typeof parsed.content === 'string' && parsed.content.length > 0 + typeof parsed.content === 'string' ? parsed.content : DEFAULT_TEMPLATE_CONTENT; return { diff --git a/src/renderer/lib/templates.ts b/src/renderer/lib/templates.ts index 298afc7..5bfade8 100644 --- a/src/renderer/lib/templates.ts +++ b/src/renderer/lib/templates.ts @@ -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 SNIPPETS: SnippetItem[] = [ - { id: 'h1', label: 'H1', insert: '\n# 标题\n' }, - { id: 'h2', label: 'H2', insert: '\n## 小标题\n' }, - { id: 'ul', label: '列表', insert: '\n- 第一项\n- 第二项\n' }, + { id: 'h1', label: 'H1', insert: '# 标题\n' }, + { id: 'h2', label: 'H2', insert: '## 小标题\n' }, + { id: 'ul', label: '列表', insert: '- 第一项\n- 第二项\n' }, { id: 'task', label: '任务', - insert: '\n- [ ] 待办事项\n- [x] 已完成\n', + insert: '- [ ] 待办事项\n- [x] 已完成\n', }, - { id: 'hr', label: '分隔', insert: '\n---\n' }, + { id: 'hr', label: '分隔', insert: '---\n' }, { id: 'link', 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', label: '代码', - insert: '\n`行内代码`\n\n```js\nconsole.log(1)\n```\n', + insert: '`行内代码`\n\n```js\nconsole.log(1)\n```\n', }, { id: 'table', label: '表格', - insert: '\n| 列1 | 列2 |\n| --- | --- |\n| A | B |\n', + insert: '| 列1 | 列2 |\n| --- | --- |\n| A | B |\n', }, ]; diff --git a/src/renderer/lib/themes.ts b/src/renderer/lib/themes.ts index ccb20ed..f98219e 100644 --- a/src/renderer/lib/themes.ts +++ b/src/renderer/lib/themes.ts @@ -87,9 +87,9 @@ export const THEME_A: EmojiTheme = { taskChecked: '✅', taskUnchecked: '⬜', heading1: frameTitleA, - heading2: (text) => `
📝${text}
\n`, - heading3: (text) => `
📝${text}
\n`, - heading4: (text) => `
▪️${text}
\n`, + heading2: (text) => `
📝 ${text}
\n`, + heading3: (text) => `
📎 ${text}
\n`, + heading4: (text) => `
▪️ ${text}
\n`, hr: '➖➖➖➖➖\n', codespan: (text) => `『${text}』`, codeblock: (code, language) =>