mirror of
https://github.com/amitwh/markdown-converter.git
synced 2026-08-23 23:10:17 +05:30
Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24c6675c82 | ||
|
|
929d72cf1d | ||
|
|
b40bff641c | ||
|
|
338669f2db | ||
|
|
54615649f4 | ||
|
|
3ff76c8c33 | ||
|
|
8160ac05e0 | ||
|
|
6762b5f9af | ||
|
|
00485d1bef | ||
|
|
24bb9aa9f5 | ||
|
|
b39bdcf475 | ||
|
|
9d154a8521 | ||
|
|
fe62c8814c | ||
|
|
9306a9c23b | ||
|
|
88e26c130e | ||
|
|
b02707ac7f | ||
|
|
ebc149ff0b | ||
|
|
be3af42fc5 | ||
|
|
ed611c77ed | ||
|
|
f25d856a2a | ||
|
|
76fed872ce | ||
|
|
9de14df016 | ||
|
|
5f0b4c9c4e | ||
|
|
7d083a024d | ||
|
|
68fcaf9bfc | ||
|
|
a2a44fbf2c | ||
|
|
026a4d9fac | ||
|
|
a461b62dd3 | ||
|
|
1cd316caf1 | ||
|
|
2bdb380130 | ||
|
|
41942a1316 | ||
|
|
9ad484744a | ||
|
|
d0a26126cc | ||
|
|
53870d58bb | ||
|
|
00d6802422 | ||
|
|
02418b943e | ||
|
|
8b2809ebaf | ||
|
|
8f5eb301b6 | ||
|
|
8f9dab1405 | ||
|
|
a6fa14124d | ||
|
|
0538aec02c | ||
|
|
1d782a00e6 | ||
|
|
9eb1fe0f00 | ||
|
|
3344b2aea9 | ||
|
|
6b23e5ef60 | ||
|
|
221598c91b | ||
|
|
d8ee743fb1 | ||
|
|
66e2b56221 | ||
|
|
d22d616727 | ||
|
|
89590a349a | ||
|
|
f447896a63 | ||
|
|
ccb998be66 | ||
|
|
813582aa8d | ||
|
|
b1e16af62d | ||
|
|
487ce2ad45 | ||
|
|
1717b2e8c0 | ||
|
|
cdd370c62d | ||
|
|
6df21ace35 | ||
|
|
c93747c476 | ||
|
|
d865b181e9 | ||
|
|
5e5bab3da9 | ||
|
|
ce2bf62d42 | ||
|
|
6da98c3a54 | ||
|
|
3598d06240 | ||
|
|
650c266945 | ||
|
|
05bbb9f86b | ||
|
|
77c8e05fa5 | ||
|
|
17f318dd75 | ||
|
|
fa5a46d5ac | ||
|
|
a4201acad9 | ||
|
|
0b5af04a6a | ||
|
|
2d6f909b0e | ||
|
|
8624257c1f | ||
|
|
b75f436aaa | ||
|
|
d81d8c28d2 | ||
|
|
559d09cad9 | ||
|
|
5ad582ec3e | ||
|
|
d02f896167 | ||
|
|
f34775ce53 | ||
|
|
5d6a55dd09 | ||
|
|
0e80e37d9d | ||
|
|
9a7e994224 | ||
|
|
3effacf816 | ||
|
|
1be10f9ae5 | ||
|
|
4c0b7d6e84 | ||
|
|
db04ea5854 | ||
|
|
567726022c | ||
|
|
1999a7716e | ||
|
|
16e071ae5e | ||
|
|
7ecf54ceb0 | ||
|
|
95e2f45f1f | ||
|
|
7fbbd60525 | ||
|
|
c715bb354c | ||
|
|
6525de7667 | ||
|
|
a2c1d0c11a | ||
|
|
e0d6315204 | ||
|
|
68ff7d076a | ||
|
|
67b57eae78 | ||
|
|
301c51ac84 | ||
|
|
904ffbdd5b | ||
|
|
ea383783ec | ||
|
|
e758a81c4c | ||
|
|
ea0f3f93bf | ||
|
|
188e73d7c1 | ||
|
|
8265e4ff88 | ||
|
|
8a8671b128 | ||
|
|
3646dc29c6 | ||
|
|
a999f598cc | ||
|
|
7a396f64a6 | ||
|
|
88e9a5290d | ||
|
|
fff15d8d3e | ||
|
|
c574d77c20 | ||
|
|
272215f9af | ||
|
|
0192590567 |
@@ -1,103 +0,0 @@
|
|||||||
# CLAUDE.md — MarkdownConverter (master)
|
|
||||||
|
|
||||||
> General code-quality, JavaScript, git, security, and testing standards are in the **global CLAUDE.md**. This file holds project- and branch-specific notes.
|
|
||||||
|
|
||||||
## Project Overview
|
|
||||||
|
|
||||||
Electron desktop app for Markdown editing and universal file conversion powered by Pandoc. Cross-platform (Win/macOS/Linux). Features: multi-tab editor with live preview, 25+ themes, PDF viewer/editor (merge/split/compress/rotate/watermark/password), export to 20+ formats (PDF/DOCX/ODT/EPUB/HTML/LaTeX/RTF/PPTX), batch conversion, syntax highlighting, diagram support (Mermaid), Git integration, and a plugin system.
|
|
||||||
|
|
||||||
- **Version:** 4.4.5
|
|
||||||
- **License:** MIT
|
|
||||||
- **App ID:** `com.concreteinfo.markdownconverter`
|
|
||||||
|
|
||||||
## Branch Specifics
|
|
||||||
|
|
||||||
This is the **primary/release branch** — a vanilla JavaScript Electron app with no bundler or framework in the renderer. The renderer is a single large `renderer.js` (5,300+ lines) loaded directly via `src/index.html`. All UI is hand-rolled DOM manipulation.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Main Process (`src/main.js` — 4,260 lines)
|
|
||||||
Monolithic main process file. Contains all IPC handlers, Pandoc invocation, file operations, menu definitions (600+ lines), and window lifecycle. Key modules extracted:
|
|
||||||
- `src/main/PDFOperations.js` — PDF manipulation via `pdf-lib` (merge, split, compress, rotate, delete, reorder, watermark, encrypt, decrypt, permissions)
|
|
||||||
- `src/main/GitOperations.js` — Git status/stage/commit/log via `simple-git`
|
|
||||||
|
|
||||||
### Renderer (`src/renderer.js` — 5,361 lines)
|
|
||||||
Vanilla JS, no framework. Directly manipulates DOM. Loads CodeMirror 6 via `src/editor/codemirror-setup.js`. Uses `marked` + `highlight.js` + `DOMPurify` + `mermaid` for rendering. Lazy-loads sidebar panels, REPL, command palette, zen mode.
|
|
||||||
|
|
||||||
### Preload (`src/preload.js` — 448 lines)
|
|
||||||
Exists as IPC bridge, but **`contextIsolation: false` and `nodeIntegration: true`** — the renderer has full Node access. Preload is effectively a thin passthrough.
|
|
||||||
|
|
||||||
### Security Model
|
|
||||||
- `contextIsolation: false` + `nodeIntegration: true` (legacy; the react-electron branch fixes this)
|
|
||||||
- Pandoc invoked via `execFile` (not `exec`) to prevent shell injection
|
|
||||||
- Path traversal protection: `validatePath()`, `resolveWritablePath()`, blocks sensitive system dirs
|
|
||||||
- Permission handler only allows `clipboard-read`/`clipboard-write`
|
|
||||||
- Rate limiter on conversions (2-second minimum interval)
|
|
||||||
- File size limit: 50MB
|
|
||||||
- Error message sanitization strips absolute paths
|
|
||||||
|
|
||||||
### Plugin System (`src/plugins/`)
|
|
||||||
Manifest-based discovery (`manifest.json`). Built-in `writing-studio` plugin with sprint/goal/snapshot management. Plugin API exposed via `src/plugins/plugin-api.js`.
|
|
||||||
|
|
||||||
### Settings
|
|
||||||
Custom JSON file store at `<userData>/settings.json` (NOT `electron-store` despite the dependency). Recent files at `<userData>/recent-files.json`.
|
|
||||||
|
|
||||||
## System Dependencies
|
|
||||||
|
|
||||||
| Dependency | Required | Notes |
|
|
||||||
|---|---|---|
|
|
||||||
| **Node.js** | >= 20 | Electron 41 bundles Node 20.x |
|
|
||||||
| **Pandoc** | Yes (for exports) | Downloaded to `bin/<platform>/pandoc` via `scripts/download-tools.js` (v3.9.0.2). Falls back to system PATH. Must be present for DOCX/ODT/EPUB/LaTeX/PPTX export. |
|
|
||||||
| **FFmpeg** | Bundled | `ffmpeg-static` npm package; `asarUnpacked` for packaged builds |
|
|
||||||
| **MiKTeX / TeX Live** | Optional | For LaTeX PDF export; MiKTeX PATH injected on Windows automatically |
|
|
||||||
| **ImageMagick** | Optional | Linux image conversion; listed as deb dependency |
|
|
||||||
| **LibreOffice** | Optional | Enhanced document conversion; listed as deb dependency |
|
|
||||||
|
|
||||||
## Development Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm start # Launch Electron app (dev mode)
|
|
||||||
npm test # Jest test suite
|
|
||||||
npm test:watch # Jest in watch mode
|
|
||||||
npm test:coverage # Jest with coverage report
|
|
||||||
npm run lint # ESLint check (src + tests)
|
|
||||||
npm run lint:fix # ESLint auto-fix
|
|
||||||
npm run format # Prettier write
|
|
||||||
npm run format:check # Prettier check only
|
|
||||||
npm run download-tools # Download Pandoc binaries to bin/
|
|
||||||
npm run generate-icons # Generate app icons via sharp
|
|
||||||
```
|
|
||||||
|
|
||||||
## Build & Package
|
|
||||||
|
|
||||||
**Tool:** `electron-builder` (v26.0.12), config inline in `package.json` (no separate config file).
|
|
||||||
|
|
||||||
| Target | Platforms |
|
|
||||||
|---|---|
|
|
||||||
| `npm run build` | electron-builder (default platform) |
|
|
||||||
| `npm run build:win` | Windows: NSIS installer + portable + zip (x64) |
|
|
||||||
| `npm run build:mac` | macOS: default dmg |
|
|
||||||
| `npm run build:linux` | Linux: deb + AppImage + snap |
|
|
||||||
| `npm run dist` | Build without publish |
|
|
||||||
| `npm run dist:all` | Build for all platforms |
|
|
||||||
|
|
||||||
**Bundled with builds:** Pandoc binary per platform. FFmpeg via `ffmpeg-static` (asarUnpacked). NSIS installer uses custom script at `scripts/nsis-installer.nsh`.
|
|
||||||
|
|
||||||
**Output:** `dist/` directory.
|
|
||||||
|
|
||||||
**CI:** GitHub Actions workflows in `.github/workflows/` (ci.yml, release.yml).
|
|
||||||
|
|
||||||
## Project Conventions / Gotchas
|
|
||||||
|
|
||||||
- **No bundler/transpilation.** The app uses vanilla CommonJS JavaScript. `src/main.js` is loaded directly by Electron. No webpack, no Vite, no TypeScript, no Babel.
|
|
||||||
- **Monolithic files.** `main.js` (4,260 lines) and `renderer.js` (5,361 lines) contain most logic. Not ideal but is the current state of this branch.
|
|
||||||
- **CodeMirror 6** for the editor, configured in `src/editor/codemirror-setup.js`.
|
|
||||||
- **PDF rendering** uses `pdfjs-dist`; **PDF manipulation** uses `pdf-lib` in the main process.
|
|
||||||
- **Renderer security is weak** — full Node access in renderer. Do NOT introduce new privileged renderer code without understanding this.
|
|
||||||
- **Pandoc is external.** Must be installed separately or downloaded via `npm run download-tools`. HTML and built-in PDF export work without Pandoc; other formats require it.
|
|
||||||
- **PDF export fallback chain:** xelatex -> pdflatex -> lualatex -> Electron built-in `printToPDF()`.
|
|
||||||
- **ESLint flat config** (`eslint.config.js`) with ECMAScript 2022. Prettier with 2-space indent, single quotes, semicolons, 100-char width.
|
|
||||||
- **Tests:** Jest with jsdom environment, 15% coverage threshold. 24 test files in `tests/`.
|
|
||||||
- **File associations:** `.md`, `.markdown`, `.pdf` registered at install.
|
|
||||||
- **Single instance lock** enforced via `app.requestSingleInstanceLock()`.
|
|
||||||
- **Adapters layer** (`src/adapters/`) abstracts file system operations for potential future non-Electron targets.
|
|
||||||
@@ -162,4 +162,4 @@ Amit Haridas (amit.wh@gmail.com)
|
|||||||
|
|
||||||
## Version
|
## Version
|
||||||
|
|
||||||
v4.5.0
|
v4.1.0
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,93 +0,0 @@
|
|||||||
Copyright (c) 2014, The Fira Code Project Authors (https://github.com/tonsky/FiraCode)
|
|
||||||
|
|
||||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
||||||
This license is copied below, and is also available with a FAQ at:
|
|
||||||
http://scripts.sil.org/OFL
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------------------------------------------
|
|
||||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
||||||
-----------------------------------------------------------
|
|
||||||
|
|
||||||
PREAMBLE
|
|
||||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
||||||
development of collaborative font projects, to support the font creation
|
|
||||||
efforts of academic and linguistic communities, and to provide a free and
|
|
||||||
open framework in which fonts may be shared and improved in partnership
|
|
||||||
with others.
|
|
||||||
|
|
||||||
The OFL allows the licensed fonts to be used, studied, modified and
|
|
||||||
redistributed freely as long as they are not sold by themselves. The
|
|
||||||
fonts, including any derivative works, can be bundled, embedded,
|
|
||||||
redistributed and/or sold with any software provided that any reserved
|
|
||||||
names are not used by derivative works. The fonts and derivatives,
|
|
||||||
however, cannot be released under any other type of license. The
|
|
||||||
requirement for fonts to remain under this license does not apply
|
|
||||||
to any document created using the fonts or their derivatives.
|
|
||||||
|
|
||||||
DEFINITIONS
|
|
||||||
"Font Software" refers to the set of files released by the Copyright
|
|
||||||
Holder(s) under this license and clearly marked as such. This may
|
|
||||||
include source files, build scripts and documentation.
|
|
||||||
|
|
||||||
"Reserved Font Name" refers to any names specified as such after the
|
|
||||||
copyright statement(s).
|
|
||||||
|
|
||||||
"Original Version" refers to the collection of Font Software components as
|
|
||||||
distributed by the Copyright Holder(s).
|
|
||||||
|
|
||||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
||||||
or substituting -- in part or in whole -- any of the components of the
|
|
||||||
Original Version, by changing formats or by porting the Font Software to a
|
|
||||||
new environment.
|
|
||||||
|
|
||||||
"Author" refers to any designer, engineer, programmer, technical
|
|
||||||
writer or other person who contributed to the Font Software.
|
|
||||||
|
|
||||||
PERMISSION & CONDITIONS
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
||||||
redistribute, and sell modified and unmodified copies of the Font
|
|
||||||
Software, subject to the following conditions:
|
|
||||||
|
|
||||||
1) Neither the Font Software nor any of its individual components,
|
|
||||||
in Original or Modified Versions, may be sold by itself.
|
|
||||||
|
|
||||||
2) Original or Modified Versions of the Font Software may be bundled,
|
|
||||||
redistributed and/or sold with any software, provided that each copy
|
|
||||||
contains the above copyright notice and this license. These can be
|
|
||||||
included either as stand-alone text files, human-readable headers or
|
|
||||||
in the appropriate machine-readable metadata fields within text or
|
|
||||||
binary files as long as those fields can be easily viewed by the user.
|
|
||||||
|
|
||||||
3) No Modified Version of the Font Software may use the Reserved Font
|
|
||||||
Name(s) unless explicit written permission is granted by the corresponding
|
|
||||||
Copyright Holder. This restriction only applies to the primary font name as
|
|
||||||
presented to the users.
|
|
||||||
|
|
||||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
||||||
Software shall not be used to promote, endorse or advertise any
|
|
||||||
Modified Version, except to acknowledge the contribution(s) of the
|
|
||||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
||||||
permission.
|
|
||||||
|
|
||||||
5) The Font Software, modified or unmodified, in part or in whole,
|
|
||||||
must be distributed entirely under this license, and must not be
|
|
||||||
distributed under any other license. The requirement for fonts to
|
|
||||||
remain under this license does not apply to any document created
|
|
||||||
using the Font Software.
|
|
||||||
|
|
||||||
TERMINATION
|
|
||||||
This license becomes null and void if any of the above conditions are
|
|
||||||
not met.
|
|
||||||
|
|
||||||
DISCLAIMER
|
|
||||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
||||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
||||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
||||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
||||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
||||||
File diff suppressed because one or more lines are too long
Binary file not shown.
@@ -1,93 +0,0 @@
|
|||||||
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
|
|
||||||
|
|
||||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
||||||
This license is copied below, and is also available with a FAQ at:
|
|
||||||
https://scripts.sil.org/OFL
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------------------------------------------
|
|
||||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
||||||
-----------------------------------------------------------
|
|
||||||
|
|
||||||
PREAMBLE
|
|
||||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
||||||
development of collaborative font projects, to support the font creation
|
|
||||||
efforts of academic and linguistic communities, and to provide a free and
|
|
||||||
open framework in which fonts may be shared and improved in partnership
|
|
||||||
with others.
|
|
||||||
|
|
||||||
The OFL allows the licensed fonts to be used, studied, modified and
|
|
||||||
redistributed freely as long as they are not sold by themselves. The
|
|
||||||
fonts, including any derivative works, can be bundled, embedded,
|
|
||||||
redistributed and/or sold with any software provided that any reserved
|
|
||||||
names are not used by derivative works. The fonts and derivatives,
|
|
||||||
however, cannot be released under any other type of license. The
|
|
||||||
requirement for fonts to remain under this license does not apply
|
|
||||||
to any document created using the fonts or their derivatives.
|
|
||||||
|
|
||||||
DEFINITIONS
|
|
||||||
"Font Software" refers to the set of files released by the Copyright
|
|
||||||
Holder(s) under this license and clearly marked as such. This may
|
|
||||||
include source files, build scripts and documentation.
|
|
||||||
|
|
||||||
"Reserved Font Name" refers to any names specified as such after the
|
|
||||||
copyright statement(s).
|
|
||||||
|
|
||||||
"Original Version" refers to the collection of Font Software components as
|
|
||||||
distributed by the Copyright Holder(s).
|
|
||||||
|
|
||||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
||||||
or substituting -- in part or in whole -- any of the components of the
|
|
||||||
Original Version, by changing formats or by porting the Font Software to a
|
|
||||||
new environment.
|
|
||||||
|
|
||||||
"Author" refers to any designer, engineer, programmer, technical
|
|
||||||
writer or other person who contributed to the Font Software.
|
|
||||||
|
|
||||||
PERMISSION & CONDITIONS
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
||||||
redistribute, and sell modified and unmodified copies of the Font
|
|
||||||
Software, subject to the following conditions:
|
|
||||||
|
|
||||||
1) Neither the Font Software nor any of its individual components,
|
|
||||||
in Original or Modified Versions, may be sold by itself.
|
|
||||||
|
|
||||||
2) Original or Modified Versions of the Font Software may be bundled,
|
|
||||||
redistributed and/or sold with any software, provided that each copy
|
|
||||||
contains the above copyright notice and this license. These can be
|
|
||||||
included either as stand-alone text files, human-readable headers or
|
|
||||||
in the appropriate machine-readable metadata fields within text or
|
|
||||||
binary files as long as those fields can be easily viewed by the user.
|
|
||||||
|
|
||||||
3) No Modified Version of the Font Software may use the Reserved Font
|
|
||||||
Name(s) unless explicit written permission is granted by the corresponding
|
|
||||||
Copyright Holder. This restriction only applies to the primary font name as
|
|
||||||
presented to the users.
|
|
||||||
|
|
||||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
||||||
Software shall not be used to promote, endorse or advertise any
|
|
||||||
Modified Version, except to acknowledge the contribution(s) of the
|
|
||||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
||||||
permission.
|
|
||||||
|
|
||||||
5) The Font Software, modified or unmodified, in part or in whole,
|
|
||||||
must be distributed entirely under this license, and must not be
|
|
||||||
distributed under any other license. The requirement for fonts to
|
|
||||||
remain under this license does not apply to any document created
|
|
||||||
using the Font Software.
|
|
||||||
|
|
||||||
TERMINATION
|
|
||||||
This license becomes null and void if any of the above conditions are
|
|
||||||
not met.
|
|
||||||
|
|
||||||
DISCLAIMER
|
|
||||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
||||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
||||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
||||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
||||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
||||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 361 KiB |
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": false,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "tailwind.config.js",
|
||||||
|
"css": "src/renderer/styles/globals.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide"
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,759 +0,0 @@
|
|||||||
# Feature Audit, Bug Fixes, New Features & Security Hardening Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Goal:** Fix every verified non-working feature in MarkdownConverter, build out the orphaned image/audio/video converter subsystem, add 9 new features extending existing architecture, remediate a critical Pandoc argument-injection vulnerability plus other security findings, then produce a clean local release build.
|
|
||||||
|
|
||||||
**Architecture:** Vanilla JS Electron app (`contextIsolation: false`, `nodeIntegration: true`). Main process (`src/main.js`, ~5000 lines) owns all IPC handlers, dialogs, and external-tool invocation (Pandoc, ffmpeg, ImageMagick, LibreOffice) via `execFile`. Renderer (`src/renderer.js`, ~6150 lines) is vanilla DOM manipulation; it uses `ipcRenderer` both directly (legacy) and via the whitelisted `window.electronAPI` bridge (`src/preload.js`). Feature modules live under `src/main/*.js` (PDF, Git, font embedding) and `src/plugins/*.js` (plugin system). Follow this existing pattern for all new code — do not introduce a bundler, framework, or TypeScript.
|
|
||||||
|
|
||||||
**Tech Stack:** Electron 41, Node 20, Pandoc (external binary via `getPandocPath()`), ffmpeg-static (bundled, via `getFFmpegPath()`), `sharp` (image ops, currently a devDependency — must move to `dependencies`), `pdf-lib` (`src/main/PDFOperations.js`), `simple-git` (`src/main/GitOperations.js`), Jest for tests, ESLint flat config + Prettier.
|
|
||||||
|
|
||||||
**Spec:** This plan is self-originated from a live codebase audit (two parallel research passes + manual verification of every finding against `src/main.js`, `src/preload.js`, `src/renderer.js`, `src/main/GitOperations.js`, `src/main/PDFOperations.js`, `src/plugins/plugin-context.js`). No separate spec doc exists; each task below states the verified current behavior and the required end behavior.
|
|
||||||
|
|
||||||
## Global Constraints
|
|
||||||
|
|
||||||
- `contextIsolation: false` / `nodeIntegration: true` is the existing (weak) security model for this branch — do not attempt to flip it as part of this plan; that is a separate, much larger migration tracked elsewhere. Do not make the security posture worse than it already is.
|
|
||||||
- All new external-process invocation MUST use `execFile` with an explicit argument array — **never** build a shell-style command string and re-tokenize it. This is the root cause of Finding SEC-1 below; do not repeat the pattern anywhere new.
|
|
||||||
- All new/changed IPC channels must be added to the correct whitelist array in `src/preload.js` (`ALLOWED_SEND_CHANNELS` for renderer→main, `ALLOWED_RECEIVE_CHANNELS` for main→renderer) — an unlisted channel is silently blocked (see `preload.js:261-282`).
|
|
||||||
- 2-space indent, single quotes, semicolons, 100-char width (Prettier). Run `npm run lint` and `npm run format:check` before every commit; both must pass.
|
|
||||||
- `npm test` (Jest, jsdom) must stay green (247 tests / 32 suites passing at plan start) after every task.
|
|
||||||
- File size limit for user-opened files is `MAX_FILE_SIZE_MB = 50` (`main.js:57-58`) — reuse this constant for any new file-accepting handler, don't invent a new limit.
|
|
||||||
- Error messages shown to the user must go through `sanitizeErrorMessage()` (`main.js:61-70`) if they might contain absolute paths.
|
|
||||||
- No forbidden markers (`TODO`, `FIXME`, `stub`, `placeholder`, `coming soon`, etc.) in any changed file.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase A — Fix Verified Non-Working Features
|
|
||||||
|
|
||||||
### Task 1: Fix "Open PDF File..." menu item (wrong IPC channel)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main.js:1666-1684` (`openPDFFile()`)
|
|
||||||
|
|
||||||
**Verified current behavior:** `openPDFFile()` sends `mainWindow.webContents.send('open-pdf-viewer', files[0])` (line 1682). No listener for `'open-pdf-viewer'` exists anywhere in the repo. The working PDF-editor open path is `show-pdf-editor-dialog`, whose renderer listener is `ipcRenderer.on('show-pdf-editor-dialog', (event, operation, openedFilePath) => {...})` (`renderer.js:3685`).
|
|
||||||
|
|
||||||
- [ ] **Step 1:** In `openPDFFile()`, replace the send call:
|
|
||||||
```javascript
|
|
||||||
mainWindow.webContents.send('show-pdf-editor-dialog', null, files[0]);
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Manually verify: `npm start`, open a PDF via File → Open PDF File (or the equivalent menu entry), confirm the PDF editor dialog opens with the file loaded (same result as opening it via the PDF toolbar button).
|
|
||||||
- [ ] **Step 3:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 4:** Commit: `git add src/main.js && git commit -m "fix(pdf): route Open PDF File menu item to the working editor dialog channel"`
|
|
||||||
|
|
||||||
### Task 2: Fix "Clear Recent Files" silent no-op
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main.js:731-736` (menu click handler), `src/main.js:4480-4491` (`ipcMain.on('clear-recent-files', ...)`)
|
|
||||||
|
|
||||||
**Verified current behavior:** The menu click handler does `mainWindow.webContents.send('clear-recent-files')` (main→renderer), but nothing in the renderer listens for that channel. The actual deletion logic lives in `ipcMain.on('clear-recent-files', (event) => {...})`, which only fires on a renderer→main `.send`/`.invoke` that never happens from this menu path. `preload.js:342` exposes a separate `clearRecent: () => ipcRenderer.send('clear-recent-files')` helper that IS the correct renderer→main direction, but the menu item bypasses it entirely by sending the same channel name in the wrong direction.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Extract the deletion logic into a standalone function above the `ipcMain.on` registration:
|
|
||||||
```javascript
|
|
||||||
function clearRecentFilesOnDisk() {
|
|
||||||
const userDataPath = app.getPath('userData');
|
|
||||||
const recentFilesPath = path.join(userDataPath, 'recent-files.json');
|
|
||||||
fs.writeFileSync(recentFilesPath, JSON.stringify([], null, 2));
|
|
||||||
createMenu();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Update the `ipcMain.on` handler to use it:
|
|
||||||
```javascript
|
|
||||||
ipcMain.on('clear-recent-files', (event) => {
|
|
||||||
try {
|
|
||||||
clearRecentFilesOnDisk();
|
|
||||||
event.reply('recent-files-cleared');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error clearing recent files:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 3:** Update the menu click handler (`main.js:731-736`) to call the main-process function directly and notify the renderer the same way the working path does:
|
|
||||||
```javascript
|
|
||||||
{
|
|
||||||
label: 'Clear Recent Files',
|
|
||||||
click: () => {
|
|
||||||
try {
|
|
||||||
clearRecentFilesOnDisk();
|
|
||||||
mainWindow.webContents.send('recent-files-cleared');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error clearing recent files:', error);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
```
|
|
||||||
- [ ] **Step 4:** Manually verify: open a few recent files, use File menu → Clear Recent Files, confirm the Recent Files submenu is empty afterward.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add src/main.js && git commit -m "fix(menu): make Clear Recent Files actually clear the list"`
|
|
||||||
|
|
||||||
### Task 3: Wire "Insert Template" submenu (content already exists, just needs a listener)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (near the existing `templates` sidebar-panel registration, ~line 1744-1758)
|
|
||||||
|
|
||||||
**Verified current behavior:** `main.js:811-847` sends `mainWindow.webContents.send('load-template-menu', '<file>.md')` for 10 menu items. `'load-template-menu'` IS already in `ALLOWED_RECEIVE_CHANNELS` (`preload.js:241`) but nothing in the renderer listens for it — **however** the underlying feature is fully implemented already: `src/templates/*.md` contains real content for all 10 templates, `ipcMain.handle('load-template', ...)` (`main.js:4641-4649`) reads them, and the sidebar Templates panel (`renderer.js:1744-1758`) already does exactly the load-into-new-tab flow needed. Do not author new template content — reuse the existing flow.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Extract the existing inline callback at `renderer.js:1746-1757` into a shared named function so both the sidebar panel and the new menu listener use it:
|
|
||||||
```javascript
|
|
||||||
async function loadTemplateIntoNewTab(file) {
|
|
||||||
const templateContent = await ipcRenderer.invoke('load-template', file);
|
|
||||||
if (templateContent) {
|
|
||||||
const content = templateContent.replace(/\{\{DATE\}\}/g, new Date().toISOString().split('T')[0]);
|
|
||||||
tabManager.createNewTab();
|
|
||||||
const tab = tabManager.tabs.get(tabManager.activeTabId);
|
|
||||||
tabManager.setEditorContent(tab.id, content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
Place this near the top of the sidebar-initialization block (wherever `tabManager` is already in scope at that point), then replace the sidebar panel's inline callback with `render: (container) => getRenderTemplatesPanel()(container, loadTemplateIntoNewTab)`.
|
|
||||||
- [ ] **Step 2:** Add a listener for the menu channel, near the other `ipcRenderer.on(...)` registrations in the same initialization area:
|
|
||||||
```javascript
|
|
||||||
ipcRenderer.on('load-template-menu', (event, file) => {
|
|
||||||
loadTemplateIntoNewTab(file);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 3:** Manually verify: File → New from Template → Blog Post (and 2-3 others), confirm a new tab opens with the real template content, `{{DATE}}` replaced with today's date.
|
|
||||||
- [ ] **Step 4:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 5:** Commit: `git add src/renderer.js && git commit -m "fix(templates): wire New from Template menu to existing template-loading flow"`
|
|
||||||
|
|
||||||
### Task 4: Wire Command Palette / Sidebar / Bottom Panel menu toggles
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (near command palette init ~line 2045, sidebar manager init ~line 1703, bottom/REPL panel init ~line 1007)
|
|
||||||
|
|
||||||
**Verified current behavior:** `main.js:1047,1057-1069,1075` send `toggle-command-palette`, `toggle-sidebar-panel` (with a panel-id arg: `explorer`/`git`/`snippets`/`templates`), and `toggle-bottom-panel`. All three channels are already whitelisted in `ALLOWED_RECEIVE_CHANNELS` (`preload.js:242-244`). None have a renderer listener — the Command Palette currently only opens via its own `Ctrl+Shift+P` keydown handler (`renderer.js:2045-2049`), sidebar panels only toggle via their own buttons, and the bottom/REPL panel only auto-shows when a code block runs (`renderer.js:1007`).
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Find the existing function/method that the `Ctrl+Shift+P` keydown handler calls to open the command palette (read `renderer.js:2040-2060` to get its exact name), then add:
|
|
||||||
```javascript
|
|
||||||
ipcRenderer.on('toggle-command-palette', () => {
|
|
||||||
/* call the same open/toggle function the Ctrl+Shift+P handler uses */
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Find the existing method on `sidebarManager` used to show/activate a panel by id (read the `SidebarManager` class, likely in `src/sidebar/` — grep `class SidebarManager`), then add:
|
|
||||||
```javascript
|
|
||||||
ipcRenderer.on('toggle-sidebar-panel', (event, panelId) => {
|
|
||||||
/* call sidebarManager's existing toggle/show method with panelId */
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 3:** Find the existing function that shows/hides the bottom REPL panel (read `renderer.js` around line 997-1012), then add:
|
|
||||||
```javascript
|
|
||||||
ipcRenderer.on('toggle-bottom-panel', () => {
|
|
||||||
/* call the same show/hide function used when a code block runs, but toggle rather than force-show */
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 4:** Manually verify each of the three View-menu items now actually opens/toggles its target.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add src/renderer.js && git commit -m "fix(menu): wire Command Palette / Sidebar / Bottom Panel View-menu toggles"`
|
|
||||||
|
|
||||||
### Task 5: Fix broken `git-diff` IPC call (renderer invokes a channel main never handles)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main/GitOperations.js`, `src/main.js` (near the other `git-*` handlers, ~line 4889-4904)
|
|
||||||
- Modify: `src/sidebar/git-panel.js`, `src/renderer.js:1714-1731`
|
|
||||||
|
|
||||||
**Verified current behavior:** `renderer.js:1718-1721` passes `gitDiff: (file) => ipcRenderer.invoke('git-diff', { file })` into the Git sidebar panel, but `src/main.js` has **no** `ipcMain.handle('git-diff', ...)` registered anywhere (only `git-status`, `git-stage`, `git-commit`, `git-log` exist at lines 4889-4904), and `GitOperations.js` exports no `diff` function. Additionally, `src/sidebar/git-panel.js:1` receives this callback as a parameter literally named `_gitDiff` (underscore-prefixed = intentionally unused) — the panel never even calls it. This is dead on both ends. Fold the real fix into Task 14 (Phase C, new git features) rather than doing a throwaway partial fix here.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** No action in this task — cross-reference only. Mark this task done once Task 14 lands, since it fully supersedes it.
|
|
||||||
|
|
||||||
### Task 6: Whitelist and wire "Document Compare" menu item
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/preload.js` (`ALLOWED_RECEIVE_CHANNELS`)
|
|
||||||
|
|
||||||
**Verified current behavior:** `main.js:1411-1413` sends `mainWindow.webContents.send('show-document-compare')`, but `'show-document-compare'` is **not** in `ALLOWED_RECEIVE_CHANNELS` at all (unlike the other dead channels, which were at least whitelisted) — per `preload.js:288-...` the `on()` wrapper drops unlisted channels. Building the actual compare UI is Task 20 (Phase C) — this task only covers the whitelist fix; C8 covers the working listener + UI.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Add `'show-document-compare'` to `ALLOWED_RECEIVE_CHANNELS` in `src/preload.js` (alongside the other `show-*-dialog`/`show-*-converter` entries for consistency).
|
|
||||||
- [ ] **Step 2:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 3:** Commit: `git add src/preload.js && git commit -m "fix(preload): whitelist show-document-compare channel"`
|
|
||||||
- Do not close this task's manual-verification step until Task 20 lands (there is nothing to see until the listener exists).
|
|
||||||
|
|
||||||
### Task 7: Reachable UI control for monospace font settings
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (Settings panel/dialog — locate existing settings UI, e.g. grep `showSettingsDialog` or similar)
|
|
||||||
|
|
||||||
**Verified current behavior:** `ipcMain.handle('set-monospace-settings', ...)` exists and works (`main.js:375` area) and the getter is used at `renderer.js:1857`, but no UI control anywhere calls the setter — a user cannot actually change the monospace font/ligature preference.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Read `main.js` around the `get-monospace-settings`/`set-monospace-settings` handlers to learn the exact settings shape (property names, e.g. `{ enabled, fontFamily, ligatures }` — use whatever the real shape is, do not invent fields).
|
|
||||||
- [ ] **Step 2:** Locate the app's existing Settings panel/dialog in `renderer.js` (grep for where `get-monospace-settings` is already invoked at line ~1857 to find the surrounding UI section) and add a toggle + font-family control there, following the existing settings-control markup/CSS pattern already used for other settings in that same dialog.
|
|
||||||
- [ ] **Step 3:** Wire the control's change handler to `ipcRenderer.invoke('set-monospace-settings', {...})` and apply the returned/echoed setting immediately (toggle the body class the same way the existing `renderer.js:1857`-area code does on load).
|
|
||||||
- [ ] **Step 4:** Manually verify: toggle monospace font in Settings, confirm the editor/preview font changes live, and confirm the preference persists across an app restart.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add src/renderer.js && git commit -m "feat(settings): expose monospace font toggle in Settings UI"`
|
|
||||||
|
|
||||||
### Task 8: Dependency hygiene — `jszip` and `sharp`
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `package.json`
|
|
||||||
|
|
||||||
**Verified current behavior:** `src/main/DocxFontEmbedder.js` and `src/main/EpubFontEmbedder.js` `require('jszip')` directly, but `jszip` is declared only under `overrides`, not `dependencies` — it currently resolves only via hoisting from a transitive dependency. `sharp` is declared under `devDependencies` (used today only by `scripts/generate-icons.js` at build time) but Phase B (media converter) will require it at **runtime** in the packaged app, where devDependencies are not installed/bundled.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** In `package.json`, add `"jszip": "^3.10.1"` to `dependencies` (matching the version already pinned in `overrides`; keep the `overrides` entry too — it still forces the version for transitive consumers).
|
|
||||||
- [ ] **Step 2:** Move `"sharp": "^0.34.3"` from `devDependencies` to `dependencies`.
|
|
||||||
- [ ] **Step 3:** Add `"node_modules/sharp/**"` to the `build.asarUnpack` array in `package.json` (alongside the existing `ffmpeg-static` and `assets/fonts` entries) — `sharp` ships native `.node` bindings that must not be packed into `app.asar`.
|
|
||||||
- [ ] **Step 4:** Run `npm install` to regenerate the lockfile, then `npm test` to confirm nothing broke.
|
|
||||||
- [ ] **Step 5:** Commit: `git add package.json package-lock.json && git commit -m "fix(deps): move jszip and sharp to runtime dependencies, unpack sharp from asar"`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase B — Build Out Image/Audio/Video Converter (currently orphaned dead API)
|
|
||||||
|
|
||||||
**Context:** `preload.js` whitelists 16 channels (`image-convert`, `image-batch-convert`, `image-resize`, `image-compress`, `image-rotate`, `audio-convert`, `audio-batch-convert`, `audio-extract`, `audio-trim`, `audio-merge`, `video-convert`, `video-batch-convert`, `video-compress`, `video-trim`, `video-frames`, `video-gif`) and 3 receive channels (`show-image-converter`, `show-audio-converter`, `show-video-converter`), but **zero** `ipcMain` handlers exist for any of them and no menu/UI ever triggers them. This is distinct from the already-working generic "Universal Converter" (`universal-convert`/`universal-convert-batch`, `main.js:2377-2622`) which does plain format-to-format conversion via bare `convertWithImageMagick`/`convertWithFFmpeg` calls with no operation-specific options. Phase B builds the **operation-specific** toolkit (resize/compress/rotate for images; trim/merge/extract for audio; compress/trim/frames/gif for video) as a new `src/main/MediaOperations.js` module, modeled directly on the existing `src/main/PDFOperations.js` pattern (single `executeOperation(operation, data)` dispatcher).
|
|
||||||
|
|
||||||
### Task 9: Image operations backend (`sharp`-based)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Create: `src/main/ImageOperations.js`
|
|
||||||
- Create: `tests/main/ImageOperations.test.js`
|
|
||||||
- Modify: `src/main.js` (register handlers near the PDF operation handlers, ~line 4535)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Produces: `module.exports = { executeOperation, imageConvert, imageResize, imageCompress, imageRotate }` — `executeOperation(operation, data)` where `operation` is one of `'convert' | 'resize' | 'compress' | 'rotate'` and `data` always includes `{ inputPath, outputPath }` plus operation-specific fields below.
|
|
||||||
- `imageConvert(data)`: `data = { inputPath, outputPath, format }` (`format` is one of sharp's supported output formats: `jpeg|png|webp|avif|tiff|gif`) → uses `sharp(inputPath).toFormat(format).toFile(outputPath)`.
|
|
||||||
- `imageResize(data)`: `data = { inputPath, outputPath, width, height, fit }` (`fit` one of `'cover'|'contain'|'fill'|'inside'|'outside'`, default `'inside'`) → `sharp(inputPath).resize({ width, height, fit }).toFile(outputPath)`. `width`/`height` may be `null` (sharp allows omitting one dimension to preserve aspect ratio) but not both.
|
|
||||||
- `imageCompress(data)`: `data = { inputPath, outputPath, quality }` (`quality` integer 1-100, default 80) → route by output extension: jpeg/webp/avif use `{ quality }`, png uses `{ quality, compressionLevel: 9 }`.
|
|
||||||
- `imageRotate(data)`: `data = { inputPath, outputPath, angle }` (`angle` integer degrees, any value — sharp's `.rotate(angle)` handles non-90 multiples by expanding canvas) → `sharp(inputPath).rotate(angle).toFile(outputPath)`.
|
|
||||||
- All four validate `inputPath` exists and is ≤ `MAX_FILE_SIZE` (import the same 50MB constant convention used in `main.js` — pass it in as a parameter from `main.js`, do not redefine a second limit).
|
|
||||||
- All four return `{ success: true, outputPath }` on success or throw an `Error` with a sanitized (no absolute-path leakage beyond what's already the app's convention) message on failure — `main.js` wraps calls in try/catch per the PDFOperations pattern.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write `tests/main/ImageOperations.test.js` covering all four operations against small fixture images (generate fixtures at test time with `sharp` itself — e.g. a 100x100 red PNG buffer — do not commit binary fixtures):
|
|
||||||
```javascript
|
|
||||||
const sharp = require('sharp');
|
|
||||||
const fs = require('fs');
|
|
||||||
const os = require('os');
|
|
||||||
const path = require('path');
|
|
||||||
const ImageOperations = require('../../src/main/ImageOperations');
|
|
||||||
|
|
||||||
describe('ImageOperations', () => {
|
|
||||||
let tmpDir, inputPath;
|
|
||||||
beforeEach(async () => {
|
|
||||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'imgops_'));
|
|
||||||
inputPath = path.join(tmpDir, 'in.png');
|
|
||||||
await sharp({ create: { width: 100, height: 100, channels: 3, background: { r: 255, g: 0, b: 0 } } })
|
|
||||||
.png()
|
|
||||||
.toFile(inputPath);
|
|
||||||
});
|
|
||||||
afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
|
|
||||||
|
|
||||||
test('imageConvert converts PNG to JPEG', async () => {
|
|
||||||
const outputPath = path.join(tmpDir, 'out.jpg');
|
|
||||||
const result = await ImageOperations.imageConvert({ inputPath, outputPath, format: 'jpeg' });
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(fs.existsSync(outputPath)).toBe(true);
|
|
||||||
const meta = await sharp(outputPath).metadata();
|
|
||||||
expect(meta.format).toBe('jpeg');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('imageResize resizes to given width preserving aspect', async () => {
|
|
||||||
const outputPath = path.join(tmpDir, 'out.png');
|
|
||||||
await ImageOperations.imageResize({ inputPath, outputPath, width: 50, height: null, fit: 'inside' });
|
|
||||||
const meta = await sharp(outputPath).metadata();
|
|
||||||
expect(meta.width).toBe(50);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('imageRotate rotates by given angle', async () => {
|
|
||||||
const outputPath = path.join(tmpDir, 'out.png');
|
|
||||||
await ImageOperations.imageRotate({ inputPath, outputPath, angle: 90 });
|
|
||||||
const meta = await sharp(outputPath).metadata();
|
|
||||||
expect(meta.width).toBe(100); // 90deg on square stays square
|
|
||||||
});
|
|
||||||
|
|
||||||
test('imageCompress produces a smaller or equal-size JPEG at low quality', async () => {
|
|
||||||
const jpegPath = path.join(tmpDir, 'in.jpg');
|
|
||||||
await sharp(inputPath).jpeg({ quality: 100 }).toFile(jpegPath);
|
|
||||||
const outputPath = path.join(tmpDir, 'compressed.jpg');
|
|
||||||
await ImageOperations.imageCompress({ inputPath: jpegPath, outputPath, quality: 10 });
|
|
||||||
expect(fs.statSync(outputPath).size).toBeLessThanOrEqual(fs.statSync(jpegPath).size);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('executeOperation dispatches to the correct function', async () => {
|
|
||||||
const outputPath = path.join(tmpDir, 'out.png');
|
|
||||||
const result = await ImageOperations.executeOperation('rotate', { inputPath, outputPath, angle: 180 });
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('unknown operation throws', async () => {
|
|
||||||
await expect(ImageOperations.executeOperation('bogus', {})).rejects.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Run `npx jest tests/main/ImageOperations.test.js` — expect FAIL (module doesn't exist).
|
|
||||||
- [ ] **Step 3:** Implement `src/main/ImageOperations.js` per the interfaces above, using `sharp`. Model the file's shape (JSDoc header, `executeOperation` switch, `module.exports`) on `src/main/PDFOperations.js:404-436`.
|
|
||||||
- [ ] **Step 4:** Run `npx jest tests/main/ImageOperations.test.js` — expect PASS.
|
|
||||||
- [ ] **Step 5:** In `src/main.js`, add a single dispatcher handler near the PDF operation handler (`process-pdf-operation`, ~line 4535):
|
|
||||||
```javascript
|
|
||||||
const ImageOperations = require('./main/ImageOperations');
|
|
||||||
// ...
|
|
||||||
ipcMain.handle('process-image-operation', async (event, { operation, data }) => {
|
|
||||||
try {
|
|
||||||
return await ImageOperations.executeOperation(operation, data);
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: sanitizeErrorMessage(error.message) };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
Note: this collapses the originally-whitelisted 5 separate channel names (`image-convert`, `image-batch-convert`, `image-resize`, `image-compress`, `image-rotate`) into one operation-dispatch channel, matching the existing `process-pdf-operation` pattern — remove the 5 stale names from `ALLOWED_SEND_CHANNELS` in `src/preload.js` and add `'process-image-operation'` in their place (also add `'select-image-folder'` if batch needs folder selection — mirror `select-pdf-folder`). Batch (`image-batch-convert`) is handled in Task 12.
|
|
||||||
- [ ] **Step 6:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 7:** Commit: `git add src/main/ImageOperations.js tests/main/ImageOperations.test.js src/main.js src/preload.js && git commit -m "feat(image): implement sharp-based image operations backend"`
|
|
||||||
|
|
||||||
### Task 10: Audio operations backend (`ffmpeg`-based)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Create: `src/main/AudioOperations.js`
|
|
||||||
- Create: `tests/main/AudioOperations.test.js`
|
|
||||||
- Modify: `src/main.js`
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- `module.exports = { executeOperation, buildConvertArgs, buildTrimArgs, buildExtractArgs, buildMergeArgs }`. Because ffmpeg is an external binary, this module exposes **pure argument-builder functions** (easily unit-testable without invoking a real binary) plus `executeOperation`, which is the only piece that actually spawns ffmpeg via `execFile` — inject the ffmpeg path and an `execFileFn` (defaulting to Node's real `execFile`) as parameters so tests can stub it.
|
|
||||||
- `buildConvertArgs({ inputPath, outputPath, format })` → returns `string[]` args, e.g. `['-i', inputPath, '-y', outputPath]` (format is implied by `outputPath`'s extension — ffmpeg infers it; do not pass a separate `-f` unless `format` is explicitly given and differs from the extension, in which case append `['-f', format]` before `outputPath`).
|
|
||||||
- `buildTrimArgs({ inputPath, outputPath, startTime, duration })` → `['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath]`. `startTime`/`duration` are seconds (numbers), validate they are finite non-negative numbers before building args (throw `Error('Invalid trim range')` otherwise — this is the injection guard, since these become argv elements passed straight to execFile with no shell involved, but malformed values should still fail fast rather than reach ffmpeg).
|
|
||||||
- `buildExtractArgs({ inputPath, outputPath })` → extracts the audio track from a video/audio file: `['-i', inputPath, '-vn', '-acodec', 'copy', '-y', outputPath]` (fallback if codec copy fails: caller retries without `-acodec copy`, letting ffmpeg transcode — implement this retry inside `executeOperation`'s `'extract'` case, not in the pure builder).
|
|
||||||
- `buildMergeArgs({ inputPaths, outputPath })` → `inputPaths` is `string[]` (2+ files) → build a temp concat-list file is the safe approach; but since this module must stay pure/testable, `buildMergeArgs` returns `{ args, concatListContent }` where `concatListContent` is the `file '<path>'` lines the caller writes to a temp file, and `args = ['-f', 'concat', '-safe', '0', '-i', tempListPath, '-c', 'copy', '-y', outputPath]` (caller supplies `tempListPath` after writing the file — see `executeOperation`'s `'merge'` case).
|
|
||||||
- `executeOperation(operation, data, { ffmpegPath, execFileFn } = {})` where `operation` is `'convert'|'trim'|'extract'|'merge'`, defaults `ffmpegPath` to the real `getFFmpegPath()`-resolved path (passed in from `main.js`, not re-implemented here) and `execFileFn` to `require('child_process').execFile`. Returns a Promise resolving `{ success: true, outputPath }`.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write `tests/main/AudioOperations.test.js` testing the pure builders directly (no real ffmpeg spawn needed for these) plus one `executeOperation` test with a stubbed `execFileFn`:
|
|
||||||
```javascript
|
|
||||||
const AudioOperations = require('../../src/main/AudioOperations');
|
|
||||||
|
|
||||||
describe('AudioOperations argument builders', () => {
|
|
||||||
test('buildConvertArgs builds correct ffmpeg args', () => {
|
|
||||||
const args = AudioOperations.buildConvertArgs({ inputPath: '/a.wav', outputPath: '/b.mp3' });
|
|
||||||
expect(args).toEqual(['-i', '/a.wav', '-y', '/b.mp3']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('buildTrimArgs builds correct trim args', () => {
|
|
||||||
const args = AudioOperations.buildTrimArgs({ inputPath: '/a.mp3', outputPath: '/b.mp3', startTime: 5, duration: 10 });
|
|
||||||
expect(args).toEqual(['-i', '/a.mp3', '-ss', '5', '-t', '10', '-y', '/b.mp3']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('buildTrimArgs rejects non-finite startTime', () => {
|
|
||||||
expect(() =>
|
|
||||||
AudioOperations.buildTrimArgs({ inputPath: '/a.mp3', outputPath: '/b.mp3', startTime: NaN, duration: 10 })
|
|
||||||
).toThrow('Invalid trim range');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('buildMergeArgs builds concat-demuxer args and list content', () => {
|
|
||||||
const { args, concatListContent } = AudioOperations.buildMergeArgs({
|
|
||||||
inputPaths: ['/a.mp3', '/b.mp3'],
|
|
||||||
outputPath: '/out.mp3',
|
|
||||||
});
|
|
||||||
expect(concatListContent).toContain("file '/a.mp3'");
|
|
||||||
expect(concatListContent).toContain("file '/b.mp3'");
|
|
||||||
expect(args).toContain('-f');
|
|
||||||
expect(args).toContain('concat');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('AudioOperations.executeOperation', () => {
|
|
||||||
test('convert calls execFileFn with ffmpeg path and args, resolves success', async () => {
|
|
||||||
const execFileFn = (cmd, args, opts, cb) => cb(null, '', '');
|
|
||||||
const result = await AudioOperations.executeOperation(
|
|
||||||
'convert',
|
|
||||||
{ inputPath: '/a.wav', outputPath: '/b.mp3' },
|
|
||||||
{ ffmpegPath: '/usr/bin/ffmpeg', execFileFn }
|
|
||||||
);
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.outputPath).toBe('/b.mp3');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('unknown operation rejects', async () => {
|
|
||||||
await expect(
|
|
||||||
AudioOperations.executeOperation('bogus', {}, { ffmpegPath: '/usr/bin/ffmpeg', execFileFn: () => {} })
|
|
||||||
).rejects.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Run `npx jest tests/main/AudioOperations.test.js` — expect FAIL.
|
|
||||||
- [ ] **Step 3:** Implement `src/main/AudioOperations.js` per the interfaces above. Use `fs.writeFileSync`/`fs.mkdtempSync` (Node `os.tmpdir()`) inside `executeOperation`'s `'merge'` case to materialize the concat list file before invoking `execFileFn`.
|
|
||||||
- [ ] **Step 4:** Run `npx jest tests/main/AudioOperations.test.js` — expect PASS.
|
|
||||||
- [ ] **Step 5:** In `src/main.js`, add the dispatcher handler (mirrors Task 9 Step 5):
|
|
||||||
```javascript
|
|
||||||
const AudioOperations = require('./main/AudioOperations');
|
|
||||||
// ...
|
|
||||||
ipcMain.handle('process-audio-operation', async (event, { operation, data }) => {
|
|
||||||
try {
|
|
||||||
return await AudioOperations.executeOperation(operation, data, { ffmpegPath: getFFmpegPath() });
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: sanitizeErrorMessage(error.message) };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
Replace the 5 stale audio channel names in `ALLOWED_SEND_CHANNELS` (`preload.js`) with `'process-audio-operation'` (batch handled in Task 12).
|
|
||||||
- [ ] **Step 6:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 7:** Commit: `git add src/main/AudioOperations.js tests/main/AudioOperations.test.js src/main.js src/preload.js && git commit -m "feat(audio): implement ffmpeg-based audio operations backend"`
|
|
||||||
|
|
||||||
### Task 11: Video operations backend (`ffmpeg`-based)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Create: `src/main/VideoOperations.js`
|
|
||||||
- Create: `tests/main/VideoOperations.test.js`
|
|
||||||
- Modify: `src/main.js`
|
|
||||||
|
|
||||||
**Interfaces:** Same shape as Task 10 (`executeOperation(operation, data, { ffmpegPath, execFileFn })`, pure arg builders for testability).
|
|
||||||
- `buildConvertArgs({ inputPath, outputPath })` → `['-i', inputPath, '-y', outputPath]`.
|
|
||||||
- `buildCompressArgs({ inputPath, outputPath, crf })` (`crf` 0-51, default 28 — lower is higher quality/larger file, matching libx264 convention) → `['-i', inputPath, '-vcodec', 'libx264', '-crf', String(crf), '-y', outputPath]`. Validate `crf` is an integer 0-51 (throw otherwise).
|
|
||||||
- `buildTrimArgs({ inputPath, outputPath, startTime, duration })` → identical shape/validation to `AudioOperations.buildTrimArgs`.
|
|
||||||
- `buildFramesArgs({ inputPath, outputDir, fps })` (`fps` frames-per-second to extract, default 1) → `['-i', inputPath, '-vf', `fps=${fps}`, path.join(outputDir, 'frame-%04d.png')]`. Validate `fps` is a positive finite number.
|
|
||||||
- `buildGifArgs({ inputPath, outputPath, fps, width })` (`fps` default 10, `width` default 480, height auto via `-1`) → `['-i', inputPath, '-vf', `fps=${fps},scale=${width}:-1:flags=lanczos`, '-y', outputPath]`.
|
|
||||||
- `operation` is `'convert'|'compress'|'trim'|'frames'|'gif'`.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write `tests/main/VideoOperations.test.js` mirroring Task 10's test structure — one test per builder function checking exact `args` array output plus validation-rejection tests for `compress` (bad `crf`) and `frames` (bad `fps`), plus one `executeOperation` test with a stubbed `execFileFn` for `'convert'` and one for `'frames'` that also verifies the output directory is created (`fs.mkdirSync(outputDir, { recursive: true })` inside `executeOperation`'s `'frames'` case before spawning ffmpeg).
|
|
||||||
- [ ] **Step 2:** Run `npx jest tests/main/VideoOperations.test.js` — expect FAIL.
|
|
||||||
- [ ] **Step 3:** Implement `src/main/VideoOperations.js` per the interfaces above.
|
|
||||||
- [ ] **Step 4:** Run `npx jest tests/main/VideoOperations.test.js` — expect PASS.
|
|
||||||
- [ ] **Step 5:** In `src/main.js`, add the dispatcher handler (mirrors B1/B2):
|
|
||||||
```javascript
|
|
||||||
const VideoOperations = require('./main/VideoOperations');
|
|
||||||
// ...
|
|
||||||
ipcMain.handle('process-video-operation', async (event, { operation, data }) => {
|
|
||||||
try {
|
|
||||||
return await VideoOperations.executeOperation(operation, data, { ffmpegPath: getFFmpegPath() });
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: sanitizeErrorMessage(error.message) };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
Replace the 6 stale video channel names in `ALLOWED_SEND_CHANNELS` with `'process-video-operation'`.
|
|
||||||
- [ ] **Step 6:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 7:** Commit: `git add src/main/VideoOperations.js tests/main/VideoOperations.test.js src/main.js src/preload.js && git commit -m "feat(video): implement ffmpeg-based video operations backend"`
|
|
||||||
|
|
||||||
### Task 12: Media Operations UI (menu entries + dialog + batch)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Create: `src/renderer/media-operations-dialog.js` (follow whatever module pattern `src/renderer.js` already uses for the PDF editor dialog — read `renderer.js:3685` onward to find that dialog's implementation file/pattern before creating this one)
|
|
||||||
- Modify: `src/main.js` (menu — add "Image/Audio/Video Tools..." entries under the existing `Tools` submenu, next to Table Generator/ASCII Art Generator at `main.js:1395-1414`; also extend `universal-convert-batch`'s existing batch-folder flow OR add three new `process-*-operation` batch loops mirroring the pattern at `main.js:2454-2563`, whichever requires less duplication once B1-B3 exist — prefer reusing `executeOperation` in a loop over `fs.readdirSync` results, matching the existing batch style)
|
|
||||||
- Modify: `src/preload.js` (add `'show-image-converter'`... already present; add `'process-image-operation'`/`'process-audio-operation'`/`'process-video-operation'` to `ALLOWED_SEND_CHANNELS` if not already added by B1-B3)
|
|
||||||
|
|
||||||
**Verified current behavior:** `show-image-converter`/`show-audio-converter`/`show-video-converter` are whitelisted receive channels with no sender and no listener — Batch Image/Audio/Video Conversion menu items already exist and work via the generic Universal Converter (`main.js:1283-1291`, `2454-2563`) for plain format conversion; this task adds the **operation-specific** single-file dialogs (resize/compress/rotate/trim/merge/extract/frames/gif) that B1-B3 implemented.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Add three menu items under `Tools` (`main.js`, after the "Document Compare" item added conceptually in Task 6/C8):
|
|
||||||
```javascript
|
|
||||||
{ label: 'Image Tools...', click: () => mainWindow.webContents.send('show-image-converter') },
|
|
||||||
{ label: 'Audio Tools...', click: () => mainWindow.webContents.send('show-audio-converter') },
|
|
||||||
{ label: 'Video Tools...', click: () => mainWindow.webContents.send('show-video-converter') },
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Build the renderer-side dialog module. Read how the existing PDF Editor dialog (triggered by `show-pdf-editor-dialog`) is structured/rendered in `renderer.js` (search for its listener at line 3685 and follow into whatever function/file builds its DOM) and replicate that construction pattern for a single dialog that: (a) lets the user pick an operation from a dropdown scoped to the current media kind (image/audio/video), (b) shows the relevant operation-specific fields (e.g. width/height for resize, quality for compress, angle for rotate, startTime/duration for trim, fps/width for gif), (c) has an input-file picker (reuse the existing `dialog.showOpenDialogSync` pattern via a new small `ipcMain.handle('select-media-file', ...)` if no generic file-picker IPC already exists — check first; `select-pdf-folder` is folder-only, so a new single-file-picker handler is likely needed), (d) calls `ipcRenderer.invoke('process-image-operation', { operation, data })` (or audio/video) and shows success/error the same way `pdf-operation-complete`/`pdf-operation-error` are surfaced elsewhere.
|
|
||||||
- [ ] **Step 3:** Wire the three `ipcRenderer.on('show-image-converter'|'show-audio-converter'|'show-video-converter', ...)` listeners in `renderer.js` to open the new dialog scoped to the right media kind.
|
|
||||||
- [ ] **Step 4:** Manually verify with `npm start`: Tools → Image Tools → Resize a test PNG, confirm the output file is created at the chosen size; repeat once each for one audio op (trim) and one video op (compress) using any small local test media file.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(media): add Image/Audio/Video Tools dialogs wired to new operation backends"`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase C — New Features (extending existing systems)
|
|
||||||
|
|
||||||
### Task 13: Expose more Pandoc export/import formats already supported by the bundled Pandoc
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main.js` (export submenu ~`main.js:864-959`; `exportFile()` at `main.js:1766`; the format switch inside `performExportWithOptions`/`buildPandocExportArgs` — see Task 23, which replaces string-building with an args-array builder; add cases there, not to the old string-concat code)
|
|
||||||
|
|
||||||
**New formats to add** (all already importable per the existing import switch at `main.js:3507` — Pandoc supports both directions for each):
|
|
||||||
- Export: AsciiDoc (`asciidoc`), reStructuredText (`rst`), MediaWiki (`mediawiki`), Org-mode (`org`), Textile (`textile`), man page (`man`), Jupyter Notebook (`ipynb`).
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Add 7 new menu entries to the Export submenu (`main.js:864-959`), grouped in a new labeled section, each calling `exportFile('<format>')` with the format id above.
|
|
||||||
- [ ] **Step 2:** Add each format to the extension-mapping table used by the export path (the `formatExtMap` object at `main.js:2624-2629` — add `asciidoc: 'adoc', mediawiki: 'wiki'`; the rest already match their format id as extension).
|
|
||||||
- [ ] **Step 3:** RULING (pre-flight scan, execution order is Phase A→B→C→D, so Task 23 has NOT run yet when this task executes): add each format as an additional `-t <format>` case to the **current** string-concatenation `pandocCmd` logic in `performExportWithOptions` (the same pattern already used for `'json'`, `'beamer'`, `'jira'` etc. around `main.js:2825-2965` — a simple `pandocCmd = \`${getPandocPath()} "${currentFile}" -t <format> -o "${outputFile}"\`; exportWithPandoc(pandocCmd, outputFile, format);` branch per new format is sufficient; do not introduce any new string-interpolated user-controlled fields — these 7 formats take no extra options beyond the standard ones already handled generically above the format switch). When Task 23 runs later (Phase D) it will read the current state of this function, per its own Step 3 instruction to "read every one of the sites... in full," and MUST carry these 7 new cases into its args-array rewrite — that responsibility already belongs to SEC-1's own scope and needs no separate action here.
|
|
||||||
- [ ] **Step 4:** Manually verify: export the currently-open sample markdown file to each of the 7 new formats, confirm each produces a non-empty output file Pandoc itself can round-trip (`pandoc out.rst -o roundtrip.md` succeeds).
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add src/main.js && git commit -m "feat(export): expose AsciiDoc, RST, MediaWiki, Org, Textile, man, ipynb export formats"`
|
|
||||||
|
|
||||||
### Task 14: Git branch / diff / push / pull
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main/GitOperations.js`
|
|
||||||
- Modify: `tests/` (find and extend the existing GitOperations test file — grep `tests/**/GitOperations*`; if none exists, create `tests/main/GitOperations.test.js`)
|
|
||||||
- Modify: `src/main.js` (register 4 new `ipcMain.handle` calls near the existing git handlers, `main.js:4889-4904`)
|
|
||||||
- Modify: `src/preload.js` (add `'git-branch'`, `'git-diff'` is already listed but unhandled — see below, `'git-push'`, `'git-pull'` to `ALLOWED_SEND_CHANNELS`)
|
|
||||||
- Modify: `src/sidebar/git-panel.js`, `src/renderer.js:1714-1731`
|
|
||||||
|
|
||||||
**Interfaces (add to `GitOperations.js`, matching the existing `try { ... } catch (err) { return { error: err.message } }` pattern used by every existing function there):**
|
|
||||||
```javascript
|
|
||||||
async function diff(dir, file) { /* git.diff([file]) if file given, else git.diff() for full working-tree diff */ }
|
|
||||||
async function branches(dir) { /* git.branchLocal() — returns { all, current, branches } */ }
|
|
||||||
async function checkoutBranch(dir, name, isNew) { /* isNew=true: git.checkoutLocalBranch(name); else git.checkout(name) */ }
|
|
||||||
async function push(dir) { /* git.push() */ }
|
|
||||||
async function pull(dir) { /* git.pull() */ }
|
|
||||||
module.exports = { getStatus, stage, commit, log, diff, branches, checkoutBranch, push, pull };
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write/extend the Jest test file covering `diff`, `branches`, `checkoutBranch`, `push`, `pull` against a real temp git repo (follow whatever fixture pattern the existing Git-related tests use — if this is the first GitOperations test file, initialize a repo with `simple-git` itself inside `beforeEach` using `fs.mkdtempSync` + `simpleGit(tmpDir).init()`, matching how `simple-git` is already used in the module under test).
|
|
||||||
- [ ] **Step 2:** Run the new tests — expect FAIL (functions don't exist).
|
|
||||||
- [ ] **Step 3:** Implement the 5 new functions in `GitOperations.js` per the interfaces above.
|
|
||||||
- [ ] **Step 4:** Run the tests — expect PASS.
|
|
||||||
- [ ] **Step 5:** In `main.js`, register handlers next to the existing 4:
|
|
||||||
```javascript
|
|
||||||
ipcMain.handle('git-diff', async (event, { file }) => {
|
|
||||||
const dir = path.dirname(currentFile || app.getPath('documents'));
|
|
||||||
return GitOperations.diff(dir, file);
|
|
||||||
});
|
|
||||||
ipcMain.handle('git-branches', async () => GitOperations.branches(path.dirname(currentFile || app.getPath('documents'))));
|
|
||||||
ipcMain.handle('git-checkout', async (event, { name, isNew }) => GitOperations.checkoutBranch(path.dirname(currentFile || app.getPath('documents')), name, isNew));
|
|
||||||
ipcMain.handle('git-push', async () => GitOperations.push(path.dirname(currentFile || app.getPath('documents'))));
|
|
||||||
ipcMain.handle('git-pull', async () => GitOperations.pull(path.dirname(currentFile || app.getPath('documents'))));
|
|
||||||
```
|
|
||||||
(Match whatever `dir` resolution the existing `git-status` handler at `main.js:4889-4891` actually uses — read those 3 lines first and reuse the identical expression rather than inventing a new one.)
|
|
||||||
- [ ] **Step 6:** Add `'git-branches'`, `'git-checkout'`, `'git-push'`, `'git-pull'` to `ALLOWED_SEND_CHANNELS` in `preload.js` (`'git-diff'` is already present).
|
|
||||||
- [ ] **Step 7:** In `src/sidebar/git-panel.js`, rename the unused `_gitDiff` parameter to `gitDiff` and add UI to actually call it (a "diff" button/icon per changed file in the status list, rendering the returned diff text in a `<pre>` block or similar — follow the panel's existing rendering style for the status list). Add branch/push/pull UI following the same panel's existing button/section style.
|
|
||||||
- [ ] **Step 8:** In `renderer.js:1714-1731`, pass the 4 new callbacks (`gitBranches`, `gitCheckout`, `gitPush`, `gitPull`) into `getRenderGitPanel()` alongside the existing ones.
|
|
||||||
- [ ] **Step 9:** Manually verify in a real git-tracked test folder: view a file diff, list branches, create+checkout a new branch, (push/pull only if a real remote is available — otherwise verify the IPC round-trip returns a sane `{error: ...}` for a repo with no remote, not a crash).
|
|
||||||
- [ ] **Step 10:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 11:** Commit: `git add -A && git commit -m "feat(git): add diff, branch, checkout, push, pull to Git sidebar panel"`
|
|
||||||
|
|
||||||
### Task 15: More PDF operations — extract text, page numbers, crop, extract images
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main/PDFOperations.js`, its test file (grep `tests/**/PDFOperations*`)
|
|
||||||
- Modify: `src/main.js` (`process-pdf-operation` already dispatches via `executeOperation` — no new handler needed, just new `case`s in `PDFOperations.js`'s existing switch at line 404)
|
|
||||||
- Modify: renderer PDF editor dialog UI (wherever the existing operation list/buttons are — find via the `show-pdf-editor-dialog` listener at `renderer.js:3685`)
|
|
||||||
|
|
||||||
**Interfaces (add to the existing `executeOperation` switch, `PDFOperations.js:404-430`):**
|
|
||||||
```javascript
|
|
||||||
async function pdfExtractText(data) { /* data: {inputPath}. Use pdf-lib's page.getTextContent() is NOT available in pdf-lib — pdf-lib has no text extraction. Use pdfjs-dist (already a dependency) instead: load with pdfjs-dist, iterate pages, getTextContent(), join strings. Return { success: true, text } */ }
|
|
||||||
async function pdfAddPageNumbers(data) { /* data: {inputPath, outputPath, position, startNumber}. For each page, drawText via pdf-lib at the given corner (reuse the position-mapping switch already present in pdfWatermark, PDFOperations.js:258-287, for corner math). */ }
|
|
||||||
async function pdfCrop(data) { /* data: {inputPath, outputPath, margins: {top,bottom,left,right}} in points. Use page.setCropBox(x, y, width, height) computed from the page's existing MediaBox minus margins. */ }
|
|
||||||
async function pdfExtractImages(data) { /* data: {inputPath, outputDir}. pdf-lib doesn't expose embedded image extraction either — use pdfjs-dist's page.getOperatorList() + page.objs to pull OPS.paintImageXObject image data, write each as PNG via sharp (already a dependency after Task 8). Return { success: true, count, files: string[] } */ }
|
|
||||||
```
|
|
||||||
Add 4 new `case` branches to `executeOperation` (`'extractText'`, `'pageNumbers'`, `'crop'`, `'extractImages'`) and add all 4 to `module.exports`.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Read `PDFOperations.js:233-317` (`pdfWatermark`) in full to reuse its exact position-to-coordinate mapping logic for `pdfAddPageNumbers` rather than re-deriving it.
|
|
||||||
- [ ] **Step 2:** Write tests for all 4 new functions in the existing PDFOperations test file, generating a minimal test PDF at test time via `pdf-lib`'s `PDFDocument.create()` (mirror however the existing test file already builds its fixture PDFs — check its `beforeEach`).
|
|
||||||
- [ ] **Step 3:** Run new tests — expect FAIL.
|
|
||||||
- [ ] **Step 4:** Implement the 4 functions.
|
|
||||||
- [ ] **Step 5:** Run new tests — expect PASS.
|
|
||||||
- [ ] **Step 6:** Add 4 corresponding buttons/menu entries to the PDF editor dialog UI, following its existing per-operation button pattern exactly (find where 'Watermark' or 'Rotate' is wired in the renderer PDF dialog and copy that structure).
|
|
||||||
- [ ] **Step 7:** Manually verify each of the 4 operations against a real PDF via the app UI.
|
|
||||||
- [ ] **Step 8:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 9:** Commit: `git add -A && git commit -m "feat(pdf): add extract text, page numbers, crop, extract images operations"`
|
|
||||||
|
|
||||||
### Task 16: PDF form field fill/flatten
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main/PDFOperations.js` (+ test file), PDF editor dialog UI
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
```javascript
|
|
||||||
async function pdfGetFormFields(data) { /* data: {inputPath}. PDFDocument.load(bytes) -> pdfDoc.getForm().getFields() -> map each to {name, type, value}. Return { success: true, fields } */ }
|
|
||||||
async function pdfFillForm(data) { /* data: {inputPath, outputPath, values: Record<string,string>, flatten}. Load, getForm(), for each key in values call form.getTextField(key).setText(value) (wrap per-field in try/catch to skip fields that don't exist or aren't text fields — this app's convention per pdfWatermark is to fail loudly on real errors but this is a batch-of-independent-fields case, so log+skip per-field failures and continue). If flatten, call form.flatten() before saving. */ }
|
|
||||||
```
|
|
||||||
Add `'formFields'` (get) and `'fillForm'` cases to `executeOperation`, add both to exports.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write tests building a test PDF with an AcroForm text field via `pdf-lib`'s `form.createTextField()` API (check pdf-lib's docs/existing usage in the codebase for the exact field-creation calls — `PDFOperations.js` already imports `pdf-lib`, follow its existing import style).
|
|
||||||
- [ ] **Step 2:** Run tests — expect FAIL.
|
|
||||||
- [ ] **Step 3:** Implement both functions.
|
|
||||||
- [ ] **Step 4:** Run tests — expect PASS.
|
|
||||||
- [ ] **Step 5:** Add a "Fill Form" UI entry to the PDF editor dialog: on open, call `formFields` to list detected fields, render a text input per field, a "Flatten after fill" checkbox, then call `fillForm` on submit.
|
|
||||||
- [ ] **Step 6:** Manually verify against a real fillable PDF (search for one under `tests/fixtures/` or create one with `pdf-lib` in a scratch script — do not commit the scratch script).
|
|
||||||
- [ ] **Step 7:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 8:** Commit: `git add -A && git commit -m "feat(pdf): add form field detection, fill, and flatten"`
|
|
||||||
|
|
||||||
### Task 17: Plugin API — export-format and file-reader registration hooks
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/plugins/plugin-context.js`, `src/plugins/plugin-loader.js` (or wherever plugin manifests are validated/loaded — grep `plugin-loader.js`), `src/main.js` (export format switch — needs to consult plugin-registered formats)
|
|
||||||
|
|
||||||
**Interfaces (extend `PluginContext`, `plugin-context.js:64-71`, alongside the existing `this.exports` block):**
|
|
||||||
```javascript
|
|
||||||
this.formats = {
|
|
||||||
registerExportFormat: (id, opts) => {
|
|
||||||
// opts: { label, extension, handler: async (markdownContent, outputPath, options) => void }
|
|
||||||
if (formatRegistry) formatRegistry.register(`${pluginId}:${id}`, opts);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
```
|
|
||||||
This requires a new small `FormatRegistry` (mirror the existing `plugin-registry.js` pattern — read it first to match its exact API shape, e.g. `register(id, opts)` / `getAll()` / `get(id)`) injected into `PluginContext`'s constructor `deps` alongside `sidebar`/`commands`/`statusBar`.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Read `src/plugins/plugin-registry.js` in full to learn its exact class/function shape before adding a sibling `FormatRegistry` (or extending the existing registry with a new namespace if it's already generic enough — prefer extending over duplicating if the existing registry is namespace-agnostic).
|
|
||||||
- [ ] **Step 2:** Add `registerExportFormat` to `PluginContext` per the interface above, wired to whatever registry mechanism Step 1 determined is the right fit.
|
|
||||||
- [ ] **Step 3:** In `src/main.js`'s export dispatch path (wherever the Export submenu's dynamic entries would need to merge in plugin formats — likely requires the Export submenu to be rebuilt after plugin load, similar to how `createMenu()` is already called after recent-files change in Task 2; check if `createMenu()` is idempotent/safe to call after plugin loading completes), add plugin-registered formats as additional Export submenu entries whose `click` handler calls the plugin's registered `handler` function instead of Pandoc.
|
|
||||||
- [ ] **Step 4:** Update the built-in `writing-studio` plugin's manifest/index (`src/plugins/built-in/`) with a trivial example usage of `registerExportFormat` (e.g. exporting sprint data as a `.txt` summary) — this both documents the new API and gives Step 5's manual test something concrete to click.
|
|
||||||
- [ ] **Step 5:** Write a unit test in `tests/plugins/` (find the existing plugin test directory/pattern) verifying a plugin calling `context.formats.registerExportFormat(...)` results in the registry containing the namespaced entry.
|
|
||||||
- [ ] **Step 6:** Manually verify: `npm start`, confirm the writing-studio example format appears in the Export menu and produces the expected output file when clicked.
|
|
||||||
- [ ] **Step 7:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 8:** Commit: `git add -A && git commit -m "feat(plugins): add export-format registration hook to plugin API"`
|
|
||||||
|
|
||||||
### Task 18: DOCX/EPUB template gallery UI
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (export dialog for DOCX/EPUB — find via `exportWordWithTemplate()` at `main.js:881` and follow into whatever renderer dialog it opens)
|
|
||||||
- Modify: `src/main.js` (wherever the existing Word-template list is sourced from — grep `WordTemplateExporter` and `listTemplates`/`getTemplates`-style function)
|
|
||||||
|
|
||||||
**Verified context:** `main.js` already has `exportWordWithTemplate()` and `WordTemplateExporter` (`src/wordTemplateExporter.js`) — a template mechanism for DOCX exists but per the feature-inventory research pass has "no discoverable UI" for browsing available templates; the user has to already know a template exists. Read `src/wordTemplateExporter.js` in full first to learn how templates are currently listed/selected (is there a folder of `.dotx`/`.docx` template files? A hardcoded list?) before designing the gallery.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Read `src/wordTemplateExporter.js` and the renderer dialog `exportWordWithTemplate()` opens, to learn the exact current template-selection mechanism (function names, data shape).
|
|
||||||
- [ ] **Step 2:** Add a visual gallery (grid of template name + thumbnail-if-available, or name + short description if no thumbnails exist) to that same dialog, replacing or augmenting whatever minimal selector currently exists, following the dialog's existing CSS/markup conventions (check `src/styles.css` for the dialog's existing classes before inventing new ones).
|
|
||||||
- [ ] **Step 3:** Do the same for EPUB export if `main.js` has an equivalent EPUB-template mechanism (grep for `epub` + `template`); if none exists, skip EPUB (do not invent a template system that doesn't exist — note this explicitly as out of scope in the commit message rather than silently dropping it).
|
|
||||||
- [ ] **Step 4:** Manually verify: open the DOCX export dialog, see the template gallery, pick one, confirm the exported DOCX uses it.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(export): add visual template gallery to DOCX export dialog"`
|
|
||||||
|
|
||||||
### Task 19: CSV-to-markdown-table toolbar converter
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (editor toolbar — find the existing toolbar button registration pattern, e.g. near table generator/ASCII generator toolbar buttons)
|
|
||||||
|
|
||||||
**Verified context:** Pandoc already imports CSV (`main.js:3507` import switch includes `csv`). This task adds a quick in-editor action: paste/select CSV-like text, convert to a markdown table without leaving the editor (distinct from the full file-import path).
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Add a toolbar button "CSV → Table" (or a Command Palette entry, matching whichever pattern is more consistent with similar single-action editor tools already in the toolbar — check what's already there before choosing).
|
|
||||||
- [ ] **Step 2:** Implement a pure client-side CSV→Markdown-table converter function in `renderer.js` (no need to round-trip through Pandoc for this simple case — parse the current selection's lines by comma, respecting basic double-quote-wrapped fields containing commas; build a `| a | b |` / `|---|---|` markdown table). Keep this function small and testable — extract it to `src/lib/csv-to-markdown-table.js` if `src/renderer.js` doesn't already have a `src/lib/`-style extraction pattern for similar pure functions (check first).
|
|
||||||
- [ ] **Step 3:** Write a Jest unit test for the converter function covering: simple CSV, quoted fields containing commas, ragged rows (fewer columns in some rows — pad with empty cells), empty input.
|
|
||||||
- [ ] **Step 4:** Wire the toolbar button to: read the editor selection, run the converter, replace the selection with the resulting markdown table.
|
|
||||||
- [ ] **Step 5:** Manually verify: select a few lines of comma-separated text in the editor, click the button, confirm it becomes a proper markdown table.
|
|
||||||
- [ ] **Step 6:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 7:** Commit: `git add -A && git commit -m "feat(editor): add CSV-to-markdown-table toolbar converter"`
|
|
||||||
|
|
||||||
### Task 20: Document Compare / diff view (completes Task 6)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (new listener for `show-document-compare`, whitelisted in Task 6)
|
|
||||||
- Create: `src/renderer/document-compare-dialog.js` (or inline in `renderer.js` if that's the dominant pattern for similar dialogs — match Task 12's finding on dialog-module conventions)
|
|
||||||
|
|
||||||
**Verified context:** `main.js:1411-1413` sends `show-document-compare`; Task 6 whitelisted the channel; nothing renders it yet. This task adds an actual two-pane diff: either two arbitrary local files, or (leveraging Task 14's new `GitOperations.diff`) the current file against its last-committed git revision.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Build a simple two-file diff dialog: two "choose file" buttons (or one defaulting to the currently-open tab + one file picker for the comparison target), a line-by-line diff render. Do not add a new diff-algorithm dependency — write a minimal LCS-based line diff in a small pure function (`src/lib/line-diff.js`) since the app has no existing diff library; keep it under ~60 lines (standard textbook LCS-diff, not a full Myers-diff library port).
|
|
||||||
- [ ] **Step 2:** Write a Jest unit test for the line-diff function: identical files (no diffs), pure additions, pure deletions, mixed changes.
|
|
||||||
- [ ] **Step 3:** Add a "Compare with Git HEAD" option in the same dialog when the current file is inside a git repo, using `GitOperations.diff` from Task 14 (raw git diff text render, separate code path from the line-diff function — git's own diff output is already a diff, don't re-diff it).
|
|
||||||
- [ ] **Step 4:** Wire `ipcRenderer.on('show-document-compare', () => { /* open the dialog */ })` in `renderer.js`.
|
|
||||||
- [ ] **Step 5:** Manually verify: Tools → Document Compare, compare two local markdown files, confirm additions/deletions are visually distinguished (e.g. green/red line backgrounds, matching the app's existing theme CSS variables rather than hardcoded colors).
|
|
||||||
- [ ] **Step 6:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 7:** Commit: `git add -A && git commit -m "feat(compare): implement Document Compare dialog with local-diff and git-HEAD-diff modes"`
|
|
||||||
|
|
||||||
### Task 21: Export presets/profiles
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main.js` (near `get-header-footer-settings`/`save-header-footer-settings` handlers, `main.js:1857-1886`)
|
|
||||||
- Modify: renderer export-options dialog (wherever `export-with-options` is invoked from — grep `export-with-options` in `renderer.js`)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
```javascript
|
|
||||||
// main.js — new handlers, settings persisted the same way header/footer settings already are
|
|
||||||
// (read main.js:1857-1886 first to copy its exact settings-file read/write pattern, e.g. settings.json path + key)
|
|
||||||
ipcMain.handle('get-export-presets', async () => { /* returns array of {id, name, format, options} */ });
|
|
||||||
ipcMain.handle('save-export-preset', async (event, preset) => { /* upsert by id, persist, return updated list */ });
|
|
||||||
ipcMain.handle('delete-export-preset', async (event, presetId) => { /* remove by id, persist, return updated list */ });
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Read `main.js:1857-1886` in full to learn the exact settings-persistence pattern already used (this app uses a custom JSON file store per `CLAUDE.md`, not `electron-store` — confirm the exact file/key convention and reuse it verbatim for presets, e.g. a new top-level `exportPresets` array in the same `settings.json`).
|
|
||||||
- [ ] **Step 2:** Implement the 3 handlers per the interfaces above, add all 3 channel names to `ALLOWED_SEND_CHANNELS` in `preload.js`.
|
|
||||||
- [ ] **Step 3:** In the renderer's export-options dialog, add a "Save as preset" button (captures the current dialog's option values, prompts for a name, calls `save-export-preset`) and a preset dropdown at the top of the dialog (populated via `get-export-presets` on open; selecting one pre-fills the dialog's fields) plus a delete icon per preset row.
|
|
||||||
- [ ] **Step 4:** Manually verify: configure export options, save as a preset, close and reopen the dialog, confirm the preset is selectable and correctly restores all fields; delete it, confirm it's gone.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(export): add save/select/delete export presets"`
|
|
||||||
|
|
||||||
### Task 22: Batch PDF operations UI (beyond format conversion)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/renderer.js` (Batch menu handling — find the `show-batch-converter` listener with `'pdf'` type)
|
|
||||||
- Modify: `src/main.js` (extend the batch loop to support PDFOperations, not just format conversion)
|
|
||||||
|
|
||||||
**Verified context:** `main.js:1293-1296` already has a "Batch PDF Conversion..." menu item sending `show-batch-converter` with type `'pdf'`, but (per the existing batch conversion handlers at `main.js:2454-2563`) batch only does format conversion via `convertWithLibreOffice`/pandoc — it never calls into `PDFOperations.executeOperation` for bulk watermark/compress/rotate across many files.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** In the renderer's batch dialog (wherever the `'pdf'`-typed batch dialog renders), add an operation-type selector when the batch type is `'pdf'`: "Convert format" (existing behavior, keep as default) vs. "Bulk PDF Operation" (new: pick one of merge/split/compress/rotate/watermark/etc. plus that operation's fields, same fields as the single-file PDF editor dialog).
|
|
||||||
- [ ] **Step 2:** Add a new `ipcMain.on('batch-pdf-operation', async (event, { operation, data, inputFolder, includeSubfolders }) => {...})` handler in `main.js` that collects matching `.pdf` files (reuse the exact `collectFiles` recursive helper already defined inside `universal-convert-batch`, `main.js:2472-2484` — extract it to a shared top-level function if it isn't already, since Task 22 needs the identical logic) and calls `PDFOperations.executeOperation(operation, {...data, inputPath: filePath, outputPath: ...})` per file in a loop, reporting progress via `mainWindow.webContents.send('batch-progress', ...)` matching the existing batch progress-reporting convention.
|
|
||||||
- [ ] **Step 3:** Add `'batch-pdf-operation'` to `ALLOWED_SEND_CHANNELS`.
|
|
||||||
- [ ] **Step 4:** Manually verify: batch-watermark a folder of 2-3 test PDFs, confirm each output file has the watermark applied.
|
|
||||||
- [ ] **Step 5:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(pdf): add bulk PDF operations (watermark/compress/rotate/etc.) to batch converter"`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase D — Security Remediation
|
|
||||||
|
|
||||||
### Task 23: Fix Pandoc argument-injection vulnerability (CRITICAL)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main.js` (every `pandocCmd` string-concatenation site: `performExportWithOptions` ~`2623-2965`, `exportPDFViaWordTemplate`-adjacent function ~`2980-3050`, `runPandocCmd`/`parseCommand` at `231-282`, the import-side builder at `~3501`, and the enhanced-export builder at `~3997-4097`)
|
|
||||||
- Modify: `tests/` (new regression test)
|
|
||||||
|
|
||||||
**Verified root cause:** `performExportWithOptions` and its siblings build a shell-style command **string** by concatenating user-influenced values (export dialog fields: `options.template`, `options.metadata` key/values, `options.variables` key/values, `options.bibliography` path, `options.csl` path, `options.geometry`, footer text, CSS file path) wrapped in double quotes, e.g. `` pandocCmd += ` --bibliography="${options.bibliography}"` ``. This string is later tokenized by `parseCommand()` (`main.js:253-282`) — a hand-rolled parser that toggles an `inQuotes` flag on any `"` or `'` character and has **no backslash-escape handling at all**. The `.replace(/"/g, '\\"')` escaping applied to `metadata`/`variables` values therefore does nothing protective: `parseCommand` sees the literal backslash as an ordinary character and the following `"` still toggles quote state exactly as an unescaped quote would. Any field that reaches `parseCommand` un-sanitized (which is most of them — `template`, `bibliography`, `csl`, `geometry`, footer text are never escaped at all) lets an attacker-controlled value containing a `"` character break out of its intended single argument and inject additional argv elements into the `execFile(pandocPath, args, ...)` call at the end of `runPandocCmd`. Because `execFile` (not `exec`) is used, this is **not** a shell-injection (no `;`, `|`, backticks interpreted) — it is **argument injection into pandoc itself**, which is still exploitable: Pandoc supports `--lua-filter=<path>` and `--filter=<path>` (arbitrary Lua/executable code execution), `-o <path>` (arbitrary file overwrite by injecting a second `-o`), and `--resource-path`/`--extract-media` (arbitrary-path writes). A malicious value in any of the un-escaped fields above is enough to reach that severity — no shell metacharacters are even needed, just a `"` followed by a new flag.
|
|
||||||
|
|
||||||
**Fix approach:** Stop building command strings entirely for every one of these call sites. Replace with direct `execFile(pandocPath, argsArray, ...)` calls where `argsArray` is built as a real JS array (`push`, never string interpolation) — this is exactly what `PDFOperations.js`/`GitOperations.js` already do correctly, and what `AudioOperations.js`/`VideoOperations.js`/`ImageOperations.js` do from Phase B. `parseCommand`/`runPandocCmd`'s string-based indirection should be deleted once all call sites are converted — do not leave it in place as unused dead code (would violate the "no forbidden markers/half-finished" standard); if any call site turns out to be legitimately hard to convert in this task, that is a signal that call site needs its own careful sub-step, not a reason to keep the vulnerable helper around "just in case."
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Write a regression test proving the vulnerability exists in the *current* code, in a new file `tests/main/pandoc-arg-safety.test.js`, calling `parseCommand` directly (it will need to be exported from `main.js` for testing, or extracted first — see Step 2) with a crafted value and asserting it does NOT produce an injected extra argument:
|
|
||||||
```javascript
|
|
||||||
// This test is written to FAIL against the current parseCommand implementation,
|
|
||||||
// proving the vulnerability, then PASS once Step 3+ removes the vulnerable path.
|
|
||||||
const { buildPandocArgs } = require('../../src/main/PandocArgs'); // new module created in Step 3
|
|
||||||
|
|
||||||
test('a bibliography path containing a double quote cannot inject extra pandoc flags', () => {
|
|
||||||
const malicious = '/tmp/x.bib" --lua-filter=/tmp/evil.lua -o "/tmp/x.bib';
|
|
||||||
const args = buildPandocArgs({
|
|
||||||
inputFile: '/in.md',
|
|
||||||
outputFile: '/out.pdf',
|
|
||||||
format: 'pdf',
|
|
||||||
options: { bibliography: malicious },
|
|
||||||
});
|
|
||||||
// The malicious string must appear as exactly ONE argv element (whatever
|
|
||||||
// value it ends up as), never split into multiple args, and
|
|
||||||
// '--lua-filter=/tmp/evil.lua' must not appear as its own array element.
|
|
||||||
expect(args).not.toContain('--lua-filter=/tmp/evil.lua');
|
|
||||||
expect(args.filter((a) => a.includes(malicious) || a === malicious).length).toBeLessThanOrEqual(1);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
- [ ] **Step 2:** Run the test — confirm it fails to even import (module doesn't exist yet) — this is expected; proceed to build the real module.
|
|
||||||
- [ ] **Step 3:** Create `src/main/PandocArgs.js` — a pure module exporting `buildPandocArgs({ inputFile, outputFile, format, options })` that returns a plain `string[]` args array (no string concatenation of the whole command — only individual argv elements are ever created via `.push(...)`), reimplementing every option currently handled across the string-building sites (`toc`, `tocDepth`, `numberSections`, `citeproc`, `bibliography`, `csl`, `template`, `metadata` (loop → `push('-M', `${key}=${value}`)` — no manual quote-escaping needed at all, since array elements are passed to `execFile` as literal argv, never re-parsed), `variables` (same pattern with `-V`), `pdfEngine`, `geometry`, monospace font header include, footer text). Read every one of the sites listed in "Files" above in full before writing this, to ensure no option is silently dropped.
|
|
||||||
- [ ] **Step 4:** Run the Step 1 test — expect PASS now.
|
|
||||||
- [ ] **Step 5:** Replace every call site that currently builds a `pandocCmd` string and calls `runPandocCmd(pandocCmd, ...)` with: build args via `PandocArgs.buildPandocArgs(...)`, then `execFile(getPandocPath(), args, { maxBuffer: 10 * 1024 * 1024 }, callback)` directly — inline this or add a tiny `runPandocArgs(args, callback)` helper next to the deleted `runPandocCmd` to avoid repeating the `execFile` options object at every site.
|
|
||||||
- [ ] **Step 6:** Delete `parseCommand` and the old `runPandocCmd` (`main.js:231-282`) once no call site references them (grep to confirm zero remaining references before deleting).
|
|
||||||
- [ ] **Step 7:** Manually re-run every export format the app supports (or at minimum: PDF, DOCX, HTML, EPUB, LaTeX — the ones with the most option surface) via the UI, confirming exports still succeed with the new args-array path, including with TOC/metadata/bibliography options actually filled in (not just defaults) to catch any option silently dropped in Step 3.
|
|
||||||
- [ ] **Step 8:** `npm run lint && npm test`
|
|
||||||
- [ ] **Step 9:** Commit: `git add -A && git commit -m "fix(security): eliminate pandoc argument-injection vector by building execFile args arrays directly"`
|
|
||||||
|
|
||||||
### Task 24: Formal security-review pass
|
|
||||||
|
|
||||||
**Files:** N/A — process task.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Invoke the `security-review` skill against the full working tree (post Phase A/B/C/SEC-1 changes) to catch anything beyond what this plan's manual audit already found — particularly re-check the new `AudioOperations`/`VideoOperations`/`ImageOperations` modules and the new file-picker/batch handlers added in Phase B/C for the same class of injection risk (all must use `execFile` with array args — verify none of them slipped into string-building), and check the new plugin `registerExportFormat` hook (Task 17) for arbitrary-code-execution risk if a malicious/compromised plugin could abuse it beyond what a plugin can already do.
|
|
||||||
- [ ] **Step 2:** For every finding the skill reports, triage severity and either fix inline (Critical/High) or explicitly log as an accepted/deferred risk with reasoning (Medium/Low) — do not silently drop findings.
|
|
||||||
- [ ] **Step 3:** Produce a short written security summary (what was found across both the manual audit and the formal pass, what was fixed, what if anything was deferred and why) and save it to `docs/superpowers/plans/2026-08-23-security-assessment-summary.md`.
|
|
||||||
- [ ] **Step 4:** Commit any additional fixes with individual, scoped commit messages (do not batch unrelated security fixes into one commit).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase E — Rebuild Local Release
|
|
||||||
|
|
||||||
### Task 25: Full verification + local build
|
|
||||||
|
|
||||||
**Files:** N/A — build/verification task.
|
|
||||||
|
|
||||||
- [ ] **Step 1:** `npm run lint` — must pass clean.
|
|
||||||
- [ ] **Step 2:** `npm run format:check` — must pass clean (run `npm run format` first if not).
|
|
||||||
- [ ] **Step 3:** `npm test` — all suites must pass; confirm the total test count has grown from the 247-test baseline (new tests from Phase B/C tasks should be present).
|
|
||||||
- [ ] **Step 4:** `npm run download-tools` (ensures bundled Pandoc/tool binaries are current for the build).
|
|
||||||
- [ ] **Step 5:** `npm run build:local` (per `package.json` script — builds Linux + Windows targets; this matches "local release" for this dev machine's platform(s)). If this machine is Linux-only and Windows cross-build tooling (wine, etc.) isn't available, fall back to `npm run build:linux-ci` and note the Windows build was skipped and why.
|
|
||||||
- [ ] **Step 6:** Verify the `dist/` output contains the expected artifacts (`.deb`, `.AppImage` at minimum) and that the packaged app launches (`./dist/*.AppImage` or the unpacked `dist/linux-unpacked/markdown-converter` binary) without immediate crash — smoke-test opening a markdown file and exporting to PDF from the packaged build specifically (not `npm start`), since `asarUnpack` behavior for `sharp`/`ffmpeg-static`/fonts only manifests in a packaged build.
|
|
||||||
- [ ] **Step 7:** Report the final `dist/` artifact list and versions to the user; do not bump `package.json`'s version number as part of this task unless the user asks — that is a separate release-management decision.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 26: Migrate `File.path` → `webUtils.getPathForFile` (Electron 41 fix) — appended by controller ruling 2026-08-23
|
|
||||||
|
|
||||||
**Origin:** Task 20 review. `File.path` was removed in Electron 32; this app pins `electron ^41.1.1` and has no `webUtils` usage — every renderer file-picker reading `file.path` gets `undefined` at runtime (~15 sites: universal converter, PDF editor pickers, bibliography/CSL pickers, custom template, media merge lists, document-compare File B).
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/preload.js` (expose a `getFilePath(file)` helper via `webUtils.getPathForFile`)
|
|
||||||
- Modify: `src/renderer.js`, `src/renderer/media-operations-dialog.js`, `src/renderer/document-compare-dialog.js` (migrate all `file.path` reads to the helper)
|
|
||||||
|
|
||||||
**Steps:**
|
|
||||||
1. In `src/preload.js`, expose `getFilePath: (file) => webUtils.getPathForFile(file)` on the existing `electronAPI` surface (webUtils is available in the preload/renderer context; it exists precisely to replace File.path). No new IPC channel needed — this is a synchronous in-process call.
|
|
||||||
2. Grep-migrate every `file.path` / `files[i].path` read in the three renderer files to `window.electronAPI.getFilePath(file)` (falling back to `file.path` if the helper is absent, to keep jsdom tests runnable — verify which tests mock this surface and update them to mock the helper).
|
|
||||||
3. Add a preload test asserting `getFilePath` is exposed (follow tests/preload.test.js conventions).
|
|
||||||
4. `npm run lint && npm test`.
|
|
||||||
5. Commit: `fix(renderer): migrate File.path reads to webUtils.getPathForFile for Electron 41`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 27: PDF encrypt/decrypt/permissions — replace silent no-op with honest failure — appended by controller ruling 2026-08-23
|
|
||||||
|
|
||||||
**Origin:** Task 22 review (empirically verified). pdf-lib 1.17.1 cannot encrypt: `save({userPassword, ownerPassword, permissions})` silently ignores these options, `PDFDocument.load({password})` is not a LoadOptions field. Current behavior: `pdfEncrypt`/`pdfSetPermissions` write unprotected files and report success; `pdfDecrypt` reports success on non-encrypted inputs (copy no-op) and always fails on genuinely encrypted ones.
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/main/PDFOperations.js` (pdfEncrypt, pdfDecrypt, pdfSetPermissions), their renderer call sites if messages surface there, and `src/main/PDFBatchOperations.js` exclusion register comment (already excludes these ops — keep excluded, update the comment to reference this task).
|
|
||||||
|
|
||||||
**Steps:**
|
|
||||||
1. Capability-detect once at module load (probe whether the installed pdf-lib honors encryption — e.g. build a tiny in-memory PDFDocument, save with a userPassword, check raw bytes for `/Encrypt`; or simply pin the known limitation with a constant + comment referencing pdf-lib 1.17.1) — prefer the empirical probe so a future library swap re-enables the ops automatically.
|
|
||||||
2. When encryption is unsupported: pdfEncrypt/pdfSetPermissions return `{success: false, message: 'Password protection is not available in this build (pdf-lib lacks encryption support).'}`; pdfDecrypt returns an equivalent honest failure. Never write a file. Never report success.
|
|
||||||
3. Update the PDF editor dialog so these three controls are disabled with explanatory hint text when unavailable (grep renderer call sites for the encrypt/permissions handlers).
|
|
||||||
4. Update tests: existing encrypt/decrypt/permissions tests (they currently pin the broken behavior — rewrite to assert honest failure); keep any genuinely-passing load-with-password tests only if the probe says the library supports them.
|
|
||||||
5. `npm run lint && npm test`.
|
|
||||||
6. Commit: `fix(pdf): make encrypt/decrypt/permissions fail honestly instead of silent no-op`
|
|
||||||
|
|
||||||
**Out of scope (user decision pending):** swapping pdf-lib for an encryption-capable fork (e.g. @cantoo/pdf-lib) to restore the feature for real — new dependency, needs sign-off.
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
# Security Assessment Summary — MarkdownConverter (master branch)
|
|
||||||
|
|
||||||
**Date:** 2026-08-23 · **Scope:** full branch `6db54a5..HEAD` (feature-audit-and-hardening plan, 27 tasks) · **Method:** manual feature/security audit at plan time + formal review pass (Task 24: three-stage vulnerability scan — identify → false-positive filter at confidence ≥ 8 → inline fix of confirmed High findings)
|
|
||||||
|
|
||||||
## 1. What the manual audit found (plan Phases A–D)
|
|
||||||
|
|
||||||
| # | Finding | Severity | Resolution |
|
|
||||||
|---|---------|----------|------------|
|
|
||||||
| SEC-1 | Pandoc invocation built as shell-style string and re-tokenized — argument injection via crafted filenames/options/bibliography paths | **Critical** | Fixed — Task 23 (`d41b7df`): every invocation now `execFile(path, args[])` via pure builder `src/main/PandocArgs.js`; string tokenizer deleted; 21 injection-vector tests + differential exploit-split proof + 23 real-pandoc e2e checks |
|
|
||||||
| UX-1..7 | Seven non-working features: PDF menu IPC misrouting, media converter with 16 IPC channels and 0 handlers, dead New-from-Template menu, dead View-menu toggles, Clear-Recent-Files no-op, unreachable font settings, jszip/sharp misplaced in devDependencies | High (functional) | Fixed — Tasks 1–14; media backends (sharp/ffmpeg) implemented execFile-array-first |
|
|
||||||
| LAT-1 | `File.path` reads dead on Electron 41 (removed in v32; app pins ^41.1.1) — every renderer file-picker returned `undefined` | High (functional) | Found during Task 20 review; fixed — Task 26 (`32a5755`): `webUtils.getPathForFile` exposed in preload + main-window shim; all ~15 picker sites migrated |
|
|
||||||
| LAT-2 | pdf-lib 1.17.1 silently ignores `userPassword`/`ownerPassword`/`permissions` — PDF encrypt/permissions wrote **unprotected** files while reporting success; decrypt was a copy no-op | High (integrity) | Found during Task 22 review; fixed — Task 27 (`78afccc`): empirical capability probe (fail-closed), honest unavailability errors, UI controls disabled with hint. Real encryption requires a library swap (see deferred #D1) |
|
|
||||||
|
|
||||||
## 2. What the formal pass (Task 24) found
|
|
||||||
|
|
||||||
**Confirmed (confidence 8/10, HIGH) — fixed inline:**
|
|
||||||
|
|
||||||
- **Git sidebar XSS → code execution** (`src/sidebar/git-panel.js`): repo-derived branch names, git-status file names, commit messages/author names, and git stderr rendered into `innerHTML` unescaped in the `nodeIntegration:true` main window, whose CSP permits `'unsafe-inline'` handlers. A malicious repo (attacker-authored commit message or crafted branch name) cloned by the victim executes script with full Node access when the Git panel loads. Fixed — `eafaf6e`: `escapeHtml` (& < > " ') across all 13 sink sites; jsdom tests assert structural inertness (no `img`/`script` elements, no attribute breakout) and that `dataset` reads still return raw names for git operations.
|
|
||||||
|
|
||||||
**Candidate assessed and dropped (with evidence):**
|
|
||||||
|
|
||||||
- PowerShell BurntToast interpolation (`main.js` ~4344): pre-existing at origin/master in identical `execFile`-array form. The dialog path interpolates a `format` chosen from a hardcoded 12-entry list; the `--convert-to <format>` CLI path feeds raw argv into the same string — but argv is trusted local-user input (precedent: CLI flags are trusted), and no shell is involved. Not exploitable. (Evidence note: the "hardcoded list" rationale covers the dialog path only; the drop stands on the argv-trust precedent for the CLI path.)
|
|
||||||
|
|
||||||
**Verified clean (14 areas):** media operation backends and all batch handlers (execFile arrays throughout, no string re-tokenization); plugin system (no escalation beyond the renderer's existing privileges; format metadata reaches main only as native menu labels and save-dialog filters); all new dialog renderers (`textContent`-only for dynamic content); PDFOperations new ops (pdfjs/sharp in-process, no shell); wordTemplateExporter (all `<w:t>` insertions escaped, no zip extraction → no zip-slip); GitOperations (simple-git array args); settings/presets stores (no deep merge → no prototype pollution); PandocArgs completeness (tree-wide grep: zero surviving string-built pandoc invocations); font embedders (fixed family→filename maps); generator windows (no untrusted prefill); print-preview (DOMPurify flow); no `eval`/`new Function`; no variable-URL `shell.openExternal`; no secrets in the diff.
|
|
||||||
|
|
||||||
## 3. Deferred / accepted risks
|
|
||||||
|
|
||||||
| ID | Risk | Disposition |
|
|
||||||
|----|------|-------------|
|
|
||||||
| D1 | **Real PDF encryption unavailable** (pdf-lib limitation) — feature now fails honestly rather than lying | Accepted for this release. Restoring it means swapping pdf-lib for an encryption-capable fork (e.g. `@cantoo/pdf-lib`, API-compatible) — **needs explicit sign-off on a new dependency** |
|
|
||||||
| D2 | `nodeIntegration:true` + `contextIsolation:false` on mainWindow, pdfWindow, hiddenWindow; main window does not load `preload.js` (inline shim instead) — the IPC whitelist is a live control only on the two generator windows | Accepted legacy risk for this branch; owned by the react-electron migration (contextIsolation + preload-everywhere), tracked separately |
|
|
||||||
| D3 | Generator-window preload whitelist is broad (`execute-code`, `read-file`, `write-file`, `delete-file` reachable from isolated windows) | No current content vector into those windows; flag for the migration to narrow per-window APIs |
|
|
||||||
| D4 | CSP allows `'unsafe-inline'` / `'unsafe-eval'` (required by marked + Mermaid rendering model) | Accepted; revisit under the migration with a nonce-based CSP |
|
|
||||||
| D5 | `outline-panel.js` / `repl-panel.js` / `analytics-panel.js` have local `escapeHtml` helpers that do not escape quotes | Deferred hardening: unsafe only if reused in attribute contexts; no such current use found |
|
|
||||||
| D6 | `scripts/download-tools.js` downloads Pandoc/fonts without checksum pinning | Build-time supply-chain hardening; recommended follow-up (pin + verify SHA-256) |
|
|
||||||
| D7 | Misc functional edge cases (batch same-folder overwrite, `pdfSplit` non-positive interval loop, rate-limiter dialog stall) | Deferred minors, logged in the plan ledger; none security-relevant |
|
|
||||||
|
|
||||||
## 4. Verification state
|
|
||||||
|
|
||||||
- Test suite: **49 suites / 512 tests passing**; ESLint and Prettier clean at every task boundary (enforced per-task during execution).
|
|
||||||
- All new external-process code paths verified `execFile`-array by independent tree-wide grep (Task 23 review) and re-verified in the formal pass.
|
|
||||||
- **Release blocker (human step):** this environment cannot launch the Electron GUI. A human pass in the running app — light + dark themes, file picking in the main dialogs (File B in Document Compare, bibliography/CSL, universal converter, PDF editor), Git sidebar on a real repo — is required before shipping.
|
|
||||||
|
|
||||||
**Bottom line:** the one Critical (argument injection) and one confirmed High (Git panel XSS) are closed with tests; two latent silent-failure bugs (File.path, fake encryption) are fixed; the remaining exposure is the documented legacy trust model (D2–D4) owned by the planned Electron security migration plus one dependency decision (D1).
|
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
# Phase 7 — Modals Design
|
||||||
|
|
||||||
|
> Companion to the parent plan: `docs/superpowers/plans/2026-06-05-react-ui-redesign.md` (Phases 7+8+9+10 are sketched there at high level; this spec locks Phase 7's architecture, file map, and contracts so it can be planned task-by-task.)
|
||||||
|
|
||||||
|
**Date:** 2026-06-05
|
||||||
|
**Phase:** 7 of 10 (React + shadcn/ui UI redesign)
|
||||||
|
**Tag (on completion):** `phase-7-modals`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Goal & Non-Goals
|
||||||
|
|
||||||
|
**Goal:** Add a layered modal system to the React renderer. Wire 7 modal types (SettingsSheet + 4 Export dialogs + About + Welcome + Confirm) to a single `<ModalLayer />`. Add a persisted `useSettingsStore` for user preferences. The modals are opened via the command store (Phase 6 pattern), and the modals themselves read/write settings via the new store.
|
||||||
|
|
||||||
|
**Non-goals (Phase 7):**
|
||||||
|
- Implement the actual export pipelines (PDF/DOCX/HTML/PNG generation) — those are main-process concerns, already implemented. Phase 7 only adds the renderer-side dialog UI.
|
||||||
|
- Real plugin system — the Plugins tab is a placeholder ("Coming soon").
|
||||||
|
- Toast notifications — Phase 8.
|
||||||
|
- Advanced tools (Zen mode, REPL, ASCII/Table generators, Print preview) — Phase 9.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architecture
|
||||||
|
|
||||||
|
### 2.1 Modal state lives in `useAppStore` (extended, not new store)
|
||||||
|
|
||||||
|
`useAppStore` is already the "global UI" store (sidebar, preview, zen, paneSizes). It's the right home for modal state because:
|
||||||
|
- It's already mounted.
|
||||||
|
- It's already persisted (via `zustand persist` with `partialize` for pane sizes).
|
||||||
|
- A separate `useUIStore` would be YAGNI.
|
||||||
|
|
||||||
|
**Add to `AppState`:**
|
||||||
|
- `modal: ModalState` (discriminated union — see §2.2)
|
||||||
|
- `openModal: <K extends ModalKind>(kind: K, props?: ModalPropsFor<K>) => void`
|
||||||
|
- `closeModal: () => void`
|
||||||
|
|
||||||
|
**Persistence:** `modal` is **runtime-only**, like `userBindings` in `useCommandStore`. We add it to the `partialize` function so only the persisted fields (`sidebarVisible`, `previewVisible`, `zenMode`, `paneSizes`) are saved. The modal kind never needs to survive a reload.
|
||||||
|
|
||||||
|
### 2.2 Discriminated-union modal shape
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export type ModalState =
|
||||||
|
| { kind: null }
|
||||||
|
| { kind: 'export-pdf'; props: { sourcePath: string } }
|
||||||
|
| { kind: 'export-docx'; props: { sourcePath: string } }
|
||||||
|
| { kind: 'export-html'; props: { sourcePath: string } }
|
||||||
|
| { kind: 'export-batch'; props: { sourcePaths: string[] } }
|
||||||
|
| { kind: 'settings' }
|
||||||
|
| { kind: 'about' }
|
||||||
|
| { kind: 'welcome' }
|
||||||
|
| { kind: 'confirm'; props: ConfirmProps };
|
||||||
|
|
||||||
|
export interface ConfirmProps {
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
confirmLabel?: string; // default "Confirm"
|
||||||
|
cancelLabel?: string; // default "Cancel"
|
||||||
|
destructive?: boolean; // switches confirm button to red variant
|
||||||
|
onConfirm: () => void | Promise<void>;
|
||||||
|
onCancel?: () => void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why a discriminated union:** every component that opens a modal must pass the right `props` shape for the `kind` — TypeScript catches mismatches at compile time. A generic `{ open: boolean, type: string }` shape would defer the error to runtime.
|
||||||
|
|
||||||
|
### 2.3 Single `<ModalLayer />`
|
||||||
|
|
||||||
|
Mounted at the bottom of `App.tsx`. Reads `modal.kind` from `useAppStore`, renders the matching component (or `null`). Each child modal calls `closeModal()` on dismiss.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// src/renderer/components/modals/ModalLayer.tsx (sketch)
|
||||||
|
export function ModalLayer() {
|
||||||
|
const modal = useAppStore((s) => s.modal);
|
||||||
|
switch (modal.kind) {
|
||||||
|
case null: return null;
|
||||||
|
case 'export-pdf': return <ExportPdfDialog {...modal.props} />;
|
||||||
|
// ... etc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`<ModalLayer />` ensures only one modal is visible at a time (the store only holds one). This is correct for v1 — no need for stacking/replacement transitions in Phase 7.
|
||||||
|
|
||||||
|
### 2.4 Settings store (new, separate)
|
||||||
|
|
||||||
|
A new `useSettingsStore` for user preferences. **Why separate from `useAppStore`:** settings is a different lifecycle. `useAppStore` is "current view configuration"; `useSettingsStore` is "user preferences that survive across sessions and are read by many features". Same precedent as `useFileStore` (file tree state) being separate from `useAppStore` (UI chrome state).
|
||||||
|
|
||||||
|
**Persistence:** `zustand persist` with `partialize` to serialize only the leaf settings (matching the pattern in `useFileStore` and `useCommandStore`).
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface SettingsState {
|
||||||
|
// Editor
|
||||||
|
fontSize: number; // 12-20, default 14
|
||||||
|
tabSize: number; // 2 | 4 | 8, default 4
|
||||||
|
lineNumbers: boolean; // default true
|
||||||
|
wordWrap: boolean; // default true
|
||||||
|
minimap: boolean; // default true
|
||||||
|
// Theme
|
||||||
|
theme: 'light' | 'dark' | 'auto'; // default 'auto'
|
||||||
|
accentColor: 'brand' | 'blue' | 'green' | 'purple' | 'orange'; // default 'brand'
|
||||||
|
fontFamily: 'system' | 'jetbrains' | 'fira'; // default 'system'
|
||||||
|
// Export
|
||||||
|
pdfFormat: 'letter' | 'a4' | 'legal'; // default 'a4'
|
||||||
|
pdfMargins: 'normal' | 'narrow' | 'wide'; // default 'normal'
|
||||||
|
pdfEmbedFonts: boolean; // default true
|
||||||
|
docxTemplate: 'standard' | 'minimal' | 'modern'; // default 'standard'
|
||||||
|
htmlHighlightStyle: 'github' | 'monokai' | 'nord' | 'none'; // default 'github'
|
||||||
|
// ASCII table formatting — applies to all 3 single-file export formats
|
||||||
|
renderTablesAsAscii: boolean; // default false
|
||||||
|
// First-launch / Welcome
|
||||||
|
welcomeDismissed: boolean; // default false
|
||||||
|
// Actions
|
||||||
|
setSetting: <K extends keyof Omit<SettingsState, ...>>(...);
|
||||||
|
resetToDefaults: () => void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Template-based exports** (per user request): `docxTemplate` is one of `'standard' | 'minimal' | 'modern'`. The export dialog shows a Select with the available templates. The IPC layer (`ipc.export.docx`) already accepts a `template` field; Phase 7 just exposes it. The main process maps these template names to actual `.docx` template files bundled with the app.
|
||||||
|
|
||||||
|
**ASCII table formatting** (per user request): `renderTablesAsAscii` is a toggle in the Settings sheet (Export tab) and in each of the 3 single-file export dialogs as an inline checkbox override. When true, the markdown AST's table nodes are converted to fixed-width monospace text (using a small `lib/ascii-table.ts` helper) *before* the export pipeline sees them. The preview pane is unaffected — this is export-time only.
|
||||||
|
|
||||||
|
### 2.5 WelcomeDialog trigger logic
|
||||||
|
|
||||||
|
A small `useEffect` in `App.tsx`:
|
||||||
|
```ts
|
||||||
|
useEffect(() => {
|
||||||
|
if (!useSettingsStore.getState().welcomeDismissed) {
|
||||||
|
useAppStore.getState().openModal('welcome');
|
||||||
|
}
|
||||||
|
}, []); // run once on mount
|
||||||
|
```
|
||||||
|
|
||||||
|
The Help menu registers a `help.welcome` command that simply calls `openModal('welcome')` — does NOT reset the `welcomeDismissed` flag. (Decision in §2.4 of the brainstorming.)
|
||||||
|
|
||||||
|
### 2.6 Commands trigger modals
|
||||||
|
|
||||||
|
The command store (Phase 6) gets new commands. Registered in `src/renderer/lib/commands/register-menu-commands.ts`:
|
||||||
|
|
||||||
|
| Command ID | Handler |
|
||||||
|
|------------------|------------------------------------------------------|
|
||||||
|
| `file.exportPdf` | `openModal('export-pdf', { sourcePath: activePath })` |
|
||||||
|
| `file.exportDocx` | `openModal('export-docx', { sourcePath: activePath })` |
|
||||||
|
| `file.exportHtml` | `openModal('export-html', { sourcePath: activePath })` |
|
||||||
|
| `file.exportBatch` | `openModal('export-batch', { sourcePaths: openFiles })` |
|
||||||
|
| `settings.open` | `openModal('settings')` |
|
||||||
|
| `help.welcome` | `openModal('welcome')` |
|
||||||
|
| `help.about` | `openModal('about')` |
|
||||||
|
| `file.confirmClose` | opens confirm dialog before closing a dirty tab |
|
||||||
|
| `app.quit` | opens confirm if dirty tabs exist, else quits |
|
||||||
|
|
||||||
|
`settings.open` and `help.about` also get buttons in `AppHeader` (already partly done in Phase 6 — we just add new icons and wire to the new commands).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. File Map
|
||||||
|
|
||||||
|
### 3.1 shadcn primitives (manually created, per the shadcn-CLI-blocked memory)
|
||||||
|
|
||||||
|
Created in `src/renderer/components/ui/`:
|
||||||
|
- `dialog.tsx` — Radix Dialog wrapper with motion preset
|
||||||
|
- `sheet.tsx` — Radix Dialog (side variant) for SettingsSheet
|
||||||
|
- `tabs.tsx` — Radix Tabs for the 5-tab SettingsSheet
|
||||||
|
- `input.tsx` — text input
|
||||||
|
- `textarea.tsx` — multi-line input (for confirm body, welcome copy)
|
||||||
|
- `select.tsx` — Radix Select for theme/font/template pickers
|
||||||
|
- `switch.tsx` — Radix Switch for boolean settings
|
||||||
|
- `checkbox.tsx` — Radix Checkbox for "don't show again" toggles
|
||||||
|
- `slider.tsx` — Radix Slider for fontSize
|
||||||
|
- `label.tsx` — Radix Label (always pair with form fields)
|
||||||
|
- `form.tsx` — react-hook-form glue components (FormField, FormItem, FormLabel, FormControl, FormDescription, FormMessage)
|
||||||
|
- `radio-group.tsx` — Radix RadioGroup for accent color / template
|
||||||
|
|
||||||
|
### 3.2 Modals (`src/renderer/components/modals/`)
|
||||||
|
|
||||||
|
- `ModalLayer.tsx` — root, mounted by `App.tsx`
|
||||||
|
- `ExportPdfDialog.tsx` — PDF options (format, margins, embed fonts, ascii tables)
|
||||||
|
- `ExportDocxDialog.tsx` — DOCX options (template picker: standard/minimal/modern, ascii tables)
|
||||||
|
- `ExportHtmlDialog.tsx` — HTML options (standalone, highlight style, ascii tables)
|
||||||
|
- `ExportBatchDialog.tsx` — batch queue (format, concurrency, file list)
|
||||||
|
- `SettingsSheet.tsx` — 5-tab sheet (side="right", 480px wide)
|
||||||
|
- `EditorSettings.tsx` — font size, tab size, line numbers, word wrap, minimap
|
||||||
|
- `ThemeSettings.tsx` — light/dark/auto, accent color, font family
|
||||||
|
- `ExportSettings.tsx` — pdf format, margins, embed fonts, docx template, html highlight, ascii tables
|
||||||
|
- `PluginsSettings.tsx` — "Coming soon" placeholder
|
||||||
|
- `AboutSettings.tsx` — app version, links, acknowledgements
|
||||||
|
- `AboutDialog.tsx` — simple read-only dialog with version + GitHub link
|
||||||
|
- `WelcomeDialog.tsx` — first-launch dialog with quick-start cards
|
||||||
|
- `ConfirmDialog.tsx` — generic confirmation (title, body, destructive, onConfirm)
|
||||||
|
- `ExportDialogFooter.tsx` — shared Cancel / Export button row used by the 4 export dialogs
|
||||||
|
- `useExportSource.ts` — shared hook: reads active buffer, validates, returns source string + path
|
||||||
|
|
||||||
|
### 3.3 Stores
|
||||||
|
|
||||||
|
- **Modify** `src/renderer/stores/app-store.ts` — add `modal` + `openModal` + `closeModal`; update `partialize` to exclude `modal`
|
||||||
|
- **Create** `src/renderer/stores/settings-store.ts` — new
|
||||||
|
|
||||||
|
### 3.4 Lib
|
||||||
|
|
||||||
|
- **Create** `src/renderer/lib/validators.ts` — zod schemas:
|
||||||
|
- `settingsSchema` (whole settings object)
|
||||||
|
- `exportPdfSchema` (format, margins, embedFonts, renderTablesAsAscii)
|
||||||
|
- `exportDocxSchema` (template, renderTablesAsAscii)
|
||||||
|
- `exportHtmlSchema` (standalone, highlightStyle, renderTablesAsAscii)
|
||||||
|
- `exportBatchSchema` (format, concurrency, file list)
|
||||||
|
- `confirmPropsSchema` (for the confirm dialog)
|
||||||
|
- **Create** `src/renderer/lib/ascii-table.ts` — `toAsciiTable(rows: string[][]): string` (the small helper that converts a 2D string array to a fixed-width ASCII table)
|
||||||
|
- **Create** `src/renderer/lib/modal-triggers.ts` — small helpers: `useWelcomeTrigger()`, `useQuitGuard()`
|
||||||
|
|
||||||
|
### 3.5 Modified files
|
||||||
|
|
||||||
|
- **Modify** `src/renderer/App.tsx` — mount `<ModalLayer />` at the bottom; add the `useWelcomeTrigger` `useEffect` for first-launch
|
||||||
|
- **Modify** `src/renderer/lib/commands/register-menu-commands.ts` — add the 9 new commands (4 export + settings + welcome + about + confirmClose + quit)
|
||||||
|
- **Modify** `src/renderer/components/layout/AppHeader.tsx` — add Settings (gear) and About (info) icon buttons that dispatch the new commands
|
||||||
|
- **Modify** `src/main.js` (verify) — no changes expected; menu items already wire to `menu:action` channels that flow through `useBridgeNativeMenu`. If any new menu items need IPC channels, add them in the main process mirror.
|
||||||
|
|
||||||
|
### 3.6 Tests
|
||||||
|
|
||||||
|
**Unit (`tests/unit/`):**
|
||||||
|
- `stores/settings-store.test.ts` (5-6 tests: defaults, setSetting, resetToDefaults, persistence/partialize)
|
||||||
|
- `stores/app-store.test.ts` extended (3 tests: openModal sets state, closeModal clears, only one modal at a time)
|
||||||
|
- `lib/validators.test.ts` (3 tests: each schema rejects bad input)
|
||||||
|
- `lib/ascii-table.test.ts` (3 tests: simple table, alignment, empty input)
|
||||||
|
|
||||||
|
**Component (`tests/component/modals/`):**
|
||||||
|
- `ExportPdfDialog.test.tsx` (4 tests: renders with default settings, submit calls ipc.export.pdf with merged opts, error renders inline, ascii-table toggle flows through)
|
||||||
|
- `ExportDocxDialog.test.tsx` (3 tests: renders, submit includes template, ascii-table toggle)
|
||||||
|
- `ExportHtmlDialog.test.tsx` (3 tests: renders, highlight style select, ascii-table toggle)
|
||||||
|
- `ExportBatchDialog.test.tsx` (3 tests: renders file list, format selector, concurrency)
|
||||||
|
- `SettingsSheet.test.tsx` (6 tests: renders 5 tabs, each tab shows correct fields, settings change persists)
|
||||||
|
- `AboutDialog.test.tsx` (2 tests: renders version, links open external)
|
||||||
|
- `WelcomeDialog.test.tsx` (3 tests: renders, dismiss sets welcomeDismissed, "don't show again" checked)
|
||||||
|
- `ConfirmDialog.test.tsx` (3 tests: confirm calls onConfirm and closes, cancel calls closeModal, destructive variant)
|
||||||
|
- `ModalLayer.test.tsx` (3 integration tests: null kind renders nothing, switching kinds replaces modal, modal unmounts on close)
|
||||||
|
|
||||||
|
**Integration (`tests/integration/`):**
|
||||||
|
- `phase7-modals-smoke.test.tsx` (4 tests: dispatch command opens modal, command store + settings store + IPC all wired, app.tsx mount triggers welcome on first launch, modal layer end-to-end)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Data Flow
|
||||||
|
|
||||||
|
### 4.1 Open a modal
|
||||||
|
```ts
|
||||||
|
// From any command handler in register-menu-commands.ts:
|
||||||
|
useAppStore.getState().openModal('export-pdf', { sourcePath: activePath });
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 The dialog reads source
|
||||||
|
```ts
|
||||||
|
// ExportPdfDialog.tsx
|
||||||
|
const { source, path } = useExportSource();
|
||||||
|
if (!source) return <EmptySourceFallback />;
|
||||||
|
```
|
||||||
|
|
||||||
|
`useExportSource` is a small hook that:
|
||||||
|
1. Reads `useFileStore.activeTabId` + `useEditorStore.buffers`
|
||||||
|
2. If no active buffer, prompts the user to open a file (uses confirm dialog)
|
||||||
|
3. Returns `{ source: string, path: string } | null`
|
||||||
|
|
||||||
|
### 4.3 Settings change
|
||||||
|
```ts
|
||||||
|
// EditorSettings.tsx — switches/inputs call setSetting
|
||||||
|
const [fontSize, setFontSize] = useSettingsStore(s => [s.fontSize, s.setSetting]);
|
||||||
|
// or
|
||||||
|
setSetting('fontSize', 16);
|
||||||
|
```
|
||||||
|
|
||||||
|
Editor and preview subscribe to specific slices. The `useTheme` hook from `next-themes` is augmented to read `theme: 'light' | 'dark' | 'auto'` from `useSettingsStore` (replacing the standalone next-themes default).
|
||||||
|
|
||||||
|
### 4.4 Export flow
|
||||||
|
```ts
|
||||||
|
// ExportPdfDialog on submit:
|
||||||
|
const settings = useSettingsStore.getState();
|
||||||
|
const result = await ipc.export.pdf({
|
||||||
|
inputPath: path,
|
||||||
|
outputPath: chosenOutputPath,
|
||||||
|
format: dialogFormat ?? settings.pdfFormat,
|
||||||
|
margins: MARGIN_PRESETS[dialogMargins ?? settings.pdfMargins],
|
||||||
|
embedFonts: dialogEmbed ?? settings.pdfEmbedFonts,
|
||||||
|
renderTablesAsAscii: dialogAscii ?? settings.renderTablesAsAscii,
|
||||||
|
});
|
||||||
|
if (!result.ok) setError(result.error.message);
|
||||||
|
else { closeModal(); /* toast in Phase 8 */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
The dialog-level overrides fall through to settings defaults when not explicitly chosen.
|
||||||
|
|
||||||
|
### 4.5 ASCII table transformation
|
||||||
|
The transformation happens in the **renderer** (pre-IPC), so the main process doesn't need to know about ASCII mode:
|
||||||
|
```ts
|
||||||
|
// In ExportPdfDialog before submitting:
|
||||||
|
const finalSource = renderTablesAsAscii
|
||||||
|
? applyAsciiTransform(source) // walks AST, replaces <table> blocks
|
||||||
|
: source;
|
||||||
|
```
|
||||||
|
`applyAsciiTransform` is a small function (10-20 lines) that:
|
||||||
|
1. Parses markdown source for `|...|` table syntax via a small regex
|
||||||
|
2. Replaces each table block with a fenced code block containing the ASCII table
|
||||||
|
3. Returns the modified source
|
||||||
|
|
||||||
|
(No AST walker needed — markdown tables are line-based and a regex per line + simple width calc is sufficient.)
|
||||||
|
|
||||||
|
### 4.6 DOCX template selection
|
||||||
|
The dialog shows a Select with 3 options (standard, minimal, modern). The main process maps these names to bundled `.docx` template files. The IPC contract is unchanged — `DocxOptions.template: string` was already defined in `types/ipc.ts` during Phase 1.
|
||||||
|
|
||||||
|
### 4.7 Confirm flow
|
||||||
|
```ts
|
||||||
|
// In a command handler:
|
||||||
|
const activeTab = ...;
|
||||||
|
if (activeTab?.dirty) {
|
||||||
|
useAppStore.getState().openModal('confirm', {
|
||||||
|
title: 'Discard unsaved changes?',
|
||||||
|
body: `"${activeTab.title}" has unsaved changes. Close without saving?`,
|
||||||
|
confirmLabel: 'Discard',
|
||||||
|
destructive: true,
|
||||||
|
onConfirm: () => doCloseTab(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
doCloseTab();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.8 Welcome first-launch
|
||||||
|
`useEffect` in `App.tsx` (run once on mount) checks `welcomeDismissed` from `useSettingsStore`. If false, calls `openModal('welcome')`. The Welcome dialog has a "Don't show again" checkbox that sets `welcomeDismissed: true` and closes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Error Handling
|
||||||
|
|
||||||
|
- **IPC errors in export dialogs:** inline error banner below the submit button. `IpcResult<T>` discriminated union makes this easy. Banner shows `result.error.message` and a "Try again" button that re-submits.
|
||||||
|
- **Settings validation:** zod schemas in `validators.ts`. Each form field shows `aria-invalid` + red border on error. Form-level errors via react-hook-form's `formState.errors`.
|
||||||
|
- **Confirm dialog cancel:** just calls `closeModal()`. No state mutation. Optional `onCancel` callback for "remember my choice" patterns (not used in Phase 7).
|
||||||
|
- **Welcome "don't show again":** persists `welcomeDismissed: true`. Help menu can re-open Welcome (without resetting the flag).
|
||||||
|
- **Settings corruption on load (bad localStorage data):** `useSettingsStore` is built with a `partialize` that also acts as a whitelist — only known fields are deserialized. Unknown fields are dropped. If a persisted value fails zod validation, fall back to defaults (logged as a warning).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Testing Strategy
|
||||||
|
|
||||||
|
TDD per the established pattern (Phases 1-6). Every component test:
|
||||||
|
- Renders with empty/default state
|
||||||
|
- One happy-path interaction (form submit, button click)
|
||||||
|
- One error/edge case (validation fail, IPC error, cancel)
|
||||||
|
|
||||||
|
Store tests focus on pure logic (state transitions, persistence, partialize). Settings store test specifically verifies:
|
||||||
|
- Defaults match schema
|
||||||
|
- `setSetting` works for leaf keys
|
||||||
|
- `resetToDefaults` clears to initial state
|
||||||
|
- Persisted payload (from `partialize`) contains exactly the leaf fields
|
||||||
|
- Hydration from a partial/corrupt payload doesn't throw
|
||||||
|
|
||||||
|
Component tests use `render` + `userEvent`, mock `window.electronAPI` for IPC.
|
||||||
|
|
||||||
|
ModalLayer integration test verifies:
|
||||||
|
1. Mounting with `kind: null` renders nothing (query container, expect empty)
|
||||||
|
2. Mounting with `kind: 'about'` renders `<AboutDialog>` (aria-label match)
|
||||||
|
3. Switching from `kind: 'about'` to `kind: 'settings'` unmounts About, mounts Settings (verified by role/aria-label transitions)
|
||||||
|
4. Confirm dialog calls `onConfirm` and `closeModal` on success
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Risks & Open Questions
|
||||||
|
|
||||||
|
**Risks:**
|
||||||
|
- **Form library complexity.** react-hook-form + zod is powerful but adds learning curve. Mitigation: a single shared `<SettingsForm>` wrapper reduces cognitive load; export dialogs use simple `useState` (no need for the full form infra).
|
||||||
|
- **shadcn Dialog animation jank with our motion presets.** Radix Dialog has its own `data-state` attributes for open/closed. We compose with our `modalPop` preset via `forceMount` + Motion. Need to verify no double-animation.
|
||||||
|
- **Settings store hydration race.** If a component reads a setting on first render before hydration completes, it gets the default. For Phase 7 this is fine — defaults are sensible.
|
||||||
|
|
||||||
|
**Open questions (deferrable):**
|
||||||
|
- Should the "ascii table" output include alignment row separators (`+---+---+`) or just be a `| a | b |`-style table? → Decision: use the `|---|` separator form (more compact, common in plain-text email).
|
||||||
|
- Should ExportBatchDialog be a Sheet (queue progress) or a Dialog (form)? → Decision: Dialog with a form; progress is shown inline (not a streaming queue). Phase 9 could revisit.
|
||||||
|
- Should `welcomeDismissed` be per-user-account or per-install? → Per-install (localStorage). No multi-user concept in v1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Out of Scope (deferred to later phases)
|
||||||
|
|
||||||
|
- Phase 8: Toast notifications on export success/failure (the dialog's inline error is v1; toasts are a follow-up).
|
||||||
|
- Phase 9: ASCII art generator (figlet) is separate from ASCII table rendering. This spec is about table formatting.
|
||||||
|
- Phase 9: Word export uses a `.docx` template *generation* step (WordExportDialog), not the IPC `ipc.export.docx` path. Distinct.
|
||||||
|
- Phase 10: Delete legacy `src/print-preview.js`, `src/wordTemplateExporter.js`, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Success Criteria
|
||||||
|
|
||||||
|
Phase 7 is complete when:
|
||||||
|
- All listed shadcn primitives exist in `src/renderer/components/ui/` with tests
|
||||||
|
- `useSettingsStore` is implemented, tested, and persisted
|
||||||
|
- `useAppStore` extended with `modal` discriminated union and tested
|
||||||
|
- All 7 modal components implemented, tested, and accessible (aria-labels, keyboard nav)
|
||||||
|
- 4 export dialogs (PDF/DOCX/HTML/Batch) all submit through the command store and call IPC correctly
|
||||||
|
- `ModalLayer` mounted in `App.tsx` and integrated with command triggers
|
||||||
|
- Welcome dialog shows on first launch, dismissible, re-openable from Help menu
|
||||||
|
- Confirm dialog used by quit-with-dirty and close-with-dirty flows
|
||||||
|
- ASCII table rendering works (toggle in settings, override in export dialogs)
|
||||||
|
- DOCX template picker in ExportDocxDialog submits the correct `template` field
|
||||||
|
- `npx vite build` succeeds, `npx vitest run` shows **all tests green** (target: +50 new tests, total ~220)
|
||||||
|
- Branch tagged `phase-7-modals` and pushed to origin
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
# Phase 8 — Toasts Design
|
||||||
|
|
||||||
|
> Companion to the parent plan: `docs/superpowers/plans/2026-06-05-react-ui-redesign.md` (Phases 8+9+10 are sketched at high level; this spec locks Phase 8's architecture, file map, and contracts so it can be planned task-by-task.)
|
||||||
|
|
||||||
|
**Date:** 2026-06-05
|
||||||
|
**Phase:** 8 of 10 (React + shadcn/ui UI redesign)
|
||||||
|
**Tag (on completion):** `phase-8-toasts`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Goal & Non-Goals
|
||||||
|
|
||||||
|
**Goal:** Add a toast notification layer to the React renderer using sonner (already installed). Surface user-initiated async action results (file save, file/folder open, exports) as transient toasts in the bottom-right of the window. The error banner pattern in export dialogs stays — toasts are a complementary global channel.
|
||||||
|
|
||||||
|
**Non-goals (Phase 8):**
|
||||||
|
- Undo/redo support (Phase 9)
|
||||||
|
- Custom toast actions/buttons (Phase 9, if needed)
|
||||||
|
- Persistent notification history
|
||||||
|
- Toast queueing/throttling for rapid-fire events
|
||||||
|
- Replacing inline error banners (they stay as per-dialog context)
|
||||||
|
|
||||||
|
**Scope decision:** Toast on user-initiated actions only. Skip silent background operations (loadChildren, etc.) to avoid noise. 4 wire points total: save (success+error), open file/folder (error only), 4 export dialogs (success+error).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architecture
|
||||||
|
|
||||||
|
### 2.1 Toast helpers in `lib/toast.ts`
|
||||||
|
|
||||||
|
A thin typed layer over sonner. The helpers exist to:
|
||||||
|
- Give us a single import surface (instead of scattering `import { toast } from 'sonner'` across the codebase)
|
||||||
|
- Provide a place to add brand colors, formatting, or analytics later without touching call sites
|
||||||
|
- Make mocking easier in tests (one module to mock)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// src/renderer/lib/toast.ts (sketch)
|
||||||
|
import { toast as sonnerToast } from 'sonner';
|
||||||
|
|
||||||
|
export const toast = {
|
||||||
|
success: (message: string) => sonnerToast.success(message),
|
||||||
|
error: (message: string) => sonnerToast.error(message),
|
||||||
|
info: (message: string) => sonnerToast.info(message),
|
||||||
|
warning: (message: string) => sonnerToast.warning(message),
|
||||||
|
promise: <T>(
|
||||||
|
promise: Promise<T>,
|
||||||
|
msgs: { loading: string; success: string | ((data: T) => string); error: string | ((err: unknown) => string) }
|
||||||
|
) => sonnerToast.promise(promise, msgs),
|
||||||
|
dismiss: (id?: string | number) => sonnerToast.dismiss(id),
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 `<Toaster />` mounted in App.tsx
|
||||||
|
|
||||||
|
A canonical shadcn Toaster wrapper (manual paste per memory `shadcn-cli-blocked-manual-primitives`). Mounts alongside `<ModalLayer />`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// src/renderer/App.tsx (sketch)
|
||||||
|
import { Toaster } from '@/components/ui/sonner';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
useWelcomeTrigger();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AppShell />
|
||||||
|
<ModalLayer />
|
||||||
|
<Toaster />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The Toaster uses sonner's `<Toaster />` component with:
|
||||||
|
- `theme={resolvedTheme}` from `useTheme()` (so toasts match the user's light/dark preference)
|
||||||
|
- `richColors` for semantic success/error/info/warning colors
|
||||||
|
- `position="bottom-right"` (sonner default; explicit for clarity)
|
||||||
|
- `closeButton` (so users can dismiss)
|
||||||
|
|
||||||
|
### 2.3 Inline wiring at 4 wire points
|
||||||
|
|
||||||
|
**Pattern choice — inline in stores/dialogs, NOT middleware.** Matches the Phase 7 precedent of inline error banners in export dialogs. Middleware would be DRY but harder to debug and harder to control granularity (we want errors on save, but NOT on silent loadChildren).
|
||||||
|
|
||||||
|
**Wire points:**
|
||||||
|
|
||||||
|
1. **`useFileStore.saveActiveBuffer`** — wrap the existing logic:
|
||||||
|
```ts
|
||||||
|
saveActiveBuffer: async () => {
|
||||||
|
// ... existing logic to get buffer ...
|
||||||
|
const writeResult = await ipc.file.write(activeTabId, buffer.content);
|
||||||
|
if (!writeResult.ok) {
|
||||||
|
toast.error(`Failed to save: ${writeResult.error.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// ... existing markSaved/markTabClean ...
|
||||||
|
toast.success(`Saved ${title}`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **`useFileStore.openFile`** — error only:
|
||||||
|
```ts
|
||||||
|
openFile: async (filePath) => {
|
||||||
|
// ... existing logic to check existing tab ...
|
||||||
|
const result = await ipc.file.read(filePath);
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Failed to open file: ${result.error.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// ... existing logic ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **`useFileStore.openFolder`** — error only:
|
||||||
|
```ts
|
||||||
|
openFolder: async (path) => {
|
||||||
|
const result = await ipc.file.list(path);
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Failed to open folder: ${result.error.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// ... existing logic ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **4 export dialogs** — both success and error (error complements the inline banner):
|
||||||
|
```ts
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Export failed: ${result.error.message}`);
|
||||||
|
setError(result.error.message);
|
||||||
|
setSubmitting(false);
|
||||||
|
} else {
|
||||||
|
toast.success(`Exported ${source.title} to ${result.data?.outputPath ?? 'file'}`);
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. File Map
|
||||||
|
|
||||||
|
### 3.1 Created files
|
||||||
|
|
||||||
|
- `src/renderer/lib/toast.ts` — typed wrappers (re-export of sonner with our naming)
|
||||||
|
- `src/renderer/components/ui/sonner.tsx` — canonical shadcn Toaster wrapper (manual paste)
|
||||||
|
- `tests/unit/lib/toast.test.ts` — ~5 unit tests
|
||||||
|
- `tests/component/ui/sonner.test.tsx` — 1 smoke test
|
||||||
|
- `tests/integration/phase8-toasts-smoke.test.tsx` — ~4 integration tests
|
||||||
|
|
||||||
|
### 3.2 Modified files
|
||||||
|
|
||||||
|
- `src/renderer/App.tsx` — mount `<Toaster />` alongside `<ModalLayer />`
|
||||||
|
- `src/renderer/stores/file-store.ts` — add 3 toast calls (save, openFile, openFolder)
|
||||||
|
- `src/renderer/components/modals/ExportPdfDialog.tsx` — toast on submit result
|
||||||
|
- `src/renderer/components/modals/ExportDocxDialog.tsx` — toast on submit result
|
||||||
|
- `src/renderer/components/modals/ExportHtmlDialog.tsx` — toast on submit result
|
||||||
|
- `src/renderer/components/modals/ExportBatchDialog.tsx` — toast on submit result
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Data Flow
|
||||||
|
|
||||||
|
User action → store action OR export dialog submit → IPC call → result →
|
||||||
|
- if error: `toast.error(message)` → sonner renders in bottom-right portal
|
||||||
|
- if success: `toast.success(message)` → sonner renders
|
||||||
|
- inline error banner in dialog stays as per-dialog context (NOT removed)
|
||||||
|
|
||||||
|
Theme comes from `useTheme()` in the Toaster component, not from individual toasts. The Toaster is mounted once at the app level.
|
||||||
|
|
||||||
|
For the 4 export dialogs: the existing inline error banner stays (it's contextual to the dialog), AND a toast is fired. This gives the user both immediate context (in the dialog) and persistent notification (toast in corner).
|
||||||
|
|
||||||
|
For file save: ONLY a toast (no inline error UI in the editor pane — keeps the editor clean). Errors still show the toast.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Error Handling
|
||||||
|
|
||||||
|
- **Toast helpers never throw.** They are thin re-exports of sonner, which handles its own error cases (e.g., render failures, missing portal target).
|
||||||
|
- **In tests**, the `toast` module is mocked so calls don't render real toasts. Mock signature: `vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn(), ... } }))`.
|
||||||
|
- **Theme fallback:** If `useTheme()` is loading or `resolvedTheme` is undefined, Toaster uses `'system'` as a fallback (sonner's default behavior).
|
||||||
|
- **Sonner missing:** If for some reason sonner fails to load, the toast calls become no-ops. The user still sees inline error banners in the export dialogs.
|
||||||
|
- **Inline error banners stay.** They are not replaced by toasts — they complement them.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Testing Strategy
|
||||||
|
|
||||||
|
### 6.1 Unit tests (`tests/unit/lib/toast.test.ts`)
|
||||||
|
|
||||||
|
5 tests:
|
||||||
|
- `toast.success` calls sonner `toast.success` with the message
|
||||||
|
- `toast.error` calls sonner `toast.error` with the message
|
||||||
|
- `toast.info` calls sonner `toast.info`
|
||||||
|
- `toast.warning` calls sonner `toast.warning`
|
||||||
|
- `toast.promise` forwards the promise and messages to sonner
|
||||||
|
|
||||||
|
All tests mock the sonner module and verify the forwarded call.
|
||||||
|
|
||||||
|
### 6.2 Component test (`tests/component/ui/sonner.test.tsx`)
|
||||||
|
|
||||||
|
1 smoke test: `<Toaster />` renders without crashing inside a ThemeProvider.
|
||||||
|
|
||||||
|
### 6.3 Integration test (`tests/integration/phase8-toasts-smoke.test.tsx`)
|
||||||
|
|
||||||
|
~4 tests:
|
||||||
|
- Saving a file → `toast.success` called with `"Saved test.md"`
|
||||||
|
- Opening a non-existent file (ipc returns error) → `toast.error` called with file path in message
|
||||||
|
- Export success (ipc returns ok) → `toast.success` called + dialog closes
|
||||||
|
- Export failure (ipc returns error) → `toast.error` called + inline banner shown + dialog stays open
|
||||||
|
|
||||||
|
TDD throughout. Mocks for `ipc.*` and `lib/toast`.
|
||||||
|
|
||||||
|
### 6.4 Existing tests must still pass
|
||||||
|
|
||||||
|
- All 243 tests from Phase 7 must remain green
|
||||||
|
- Export dialog tests will need updates to verify the new toast calls (the dialog tests currently check for inline banner; they should ALSO verify the toast call)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Risks & Open Questions
|
||||||
|
|
||||||
|
**Risks:**
|
||||||
|
- **Sonner theme switching:** If `useTheme()` returns `'system'` and the OS preference changes mid-session, sonner will re-render. This is the correct behavior; just confirm in test.
|
||||||
|
- **Toast spam:** If user holds Cmd+S, the save could fire many times. Sonner deduplicates by default for similar messages? → Decision: rely on sonner's default behavior. If spam becomes an issue, add a `toast.dismiss()` debounce in v2.
|
||||||
|
|
||||||
|
**Open questions (deferrable):**
|
||||||
|
- Should we add a custom toast for "undo last close" (Phase 9's undo feature)? → Decision: out of scope for Phase 8. Phase 9 will handle undo toasts.
|
||||||
|
- Should the export dialog inline banner be removed once toasts are wired? → Decision: NO — keep both. The inline banner is contextual to the dialog; the toast is global. They serve different purposes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Out of Scope (deferred to later phases)
|
||||||
|
|
||||||
|
- Phase 9: Undo toasts ("Tab closed — Undo" with action button)
|
||||||
|
- Phase 9: Long-running operation progress toasts (e.g., batch export queue)
|
||||||
|
- Phase 9: Custom toast variants for advanced tools (ASCII generator, table generator)
|
||||||
|
- Phase 10: Cleanup of inline error banners (will evaluate in Phase 10 if redundant)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Success Criteria
|
||||||
|
|
||||||
|
Phase 8 is complete when:
|
||||||
|
- `lib/toast.ts` exists with typed wrappers
|
||||||
|
- `<Toaster />` is mounted in `App.tsx` and renders toasts
|
||||||
|
- `useFileStore.saveActiveBuffer` calls `toast.success`/`toast.error` on result
|
||||||
|
- `useFileStore.openFile` calls `toast.error` on failure
|
||||||
|
- `useFileStore.openFolder` calls `toast.error` on failure
|
||||||
|
- 4 export dialogs call `toast.success`/`toast.error` on result
|
||||||
|
- All tests pass: ~+10 new tests, total ~253
|
||||||
|
- `npx vite build` succeeds
|
||||||
|
- Branch tagged `phase-8-toasts` and pushed to origin
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
# MarkdownConverter — React + shadcn/ui UI Redesign
|
||||||
|
|
||||||
|
**Date:** 2026-06-05
|
||||||
|
**Status:** Design (awaiting user approval)
|
||||||
|
**Branch:** `react-electron`
|
||||||
|
**Author:** Brainstormed with user via superpowers:brainstorming
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Replace the legacy vanilla JS renderer (`src/renderer.js` is 213 KB; `src/styles.css` is 74 KB) with a modern React 19 + Vite + TypeScript + shadcn/ui renderer that achieves visual feature parity while delivering a Polished + Glassy (Raycast/Arc-style) aesthetic. The Electron main process, preload bridge, and IPC contracts stay unchanged. Work proceeds via vertical slices — each PR ships a demoable feature.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
1. Replace every render-time feature of the legacy renderer with an idiomatic React + shadcn/ui implementation.
|
||||||
|
2. Adopt the "Polished + Glassy" visual language (subtle shadows, 8–12 px radii, gradient accents, gentle depth) on top of the existing ConcreteInfo brand tokens and design system.
|
||||||
|
3. Use a single component foundation (shadcn/ui) and a single motion library (Motion / Framer Motion) to keep the dependency surface narrow and the design coherent.
|
||||||
|
4. Keep the main process, preload, and IPC contracts untouched. The renderer is the only surface being rewritten.
|
||||||
|
5. Keep the app runnable at every commit. No "big bang" merge.
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- Migrating the main process to TypeScript (out of scope for this spec).
|
||||||
|
- Adding new features the legacy renderer does not have (plugin system, AI features, etc. — those are future specs).
|
||||||
|
- Replacing Pandoc/FFmpeg/ImageMagick orchestration.
|
||||||
|
- Changing the packaging pipeline (electron-builder config stays).
|
||||||
|
- Replacing the CodeMirror 6 editor — it is the right tool and is already wired up.
|
||||||
|
|
||||||
|
## Decisions Locked During Brainstorming
|
||||||
|
|
||||||
|
| Decision | Choice | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| Scope | Full feature parity with legacy renderer | User-selected option. Renderer is one cohesive surface; splitting it across specs would force premature contracts. |
|
||||||
|
| Visual style | **B — Polished + Glassy** (Raycast/Arc aesthetic) | "Fancy" comes from elevation, gradient accents, and material depth — not over-designed visuals. |
|
||||||
|
| Layout | **2 — IDE-style** (equal editor/preview, draggable divider, collapsible sidebar) | Power-user markdown apps converge on this. Draggable divider + keyboard reset. |
|
||||||
|
| Modal patterns | **A (Centered Dialog), B (Right Side-Sheet), D (Toasts)** | No command palette. |
|
||||||
|
| Command palette | **No** — full menus, no ⌘K | Power users can use the OS-level launcher. App stays focused on writing. |
|
||||||
|
| Animation | **Motion (Framer Motion)** | Best for layout transitions, modal/drawer enter/exit, drag. Sparingly used. |
|
||||||
|
| Component library | **shadcn/ui** | Tailwind + Radix primitives, copy-paste ownership, perfect fit for the "glassy" aesthetic and the HSL-CSS-variable foundation that is already in place. |
|
||||||
|
| Implementation strategy | **Vertical slices** — one feature end-to-end per PR | App stays runnable. Each PR is reviewable. |
|
||||||
|
|
||||||
|
## Defaults (Used Unless Overridden Later)
|
||||||
|
|
||||||
|
| Item | Default | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| State management | Zustand (already in deps) + Immer for nested patches | Already in `package.json`; perfect for editor state. |
|
||||||
|
| Theming | shadcn `next-themes`, dark default + light, system-aware | shadcn canonical pattern. Brand colors already in CSS vars. |
|
||||||
|
| Icons | `lucide-react` (already in deps) | 1000+ tree-shakable icons. |
|
||||||
|
| Forms | `react-hook-form` + `zod` | Standard for shadcn forms. |
|
||||||
|
| Drag/drop (sortable lists) | `@dnd-kit/core` | De facto React drag lib (file tree reordering, plugin list reorder). |
|
||||||
|
| Pane resize (split layout) | `react-resizable-panels` | Canonical React lib for resizable pane groups; handles drag, arrow keys, snap, persisted sizes. |
|
||||||
|
| Testing | Vitest + RTL + Playwright (E2E + visual regression) | Standard for React + Electron. |
|
||||||
|
| TypeScript | Strict mode (already wired) | Already in deps and `vite.renderer.config.ts`. |
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The Electron app keeps its existing process model. Only the renderer is rewritten.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ Electron Main (UNCHANGED) │
|
||||||
|
│ - BrowserWindow, IPC handlers, file/fs ops │
|
||||||
|
│ - Pandoc, FFmpeg, ImageMagick orchestration │
|
||||||
|
└────────────┬─────────────────────────────────────────────┘
|
||||||
|
│ contextBridge (UNCHANGED preload.js)
|
||||||
|
┌────────────▼─────────────────────────────────────────────┐
|
||||||
|
│ React Renderer (REWRITTEN) │
|
||||||
|
│ ┌────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ AppShell (layout) │ │
|
||||||
|
│ │ ├─ MenuBar (native) │ │
|
||||||
|
│ │ ├─ AppHeader (logo, breadcrumbs, theme toggle) │ │
|
||||||
|
│ │ ├─ TabBar (open files) │ │
|
||||||
|
│ │ ├─ Toolbar (formatting) │ │
|
||||||
|
│ │ ├─ ResizablePaneGroup (sidebar | editor | preview) │ │
|
||||||
|
│ │ │ ├─ Sidebar (file tree, outline) │ │
|
||||||
|
│ │ │ ├─ EditorPane (CodeMirror 6) │ │
|
||||||
|
│ │ │ └─ PreviewPane (marked + KaTeX + Mermaid) │ │
|
||||||
|
│ │ ├─ StatusBar (word count, encoding, cursor pos) │ │
|
||||||
|
│ │ └─ ModalLayer (Dialog, SideSheet, Toaster) │ │
|
||||||
|
│ └────────────────────────────────────────────────────┘ │
|
||||||
|
│ ┌────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Feature Modules (each owns UI + state slice) │ │
|
||||||
|
│ │ ├─ editor/ CodeMirror wrapper, syntax, themes │ │
|
||||||
|
│ │ ├─ preview/ markdown→html, KaTeX, Mermaid │ │
|
||||||
|
│ │ ├─ tabs/ open files, dirty state │ │
|
||||||
|
│ │ ├─ sidebar/ file tree, outline, search results │ │
|
||||||
|
│ │ ├─ modals/ export, settings, about, etc. │ │
|
||||||
|
│ │ ├─ tools/ zen, repl, ascii-gen, table-gen │ │
|
||||||
|
│ │ └─ export/ pdf, docx, html, image batch │ │
|
||||||
|
│ └────────────────────────────────────────────────────┘ │
|
||||||
|
│ ┌────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Shared Infrastructure │ │
|
||||||
|
│ │ ├─ stores/ Zustand slices per feature │ │
|
||||||
|
│ │ ├─ hooks/ useFile, useEditor, useTheme, etc. │ │
|
||||||
|
│ │ ├─ lib/ cn, ipc, formatters, validators │ │
|
||||||
|
│ │ ├─ ui/ shadcn primitives: button, dialog… │ │
|
||||||
|
│ │ └─ types/ shared TS types │ │
|
||||||
|
│ └────────────────────────────────────────────────────┘ │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Architectural Rules
|
||||||
|
|
||||||
|
- **Shell components** (`AppHeader`, `TabBar`, `StatusBar`) subscribe only to `useAppStore`.
|
||||||
|
- **Feature components** subscribe to their own feature's store.
|
||||||
|
- **Cross-feature access** goes through hooks, not direct store imports (e.g., `useFileTree()` wraps `useFileStore`).
|
||||||
|
- **Feature modules are self-contained** — each owns its components, its Zustand slice, and its types. Safe to develop in parallel later.
|
||||||
|
- **No direct `window.electronAPI` calls** from feature code. All IPC goes through `lib/ipc.ts` for type safety and error normalization.
|
||||||
|
|
||||||
|
## State Management
|
||||||
|
|
||||||
|
```
|
||||||
|
stores/
|
||||||
|
├─ useAppStore // global UI: theme, sidebar, pane sizes, modals open
|
||||||
|
├─ useFileStore // file system: tree, open files, active tab
|
||||||
|
├─ useEditorStore // editor: per-file content, cursor, selection, dirty
|
||||||
|
├─ usePreviewStore // preview: scroll sync, zoom, theme
|
||||||
|
├─ useSettingsStore // user prefs (persisted to electron-store)
|
||||||
|
└─ useCommandStore // menu actions registry, recent actions
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why slices instead of one mega-store?** Editor content can be megabytes. Keeping it in its own slice lets React avoid re-rendering the preview when only the editor changes — components subscribe with selectors.
|
||||||
|
|
||||||
|
**Persistent state** (auto-saved to electron-store via Zustand `persist` middleware): theme, sidebar visibility, last open files, pane divider positions, settings.
|
||||||
|
|
||||||
|
**Ephemeral state** (lost on quit): active modal, hover states, search query, current file content (saved to disk on idle).
|
||||||
|
|
||||||
|
## Visual Design System
|
||||||
|
|
||||||
|
### Color Tokens
|
||||||
|
|
||||||
|
The existing `globals.css` HSL variables stay. Additions for the "glassy" aesthetic:
|
||||||
|
|
||||||
|
```css
|
||||||
|
--shadow-sm: 0 1px 2px rgba(13, 11, 9, 0.06);
|
||||||
|
--shadow-md: 0 4px 12px rgba(13, 11, 9, 0.08), 0 0 0 1px rgba(13, 11, 9, 0.04);
|
||||||
|
--shadow-lg: 0 12px 32px rgba(13, 11, 9, 0.12), 0 0 0 1px rgba(13, 11, 9, 0.06);
|
||||||
|
--shadow-glow-brand: 0 0 24px rgba(229, 70, 31, 0.25);
|
||||||
|
|
||||||
|
--glass-bg-light: rgba(255, 255, 255, 0.72);
|
||||||
|
--glass-bg-dark: rgba(13, 11, 9, 0.72);
|
||||||
|
--glass-border-light: rgba(255, 255, 255, 0.4);
|
||||||
|
--glass-border-dark: rgba(255, 255, 255, 0.08);
|
||||||
|
```
|
||||||
|
|
||||||
|
### shadcn Components
|
||||||
|
|
||||||
|
Install via `npx shadcn@latest add`:
|
||||||
|
|
||||||
|
**Primitives** (need all of these): `button`, `dialog`, `sheet`, `popover`, `tooltip`, `select`, `dropdown-menu`, `tabs`, `separator`, `scroll-area`, `toggle`, `switch`, `slider`, `input`, `textarea`, `label`, `form`, `skeleton`, `sonner`, `command`.
|
||||||
|
|
||||||
|
**Composite** (custom-built on top of primitives): `file-tree`, `pane-group`, `divider`, `status-bar`, `menu-bar`, `toast`.
|
||||||
|
|
||||||
|
### Typography
|
||||||
|
|
||||||
|
- Body: Plus Jakarta Sans 15 px / line-height 1.6
|
||||||
|
- Code: JetBrains Mono 13.5 px
|
||||||
|
- Display: Barlow Condensed 700/800 — used sparingly (page titles, big metrics)
|
||||||
|
- Headings: Plus Jakarta Sans 600/700 with tight letter-spacing
|
||||||
|
- Labels (`.label`): Plus Jakarta Sans 500, 12 px, uppercase, 0.05 em letter-spacing
|
||||||
|
|
||||||
|
### Motion Choreography
|
||||||
|
|
||||||
|
| Element | Motion | Duration | Easing |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Modal (Dialog A) | Scale 0.96→1, opacity 0→1 | 200 ms | `ease-out` |
|
||||||
|
| Side sheet (B) | TranslateX 100%→0, opacity 0→1 | 300 ms | `cubic-bezier(0.16, 1, 0.3, 1)` |
|
||||||
|
| Toast | TranslateY 100%→0, opacity | 250 ms | spring(stiffness: 300, damping: 30) |
|
||||||
|
| Sidebar toggle | Width 264 px↔72 px, content fade | 250 ms | `ease-in-out` |
|
||||||
|
| Divider drag | Live width update | 0 ms | none (instant) |
|
||||||
|
| Theme switch | CSS variables, opacity overlay | 300 ms | `ease-in-out` |
|
||||||
|
| Tab switch | Underline slide | 200 ms | `ease-out` |
|
||||||
|
| Hover (buttons) | `bg` + `shadow` shift | 150 ms | `ease-out` |
|
||||||
|
| Focus ring | Outline grow | 100 ms | `ease-out` |
|
||||||
|
|
||||||
|
**Rules:** Every motion has a purpose. No gratuitous animation. Respects `prefers-reduced-motion` (Motion handles this automatically).
|
||||||
|
|
||||||
|
### Empty / Loading / Error States
|
||||||
|
|
||||||
|
Every async surface ships all three. Sonner toasts for ephemeral feedback. Skeleton screens for content areas. Empty-state components with icon + message + primary CTA.
|
||||||
|
|
||||||
|
## Modal/Overlay Patterns
|
||||||
|
|
||||||
|
| Use case | Pattern | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| Export (PDF/DOCX/HTML) | A — Centered Dialog | Focused decision, ~3–5 fields, "do one thing" |
|
||||||
|
| Settings | B — Right Side-Sheet | Long form, tabbed sections, stays open while editing |
|
||||||
|
| Find/Replace | Inline toolbar (not modal) | Always-visible utility |
|
||||||
|
| About | A — Centered Dialog | Tiny info dump |
|
||||||
|
| Confirm destructive (delete, close unsaved) | A — Centered Dialog | Forces attention |
|
||||||
|
| File save error | D — Toast | Non-blocking info |
|
||||||
|
| Pandoc/FFmpeg progress | D — Toast → sticky on >3 s | Background work feedback |
|
||||||
|
| Plugin manager | B — Right Side-Sheet | Lists + per-item actions |
|
||||||
|
| ASCII/Table generators | A — Centered Dialog | Tool-style focused input → output |
|
||||||
|
| Print preview | A — Centered Dialog | Full-screen-ish modal overlay |
|
||||||
|
| Welcome (first launch) | A — Centered Dialog | One-time onboarding |
|
||||||
|
| Word export | A — Centered Dialog | Template selection |
|
||||||
|
| Zen mode | Full-viewport toggle (no modal) | Replaces the editor entirely |
|
||||||
|
| REPL | Bottom-pinned panel (split-pane) | Persistent terminal-like UI |
|
||||||
|
| Quick file open | B — Right Side-Sheet | File tree, search, recent |
|
||||||
|
|
||||||
|
### Dialog A Anatomy (Export as example)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─ Backdrop (rgba(13,11,9,0.45) + backdrop-blur 4px) ─────────┐
|
||||||
|
│ │
|
||||||
|
│ ┌──── Modal (max-w-md, rounded-2xl, shadow-lg) ─────┐ │
|
||||||
|
│ │ ┌── Header ────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ [Icon] Export as PDF [×] │ │ │
|
||||||
|
│ │ │ Choose format options │ │ │
|
||||||
|
│ │ └─────────────────────────────────────────────┘ │ │
|
||||||
|
│ │ ┌── Body ──────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ Format: [Letter] [A4] [Legal] │ │ │
|
||||||
|
│ │ │ Margins: ────●──── │ │ │
|
||||||
|
│ │ │ ☐ Include table of contents │ │ │
|
||||||
|
│ │ │ ☐ Embed fonts │ │ │
|
||||||
|
│ │ └─────────────────────────────────────────────┘ │ │
|
||||||
|
│ │ ┌── Footer ────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ [Cancel] [Export →] │ │ │
|
||||||
|
│ │ └─────────────────────────────────────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
└────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Side-Sheet B Anatomy (Settings as example)
|
||||||
|
|
||||||
|
Slides in from right, ~50 % width (max 560 px). Backdrop is `rgba(13,11,9,0.2)` with `backdrop-blur(2 px)` (lighter than dialog — the sheet is the focus). Tab navigation in the sheet header (Editor / Theme / Export / Plugins / About).
|
||||||
|
|
||||||
|
### Toast D Anatomy (Sonner)
|
||||||
|
|
||||||
|
Stacked bottom-right, max 3 visible. Glass background. Color-coded 3 px left border — success `#1a7a56`, error `#ef4444`, info `#0ea5e9`, warning `#eab308`. Icon + title + description. Optional action button. Auto-dismiss 4 s for success, sticky for error.
|
||||||
|
|
||||||
|
## Data Flow (Editor → Preview Pipeline)
|
||||||
|
|
||||||
|
```
|
||||||
|
User types
|
||||||
|
↓
|
||||||
|
CodeMirror onChange
|
||||||
|
↓
|
||||||
|
useEditorStore.updateContent(tabId, content) ← debounced 50 ms
|
||||||
|
↓
|
||||||
|
┌─ Persist to electron-store on idle (1 s) ─┐
|
||||||
|
│ │
|
||||||
|
└─ Publish to usePreviewStore (subscribed) ─┘
|
||||||
|
↓
|
||||||
|
marked(content) → sanitized HTML
|
||||||
|
↓
|
||||||
|
PreviewPane renders HTML
|
||||||
|
KaTeX post-processes $...$
|
||||||
|
Mermaid post-processes ```mermaid
|
||||||
|
Highlight.js post-processes ```lang
|
||||||
|
↓
|
||||||
|
useEffect: scroll-sync editor cursor → preview position
|
||||||
|
```
|
||||||
|
|
||||||
|
**Bidirectional scroll sync:** editor scroll → preview (primary), preview click → editor cursor (secondary). Throttled to 60 fps via `requestAnimationFrame`.
|
||||||
|
|
||||||
|
## IPC Contract
|
||||||
|
|
||||||
|
The preload bridge stays unchanged. A new `src/renderer/lib/ipc.ts` wraps every channel with TypeScript types and normalizes errors to a discriminated union:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type IpcResult<T> =
|
||||||
|
| { ok: true; data: T }
|
||||||
|
| { ok: false; error: { code: string; message: string } };
|
||||||
|
|
||||||
|
export const ipc = {
|
||||||
|
file: {
|
||||||
|
open: (): Promise<IpcResult<FileResult>>,
|
||||||
|
read: (path: string): Promise<IpcResult<string>>,
|
||||||
|
write: (path: string, content: string): Promise<IpcResult<void>>,
|
||||||
|
list: (dir: string): Promise<IpcResult<FileEntry[]>>,
|
||||||
|
onChange: (cb: (path: string) => void) => () => void,
|
||||||
|
},
|
||||||
|
export: {
|
||||||
|
pdf: (opts: PdfOptions): Promise<IpcResult<ExportResult>>,
|
||||||
|
docx: (opts: DocxOptions): Promise<IpcResult<ExportResult>>,
|
||||||
|
html: (opts: HtmlOptions): Promise<IpcResult<ExportResult>>,
|
||||||
|
batch: (items: BatchItem[], opts: BatchOptions): Promise<IpcResult<BatchResult>>,
|
||||||
|
},
|
||||||
|
app: {
|
||||||
|
getVersion: (): Promise<IpcResult<string>>,
|
||||||
|
openExternal: (url: string): Promise<IpcResult<void>>,
|
||||||
|
showItemInFolder: (path: string): Promise<IpcResult<void>>,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
Layered defense — no single failure can crash the app:
|
||||||
|
|
||||||
|
1. **IPC errors** → caught in `lib/ipc.ts` wrapper, returned as `IpcResult<T>` discriminated union. Components show toast on error.
|
||||||
|
2. **Component errors** → React error boundary per feature area (one for editor, one for preview, one for modals). On error: show inline error UI with "Reload this panel" + "Copy details" actions.
|
||||||
|
3. **Async operations** (export, file ops) → loading state on button + toast on completion. Long ops (>2 s) get a sticky toast with cancel.
|
||||||
|
4. **Validation errors** (settings, export options) → inline form errors via `react-hook-form` + `zod`. shadcn `Form` component for consistent error display.
|
||||||
|
5. **Pandoc/FFmpeg missing** → detected at startup, banner + disable export menu items. Don't surprise-fail at export time.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- **Unit (Vitest):** stores, hooks, lib utilities, formatters, validators
|
||||||
|
- **Component (Vitest + RTL):** shadcn wrappers, dialog interactions, sidebar toggle, divider drag, theme toggle
|
||||||
|
- **Integration (Vitest + RTL):** editor ↔ preview flow, file open → tab add → content display, settings change persists
|
||||||
|
- **E2E (Playwright):** app launches, file opens, markdown renders, export to PDF works
|
||||||
|
- **Visual regression (Playwright snapshots):** locked-in screenshots for header, sidebar, dialogs, toasts — catch accidental style drift
|
||||||
|
- **Target coverage:** stores/hooks/lib ≥ 90 %, components ≥ 75 %, E2E covers all critical paths
|
||||||
|
|
||||||
|
## Accessibility (WCAG 2.1 AA)
|
||||||
|
|
||||||
|
Baked in via shadcn + Radix:
|
||||||
|
|
||||||
|
- All dialogs focus-trap, Esc to close, return focus to trigger
|
||||||
|
- All interactive elements keyboard-reachable
|
||||||
|
- Visible focus rings (2 px brand ring)
|
||||||
|
- 4.5:1 contrast minimum (already met by brand colors)
|
||||||
|
- `aria-label` on icon buttons, `role="alert"` on toasts
|
||||||
|
- Respects `prefers-reduced-motion` (Motion handles this automatically)
|
||||||
|
|
||||||
|
## Implementation Phases (Vertical Slices)
|
||||||
|
|
||||||
|
Each phase is a shippable PR that keeps the app runnable. The legacy `renderer.js` is gradually replaced; until each phase is complete, the old renderer code still runs the missing parts.
|
||||||
|
|
||||||
|
| # | Phase | Output | Acceptance |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | **Foundation** | shadcn installed; `next-themes`, `motion`, `react-hook-form`, `zod`, `@dnd-kit/core`, `react-resizable-panels`, `sonner` installed; design tokens finalized; `lib/utils.ts` (`cn`), `lib/ipc.ts` typed wrappers, `lib/motion.ts` preset transitions, `App.tsx` shell skeleton renders | `npm run build` succeeds; dev server shows the new shell with theme toggle working |
|
||||||
|
| 2 | **App shell + layout** | `AppHeader`, `TabBar`, `Toolbar`, `Breadcrumb`, `StatusBar`, `ResizablePaneGroup` with sidebar toggle and draggable divider. Empty editor/preview panes. | Resize divider with mouse and arrow keys; sidebar collapses; pane sizes persist. |
|
||||||
|
| 3 | **Editor pane** | CodeMirror 6 wrapped, dark/light themes wired to shadcn theme, syntax highlighting, line numbers, search, autocomplete | Open `.md` file → renders in editor; can edit and save. |
|
||||||
|
| 4 | **Preview pane** | marked + DOMPurify + KaTeX + Mermaid + highlight.js. Bidirectional scroll sync with editor. | Open file → preview renders, follows cursor. |
|
||||||
|
| 5 | **File tree + tabs** | Sidebar file tree (read directory on demand, lazy-expand children only on click). Tabs for open files. Dirty state indicator. File content is read from disk only when the tab is activated. | Open folder → root populates; click folder → children load; click file → opens in tab; close tab reverts dirty. |
|
||||||
|
| 6 | **Native menus + toolbar** | Replace the legacy `CommandPalette` with full menus (File / Edit / View / Insert / Format / Tools / Help) bound to keyboard shortcuts. Toolbar buttons. | All menu items invoke the right action; shortcuts work; toolbar reflects active state. |
|
||||||
|
| 7 | **Modals** | Export dialog (PDF/DOCX/HTML/batch), Settings side-sheet (Editor/Theme/Export/Plugins/About tabs), About dialog, Confirm-destructive dialog | All dialogs and sheet render with proper motion; settings persist; export works end-to-end. |
|
||||||
|
| 8 | **Toasts** | Sonner wired into all async operations (save, export, errors, tool missing) | All operations give appropriate feedback; no silent failures. |
|
||||||
|
| 9 | **Advanced tools** | Zen mode (full-viewport toggle), REPL (bottom-pinned panel), ASCII generator, Table generator, Word export template picker, Print preview | Each tool is feature-complete vs. legacy version. |
|
||||||
|
| 10 | **Polish + delete legacy** | Visual regression snapshots locked; remove `renderer.js` and old `styles*.css` references from build; `npm run build:linux` produces a working installer | Final PR ships an installer with no legacy code paths. |
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Mitigation |
|
||||||
|
|---|---|
|
||||||
|
| shadcn CLI requires Vite (not vanilla Electron renderer) | Vite is already configured for the renderer in `vite.renderer.config.ts`; the CLI works against the same project. |
|
||||||
|
| shadcn CLI assumes Tailwind is at project root; we have it in renderer/ only | Point the CLI at `src/renderer/components.json` and set `tailwind.css` to the right path. |
|
||||||
|
| Marked + KaTeX + Mermaid + highlight.js together is heavy | Lazy-load Mermaid (only when `mermaid` code block encountered). KaTeX is loaded once, cached. |
|
||||||
|
| Editor content state can be megabytes → re-render storms | Editor content lives in its own slice; preview subscribes to a derived/cached HTML string; components use `useShallow` / selector subscriptions. |
|
||||||
|
| Bidirectional scroll sync loops | `useEffect` debounce + ignore if cursor/selection is the sync source. |
|
||||||
|
| CodeMirror 6 doesn't ship a Tailwind theme by default | Use `@codemirror/theme-one-dark` for dark; build a custom theme that pulls from CSS variables for light. |
|
||||||
|
| The legacy `renderer.js` and `styles*.css` are referenced from `index.html` (now `src/renderer/index.html`) | Phase 10 deletes the references; until then, both run side-by-side and the new React app sits in a known root div. |
|
||||||
|
| Electron `nodeIntegration` is off; we use contextBridge | Already the case. Document the contract clearly in `lib/ipc.ts`. |
|
||||||
|
|
||||||
|
## Open Questions (to confirm before implementation)
|
||||||
|
|
||||||
|
None. All major decisions are locked. Defaults will be used unless the user overrides them when reviewing the implementation plan.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `src/renderer.js` (213 KB) — legacy renderer being replaced
|
||||||
|
- `src/styles.css` (74 KB), `src/styles-modern.css` (71 KB), `src/styles-concreteinfo.css` (21 KB) — legacy styles being replaced
|
||||||
|
- `src/renderer/styles/globals.css` — already shadcn-compatible (HSL CSS variables)
|
||||||
|
- `src/renderer/App.tsx` — empty skeleton that references components we will build
|
||||||
|
- `tailwind.config.js` — brand colors and fonts already defined
|
||||||
|
- `vite.renderer.config.ts` — Vite + React plugin already configured
|
||||||
|
- `package.json` — CodeMirror 6, TanStack Table, lucide-react, cva, clsx, tailwind-merge, tailwindcss-animate already installed
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
# MarkdownConverter — Monospace Font Embedding Design
|
|
||||||
|
|
||||||
**Date:** 2026-06-30
|
|
||||||
**Status:** Approved
|
|
||||||
**Author:** Amit Haridas
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
Guarantee proper ASCII character alignment in MarkdownConverter's preview and every supported export format (PDF, DOCX, HTML, plus ODT/RTF/EPUB/LaTeX), with no OS-level font dependency. The user can pick between **JetBrains Mono** (default) and **Fira Code**, and toggle ligatures (default off). Both font families are bundled inside the app, so alignment holds on every supported platform (Windows/macOS/Linux) without an internet connection, without system-wide font installation, and without the user touching anything system-level.
|
|
||||||
|
|
||||||
## Goals
|
|
||||||
|
|
||||||
1. ASCII art and code-block tables (e.g. `+----+----+` column delimiters) render at identical advance widths in the live preview **and** in every exported file.
|
|
||||||
2. No OS font dependency — TTFs ship inside the app.
|
|
||||||
3. Per-user choice of monospace family + ligature behaviour.
|
|
||||||
4. Self-contained exports: the exported PDF/DOCX/HTML file is portable to another machine and stays aligned.
|
|
||||||
|
|
||||||
## Non-Goals (v1)
|
|
||||||
|
|
||||||
- No font subsetting of TTFs (we ship the full file; xelatex subsets it into the PDF automatically; DOCX carriers get the full TTF in `word/fonts/`).
|
|
||||||
- No support for the user adding a third bundled font family.
|
|
||||||
- No PPTX or revealjs/Beamer ligature-toggle (PPTX is a slide format that rarely carries ASCII tables; revealjs/Beamer inherit HTML/LaTeX defaults).
|
|
||||||
- No licensed/commercial fonts (Fira Code and JetBrains Mono are both SIL OFL — confirmed in `assets/fonts/JetBrainsMono-LICENSE.txt`).
|
|
||||||
|
|
||||||
## Decisions Locked
|
|
||||||
|
|
||||||
| Decision | Choice | Reason |
|
|
||||||
|---|---|---|
|
|
||||||
| Scope | All export formats | All-surfaces alignment |
|
|
||||||
| DOCX strategy | Embed TTF into the DOCX zip | Truly portable; alignment holds even when the recipient lacks the font |
|
|
||||||
| PDF strategy | Pass TTF path to xelatex via `fontspec` (`\setmonofont[Path=...]`) | xelatex subsets the font into the PDF; reproducible across machines |
|
|
||||||
| Font choice | Both bundled; user-pickable in settings | Cover both preferences; default JetBrains Mono |
|
|
||||||
| Ligatures | Off by default; user toggle | Ligatures change advance widths and break ASCII grid alignment |
|
|
||||||
| License | SIL OFL (both families) | Embedding/bundling explicitly permitted when license travels with the binary (already present at `assets/fonts/JetBrainsMono-LICENSE.txt`) |
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
settings.json
|
|
||||||
│
|
|
||||||
│ (renderer + main read on init)
|
|
||||||
▼
|
|
||||||
CSS body classes: .mono-jetbrains / .mono-fira
|
|
||||||
.mono-ligatures-on / .mono-ligatures-off
|
|
||||||
--font-mono-active token
|
|
||||||
▲ ▲
|
|
||||||
│ IPC │ IPC
|
|
||||||
│ │
|
|
||||||
Preview pane ┌───────────┴──────────┐
|
|
||||||
ASCII Generator window │ Export pipeline │
|
|
||||||
Print-preview iframe │ (main process) │
|
|
||||||
│ uses MonospaceFontConfig
|
|
||||||
└──────────────────────┘
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
Bundle: assets/fonts/
|
|
||||||
├─ JetBrainsMono-Regular.ttf
|
|
||||||
├─ JetBrainsMono-Bold.ttf
|
|
||||||
├─ FiraCode-Regular.ttf
|
|
||||||
├─ FiraCode-Bold.ttf
|
|
||||||
└─ (existing woff2 for renderer)
|
|
||||||
```
|
|
||||||
|
|
||||||
## New Modules
|
|
||||||
|
|
||||||
| File | Role |
|
|
||||||
|---|---|
|
|
||||||
| `src/main/MonospaceFontConfig.js` | Single source of truth. Resolves the active monospace family + weight → absolute TTF path, with awareness of dev vs packaged (asar.unpacked) layout. Returns `null` + warns when a file is missing. |
|
|
||||||
| `src/main/PdfFontHeader.js` | Builds the xelatex `header.tex` snippet with `\usepackage{fontspec}\setmonofont{...ttf}[Path=...,UprightFont=*-Regular,BoldFont=*-Bold,Ligatures=NoCommon/TeX]`. Also returns the lualatex equivalent. |
|
|
||||||
| `src/main/DocxFontEmbedder.js` | Unzips a pandoc-produced DOCX with `jszip`, writes TTFs into `word/fonts/`, patches `[Content_Types].xml`, `_rels/document.xml.rels`, creates `word/fontTable.xml` with `<w:embedRegular/>` referencing the TTF, patches `word/styles.xml` so the `SourceCode`/`VerbatimChar` styles bind to the embedded font name, then rezips. Idempotent. |
|
|
||||||
| `src/main/EpubFontEmbedder.js` | Wrapper around pandoc `--epub-embed-font` — verifies the chosen TTF is referenced in `OEBPS/content.opf`; patches the manifest if missing. |
|
|
||||||
| `src/main/ExportCss.js` | Returns a self-contained CSS string with `@font-face { src: url(data:font/woff2;base64,...) }` for the chosen family. Used by HTML export `--css` and by print-preview iframe. |
|
|
||||||
| `src/main/settings/SettingsUI.Monospace.js` | Two new controls in the in-app settings dialog: monospace font select + ligatures checkbox. Persists to `<userData>/settings.json`. |
|
|
||||||
|
|
||||||
## Modified Modules
|
|
||||||
|
|
||||||
| File | Change |
|
|
||||||
|---|---|
|
|
||||||
| `src/fonts.css` | Add `@font-face` entries for Fira Code Regular (400) and Bold (700), pointing to `assets/fonts/FiraCode-*.woff2` (downloaded via the extended `download-tools.js`). |
|
|
||||||
| `src/styles/tokens.css` + `src/styles-concreteinfo.css` | Define new tokens `--font-mono-active` (resolves to `"JetBrains Mono"` or `"Fira Code"`) and `--font-mono-feature` (`"liga" 0, "calt" 0, "dlig" 0` for ligatures-off, else `normal`). Body classes flip these. |
|
|
||||||
| `src/styles-modern.css` | `.editor-textarea`, `.preview-content code`, `.preview-content pre`, `.codemirror-container .cm-editor` reference `var(--font-mono-active)` and apply `font-feature-settings: var(--font-mono-feature)`. |
|
|
||||||
| `src/ascii-generator.html` | Replace `<link href="https://fonts.googleapis.com/...">` with `<link rel="stylesheet" href="../styles/fonts.css">` plus inline `body` class defaulting. The window is plain HTML; the renderer script that opens it sets `body.classList` from settings. |
|
|
||||||
| `src/print-preview.js` | Inject `<style>` with embedded woff2 base64 from `ExportCss.js` into the srcdoc iframe HTML; set `pre`/`code` font-family to `var(--font-mono-active)`. |
|
|
||||||
| `src/main.js` | Five `--css/-V monofont=Consolas` lines and the export pipelines need surgery (table below). On successful DOCX export, pipeline the output through `DocxFontEmbedder`. On HTML export, pass `--css` referencing a temp file emitted by `ExportCss.js`. On EPUB, pass `--epub-embed-font` for both Regular and Bold. On LaTeX/PDF, pass `--include-in-header` referencing a temp `header.tex` emitted by `PdfFontHeader.js`. The Electron `printToPDF` fallback also consumes `ExportCss.js`. |
|
|
||||||
| `src/renderer.js` | On `settings-changed`, toggle `document.body.classList` between `mono-jetbrains` / `mono-fira` and `mono-ligatures-on` / `mono-ligatures-off`. The active class is also written by the bit that initializes Monaco/CodeMirror when the editor is mounted. |
|
|
||||||
| `scripts/download-tools.js` | Add `fira-code` task: downloads `FiraCode-Regular.ttf`, `FiraCode-Bold.ttf`, `FiraCode-LICENSE.txt` from the official `tonsky/FiraCode` GitHub release (version-pinned, mirrors how Pandoc is downloaded). |
|
|
||||||
| `package.json` | `build.asarUnpack` extended to `"assets/fonts/**"` so xelatex/Pandoc can read TTFs at runtime in packaged builds. No new NPM dependencies — `jszip ^3.10.1` is already present. |
|
|
||||||
|
|
||||||
## Per-Export Behaviour
|
|
||||||
|
|
||||||
| Format | What changes | Post-processing | Resulting file shape |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **PDF** (xelatex) | Replace `-V monofont="Consolas"` with `--include-in-header=<tmp>.tex` from `PdfFontHeader` (`\setmonofont{JetBrainsMono-Regular.ttf}[Path=…,Extension=.ttf,UprightFont=*-Regular,BoldFont=*-Bold,Ligatures=NoCommon]`). | none — xelatex subsets the font into the PDF. | Self-contained PDF; code-block columns align across pages. |
|
|
||||||
| **PDF** (lualatex fallback) | Same header uses lualatex-compatible fontspec syntax (identical to xelatex in modern LuaTeX). | none | Same as above. |
|
|
||||||
| **PDF** (pdflatex final fallback) | Revert to `-V monofont="Consolas"` + warn (Consolas not on all systems; document limitation). | none | Best-effort — relies on pdftex default monospace. |
|
|
||||||
| **DOCX** | Existing pandoc invocation. After pandoc writes, hand to `DocxFontEmbedder`. | Embed Regular + Bold TTF into `word/fonts/`; patch `[Content_Types].xml` Default+Override; add `word/_rels` entry for `fontTable.xml.rels`; create `word/fontTable.xml` with `<w:embedRegular/>` for each font weight; patch `word/styles.xml` so `SourceCode` (or whatever style Pandoc wrote under) sets `w:rFonts ascii="JetBrains Mono" hAnsi="JetBrains Mono"`. | ~550 KB larger DOCX; fully portable. |
|
|
||||||
| **HTML** (standalone) | Add `--css=<tmp>.css` (built by `ExportCss` with base64 woff2). | none | One self-contained `.html`; aligned anywhere, offline. |
|
|
||||||
| **EPUB** | Add `--epub-embed-font=<bundleAbs>/<Family>-Regular.ttf` and same for Bold (Pandoc 2.11+ supports this natively). | `EpubFontEmbedder` patches `OEBPS/content.opf` if the font reference is missing. | Embedded font travels in the EPUB. |
|
|
||||||
| **ODT** | `--variable=mainfont="JetBrains Mono"` (or Fira). | Before final write, show a non-blocking confirmation: "ODT embeds the font *name* — recipients must also have it installed to keep alignment. Continue?". | Light; portability caveat explicit to user. |
|
|
||||||
| **RTF** | `\fonttbl` directive already injected by pandoc when `mainfont=` is set. | Same ODT confirmation. | Same caveat as ODT. |
|
|
||||||
| **LaTeX (`.tex`)** | `--include-in-header=<tmp>.tex` identical to the PDF header. | none | Self-contained `.tex` for downstream compile. |
|
|
||||||
| **PPTX** | unchanged | n/a | v1: don't try to enforce. |
|
|
||||||
| **RevealJS** | behaves like HTML (uses `ExportCss`). | n/a | self-contained. |
|
|
||||||
| **Beamer** | behaves like LaTeX (uses `PdfFontHeader` snippet). | n/a | downstream PDF compile respects font. |
|
|
||||||
| **Print preview** | n/a | `ExportCss` injected into srcdoc iframe HTML. | Inside-app preview aligned. |
|
|
||||||
| **ASCII Generator window** | Replace Google Fonts CDN link with local `fonts.css`. | n/a | Offline, aligned. |
|
|
||||||
|
|
||||||
## Path Resolution
|
|
||||||
|
|
||||||
`MonospaceFontConfig` exposes:
|
|
||||||
|
|
||||||
```js
|
|
||||||
exports.getActiveMonoFontPath = function getActiveMonoFontPath(weight = 400)
|
|
||||||
exports.getActiveMonoFamily = function getActiveMonoFamily()
|
|
||||||
exports.ligaturesEnabled = function ligaturesEnabled()
|
|
||||||
```
|
|
||||||
|
|
||||||
- Dev: `<repoRoot>/assets/fonts/<Family>-<Weight>.ttf`
|
|
||||||
- Packaged: `<process.resourcesPath>/app.asar.unpacked/assets/fonts/<Family>-<Weight>.ttf`
|
|
||||||
- If the file is missing, returns `null` and emits a `console.warn` + a single non-blocking toast: "Using system monospace — bundled font missing".
|
|
||||||
|
|
||||||
## Settings Schema
|
|
||||||
|
|
||||||
Extended `<userData>/settings.json`:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
// ... existing keys ...
|
|
||||||
"monospaceFont": "jetbrains-mono", // "jetbrains-mono" | "fira-code"
|
|
||||||
"monospaceLigatures": false // bool
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Defaults: `monospaceFont: "jetbrains-mono"`, `monospaceLigatures: false`. Migration: if a settings file exists without these keys, fill with defaults silently on read.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
**New test files:**
|
|
||||||
|
|
||||||
| File | Asserts |
|
|
||||||
|---|---|
|
|
||||||
| `tests/monospace-font-config.test.js` | Dev vs packaged path semantics; null-and-warn on missing TTF; settings-driven family selection. |
|
|
||||||
| `tests/docx-font-embedder.test.js` | Produces a valid DOCX; `unzip -l` lists `word/fonts/JetBrainsMono-{Regular,Bold}.ttf`; `word/fontTable.xml` contains `<w:embedRegular r:id="…"/>` entries with correct names; `styles.xml` binds the monospace style to `"JetBrains Mono"`; idempotent (running twice doesn't double-embed). |
|
|
||||||
| `tests/pdf-font-header.test.js` | Output contains `\setmonofont{JetBrainsMono-Regular.ttf}` with `Path=` matching the resolved absolute path; `Ligatures=NoCommon` when settings say off. |
|
|
||||||
| `tests/export-css.test.js` | Output contains a `@font-face` block with `src: url('data:font/woff2;base64,<…>')`; the base64 string decodes to > 50 000 bytes; `pre`/`code`/`kbd` use `var(--font-mono-active)`. |
|
|
||||||
| `tests/epub-font-embedder.test.js` | After embedding, `OEBPS/content.opf` references both Regular and Bold TTFs in `<manifest>`. |
|
|
||||||
|
|
||||||
**Integration test (manual, repeatable):**
|
|
||||||
|
|
||||||
1. Create a fixture markdown file with three ASCII grids (boxes, columns, arrows).
|
|
||||||
2. Open the file in MarkdownConverter.
|
|
||||||
3. Set monospace font = JetBrains Mono, ligatures off.
|
|
||||||
4. Export to PDF / DOCX / HTML.
|
|
||||||
5. Open each result; confirm the `+---+` column delimiters sit at identical X-positions across all three formats and across pages.
|
|
||||||
6. Switch to Fira Code with ligatures on; export again; confirm round-trip works (no crashes) and ligature toggle affects preview.
|
|
||||||
|
|
||||||
## Error Handling
|
|
||||||
|
|
||||||
| Failure | Behaviour |
|
|
||||||
|---|---|
|
|
||||||
| Bundled TTF missing | `MonospaceFontConfig` returns `null`; renderer/main falls back to system monospace; non-blocking toast; never a silent drop. |
|
|
||||||
| `DocxFontEmbedder` fails (zip corruption, insufficient permissions, missing required OOXML element) | Keep the un-embedded DOCX; show a dialog with the exact failure message and a "Report issue" link. Do **not** claim success. |
|
|
||||||
| `PdfFontHeader` can't write temp tex (filesystem permission) | Show an error dialog naming the permission issue; abort the export. |
|
|
||||||
| Pandoc `--epub-embed-font` not supported (Pandoc < 2.11) | Detect via `pandoc --version` at startup (cache `pandocAvailable` already exists). Skip embedding; warn user that the EPUB will degrade if their reader lacks the font. |
|
|
||||||
| Pandoc `--css` flag missing (Pandoc < 2.0) | Detect via the same version check. Skip the `--css` injection; warn user that the exported HTML is not self-contained for the chosen font. |
|
|
||||||
| xelatex fails after fontspec injection | Existing `tryPdfFallback` chain reorders to `lualatex → pdflatex` (Consolas). Already implemented; the reorder is a one-liner. |
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [ ] All five rows of `Per-Export Behaviour` produce files where ASCII alignment is identical to the editor.
|
|
||||||
- [ ] No new NPM dependencies added (use existing `jszip`, `fontkit`).
|
|
||||||
- [ ] `asarUnpack` covers `assets/fonts/**`.
|
|
||||||
- [ ] Bundle size increase ≤ 1.5 MB (TTFs + Fira TTF + extra metadata).
|
|
||||||
- [ ] No `TODO`/`FIXME`/`HACK` markers in newly touched code.
|
|
||||||
- [ ] Preview, ASCII Generator window, print-preview iframe, PDF, DOCX, HTML, EPUB, ODT all use the same active font + ligature setting (single source of truth).
|
|
||||||
- [ ] On a clean machine with no JetBrains Mono / Fira Code installed system-wide, every export still produces correct alignment.
|
|
||||||
- [ ] Switching between fonts in settings updates preview immediately and is honoured by all subsequent exports in the same session.
|
|
||||||
- [ ] Both font files travel with the binary (`LICENSE.txt` present for both families).
|
|
||||||
|
|
||||||
## File Inventory
|
|
||||||
|
|
||||||
**New (10 files):**
|
|
||||||
|
|
||||||
```
|
|
||||||
src/main/MonospaceFontConfig.js
|
|
||||||
src/main/PdfFontHeader.js
|
|
||||||
src/main/DocxFontEmbedder.js
|
|
||||||
src/main/EpubFontEmbedder.js
|
|
||||||
src/main/ExportCss.js
|
|
||||||
src/main/settings/SettingsUI.Monospace.js
|
|
||||||
tests/monospace-font-config.test.js
|
|
||||||
tests/docx-font-embedder.test.js
|
|
||||||
tests/pdf-font-header.test.js
|
|
||||||
tests/export-css.test.js
|
|
||||||
tests/epub-font-embedder.test.js
|
|
||||||
assets/fonts/FiraCode-Regular.ttf
|
|
||||||
assets/fonts/FiraCode-Bold.ttf
|
|
||||||
assets/fonts/FiraCode-LICENSE.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
**Modified:**
|
|
||||||
|
|
||||||
```
|
|
||||||
src/fonts.css
|
|
||||||
src/styles/tokens.css
|
|
||||||
src/styles-concreteinfo.css
|
|
||||||
src/styles-modern.css
|
|
||||||
src/ascii-generator.html
|
|
||||||
src/print-preview.js
|
|
||||||
src/main.js
|
|
||||||
src/renderer.js
|
|
||||||
scripts/download-tools.js
|
|
||||||
package.json
|
|
||||||
```
|
|
||||||
|
|
||||||
(3 added TTF files counted under "New"; OFL `LICENSE.txt` only required when bundling Fira Code.)
|
|
||||||
+12
-10
@@ -11,7 +11,10 @@ module.exports = {
|
|||||||
rootDir: '.',
|
rootDir: '.',
|
||||||
|
|
||||||
// Test file patterns
|
// Test file patterns
|
||||||
testMatch: ['**/tests/**/*.test.js', '**/tests/**/*.spec.js'],
|
testMatch: [
|
||||||
|
'**/tests/**/*.test.js',
|
||||||
|
'**/tests/**/*.spec.js'
|
||||||
|
],
|
||||||
|
|
||||||
// Coverage configuration
|
// Coverage configuration
|
||||||
collectCoverageFrom: [
|
collectCoverageFrom: [
|
||||||
@@ -19,7 +22,7 @@ module.exports = {
|
|||||||
'!src/main.js', // Main process needs electron-mock
|
'!src/main.js', // Main process needs electron-mock
|
||||||
'!src/renderer.js', // Large renderer file with duplicate declarations
|
'!src/renderer.js', // Large renderer file with duplicate declarations
|
||||||
'!src/preload.js', // Electron preload requires contextBridge
|
'!src/preload.js', // Electron preload requires contextBridge
|
||||||
'!**/node_modules/**',
|
'!**/node_modules/**'
|
||||||
],
|
],
|
||||||
|
|
||||||
// Coverage thresholds (raised with expanded test suite)
|
// Coverage thresholds (raised with expanded test suite)
|
||||||
@@ -28,8 +31,8 @@ module.exports = {
|
|||||||
branches: 10,
|
branches: 10,
|
||||||
functions: 15,
|
functions: 15,
|
||||||
lines: 15,
|
lines: 15,
|
||||||
statements: 15,
|
statements: 15
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Transform settings (no transpilation needed for vanilla JS)
|
// Transform settings (no transpilation needed for vanilla JS)
|
||||||
@@ -42,11 +45,10 @@ module.exports = {
|
|||||||
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
|
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
|
||||||
|
|
||||||
// Ignore patterns
|
// Ignore patterns
|
||||||
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
|
testPathIgnorePatterns: [
|
||||||
|
'/node_modules/',
|
||||||
// Keep the haste map / snapshot scanner out of build output — electron-builder's
|
'/dist/'
|
||||||
// .snap (Squashfs) artifacts otherwise register as obsolete Jest snapshots.
|
],
|
||||||
modulePathIgnorePatterns: ['/dist/'],
|
|
||||||
|
|
||||||
// Verbose output
|
// Verbose output
|
||||||
verbose: true,
|
verbose: true,
|
||||||
@@ -55,5 +57,5 @@ module.exports = {
|
|||||||
clearMocks: true,
|
clearMocks: true,
|
||||||
|
|
||||||
// Reset modules between tests
|
// Reset modules between tests
|
||||||
resetModules: true,
|
resetModules: true
|
||||||
};
|
};
|
||||||
|
|||||||
Generated
+4425
-146
File diff suppressed because it is too large
Load Diff
+59
-13
@@ -1,13 +1,16 @@
|
|||||||
{
|
{
|
||||||
"name": "markdown-converter",
|
"name": "markdown-converter",
|
||||||
"version": "4.5.0",
|
"version": "4.4.2",
|
||||||
"description": "Professional Markdown editor and universal file converter with PDF editing, batch processing, and syntax highlighting",
|
"description": "Professional Markdown editor and universal file converter with PDF editing, batch processing, and syntax highlighting",
|
||||||
"main": "src/main.js",
|
"main": "src/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "electron .",
|
"start": "electron .",
|
||||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
"test": "jest",
|
||||||
"test:watch": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage",
|
"test:coverage": "jest --coverage",
|
||||||
|
"test:renderer": "vitest run",
|
||||||
|
"test:renderer:watch": "vitest",
|
||||||
|
"test:renderer:coverage": "vitest run --coverage",
|
||||||
"lint": "eslint src tests",
|
"lint": "eslint src tests",
|
||||||
"lint:fix": "eslint src tests --fix",
|
"lint:fix": "eslint src tests --fix",
|
||||||
"format": "prettier --write src tests",
|
"format": "prettier --write src tests",
|
||||||
@@ -43,7 +46,19 @@
|
|||||||
"url": "https://github.com/amitwh/markdown-converter"
|
"url": "https://github.com/amitwh/markdown-converter"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.60.0",
|
||||||
"@testing-library/dom": "^10.4.1",
|
"@testing-library/dom": "^10.4.1",
|
||||||
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
|
"@testing-library/react": "^16.3.2",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
|
"@types/node": "^25.9.1",
|
||||||
|
"@types/react": "^19.2.16",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^6.0.2",
|
||||||
|
"@vitest/ui": "^4.1.8",
|
||||||
|
"autoprefixer": "^10.5.0",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
"cross-env": "^10.0.0",
|
"cross-env": "^10.0.0",
|
||||||
"electron": "^41.1.1",
|
"electron": "^41.1.1",
|
||||||
"electron-builder": "^26.0.12",
|
"electron-builder": "^26.0.12",
|
||||||
@@ -52,7 +67,17 @@
|
|||||||
"eslint-plugin-prettier": "^5.5.4",
|
"eslint-plugin-prettier": "^5.5.4",
|
||||||
"jest": "^30.2.0",
|
"jest": "^30.2.0",
|
||||||
"jest-environment-jsdom": "^30.2.0",
|
"jest-environment-jsdom": "^30.2.0",
|
||||||
"prettier": "^3.7.4"
|
"jsdom": "^29.1.1",
|
||||||
|
"lucide-react": "^1.17.0",
|
||||||
|
"postcss": "^8.5.15",
|
||||||
|
"prettier": "^3.7.4",
|
||||||
|
"sharp": "^0.34.3",
|
||||||
|
"tailwind-merge": "^3.6.0",
|
||||||
|
"tailwindcss": "^3.4.19",
|
||||||
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"typescript": "^6.0.3",
|
||||||
|
"vite": "^8.0.16",
|
||||||
|
"vitest": "^4.1.8"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.20.1",
|
"@codemirror/autocomplete": "^6.20.1",
|
||||||
@@ -69,6 +94,23 @@
|
|||||||
"@codemirror/state": "^6.5.4",
|
"@codemirror/state": "^6.5.4",
|
||||||
"@codemirror/theme-one-dark": "^6.1.3",
|
"@codemirror/theme-one-dark": "^6.1.3",
|
||||||
"@codemirror/view": "^6.39.16",
|
"@codemirror/view": "^6.39.16",
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@hookform/resolvers": "^5.4.0",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
|
"@radix-ui/react-collapsible": "^1.1.12",
|
||||||
|
"@radix-ui/react-context-menu": "^2.2.16",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
|
"@radix-ui/react-radio-group": "^1.3.8",
|
||||||
|
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||||
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
|
"@radix-ui/react-slider": "^1.3.6",
|
||||||
|
"@radix-ui/react-slot": "^1.2.4",
|
||||||
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.13",
|
||||||
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"codemirror": "^6.0.2",
|
"codemirror": "^6.0.2",
|
||||||
"core-util-is": "^1.0.3",
|
"core-util-is": "^1.0.3",
|
||||||
"docx": "^9.6.0",
|
"docx": "^9.6.0",
|
||||||
@@ -78,18 +120,26 @@
|
|||||||
"ffmpeg-static": "^5.3.0",
|
"ffmpeg-static": "^5.3.0",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
"html2pdf.js": "^0.14.0",
|
"html2pdf.js": "^0.14.0",
|
||||||
"jszip": "^3.10.1",
|
"immer": "^11.1.8",
|
||||||
"marked": "^17.0.3",
|
"marked": "^17.0.3",
|
||||||
"marked-footnote": "^1.4.0",
|
"marked-footnote": "^1.4.0",
|
||||||
"marked-highlight": "^2.2.3",
|
"marked-highlight": "^2.2.3",
|
||||||
"mermaid": "^11.12.3",
|
"mermaid": "^11.12.3",
|
||||||
|
"motion": "^12.40.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
"pdfjs-dist": "^5.5.207",
|
"pdfjs-dist": "^5.5.207",
|
||||||
"pdfkit": "^0.17.2",
|
"pdfkit": "^0.17.2",
|
||||||
"pizzip": "^3.2.0",
|
"pizzip": "^3.2.0",
|
||||||
"sharp": "^0.34.3",
|
"react": "^19.2.7",
|
||||||
|
"react-dom": "^19.2.7",
|
||||||
|
"react-hook-form": "^7.77.0",
|
||||||
|
"react-resizable-panels": "^4.11.2",
|
||||||
"simple-git": "^3.32.3",
|
"simple-git": "^3.32.3",
|
||||||
"tslib": "^2.8.1"
|
"sonner": "^2.0.7",
|
||||||
|
"tslib": "^2.8.1",
|
||||||
|
"zod": "^4.4.3",
|
||||||
|
"zustand": "^5.0.14"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"jszip": "^3.10.1",
|
"jszip": "^3.10.1",
|
||||||
@@ -114,11 +164,7 @@
|
|||||||
"package.json"
|
"package.json"
|
||||||
],
|
],
|
||||||
"asarUnpack": [
|
"asarUnpack": [
|
||||||
"node_modules/ffmpeg-static/**",
|
"node_modules/ffmpeg-static/**"
|
||||||
"node_modules/sharp/**",
|
|
||||||
"node_modules/@img/**",
|
|
||||||
"node_modules/@napi-rs/**",
|
|
||||||
"assets/fonts/**"
|
|
||||||
],
|
],
|
||||||
"extraFiles": [],
|
"extraFiles": [],
|
||||||
"fileAssociations": [
|
"fileAssociations": [
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
-604
@@ -1,604 +0,0 @@
|
|||||||
# Repository Structure Map
|
|
||||||
|
|
||||||
Auto-generated by `~/.claude-shared/scripts/repo-map.sh` (universal-ctags).
|
|
||||||
Signatures only — classes, functions, methods, interfaces, enums, types, namespaces, traits.
|
|
||||||
Regenerate after structural changes. Languages: `JavaScript,Sh`.
|
|
||||||
|
|
||||||
```
|
|
||||||
scripts/download-tools.js:
|
|
||||||
L22 method extract (PANDOC_CONFIG.linux)
|
|
||||||
L36 method extract (PANDOC_CONFIG.win32)
|
|
||||||
L51 method extract (PANDOC_CONFIG.darwin)
|
|
||||||
L63 function download
|
|
||||||
L70 function get (download)
|
|
||||||
L109 function downloadPandoc
|
|
||||||
|
|
||||||
scripts/generate-icons.js:
|
|
||||||
L17 function generateIcons
|
|
||||||
|
|
||||||
src/adapters/electron/fs.js:
|
|
||||||
L20 method readFile (electronFsAdapter)
|
|
||||||
L30 method writeFile (electronFsAdapter)
|
|
||||||
L39 method deleteFile (electronFsAdapter)
|
|
||||||
L48 method ensureDir (electronFsAdapter)
|
|
||||||
L57 method listDirectory (electronFsAdapter)
|
|
||||||
L77 method exists (electronFsAdapter)
|
|
||||||
L86 method isDirectory (electronFsAdapter)
|
|
||||||
L96 method copy (electronFsAdapter)
|
|
||||||
L106 method move (electronFsAdapter)
|
|
||||||
|
|
||||||
src/analytics/analytics-panel.js:
|
|
||||||
L7 function showAnalyticsModal
|
|
||||||
L105 function escHandler (showAnalyticsModal)
|
|
||||||
L116 function escapeHtml
|
|
||||||
|
|
||||||
src/analytics/writing-analytics.js:
|
|
||||||
L77 function countSyllables
|
|
||||||
L83 function extractWords
|
|
||||||
L87 function getReadabilityLabel
|
|
||||||
L95 function analyze
|
|
||||||
|
|
||||||
src/command-palette.js:
|
|
||||||
L1 class CommandPalette
|
|
||||||
L2 method constructor (CommandPalette)
|
|
||||||
L12 method register (CommandPalette)
|
|
||||||
L16 method open (CommandPalette)
|
|
||||||
L24 method close (CommandPalette)
|
|
||||||
L28 method isOpen (CommandPalette)
|
|
||||||
L32 method setupEventListeners (CommandPalette)
|
|
||||||
L61 method renderResults (CommandPalette)
|
|
||||||
L90 method highlightMatch (CommandPalette)
|
|
||||||
L96 method updateSelection (CommandPalette)
|
|
||||||
L105 method executeSelected (CommandPalette)
|
|
||||||
|
|
||||||
src/editor/codemirror-setup.js:
|
|
||||||
L46 function createEditor
|
|
||||||
L61 function onChange (createEditor)
|
|
||||||
L118 function getLanguageExtension
|
|
||||||
L120 method javascript (getLanguageExtension.loaders)
|
|
||||||
L124 method html (getLanguageExtension.loaders)
|
|
||||||
L128 method css (getLanguageExtension.loaders)
|
|
||||||
L132 method json (getLanguageExtension.loaders)
|
|
||||||
L136 method python (getLanguageExtension.loaders)
|
|
||||||
|
|
||||||
src/main.js:
|
|
||||||
L18 function getPandocPath
|
|
||||||
L36 function getFFmpegPath
|
|
||||||
L55 function sanitizeErrorMessage
|
|
||||||
L64 function createRateLimiter
|
|
||||||
L66 function canProceed (createRateLimiter)
|
|
||||||
L83 function validatePath
|
|
||||||
L136 function resolveWritablePath
|
|
||||||
L181 function isPathAccessible
|
|
||||||
L203 function convertDataToMarkdown
|
|
||||||
L225 function runPandocCmd
|
|
||||||
L247 function parseCommand
|
|
||||||
L282 method get (store)
|
|
||||||
L291 method set (store)
|
|
||||||
L488 function checkPandocAvailability
|
|
||||||
L500 function createWindow
|
|
||||||
L586 function buildRecentFilesMenu
|
|
||||||
L599 method click (buildRecentFilesMenu.anonymousObjectc5643c890c05)
|
|
||||||
L637 function getRecentFiles
|
|
||||||
L647 function createMenu
|
|
||||||
L872 method click (createMenu.anonymousObjectc5643c890e05.anonymousObjectc5643c894505)
|
|
||||||
L1118 method click (createMenu.anonymousObjectc5643c895205.anonymousObjectc5643c897e05)
|
|
||||||
L1279 method click (createMenu.anonymousObjectc5643c899305.anonymousObjectc5643c89a505)
|
|
||||||
L1351 function showAboutDialog
|
|
||||||
L1452 function showDependenciesDialog
|
|
||||||
L1564 function openPDFFile
|
|
||||||
L1583 function openFile
|
|
||||||
L1622 function openPdfFile
|
|
||||||
L1645 function saveAsFile
|
|
||||||
L1664 function exportFile
|
|
||||||
L1673 function showExportOptionsDialog
|
|
||||||
L1676 function showBatchConversionDialog
|
|
||||||
L1681 function selectWordTemplate
|
|
||||||
L1705 function showTemplateSettings
|
|
||||||
L1902 function processDynamicFields
|
|
||||||
L1921 function setDocxPageSize
|
|
||||||
L1980 function addHeaderFooterToDocx
|
|
||||||
L2111 function exportWordWithTemplate
|
|
||||||
L2153 function exportPDFViaWordTemplate
|
|
||||||
L2231 function showUniversalConverterDialog
|
|
||||||
L2236 function showPDFEditorDialog
|
|
||||||
L2246 function checkConverterAvailable
|
|
||||||
L2370 function collectFiles
|
|
||||||
L2464 function convertWithLibreOffice
|
|
||||||
L2498 function convertWithImageMagick
|
|
||||||
L2507 function convertWithFFmpeg
|
|
||||||
L2515 function convertWithPandoc
|
|
||||||
L2521 function performExportWithOptions
|
|
||||||
L2805 function tryPdfFallback
|
|
||||||
L2882 function showExportSuccess
|
|
||||||
L2892 function exportWithPandoc
|
|
||||||
L2964 function exportToHTML
|
|
||||||
L3080 function exportToPDFElectron
|
|
||||||
L3224 function exportSpreadsheet
|
|
||||||
L3233 function importDocument
|
|
||||||
L3355 function setTheme
|
|
||||||
L3536 function extractTablesFromMarkdown
|
|
||||||
L3574 function performBatchConversion
|
|
||||||
L3597 function findMarkdownFiles (performBatchConversion)
|
|
||||||
L3636 function processNextFile (performBatchConversion)
|
|
||||||
L3970 function handleCLIConversion
|
|
||||||
L3997 function showConversionDialog
|
|
||||||
L4064 function performCLIConversion
|
|
||||||
L4098 function buildPandocCommand
|
|
||||||
L4319 function openFileFromPath
|
|
||||||
L4394 function openAsciiGenerator
|
|
||||||
L4426 function openTableGenerator
|
|
||||||
L4724 function loadSnippets
|
|
||||||
L4734 function saveSnippetsFile
|
|
||||||
|
|
||||||
src/main/GitOperations.js:
|
|
||||||
L3 function getGitInstance
|
|
||||||
L7 function getStatus
|
|
||||||
L16 function stage
|
|
||||||
L26 function commit
|
|
||||||
L35 function log
|
|
||||||
|
|
||||||
src/main/PDFOperations.js:
|
|
||||||
L5 function parsePageRanges
|
|
||||||
L28 function hexToRgb
|
|
||||||
L39 function pdfMerge
|
|
||||||
L59 function pdfSplit
|
|
||||||
L126 function pdfCompress
|
|
||||||
L152 function pdfRotate
|
|
||||||
L182 function pdfDeletePages
|
|
||||||
L208 function pdfReorder
|
|
||||||
L233 function pdfWatermark
|
|
||||||
L319 function pdfEncrypt
|
|
||||||
L353 function pdfDecrypt
|
|
||||||
L370 function pdfSetPermissions
|
|
||||||
L404 function executeOperation
|
|
||||||
L431 function getPageCount
|
|
||||||
|
|
||||||
src/plugins/built-in/_sample/index.js:
|
|
||||||
L3 class SamplePlugin
|
|
||||||
L4 method init (SamplePlugin)
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/goal-tracker.js:
|
|
||||||
L3 class GoalTracker
|
|
||||||
L7 method constructor (GoalTracker)
|
|
||||||
L11 method _getHistory (GoalTracker)
|
|
||||||
L16 method _setHistory (GoalTracker)
|
|
||||||
L20 method _setHistoryDay (GoalTracker)
|
|
||||||
L26 method addWords (GoalTracker)
|
|
||||||
L37 method getDailyProgress (GoalTracker)
|
|
||||||
L44 method getStreak (GoalTracker)
|
|
||||||
L61 method getLast30Days (GoalTracker)
|
|
||||||
L74 method getWeeklyTotal (GoalTracker)
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/index.js:
|
|
||||||
L7 class WritingStudioPlugin
|
|
||||||
L8 method init (WritingStudioPlugin)
|
|
||||||
L34 method _registerCommands (WritingStudioPlugin)
|
|
||||||
L112 method _registerStatusBar (WritingStudioPlugin)
|
|
||||||
L123 method deactivate (WritingStudioPlugin)
|
|
||||||
L127 method getEngines (WritingStudioPlugin)
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/panels/goals-panel.js:
|
|
||||||
L1 function renderGoalsPanel
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/panels/manuscript-panel.js:
|
|
||||||
L1 function renderManuscriptPanel
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/panels/proofread-panel.js:
|
|
||||||
L1 function renderProofreadPanel
|
|
||||||
L41 method callback (anonymousObject39a0f0110105)
|
|
||||||
L50 function renderIssues
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/panels/snapshots-panel.js:
|
|
||||||
L1 function renderSnapshotsPanel
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/project-manager.js:
|
|
||||||
L1 class ProjectManager
|
|
||||||
L5 method constructor (ProjectManager)
|
|
||||||
L9 method createProject (ProjectManager)
|
|
||||||
L21 method loadProject (ProjectManager)
|
|
||||||
L27 method _saveProject (ProjectManager)
|
|
||||||
L31 method addChapter (ProjectManager)
|
|
||||||
L38 method updateChapter (ProjectManager)
|
|
||||||
L45 method compileManuscript (ProjectManager)
|
|
||||||
L56 method getStats (ProjectManager)
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/snapshot-manager.js:
|
|
||||||
L1 class SnapshotManager
|
|
||||||
L6 method constructor (SnapshotManager)
|
|
||||||
L11 method _getAll (SnapshotManager)
|
|
||||||
L16 method _saveAll (SnapshotManager)
|
|
||||||
L20 method create (SnapshotManager)
|
|
||||||
L34 method list (SnapshotManager)
|
|
||||||
L38 method getById (SnapshotManager)
|
|
||||||
L42 method restore (SnapshotManager)
|
|
||||||
L48 method delete (SnapshotManager)
|
|
||||||
L53 method diff (SnapshotManager)
|
|
||||||
L71 method prune (SnapshotManager)
|
|
||||||
|
|
||||||
src/plugins/built-in/writing-studio/sprint-engine.js:
|
|
||||||
L1 class SprintEngine
|
|
||||||
L6 method constructor (SprintEngine)
|
|
||||||
L14 method start (SprintEngine)
|
|
||||||
L22 method stop (SprintEngine)
|
|
||||||
L33 method tick (SprintEngine)
|
|
||||||
L43 method isActive (SprintEngine)
|
|
||||||
L47 method getRemaining (SprintEngine)
|
|
||||||
|
|
||||||
src/plugins/event-bus.js:
|
|
||||||
L1 class EventBus
|
|
||||||
L2 method constructor (EventBus)
|
|
||||||
L6 method on (EventBus)
|
|
||||||
L13 method off (EventBus)
|
|
||||||
L25 method emit (EventBus)
|
|
||||||
L37 method hasHandler (EventBus)
|
|
||||||
|
|
||||||
src/plugins/plugin-api.js:
|
|
||||||
L1 class PluginAPI
|
|
||||||
L7 method init (PluginAPI)
|
|
||||||
L12 method activate (PluginAPI)
|
|
||||||
L15 method deactivate (PluginAPI)
|
|
||||||
L18 method getManifest (PluginAPI)
|
|
||||||
|
|
||||||
src/plugins/plugin-context.js:
|
|
||||||
L1 class PluginContext
|
|
||||||
L14 method constructor (PluginContext)
|
|
||||||
L23 method register (PluginContext.constructor.commands)
|
|
||||||
L24 function safeHandler (PluginContext.constructor.commands.register)
|
|
||||||
L65 method registerPreHook (PluginContext.constructor.exports)
|
|
||||||
L68 method registerPostHook (PluginContext.constructor.exports)
|
|
||||||
|
|
||||||
src/plugins/plugin-loader.js:
|
|
||||||
L4 class PluginLoader
|
|
||||||
L8 method constructor (PluginLoader)
|
|
||||||
L17 method discoverPlugins (PluginLoader)
|
|
||||||
L66 method validateManifest (PluginLoader)
|
|
||||||
|
|
||||||
src/plugins/plugin-registry.js:
|
|
||||||
L4 class PluginRegistry
|
|
||||||
L5 method constructor (PluginRegistry)
|
|
||||||
L15 method register (PluginRegistry)
|
|
||||||
L49 method getPlugin (PluginRegistry)
|
|
||||||
L53 method getAll (PluginRegistry)
|
|
||||||
L57 method activate (PluginRegistry)
|
|
||||||
L68 method deactivate (PluginRegistry)
|
|
||||||
|
|
||||||
src/plugins/settings-store.js:
|
|
||||||
L1 class SettingsStore
|
|
||||||
L5 method constructor (SettingsStore)
|
|
||||||
L9 method get (SettingsStore)
|
|
||||||
L13 method set (SettingsStore)
|
|
||||||
L17 method onChanged (SettingsStore)
|
|
||||||
|
|
||||||
src/preload.js:
|
|
||||||
L257 method send (anonymousObjectb0724fcb0105)
|
|
||||||
L271 method invoke (anonymousObjectb0724fcb0105)
|
|
||||||
L290 method on (anonymousObjectb0724fcb0105)
|
|
||||||
L292 function subscription (anonymousObjectb0724fcb0105.on)
|
|
||||||
L310 method once (anonymousObjectb0724fcb0105)
|
|
||||||
L322 method removeAllListeners (anonymousObjectb0724fcb0105)
|
|
||||||
|
|
||||||
src/print-preview.js:
|
|
||||||
L1 class PrintPreview
|
|
||||||
L2 method constructor (PrintPreview)
|
|
||||||
L9 method open (PrintPreview)
|
|
||||||
L20 method close (PrintPreview)
|
|
||||||
L28 method setupEventListeners (PrintPreview)
|
|
||||||
L53 method updateScaleLabel (PrintPreview)
|
|
||||||
L59 method updatePreview (PrintPreview)
|
|
||||||
L111 method refreshPreview (PrintPreview)
|
|
||||||
L117 method getOptions (PrintPreview)
|
|
||||||
L130 method executePrint (PrintPreview)
|
|
||||||
|
|
||||||
src/renderer.js:
|
|
||||||
L19 method send (window.electronAPI)
|
|
||||||
L22 method invoke (window.electronAPI)
|
|
||||||
L25 method on (window.electronAPI)
|
|
||||||
L26 function subscription (window.electronAPI.on)
|
|
||||||
L32 method once (window.electronAPI)
|
|
||||||
L35 method removeAllListeners (window.electronAPI)
|
|
||||||
L81 function getSidebarManager
|
|
||||||
L85 function getRenderTemplatesPanel
|
|
||||||
L90 function getRenderExplorerPanel
|
|
||||||
L95 function getRenderGitPanel
|
|
||||||
L99 function getRenderSnippetsPanel
|
|
||||||
L105 function getRenderOutlinePanel
|
|
||||||
L110 function getReplPanel
|
|
||||||
L114 function getCommandPalette
|
|
||||||
L118 function getPrintPreview
|
|
||||||
L122 function getCreateWelcomeContent
|
|
||||||
L127 function getZenMode
|
|
||||||
L132 function getShowAnalyticsModal
|
|
||||||
L137 function ensureToastContainer
|
|
||||||
L147 function notifyUser
|
|
||||||
L159 function dismiss (notifyUser)
|
|
||||||
L173 method highlight (anonymousObject71555c7b0405)
|
|
||||||
L202 method start (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
|
|
||||||
L205 method tokenizer (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
|
|
||||||
L221 method renderer (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
|
|
||||||
L241 function plantumlEncode (notifyUser)
|
|
||||||
L249 function scopeCSS (notifyUser)
|
|
||||||
L271 class TabManager (notifyUser)
|
|
||||||
L272 method constructor (notifyUser.TabManager)
|
|
||||||
L306 method setupEventListeners (notifyUser.TabManager)
|
|
||||||
L354 method createNewTab (notifyUser.TabManager)
|
|
||||||
L379 method createPdfTab (notifyUser.TabManager)
|
|
||||||
L405 method createPdfTabElements (notifyUser.TabManager)
|
|
||||||
L436 method setupPdfTabEvents (notifyUser.TabManager)
|
|
||||||
L503 method loadPdfInTab (notifyUser.TabManager)
|
|
||||||
L528 method renderPdfPageInTab (notifyUser.TabManager)
|
|
||||||
L555 method createTabElements (notifyUser.TabManager)
|
|
||||||
L580 method onChange (anonymousObject71555c7b0d05)
|
|
||||||
L602 method onUpdate (anonymousObject71555c7b0d05)
|
|
||||||
L614 method switchToTab (notifyUser.TabManager)
|
|
||||||
L641 method switchToNextTab (notifyUser.TabManager)
|
|
||||||
L647 method closeTab (notifyUser.TabManager)
|
|
||||||
L692 method updateTabBar (notifyUser.TabManager)
|
|
||||||
L718 method updateUI (notifyUser.TabManager)
|
|
||||||
L748 method saveCurrentTabState (notifyUser.TabManager)
|
|
||||||
L756 method restoreTabState (notifyUser.TabManager)
|
|
||||||
L765 method focusActiveEditor (notifyUser.TabManager)
|
|
||||||
L771 method updatePreview (notifyUser.TabManager)
|
|
||||||
L800 method _hash (notifyUser.TabManager)
|
|
||||||
L809 method _renderPreview (notifyUser.TabManager)
|
|
||||||
L963 function onerror (img)
|
|
||||||
L997 method updatePreviewVisibility (notifyUser.TabManager)
|
|
||||||
L1010 method updateLineNumbers (notifyUser.TabManager)
|
|
||||||
L1015 method updateWordCount (notifyUser.TabManager)
|
|
||||||
L1031 method updateCursorPosition (notifyUser.TabManager)
|
|
||||||
L1038 method updateFilePath (notifyUser.TabManager)
|
|
||||||
L1046 method updateBreadcrumb (notifyUser.TabManager)
|
|
||||||
L1054 method setupEditorEvents (notifyUser.TabManager)
|
|
||||||
L1058 method handleEditorInput (notifyUser.TabManager)
|
|
||||||
L1073 method startAutoSave (notifyUser.TabManager)
|
|
||||||
L1081 method stopAutoSave (notifyUser.TabManager)
|
|
||||||
L1087 method performAutoSave (notifyUser.TabManager)
|
|
||||||
L1103 method showAutoSaveIndicator (notifyUser.TabManager)
|
|
||||||
L1119 method addToRecentFiles (notifyUser.TabManager)
|
|
||||||
L1135 method getRecentFiles (notifyUser.TabManager)
|
|
||||||
L1145 method setupToolbarEvents (notifyUser.TabManager)
|
|
||||||
L1215 method wrapSelection (notifyUser.TabManager)
|
|
||||||
L1233 method insertAtLineStart (notifyUser.TabManager)
|
|
||||||
L1249 method insertTable (notifyUser.TabManager)
|
|
||||||
L1259 method insertCodeBlock (notifyUser.TabManager)
|
|
||||||
L1277 method insertHorizontalRule (notifyUser.TabManager)
|
|
||||||
L1280 method setupFindEvents (notifyUser.TabManager)
|
|
||||||
L1350 method performFind (notifyUser.TabManager)
|
|
||||||
L1384 method findNext (notifyUser.TabManager)
|
|
||||||
L1390 method findPrevious (notifyUser.TabManager)
|
|
||||||
L1399 method highlightMatch (notifyUser.TabManager)
|
|
||||||
L1430 method replaceOne (notifyUser.TabManager)
|
|
||||||
L1454 method replaceAll (notifyUser.TabManager)
|
|
||||||
L1485 method clearFindHighlights (notifyUser.TabManager)
|
|
||||||
L1492 method checkForLargeFile (notifyUser.TabManager)
|
|
||||||
L1508 method openFile (notifyUser.TabManager)
|
|
||||||
L1555 method getEditorContent (notifyUser.TabManager)
|
|
||||||
L1564 method setEditorContent (notifyUser.TabManager)
|
|
||||||
L1579 method insertAtCursor (notifyUser.TabManager)
|
|
||||||
L1594 method getSelection (notifyUser.TabManager)
|
|
||||||
L1602 method replaceSelection (notifyUser.TabManager)
|
|
||||||
L1616 method getCurrentContent (notifyUser.TabManager)
|
|
||||||
L1620 method getCurrentFilePath (notifyUser.TabManager)
|
|
||||||
L1735 method render (anonymousObject71555c7b2d05)
|
|
||||||
L1788 method registerIndicator (anonymousObject71555c7b3105.statusBar)
|
|
||||||
L1881 function onload (reader)
|
|
||||||
L2032 method onChange (anonymousObject71555c7b3405)
|
|
||||||
L2040 method onUpdate (anonymousObject71555c7b3405)
|
|
||||||
L2164 function applyCustomPreviewCSS (notifyUser)
|
|
||||||
L2174 function triggerLoadCustomCSS (notifyUser)
|
|
||||||
L2188 function triggerClearCustomCSS (notifyUser)
|
|
||||||
L2202 function updateFontSizes (notifyUser)
|
|
||||||
L2234 function openPrintPreviewDialog (notifyUser)
|
|
||||||
L2255 function showExportDialog (notifyUser)
|
|
||||||
L2269 function hideExportDialog (notifyUser)
|
|
||||||
L2273 function initializeExportForm (notifyUser)
|
|
||||||
L2343 function collectExportOptions (notifyUser)
|
|
||||||
L2444 function loadExportProfiles (notifyUser)
|
|
||||||
L2456 function saveExportProfiles (notifyUser)
|
|
||||||
L2459 function populateProfileDropdown (notifyUser)
|
|
||||||
L2476 function saveCurrentProfile (notifyUser)
|
|
||||||
L2511 function loadProfile (notifyUser)
|
|
||||||
L2545 function deleteSelectedProfile (notifyUser)
|
|
||||||
L2679 function onchange (input)
|
|
||||||
L2776 function showBatchDialog (notifyUser)
|
|
||||||
L2796 function hideBatchDialog (notifyUser)
|
|
||||||
L2799 function updateBatchProgress (notifyUser)
|
|
||||||
L2816 function validateBatchForm (notifyUser)
|
|
||||||
L3375 function showUniversalConverterDialog (notifyUser)
|
|
||||||
L3383 function updateConverterFormats (notifyUser)
|
|
||||||
L3423 function updateConverterAdvancedOptions (notifyUser)
|
|
||||||
L3434 function collectConverterAdvancedOptions (notifyUser)
|
|
||||||
L3645 function showPDFEditorDialog (notifyUser)
|
|
||||||
L3769 function hidePDFEditorDialog (notifyUser)
|
|
||||||
L3780 function updateMergeFilesList (notifyUser)
|
|
||||||
L4107 function getPDFStatusElement (notifyUser)
|
|
||||||
L4110 function showPDFStatus (notifyUser)
|
|
||||||
L4117 function clearPDFStatus (notifyUser)
|
|
||||||
L4124 function showPDFValidationMessage (notifyUser)
|
|
||||||
L4135 function processPDFOperation (notifyUser)
|
|
||||||
L4379 function initMathSupport (notifyUser)
|
|
||||||
L4391 function onload (katexJS)
|
|
||||||
L4396 function onload (autoRenderJS)
|
|
||||||
L4417 function openHeaderFooterDialog (notifyUser)
|
|
||||||
L4425 function closeHeaderFooterDialog (notifyUser)
|
|
||||||
L4430 function openFieldPickerDialog (notifyUser)
|
|
||||||
L4436 function closeFieldPickerDialog (notifyUser)
|
|
||||||
L4477 function toggleConfigContent (notifyUser)
|
|
||||||
L4488 function saveHeaderFooterSettings (notifyUser)
|
|
||||||
L4509 function browseForLogo (notifyUser)
|
|
||||||
L4519 function clearLogo (notifyUser)
|
|
||||||
L4528 function insertDynamicField (notifyUser)
|
|
||||||
L4594 function showTableGenerator (notifyUser)
|
|
||||||
L4605 function hideTableGenerator (notifyUser)
|
|
||||||
L4608 function generateTablePreview (notifyUser)
|
|
||||||
L4616 function generateMarkdownTable (notifyUser)
|
|
||||||
L4685 function insertGeneratedTable (notifyUser)
|
|
||||||
L4742 function showASCIIGenerator (notifyUser)
|
|
||||||
L4753 function hideASCIIGenerator (notifyUser)
|
|
||||||
L4756 function switchASCIIMode (notifyUser)
|
|
||||||
L4784 function generateASCIIPreview (notifyUser)
|
|
||||||
L4802 function textToASCII (notifyUser)
|
|
||||||
L5238 function createASCIIBox (notifyUser)
|
|
||||||
L5312 function getASCIITemplate (notifyUser)
|
|
||||||
L5469 function loadASCIITemplate (notifyUser)
|
|
||||||
L5473 function insertASCIIArt (notifyUser)
|
|
||||||
L5523 function anonymousFunction71555c7bd300
|
|
||||||
L5603 function getPdfjsLib (notifyUser)
|
|
||||||
L5612 function openPdfFile (notifyUser)
|
|
||||||
L5627 function renderPdfPage (notifyUser)
|
|
||||||
L5733 function closePdfViewer (notifyUser)
|
|
||||||
L5783 function openPdfEditorDialog (notifyUser)
|
|
||||||
L5831 function initPaneResizer (notifyUser)
|
|
||||||
L5920 function onPDFFileSelected (notifyUser)
|
|
||||||
L5935 function loadPDFThumbnails (notifyUser)
|
|
||||||
L5966 function renderThumbnailGrid (notifyUser)
|
|
||||||
L6060 function renderThumbnail (notifyUser)
|
|
||||||
L6085 function syncRotateInput (notifyUser)
|
|
||||||
L6094 function syncDeleteInput (notifyUser)
|
|
||||||
L6103 function syncReorderInput (notifyUser)
|
|
||||||
|
|
||||||
src/repl/repl-panel.js:
|
|
||||||
L1 class ReplPanel
|
|
||||||
L2 method constructor (ReplPanel)
|
|
||||||
L8 method setupEventListeners (ReplPanel)
|
|
||||||
L13 method toggle (ReplPanel)
|
|
||||||
L19 method show (ReplPanel)
|
|
||||||
L25 method clear (ReplPanel)
|
|
||||||
L29 method appendOutput (ReplPanel)
|
|
||||||
L42 method escapeHtml (ReplPanel)
|
|
||||||
|
|
||||||
src/sidebar/explorer-panel.js:
|
|
||||||
L1 function renderExplorerPanel
|
|
||||||
L40 function renderTree
|
|
||||||
L79 function getFileIcon
|
|
||||||
|
|
||||||
src/sidebar/git-panel.js:
|
|
||||||
L1 function renderGitPanel
|
|
||||||
L24 function loadGitStatus (renderGitPanel)
|
|
||||||
|
|
||||||
src/sidebar/outline-panel.js:
|
|
||||||
L6 function renderOutlinePanel
|
|
||||||
L18 function parseHeadings (renderOutlinePanel)
|
|
||||||
L36 function findActiveHeading (renderOutlinePanel)
|
|
||||||
L48 function renderHeadings (renderOutlinePanel)
|
|
||||||
L89 function escapeHtml (renderOutlinePanel)
|
|
||||||
L95 function refresh (renderOutlinePanel)
|
|
||||||
L100 function setActiveHeading (renderOutlinePanel)
|
|
||||||
|
|
||||||
src/sidebar/sidebar-manager.js:
|
|
||||||
L1 class SidebarManager
|
|
||||||
L2 method constructor (SidebarManager)
|
|
||||||
L11 method setupEventListeners (SidebarManager)
|
|
||||||
L20 method registerPanel (SidebarManager)
|
|
||||||
L24 method togglePanel (SidebarManager)
|
|
||||||
L32 method expand (SidebarManager)
|
|
||||||
L45 method collapse (SidebarManager)
|
|
||||||
|
|
||||||
src/sidebar/snippets-panel.js:
|
|
||||||
L1 function renderSnippetsPanel
|
|
||||||
L14 function loadSnippets (renderSnippetsPanel)
|
|
||||||
L19 function renderList (renderSnippetsPanel)
|
|
||||||
|
|
||||||
src/sidebar/templates-panel.js:
|
|
||||||
L18 function renderTemplatesPanel
|
|
||||||
|
|
||||||
src/utils/ModalManager.js:
|
|
||||||
L5 class ModalManager
|
|
||||||
L16 method constructor (ModalManager)
|
|
||||||
L31 method init (ModalManager)
|
|
||||||
L47 method setupCloseTriggers (ModalManager)
|
|
||||||
L51 function handler (ModalManager.setupCloseTriggers)
|
|
||||||
L65 function handler
|
|
||||||
L74 method getFocusableElements (ModalManager)
|
|
||||||
L89 method trapFocus (ModalManager)
|
|
||||||
L111 method handleKeydown (ModalManager)
|
|
||||||
L119 method open (ModalManager)
|
|
||||||
L141 function keydownHandler (ModalManager.open)
|
|
||||||
L164 method close (ModalManager)
|
|
||||||
L182 function addHidden (ModalManager.close)
|
|
||||||
L188 function onTransitionEnd (ModalManager.close)
|
|
||||||
L223 method isOpen (ModalManager)
|
|
||||||
L227 method destroy (ModalManager)
|
|
||||||
|
|
||||||
src/welcome.js:
|
|
||||||
L1 function createWelcomeContent
|
|
||||||
|
|
||||||
src/wordTemplateExporter.js:
|
|
||||||
L11 class WordTemplateExporter
|
|
||||||
L12 method constructor (WordTemplateExporter)
|
|
||||||
L24 method preprocessMarkdownForWordExport (WordTemplateExporter)
|
|
||||||
L33 function flush (WordTemplateExporter.preprocessMarkdownForWordExport)
|
|
||||||
L59 function stripArtifacts (WordTemplateExporter.preprocessMarkdownForWordExport)
|
|
||||||
|
|
||||||
src/zen-mode.js:
|
|
||||||
L10 class ZenMode
|
|
||||||
L14 method constructor (ZenMode)
|
|
||||||
L23 method activate (ZenMode)
|
|
||||||
L65 method deactivate (ZenMode)
|
|
||||||
L101 method toggle (ZenMode)
|
|
||||||
L109 method _applyTypewriterBehavior (ZenMode)
|
|
||||||
L111 function scrollFn (ZenMode._applyTypewriterBehavior)
|
|
||||||
L151 method _createHUD (ZenMode)
|
|
||||||
L169 method _updateHUD (ZenMode)
|
|
||||||
L220 method constructor (anonymousObject3acf7ce30205)
|
|
||||||
L240 function getOpacity
|
|
||||||
L250 method constructor (anonymousObject3acf7ce30405)
|
|
||||||
|
|
||||||
tests/git-operations.test.js:
|
|
||||||
L26 function asyncFn
|
|
||||||
L35 function asyncFnWithError
|
|
||||||
|
|
||||||
tests/main-utils.test.js:
|
|
||||||
L7 function sanitizeErrorMessage
|
|
||||||
L49 function createRateLimiter
|
|
||||||
L51 function canProceed (createRateLimiter)
|
|
||||||
|
|
||||||
tests/markdown-extensions.test.js:
|
|
||||||
L83 method start (extension)
|
|
||||||
L86 method tokenizer (extension)
|
|
||||||
L102 method renderer (extension)
|
|
||||||
L151 function plantumlEncode
|
|
||||||
L176 function slugify
|
|
||||||
L203 function scopeCSS
|
|
||||||
|
|
||||||
tests/modal-manager.test.js:
|
|
||||||
L11 function createModalElement
|
|
||||||
|
|
||||||
tests/plugin-api.test.js:
|
|
||||||
L18 class MyPlugin
|
|
||||||
L19 method init (MyPlugin)
|
|
||||||
|
|
||||||
tests/plugin-context.test.js:
|
|
||||||
L39 function badHandler
|
|
||||||
|
|
||||||
tests/plugin-loader.test.js:
|
|
||||||
L17 function writeManifest
|
|
||||||
|
|
||||||
tests/plugin-registry.test.js:
|
|
||||||
L5 class TestPlugin
|
|
||||||
L6 method init (TestPlugin)
|
|
||||||
L10 method activate (TestPlugin)
|
|
||||||
L13 method deactivate (TestPlugin)
|
|
||||||
L69 class BadPlugin
|
|
||||||
L70 method init (BadPlugin)
|
|
||||||
|
|
||||||
tests/setup.js:
|
|
||||||
L96 function error (console)
|
|
||||||
|
|
||||||
tests/sidebar.test.js:
|
|
||||||
L41 method render (anonymousObjectfe2d35d70105)
|
|
||||||
L52 method render (anonymousObjectfe2d35d70205)
|
|
||||||
L62 method render (anonymousObjectfe2d35d70305)
|
|
||||||
L68 method render (anonymousObjectfe2d35d70405)
|
|
||||||
L80 method render (anonymousObjectfe2d35d70505)
|
|
||||||
L88 method render (anonymousObjectfe2d35d70605)
|
|
||||||
L96 method render (anonymousObjectfe2d35d70705)
|
|
||||||
L120 method render (anonymousObjectfe2d35d70905)
|
|
||||||
L130 method render (anonymousObjectfe2d35d70a05)
|
|
||||||
|
|
||||||
tests/utils.test.js:
|
|
||||||
L9 function parseCommand
|
|
||||||
L78 function hexToRgb
|
|
||||||
L121 function getExtension
|
|
||||||
L133 function replaceExtension
|
|
||||||
```
|
|
||||||
@@ -106,27 +106,6 @@ function download(url, destPath) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function downloadFiraCode() {
|
|
||||||
const destDir = path.join(__dirname, '..', 'assets', 'fonts');
|
|
||||||
fs.mkdirSync(destDir, { recursive: true });
|
|
||||||
|
|
||||||
const targets = [
|
|
||||||
{ url: 'https://github.com/tonsky/FiraCode/raw/master/distr/ttf/FiraCode-Regular.ttf', out: 'FiraCode-Regular.ttf' },
|
|
||||||
{ url: 'https://github.com/tonsky/FiraCode/raw/master/distr/ttf/FiraCode-Bold.ttf', out: 'FiraCode-Bold.ttf' },
|
|
||||||
{ url: 'https://raw.githubusercontent.com/tonsky/FiraCode/master/LICENSE', out: 'FiraCode-LICENSE.txt' },
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const t of targets) {
|
|
||||||
const destFile = path.join(destDir, t.out);
|
|
||||||
if (fs.existsSync(destFile)) {
|
|
||||||
console.log(`[download-tools] ${t.out} already present — skipping.`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
console.log(`[download-tools] Downloading ${t.out}...`);
|
|
||||||
await download(t.url, destFile);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadPandoc() {
|
async function downloadPandoc() {
|
||||||
const platform = process.platform;
|
const platform = process.platform;
|
||||||
const config = PANDOC_CONFIG[platform];
|
const config = PANDOC_CONFIG[platform];
|
||||||
@@ -163,7 +142,7 @@ async function downloadPandoc() {
|
|||||||
console.log(`[download-tools] pandoc ready: ${destFile}`);
|
console.log(`[download-tools] pandoc ready: ${destFile}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
Promise.all([downloadPandoc(), downloadFiraCode()]).catch((err) => {
|
downloadPandoc().catch((err) => {
|
||||||
console.error('[download-tools] FAILED:', err.message);
|
console.error('[download-tools] FAILED:', err.message);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
+89
-89
@@ -12,100 +12,100 @@
|
|||||||
* @type {import('../types').FileSystemAdapter}
|
* @type {import('../types').FileSystemAdapter}
|
||||||
*/
|
*/
|
||||||
const electronFsAdapter = {
|
const electronFsAdapter = {
|
||||||
/**
|
/**
|
||||||
* Read file content
|
* Read file content
|
||||||
* @param {string} path - File path
|
* @param {string} path - File path
|
||||||
* @returns {Promise<string>} File content
|
* @returns {Promise<string>} File content
|
||||||
*/
|
*/
|
||||||
async readFile(path) {
|
async readFile(path) {
|
||||||
return await window.electronAPI.file.read(path);
|
return await window.electronAPI.file.read(path);
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write content to file
|
* Write content to file
|
||||||
* @param {string} path - File path
|
* @param {string} path - File path
|
||||||
* @param {string} content - File content
|
* @param {string} content - File content
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async writeFile(path, content) {
|
async writeFile(path, content) {
|
||||||
return await window.electronAPI.file.write(path, content);
|
return await window.electronAPI.file.write(path, content);
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete file
|
* Delete file
|
||||||
* @param {string} path - File path
|
* @param {string} path - File path
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async deleteFile(path) {
|
async deleteFile(path) {
|
||||||
return await window.electronAPI.file.delete(path);
|
return await window.electronAPI.file.delete(path);
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure directory exists
|
* Ensure directory exists
|
||||||
* @param {string} path - Directory path
|
* @param {string} path - Directory path
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async ensureDir(path) {
|
async ensureDir(path) {
|
||||||
return await window.electronAPI.file.ensureDir(path);
|
return await window.electronAPI.file.ensureDir(path);
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List directory contents
|
* List directory contents
|
||||||
* @param {string} path - Directory path
|
* @param {string} path - Directory path
|
||||||
* @returns {Promise<Array<import('../types').FileInfo>>}
|
* @returns {Promise<Array<import('../types').FileInfo>>}
|
||||||
*/
|
*/
|
||||||
async listDirectory(path) {
|
async listDirectory(path) {
|
||||||
const result = await window.electronAPI.invoke('list-directory', path);
|
const result = await window.electronAPI.invoke('list-directory', path);
|
||||||
if (!result?.entries) {
|
if (!result?.entries) {
|
||||||
return [];
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.entries.map((entry) => ({
|
||||||
|
name: entry.name,
|
||||||
|
isDir: entry.isDirectory,
|
||||||
|
size: entry.size ?? 0,
|
||||||
|
modified: entry.modified ?? 0,
|
||||||
|
path: entry.path
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if path exists
|
||||||
|
* @param {string} path - Path to check
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async exists(path) {
|
||||||
|
return await window.electronAPI.file.exists(path);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if path is a directory
|
||||||
|
* @param {string} path - Path to check
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async isDirectory(path) {
|
||||||
|
return await window.electronAPI.file.isDirectory(path);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy file or directory
|
||||||
|
* @param {string} source - Source path
|
||||||
|
* @param {string} dest - Destination path
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async copy(source, dest) {
|
||||||
|
return await window.electronAPI.file.copy(source, dest);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move file or directory
|
||||||
|
* @param {string} source - Source path
|
||||||
|
* @param {string} dest - Destination path
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async move(source, dest) {
|
||||||
|
return await window.electronAPI.file.move(source, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result.entries.map((entry) => ({
|
|
||||||
name: entry.name,
|
|
||||||
isDir: entry.isDirectory,
|
|
||||||
size: entry.size ?? 0,
|
|
||||||
modified: entry.modified ?? 0,
|
|
||||||
path: entry.path,
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if path exists
|
|
||||||
* @param {string} path - Path to check
|
|
||||||
* @returns {Promise<boolean>}
|
|
||||||
*/
|
|
||||||
async exists(path) {
|
|
||||||
return await window.electronAPI.file.exists(path);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if path is a directory
|
|
||||||
* @param {string} path - Path to check
|
|
||||||
* @returns {Promise<boolean>}
|
|
||||||
*/
|
|
||||||
async isDirectory(path) {
|
|
||||||
return await window.electronAPI.file.isDirectory(path);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Copy file or directory
|
|
||||||
* @param {string} source - Source path
|
|
||||||
* @param {string} dest - Destination path
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async copy(source, dest) {
|
|
||||||
return await window.electronAPI.file.copy(source, dest);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Move file or directory
|
|
||||||
* @param {string} source - Source path
|
|
||||||
* @param {string} dest - Destination path
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async move(source, dest) {
|
|
||||||
return await window.electronAPI.file.move(source, dest);
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = { electronFsAdapter };
|
module.exports = { electronFsAdapter };
|
||||||
|
|||||||
@@ -129,5 +129,5 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
// Type definitions are JSDoc only, no runtime exports needed
|
// Type definitions are JSDoc only, no runtime exports needed
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,19 +5,19 @@
|
|||||||
const { analyze } = require('./writing-analytics');
|
const { analyze } = require('./writing-analytics');
|
||||||
|
|
||||||
function showAnalyticsModal(tabManager) {
|
function showAnalyticsModal(tabManager) {
|
||||||
const existing = document.getElementById('analytics-modal');
|
const existing = document.getElementById('analytics-modal');
|
||||||
if (existing) existing.remove();
|
if (existing) existing.remove();
|
||||||
|
|
||||||
const content = tabManager.getEditorContent();
|
const content = tabManager.getEditorContent();
|
||||||
const metrics = analyze(content);
|
const metrics = analyze(content);
|
||||||
|
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.id = 'analytics-modal';
|
overlay.id = 'analytics-modal';
|
||||||
overlay.className = 'analytics-overlay';
|
overlay.className = 'analytics-overlay';
|
||||||
|
|
||||||
const maxCount = metrics.topWords.length > 0 ? metrics.topWords[0].count : 1;
|
const maxCount = metrics.topWords.length > 0 ? metrics.topWords[0].count : 1;
|
||||||
|
|
||||||
overlay.innerHTML = `
|
overlay.innerHTML = `
|
||||||
<div class="analytics-modal">
|
<div class="analytics-modal">
|
||||||
<div class="analytics-header">
|
<div class="analytics-header">
|
||||||
<h2>Writing Analytics</h2>
|
<h2>Writing Analytics</h2>
|
||||||
@@ -61,15 +61,11 @@ function showAnalyticsModal(tabManager) {
|
|||||||
<span class="analytics-label">Avg Sentence</span>
|
<span class="analytics-label">Avg Sentence</span>
|
||||||
<span class="analytics-value">${metrics.avgSentenceLength} words</span>
|
<span class="analytics-value">${metrics.avgSentenceLength} words</span>
|
||||||
</div>
|
</div>
|
||||||
${
|
${metrics.longestSentenceLength > 0 ? `
|
||||||
metrics.longestSentenceLength > 0
|
|
||||||
? `
|
|
||||||
<div class="analytics-row analytics-longest">
|
<div class="analytics-row analytics-longest">
|
||||||
<span class="analytics-label">Longest (${metrics.longestSentenceLength} words)</span>
|
<span class="analytics-label">Longest (${metrics.longestSentenceLength} words)</span>
|
||||||
<span class="analytics-value analytics-sentence-preview">${escapeHtml(metrics.longestSentence)}</span>
|
<span class="analytics-value analytics-sentence-preview">${escapeHtml(metrics.longestSentence)}</span>
|
||||||
</div>`
|
</div>` : ''}
|
||||||
: ''
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="analytics-section">
|
<div class="analytics-section">
|
||||||
@@ -78,45 +74,39 @@ function showAnalyticsModal(tabManager) {
|
|||||||
<span class="analytics-label">Unique</span>
|
<span class="analytics-label">Unique</span>
|
||||||
<span class="analytics-value">${metrics.uniqueWordCount} / ${metrics.wordCount}<small>${metrics.lexicalDiversity}%</small></span>
|
<span class="analytics-value">${metrics.uniqueWordCount} / ${metrics.wordCount}<small>${metrics.lexicalDiversity}%</small></span>
|
||||||
</div>
|
</div>
|
||||||
${
|
${metrics.topWords.length > 0 ? `
|
||||||
metrics.topWords.length > 0
|
|
||||||
? `
|
|
||||||
<div class="word-cloud">
|
<div class="word-cloud">
|
||||||
${metrics.topWords
|
${metrics.topWords.map(w => {
|
||||||
.map((w) => {
|
|
||||||
const scale = 13 + Math.round((w.count / maxCount) * 3);
|
const scale = 13 + Math.round((w.count / maxCount) * 3);
|
||||||
return `<span class="word-tag" style="font-size:${scale}px">${escapeHtml(w.word)}<small>${w.count}</small></span>`;
|
return `<span class="word-tag" style="font-size:${scale}px">${escapeHtml(w.word)}<small>${w.count}</small></span>`;
|
||||||
})
|
}).join('')}
|
||||||
.join('')}
|
</div>` : ''}
|
||||||
</div>`
|
|
||||||
: ''
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const closeBtn = overlay.querySelector('.analytics-close');
|
const closeBtn = overlay.querySelector('.analytics-close');
|
||||||
closeBtn.addEventListener('click', () => overlay.remove());
|
closeBtn.addEventListener('click', () => overlay.remove());
|
||||||
overlay.addEventListener('click', (e) => {
|
overlay.addEventListener('click', (e) => {
|
||||||
if (e.target === overlay) overlay.remove();
|
if (e.target === overlay) overlay.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
const escHandler = (e) => {
|
const escHandler = (e) => {
|
||||||
if (e.key === 'Escape') {
|
if (e.key === 'Escape') {
|
||||||
overlay.remove();
|
overlay.remove();
|
||||||
document.removeEventListener('keydown', escHandler);
|
document.removeEventListener('keydown', escHandler);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
document.addEventListener('keydown', escHandler);
|
document.addEventListener('keydown', escHandler);
|
||||||
|
|
||||||
document.body.appendChild(overlay);
|
document.body.appendChild(overlay);
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeHtml(str) {
|
function escapeHtml(str) {
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
div.textContent = str;
|
div.textContent = str;
|
||||||
return div.innerHTML;
|
return div.innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { showAnalyticsModal };
|
module.exports = { showAnalyticsModal };
|
||||||
|
|||||||
+104
-177
@@ -4,197 +4,124 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const STOP_WORDS = new Set([
|
const STOP_WORDS = new Set([
|
||||||
'the',
|
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been',
|
||||||
'a',
|
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
|
||||||
'an',
|
'could', 'should', 'to', 'of', 'in', 'for', 'on', 'with',
|
||||||
'is',
|
'at', 'by', 'from', 'as', 'and', 'or', 'but', 'if', 'it',
|
||||||
'are',
|
'its', 'this', 'that', 'these', 'those', 'i', 'me', 'my',
|
||||||
'was',
|
'we', 'our', 'you', 'your', 'he', 'him', 'his', 'she', 'her',
|
||||||
'were',
|
'they', 'them', 'their', 'not', 'no', 'so', 'than', 'too',
|
||||||
'be',
|
'very', 'also', 'just', 'about', 'up', 'out', 'what', 'which', 'who'
|
||||||
'been',
|
|
||||||
'have',
|
|
||||||
'has',
|
|
||||||
'had',
|
|
||||||
'do',
|
|
||||||
'does',
|
|
||||||
'did',
|
|
||||||
'will',
|
|
||||||
'would',
|
|
||||||
'could',
|
|
||||||
'should',
|
|
||||||
'to',
|
|
||||||
'of',
|
|
||||||
'in',
|
|
||||||
'for',
|
|
||||||
'on',
|
|
||||||
'with',
|
|
||||||
'at',
|
|
||||||
'by',
|
|
||||||
'from',
|
|
||||||
'as',
|
|
||||||
'and',
|
|
||||||
'or',
|
|
||||||
'but',
|
|
||||||
'if',
|
|
||||||
'it',
|
|
||||||
'its',
|
|
||||||
'this',
|
|
||||||
'that',
|
|
||||||
'these',
|
|
||||||
'those',
|
|
||||||
'i',
|
|
||||||
'me',
|
|
||||||
'my',
|
|
||||||
'we',
|
|
||||||
'our',
|
|
||||||
'you',
|
|
||||||
'your',
|
|
||||||
'he',
|
|
||||||
'him',
|
|
||||||
'his',
|
|
||||||
'she',
|
|
||||||
'her',
|
|
||||||
'they',
|
|
||||||
'them',
|
|
||||||
'their',
|
|
||||||
'not',
|
|
||||||
'no',
|
|
||||||
'so',
|
|
||||||
'than',
|
|
||||||
'too',
|
|
||||||
'very',
|
|
||||||
'also',
|
|
||||||
'just',
|
|
||||||
'about',
|
|
||||||
'up',
|
|
||||||
'out',
|
|
||||||
'what',
|
|
||||||
'which',
|
|
||||||
'who',
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function countSyllables(word) {
|
function countSyllables(word) {
|
||||||
word = word.toLowerCase().replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
|
word = word.toLowerCase().replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
|
||||||
word = word.replace(/^y/, '');
|
word = word.replace(/^y/, '');
|
||||||
return word.match(/[aeiouy]{1,2}/gi)?.length || 1;
|
return word.match(/[aeiouy]{1,2}/gi)?.length || 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractWords(text) {
|
function extractWords(text) {
|
||||||
return text.match(/[a-zA-Z]+(?:['-][a-zA-Z]+)*/g) || [];
|
return text.match(/[a-zA-Z]+(?:['-][a-zA-Z]+)*/g) || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
function getReadabilityLabel(score) {
|
function getReadabilityLabel(score) {
|
||||||
if (score >= 90) return 'Very Easy';
|
if (score >= 90) return 'Very Easy';
|
||||||
if (score >= 70) return 'Easy';
|
if (score >= 70) return 'Easy';
|
||||||
if (score >= 50) return 'Standard';
|
if (score >= 50) return 'Standard';
|
||||||
if (score >= 30) return 'Difficult';
|
if (score >= 30) return 'Difficult';
|
||||||
return 'Very Difficult';
|
return 'Very Difficult';
|
||||||
}
|
}
|
||||||
|
|
||||||
function analyze(text) {
|
function analyze(text) {
|
||||||
if (!text || !text.trim()) {
|
if (!text || !text.trim()) {
|
||||||
|
return {
|
||||||
|
wordCount: 0,
|
||||||
|
sentenceCount: 0,
|
||||||
|
paragraphCount: 0,
|
||||||
|
fleschEase: 0,
|
||||||
|
fleschGrade: 0,
|
||||||
|
readabilityLabel: 'N/A',
|
||||||
|
readingTime: 0,
|
||||||
|
speakingTime: 0,
|
||||||
|
uniqueWordCount: 0,
|
||||||
|
lexicalDiversity: 0,
|
||||||
|
avgSentenceLength: 0,
|
||||||
|
longestSentence: '',
|
||||||
|
longestSentenceLength: 0,
|
||||||
|
topWords: []
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const words = extractWords(text);
|
||||||
|
const wordCount = words.length;
|
||||||
|
|
||||||
|
const sentences = text.split(/[.!?]+/).map(s => s.trim()).filter(Boolean);
|
||||||
|
const sentenceCount = Math.max(sentences.length, 1);
|
||||||
|
|
||||||
|
const paragraphs = text.split(/\n\s*\n/).map(p => p.trim()).filter(Boolean);
|
||||||
|
const paragraphCount = Math.max(paragraphs.length, 1);
|
||||||
|
|
||||||
|
let totalSyllables = 0;
|
||||||
|
for (const w of words) {
|
||||||
|
totalSyllables += countSyllables(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fleschEase = Math.round((206.835 - 1.015 * (wordCount / sentenceCount) - 84.6 * (totalSyllables / wordCount)) * 10) / 10;
|
||||||
|
const fleschGrade = Math.round((0.39 * (wordCount / sentenceCount) + 11.8 * (totalSyllables / wordCount) - 15.59) * 10) / 10;
|
||||||
|
const readabilityLabel = getReadabilityLabel(fleschEase);
|
||||||
|
|
||||||
|
const readingTime = Math.ceil(wordCount / 200);
|
||||||
|
const speakingTime = Math.ceil(wordCount / 130);
|
||||||
|
|
||||||
|
const uniqueWords = new Set(words.map(w => w.toLowerCase()));
|
||||||
|
const uniqueWordCount = uniqueWords.size;
|
||||||
|
const lexicalDiversity = wordCount > 0 ? Math.round((uniqueWordCount / wordCount) * 1000) / 10 : 0;
|
||||||
|
|
||||||
|
const avgSentenceLength = Math.round((wordCount / sentenceCount) * 10) / 10;
|
||||||
|
|
||||||
|
let longestSentence = '';
|
||||||
|
let longestSentenceLength = 0;
|
||||||
|
for (const s of sentences) {
|
||||||
|
const sWords = extractWords(s);
|
||||||
|
if (sWords.length > longestSentenceLength) {
|
||||||
|
longestSentenceLength = sWords.length;
|
||||||
|
longestSentence = s.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (longestSentence.length > 80) {
|
||||||
|
longestSentence = longestSentence.substring(0, 80) + '...';
|
||||||
|
}
|
||||||
|
|
||||||
|
const wordFreq = {};
|
||||||
|
for (const w of words) {
|
||||||
|
const lower = w.toLowerCase();
|
||||||
|
if (!STOP_WORDS.has(lower) && lower.length > 1) {
|
||||||
|
wordFreq[lower] = (wordFreq[lower] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const topWords = Object.entries(wordFreq)
|
||||||
|
.sort((a, b) => b[1] - a[1])
|
||||||
|
.slice(0, 10)
|
||||||
|
.map(([word, count]) => ({ word, count }));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
wordCount: 0,
|
wordCount,
|
||||||
sentenceCount: 0,
|
sentenceCount,
|
||||||
paragraphCount: 0,
|
paragraphCount,
|
||||||
fleschEase: 0,
|
fleschEase,
|
||||||
fleschGrade: 0,
|
fleschGrade,
|
||||||
readabilityLabel: 'N/A',
|
readabilityLabel,
|
||||||
readingTime: 0,
|
readingTime,
|
||||||
speakingTime: 0,
|
speakingTime,
|
||||||
uniqueWordCount: 0,
|
uniqueWordCount,
|
||||||
lexicalDiversity: 0,
|
lexicalDiversity,
|
||||||
avgSentenceLength: 0,
|
avgSentenceLength,
|
||||||
longestSentence: '',
|
longestSentence,
|
||||||
longestSentenceLength: 0,
|
longestSentenceLength,
|
||||||
topWords: [],
|
topWords
|
||||||
};
|
};
|
||||||
}
|
|
||||||
|
|
||||||
const words = extractWords(text);
|
|
||||||
const wordCount = words.length;
|
|
||||||
|
|
||||||
const sentences = text
|
|
||||||
.split(/[.!?]+/)
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const sentenceCount = Math.max(sentences.length, 1);
|
|
||||||
|
|
||||||
const paragraphs = text
|
|
||||||
.split(/\n\s*\n/)
|
|
||||||
.map((p) => p.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const paragraphCount = Math.max(paragraphs.length, 1);
|
|
||||||
|
|
||||||
let totalSyllables = 0;
|
|
||||||
for (const w of words) {
|
|
||||||
totalSyllables += countSyllables(w);
|
|
||||||
}
|
|
||||||
|
|
||||||
const fleschEase =
|
|
||||||
Math.round(
|
|
||||||
(206.835 - 1.015 * (wordCount / sentenceCount) - 84.6 * (totalSyllables / wordCount)) * 10
|
|
||||||
) / 10;
|
|
||||||
const fleschGrade =
|
|
||||||
Math.round(
|
|
||||||
(0.39 * (wordCount / sentenceCount) + 11.8 * (totalSyllables / wordCount) - 15.59) * 10
|
|
||||||
) / 10;
|
|
||||||
const readabilityLabel = getReadabilityLabel(fleschEase);
|
|
||||||
|
|
||||||
const readingTime = Math.ceil(wordCount / 200);
|
|
||||||
const speakingTime = Math.ceil(wordCount / 130);
|
|
||||||
|
|
||||||
const uniqueWords = new Set(words.map((w) => w.toLowerCase()));
|
|
||||||
const uniqueWordCount = uniqueWords.size;
|
|
||||||
const lexicalDiversity =
|
|
||||||
wordCount > 0 ? Math.round((uniqueWordCount / wordCount) * 1000) / 10 : 0;
|
|
||||||
|
|
||||||
const avgSentenceLength = Math.round((wordCount / sentenceCount) * 10) / 10;
|
|
||||||
|
|
||||||
let longestSentence = '';
|
|
||||||
let longestSentenceLength = 0;
|
|
||||||
for (const s of sentences) {
|
|
||||||
const sWords = extractWords(s);
|
|
||||||
if (sWords.length > longestSentenceLength) {
|
|
||||||
longestSentenceLength = sWords.length;
|
|
||||||
longestSentence = s.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (longestSentence.length > 80) {
|
|
||||||
longestSentence = longestSentence.substring(0, 80) + '...';
|
|
||||||
}
|
|
||||||
|
|
||||||
const wordFreq = {};
|
|
||||||
for (const w of words) {
|
|
||||||
const lower = w.toLowerCase();
|
|
||||||
if (!STOP_WORDS.has(lower) && lower.length > 1) {
|
|
||||||
wordFreq[lower] = (wordFreq[lower] || 0) + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const topWords = Object.entries(wordFreq)
|
|
||||||
.sort((a, b) => b[1] - a[1])
|
|
||||||
.slice(0, 10)
|
|
||||||
.map(([word, count]) => ({ word, count }));
|
|
||||||
|
|
||||||
return {
|
|
||||||
wordCount,
|
|
||||||
sentenceCount,
|
|
||||||
paragraphCount,
|
|
||||||
fleschEase,
|
|
||||||
fleschGrade,
|
|
||||||
readabilityLabel,
|
|
||||||
readingTime,
|
|
||||||
speakingTime,
|
|
||||||
uniqueWordCount,
|
|
||||||
lexicalDiversity,
|
|
||||||
avgSentenceLength,
|
|
||||||
longestSentence,
|
|
||||||
longestSentenceLength,
|
|
||||||
topWords,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { analyze };
|
module.exports = { analyze };
|
||||||
|
|||||||
+536
-686
File diff suppressed because it is too large
Load Diff
+87
-91
@@ -1,113 +1,109 @@
|
|||||||
class CommandPalette {
|
class CommandPalette {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.overlay = document.getElementById('command-palette-overlay');
|
this.overlay = document.getElementById('command-palette-overlay');
|
||||||
this.input = document.getElementById('command-palette-input');
|
this.input = document.getElementById('command-palette-input');
|
||||||
this.results = document.getElementById('command-palette-results');
|
this.results = document.getElementById('command-palette-results');
|
||||||
this.commands = [];
|
this.commands = [];
|
||||||
this.selectedIndex = 0;
|
this.selectedIndex = 0;
|
||||||
this.filteredCommands = [];
|
this.filteredCommands = [];
|
||||||
this.setupEventListeners();
|
this.setupEventListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
register(label, shortcut, action) {
|
register(label, shortcut, action) {
|
||||||
this.commands.push({ label, shortcut, action });
|
this.commands.push({ label, shortcut, action });
|
||||||
}
|
}
|
||||||
|
|
||||||
open() {
|
open() {
|
||||||
this.overlay.classList.remove('hidden');
|
this.overlay.classList.remove('hidden');
|
||||||
this.input.value = '';
|
this.input.value = '';
|
||||||
this.input.focus();
|
this.input.focus();
|
||||||
this.selectedIndex = 0;
|
this.selectedIndex = 0;
|
||||||
this.renderResults('');
|
this.renderResults('');
|
||||||
}
|
}
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
this.overlay.classList.add('hidden');
|
this.overlay.classList.add('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
isOpen() {
|
isOpen() {
|
||||||
return !this.overlay.classList.contains('hidden');
|
return !this.overlay.classList.contains('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
setupEventListeners() {
|
setupEventListeners() {
|
||||||
this.input.addEventListener('input', () => {
|
this.input.addEventListener('input', () => {
|
||||||
this.selectedIndex = 0;
|
this.selectedIndex = 0;
|
||||||
this.renderResults(this.input.value);
|
this.renderResults(this.input.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.overlay.addEventListener('click', (e) => {
|
this.overlay.addEventListener('click', (e) => {
|
||||||
if (e.target === this.overlay) this.close();
|
if (e.target === this.overlay) this.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
this.input.addEventListener('keydown', (e) => {
|
this.input.addEventListener('keydown', (e) => {
|
||||||
if (e.key === 'Escape') {
|
if (e.key === 'Escape') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.close();
|
this.close();
|
||||||
} else if (e.key === 'Enter') {
|
} else if (e.key === 'Enter') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.executeSelected();
|
this.executeSelected();
|
||||||
} else if (e.key === 'ArrowDown') {
|
} else if (e.key === 'ArrowDown') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCommands.length - 1);
|
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCommands.length - 1);
|
||||||
this.updateSelection();
|
this.updateSelection();
|
||||||
} else if (e.key === 'ArrowUp') {
|
} else if (e.key === 'ArrowUp') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
|
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
|
||||||
this.updateSelection();
|
this.updateSelection();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
renderResults(query) {
|
renderResults(query) {
|
||||||
this.filteredCommands = query
|
this.filteredCommands = query
|
||||||
? this.commands.filter((cmd) => cmd.label.toLowerCase().includes(query.toLowerCase()))
|
? this.commands.filter(cmd => cmd.label.toLowerCase().includes(query.toLowerCase()))
|
||||||
: [...this.commands];
|
: [...this.commands];
|
||||||
|
|
||||||
this.results.innerHTML = this.filteredCommands
|
this.results.innerHTML = this.filteredCommands.map((cmd, i) => `
|
||||||
.map(
|
|
||||||
(cmd, i) => `
|
|
||||||
<div class="command-item ${i === this.selectedIndex ? 'selected' : ''}" data-index="${i}">
|
<div class="command-item ${i === this.selectedIndex ? 'selected' : ''}" data-index="${i}">
|
||||||
<span class="command-label">${this.highlightMatch(cmd.label, query)}</span>
|
<span class="command-label">${this.highlightMatch(cmd.label, query)}</span>
|
||||||
${cmd.shortcut ? `<span class="command-shortcut">${cmd.shortcut}</span>` : ''}
|
${cmd.shortcut ? `<span class="command-shortcut">${cmd.shortcut}</span>` : ''}
|
||||||
</div>
|
</div>
|
||||||
`
|
`).join('');
|
||||||
)
|
|
||||||
.join('');
|
|
||||||
|
|
||||||
this.results.querySelectorAll('.command-item').forEach((el) => {
|
this.results.querySelectorAll('.command-item').forEach((el) => {
|
||||||
el.addEventListener('click', () => {
|
el.addEventListener('click', () => {
|
||||||
const idx = parseInt(el.dataset.index);
|
const idx = parseInt(el.dataset.index);
|
||||||
this.filteredCommands[idx].action();
|
this.filteredCommands[idx].action();
|
||||||
this.close();
|
this.close();
|
||||||
});
|
});
|
||||||
el.addEventListener('mouseenter', () => {
|
el.addEventListener('mouseenter', () => {
|
||||||
this.selectedIndex = parseInt(el.dataset.index);
|
this.selectedIndex = parseInt(el.dataset.index);
|
||||||
this.updateSelection();
|
this.updateSelection();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
highlightMatch(text, query) {
|
highlightMatch(text, query) {
|
||||||
if (!query) return text;
|
if (!query) return text;
|
||||||
const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
|
const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
|
||||||
return text.replace(regex, '<strong>$1</strong>');
|
return text.replace(regex, '<strong>$1</strong>');
|
||||||
}
|
}
|
||||||
|
|
||||||
updateSelection() {
|
updateSelection() {
|
||||||
this.results.querySelectorAll('.command-item').forEach((el, i) => {
|
this.results.querySelectorAll('.command-item').forEach((el, i) => {
|
||||||
el.classList.toggle('selected', i === this.selectedIndex);
|
el.classList.toggle('selected', i === this.selectedIndex);
|
||||||
});
|
});
|
||||||
// Scroll selected into view
|
// Scroll selected into view
|
||||||
const selected = this.results.querySelector('.command-item.selected');
|
const selected = this.results.querySelector('.command-item.selected');
|
||||||
if (selected) selected.scrollIntoView({ block: 'nearest' });
|
if (selected) selected.scrollIntoView({ block: 'nearest' });
|
||||||
}
|
}
|
||||||
|
|
||||||
executeSelected() {
|
executeSelected() {
|
||||||
if (this.filteredCommands[this.selectedIndex]) {
|
if (this.filteredCommands[this.selectedIndex]) {
|
||||||
this.filteredCommands[this.selectedIndex].action();
|
this.filteredCommands[this.selectedIndex].action();
|
||||||
this.close();
|
this.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { CommandPalette };
|
module.exports = { CommandPalette };
|
||||||
|
|||||||
@@ -12,23 +12,38 @@ const { EditorState } = require('@codemirror/state');
|
|||||||
const { markdown, markdownLanguage } = require('@codemirror/lang-markdown');
|
const { markdown, markdownLanguage } = require('@codemirror/lang-markdown');
|
||||||
// Language extensions loaded lazily on first use
|
// Language extensions loaded lazily on first use
|
||||||
let _javascript, _html, _css, _json, _python;
|
let _javascript, _html, _css, _json, _python;
|
||||||
const { defaultKeymap, history, historyKeymap, indentWithTab } = require('@codemirror/commands');
|
const {
|
||||||
const { searchKeymap, highlightSelectionMatches } = require('@codemirror/search');
|
defaultKeymap,
|
||||||
const { autocompletion, completionKeymap } = require('@codemirror/autocomplete');
|
history,
|
||||||
const { bracketMatching, foldGutter, indentOnInput } = require('@codemirror/language');
|
historyKeymap,
|
||||||
|
indentWithTab,
|
||||||
|
} = require('@codemirror/commands');
|
||||||
|
const {
|
||||||
|
searchKeymap,
|
||||||
|
highlightSelectionMatches,
|
||||||
|
} = require('@codemirror/search');
|
||||||
|
const {
|
||||||
|
autocompletion,
|
||||||
|
completionKeymap,
|
||||||
|
} = require('@codemirror/autocomplete');
|
||||||
|
const {
|
||||||
|
bracketMatching,
|
||||||
|
foldGutter,
|
||||||
|
indentOnInput,
|
||||||
|
} = require('@codemirror/language');
|
||||||
const { oneDark } = require('@codemirror/theme-one-dark');
|
const { oneDark } = require('@codemirror/theme-one-dark');
|
||||||
|
|
||||||
// Custom theme for JetBrains Mono font
|
// Custom theme for JetBrains Mono font
|
||||||
const jetBrainsMonoTheme = EditorView.theme({
|
const jetBrainsMonoTheme = EditorView.theme({
|
||||||
'&': {
|
'&': {
|
||||||
fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, 'Courier New', monospace",
|
fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, 'Courier New', monospace"
|
||||||
},
|
},
|
||||||
'.cm-content': {
|
'.cm-content': {
|
||||||
fontFamily: 'inherit',
|
fontFamily: 'inherit'
|
||||||
},
|
},
|
||||||
'.cm-scroller': {
|
'.cm-scroller': {
|
||||||
fontFamily: 'inherit',
|
fontFamily: 'inherit'
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -44,14 +59,7 @@ const jetBrainsMonoTheme = EditorView.theme({
|
|||||||
* @returns {EditorView} the created editor view
|
* @returns {EditorView} the created editor view
|
||||||
*/
|
*/
|
||||||
function createEditor(parentElement, options = {}) {
|
function createEditor(parentElement, options = {}) {
|
||||||
console.log(
|
console.log('[createEditor] Called with parentElement:', parentElement?.id, 'dimensions:', parentElement?.clientWidth, 'x', parentElement?.clientHeight);
|
||||||
'[createEditor] Called with parentElement:',
|
|
||||||
parentElement?.id,
|
|
||||||
'dimensions:',
|
|
||||||
parentElement?.clientWidth,
|
|
||||||
'x',
|
|
||||||
parentElement?.clientHeight
|
|
||||||
);
|
|
||||||
if (!parentElement) {
|
if (!parentElement) {
|
||||||
console.error('[createEditor] ERROR: parentElement is null or undefined!');
|
console.error('[createEditor] ERROR: parentElement is null or undefined!');
|
||||||
return null;
|
return null;
|
||||||
@@ -117,26 +125,11 @@ function createEditor(parentElement, options = {}) {
|
|||||||
*/
|
*/
|
||||||
function getLanguageExtension(lang) {
|
function getLanguageExtension(lang) {
|
||||||
const loaders = {
|
const loaders = {
|
||||||
javascript: () => {
|
javascript: () => { if (!_javascript) _javascript = require('@codemirror/lang-javascript').javascript; return _javascript(); },
|
||||||
if (!_javascript) _javascript = require('@codemirror/lang-javascript').javascript;
|
html: () => { if (!_html) _html = require('@codemirror/lang-html').html; return _html(); },
|
||||||
return _javascript();
|
css: () => { if (!_css) _css = require('@codemirror/lang-css').css; return _css(); },
|
||||||
},
|
json: () => { if (!_json) _json = require('@codemirror/lang-json').json; return _json(); },
|
||||||
html: () => {
|
python: () => { if (!_python) _python = require('@codemirror/lang-python').python; return _python(); },
|
||||||
if (!_html) _html = require('@codemirror/lang-html').html;
|
|
||||||
return _html();
|
|
||||||
},
|
|
||||||
css: () => {
|
|
||||||
if (!_css) _css = require('@codemirror/lang-css').css;
|
|
||||||
return _css();
|
|
||||||
},
|
|
||||||
json: () => {
|
|
||||||
if (!_json) _json = require('@codemirror/lang-json').json;
|
|
||||||
return _json();
|
|
||||||
},
|
|
||||||
python: () => {
|
|
||||||
if (!_python) _python = require('@codemirror/lang-python').python;
|
|
||||||
return _python();
|
|
||||||
},
|
|
||||||
markdown: () => markdown({ base: markdownLanguage }),
|
markdown: () => markdown({ base: markdownLanguage }),
|
||||||
};
|
};
|
||||||
loaders.js = loaders.javascript;
|
loaders.js = loaders.javascript;
|
||||||
|
|||||||
+45
-62
@@ -2,91 +2,74 @@
|
|||||||
|
|
||||||
/* Inter Font Family */
|
/* Inter Font Family */
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Inter';
|
font-family: 'Inter';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 300;
|
font-weight: 300;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/Inter-Light.woff2') format('woff2');
|
src: url('../assets/fonts/Inter-Light.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Inter';
|
font-family: 'Inter';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/Inter-Regular.woff2') format('woff2');
|
src: url('../assets/fonts/Inter-Regular.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Inter';
|
font-family: 'Inter';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/Inter-Medium.woff2') format('woff2');
|
src: url('../assets/fonts/Inter-Medium.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Inter';
|
font-family: 'Inter';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/Inter-SemiBold.woff2') format('woff2');
|
src: url('../assets/fonts/Inter-SemiBold.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Inter';
|
font-family: 'Inter';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/Inter-Bold.woff2') format('woff2');
|
src: url('../assets/fonts/Inter-Bold.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
/* JetBrains Mono Font Family - For code, markdown editor, and ASCII art */
|
/* JetBrains Mono Font Family - For code, markdown editor, and ASCII art */
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'JetBrains Mono';
|
font-family: 'JetBrains Mono';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/JetBrainsMono-Regular.woff2') format('woff2');
|
src: url('../assets/fonts/JetBrainsMono-Regular.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'JetBrains Mono';
|
font-family: 'JetBrains Mono';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/JetBrainsMono-Medium.woff2') format('woff2');
|
src: url('../assets/fonts/JetBrainsMono-Medium.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'JetBrains Mono';
|
font-family: 'JetBrains Mono';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/JetBrainsMono-SemiBold.woff2') format('woff2');
|
src: url('../assets/fonts/JetBrainsMono-SemiBold.woff2') format('woff2');
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'JetBrains Mono';
|
font-family: 'JetBrains Mono';
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2');
|
src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2');
|
||||||
}
|
|
||||||
|
|
||||||
/* Fira Code Font Family - bundled with the app */
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Fira Code';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 400;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/FiraCode-Regular.ttf') format('truetype');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Fira Code';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 700;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/FiraCode-Bold.ttf') format('truetype');
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1601
-2728
File diff suppressed because it is too large
Load Diff
+1436
-2557
File diff suppressed because it is too large
Load Diff
@@ -1,171 +0,0 @@
|
|||||||
/**
|
|
||||||
* Audio Operations Module
|
|
||||||
*
|
|
||||||
* Handles audio manipulation via `ffmpeg`: format conversion, trim, extract (audio
|
|
||||||
* track from video/audio), and merge (concat demuxer). Because ffmpeg is an external
|
|
||||||
* binary, this module is split into pure/testable argument-builder functions and a
|
|
||||||
* single `executeOperation` that is the only piece which actually spawns ffmpeg —
|
|
||||||
* the ffmpeg binary path and the `execFile` implementation are both injected so tests
|
|
||||||
* can replace them with fakes, without invoking a real binary.
|
|
||||||
*
|
|
||||||
* @module AudioOperations
|
|
||||||
*/
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const os = require('os');
|
|
||||||
const path = require('path');
|
|
||||||
const { execFile } = require('child_process');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args for a straight format conversion. ffmpeg infers the output format from
|
|
||||||
* outputPath's extension; only pass -f explicitly when format is given and differs
|
|
||||||
* from that extension.
|
|
||||||
*/
|
|
||||||
function buildConvertArgs({ inputPath, outputPath, format }) {
|
|
||||||
const args = ['-i', inputPath, '-y'];
|
|
||||||
|
|
||||||
if (format) {
|
|
||||||
const ext = path.extname(outputPath).replace(/^\./, '').toLowerCase();
|
|
||||||
if (format.toLowerCase() !== ext) {
|
|
||||||
args.push('-f', format);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push(outputPath);
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to trim inputPath to [startTime, startTime + duration) seconds.
|
|
||||||
* startTime/duration must be finite, non-negative numbers — they become argv
|
|
||||||
* elements passed straight to execFile with no shell involved, so there's no
|
|
||||||
* injection risk, but malformed values should still fail fast rather than reach
|
|
||||||
* ffmpeg with garbage.
|
|
||||||
*/
|
|
||||||
function buildTrimArgs({ inputPath, outputPath, startTime, duration }) {
|
|
||||||
const isValid = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
|
|
||||||
|
|
||||||
if (!isValid(startTime) || !isValid(duration)) {
|
|
||||||
throw new Error('Invalid trim range');
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to extract the audio track (stream copy, no video, no re-encode).
|
|
||||||
* If codec copy fails, executeOperation's 'extract' case retries without -acodec copy.
|
|
||||||
*/
|
|
||||||
function buildExtractArgs({ inputPath, outputPath }) {
|
|
||||||
return ['-i', inputPath, '-vn', '-acodec', 'copy', '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fallback extract args that let ffmpeg transcode instead of stream-copying.
|
|
||||||
*/
|
|
||||||
function buildExtractFallbackArgs({ inputPath, outputPath }) {
|
|
||||||
return ['-i', inputPath, '-vn', '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to merge 2+ files via the concat demuxer. Returns both concatListContent
|
|
||||||
* (the `file '<path>'` lines the caller writes to a temp list file) and args — the
|
|
||||||
* caller doesn't know the temp list file's path until it creates it, so tempListPath
|
|
||||||
* is an optional param: executeOperation's 'merge' case calls this once to obtain
|
|
||||||
* concatListContent, writes it to disk, then calls it again with the real
|
|
||||||
* tempListPath to obtain the final args referencing that file.
|
|
||||||
*/
|
|
||||||
function buildMergeArgs({ inputPaths, outputPath, tempListPath = null }) {
|
|
||||||
if (!Array.isArray(inputPaths) || inputPaths.length < 2) {
|
|
||||||
throw new Error('inputPaths must contain at least 2 files');
|
|
||||||
}
|
|
||||||
|
|
||||||
const concatListContent = inputPaths.map((p) => `file '${p}'`).join('\n') + '\n';
|
|
||||||
|
|
||||||
const args = ['-f', 'concat', '-safe', '0', '-i', tempListPath, '-c', 'copy', '-y', outputPath];
|
|
||||||
|
|
||||||
return { args, concatListContent };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run ffmpeg with the given args via the injected execFileFn, wrapped in a Promise.
|
|
||||||
*/
|
|
||||||
function runFfmpeg(ffmpegPath, args, execFileFn) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
execFileFn(ffmpegPath, args, { maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
||||||
if (error) {
|
|
||||||
reject(new Error(stderr || error.message));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeOperation(operation, data, { ffmpegPath, execFileFn } = {}) {
|
|
||||||
const resolvedFfmpegPath = ffmpegPath || 'ffmpeg';
|
|
||||||
const resolvedExecFileFn = execFileFn || execFile;
|
|
||||||
|
|
||||||
switch (operation) {
|
|
||||||
case 'convert': {
|
|
||||||
const { inputPath, outputPath, format } = data || {};
|
|
||||||
const args = buildConvertArgs({ inputPath, outputPath, format });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'trim': {
|
|
||||||
const { inputPath, outputPath, startTime, duration } = data || {};
|
|
||||||
const args = buildTrimArgs({ inputPath, outputPath, startTime, duration });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'extract': {
|
|
||||||
const { inputPath, outputPath } = data || {};
|
|
||||||
try {
|
|
||||||
const args = buildExtractArgs({ inputPath, outputPath });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
} catch {
|
|
||||||
// Codec copy can fail when the source audio codec isn't valid in the target
|
|
||||||
// container — fall back to letting ffmpeg transcode instead.
|
|
||||||
const fallbackArgs = buildExtractFallbackArgs({ inputPath, outputPath });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, fallbackArgs, resolvedExecFileFn);
|
|
||||||
}
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'merge': {
|
|
||||||
const { inputPaths, outputPath } = data || {};
|
|
||||||
const { concatListContent } = buildMergeArgs({ inputPaths, outputPath });
|
|
||||||
|
|
||||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'audio-merge-'));
|
|
||||||
const tempListPath = path.join(tempDir, 'concat-list.txt');
|
|
||||||
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(tempListPath, concatListContent, 'utf8');
|
|
||||||
const { args } = buildMergeArgs({ inputPaths, outputPath, tempListPath });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
||||||
} catch {
|
|
||||||
/* best-effort cleanup */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown operation: ${operation}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
executeOperation,
|
|
||||||
buildConvertArgs,
|
|
||||||
buildTrimArgs,
|
|
||||||
buildExtractArgs,
|
|
||||||
buildMergeArgs,
|
|
||||||
};
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const JSZip = require('jszip');
|
|
||||||
|
|
||||||
const REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
|
|
||||||
|
|
||||||
function generatedRId(idx) {
|
|
||||||
return `rIdFont${idx}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function patchZipWithFonts(inputPath, fonts) {
|
|
||||||
const buf = fs.readFileSync(inputPath);
|
|
||||||
const zip = await JSZip.loadAsync(buf);
|
|
||||||
const existingFontNames = new Set();
|
|
||||||
|
|
||||||
// Detect prior embeds (idempotency: skip TTF files already present).
|
|
||||||
for (const f of Object.keys(zip.files)) {
|
|
||||||
if (zip.files[f].name && /^word\/fonts\//.test(zip.files[f].name)) {
|
|
||||||
existingFontNames.add(path.basename(f));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 0; i < fonts.length; i++) {
|
|
||||||
const { path: fontPath } = fonts[i];
|
|
||||||
const fname = path.basename(fontPath);
|
|
||||||
const wordPath = `word/fonts/${fname}`;
|
|
||||||
if (!existingFontNames.has(fname)) {
|
|
||||||
zip.file(wordPath, fs.readFileSync(fontPath));
|
|
||||||
existingFontNames.add(fname);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build/replace word/fontTable.xml so Word knows the family and where to
|
|
||||||
// fetch the embedded TTF data.
|
|
||||||
const fontTableXml =
|
|
||||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
|
|
||||||
`<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/main">\n` +
|
|
||||||
fonts
|
|
||||||
.map(
|
|
||||||
(f, i) =>
|
|
||||||
` <w:font w:name="${f.family}"><w:embedRegular r:id="${generatedRId(i)}" xmlns:r="${REL_NS}"/></w:font>`
|
|
||||||
)
|
|
||||||
.join('\n') +
|
|
||||||
`\n</w:fonts>\n`;
|
|
||||||
|
|
||||||
zip.file('word/fontTable.xml', fontTableXml);
|
|
||||||
|
|
||||||
// Patch [Content_Types].xml — add Override for /word/fontTable.xml and each TTF.
|
|
||||||
const ctPath = '[Content_Types].xml';
|
|
||||||
let ct = await zip.file(ctPath).async('string');
|
|
||||||
if (!ct.includes('PartName="/word/fontTable.xml"')) {
|
|
||||||
ct = ct.replace(
|
|
||||||
'</Types>',
|
|
||||||
'<Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (const f of fonts) {
|
|
||||||
const ttfCt = 'application/x-font-ttf';
|
|
||||||
const filePart = `/word/fonts/${path.basename(f.path)}`;
|
|
||||||
if (!ct.includes(`PartName="${filePart}"`)) {
|
|
||||||
ct = ct.replace(
|
|
||||||
'</Types>',
|
|
||||||
`<Override PartName="${filePart}" ContentType="${ttfCt}"/></Types>`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!ct.includes('Default Extension="ttf"')) {
|
|
||||||
ct = ct.replace(
|
|
||||||
'</Types>',
|
|
||||||
'<Default Extension="ttf" ContentType="application/x-font-ttf"/></Types>'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
zip.file(ctPath, ct);
|
|
||||||
|
|
||||||
// Patch word/_rels/document.xml.rels — relationships for fontTable + each font.
|
|
||||||
const relsPath = 'word/_rels/document.xml.rels';
|
|
||||||
if (!zip.files[relsPath]) {
|
|
||||||
zip.file(
|
|
||||||
relsPath,
|
|
||||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="${REL_NS}"/>`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let rels = await zip.file(relsPath).async('string');
|
|
||||||
if (!rels.includes('fontTable.xml')) {
|
|
||||||
rels = rels.replace(
|
|
||||||
'</Relationships>',
|
|
||||||
`<Relationship Id="${generatedRId(fonts.length)}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (let i = 0; i < fonts.length; i++) {
|
|
||||||
const fname = path.basename(fonts[i].path);
|
|
||||||
if (!rels.includes(fname)) {
|
|
||||||
rels = rels.replace(
|
|
||||||
'</Relationships>',
|
|
||||||
`<Relationship Id="${generatedRId(i)}" Type="http://schemas.microsoft.com/office/2011/relationships/font" Target="fonts/${fname}"/></Relationships>`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
zip.file(relsPath, rels);
|
|
||||||
|
|
||||||
// Patch word/styles.xml — bind SourceCode/VerbatimChar styles to the family.
|
|
||||||
const stylesPath = 'word/styles.xml';
|
|
||||||
if (zip.files[stylesPath]) {
|
|
||||||
let styles = await zip.file(stylesPath).async('string');
|
|
||||||
const family = fonts[0].family;
|
|
||||||
if (!styles.includes(`w:ascii="${family}"`)) {
|
|
||||||
styles = styles.replace(
|
|
||||||
/(<w:style[^>]*w:styleId="(?:SourceCode|VerbatimChar)"[^>]*>)/,
|
|
||||||
`$1<w:rPr><w:rFonts w:ascii="${family}" w:hAnsi="${family}" w:cs="${family}"/></w:rPr>`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
zip.file(stylesPath, styles);
|
|
||||||
}
|
|
||||||
|
|
||||||
const outBuf = await zip.generateAsync({ type: 'nodebuffer' });
|
|
||||||
fs.writeFileSync(inputPath, outBuf);
|
|
||||||
return inputPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function embed(docxPath, fonts) {
|
|
||||||
return patchZipWithFonts(docxPath, fonts);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { embed };
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const JSZip = require('jszip');
|
|
||||||
|
|
||||||
// Patches an EPUB produced by pandoc so it embeds the supplied TTF font files
|
|
||||||
// inside the OEBPS and registers them in the OPF manifest. Used after
|
|
||||||
// `pandoc --epub-embed-font=...` runs (which embeds the font data) but does
|
|
||||||
// not always add the manifest item we need for readers to discover the font.
|
|
||||||
//
|
|
||||||
// Writes a new file at `${epubPath}.patched.epub` and returns the patched path.
|
|
||||||
// Caller should overwrite the original after a successful export.
|
|
||||||
async function patchManifest(epubPath, fonts) {
|
|
||||||
const zip = await JSZip.loadAsync(fs.readFileSync(epubPath));
|
|
||||||
const opfPath = Object.keys(zip.files).find((f) => f.endsWith('content.opf'));
|
|
||||||
if (!opfPath) throw new Error('EPUB has no content.opf');
|
|
||||||
let opf = await zip.file(opfPath).async('string');
|
|
||||||
|
|
||||||
for (const { path: fontPath, family, weight } of fonts) {
|
|
||||||
const filename = path.basename(fontPath);
|
|
||||||
const inFontDir = `OEBPS/fonts/${filename}`;
|
|
||||||
zip.file(inFontDir, fs.readFileSync(fontPath));
|
|
||||||
if (!opf.includes(filename)) {
|
|
||||||
const safeFamily = String(family || 'Font').replace(/\s+/g, '-');
|
|
||||||
const item = `<item id="font-${safeFamily}-${weight}" href="${inFontDir}" media-type="application/x-font-ttf"/>`;
|
|
||||||
if (opf.includes('</manifest>')) {
|
|
||||||
opf = opf.replace('</manifest>', `${item}</manifest>`);
|
|
||||||
} else {
|
|
||||||
// OPF without a manifest element (unusual but tolerated): inject one
|
|
||||||
// just before </package> so the font item is still discoverable.
|
|
||||||
opf = opf.replace('</package>', `<manifest>${item}</manifest></package>`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
zip.file(opfPath, opf);
|
|
||||||
const buf = await zip.generateAsync({ type: 'nodebuffer' });
|
|
||||||
const tmp = `${epubPath}.patched.epub`;
|
|
||||||
fs.writeFileSync(tmp, buf);
|
|
||||||
return tmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { patchManifest };
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
function toDataUri(filePath) {
|
|
||||||
const buf = fs.readFileSync(filePath);
|
|
||||||
return `data:font/woff2;base64,${buf.toString('base64')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function build({ activeFontPath, family, weight = 400, ligatures = false }) {
|
|
||||||
const features = ligatures ? 'normal' : "'liga' 0, 'calt' 0, 'dlig' 0";
|
|
||||||
const faceBlock = activeFontPath
|
|
||||||
? `@font-face {
|
|
||||||
font-family: '${family}';
|
|
||||||
font-weight: ${weight};
|
|
||||||
font-style: normal;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('${toDataUri(activeFontPath)}') format('woff2');
|
|
||||||
}
|
|
||||||
`
|
|
||||||
: '';
|
|
||||||
|
|
||||||
return `${faceBlock}code, pre, kbd, samp {
|
|
||||||
font-family: '${family}', monospace;
|
|
||||||
font-feature-settings: ${features};
|
|
||||||
}
|
|
||||||
pre, code {
|
|
||||||
white-space: pre;
|
|
||||||
tab-size: 4;
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { build };
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Export preset persistence (Task 21 — export presets/profiles).
|
|
||||||
*
|
|
||||||
* Pure list operations over the `exportPresets` array kept in the app's
|
|
||||||
* settings.json store (the `store.get`/`store.set` helpers defined in
|
|
||||||
* src/main.js — the same store that holds headerFooterSettings and
|
|
||||||
* pageSettings). The store is injected so the logic is unit-testable with a
|
|
||||||
* fake store (see tests/main/ExportPresets.test.js); src/main.js wires these
|
|
||||||
* functions to the get-export-presets / save-export-preset /
|
|
||||||
* delete-export-preset invoke channels.
|
|
||||||
*
|
|
||||||
* Preset shape: { id: string, name: string, format: string|null, options: object }
|
|
||||||
* — `options` is the export-options snapshot captured from the renderer's
|
|
||||||
* export dialog, so selecting a preset can pre-fill that dialog exactly.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const PRESET_KEY = 'exportPresets';
|
|
||||||
const MAX_PRESETS = 50;
|
|
||||||
const MAX_NAME_LENGTH = 100;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read the stored presets, defensively skipping corrupt data.
|
|
||||||
* @param {{get: Function, set: Function}} store settings store
|
|
||||||
* @returns {Array<{id: string, name: string, format: string|null, options: Object}>}
|
|
||||||
*/
|
|
||||||
function loadPresets(store) {
|
|
||||||
const stored = store.get(PRESET_KEY, []);
|
|
||||||
if (!Array.isArray(stored)) return [];
|
|
||||||
return stored.filter(
|
|
||||||
(preset) =>
|
|
||||||
preset &&
|
|
||||||
typeof preset === 'object' &&
|
|
||||||
typeof preset.id === 'string' &&
|
|
||||||
typeof preset.name === 'string'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate, normalize, and upsert a preset by id. A missing id gets a newly
|
|
||||||
* generated one (insert); an id that already exists is replaced (update).
|
|
||||||
* @param {{get: Function, set: Function}} store settings store
|
|
||||||
* @param {{id?: string, name?: string, format?: string, options?: Object}} preset
|
|
||||||
* @returns {Array} the updated preset list (also persisted)
|
|
||||||
* @throws when the preset is not an object, the name is empty, or the cap is hit
|
|
||||||
*/
|
|
||||||
function savePreset(store, preset) {
|
|
||||||
if (!preset || typeof preset !== 'object') {
|
|
||||||
throw new Error('Preset must be an object');
|
|
||||||
}
|
|
||||||
const name = typeof preset.name === 'string' ? preset.name.trim().slice(0, MAX_NAME_LENGTH) : '';
|
|
||||||
if (!name) {
|
|
||||||
throw new Error('Preset name is required');
|
|
||||||
}
|
|
||||||
const options = preset.options && typeof preset.options === 'object' ? preset.options : {};
|
|
||||||
const format = typeof preset.format === 'string' ? preset.format : null;
|
|
||||||
|
|
||||||
const presets = loadPresets(store);
|
|
||||||
const id = typeof preset.id === 'string' && preset.id ? preset.id : createPresetId();
|
|
||||||
const entry = { id, name, format, options };
|
|
||||||
|
|
||||||
const index = presets.findIndex((existing) => existing.id === id);
|
|
||||||
if (index >= 0) {
|
|
||||||
presets[index] = entry;
|
|
||||||
} else {
|
|
||||||
if (presets.length >= MAX_PRESETS) {
|
|
||||||
throw new Error(`Cannot store more than ${MAX_PRESETS} export presets`);
|
|
||||||
}
|
|
||||||
presets.push(entry);
|
|
||||||
}
|
|
||||||
store.set(PRESET_KEY, presets);
|
|
||||||
return presets;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the preset with the given id (idempotent).
|
|
||||||
* @param {{get: Function, set: Function}} store settings store
|
|
||||||
* @param {string} presetId
|
|
||||||
* @returns {Array} the updated preset list (also persisted)
|
|
||||||
*/
|
|
||||||
function deletePreset(store, presetId) {
|
|
||||||
const presets = loadPresets(store).filter((preset) => preset.id !== presetId);
|
|
||||||
store.set(PRESET_KEY, presets);
|
|
||||||
return presets;
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPresetId() {
|
|
||||||
return `preset-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { loadPresets, savePreset, deletePreset, PRESET_KEY, MAX_PRESETS };
|
|
||||||
@@ -8,7 +8,7 @@ async function getStatus(dir) {
|
|||||||
try {
|
try {
|
||||||
const git = getGitInstance(dir);
|
const git = getGitInstance(dir);
|
||||||
return await git.status();
|
return await git.status();
|
||||||
} catch {
|
} catch (err) {
|
||||||
return { error: 'Not a git repository' };
|
return { error: 'Not a git repository' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -41,55 +41,4 @@ async function log(dir, maxCount = 20) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// againstHead=true compares the working tree (staged + unstaged) against the last
|
module.exports = { getStatus, stage, commit, log };
|
||||||
// commit instead of against the index — used by the Document Compare dialog's
|
|
||||||
// "Git HEAD" mode. Default behavior (worktree vs index) is unchanged.
|
|
||||||
async function diff(dir, file, againstHead = false) {
|
|
||||||
try {
|
|
||||||
const git = getGitInstance(dir);
|
|
||||||
if (againstHead) {
|
|
||||||
return file ? await git.diff(['HEAD', '--', file]) : await git.diff('HEAD');
|
|
||||||
}
|
|
||||||
return file ? await git.diff([file]) : await git.diff();
|
|
||||||
} catch (err) {
|
|
||||||
return { error: err.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function branches(dir) {
|
|
||||||
try {
|
|
||||||
const git = getGitInstance(dir);
|
|
||||||
return await git.branchLocal();
|
|
||||||
} catch (err) {
|
|
||||||
return { error: err.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkoutBranch(dir, name, isNew) {
|
|
||||||
try {
|
|
||||||
const git = getGitInstance(dir);
|
|
||||||
return isNew ? await git.checkoutLocalBranch(name) : await git.checkout(name);
|
|
||||||
} catch (err) {
|
|
||||||
return { error: err.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function push(dir) {
|
|
||||||
try {
|
|
||||||
const git = getGitInstance(dir);
|
|
||||||
return await git.push();
|
|
||||||
} catch (err) {
|
|
||||||
return { error: err.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pull(dir) {
|
|
||||||
try {
|
|
||||||
const git = getGitInstance(dir);
|
|
||||||
return await git.pull();
|
|
||||||
} catch (err) {
|
|
||||||
return { error: err.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getStatus, stage, commit, log, diff, branches, checkoutBranch, push, pull };
|
|
||||||
|
|||||||
@@ -1,198 +0,0 @@
|
|||||||
/**
|
|
||||||
* Image Operations Module
|
|
||||||
*
|
|
||||||
* Handles image manipulation via `sharp`: format conversion, resize, compress, rotate.
|
|
||||||
* Mirrors the executeOperation(operation, data) dispatcher pattern used by PDFOperations.js.
|
|
||||||
*
|
|
||||||
* sharp loads LAZILY: its native bindings (@img/sharp-*) are optionalDependencies
|
|
||||||
* that a packaged build can prune or fail to unpack, and a top-level require would
|
|
||||||
* then crash the whole app at boot (src/main.js requires this module unconditionally).
|
|
||||||
* When sharp cannot load, operations degrade honestly instead of killing the app —
|
|
||||||
* the same honest-failure precedent PDFOperations set for missing pdf-lib features.
|
|
||||||
*
|
|
||||||
* @module ImageOperations
|
|
||||||
*/
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
let sharpModule = null;
|
|
||||||
let sharpLoadError = null;
|
|
||||||
|
|
||||||
function loadSharp() {
|
|
||||||
if (sharpModule) return sharpModule;
|
|
||||||
if (sharpLoadError) throw sharpLoadError;
|
|
||||||
try {
|
|
||||||
sharpModule = require('sharp');
|
|
||||||
return sharpModule;
|
|
||||||
} catch (error) {
|
|
||||||
sharpLoadError = error;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strip absolute paths from error text before it reaches callers, mirroring
|
|
||||||
// sanitizeErrorMessage() in main.js (that helper is not importable from here).
|
|
||||||
function sanitizeMessage(message) {
|
|
||||||
if (typeof message !== 'string') return String(message);
|
|
||||||
return message
|
|
||||||
.replace(/[A-Z]:\\[^\s"']+\\([^\s"'\\]+)/gi, '$1')
|
|
||||||
.replace(/\/[^\s"']+\/([^\s"'/]+)/g, '$1');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Must match the MAX_FILE_SIZE convention defined in main.js (50MB). main.js is the
|
|
||||||
// single source of truth for this limit; this module does not redefine it independently
|
|
||||||
// — callers (main.js) pass it in via data.maxFileSize when they want it enforced, and we
|
|
||||||
// fall back to the same 50MB default so direct/unit-test callers are still protected.
|
|
||||||
const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024;
|
|
||||||
|
|
||||||
const RASTER_FORMATS = ['jpeg', 'png', 'webp', 'avif', 'tiff', 'gif'];
|
|
||||||
const RESIZE_FIT_MODES = ['cover', 'contain', 'fill', 'inside', 'outside'];
|
|
||||||
|
|
||||||
function validateInput(data) {
|
|
||||||
const { inputPath, outputPath, maxFileSize } = data || {};
|
|
||||||
|
|
||||||
if (!inputPath || !outputPath) {
|
|
||||||
throw new Error('inputPath and outputPath are required');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!fs.existsSync(inputPath)) {
|
|
||||||
throw new Error(`Input file not found: ${path.basename(inputPath)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const limit = typeof maxFileSize === 'number' ? maxFileSize : DEFAULT_MAX_FILE_SIZE;
|
|
||||||
const stats = fs.statSync(inputPath);
|
|
||||||
if (stats.size > limit) {
|
|
||||||
throw new Error(`File exceeds the ${Math.floor(limit / (1024 * 1024))}MB size limit.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function imageConvert(data) {
|
|
||||||
try {
|
|
||||||
const sharp = loadSharp();
|
|
||||||
validateInput(data);
|
|
||||||
const { inputPath, outputPath, format } = data;
|
|
||||||
|
|
||||||
if (!RASTER_FORMATS.includes(format)) {
|
|
||||||
throw new Error(`Unsupported output format: ${format}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await sharp(inputPath).toFormat(format).toFile(outputPath);
|
|
||||||
|
|
||||||
return { success: true, outputPath };
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Image conversion failed: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function imageResize(data) {
|
|
||||||
try {
|
|
||||||
const sharp = loadSharp();
|
|
||||||
validateInput(data);
|
|
||||||
const { inputPath, outputPath, width = null, height = null, fit = 'inside' } = data;
|
|
||||||
|
|
||||||
if (width === null && height === null) {
|
|
||||||
throw new Error('At least one of width or height must be provided');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!RESIZE_FIT_MODES.includes(fit)) {
|
|
||||||
throw new Error(`Unsupported fit mode: ${fit}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await sharp(inputPath).resize({ width, height, fit }).toFile(outputPath);
|
|
||||||
|
|
||||||
return { success: true, outputPath };
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Image resize failed: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function imageCompress(data) {
|
|
||||||
try {
|
|
||||||
const sharp = loadSharp();
|
|
||||||
validateInput(data);
|
|
||||||
const { inputPath, outputPath, quality = 80 } = data;
|
|
||||||
|
|
||||||
if (!Number.isInteger(quality) || quality < 1 || quality > 100) {
|
|
||||||
throw new Error('quality must be an integer between 1 and 100');
|
|
||||||
}
|
|
||||||
|
|
||||||
const ext = path.extname(outputPath).toLowerCase().replace('.', '');
|
|
||||||
let pipeline = sharp(inputPath);
|
|
||||||
|
|
||||||
switch (ext) {
|
|
||||||
case 'jpg':
|
|
||||||
case 'jpeg':
|
|
||||||
pipeline = pipeline.jpeg({ quality });
|
|
||||||
break;
|
|
||||||
case 'webp':
|
|
||||||
pipeline = pipeline.webp({ quality });
|
|
||||||
break;
|
|
||||||
case 'avif':
|
|
||||||
pipeline = pipeline.avif({ quality });
|
|
||||||
break;
|
|
||||||
case 'png':
|
|
||||||
pipeline = pipeline.png({ quality, compressionLevel: 9 });
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new Error(`Unsupported compression output format: ${ext}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await pipeline.toFile(outputPath);
|
|
||||||
|
|
||||||
return { success: true, outputPath };
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Image compression failed: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function imageRotate(data) {
|
|
||||||
try {
|
|
||||||
const sharp = loadSharp();
|
|
||||||
validateInput(data);
|
|
||||||
const { inputPath, outputPath, angle } = data;
|
|
||||||
|
|
||||||
if (typeof angle !== 'number' || !Number.isFinite(angle)) {
|
|
||||||
throw new Error('angle must be a number');
|
|
||||||
}
|
|
||||||
|
|
||||||
await sharp(inputPath).rotate(angle).toFile(outputPath);
|
|
||||||
|
|
||||||
return { success: true, outputPath };
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Image rotation failed: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function executeOperation(operation, data) {
|
|
||||||
try {
|
|
||||||
loadSharp();
|
|
||||||
} catch (error) {
|
|
||||||
// Honest degradation: the app keeps booting and every image op reports the
|
|
||||||
// unavailable state as a resolved result instead of throwing at import time.
|
|
||||||
return Promise.resolve({
|
|
||||||
success: false,
|
|
||||||
error: `Image operations unavailable: ${sanitizeMessage(error.message)}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
switch (operation) {
|
|
||||||
case 'convert':
|
|
||||||
return imageConvert(data);
|
|
||||||
case 'resize':
|
|
||||||
return imageResize(data);
|
|
||||||
case 'compress':
|
|
||||||
return imageCompress(data);
|
|
||||||
case 'rotate':
|
|
||||||
return imageRotate(data);
|
|
||||||
default:
|
|
||||||
return Promise.reject(new Error(`Unknown operation: ${operation}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
executeOperation,
|
|
||||||
imageConvert,
|
|
||||||
imageResize,
|
|
||||||
imageCompress,
|
|
||||||
imageRotate,
|
|
||||||
};
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const {
|
|
||||||
getActiveMonoFont,
|
|
||||||
isLigaturesEnabled,
|
|
||||||
FAMILY_BY_KEY,
|
|
||||||
} = require('./settings/monospaceSettings');
|
|
||||||
|
|
||||||
const WEIGHT_BY_KEY = { 300: 'Light', 400: 'Regular', 500: 'Medium', 600: 'SemiBold', 700: 'Bold' };
|
|
||||||
|
|
||||||
function getAppRoot() {
|
|
||||||
if (
|
|
||||||
process.resourcesPath &&
|
|
||||||
fs.existsSync(path.join(process.resourcesPath, 'app.asar.unpacked'))
|
|
||||||
) {
|
|
||||||
return process.resourcesPath;
|
|
||||||
}
|
|
||||||
return path.resolve(__dirname, '..', '..');
|
|
||||||
}
|
|
||||||
|
|
||||||
function getCandidatePaths(family, weight) {
|
|
||||||
const familyDir = family === 'Fira Code' ? 'FiraCode' : 'JetBrainsMono';
|
|
||||||
const weightName = WEIGHT_BY_KEY[weight] || 'Regular';
|
|
||||||
const filename = `${familyDir}-${weightName}.ttf`;
|
|
||||||
|
|
||||||
const candidates = [];
|
|
||||||
candidates.push(path.resolve(getAppRoot(), 'assets', 'fonts', filename));
|
|
||||||
const packagedRoot = process.resourcesPath || getAppRoot();
|
|
||||||
candidates.push(path.join(packagedRoot, 'app.asar.unpacked', 'assets', 'fonts', filename));
|
|
||||||
return candidates;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getMonoFontTtfPath(familyKey, weight = 400) {
|
|
||||||
const family = FAMILY_BY_KEY[familyKey] || 'JetBrains Mono';
|
|
||||||
const candidates = getCandidatePaths(family, weight);
|
|
||||||
for (const p of candidates) {
|
|
||||||
if (fs.existsSync(p)) return p;
|
|
||||||
}
|
|
||||||
const filename = path.basename(candidates[candidates.length - 1]);
|
|
||||||
console.warn(
|
|
||||||
`[MonospaceFontConfig] bundled font missing: ${filename}; falling back to system monospace`
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ligaturesEnabled(settings) {
|
|
||||||
return isLigaturesEnabled(settings);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getActiveFamily(settings) {
|
|
||||||
return getActiveMonoFont(settings);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getMonoFontTtfPath, ligaturesEnabled, getActiveFamily };
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
/**
|
|
||||||
* PDFBatchOperations
|
|
||||||
*
|
|
||||||
* Applies one PDFOperations.executeOperation() operation (watermark, compress,
|
|
||||||
* rotate, split, ...) to every .pdf file in an input folder — the PDF sibling of
|
|
||||||
* runMediaBatchOperation() in main.js (Task 12's image/audio/video batch mode):
|
|
||||||
* collect matching files via collectFilesByExtension (which generalizes the
|
|
||||||
* inline collectFiles() of the 'universal-convert-batch' handler), loop the
|
|
||||||
* operation over them, and report per-file progress plus a final
|
|
||||||
* completed/failed summary.
|
|
||||||
*
|
|
||||||
* Pulled out as its own Electron-free module (same precedent as
|
|
||||||
* collectFilesByExtension) so the batch loop is unit-testable against real
|
|
||||||
* pdf-lib fixtures; main.js injects the IPC-facing callbacks:
|
|
||||||
* onProgress -> mainWindow.webContents.send('batch-progress', ...)
|
|
||||||
* onComplete -> mainWindow.webContents.send('pdf-batch-complete', ...) + dialog
|
|
||||||
*
|
|
||||||
* Not every executeOperation op fits the "apply the same operation to every
|
|
||||||
* file" batch model. Excluded (enforced by absence from PDF_BATCH_OUTPUT_SPEC,
|
|
||||||
* which doubles as the defensive backstop for renderer-supplied op names):
|
|
||||||
* - merge / reorder / fillForm — consume per-file knowledge the batch flow
|
|
||||||
* cannot supply (merge takes many inputs in one op; reorder needs each
|
|
||||||
* file's full page order; fillForm's field values differ per file).
|
|
||||||
* - formFields — a read-only query returning data, not a transform.
|
|
||||||
* - encrypt / decrypt / permissions — pdf-lib 1.17.1 (bundled) lacks
|
|
||||||
* encryption support, so since Task 27 these ops fail honestly with an
|
|
||||||
* "unavailable" result instead of silently writing unprotected files;
|
|
||||||
* a batch run would deterministically fail every file.
|
|
||||||
*
|
|
||||||
* @module PDFBatchOperations
|
|
||||||
*/
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const PDFOperations = require('./PDFOperations');
|
|
||||||
const { collectFilesByExtension } = require('./collectFilesByExtension');
|
|
||||||
|
|
||||||
// How to derive each output file's path (or directory) from the source file,
|
|
||||||
// mirroring BATCH_OUTPUT_SPEC in main.js:
|
|
||||||
// { ext: 'original' } -> <outputFolder>/<relativeDir>/<baseName>.pdf via outputPath
|
|
||||||
// { ext: 'txt' } -> <outputFolder>/<relativeDir>/<baseName>.txt via outputPath
|
|
||||||
// { folder: true } -> split writes its `<baseName>_part_N.pdf` files into
|
|
||||||
// the mirrored output folder via outputFolder
|
|
||||||
// { dir: true } -> extractImages writes images into a per-PDF
|
|
||||||
// <outputFolder>/<relativeDir>/<baseName>/ via outputDir
|
|
||||||
const PDF_BATCH_OUTPUT_SPEC = {
|
|
||||||
split: { folder: true },
|
|
||||||
compress: { ext: 'original' },
|
|
||||||
rotate: { ext: 'original' },
|
|
||||||
delete: { ext: 'original' },
|
|
||||||
watermark: { ext: 'original' },
|
|
||||||
extractText: { ext: 'txt' },
|
|
||||||
pageNumbers: { ext: 'original' },
|
|
||||||
crop: { ext: 'original' },
|
|
||||||
extractImages: { dir: true },
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs a single PDFOperations operation over every .pdf under `inputFolder`.
|
|
||||||
*
|
|
||||||
* @param {object} args
|
|
||||||
* @param {string} args.operation - executeOperation op name (must be batchable).
|
|
||||||
* @param {string} args.inputFolder - Folder to scan for .pdf files.
|
|
||||||
* @param {string} args.outputFolder - Destination folder (created if missing);
|
|
||||||
* the input folder's relative structure is mirrored beneath it.
|
|
||||||
* @param {boolean} [args.includeSubfolders=true] - Recurse into subdirectories.
|
|
||||||
* @param {object} [args.data={}] - Shared operation options forwarded to
|
|
||||||
* executeOperation for every file (same option shapes as the single-file PDF
|
|
||||||
* editor dialog; inputPath/outputPath are added per file here).
|
|
||||||
* @param {number} [args.maxFileSize] - Skip (count as failed) files larger than
|
|
||||||
* this many bytes, mirroring the batch-convert handler's file-size guard.
|
|
||||||
* @param {Function} [args.onProgress] - Called with { completed, failed, total,
|
|
||||||
* currentFile } before each file and once (currentFile: null) at the end —
|
|
||||||
* the existing 'batch-progress' payload shape.
|
|
||||||
* @param {Function} args.onComplete - Called exactly once with the outcome:
|
|
||||||
* { success: false, error } for early failures, otherwise
|
|
||||||
* { success: true, completed, failed, total, outputFolder }.
|
|
||||||
* @param {Function} [args.sanitizeError] - Sanitizer for error messages that
|
|
||||||
* could leak absolute paths (main.js passes sanitizeErrorMessage).
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function runPDFBatchOperation({
|
|
||||||
operation,
|
|
||||||
inputFolder,
|
|
||||||
outputFolder,
|
|
||||||
includeSubfolders,
|
|
||||||
data = {},
|
|
||||||
maxFileSize,
|
|
||||||
onProgress = () => {},
|
|
||||||
onComplete,
|
|
||||||
sanitizeError = (message) => message,
|
|
||||||
}) {
|
|
||||||
const spec = PDF_BATCH_OUTPUT_SPEC[operation];
|
|
||||||
if (!spec) {
|
|
||||||
onComplete({
|
|
||||||
success: false,
|
|
||||||
error: `Batch mode is not supported for the "${operation}" operation.`,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!inputFolder || !fs.existsSync(inputFolder)) {
|
|
||||||
onComplete({ success: false, error: 'Input folder does not exist.' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
fs.mkdirSync(outputFolder, { recursive: true });
|
|
||||||
} catch (error) {
|
|
||||||
onComplete({
|
|
||||||
success: false,
|
|
||||||
error: sanitizeError(`Failed to create output folder: ${error.message}`),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const files = collectFilesByExtension(inputFolder, ['.pdf'], includeSubfolders !== false);
|
|
||||||
if (files.length === 0) {
|
|
||||||
onComplete({ success: false, error: 'No matching files found in the selected folder.' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const total = files.length;
|
|
||||||
let completed = 0;
|
|
||||||
let failed = 0;
|
|
||||||
|
|
||||||
for (const filePath of files) {
|
|
||||||
onProgress({
|
|
||||||
completed,
|
|
||||||
failed,
|
|
||||||
total,
|
|
||||||
currentFile: path.basename(filePath),
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (maxFileSize && fs.statSync(filePath).size > maxFileSize) {
|
|
||||||
failed++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseName = path.basename(filePath, path.extname(filePath));
|
|
||||||
const relativeDir = path.dirname(path.relative(inputFolder, filePath));
|
|
||||||
const targetDir = relativeDir === '.' ? outputFolder : path.join(outputFolder, relativeDir);
|
|
||||||
fs.mkdirSync(targetDir, { recursive: true });
|
|
||||||
|
|
||||||
const fileData = { ...data, inputPath: filePath };
|
|
||||||
if (spec.dir) {
|
|
||||||
fileData.outputDir = path.join(targetDir, baseName);
|
|
||||||
} else if (spec.folder) {
|
|
||||||
fileData.outputFolder = targetDir;
|
|
||||||
} else {
|
|
||||||
const ext = spec.ext === 'original' ? 'pdf' : spec.ext;
|
|
||||||
fileData.outputPath = path.join(targetDir, `${baseName}.${ext}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// PDFOperations ops report failures via { success: false } rather than by
|
|
||||||
// throwing (each op catches internally), so the result flag — not just
|
|
||||||
// the promise — decides the per-file outcome.
|
|
||||||
const result = await PDFOperations.executeOperation(operation, fileData);
|
|
||||||
if (result && result.success) {
|
|
||||||
completed++;
|
|
||||||
} else {
|
|
||||||
failed++;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// stat/mkdir can throw (file vanished mid-scan, output path became a
|
|
||||||
// file, ...): count the file as failed and keep the batch going, matching
|
|
||||||
// how executeOperation's own failures are handled.
|
|
||||||
failed++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onProgress({ completed, failed, total, currentFile: null });
|
|
||||||
onComplete({ success: true, completed, failed, total, outputFolder });
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { runPDFBatchOperation, PDF_BATCH_OUTPUT_SPEC };
|
|
||||||
+82
-409
@@ -2,37 +2,13 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
|
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
|
||||||
|
|
||||||
// pdf-lib 1.17.1 cannot encrypt: SaveOptions has no userPassword/ownerPassword/
|
|
||||||
// permissions fields, so save() silently ignores them and writes an unprotected
|
|
||||||
// file, and PDFDocument.load() cannot open password-protected input (verified
|
|
||||||
// empirically in Task 22's review). Rather than trusting a pinned version
|
|
||||||
// string, probe the installed library once at module load: save a tiny
|
|
||||||
// in-memory document with a userPassword and check the raw bytes for an
|
|
||||||
// /Encrypt dictionary (which an unencrypted document never contains). A library
|
|
||||||
// that supports encryption passes the probe and the password ops re-enable
|
|
||||||
// automatically. Probe errors fail closed (treated as unsupported).
|
|
||||||
const pdfEncryptionSupported = (async () => {
|
|
||||||
try {
|
|
||||||
const probeDoc = await PDFDocument.create();
|
|
||||||
const probeBytes = await probeDoc.save({ userPassword: 'encryption-capability-probe' });
|
|
||||||
return Buffer.from(probeBytes).includes('/Encrypt');
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
// Returned by the password ops when the probe reports no encryption support
|
|
||||||
// (Task 27): fail honestly instead of silently writing an unprotected file.
|
|
||||||
const PDF_ENCRYPTION_UNAVAILABLE_MESSAGE =
|
|
||||||
'Password protection is not available in this build (pdf-lib lacks encryption support).';
|
|
||||||
|
|
||||||
function parsePageRanges(rangeString, totalPages) {
|
function parsePageRanges(rangeString, totalPages) {
|
||||||
const pages = [];
|
const pages = [];
|
||||||
const ranges = rangeString.split(',').map((r) => r.trim());
|
const ranges = rangeString.split(',').map(r => r.trim());
|
||||||
|
|
||||||
for (const range of ranges) {
|
for (const range of ranges) {
|
||||||
if (range.includes('-')) {
|
if (range.includes('-')) {
|
||||||
const [start, end] = range.split('-').map((n) => parseInt(n.trim()));
|
const [start, end] = range.split('-').map(n => parseInt(n.trim()));
|
||||||
for (let i = start; i <= end && i <= totalPages; i++) {
|
for (let i = start; i <= end && i <= totalPages; i++) {
|
||||||
if (i > 0 && !pages.includes(i - 1)) {
|
if (i > 0 && !pages.includes(i - 1)) {
|
||||||
pages.push(i - 1);
|
pages.push(i - 1);
|
||||||
@@ -51,13 +27,11 @@ function parsePageRanges(rangeString, totalPages) {
|
|||||||
|
|
||||||
function hexToRgb(hex) {
|
function hexToRgb(hex) {
|
||||||
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
|
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
|
||||||
return result
|
return result ? {
|
||||||
? {
|
r: parseInt(result[1], 16) / 255,
|
||||||
r: parseInt(result[1], 16) / 255,
|
g: parseInt(result[2], 16) / 255,
|
||||||
g: parseInt(result[2], 16) / 255,
|
b: parseInt(result[3], 16) / 255
|
||||||
b: parseInt(result[3], 16) / 255,
|
} : { r: 0, g: 0, b: 0 };
|
||||||
}
|
|
||||||
: { r: 0, g: 0, b: 0 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pdfMerge(data) {
|
async function pdfMerge(data) {
|
||||||
@@ -68,7 +42,7 @@ async function pdfMerge(data) {
|
|||||||
const pdfBytes = fs.readFileSync(filePath);
|
const pdfBytes = fs.readFileSync(filePath);
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
const pdf = await PDFDocument.load(pdfBytes);
|
||||||
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
|
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
|
||||||
copiedPages.forEach((page) => mergedPdf.addPage(page));
|
copiedPages.forEach(page => mergedPdf.addPage(page));
|
||||||
}
|
}
|
||||||
|
|
||||||
const pdfBytes = await mergedPdf.save();
|
const pdfBytes = await mergedPdf.save();
|
||||||
@@ -89,13 +63,13 @@ async function pdfSplit(data) {
|
|||||||
const splits = [];
|
const splits = [];
|
||||||
|
|
||||||
if (data.splitMode === 'pages') {
|
if (data.splitMode === 'pages') {
|
||||||
const ranges = data.pageRanges.split(',').map((r) => r.trim());
|
const ranges = data.pageRanges.split(',').map(r => r.trim());
|
||||||
for (let i = 0; i < ranges.length; i++) {
|
for (let i = 0; i < ranges.length; i++) {
|
||||||
const range = ranges[i];
|
const range = ranges[i];
|
||||||
const pages = [];
|
const pages = [];
|
||||||
|
|
||||||
if (range.includes('-')) {
|
if (range.includes('-')) {
|
||||||
const [start, end] = range.split('-').map((n) => parseInt(n.trim()));
|
const [start, end] = range.split('-').map(n => parseInt(n.trim()));
|
||||||
for (let p = start; p <= end && p <= totalPages; p++) {
|
for (let p = start; p <= end && p <= totalPages; p++) {
|
||||||
pages.push(p - 1);
|
pages.push(p - 1);
|
||||||
}
|
}
|
||||||
@@ -112,9 +86,6 @@ async function pdfSplit(data) {
|
|||||||
}
|
}
|
||||||
} else if (data.splitMode === 'interval') {
|
} else if (data.splitMode === 'interval') {
|
||||||
const interval = data.interval;
|
const interval = data.interval;
|
||||||
if (!Number.isInteger(interval) || interval <= 0) {
|
|
||||||
return { success: false, message: 'Split interval must be a positive integer.' };
|
|
||||||
}
|
|
||||||
for (let i = 0; i < totalPages; i += interval) {
|
for (let i = 0; i < totalPages; i += interval) {
|
||||||
const pages = [];
|
const pages = [];
|
||||||
for (let j = i; j < i + interval && j < totalPages; j++) {
|
for (let j = i; j < i + interval && j < totalPages; j++) {
|
||||||
@@ -137,7 +108,7 @@ async function pdfSplit(data) {
|
|||||||
for (const split of splits) {
|
for (const split of splits) {
|
||||||
const newPdf = await PDFDocument.create();
|
const newPdf = await PDFDocument.create();
|
||||||
const copiedPages = await newPdf.copyPages(pdf, split.pages);
|
const copiedPages = await newPdf.copyPages(pdf, split.pages);
|
||||||
copiedPages.forEach((page) => newPdf.addPage(page));
|
copiedPages.forEach(page => newPdf.addPage(page));
|
||||||
|
|
||||||
const outputPath = path.join(data.outputFolder, `${baseName}_${split.name}.pdf`);
|
const outputPath = path.join(data.outputFolder, `${baseName}_${split.name}.pdf`);
|
||||||
const newPdfBytes = await newPdf.save();
|
const newPdfBytes = await newPdf.save();
|
||||||
@@ -158,18 +129,18 @@ async function pdfCompress(data) {
|
|||||||
const compressedPdfBytes = await pdf.save({
|
const compressedPdfBytes = await pdf.save({
|
||||||
useObjectStreams: true,
|
useObjectStreams: true,
|
||||||
addDefaultPage: false,
|
addDefaultPage: false,
|
||||||
objectsPerTick: 50,
|
objectsPerTick: 50
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(data.outputPath, compressedPdfBytes);
|
fs.writeFileSync(data.outputPath, compressedPdfBytes);
|
||||||
|
|
||||||
const originalSize = fs.statSync(data.inputPath).size;
|
const originalSize = fs.statSync(data.inputPath).size;
|
||||||
const compressedSize = fs.statSync(data.outputPath).size;
|
const compressedSize = fs.statSync(data.outputPath).size;
|
||||||
const savings = (((originalSize - compressedSize) / originalSize) * 100).toFixed(1);
|
const savings = ((originalSize - compressedSize) / originalSize * 100).toFixed(1);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `PDF compressed. Size reduced by ${savings}% (${(originalSize / 1024).toFixed(1)}KB → ${(compressedSize / 1024).toFixed(1)}KB)`,
|
message: `PDF compressed. Size reduced by ${savings}% (${(originalSize / 1024).toFixed(1)}KB → ${(compressedSize / 1024).toFixed(1)}KB)`
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
@@ -189,7 +160,7 @@ async function pdfRotate(data) {
|
|||||||
pagesToRotate = Array.from({ length: totalPages }, (_, i) => i);
|
pagesToRotate = Array.from({ length: totalPages }, (_, i) => i);
|
||||||
}
|
}
|
||||||
|
|
||||||
pagesToRotate.forEach((pageIndex) => {
|
pagesToRotate.forEach(pageIndex => {
|
||||||
const page = pdf.getPage(pageIndex);
|
const page = pdf.getPage(pageIndex);
|
||||||
page.setRotation(degrees(data.angle));
|
page.setRotation(degrees(data.angle));
|
||||||
});
|
});
|
||||||
@@ -199,7 +170,7 @@ async function pdfRotate(data) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Successfully rotated ${pagesToRotate.length} page(s) by ${data.angle}\u00B0`,
|
message: `Successfully rotated ${pagesToRotate.length} page(s) by ${data.angle}\u00B0`
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
@@ -214,18 +185,16 @@ async function pdfDeletePages(data) {
|
|||||||
|
|
||||||
const pagesToDelete = parsePageRanges(data.pages, totalPages);
|
const pagesToDelete = parsePageRanges(data.pages, totalPages);
|
||||||
|
|
||||||
pagesToDelete
|
pagesToDelete.sort((a, b) => b - a).forEach(pageIndex => {
|
||||||
.sort((a, b) => b - a)
|
pdf.removePage(pageIndex);
|
||||||
.forEach((pageIndex) => {
|
});
|
||||||
pdf.removePage(pageIndex);
|
|
||||||
});
|
|
||||||
|
|
||||||
const newPdfBytes = await pdf.save();
|
const newPdfBytes = await pdf.save();
|
||||||
fs.writeFileSync(data.outputPath, newPdfBytes);
|
fs.writeFileSync(data.outputPath, newPdfBytes);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Successfully deleted ${pagesToDelete.length} page(s). New PDF has ${totalPages - pagesToDelete.length} pages`,
|
message: `Successfully deleted ${pagesToDelete.length} page(s). New PDF has ${totalPages - pagesToDelete.length} pages`
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
@@ -238,7 +207,7 @@ async function pdfReorder(data) {
|
|||||||
const pdf = await PDFDocument.load(pdfBytes);
|
const pdf = await PDFDocument.load(pdfBytes);
|
||||||
const totalPages = pdf.getPageCount();
|
const totalPages = pdf.getPageCount();
|
||||||
|
|
||||||
const newOrder = data.newOrder.split(',').map((n) => parseInt(n.trim()) - 1);
|
const newOrder = data.newOrder.split(',').map(n => parseInt(n.trim()) - 1);
|
||||||
|
|
||||||
if (newOrder.length !== totalPages) {
|
if (newOrder.length !== totalPages) {
|
||||||
return { success: false, error: `New order must include all ${totalPages} pages` };
|
return { success: false, error: `New order must include all ${totalPages} pages` };
|
||||||
@@ -246,7 +215,7 @@ async function pdfReorder(data) {
|
|||||||
|
|
||||||
const newPdf = await PDFDocument.create();
|
const newPdf = await PDFDocument.create();
|
||||||
const copiedPages = await newPdf.copyPages(pdf, newOrder);
|
const copiedPages = await newPdf.copyPages(pdf, newOrder);
|
||||||
copiedPages.forEach((page) => newPdf.addPage(page));
|
copiedPages.forEach(page => newPdf.addPage(page));
|
||||||
|
|
||||||
const reorderedPdfBytes = await newPdf.save();
|
const reorderedPdfBytes = await newPdf.save();
|
||||||
fs.writeFileSync(data.outputPath, reorderedPdfBytes);
|
fs.writeFileSync(data.outputPath, reorderedPdfBytes);
|
||||||
@@ -257,30 +226,6 @@ async function pdfReorder(data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared corner/center coordinate mapping used by pdfWatermark and pdfAddPageNumbers.
|
|
||||||
function resolvePosition(position, width, height, margin = 50) {
|
|
||||||
switch (position) {
|
|
||||||
case 'center':
|
|
||||||
return { x: width / 2, y: height / 2 };
|
|
||||||
case 'diagonal':
|
|
||||||
return { x: width / 2, y: height / 2 };
|
|
||||||
case 'top-left':
|
|
||||||
return { x: margin, y: height - margin };
|
|
||||||
case 'top-center':
|
|
||||||
return { x: width / 2, y: height - margin };
|
|
||||||
case 'top-right':
|
|
||||||
return { x: width - margin, y: height - margin };
|
|
||||||
case 'bottom-left':
|
|
||||||
return { x: margin, y: margin };
|
|
||||||
case 'bottom-center':
|
|
||||||
return { x: width / 2, y: margin };
|
|
||||||
case 'bottom-right':
|
|
||||||
return { x: width - margin, y: margin };
|
|
||||||
default:
|
|
||||||
return { x: width / 2, y: height / 2 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfWatermark(data) {
|
async function pdfWatermark(data) {
|
||||||
try {
|
try {
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
const pdfBytes = fs.readFileSync(data.inputPath);
|
||||||
@@ -301,8 +246,46 @@ async function pdfWatermark(data) {
|
|||||||
const page = pdf.getPage(pageIndex);
|
const page = pdf.getPage(pageIndex);
|
||||||
const { width, height } = page.getSize();
|
const { width, height } = page.getSize();
|
||||||
|
|
||||||
const { x, y } = resolvePosition(data.position, width, height, 50);
|
let x, y, rotation = 0;
|
||||||
const rotation = data.position === 'diagonal' ? 45 : 0;
|
|
||||||
|
switch (data.position) {
|
||||||
|
case 'center':
|
||||||
|
x = width / 2;
|
||||||
|
y = height / 2;
|
||||||
|
break;
|
||||||
|
case 'diagonal':
|
||||||
|
x = width / 2;
|
||||||
|
y = height / 2;
|
||||||
|
rotation = 45;
|
||||||
|
break;
|
||||||
|
case 'top-left':
|
||||||
|
x = 50;
|
||||||
|
y = height - 50;
|
||||||
|
break;
|
||||||
|
case 'top-center':
|
||||||
|
x = width / 2;
|
||||||
|
y = height - 50;
|
||||||
|
break;
|
||||||
|
case 'top-right':
|
||||||
|
x = width - 50;
|
||||||
|
y = height - 50;
|
||||||
|
break;
|
||||||
|
case 'bottom-left':
|
||||||
|
x = 50;
|
||||||
|
y = 50;
|
||||||
|
break;
|
||||||
|
case 'bottom-center':
|
||||||
|
x = width / 2;
|
||||||
|
y = 50;
|
||||||
|
break;
|
||||||
|
case 'bottom-right':
|
||||||
|
x = width - 50;
|
||||||
|
y = 50;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
x = width / 2;
|
||||||
|
y = height / 2;
|
||||||
|
}
|
||||||
|
|
||||||
page.drawText(data.text, {
|
page.drawText(data.text, {
|
||||||
x,
|
x,
|
||||||
@@ -311,7 +294,7 @@ async function pdfWatermark(data) {
|
|||||||
font,
|
font,
|
||||||
color: rgb(color.r, color.g, color.b),
|
color: rgb(color.r, color.g, color.b),
|
||||||
opacity: data.opacity,
|
opacity: data.opacity,
|
||||||
rotate: degrees(rotation),
|
rotate: degrees(rotation)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,7 +303,7 @@ async function pdfWatermark(data) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Successfully added watermark to ${pagesToWatermark.length} page(s)`,
|
message: `Successfully added watermark to ${pagesToWatermark.length} page(s)`
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
@@ -328,9 +311,6 @@ async function pdfWatermark(data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function pdfEncrypt(data) {
|
async function pdfEncrypt(data) {
|
||||||
if (!(await pdfEncryptionSupported)) {
|
|
||||||
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
const pdfBytes = fs.readFileSync(data.inputPath);
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
const pdf = await PDFDocument.load(pdfBytes);
|
||||||
@@ -345,8 +325,8 @@ async function pdfEncrypt(data) {
|
|||||||
annotating: data.permissions.annotating,
|
annotating: data.permissions.annotating,
|
||||||
fillingForms: data.permissions.fillingForms,
|
fillingForms: data.permissions.fillingForms,
|
||||||
contentAccessibility: data.permissions.contentAccessibility,
|
contentAccessibility: data.permissions.contentAccessibility,
|
||||||
documentAssembly: data.permissions.documentAssembly,
|
documentAssembly: data.permissions.documentAssembly
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(data.outputPath, encryptedPdfBytes);
|
fs.writeFileSync(data.outputPath, encryptedPdfBytes);
|
||||||
@@ -356,8 +336,7 @@ async function pdfEncrypt(data) {
|
|||||||
if (error.message.includes('encrypt') || error.message.includes('password')) {
|
if (error.message.includes('encrypt') || error.message.includes('password')) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error:
|
error: 'PDF encryption requires pdf-lib with encryption support. This feature may not be available in the current version.'
|
||||||
'PDF encryption requires pdf-lib with encryption support. This feature may not be available in the current version.',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
@@ -365,9 +344,6 @@ async function pdfEncrypt(data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function pdfDecrypt(data) {
|
async function pdfDecrypt(data) {
|
||||||
if (!(await pdfEncryptionSupported)) {
|
|
||||||
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
const pdfBytes = fs.readFileSync(data.inputPath);
|
||||||
const pdf = await PDFDocument.load(pdfBytes, { password: data.password });
|
const pdf = await PDFDocument.load(pdfBytes, { password: data.password });
|
||||||
@@ -385,9 +361,6 @@ async function pdfDecrypt(data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function pdfSetPermissions(data) {
|
async function pdfSetPermissions(data) {
|
||||||
if (!(await pdfEncryptionSupported)) {
|
|
||||||
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
const pdfBytes = fs.readFileSync(data.inputPath);
|
||||||
const loadOptions = data.currentPassword ? { password: data.currentPassword } : {};
|
const loadOptions = data.currentPassword ? { password: data.currentPassword } : {};
|
||||||
@@ -402,8 +375,8 @@ async function pdfSetPermissions(data) {
|
|||||||
annotating: data.permissions.annotating,
|
annotating: data.permissions.annotating,
|
||||||
fillingForms: data.permissions.fillingForms,
|
fillingForms: data.permissions.fillingForms,
|
||||||
contentAccessibility: data.permissions.contentAccessibility,
|
contentAccessibility: data.permissions.contentAccessibility,
|
||||||
documentAssembly: data.permissions.documentAssembly,
|
documentAssembly: data.permissions.documentAssembly
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(data.outputPath, newPdfBytes);
|
fs.writeFileSync(data.outputPath, newPdfBytes);
|
||||||
@@ -413,318 +386,26 @@ async function pdfSetPermissions(data) {
|
|||||||
if (error.message.includes('encrypt') || error.message.includes('permission')) {
|
if (error.message.includes('encrypt') || error.message.includes('permission')) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error:
|
error: 'PDF permissions require pdf-lib with encryption support. This feature may not be available in the current version.'
|
||||||
'PDF permissions require pdf-lib with encryption support. This feature may not be available in the current version.',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pdf-lib has no text-extraction API, so this loads pdfjs-dist's Node-friendly
|
|
||||||
// "legacy" build (the standard build assumes DOM globals like DOMMatrix).
|
|
||||||
// pdfjs-dist v5.x ships ESM-only, so it must be loaded via dynamic import()
|
|
||||||
// even from this CommonJS module.
|
|
||||||
async function loadPdfjs() {
|
|
||||||
return import('pdfjs-dist/legacy/build/pdf.mjs');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Points pdfjs-dist at its bundled standard font metrics so it doesn't warn
|
|
||||||
// (and degrade text-extraction fidelity) when a PDF uses a standard font.
|
|
||||||
function getStandardFontDataUrl() {
|
|
||||||
return (
|
|
||||||
path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts') + path.sep
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfExtractText(data) {
|
|
||||||
try {
|
|
||||||
const pdfjsLib = await loadPdfjs();
|
|
||||||
const fileData = new Uint8Array(fs.readFileSync(data.inputPath));
|
|
||||||
const pdf = await pdfjsLib.getDocument({
|
|
||||||
data: fileData,
|
|
||||||
standardFontDataUrl: getStandardFontDataUrl(),
|
|
||||||
}).promise;
|
|
||||||
|
|
||||||
let text = '';
|
|
||||||
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
|
|
||||||
const page = await pdf.getPage(pageNum);
|
|
||||||
const content = await page.getTextContent();
|
|
||||||
const pageText = content.items.map((item) => item.str).join(' ');
|
|
||||||
text += pageText + '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
const trimmedText = text.trim();
|
|
||||||
const result = { success: true, text: trimmedText };
|
|
||||||
|
|
||||||
// outputPath is optional: when provided (e.g. from the PDF editor UI),
|
|
||||||
// also save the extracted text to disk and report where it went.
|
|
||||||
if (data.outputPath) {
|
|
||||||
fs.writeFileSync(data.outputPath, trimmedText, 'utf8');
|
|
||||||
result.message = `Successfully extracted text to ${data.outputPath}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfAddPageNumbers(data) {
|
|
||||||
try {
|
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
|
||||||
const totalPages = pdf.getPageCount();
|
|
||||||
|
|
||||||
const font = await pdf.embedFont(StandardFonts.Helvetica);
|
|
||||||
const position = data.position || 'bottom-center';
|
|
||||||
const fontSize = data.fontSize || 12;
|
|
||||||
const startNumber = data.startNumber && data.startNumber > 0 ? data.startNumber : 1;
|
|
||||||
|
|
||||||
for (let i = 0; i < totalPages; i++) {
|
|
||||||
const page = pdf.getPage(i);
|
|
||||||
const { width, height } = page.getSize();
|
|
||||||
const { x, y } = resolvePosition(position, width, height, 30);
|
|
||||||
|
|
||||||
const label = String(startNumber + i);
|
|
||||||
const textWidth = font.widthOfTextAtSize(label, fontSize);
|
|
||||||
|
|
||||||
let drawX = x;
|
|
||||||
if (position.includes('center')) {
|
|
||||||
drawX = x - textWidth / 2;
|
|
||||||
} else if (position.includes('right')) {
|
|
||||||
drawX = x - textWidth;
|
|
||||||
}
|
|
||||||
|
|
||||||
page.drawText(label, {
|
|
||||||
x: drawX,
|
|
||||||
y,
|
|
||||||
size: fontSize,
|
|
||||||
font,
|
|
||||||
color: rgb(0, 0, 0),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const newPdfBytes = await pdf.save();
|
|
||||||
fs.writeFileSync(data.outputPath, newPdfBytes);
|
|
||||||
|
|
||||||
return { success: true, message: `Successfully added page numbers to ${totalPages} page(s)` };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfCrop(data) {
|
|
||||||
try {
|
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
|
||||||
const totalPages = pdf.getPageCount();
|
|
||||||
|
|
||||||
const margins = data.margins || {};
|
|
||||||
const top = margins.top || 0;
|
|
||||||
const bottom = margins.bottom || 0;
|
|
||||||
const left = margins.left || 0;
|
|
||||||
const right = margins.right || 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < totalPages; i++) {
|
|
||||||
const page = pdf.getPage(i);
|
|
||||||
const mediaBox = page.getMediaBox();
|
|
||||||
const newWidth = mediaBox.width - left - right;
|
|
||||||
const newHeight = mediaBox.height - top - bottom;
|
|
||||||
|
|
||||||
if (newWidth <= 0 || newHeight <= 0) {
|
|
||||||
return { success: false, error: `Crop margins are too large for page ${i + 1}` };
|
|
||||||
}
|
|
||||||
|
|
||||||
page.setCropBox(mediaBox.x + left, mediaBox.y + bottom, newWidth, newHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
const croppedPdfBytes = await pdf.save();
|
|
||||||
fs.writeFileSync(data.outputPath, croppedPdfBytes);
|
|
||||||
|
|
||||||
return { success: true, message: `Successfully cropped ${totalPages} page(s)` };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfExtractImages(data) {
|
|
||||||
try {
|
|
||||||
const pdfjsLib = await loadPdfjs();
|
|
||||||
// sharp is only needed here; require lazily to match the module's existing
|
|
||||||
// pattern of not pulling heavy optional deps in until an operation runs.
|
|
||||||
const sharp = require('sharp');
|
|
||||||
|
|
||||||
const fileData = new Uint8Array(fs.readFileSync(data.inputPath));
|
|
||||||
const pdf = await pdfjsLib.getDocument({
|
|
||||||
data: fileData,
|
|
||||||
standardFontDataUrl: getStandardFontDataUrl(),
|
|
||||||
}).promise;
|
|
||||||
|
|
||||||
if (!fs.existsSync(data.outputDir)) {
|
|
||||||
fs.mkdirSync(data.outputDir, { recursive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseName = path.basename(data.inputPath, path.extname(data.inputPath));
|
|
||||||
const files = [];
|
|
||||||
let imageIndex = 0;
|
|
||||||
|
|
||||||
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
|
|
||||||
const page = await pdf.getPage(pageNum);
|
|
||||||
const opList = await page.getOperatorList();
|
|
||||||
|
|
||||||
for (let i = 0; i < opList.fnArray.length; i++) {
|
|
||||||
if (opList.fnArray[i] !== pdfjsLib.OPS.paintImageXObject) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const objId = opList.argsArray[i][0];
|
|
||||||
|
|
||||||
try {
|
|
||||||
const imgObj = await new Promise((resolve) => page.objs.get(objId, resolve));
|
|
||||||
|
|
||||||
if (!imgObj || !imgObj.data || !imgObj.width || !imgObj.height) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const channels =
|
|
||||||
imgObj.kind === pdfjsLib.ImageKind.RGBA_32BPP
|
|
||||||
? 4
|
|
||||||
: imgObj.kind === pdfjsLib.ImageKind.GRAYSCALE_1BPP
|
|
||||||
? 1
|
|
||||||
: 3;
|
|
||||||
|
|
||||||
imageIndex++;
|
|
||||||
const outputFile = path.join(
|
|
||||||
data.outputDir,
|
|
||||||
`${baseName}_page${pageNum}_img${imageIndex}.png`
|
|
||||||
);
|
|
||||||
|
|
||||||
await sharp(Buffer.from(imgObj.data), {
|
|
||||||
raw: { width: imgObj.width, height: imgObj.height, channels },
|
|
||||||
})
|
|
||||||
.png()
|
|
||||||
.toFile(outputFile);
|
|
||||||
|
|
||||||
files.push(outputFile);
|
|
||||||
} catch {
|
|
||||||
// Skip images pdfjs/sharp can't decode (e.g. unsupported color spaces).
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
count: files.length,
|
|
||||||
files,
|
|
||||||
message: `Successfully extracted ${files.length} image(s)`,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfGetFormFields(data) {
|
|
||||||
try {
|
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
|
||||||
const form = pdf.getForm();
|
|
||||||
|
|
||||||
const fields = form.getFields().map((field) => {
|
|
||||||
let value;
|
|
||||||
try {
|
|
||||||
if (typeof field.getText === 'function') {
|
|
||||||
value = field.getText();
|
|
||||||
} else if (typeof field.isChecked === 'function') {
|
|
||||||
value = field.isChecked();
|
|
||||||
} else if (typeof field.getSelected === 'function') {
|
|
||||||
value = field.getSelected();
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Some field types throw when read in an unexpected state; leave value undefined.
|
|
||||||
value = undefined;
|
|
||||||
}
|
|
||||||
return { name: field.getName(), type: field.constructor.name, value };
|
|
||||||
});
|
|
||||||
|
|
||||||
return { success: true, fields };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pdfFillForm(data) {
|
|
||||||
try {
|
|
||||||
const pdfBytes = fs.readFileSync(data.inputPath);
|
|
||||||
const pdf = await PDFDocument.load(pdfBytes);
|
|
||||||
const form = pdf.getForm();
|
|
||||||
|
|
||||||
const values = data.values || {};
|
|
||||||
let filledCount = 0;
|
|
||||||
|
|
||||||
for (const [name, value] of Object.entries(values)) {
|
|
||||||
try {
|
|
||||||
const field = form.getTextField(name);
|
|
||||||
field.setText(value !== null && value !== undefined ? String(value) : '');
|
|
||||||
filledCount++;
|
|
||||||
} catch (fieldError) {
|
|
||||||
// Batch-of-independent-fields: a field that doesn't exist or isn't a text
|
|
||||||
// field shouldn't fail the whole fill — skip it and keep going (same
|
|
||||||
// partial-success precedent as pdfExtractImages).
|
|
||||||
console.warn(`pdfFillForm: skipping field "${name}": ${fieldError.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.flatten) {
|
|
||||||
form.flatten();
|
|
||||||
}
|
|
||||||
|
|
||||||
const filledPdfBytes = await pdf.save();
|
|
||||||
fs.writeFileSync(data.outputPath, filledPdfBytes);
|
|
||||||
|
|
||||||
return { success: true, message: `Successfully filled ${filledCount} form field(s)` };
|
|
||||||
} catch (error) {
|
|
||||||
return { success: false, error: error.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function executeOperation(operation, data) {
|
function executeOperation(operation, data) {
|
||||||
switch (operation) {
|
switch (operation) {
|
||||||
case 'merge':
|
case 'merge': return pdfMerge(data);
|
||||||
return pdfMerge(data);
|
case 'split': return pdfSplit(data);
|
||||||
case 'split':
|
case 'compress': return pdfCompress(data);
|
||||||
return pdfSplit(data);
|
case 'rotate': return pdfRotate(data);
|
||||||
case 'compress':
|
case 'delete': return pdfDeletePages(data);
|
||||||
return pdfCompress(data);
|
case 'reorder': return pdfReorder(data);
|
||||||
case 'rotate':
|
case 'watermark': return pdfWatermark(data);
|
||||||
return pdfRotate(data);
|
case 'encrypt': return pdfEncrypt(data);
|
||||||
case 'delete':
|
case 'decrypt': return pdfDecrypt(data);
|
||||||
return pdfDeletePages(data);
|
case 'permissions': return pdfSetPermissions(data);
|
||||||
case 'reorder':
|
default: return Promise.resolve({ success: false, error: `Unknown operation: ${operation}` });
|
||||||
return pdfReorder(data);
|
|
||||||
case 'watermark':
|
|
||||||
return pdfWatermark(data);
|
|
||||||
case 'encrypt':
|
|
||||||
return pdfEncrypt(data);
|
|
||||||
case 'decrypt':
|
|
||||||
return pdfDecrypt(data);
|
|
||||||
case 'permissions':
|
|
||||||
return pdfSetPermissions(data);
|
|
||||||
case 'extractText':
|
|
||||||
return pdfExtractText(data);
|
|
||||||
case 'pageNumbers':
|
|
||||||
return pdfAddPageNumbers(data);
|
|
||||||
case 'crop':
|
|
||||||
return pdfCrop(data);
|
|
||||||
case 'extractImages':
|
|
||||||
return pdfExtractImages(data);
|
|
||||||
case 'formFields':
|
|
||||||
return pdfGetFormFields(data);
|
|
||||||
case 'fillForm':
|
|
||||||
return pdfFillForm(data);
|
|
||||||
default:
|
|
||||||
return Promise.resolve({ success: false, error: `Unknown operation: ${operation}` });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -737,8 +418,6 @@ async function getPageCount(filePath) {
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
parsePageRanges,
|
parsePageRanges,
|
||||||
hexToRgb,
|
hexToRgb,
|
||||||
pdfEncryptionSupported,
|
|
||||||
PDF_ENCRYPTION_UNAVAILABLE_MESSAGE,
|
|
||||||
pdfMerge,
|
pdfMerge,
|
||||||
pdfSplit,
|
pdfSplit,
|
||||||
pdfCompress,
|
pdfCompress,
|
||||||
@@ -749,12 +428,6 @@ module.exports = {
|
|||||||
pdfEncrypt,
|
pdfEncrypt,
|
||||||
pdfDecrypt,
|
pdfDecrypt,
|
||||||
pdfSetPermissions,
|
pdfSetPermissions,
|
||||||
pdfExtractText,
|
|
||||||
pdfAddPageNumbers,
|
|
||||||
pdfCrop,
|
|
||||||
pdfExtractImages,
|
|
||||||
pdfGetFormFields,
|
|
||||||
pdfFillForm,
|
|
||||||
executeOperation,
|
executeOperation,
|
||||||
getPageCount,
|
getPageCount
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,135 +0,0 @@
|
|||||||
/**
|
|
||||||
* Pure builders for Pandoc execFile argument arrays.
|
|
||||||
*
|
|
||||||
* Every Pandoc invocation in the main process must call
|
|
||||||
* execFile(pandocPath, args) with an argument array built here or with plain
|
|
||||||
* Array.push calls — never a command string that is later re-tokenized.
|
|
||||||
* Values that come from the user (file paths, template names, metadata values)
|
|
||||||
* are pushed verbatim as single argv elements, so a crafted value such as
|
|
||||||
* `/tmp/x.bib" --lua-filter=/tmp/evil.lua` can never break out of its argument
|
|
||||||
* and inject additional Pandoc flags (security finding SEC-1).
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats exported through a plain `-t <target>` conversion. The export dialog
|
|
||||||
* replaces the whole command for these formats (dialog options like template or
|
|
||||||
* metadata are not applied) — this map preserves that pre-existing behavior.
|
|
||||||
*/
|
|
||||||
const SIMPLE_TARGET_FORMATS = {
|
|
||||||
json: 'json',
|
|
||||||
beamer: 'beamer',
|
|
||||||
confluence: 'jira',
|
|
||||||
jira: 'jira',
|
|
||||||
asciidoc: 'asciidoc',
|
|
||||||
rst: 'rst',
|
|
||||||
mediawiki: 'mediawiki',
|
|
||||||
org: 'org',
|
|
||||||
textile: 'textile',
|
|
||||||
man: 'man',
|
|
||||||
ipynb: 'ipynb',
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Append the export-dialog options shared by the export, batch-conversion and
|
|
||||||
* fallback paths. Each value lands in argv exactly once, unquoted and
|
|
||||||
* unescaped — execFile passes array elements as literal arguments.
|
|
||||||
* @param {string[]} args - Argument array to append to (mutated)
|
|
||||||
* @param {Object} options - Export options ({ template, metadata, variables,
|
|
||||||
* toc, tocDepth, numberSections, citeproc, bibliography, csl })
|
|
||||||
*/
|
|
||||||
function appendCommonOptions(args, options) {
|
|
||||||
if (!options) return;
|
|
||||||
|
|
||||||
if (options.template && options.template !== 'default') {
|
|
||||||
args.push(`--template=${options.template}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.metadata) {
|
|
||||||
for (const [key, value] of Object.entries(options.metadata)) {
|
|
||||||
if (value.trim()) {
|
|
||||||
args.push('-M', `${key}=${value}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.variables) {
|
|
||||||
for (const [key, value] of Object.entries(options.variables)) {
|
|
||||||
if (value.trim()) {
|
|
||||||
args.push('-V', `${key}=${value}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.toc) args.push('--toc');
|
|
||||||
if (options.tocDepth) args.push(`--toc-depth=${options.tocDepth}`);
|
|
||||||
if (options.numberSections) args.push('--number-sections');
|
|
||||||
if (options.citeproc) args.push('--citeproc');
|
|
||||||
if (options.bibliography) args.push(`--bibliography=${options.bibliography}`);
|
|
||||||
if (options.csl) args.push(`--csl=${options.csl}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Append the shared prefix of every PDF invocation: the pdf engine flag and,
|
|
||||||
* when set, the page geometry variable.
|
|
||||||
* @param {string[]} args - Argument array to append to (mutated)
|
|
||||||
* @param {Object} params
|
|
||||||
* @param {string} [params.pdfEngine] - Falls back to xelatex when omitted
|
|
||||||
* @param {string} [params.geometry] - LaTeX geometry string (e.g. margin=1in)
|
|
||||||
*/
|
|
||||||
function appendPdfEngineOptions(args, { pdfEngine, geometry } = {}) {
|
|
||||||
args.push(`--pdf-engine=${pdfEngine || 'xelatex'}`);
|
|
||||||
if (geometry) args.push('-V', `geometry:${geometry}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Append the PowerPoint footer variable (used when header/footer is enabled).
|
|
||||||
* @param {string[]} args - Argument array to append to (mutated)
|
|
||||||
* @param {string} footerText - Processed footer text
|
|
||||||
*/
|
|
||||||
function appendFooterVariable(args, footerText) {
|
|
||||||
if (footerText) args.push('--variable', `footer=${footerText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the base argument array for the export dialog and batch conversion:
|
|
||||||
* input, -o output, the shared export options, and the `-t docx` tail for
|
|
||||||
* Word exports. Format-specific extras (PDF engine flags, EPUB fonts, HTML
|
|
||||||
* css, reveal.js themes) are appended by the call site.
|
|
||||||
* @param {Object} params
|
|
||||||
* @param {string} params.inputFile - Path passed to pandoc verbatim
|
|
||||||
* @param {string} params.outputFile - Path passed to pandoc verbatim
|
|
||||||
* @param {string} [params.format] - Export format name
|
|
||||||
* @param {Object} [params.options] - Export dialog options
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
function buildPandocArgs({ inputFile, outputFile, format, options = {} }) {
|
|
||||||
const args = [inputFile, '-o', outputFile];
|
|
||||||
appendCommonOptions(args, options);
|
|
||||||
if (format === 'docx') {
|
|
||||||
args.push('-t', 'docx');
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args for the simple `-t <target>` formats (see SIMPLE_TARGET_FORMATS).
|
|
||||||
* @param {string} inputFile - Input path
|
|
||||||
* @param {string} outputFile - Output path
|
|
||||||
* @param {string} format - Export format name
|
|
||||||
* @returns {string[]|null} Argument array, or null when format is not one of
|
|
||||||
* the simple target formats
|
|
||||||
*/
|
|
||||||
function buildSimpleTargetArgs(inputFile, outputFile, format) {
|
|
||||||
const target = SIMPLE_TARGET_FORMATS[format];
|
|
||||||
if (!target) return null;
|
|
||||||
return [inputFile, '-t', target, '-o', outputFile];
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
SIMPLE_TARGET_FORMATS,
|
|
||||||
appendCommonOptions,
|
|
||||||
appendPdfEngineOptions,
|
|
||||||
appendFooterVariable,
|
|
||||||
buildPandocArgs,
|
|
||||||
buildSimpleTargetArgs,
|
|
||||||
};
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
// fontspec accepts forward-slash paths on all platforms (TeX normalizes).
|
|
||||||
// Normalize Windows backslashes so we can reliably build Path/filename.
|
|
||||||
function toPosix(p) {
|
|
||||||
return String(p).replace(/\\/g, '/');
|
|
||||||
}
|
|
||||||
|
|
||||||
function escape(s) {
|
|
||||||
// fontspec values: braces are the only TeX-significant chars we might emit
|
|
||||||
// from a basename. Backslashes are converted to '/' upstream by toPosix().
|
|
||||||
return String(s).replace(/[{}]/g, '\\$&');
|
|
||||||
}
|
|
||||||
|
|
||||||
function dirOf(p) {
|
|
||||||
return toPosix(p).replace(/\/[^/]+$/, '') + '/';
|
|
||||||
}
|
|
||||||
|
|
||||||
function baseName(p) {
|
|
||||||
return toPosix(p).split('/').pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strip a weight-style suffix from a TTF filename to get the family prefix
|
|
||||||
// (e.g. JetBrainsMono-Regular.ttf -> JetBrainsMono). Used as the `\setmonofont`
|
|
||||||
// argument so `*-Regular` / `*-Bold` globs resolve to the right files.
|
|
||||||
function weightPrefix(p) {
|
|
||||||
return baseName(p).replace(/-(Regular|Bold|Light|Medium|SemiBold|Italic)\.ttf$/i, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
function build({ fontTtfPath, boldTtfPath, ligatures }) {
|
|
||||||
if (!fontTtfPath) {
|
|
||||||
return '% Monospace font path unavailable; TeX will use its default monospace.\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
// `boldTtfPath` is accepted for API symmetry with future formats; the glob
|
|
||||||
// below resolves the bold file from the regular file's family prefix.
|
|
||||||
void boldTtfPath;
|
|
||||||
|
|
||||||
const ligValue = ligatures ? 'Ligatures=TeX' : 'Ligatures=NoCommon';
|
|
||||||
const prefix = escape(weightPrefix(fontTtfPath));
|
|
||||||
|
|
||||||
return `\\usepackage{fontspec}
|
|
||||||
\\setmonofont[Path=${escape(dirOf(fontTtfPath))},Extension=.ttf,UprightFont=*-Regular,BoldFont=*-Bold,${ligValue}]{${prefix}}
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { build };
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
/**
|
|
||||||
* Video Operations Module
|
|
||||||
*
|
|
||||||
* Handles video manipulation via `ffmpeg`: format conversion, compression, trim,
|
|
||||||
* frame extraction, and GIF conversion. Because ffmpeg is an external binary, this
|
|
||||||
* module is split into pure/testable argument-builder functions and a single
|
|
||||||
* `executeOperation` that is the only piece which actually spawns ffmpeg — the
|
|
||||||
* ffmpeg binary path and the `execFile` implementation are both injected so tests
|
|
||||||
* can replace them with fakes, without invoking a real binary.
|
|
||||||
*
|
|
||||||
* @module VideoOperations
|
|
||||||
*/
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const { execFile } = require('child_process');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args for a straight format conversion. ffmpeg infers the output format
|
|
||||||
* from outputPath's extension.
|
|
||||||
*/
|
|
||||||
function buildConvertArgs({ inputPath, outputPath }) {
|
|
||||||
return ['-i', inputPath, '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to re-encode inputPath with libx264 at the given CRF (Constant Rate
|
|
||||||
* Factor). Lower CRF = higher quality/larger file, per libx264 convention. crf
|
|
||||||
* must be an integer in [0, 51].
|
|
||||||
*/
|
|
||||||
function buildCompressArgs({ inputPath, outputPath, crf = 28 }) {
|
|
||||||
if (!Number.isInteger(crf) || crf < 0 || crf > 51) {
|
|
||||||
throw new Error('Invalid crf: must be an integer between 0 and 51');
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['-i', inputPath, '-vcodec', 'libx264', '-crf', String(crf), '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to trim inputPath to [startTime, startTime + duration) seconds.
|
|
||||||
* startTime/duration must be finite, non-negative numbers — they become argv
|
|
||||||
* elements passed straight to execFile with no shell involved, so there's no
|
|
||||||
* injection risk, but malformed values should still fail fast rather than reach
|
|
||||||
* ffmpeg with garbage.
|
|
||||||
*/
|
|
||||||
function buildTrimArgs({ inputPath, outputPath, startTime, duration }) {
|
|
||||||
const isValid = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
|
|
||||||
|
|
||||||
if (!isValid(startTime) || !isValid(duration)) {
|
|
||||||
throw new Error('Invalid trim range');
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to extract frames from inputPath at fps frames-per-second, written
|
|
||||||
* as sequentially numbered PNGs into outputDir. fps must be a positive finite
|
|
||||||
* number.
|
|
||||||
*/
|
|
||||||
function buildFramesArgs({ inputPath, outputDir, fps = 1 }) {
|
|
||||||
if (typeof fps !== 'number' || !Number.isFinite(fps) || fps <= 0) {
|
|
||||||
throw new Error('Invalid fps: must be a positive finite number');
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['-i', inputPath, '-vf', `fps=${fps}`, path.join(outputDir, 'frame-%04d.png')];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build args to convert inputPath to an animated GIF at the given fps and width
|
|
||||||
* (height scales automatically via -1), using the lanczos scaling filter.
|
|
||||||
*/
|
|
||||||
function buildGifArgs({ inputPath, outputPath, fps = 10, width = 480 }) {
|
|
||||||
return ['-i', inputPath, '-vf', `fps=${fps},scale=${width}:-1:flags=lanczos`, '-y', outputPath];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run ffmpeg with the given args via the injected execFileFn, wrapped in a Promise.
|
|
||||||
*/
|
|
||||||
function runFfmpeg(ffmpegPath, args, execFileFn) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
execFileFn(ffmpegPath, args, { maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
||||||
if (error) {
|
|
||||||
reject(new Error(stderr || error.message));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeOperation(operation, data, { ffmpegPath, execFileFn } = {}) {
|
|
||||||
const resolvedFfmpegPath = ffmpegPath || 'ffmpeg';
|
|
||||||
const resolvedExecFileFn = execFileFn || execFile;
|
|
||||||
|
|
||||||
switch (operation) {
|
|
||||||
case 'convert': {
|
|
||||||
const { inputPath, outputPath } = data || {};
|
|
||||||
const args = buildConvertArgs({ inputPath, outputPath });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'compress': {
|
|
||||||
const { inputPath, outputPath, crf } = data || {};
|
|
||||||
const args = buildCompressArgs({ inputPath, outputPath, crf });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'trim': {
|
|
||||||
const { inputPath, outputPath, startTime, duration } = data || {};
|
|
||||||
const args = buildTrimArgs({ inputPath, outputPath, startTime, duration });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'frames': {
|
|
||||||
const { inputPath, outputDir, fps } = data || {};
|
|
||||||
const args = buildFramesArgs({ inputPath, outputDir, fps });
|
|
||||||
fs.mkdirSync(outputDir, { recursive: true });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputDir };
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'gif': {
|
|
||||||
const { inputPath, outputPath, fps, width } = data || {};
|
|
||||||
const args = buildGifArgs({ inputPath, outputPath, fps, width });
|
|
||||||
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
|
|
||||||
return { success: true, outputPath };
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Unknown operation: ${operation}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
executeOperation,
|
|
||||||
buildConvertArgs,
|
|
||||||
buildCompressArgs,
|
|
||||||
buildTrimArgs,
|
|
||||||
buildFramesArgs,
|
|
||||||
buildGifArgs,
|
|
||||||
};
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
/**
|
|
||||||
* collectFilesByExtension
|
|
||||||
*
|
|
||||||
* Recursively (optionally) collects files under a directory whose extension matches
|
|
||||||
* one of a given set of extensions. Generalizes the `collectFiles()` closure defined
|
|
||||||
* inside `ipcMain.on('universal-convert-batch', ...)` in main.js (which matches a
|
|
||||||
* single `.${fromFormat}` extension) to match against an arbitrary extension list —
|
|
||||||
* used by the batch-image/audio/video-operation handlers, which need to match several
|
|
||||||
* possible input extensions per media kind (e.g. .jpg/.jpeg/.png/... for images).
|
|
||||||
*
|
|
||||||
* Pulled out as its own module (rather than an inline closure like the original) so it
|
|
||||||
* can be unit tested without Electron.
|
|
||||||
*
|
|
||||||
* @module collectFilesByExtension
|
|
||||||
*/
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} dir - Directory to scan.
|
|
||||||
* @param {string[]} extensions - Extensions to match, each including the leading dot
|
|
||||||
* (e.g. ['.jpg', '.png']). Matching is case-insensitive.
|
|
||||||
* @param {boolean} [includeSubfolders=true] - Recurse into subdirectories.
|
|
||||||
* @returns {string[]} Absolute paths of matching files, in directory-walk order.
|
|
||||||
*/
|
|
||||||
function collectFilesByExtension(dir, extensions, includeSubfolders = true) {
|
|
||||||
const normalizedExts = (extensions || []).map((ext) => ext.toLowerCase());
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
function walk(currentDir) {
|
|
||||||
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
||||||
for (const entry of entries) {
|
|
||||||
const fullPath = path.join(currentDir, entry.name);
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
if (includeSubfolders) {
|
|
||||||
walk(fullPath);
|
|
||||||
}
|
|
||||||
} else if (entry.isFile()) {
|
|
||||||
const ext = path.extname(entry.name).toLowerCase();
|
|
||||||
if (normalizedExts.includes(ext)) {
|
|
||||||
results.push(fullPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
walk(dir);
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { collectFilesByExtension };
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const FAMILY_BY_KEY = {
|
|
||||||
'jetbrains-mono': 'JetBrains Mono',
|
|
||||||
'fira-code': 'Fira Code',
|
|
||||||
};
|
|
||||||
|
|
||||||
function getDefaults() {
|
|
||||||
return Object.freeze({ monospaceFont: 'jetbrains-mono', monospaceLigatures: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
function getActiveMonoFont(settings) {
|
|
||||||
const key = settings && settings.monospaceFont;
|
|
||||||
return FAMILY_BY_KEY[key] || 'JetBrains Mono';
|
|
||||||
}
|
|
||||||
|
|
||||||
function isLigaturesEnabled(settings) {
|
|
||||||
return Boolean(settings && settings.monospaceLigatures === true);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getDefaults, getActiveMonoFont, isLigaturesEnabled, FAMILY_BY_KEY };
|
|
||||||
@@ -5,7 +5,9 @@
|
|||||||
"description": "Demonstrates the plugin system. Safe to delete.",
|
"description": "Demonstrates the plugin system. Safe to delete.",
|
||||||
"icon": "puzzle",
|
"icon": "puzzle",
|
||||||
"extensionPoints": {
|
"extensionPoints": {
|
||||||
"commands": [{ "id": "hello", "label": "Sample: Hello World", "shortcut": "" }]
|
"commands": [
|
||||||
|
{ "id": "hello", "label": "Sample: Hello World", "shortcut": "" }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"settings": []
|
"settings": []
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ class WritingStudioPlugin extends PluginAPI {
|
|||||||
this.context = context;
|
this.context = context;
|
||||||
|
|
||||||
this.sprintEngine = new SprintEngine({
|
this.sprintEngine = new SprintEngine({
|
||||||
onEvent: (name, data) => context.events.emit(name, data),
|
onEvent: (name, data) => context.events.emit(name, data)
|
||||||
});
|
});
|
||||||
this.goalTracker = new GoalTracker(context.settings);
|
this.goalTracker = new GoalTracker(context.settings);
|
||||||
this.snapshotManager = new SnapshotManager(context.settings);
|
this.snapshotManager = new SnapshotManager(context.settings);
|
||||||
@@ -17,143 +17,76 @@ class WritingStudioPlugin extends PluginAPI {
|
|||||||
readFile: (p) => context.ipc.invoke('read-file', p),
|
readFile: (p) => context.ipc.invoke('read-file', p),
|
||||||
writeFile: (p, c) => context.ipc.invoke('write-file', p, c),
|
writeFile: (p, c) => context.ipc.invoke('write-file', p, c),
|
||||||
fileExists: (p) => context.ipc.invoke('path-exists', p),
|
fileExists: (p) => context.ipc.invoke('path-exists', p),
|
||||||
listDir: (p) => context.ipc.invoke('list-directory', p),
|
listDir: (p) => context.ipc.invoke('list-directory', p)
|
||||||
});
|
});
|
||||||
|
|
||||||
this._engines = {
|
this._engines = {
|
||||||
sprint: this.sprintEngine,
|
sprint: this.sprintEngine,
|
||||||
goals: this.goalTracker,
|
goals: this.goalTracker,
|
||||||
snapshots: this.snapshotManager,
|
snapshots: this.snapshotManager,
|
||||||
projects: this.projectManager,
|
projects: this.projectManager
|
||||||
};
|
};
|
||||||
|
|
||||||
this._registerCommands(context);
|
this._registerCommands(context);
|
||||||
this._registerStatusBar(context);
|
this._registerStatusBar(context);
|
||||||
this._registerExportFormats(context);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_registerCommands(context) {
|
_registerCommands(context) {
|
||||||
const { sprintEngine, snapshotManager, goalTracker } = this;
|
const { sprintEngine, snapshotManager, goalTracker } = this;
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('start-sprint', 'Studio: Start Sprint', () => {
|
||||||
'start-sprint',
|
const duration = context.settings.get('sprintDuration') || 25;
|
||||||
'Studio: Start Sprint',
|
const content = context.editor.getContent() || '';
|
||||||
() => {
|
const words = content.split(/\s+/).filter(Boolean).length;
|
||||||
const duration = context.settings.get('sprintDuration') || 25;
|
sprintEngine.start(duration, words);
|
||||||
const content = context.editor.getContent() || '';
|
}, 'Ctrl+Alt+S');
|
||||||
const words = content.split(/\s+/).filter(Boolean).length;
|
|
||||||
sprintEngine.start(duration, words);
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+S'
|
|
||||||
);
|
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('stop-sprint', 'Studio: Stop Sprint', () => {
|
||||||
'stop-sprint',
|
if (!sprintEngine.isActive()) return;
|
||||||
'Studio: Stop Sprint',
|
const content = context.editor.getContent() || '';
|
||||||
() => {
|
const words = content.split(/\s+/).filter(Boolean).length;
|
||||||
if (!sprintEngine.isActive()) return;
|
const result = sprintEngine.stop(words);
|
||||||
const content = context.editor.getContent() || '';
|
goalTracker.addWords(result.wordDelta);
|
||||||
const words = content.split(/\s+/).filter(Boolean).length;
|
context.events.emit('sprint:stopped', result);
|
||||||
const result = sprintEngine.stop(words);
|
}, 'Ctrl+Alt+Shift+S');
|
||||||
goalTracker.addWords(result.wordDelta);
|
|
||||||
context.events.emit('sprint:stopped', result);
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+Shift+S'
|
|
||||||
);
|
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('take-snapshot', 'Studio: Take Snapshot', () => {
|
||||||
'take-snapshot',
|
const content = context.editor.getContent() || '';
|
||||||
'Studio: Take Snapshot',
|
snapshotManager.create(content, 'manual');
|
||||||
() => {
|
context.events.emit('snapshot:created', {});
|
||||||
const content = context.editor.getContent() || '';
|
}, 'Ctrl+Alt+N');
|
||||||
snapshotManager.create(content, 'manual');
|
|
||||||
context.events.emit('snapshot:created', {});
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+N'
|
|
||||||
);
|
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('restore-last-snapshot', 'Studio: Restore Last Snapshot', () => {
|
||||||
'restore-last-snapshot',
|
const snaps = snapshotManager.list();
|
||||||
'Studio: Restore Last Snapshot',
|
if (snaps.length === 0) return;
|
||||||
() => {
|
const content = snapshotManager.restore(snaps[0].id);
|
||||||
const snaps = snapshotManager.list();
|
context.editor.insertAtCursor(content);
|
||||||
if (snaps.length === 0) return;
|
}, 'Ctrl+Alt+Z');
|
||||||
const content = snapshotManager.restore(snaps[0].id);
|
|
||||||
context.editor.insertAtCursor(content);
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+Z'
|
|
||||||
);
|
|
||||||
|
|
||||||
context.commands.register('new-project', 'Studio: New Project', () => {
|
context.commands.register('new-project', 'Studio: New Project', () => {
|
||||||
context.events.emit('studio:new-project', {});
|
context.events.emit('studio:new-project', {});
|
||||||
});
|
});
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('compile-manuscript', 'Studio: Compile Manuscript', () => {
|
||||||
'compile-manuscript',
|
context.events.emit('studio:compile', {});
|
||||||
'Studio: Compile Manuscript',
|
}, 'Ctrl+Alt+E');
|
||||||
() => {
|
|
||||||
context.events.emit('studio:compile', {});
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+E'
|
|
||||||
);
|
|
||||||
|
|
||||||
context.commands.register(
|
context.commands.register('proofread-document', 'Studio: Proofread Document', () => {
|
||||||
'proofread-document',
|
if (context.events.hasHandler('ai:analyze')) {
|
||||||
'Studio: Proofread Document',
|
const content = context.editor.getContent() || '';
|
||||||
() => {
|
context.events.emit('ai:analyze', { text: content, type: 'grammar' });
|
||||||
if (context.events.hasHandler('ai:analyze')) {
|
}
|
||||||
const content = context.editor.getContent() || '';
|
}, 'Ctrl+Alt+G');
|
||||||
context.events.emit('ai:analyze', { text: content, type: 'grammar' });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'Ctrl+Alt+G'
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_registerStatusBar(context) {
|
_registerStatusBar(context) {
|
||||||
context.statusBar.registerIndicator('word-goal', {
|
context.statusBar.registerIndicator('word-goal', {
|
||||||
text: '0/1000',
|
text: '0/1000',
|
||||||
tooltip: 'Daily word goal progress',
|
tooltip: 'Daily word goal progress'
|
||||||
});
|
});
|
||||||
context.statusBar.registerIndicator('sprint-timer', {
|
context.statusBar.registerIndicator('sprint-timer', {
|
||||||
text: '',
|
text: '',
|
||||||
tooltip: 'Writing sprint timer',
|
tooltip: 'Writing sprint timer'
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Example usage of context.formats.registerExportFormat (Task 17): adds
|
|
||||||
// a "Writing Studio Summary" entry to the Export menu that writes a
|
|
||||||
// plain-text snapshot of today's sprint/goal progress instead of going
|
|
||||||
// through Pandoc. Doubles as documentation for how a plugin can offer
|
|
||||||
// its own export target.
|
|
||||||
_registerExportFormats(context) {
|
|
||||||
const { sprintEngine, goalTracker } = this;
|
|
||||||
|
|
||||||
context.formats.registerExportFormat('sprint-summary', {
|
|
||||||
label: 'Writing Studio Summary (.txt)',
|
|
||||||
extension: 'txt',
|
|
||||||
handler: async (markdownContent, outputPath) => {
|
|
||||||
const fs = require('fs');
|
|
||||||
const goal = context.settings.get('dailyGoal') || 1000;
|
|
||||||
const progress = goalTracker.getDailyProgress(goal);
|
|
||||||
const streak = goalTracker.getStreak(goal);
|
|
||||||
const wordCount = (markdownContent || '').split(/\s+/).filter(Boolean).length;
|
|
||||||
|
|
||||||
const lines = [
|
|
||||||
'Writing Studio Summary',
|
|
||||||
'=======================',
|
|
||||||
`Generated: ${new Date().toISOString()}`,
|
|
||||||
'',
|
|
||||||
`Document word count: ${wordCount}`,
|
|
||||||
`Daily goal: ${goal}`,
|
|
||||||
`Words written today: ${progress.written} (${progress.pct}%)`,
|
|
||||||
`Current streak: ${streak} day(s)`,
|
|
||||||
`Sprint active: ${sprintEngine.isActive() ? 'yes' : 'no'}`,
|
|
||||||
'',
|
|
||||||
];
|
|
||||||
|
|
||||||
fs.writeFileSync(outputPath, lines.join('\n'), 'utf-8');
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,41 +15,17 @@
|
|||||||
{ "id": "start-sprint", "label": "Studio: Start Sprint", "shortcut": "Ctrl+Alt+S" },
|
{ "id": "start-sprint", "label": "Studio: Start Sprint", "shortcut": "Ctrl+Alt+S" },
|
||||||
{ "id": "stop-sprint", "label": "Studio: Stop Sprint", "shortcut": "Ctrl+Alt+Shift+S" },
|
{ "id": "stop-sprint", "label": "Studio: Stop Sprint", "shortcut": "Ctrl+Alt+Shift+S" },
|
||||||
{ "id": "take-snapshot", "label": "Studio: Take Snapshot", "shortcut": "Ctrl+Alt+N" },
|
{ "id": "take-snapshot", "label": "Studio: Take Snapshot", "shortcut": "Ctrl+Alt+N" },
|
||||||
{
|
{ "id": "restore-last-snapshot", "label": "Studio: Restore Last Snapshot", "shortcut": "Ctrl+Alt+Z" },
|
||||||
"id": "restore-last-snapshot",
|
|
||||||
"label": "Studio: Restore Last Snapshot",
|
|
||||||
"shortcut": "Ctrl+Alt+Z"
|
|
||||||
},
|
|
||||||
{ "id": "new-project", "label": "Studio: New Project", "shortcut": "" },
|
{ "id": "new-project", "label": "Studio: New Project", "shortcut": "" },
|
||||||
{
|
{ "id": "compile-manuscript", "label": "Studio: Compile Manuscript", "shortcut": "Ctrl+Alt+E" },
|
||||||
"id": "compile-manuscript",
|
{ "id": "proofread-document", "label": "Studio: Proofread Document", "shortcut": "Ctrl+Alt+G" }
|
||||||
"label": "Studio: Compile Manuscript",
|
|
||||||
"shortcut": "Ctrl+Alt+E"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "proofread-document",
|
|
||||||
"label": "Studio: Proofread Document",
|
|
||||||
"shortcut": "Ctrl+Alt+G"
|
|
||||||
}
|
|
||||||
],
|
],
|
||||||
"statusBar": { "indicators": ["sprint-timer", "word-goal"] },
|
"statusBar": { "indicators": ["sprint-timer", "word-goal"] }
|
||||||
"exportFormats": [
|
|
||||||
{
|
|
||||||
"id": "sprint-summary",
|
|
||||||
"label": "Writing Studio Summary (.txt)",
|
|
||||||
"extension": "txt"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"settings": [
|
"settings": [
|
||||||
{ "key": "dailyGoal", "type": "number", "default": 1000, "label": "Daily word goal" },
|
{ "key": "dailyGoal", "type": "number", "default": 1000, "label": "Daily word goal" },
|
||||||
{ "key": "sprintDuration", "type": "number", "default": 25, "label": "Sprint duration (min)" },
|
{ "key": "sprintDuration", "type": "number", "default": 25, "label": "Sprint duration (min)" },
|
||||||
{
|
{ "key": "autoSnapshotInterval", "type": "number", "default": 0, "label": "Auto-snapshot interval (min, 0=off)" },
|
||||||
"key": "autoSnapshotInterval",
|
|
||||||
"type": "number",
|
|
||||||
"default": 0,
|
|
||||||
"label": "Auto-snapshot interval (min, 0=off)"
|
|
||||||
},
|
|
||||||
{ "key": "maxSnapshots", "type": "number", "default": 50, "label": "Max snapshots to keep" }
|
{ "key": "maxSnapshots", "type": "number", "default": 50, "label": "Max snapshots to keep" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,8 +29,7 @@ function renderGoalsPanel(container, { engines, settings }) {
|
|||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'ws-stat-row';
|
row.className = 'ws-stat-row';
|
||||||
const label = document.createElement('span');
|
const label = document.createElement('span');
|
||||||
label.textContent =
|
label.textContent = progress.written.toLocaleString() + ' / ' + dailyGoal.toLocaleString() + ' words';
|
||||||
progress.written.toLocaleString() + ' / ' + dailyGoal.toLocaleString() + ' words';
|
|
||||||
const pct = document.createElement('span');
|
const pct = document.createElement('span');
|
||||||
pct.className = 'ws-pct';
|
pct.className = 'ws-pct';
|
||||||
pct.textContent = progress.pct + '%';
|
pct.textContent = progress.pct + '%';
|
||||||
@@ -82,7 +81,7 @@ function renderGoalsPanel(container, { engines, settings }) {
|
|||||||
|
|
||||||
const chart = document.createElement('div');
|
const chart = document.createElement('div');
|
||||||
chart.className = 'ws-chart';
|
chart.className = 'ws-chart';
|
||||||
const maxWords = Math.max(...last30.map((d) => d.words), 1);
|
const maxWords = Math.max(...last30.map(d => d.words), 1);
|
||||||
for (const day of last30) {
|
for (const day of last30) {
|
||||||
const barEl = document.createElement('div');
|
const barEl = document.createElement('div');
|
||||||
const height = Math.max(2, (day.words / maxWords) * 60);
|
const height = Math.max(2, (day.words / maxWords) * 60);
|
||||||
|
|||||||
@@ -69,8 +69,7 @@ function renderManuscriptPanel(container, { engines, editor, settings }) {
|
|||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'ws-stat-row';
|
row.className = 'ws-stat-row';
|
||||||
const label = document.createElement('span');
|
const label = document.createElement('span');
|
||||||
label.textContent =
|
label.textContent = stats.totalWords.toLocaleString() + ' / ' + stats.targetWords.toLocaleString() + ' words';
|
||||||
stats.totalWords.toLocaleString() + ' / ' + stats.targetWords.toLocaleString() + ' words';
|
|
||||||
const pct = document.createElement('span');
|
const pct = document.createElement('span');
|
||||||
pct.className = 'ws-pct';
|
pct.className = 'ws-pct';
|
||||||
pct.textContent = stats.pctComplete + '%';
|
pct.textContent = stats.pctComplete + '%';
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ function renderProofreadPanel(container, { events, editor }) {
|
|||||||
if (result && result.issues) {
|
if (result && result.issues) {
|
||||||
renderIssues(issuesList, result.issues);
|
renderIssues(issuesList, result.issues);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -80,10 +80,7 @@ function renderIssues(container, issues) {
|
|||||||
|
|
||||||
const actions = document.createElement('div');
|
const actions = document.createElement('div');
|
||||||
actions.className = 'ws-issue-actions';
|
actions.className = 'ws-issue-actions';
|
||||||
for (const [, label] of [
|
for (const [action, label] of [['accept', 'Accept'], ['dismiss', 'Dismiss']]) {
|
||||||
['accept', 'Accept'],
|
|
||||||
['dismiss', 'Dismiss'],
|
|
||||||
]) {
|
|
||||||
const actionBtn = document.createElement('button');
|
const actionBtn = document.createElement('button');
|
||||||
actionBtn.className = 'ws-btn ws-btn-sm';
|
actionBtn.className = 'ws-btn ws-btn-sm';
|
||||||
actionBtn.textContent = label;
|
actionBtn.textContent = label;
|
||||||
|
|||||||
@@ -45,11 +45,7 @@ function renderSnapshotsPanel(container, { engines, editor }) {
|
|||||||
|
|
||||||
const actions = document.createElement('div');
|
const actions = document.createElement('div');
|
||||||
actions.className = 'ws-snapshot-actions';
|
actions.className = 'ws-snapshot-actions';
|
||||||
for (const [action, text, cls] of [
|
for (const [action, text, cls] of [['restore', 'Restore', ''], ['diff', 'Diff', ''], ['delete', 'Delete', 'ws-btn-danger']]) {
|
||||||
['restore', 'Restore', ''],
|
|
||||||
['diff', 'Diff', ''],
|
|
||||||
['delete', 'Delete', 'ws-btn-danger'],
|
|
||||||
]) {
|
|
||||||
const actionBtn = document.createElement('button');
|
const actionBtn = document.createElement('button');
|
||||||
actionBtn.className = 'ws-btn ws-btn-sm' + (cls ? ' ' + cls : '');
|
actionBtn.className = 'ws-btn ws-btn-sm' + (cls ? ' ' + cls : '');
|
||||||
actionBtn.textContent = text;
|
actionBtn.textContent = text;
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ class ProjectManager {
|
|||||||
type: opts.type || 'manuscript',
|
type: opts.type || 'manuscript',
|
||||||
target: { words: opts.targetWords || 0, deadline: opts.deadline || null },
|
target: { words: opts.targetWords || 0, deadline: opts.deadline || null },
|
||||||
chapters: [],
|
chapters: [],
|
||||||
metadata: opts.metadata || {},
|
metadata: opts.metadata || {}
|
||||||
};
|
};
|
||||||
this.fs.writeFile(dir + '/.project.json', JSON.stringify(project, null, 2));
|
this.fs.writeFile(dir + '/.project.json', JSON.stringify(project, null, 2));
|
||||||
return project;
|
return project;
|
||||||
@@ -66,7 +66,7 @@ class ProjectManager {
|
|||||||
totalWords,
|
totalWords,
|
||||||
chapterCount: project.chapters.length,
|
chapterCount: project.chapters.length,
|
||||||
targetWords: target,
|
targetWords: target,
|
||||||
pctComplete: target > 0 ? Math.min(100, Math.round((totalWords / target) * 100)) : 0,
|
pctComplete: target > 0 ? Math.min(100, Math.round((totalWords / target) * 100)) : 0
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class SnapshotManager {
|
|||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
content,
|
content,
|
||||||
wordCount: content.split(/\s+/).filter(Boolean).length,
|
wordCount: content.split(/\s+/).filter(Boolean).length,
|
||||||
label,
|
label
|
||||||
};
|
};
|
||||||
snaps.unshift(snap);
|
snaps.unshift(snap);
|
||||||
this._saveAll(snaps);
|
this._saveAll(snaps);
|
||||||
@@ -36,7 +36,7 @@ class SnapshotManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getById(id) {
|
getById(id) {
|
||||||
return this._getAll().find((s) => s.id === id) || null;
|
return this._getAll().find(s => s.id === id) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
restore(id) {
|
restore(id) {
|
||||||
@@ -46,7 +46,7 @@ class SnapshotManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
delete(id) {
|
delete(id) {
|
||||||
const snaps = this._getAll().filter((s) => s.id !== id);
|
const snaps = this._getAll().filter(s => s.id !== id);
|
||||||
this._saveAll(snaps);
|
this._saveAll(snaps);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,12 +59,8 @@ class SnapshotManager {
|
|||||||
const newSet = new Set(newLines);
|
const newSet = new Set(newLines);
|
||||||
let added = 0;
|
let added = 0;
|
||||||
let removed = 0;
|
let removed = 0;
|
||||||
for (const line of newLines) {
|
for (const line of newLines) { if (!oldSet.has(line)) added++; }
|
||||||
if (!oldSet.has(line)) added++;
|
for (const line of oldLines) { if (!newSet.has(line)) removed++; }
|
||||||
}
|
|
||||||
for (const line of oldLines) {
|
|
||||||
if (!newSet.has(line)) removed++;
|
|
||||||
}
|
|
||||||
return { added, removed };
|
return { added, removed };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,9 +40,7 @@ class SprintEngine {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isActive() {
|
isActive() { return this._active; }
|
||||||
return this._active;
|
|
||||||
}
|
|
||||||
|
|
||||||
getRemaining() {
|
getRemaining() {
|
||||||
if (!this._active) return 0;
|
if (!this._active) return 0;
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
/**
|
|
||||||
* FormatRegistry — tracks export formats registered by plugins via
|
|
||||||
* `context.formats.registerExportFormat(id, opts)`.
|
|
||||||
*
|
|
||||||
* Mirrors the simple Map-backed storage pattern used by PluginRegistry
|
|
||||||
* (see plugin-registry.js), scoped to a single concern: export format
|
|
||||||
* metadata + handler functions rather than whole plugin instances.
|
|
||||||
*/
|
|
||||||
class FormatRegistry {
|
|
||||||
constructor() {
|
|
||||||
this.formats = new Map();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register (or overwrite) an export format entry.
|
|
||||||
* @param {string} id - Fully-namespaced format id, e.g. "writing-studio:sprint-summary"
|
|
||||||
* @param {object} opts - { label, extension, handler: async (markdownContent, outputPath, options) => void }
|
|
||||||
*/
|
|
||||||
register(id, opts) {
|
|
||||||
this.formats.set(id, opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Look up a single registered format entry by its namespaced id.
|
|
||||||
* @param {string} id
|
|
||||||
* @returns {object|undefined}
|
|
||||||
*/
|
|
||||||
get(id) {
|
|
||||||
return this.formats.get(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return all registered formats as an array of { id, ...opts }.
|
|
||||||
*/
|
|
||||||
getAll() {
|
|
||||||
return Array.from(this.formats.entries()).map(([id, opts]) => ({ id, ...opts }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { FormatRegistry };
|
|
||||||
@@ -10,24 +10,12 @@ class PluginContext {
|
|||||||
* @param {object} deps.editor - { getContent, getSelection, insertAtCursor, onContentChanged }
|
* @param {object} deps.editor - { getContent, getSelection, insertAtCursor, onContentChanged }
|
||||||
* @param {object} deps.ipc - { invoke, on }
|
* @param {object} deps.ipc - { invoke, on }
|
||||||
* @param {object} deps.exportHooks - { preHooks: [], postHooks: [] }
|
* @param {object} deps.exportHooks - { preHooks: [], postHooks: [] }
|
||||||
* @param {object} deps.formatRegistry - FormatRegistry instance ({ register, get, getAll })
|
|
||||||
*/
|
*/
|
||||||
constructor(deps) {
|
constructor(deps) {
|
||||||
const {
|
const { pluginId, sidebar, commands, statusBar, eventBus, settings, editor, ipc, exportHooks } = deps;
|
||||||
pluginId,
|
|
||||||
sidebar,
|
|
||||||
commands,
|
|
||||||
statusBar,
|
|
||||||
eventBus,
|
|
||||||
settings,
|
|
||||||
editor,
|
|
||||||
ipc,
|
|
||||||
exportHooks,
|
|
||||||
formatRegistry,
|
|
||||||
} = deps;
|
|
||||||
|
|
||||||
this.sidebar = {
|
this.sidebar = {
|
||||||
registerPanel: (id, opts) => sidebar.registerPanel(`${pluginId}:${id}`, opts),
|
registerPanel: (id, opts) => sidebar.registerPanel(`${pluginId}:${id}`, opts)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.commands = {
|
this.commands = {
|
||||||
@@ -40,58 +28,41 @@ class PluginContext {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
commands.register(`${pluginId}:${id}`, label, safeHandler, shortcut);
|
commands.register(`${pluginId}:${id}`, label, safeHandler, shortcut);
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.statusBar = {
|
this.statusBar = {
|
||||||
registerIndicator: (id, opts) => statusBar.registerIndicator(`${pluginId}:${id}`, opts),
|
registerIndicator: (id, opts) => statusBar.registerIndicator(`${pluginId}:${id}`, opts)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.settings = {
|
this.settings = {
|
||||||
get: (key) => settings.get(`plugins.${pluginId}.${key}`),
|
get: (key) => settings.get(`plugins.${pluginId}.${key}`),
|
||||||
set: (key, value) => settings.set(`plugins.${pluginId}.${key}`, value),
|
set: (key, value) => settings.set(`plugins.${pluginId}.${key}`, value),
|
||||||
onChanged: (key, cb) => settings.onChanged(`plugins.${pluginId}.${key}`, cb),
|
onChanged: (key, cb) => settings.onChanged(`plugins.${pluginId}.${key}`, cb)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.editor = {
|
this.editor = {
|
||||||
getContent: () => editor.getContent(),
|
getContent: () => editor.getContent(),
|
||||||
getSelection: () => editor.getSelection(),
|
getSelection: () => editor.getSelection(),
|
||||||
insertAtCursor: (text) => editor.insertAtCursor(text),
|
insertAtCursor: (text) => editor.insertAtCursor(text),
|
||||||
onContentChanged: (cb) => editor.onContentChanged(cb),
|
onContentChanged: (cb) => editor.onContentChanged(cb)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.events = {
|
this.events = {
|
||||||
on: (event, handler) => eventBus.on(event, handler),
|
on: (event, handler) => eventBus.on(event, handler),
|
||||||
off: (event, handler) => eventBus.off(event, handler),
|
off: (event, handler) => eventBus.off(event, handler),
|
||||||
emit: (event, payload) => eventBus.emit(event, payload),
|
emit: (event, payload) => eventBus.emit(event, payload),
|
||||||
hasHandler: (event) => eventBus.hasHandler(event),
|
hasHandler: (event) => eventBus.hasHandler(event)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.ipc = {
|
this.ipc = {
|
||||||
invoke: (channel, ...args) => ipc.invoke(channel, ...args),
|
invoke: (channel, ...args) => ipc.invoke(channel, ...args),
|
||||||
on: (channel, handler) => ipc.on(channel, handler),
|
on: (channel, handler) => ipc.on(channel, handler)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.exports = {
|
this.exports = {
|
||||||
registerPreHook: (handler) => {
|
registerPreHook: (handler) => { if (exportHooks) exportHooks.preHooks.push(handler); },
|
||||||
if (exportHooks) exportHooks.preHooks.push(handler);
|
registerPostHook: (handler) => { if (exportHooks) exportHooks.postHooks.push(handler); }
|
||||||
},
|
|
||||||
registerPostHook: (handler) => {
|
|
||||||
if (exportHooks) exportHooks.postHooks.push(handler);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
this.formats = {
|
|
||||||
/**
|
|
||||||
* Register a plugin-provided export format. It is namespaced as
|
|
||||||
* `${pluginId}:${id}` so plugins can't collide with each other or
|
|
||||||
* with the built-in Pandoc-backed formats.
|
|
||||||
* @param {string} id - Format id, unique within this plugin.
|
|
||||||
* @param {object} opts - { label, extension, handler: async (markdownContent, outputPath, options) => void }
|
|
||||||
*/
|
|
||||||
registerExportFormat: (id, opts) => {
|
|
||||||
if (formatRegistry) formatRegistry.register(`${pluginId}:${id}`, opts);
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,10 +35,7 @@ class PluginLoader {
|
|||||||
const loaded = require(indexPath);
|
const loaded = require(indexPath);
|
||||||
PluginClass = loaded.Plugin || loaded.default || null;
|
PluginClass = loaded.Plugin || loaded.default || null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(
|
console.error(`[PluginLoader] Failed to load index.js for "${manifest.id}":`, err.message);
|
||||||
`[PluginLoader] Failed to load index.js for "${manifest.id}":`,
|
|
||||||
err.message
|
|
||||||
);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,7 +46,7 @@ class PluginLoader {
|
|||||||
description: manifest.description,
|
description: manifest.description,
|
||||||
manifest,
|
manifest,
|
||||||
PluginClass,
|
PluginClass,
|
||||||
dir: pluginDir,
|
dir: pluginDir
|
||||||
});
|
});
|
||||||
this.loadedIds.add(manifest.id);
|
this.loadedIds.add(manifest.id);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -32,8 +32,7 @@ class PluginRegistry {
|
|||||||
settings: this.deps.settings,
|
settings: this.deps.settings,
|
||||||
editor: this.deps.editor,
|
editor: this.deps.editor,
|
||||||
ipc: this.deps.ipc,
|
ipc: this.deps.ipc,
|
||||||
exportHooks: this.exportHooks,
|
exportHooks: this.exportHooks
|
||||||
formatRegistry: this.deps.formatRegistry,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ class SettingsStore {
|
|||||||
this.backend.set(key, value);
|
this.backend.set(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
onChanged(_key, _callback) {
|
onChanged(key, callback) {
|
||||||
// Deferred: plugins read settings on init/activate for MVP.
|
// Deferred: plugins read settings on init/activate for MVP.
|
||||||
// Full change notification requires IPC watcher in main process.
|
// Full change notification requires IPC watcher in main process.
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-84
@@ -12,7 +12,7 @@
|
|||||||
* @version 4.4.1
|
* @version 4.4.1
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const { contextBridge, ipcRenderer, webUtils } = require('electron');
|
const { contextBridge, ipcRenderer } = require('electron');
|
||||||
|
|
||||||
// Define allowed IPC channels for security
|
// Define allowed IPC channels for security
|
||||||
const ALLOWED_SEND_CHANNELS = [
|
const ALLOWED_SEND_CHANNELS = [
|
||||||
@@ -36,10 +36,6 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'export-with-options',
|
'export-with-options',
|
||||||
'export-spreadsheet',
|
'export-spreadsheet',
|
||||||
|
|
||||||
// Plugin export formats
|
|
||||||
'plugin-export-formats-registered',
|
|
||||||
'plugin-export-format-result',
|
|
||||||
|
|
||||||
// Batch conversion
|
// Batch conversion
|
||||||
'batch-convert',
|
'batch-convert',
|
||||||
'select-folder',
|
'select-folder',
|
||||||
@@ -49,17 +45,26 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'universal-convert-batch',
|
'universal-convert-batch',
|
||||||
|
|
||||||
// Image converter
|
// Image converter
|
||||||
'process-image-operation',
|
'image-convert',
|
||||||
'select-image-folder',
|
'image-batch-convert',
|
||||||
'batch-image-operation',
|
'image-resize',
|
||||||
|
'image-compress',
|
||||||
|
'image-rotate',
|
||||||
|
|
||||||
// Audio converter
|
// Audio converter
|
||||||
'process-audio-operation',
|
'audio-convert',
|
||||||
'batch-audio-operation',
|
'audio-batch-convert',
|
||||||
|
'audio-extract',
|
||||||
|
'audio-trim',
|
||||||
|
'audio-merge',
|
||||||
|
|
||||||
// Video converter
|
// Video converter
|
||||||
'process-video-operation',
|
'video-convert',
|
||||||
'batch-video-operation',
|
'video-batch-convert',
|
||||||
|
'video-compress',
|
||||||
|
'video-trim',
|
||||||
|
'video-frames',
|
||||||
|
'video-gif',
|
||||||
|
|
||||||
// Header/Footer
|
// Header/Footer
|
||||||
'get-header-footer-settings',
|
'get-header-footer-settings',
|
||||||
@@ -68,28 +73,17 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'save-header-footer-logo',
|
'save-header-footer-logo',
|
||||||
'clear-header-footer-logo',
|
'clear-header-footer-logo',
|
||||||
|
|
||||||
// Word template settings
|
|
||||||
'get-word-template-settings',
|
|
||||||
'save-word-template-settings',
|
|
||||||
'browse-word-template',
|
|
||||||
'clear-word-template',
|
|
||||||
|
|
||||||
// Export presets (invoke channels — gated by this same array)
|
|
||||||
'get-export-presets',
|
|
||||||
'save-export-preset',
|
|
||||||
'delete-export-preset',
|
|
||||||
|
|
||||||
// Page settings
|
// Page settings
|
||||||
'get-page-settings',
|
'get-page-settings',
|
||||||
'update-page-settings',
|
'update-page-settings',
|
||||||
|
|
||||||
|
// Template settings
|
||||||
|
'set-custom-start-page',
|
||||||
|
|
||||||
// PDF operations
|
// PDF operations
|
||||||
'process-pdf-operation',
|
'process-pdf-operation',
|
||||||
'get-pdf-page-count',
|
'get-pdf-page-count',
|
||||||
'get-pdf-form-fields',
|
|
||||||
'get-pdf-capabilities',
|
|
||||||
'select-pdf-folder',
|
'select-pdf-folder',
|
||||||
'batch-pdf-operation',
|
|
||||||
|
|
||||||
// ASCII generator (separate window)
|
// ASCII generator (separate window)
|
||||||
'open-ascii-generator',
|
'open-ascii-generator',
|
||||||
@@ -122,10 +116,6 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'git-stage',
|
'git-stage',
|
||||||
'git-commit',
|
'git-commit',
|
||||||
'git-log',
|
'git-log',
|
||||||
'git-branches',
|
|
||||||
'git-checkout',
|
|
||||||
'git-push',
|
|
||||||
'git-pull',
|
|
||||||
|
|
||||||
// Snippets
|
// Snippets
|
||||||
'get-snippets',
|
'get-snippets',
|
||||||
@@ -150,11 +140,7 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
|
|
||||||
// Plugin settings
|
// Plugin settings
|
||||||
'plugin-settings:get',
|
'plugin-settings:get',
|
||||||
'plugin-settings:set',
|
'plugin-settings:set'
|
||||||
|
|
||||||
// Monospace font settings
|
|
||||||
'get-monospace-settings',
|
|
||||||
'set-monospace-settings',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const ALLOWED_RECEIVE_CHANNELS = [
|
const ALLOWED_RECEIVE_CHANNELS = [
|
||||||
@@ -182,7 +168,6 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
|
|
||||||
// Font
|
// Font
|
||||||
'adjust-font-size',
|
'adjust-font-size',
|
||||||
'monospace-setting-change',
|
|
||||||
|
|
||||||
// Print
|
// Print
|
||||||
'print-preview',
|
'print-preview',
|
||||||
@@ -194,7 +179,6 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
'show-universal-converter-dialog',
|
'show-universal-converter-dialog',
|
||||||
'show-table-generator',
|
'show-table-generator',
|
||||||
'show-pdf-editor-dialog',
|
'show-pdf-editor-dialog',
|
||||||
'show-document-compare',
|
|
||||||
|
|
||||||
// Converter dialogs
|
// Converter dialogs
|
||||||
'show-image-converter',
|
'show-image-converter',
|
||||||
@@ -212,34 +196,22 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
'audio-conversion-complete',
|
'audio-conversion-complete',
|
||||||
'video-conversion-complete',
|
'video-conversion-complete',
|
||||||
|
|
||||||
// Batch media operations (Image/Audio/Video Tools dialog batch mode)
|
|
||||||
'media-batch-progress',
|
|
||||||
'media-batch-complete',
|
|
||||||
|
|
||||||
// Folder selection
|
// Folder selection
|
||||||
'folder-selected',
|
'folder-selected',
|
||||||
'pdf-folder-selected',
|
'pdf-folder-selected',
|
||||||
'image-folder-selected',
|
|
||||||
|
|
||||||
// Header/Footer
|
// Header/Footer
|
||||||
'header-footer-settings-data',
|
'header-footer-settings-data',
|
||||||
'header-footer-logo-selected',
|
'header-footer-logo-selected',
|
||||||
'header-footer-logo-saved',
|
'header-footer-logo-saved',
|
||||||
|
|
||||||
// Word template settings
|
|
||||||
'word-template-settings-data',
|
|
||||||
'word-template-browsed',
|
|
||||||
'open-word-template-dialog',
|
|
||||||
|
|
||||||
// Page settings
|
// Page settings
|
||||||
'page-settings-data',
|
'page-settings-data',
|
||||||
|
|
||||||
// PDF operations
|
// PDF operations
|
||||||
'pdf-page-count',
|
'pdf-page-count',
|
||||||
'pdf-form-fields',
|
|
||||||
'pdf-operation-complete',
|
'pdf-operation-complete',
|
||||||
'pdf-operation-error',
|
'pdf-operation-error',
|
||||||
'pdf-batch-complete',
|
|
||||||
|
|
||||||
// ASCII Art Generator
|
// ASCII Art Generator
|
||||||
'show-ascii-generator-window',
|
'show-ascii-generator-window',
|
||||||
@@ -267,8 +239,10 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
'toggle-sidebar-panel',
|
'toggle-sidebar-panel',
|
||||||
'toggle-bottom-panel',
|
'toggle-bottom-panel',
|
||||||
|
|
||||||
// Plugin export formats
|
// File dialog / directory listing
|
||||||
'run-plugin-export-format',
|
'list-directory',
|
||||||
|
'pick-folder',
|
||||||
|
'pick-file'
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -376,22 +350,25 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
isDirectory: (filePath) => ipcRenderer.invoke('is-directory', filePath),
|
isDirectory: (filePath) => ipcRenderer.invoke('is-directory', filePath),
|
||||||
copy: (source, destination) => ipcRenderer.invoke('copy-path', { source, destination }),
|
copy: (source, destination) => ipcRenderer.invoke('copy-path', { source, destination }),
|
||||||
move: (source, destination) => ipcRenderer.invoke('move-path', { source, destination }),
|
move: (source, destination) => ipcRenderer.invoke('move-path', { source, destination }),
|
||||||
|
list: (dirPath) => ipcRenderer.invoke('list-directory', dirPath),
|
||||||
|
pickFolder: () => ipcRenderer.invoke('pick-folder'),
|
||||||
|
pickFile: () => ipcRenderer.invoke('pick-file')
|
||||||
},
|
},
|
||||||
|
|
||||||
// Theme Operations
|
// Theme Operations
|
||||||
theme: {
|
theme: {
|
||||||
get: () => ipcRenderer.send('get-theme'),
|
get: () => ipcRenderer.send('get-theme')
|
||||||
},
|
},
|
||||||
|
|
||||||
// Print Operations
|
// Print Operations
|
||||||
print: {
|
print: {
|
||||||
doPrint: (options) => ipcRenderer.send('do-print', options),
|
doPrint: (options) => ipcRenderer.send('do-print', options)
|
||||||
},
|
},
|
||||||
|
|
||||||
// Export Operations
|
// Export Operations
|
||||||
export: {
|
export: {
|
||||||
withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }),
|
withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }),
|
||||||
spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format }),
|
spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format })
|
||||||
},
|
},
|
||||||
|
|
||||||
// Batch Conversion
|
// Batch Conversion
|
||||||
@@ -399,7 +376,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
convert: (inputFolder, outputFolder, format, options) => {
|
convert: (inputFolder, outputFolder, format, options) => {
|
||||||
ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options });
|
ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options });
|
||||||
},
|
},
|
||||||
selectFolder: (type) => ipcRenderer.send('select-folder', type),
|
selectFolder: (type) => ipcRenderer.send('select-folder', type)
|
||||||
},
|
},
|
||||||
|
|
||||||
// Universal Converter
|
// Universal Converter
|
||||||
@@ -408,14 +385,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath });
|
ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath });
|
||||||
},
|
},
|
||||||
convertBatch: (tool, fromFormat, toFormat, inputFolder, outputFolder) => {
|
convertBatch: (tool, fromFormat, toFormat, inputFolder, outputFolder) => {
|
||||||
ipcRenderer.send('universal-convert-batch', {
|
ipcRenderer.send('universal-convert-batch', { tool, fromFormat, toFormat, inputFolder, outputFolder });
|
||||||
tool,
|
}
|
||||||
fromFormat,
|
|
||||||
toFormat,
|
|
||||||
inputFolder,
|
|
||||||
outputFolder,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
|
|
||||||
// Header/Footer Operations
|
// Header/Footer Operations
|
||||||
@@ -423,46 +394,59 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
getSettings: () => ipcRenderer.send('get-header-footer-settings'),
|
getSettings: () => ipcRenderer.send('get-header-footer-settings'),
|
||||||
saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings),
|
saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings),
|
||||||
browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position),
|
browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position),
|
||||||
saveLogo: (position, filePath) =>
|
saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }),
|
||||||
ipcRenderer.send('save-header-footer-logo', { position, filePath }),
|
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position)
|
||||||
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position),
|
|
||||||
},
|
},
|
||||||
|
|
||||||
// Page Settings
|
// Page Settings
|
||||||
page: {
|
page: {
|
||||||
getSettings: () => ipcRenderer.send('get-page-settings'),
|
getSettings: () => ipcRenderer.send('get-page-settings'),
|
||||||
updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings),
|
updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings),
|
||||||
},
|
setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber)
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve a File object chosen via `<input type="file">` to its absolute
|
|
||||||
* path. `File.path` was removed in Electron 32; `webUtils.getPathForFile`
|
|
||||||
* is its replacement. Falls back to `file.path` on older Electron where
|
|
||||||
* webUtils is unavailable.
|
|
||||||
* @param {File} file - File object from a file input's files list
|
|
||||||
* @returns {string | undefined} Absolute filesystem path when resolvable
|
|
||||||
*/
|
|
||||||
getFilePath: (file) => {
|
|
||||||
if (webUtils && typeof webUtils.getPathForFile === 'function') {
|
|
||||||
return webUtils.getPathForFile(file);
|
|
||||||
}
|
|
||||||
return file && file.path;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
// PDF Operations
|
// PDF Operations
|
||||||
pdf: {
|
pdf: {
|
||||||
processOperation: (data) => ipcRenderer.send('process-pdf-operation', data),
|
processOperation: (data) => ipcRenderer.send('process-pdf-operation', data),
|
||||||
getPageCount: (filePath) => ipcRenderer.send('get-pdf-page-count', filePath),
|
getPageCount: (filePath) => ipcRenderer.send('get-pdf-page-count', filePath),
|
||||||
selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId),
|
selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId)
|
||||||
|
},
|
||||||
|
|
||||||
|
// Image Converter Operations
|
||||||
|
image: {
|
||||||
|
convert: (data) => ipcRenderer.send('image-convert', data),
|
||||||
|
batchConvert: (data) => ipcRenderer.send('image-batch-convert', data),
|
||||||
|
resize: (data) => ipcRenderer.send('image-resize', data),
|
||||||
|
compress: (data) => ipcRenderer.send('image-compress', data),
|
||||||
|
rotate: (data) => ipcRenderer.send('image-rotate', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
// Audio Converter Operations
|
||||||
|
audio: {
|
||||||
|
convert: (data) => ipcRenderer.send('audio-convert', data),
|
||||||
|
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
|
||||||
|
extract: (data) => ipcRenderer.send('audio-extract', data),
|
||||||
|
trim: (data) => ipcRenderer.send('audio-trim', data),
|
||||||
|
merge: (data) => ipcRenderer.send('audio-merge', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
// Video Converter Operations
|
||||||
|
video: {
|
||||||
|
convert: (data) => ipcRenderer.send('video-convert', data),
|
||||||
|
batchConvert: (data) => ipcRenderer.send('video-batch-convert', data),
|
||||||
|
compress: (data) => ipcRenderer.send('video-compress', data),
|
||||||
|
trim: (data) => ipcRenderer.send('video-trim', data),
|
||||||
|
extractFrames: (data) => ipcRenderer.send('video-frames', data),
|
||||||
|
toGif: (data) => ipcRenderer.send('video-gif', data)
|
||||||
},
|
},
|
||||||
|
|
||||||
// Generator Windows
|
// Generator Windows
|
||||||
generators: {
|
generators: {
|
||||||
openAscii: () => ipcRenderer.send('open-ascii-generator'),
|
openAscii: () => ipcRenderer.send('open-ascii-generator'),
|
||||||
openTable: () => ipcRenderer.send('open-table-generator'),
|
openTable: () => ipcRenderer.send('open-table-generator')
|
||||||
},
|
},
|
||||||
|
|
||||||
getAppVersion: () => ipcRenderer.invoke('get-app-version'),
|
getAppVersion: () => ipcRenderer.invoke('get-app-version')
|
||||||
});
|
});
|
||||||
|
|
||||||
// Log successful preload initialization
|
// Log successful preload initialization
|
||||||
|
|||||||
+91
-156
@@ -1,143 +1,89 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
function getBundledFontWoff2Path(familyKey, weight) {
|
|
||||||
// Renderer can read directly from disk because nodeIntegration is on.
|
|
||||||
// Try repo-relative first, then packaged app.asar mirror.
|
|
||||||
const familyDir = familyKey === 'fira-code' ? 'FiraCode' : 'JetBrainsMono';
|
|
||||||
const weightName = weight >= 700 ? 'Bold' : 'Regular';
|
|
||||||
const filename = `${familyDir}-${weightName}.woff2`;
|
|
||||||
const repoPath = path.resolve(__dirname, '..', 'assets', 'fonts', filename);
|
|
||||||
if (fs.existsSync(repoPath)) return repoPath;
|
|
||||||
// Packaged: under <resourcesPath>/assets/fonts/
|
|
||||||
if (process.resourcesPath) {
|
|
||||||
const packaged = path.join(process.resourcesPath, 'assets', 'fonts', filename);
|
|
||||||
if (fs.existsSync(packaged)) return packaged;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildFontFaceBlock(familyKey) {
|
|
||||||
const family = familyKey === 'fira-code' ? 'Fira Code' : 'JetBrains Mono';
|
|
||||||
const fontPath = getBundledFontWoff2Path(familyKey, 400);
|
|
||||||
if (!fontPath) return '';
|
|
||||||
try {
|
|
||||||
const data = fs.readFileSync(fontPath);
|
|
||||||
const dataUri = `data:font/woff2;base64,${data.toString('base64')}`;
|
|
||||||
return `@font-face { font-family: '${family}'; font-weight: 400; font-style: normal; src: url('${dataUri}') format('woff2'); }`;
|
|
||||||
} catch (err) {
|
|
||||||
// Non-fatal: fall back to the system monospace stack declared in styles-modern.css.
|
|
||||||
if (typeof console !== 'undefined')
|
|
||||||
console.warn('[print-preview] font embed failed:', err.message);
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class PrintPreview {
|
class PrintPreview {
|
||||||
constructor(monospaceSettings = {}) {
|
constructor() {
|
||||||
this.overlay = document.getElementById('print-preview-overlay');
|
this.overlay = document.getElementById('print-preview-overlay');
|
||||||
this.modal = window.modals?.printPreviewModal;
|
this.modal = window.modals?.printPreviewModal;
|
||||||
this._lastContent = '';
|
this._lastContent = '';
|
||||||
this._monospaceSettings = {
|
this.setupEventListeners();
|
||||||
monospaceFont: monospaceSettings.monospaceFont || 'jetbrains-mono',
|
|
||||||
monospaceLigatures: monospaceSettings.monospaceLigatures === true,
|
|
||||||
};
|
|
||||||
this.setupEventListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
setMonospaceSettings(settings) {
|
|
||||||
this._monospaceSettings = {
|
|
||||||
monospaceFont: (settings && settings.monospaceFont) || 'jetbrains-mono',
|
|
||||||
monospaceLigatures: !!(settings && settings.monospaceLigatures === true),
|
|
||||||
};
|
|
||||||
this.refreshPreview();
|
|
||||||
}
|
|
||||||
|
|
||||||
open(htmlContent) {
|
|
||||||
this._lastContent = htmlContent;
|
|
||||||
if (this.modal) {
|
|
||||||
this.modal.open();
|
|
||||||
} else {
|
|
||||||
this.overlay.classList.remove('hidden');
|
|
||||||
}
|
}
|
||||||
this.updatePreview(htmlContent);
|
|
||||||
this.updateScaleLabel();
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
open(htmlContent) {
|
||||||
if (this.modal) {
|
this._lastContent = htmlContent;
|
||||||
this.modal.close();
|
if (this.modal) {
|
||||||
} else {
|
this.modal.open();
|
||||||
this.overlay.classList.add('hidden');
|
} else {
|
||||||
|
this.overlay.classList.remove('hidden');
|
||||||
|
}
|
||||||
|
this.updatePreview(htmlContent);
|
||||||
|
this.updateScaleLabel();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
setupEventListeners() {
|
close() {
|
||||||
document.getElementById('print-preview-close')?.addEventListener('click', () => this.close());
|
if (this.modal) {
|
||||||
document.getElementById('print-cancel')?.addEventListener('click', () => this.close());
|
this.modal.close();
|
||||||
document.getElementById('print-execute')?.addEventListener('click', () => this.executePrint());
|
} else {
|
||||||
|
this.overlay.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Update preview on option changes
|
setupEventListeners() {
|
||||||
['print-paper-size', 'print-orientation', 'print-margins'].forEach((id) => {
|
document.getElementById('print-preview-close')?.addEventListener('click', () => this.close());
|
||||||
document.getElementById(id)?.addEventListener('change', () => this.refreshPreview());
|
document.getElementById('print-cancel')?.addEventListener('click', () => this.close());
|
||||||
});
|
document.getElementById('print-execute')?.addEventListener('click', () => this.executePrint());
|
||||||
|
|
||||||
// Scale slider
|
// Update preview on option changes
|
||||||
const scaleSlider = document.getElementById('print-scale');
|
['print-paper-size', 'print-orientation', 'print-margins'].forEach(id => {
|
||||||
scaleSlider?.addEventListener('input', () => this.updateScaleLabel());
|
document.getElementById(id)?.addEventListener('change', () => this.refreshPreview());
|
||||||
|
});
|
||||||
|
|
||||||
// Page range toggle
|
// Scale slider
|
||||||
document.getElementById('print-pages')?.addEventListener('change', (e) => {
|
const scaleSlider = document.getElementById('print-scale');
|
||||||
const rangeInput = document.getElementById('print-page-range');
|
scaleSlider?.addEventListener('input', () => this.updateScaleLabel());
|
||||||
if (rangeInput) {
|
|
||||||
rangeInput.classList.toggle('hidden', e.target.value !== 'custom');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Note: Backdrop click and Escape key are now handled by ModalManager
|
// Page range toggle
|
||||||
}
|
document.getElementById('print-pages')?.addEventListener('change', (e) => {
|
||||||
|
const rangeInput = document.getElementById('print-page-range');
|
||||||
|
if (rangeInput) {
|
||||||
|
rangeInput.classList.toggle('hidden', e.target.value !== 'custom');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
updateScaleLabel() {
|
// Note: Backdrop click and Escape key are now handled by ModalManager
|
||||||
const scale = document.getElementById('print-scale')?.value || 100;
|
}
|
||||||
const label = document.getElementById('print-scale-value');
|
|
||||||
if (label) label.textContent = `${scale}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
updatePreview(htmlContent) {
|
updateScaleLabel() {
|
||||||
const frame = document.getElementById('print-preview-frame');
|
const scale = document.getElementById('print-scale')?.value || 100;
|
||||||
if (!frame) return;
|
const label = document.getElementById('print-scale-value');
|
||||||
|
if (label) label.textContent = `${scale}%`;
|
||||||
|
}
|
||||||
|
|
||||||
this._lastContent = htmlContent;
|
updatePreview(htmlContent) {
|
||||||
|
const frame = document.getElementById('print-preview-frame');
|
||||||
|
if (!frame) return;
|
||||||
|
|
||||||
const orientation = document.getElementById('print-orientation')?.value || 'portrait';
|
this._lastContent = htmlContent;
|
||||||
const paperSize = document.getElementById('print-paper-size')?.value || 'A4';
|
|
||||||
|
|
||||||
// Get dimensions for paper size
|
const orientation = document.getElementById('print-orientation')?.value || 'portrait';
|
||||||
const sizes = {
|
const paperSize = document.getElementById('print-paper-size')?.value || 'A4';
|
||||||
A3: { width: '297mm', height: '420mm' },
|
|
||||||
A4: { width: '210mm', height: '297mm' },
|
|
||||||
A5: { width: '148mm', height: '210mm' },
|
|
||||||
Letter: { width: '8.5in', height: '11in' },
|
|
||||||
Legal: { width: '8.5in', height: '14in' },
|
|
||||||
Tabloid: { width: '11in', height: '17in' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const size = sizes[paperSize] || sizes['A4'];
|
// Get dimensions for paper size
|
||||||
const width = orientation === 'landscape' ? size.height : size.width;
|
const sizes = {
|
||||||
const height = orientation === 'landscape' ? size.width : size.height;
|
'A3': { width: '297mm', height: '420mm' },
|
||||||
|
'A4': { width: '210mm', height: '297mm' },
|
||||||
|
'A5': { width: '148mm', height: '210mm' },
|
||||||
|
'Letter': { width: '8.5in', height: '11in' },
|
||||||
|
'Legal': { width: '8.5in', height: '14in' },
|
||||||
|
'Tabloid': { width: '11in', height: '17in' },
|
||||||
|
};
|
||||||
|
|
||||||
const family =
|
const size = sizes[paperSize] || sizes['A4'];
|
||||||
this._monospaceSettings.monospaceFont === 'fira-code' ? 'Fira Code' : 'JetBrains Mono';
|
const width = orientation === 'landscape' ? size.height : size.width;
|
||||||
const ligaturesOn = this._monospaceSettings.monospaceLigatures === true;
|
const height = orientation === 'landscape' ? size.width : size.height;
|
||||||
const featureSettings = ligaturesOn ? 'normal' : "'liga' 0, 'calt' 0, 'dlig' 0";
|
|
||||||
const fontFaceBlock = buildFontFaceBlock(this._monospaceSettings.monospaceFont);
|
|
||||||
|
|
||||||
const previewHtml = `
|
const previewHtml = `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<style>
|
<style>
|
||||||
${fontFaceBlock}
|
|
||||||
body {
|
body {
|
||||||
margin: 20px;
|
margin: 20px;
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||||
@@ -145,18 +91,7 @@ class PrintPreview {
|
|||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
}
|
}
|
||||||
@page { size: ${width} ${height}; }
|
@page { size: ${width} ${height}; }
|
||||||
pre, code, kbd, samp {
|
pre { background: #f5f5f5; padding: 12px; border-radius: 6px; overflow-x: auto; }
|
||||||
font-family: '${family}', monospace;
|
|
||||||
font-feature-settings: ${featureSettings};
|
|
||||||
}
|
|
||||||
pre {
|
|
||||||
background: #f5f5f5;
|
|
||||||
padding: 12px;
|
|
||||||
border-radius: 6px;
|
|
||||||
overflow-x: auto;
|
|
||||||
white-space: pre;
|
|
||||||
tab-size: 4;
|
|
||||||
}
|
|
||||||
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
|
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
|
||||||
pre code { background: none; padding: 0; }
|
pre code { background: none; padding: 0; }
|
||||||
table { border-collapse: collapse; width: 100%; }
|
table { border-collapse: collapse; width: 100%; }
|
||||||
@@ -170,34 +105,34 @@ class PrintPreview {
|
|||||||
</html>
|
</html>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
frame.srcdoc = previewHtml;
|
frame.srcdoc = previewHtml;
|
||||||
}
|
|
||||||
|
|
||||||
refreshPreview() {
|
|
||||||
if (this._lastContent) {
|
|
||||||
this.updatePreview(this._lastContent);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
getOptions() {
|
refreshPreview() {
|
||||||
return {
|
if (this._lastContent) {
|
||||||
paperSize: document.getElementById('print-paper-size')?.value || 'A4',
|
this.updatePreview(this._lastContent);
|
||||||
orientation: document.getElementById('print-orientation')?.value || 'portrait',
|
}
|
||||||
margins: document.getElementById('print-margins')?.value || 'default',
|
}
|
||||||
scale: parseInt(document.getElementById('print-scale')?.value || '100'),
|
|
||||||
headers: document.getElementById('print-headers')?.checked ?? true,
|
|
||||||
background: document.getElementById('print-background')?.checked ?? true,
|
|
||||||
pages: document.getElementById('print-pages')?.value || 'all',
|
|
||||||
pageRange: document.getElementById('print-page-range')?.value || '',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
executePrint() {
|
getOptions() {
|
||||||
const options = this.getOptions();
|
return {
|
||||||
const { ipcRenderer } = require('electron');
|
paperSize: document.getElementById('print-paper-size')?.value || 'A4',
|
||||||
ipcRenderer.send('do-print-with-options', options);
|
orientation: document.getElementById('print-orientation')?.value || 'portrait',
|
||||||
this.close();
|
margins: document.getElementById('print-margins')?.value || 'default',
|
||||||
}
|
scale: parseInt(document.getElementById('print-scale')?.value || '100'),
|
||||||
|
headers: document.getElementById('print-headers')?.checked ?? true,
|
||||||
|
background: document.getElementById('print-background')?.checked ?? true,
|
||||||
|
pages: document.getElementById('print-pages')?.value || 'all',
|
||||||
|
pageRange: document.getElementById('print-page-range')?.value || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
executePrint() {
|
||||||
|
const options = this.getOptions();
|
||||||
|
const { ipcRenderer } = require('electron');
|
||||||
|
ipcRenderer.send('do-print-with-options', options);
|
||||||
|
this.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { PrintPreview };
|
module.exports = { PrintPreview };
|
||||||
|
|||||||
+4417
-5678
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
|||||||
|
import { AppShell } from './components/layout/AppShell';
|
||||||
|
import { ModalLayer } from './components/modals/ModalLayer';
|
||||||
|
import { Toaster } from './components/ui/sonner';
|
||||||
|
import { useWelcomeTrigger } from './hooks/use-welcome-trigger';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
useWelcomeTrigger();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AppShell />
|
||||||
|
<ModalLayer />
|
||||||
|
<Toaster />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export default App;
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { EditorState, Compartment } from '@codemirror/state';
|
||||||
|
import { EditorView, keymap, lineNumbers, highlightActiveLine, drawSelection } from '@codemirror/view';
|
||||||
|
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||||
|
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
|
||||||
|
import { searchKeymap, highlightSelectionMatches } from '@codemirror/search';
|
||||||
|
import { autocompletion, completionKeymap } from '@codemirror/autocomplete';
|
||||||
|
import { oneDark } from '@codemirror/theme-one-dark';
|
||||||
|
import { useTheme } from 'next-themes';
|
||||||
|
import { lightTheme, lightHighlight } from './themes/light';
|
||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
bufferId: string;
|
||||||
|
initialContent: string;
|
||||||
|
onChange?: (content: string) => void;
|
||||||
|
onCursorChange?: (line: number, column: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CodeMirrorEditor({ bufferId, initialContent, onChange, onCursorChange }: Props) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const viewRef = useRef<EditorView | null>(null);
|
||||||
|
const themeCompartment = useRef(new Compartment());
|
||||||
|
const { resolvedTheme } = useTheme();
|
||||||
|
const updateContent = useEditorStore((s) => s.updateContent);
|
||||||
|
const setCursor = useEditorStore((s) => s.setCursor);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ref.current) return;
|
||||||
|
const state = EditorState.create({
|
||||||
|
doc: initialContent,
|
||||||
|
extensions: [
|
||||||
|
lineNumbers(),
|
||||||
|
highlightActiveLine(),
|
||||||
|
highlightSelectionMatches(),
|
||||||
|
history(),
|
||||||
|
drawSelection(),
|
||||||
|
markdown({ base: markdownLanguage, codeLanguages: [] }),
|
||||||
|
autocompletion(),
|
||||||
|
keymap.of([...defaultKeymap, ...historyKeymap, ...searchKeymap, ...completionKeymap, indentWithTab]),
|
||||||
|
themeCompartment.current.of(resolvedTheme === 'dark' ? [oneDark] : [lightTheme, lightHighlight]),
|
||||||
|
EditorView.lineWrapping,
|
||||||
|
EditorView.updateListener.of((v) => {
|
||||||
|
if (v.docChanged) {
|
||||||
|
const content = v.state.doc.toString();
|
||||||
|
updateContent(bufferId, content);
|
||||||
|
onChange?.(content);
|
||||||
|
}
|
||||||
|
if (v.selectionSet || v.docChanged) {
|
||||||
|
const head = v.state.selection.main.head;
|
||||||
|
const line = v.state.doc.lineAt(head);
|
||||||
|
const lineNo = line.number;
|
||||||
|
const col = head - line.from + 1;
|
||||||
|
setCursor(bufferId, lineNo, col);
|
||||||
|
onCursorChange?.(lineNo, col);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const view = new EditorView({ state, parent: ref.current });
|
||||||
|
viewRef.current = view;
|
||||||
|
return () => {
|
||||||
|
view.destroy();
|
||||||
|
viewRef.current = null;
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [bufferId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const view = viewRef.current;
|
||||||
|
if (!view) return;
|
||||||
|
view.dispatch({
|
||||||
|
effects: themeCompartment.current.reconfigure(
|
||||||
|
resolvedTheme === 'dark' ? [oneDark] : [lightTheme, lightHighlight]
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}, [resolvedTheme]);
|
||||||
|
|
||||||
|
return <div ref={ref} className="h-full overflow-hidden" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { CodeMirrorEditor } from './CodeMirrorEditor';
|
||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
import { usePreviewStore } from '@/stores/preview-store';
|
||||||
|
|
||||||
|
export function EditorPane() {
|
||||||
|
const { buffers, activeId } = useEditorStore();
|
||||||
|
const buf = activeId ? buffers.get(activeId) : null;
|
||||||
|
const setPreviewSource = usePreviewStore((s) => s.setSource);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (buf) setPreviewSource(buf.content);
|
||||||
|
}, [buf?.id, buf?.content, buf, setPreviewSource]);
|
||||||
|
|
||||||
|
if (!buf) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full items-center justify-center bg-background text-muted-foreground">
|
||||||
|
<p>No file open. Use File → Open to start.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-full">
|
||||||
|
<CodeMirrorEditor
|
||||||
|
key={buf.id}
|
||||||
|
bufferId={buf.id}
|
||||||
|
initialContent={buf.content}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { EditorView } from '@codemirror/view';
|
||||||
|
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
|
||||||
|
import { tags as t } from '@lezer/highlight';
|
||||||
|
|
||||||
|
const colors = {
|
||||||
|
background: '#ffffff',
|
||||||
|
foreground: '#0d0b09',
|
||||||
|
cursor: '#e5461f',
|
||||||
|
selection: 'rgba(229, 70, 31, 0.15)',
|
||||||
|
gutterBackground: '#fafbfc',
|
||||||
|
gutterForeground: '#7a7878',
|
||||||
|
lineHighlight: 'rgba(0, 0, 0, 0.04)',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const lightTheme = EditorView.theme(
|
||||||
|
{
|
||||||
|
'&': {
|
||||||
|
backgroundColor: colors.background,
|
||||||
|
color: colors.foreground,
|
||||||
|
height: '100%',
|
||||||
|
},
|
||||||
|
'.cm-content': {
|
||||||
|
caretColor: colors.cursor,
|
||||||
|
fontFamily: 'JetBrains Mono, Fira Code, monospace',
|
||||||
|
fontSize: '13.5px',
|
||||||
|
},
|
||||||
|
'.cm-cursor, .cm-dropCursor': { borderLeftColor: colors.cursor },
|
||||||
|
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {
|
||||||
|
backgroundColor: colors.selection,
|
||||||
|
},
|
||||||
|
'.cm-gutters': {
|
||||||
|
backgroundColor: colors.gutterBackground,
|
||||||
|
color: colors.gutterForeground,
|
||||||
|
border: 'none',
|
||||||
|
},
|
||||||
|
'.cm-activeLine': { backgroundColor: colors.lineHighlight },
|
||||||
|
'.cm-activeLineGutter': { backgroundColor: 'transparent', color: '#e5461f' },
|
||||||
|
},
|
||||||
|
{ dark: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const highlightStyle = HighlightStyle.define([
|
||||||
|
{ tag: t.heading1, color: '#0d0b09', fontWeight: '700' },
|
||||||
|
{ tag: t.heading2, color: '#0d0b09', fontWeight: '700' },
|
||||||
|
{ tag: t.heading3, color: '#464646', fontWeight: '600' },
|
||||||
|
{ tag: t.link, color: '#e5461f', textDecoration: 'underline' },
|
||||||
|
{ tag: t.url, color: '#e5461f' },
|
||||||
|
{ tag: t.emphasis, fontStyle: 'italic' },
|
||||||
|
{ tag: t.strong, fontWeight: '700' },
|
||||||
|
{ tag: t.monospace, color: '#c93a18' },
|
||||||
|
{ tag: t.list, color: '#0ea5e9' },
|
||||||
|
{ tag: t.quote, color: '#7a7878', fontStyle: 'italic' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const lightHighlight = syntaxHighlighting(highlightStyle);
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { PanelLeft, PanelRight, Keyboard, Settings, Info } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { ThemeToggle } from '@/components/theme-toggle';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useCommandStore } from '@/stores/command-store';
|
||||||
|
|
||||||
|
export function AppHeader() {
|
||||||
|
const { sidebarVisible, previewVisible } = useAppStore();
|
||||||
|
const dispatch = useCommandStore((s) => s.dispatch);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="flex h-14 items-center justify-between border-b border-border bg-card/40 px-4 backdrop-blur">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div
|
||||||
|
className="h-7 w-7 rounded-md bg-gradient-to-br from-brand to-brand-dark shadow-[var(--shadow-glow-brand)]"
|
||||||
|
aria-label="MarkdownConverter logo"
|
||||||
|
/>
|
||||||
|
<h1 className="font-display text-lg font-bold tracking-tight">MarkdownConverter</h1>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Toggle sidebar"
|
||||||
|
aria-pressed={sidebarVisible}
|
||||||
|
data-testid="header-toggle-sidebar"
|
||||||
|
onClick={() => dispatch('view.toggleSidebar')}
|
||||||
|
>
|
||||||
|
<PanelLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Toggle preview"
|
||||||
|
aria-pressed={previewVisible}
|
||||||
|
data-testid="header-toggle-preview"
|
||||||
|
onClick={() => dispatch('view.togglePreview')}
|
||||||
|
>
|
||||||
|
<PanelRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Keyboard shortcuts"
|
||||||
|
data-testid="header-shortcuts"
|
||||||
|
onClick={() => dispatch('shortcuts.show')}
|
||||||
|
>
|
||||||
|
<Keyboard className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Settings"
|
||||||
|
onClick={() => dispatch('settings.open')}
|
||||||
|
>
|
||||||
|
<Settings className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="About"
|
||||||
|
onClick={() => dispatch('help.about')}
|
||||||
|
>
|
||||||
|
<Info className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<ThemeToggle />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { AppHeader } from './AppHeader';
|
||||||
|
import { TabBar } from './TabBar';
|
||||||
|
import { Toolbar } from './Toolbar';
|
||||||
|
import { Breadcrumb } from './Breadcrumb';
|
||||||
|
import { StatusBar } from './StatusBar';
|
||||||
|
import { EditorPane } from '@/components/editor/EditorPane';
|
||||||
|
import { PreviewPane } from '@/components/preview/PreviewPane';
|
||||||
|
import { Sidebar } from '@/components/sidebar/Sidebar';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||||
|
import { useFileShortcuts } from '@/hooks/use-file-shortcuts';
|
||||||
|
import { useRestoreLastFolder } from '@/hooks/use-restore-last-folder';
|
||||||
|
import { useRegisterMenuCommands, useBridgeNativeMenu } from '@/lib/commands/register-menu-commands';
|
||||||
|
|
||||||
|
export function AppShell() {
|
||||||
|
useFileShortcuts();
|
||||||
|
useRestoreLastFolder();
|
||||||
|
useRegisterMenuCommands();
|
||||||
|
useBridgeNativeMenu();
|
||||||
|
const { sidebarVisible, previewVisible, paneSizes, setPaneSizes } = useAppStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||||
|
<AppHeader />
|
||||||
|
<TabBar />
|
||||||
|
<Toolbar />
|
||||||
|
<Breadcrumb />
|
||||||
|
<main className="flex-1 overflow-hidden">
|
||||||
|
<ResizablePanelGroup
|
||||||
|
direction="horizontal"
|
||||||
|
onLayout={(sizes) => setPaneSizes({ sidebar: sizes[0], editor: sizes[1], preview: sizes[2] })}
|
||||||
|
>
|
||||||
|
{sidebarVisible && (
|
||||||
|
<>
|
||||||
|
<ResizablePanel defaultSize={paneSizes.sidebar} minSize={15} maxSize={40}>
|
||||||
|
<aside className="h-full border-r border-border bg-card/10 p-3 text-sm text-muted-foreground">
|
||||||
|
<Sidebar />
|
||||||
|
</aside>
|
||||||
|
</ResizablePanel>
|
||||||
|
<ResizableHandle />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<ResizablePanel defaultSize={previewVisible ? paneSizes.editor : 100} minSize={20}>
|
||||||
|
<EditorPane />
|
||||||
|
</ResizablePanel>
|
||||||
|
{previewVisible && (
|
||||||
|
<>
|
||||||
|
<ResizableHandle />
|
||||||
|
<ResizablePanel defaultSize={paneSizes.preview} minSize={20}>
|
||||||
|
<PreviewPane />
|
||||||
|
</ResizablePanel>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ResizablePanelGroup>
|
||||||
|
</main>
|
||||||
|
<StatusBar />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export function Breadcrumb() {
|
||||||
|
return (
|
||||||
|
<nav aria-label="File path" className="flex h-7 items-center border-b border-border bg-card/10 px-3 text-xs text-muted-foreground">
|
||||||
|
<span>No file selected</span>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
|
||||||
|
function countWords(text: string): number {
|
||||||
|
return text.trim().length === 0 ? 0 : text.trim().split(/\s+/).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StatusBar() {
|
||||||
|
const { buffers, activeId } = useEditorStore();
|
||||||
|
const buf = activeId ? buffers.get(activeId) : null;
|
||||||
|
const wordCount = buf ? countWords(buf.content) : 0;
|
||||||
|
const cursor = buf?.cursor ?? { line: 1, column: 1 };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<footer className="flex h-7 items-center justify-between border-t border-border bg-card/20 px-3 text-xs text-muted-foreground">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<span>{wordCount} words</span>
|
||||||
|
<span>UTF-8</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<span>Ln {cursor.line}, Col {cursor.column}</span>
|
||||||
|
<span>Markdown</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { X } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
DndContext,
|
||||||
|
PointerSensor,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
closestCenter,
|
||||||
|
type DragEndEvent,
|
||||||
|
} from '@dnd-kit/core';
|
||||||
|
import {
|
||||||
|
SortableContext,
|
||||||
|
horizontalListSortingStrategy,
|
||||||
|
useSortable,
|
||||||
|
} from '@dnd-kit/sortable';
|
||||||
|
import { CSS } from '@dnd-kit/utilities';
|
||||||
|
import { useFileStore, type OpenTab } from '@/stores/file-store';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
function SortableTab({
|
||||||
|
tab,
|
||||||
|
isActive,
|
||||||
|
onSelect,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
tab: OpenTab;
|
||||||
|
isActive: boolean;
|
||||||
|
onSelect: (id: string) => void;
|
||||||
|
onClose: (id: string) => void;
|
||||||
|
}) {
|
||||||
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||||
|
id: tab.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const style = {
|
||||||
|
transform: CSS.Transform.toString(transform),
|
||||||
|
transition,
|
||||||
|
opacity: isDragging ? 0.5 : 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={setNodeRef}
|
||||||
|
style={style}
|
||||||
|
{...attributes}
|
||||||
|
{...listeners}
|
||||||
|
role="tab"
|
||||||
|
aria-selected={isActive}
|
||||||
|
aria-current={isActive ? 'page' : undefined}
|
||||||
|
data-testid={`tab-${tab.id}`}
|
||||||
|
className={cn(
|
||||||
|
'group flex h-full cursor-pointer select-none items-center gap-1 border-r border-border px-3 text-xs transition-colors',
|
||||||
|
isActive
|
||||||
|
? 'bg-accent text-accent-foreground'
|
||||||
|
: 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'
|
||||||
|
)}
|
||||||
|
onClick={() => onSelect(tab.id)}
|
||||||
|
>
|
||||||
|
{tab.dirty && (
|
||||||
|
<span
|
||||||
|
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
|
||||||
|
aria-label="Unsaved changes"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span className="max-w-[120px] truncate">{tab.title}</span>
|
||||||
|
<button
|
||||||
|
aria-label={`Close ${tab.title}`}
|
||||||
|
className="ml-1 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-muted-foreground/20 transition-opacity"
|
||||||
|
onPointerDown={(e) => e.stopPropagation()}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onClose(tab.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TabBar() {
|
||||||
|
const openTabs = useFileStore((s) => s.openTabs);
|
||||||
|
const activeTabId = useFileStore((s) => s.activeTabId);
|
||||||
|
const setActiveTab = useFileStore((s) => s.setActiveTab);
|
||||||
|
const closeTab = useFileStore((s) => s.closeTab);
|
||||||
|
const reorderTabs = useFileStore((s) => s.reorderTabs);
|
||||||
|
|
||||||
|
// Require a small drag distance before activating — so a click on the tab
|
||||||
|
// body still triggers `onClick` (dnd-kit's PointerSensor default is 0).
|
||||||
|
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
|
||||||
|
|
||||||
|
if (openTabs.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-9 items-center border-b border-border bg-card/20 px-3 text-xs text-muted-foreground">
|
||||||
|
<span>No files open</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDragEnd(e: DragEndEvent) {
|
||||||
|
const { active, over } = e;
|
||||||
|
if (!over || active.id === over.id) return;
|
||||||
|
const fromIndex = openTabs.findIndex((t) => t.id === active.id);
|
||||||
|
const toIndex = openTabs.findIndex((t) => t.id === over.id);
|
||||||
|
if (fromIndex === -1 || toIndex === -1) return;
|
||||||
|
reorderTabs(fromIndex, toIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-9 items-center border-b border-border bg-card/20 overflow-x-auto">
|
||||||
|
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||||
|
<SortableContext items={openTabs.map((t) => t.id)} strategy={horizontalListSortingStrategy}>
|
||||||
|
<div className="flex h-full items-center px-1">
|
||||||
|
{openTabs.map((tab) => (
|
||||||
|
<SortableTab
|
||||||
|
key={tab.id}
|
||||||
|
tab={tab}
|
||||||
|
isActive={tab.id === activeTabId}
|
||||||
|
onSelect={setActiveTab}
|
||||||
|
onClose={closeTab}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</SortableContext>
|
||||||
|
</DndContext>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { Bold, Italic, List, ListOrdered, Code, Link as LinkIcon, PanelLeft, PanelRight, Save, FolderOpen, FileText } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useCommandStore } from '@/stores/command-store';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
|
||||||
|
export function Toolbar() {
|
||||||
|
const dispatch = useCommandStore((s) => s.dispatch);
|
||||||
|
const { sidebarVisible, previewVisible } = useAppStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="toolbar"
|
||||||
|
aria-label="Main toolbar"
|
||||||
|
className="flex h-10 items-center gap-1 border-b border-border bg-card/10 px-3"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Open file"
|
||||||
|
data-testid="toolbar-open-file"
|
||||||
|
onClick={() => dispatch('file.open')}
|
||||||
|
>
|
||||||
|
<FileText className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Open folder"
|
||||||
|
data-testid="toolbar-open-folder"
|
||||||
|
onClick={() => dispatch('file.openFolder')}
|
||||||
|
>
|
||||||
|
<FolderOpen className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Save"
|
||||||
|
data-testid="toolbar-save"
|
||||||
|
onClick={() => dispatch('file.save')}
|
||||||
|
>
|
||||||
|
<Save className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className="mx-1 h-5 w-px bg-border" aria-hidden="true" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Toggle sidebar"
|
||||||
|
aria-pressed={sidebarVisible}
|
||||||
|
data-testid="toolbar-toggle-sidebar"
|
||||||
|
onClick={() => dispatch('view.toggleSidebar')}
|
||||||
|
>
|
||||||
|
<PanelLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Toggle preview"
|
||||||
|
aria-pressed={previewVisible}
|
||||||
|
data-testid="toolbar-toggle-preview"
|
||||||
|
onClick={() => dispatch('view.togglePreview')}
|
||||||
|
>
|
||||||
|
<PanelRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className="mx-1 h-5 w-px bg-border" aria-hidden="true" />
|
||||||
|
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Bold" disabled><Bold className="h-4 w-4" /></Button>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Italic" disabled><Italic className="h-4 w-4" /></Button>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Unordered list" disabled><List className="h-4 w-4" /></Button>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Ordered list" disabled><ListOrdered className="h-4 w-4" /></Button>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Code" disabled><Code className="h-4 w-4" /></Button>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Link" disabled><LinkIcon className="h-4 w-4" /></Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
|
||||||
|
export function AboutDialog() {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const isOpen = useAppStore((s) => s.modal.kind) === 'about';
|
||||||
|
const [version, setVersion] = useState<string>('…');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
ipc.app.getVersion().then((r) => {
|
||||||
|
if (r.ok && typeof r.data === 'string') setVersion(r.data);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={isOpen} onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="about-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>About MarkdownConverter</DialogTitle>
|
||||||
|
<DialogDescription id="about-desc">
|
||||||
|
Professional Markdown editor and universal file converter.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-2 text-sm text-muted-foreground">
|
||||||
|
<p>Version: {version}</p>
|
||||||
|
<p>
|
||||||
|
<a
|
||||||
|
href="https://github.com/amitwh/markdown-converter"
|
||||||
|
className="text-brand hover:underline"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
ipc.app.openExternal('https://github.com/amitwh/markdown-converter');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
GitHub repository
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p className="text-xs">© ConcreteInfo. Licensed under MIT.</p>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button onClick={closeModal}>Close</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
|
||||||
|
export function AboutSettings() {
|
||||||
|
const [version, setVersion] = useState('…');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
ipc.app.getVersion().then((r) => {
|
||||||
|
if (r.ok && typeof r.data === 'string') setVersion(r.data);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<h3 className="text-base font-semibold">MarkdownConverter</h3>
|
||||||
|
<p className="text-muted-foreground">Version {version}</p>
|
||||||
|
<p>
|
||||||
|
<a
|
||||||
|
href="https://github.com/amitwh/markdown-converter"
|
||||||
|
className="text-brand hover:underline"
|
||||||
|
onClick={(e) => { e.preventDefault(); ipc.app.openExternal('https://github.com/amitwh/markdown-converter'); }}
|
||||||
|
>
|
||||||
|
GitHub repository
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<a
|
||||||
|
href="https://concreteinfo.co.in"
|
||||||
|
className="text-brand hover:underline"
|
||||||
|
onClick={(e) => { e.preventDefault(); ipc.app.openExternal('https://concreteinfo.co.in'); }}
|
||||||
|
>
|
||||||
|
ConcreteInfo
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">© ConcreteInfo. Licensed under MIT.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useAppStore, type ConfirmProps } from '@/stores/app-store';
|
||||||
|
|
||||||
|
export function ConfirmDialog(props: ConfirmProps) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const { title, body, confirmLabel = 'Confirm', cancelLabel = 'Cancel', destructive, onConfirm, onCancel } = props;
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
await onConfirm();
|
||||||
|
closeModal();
|
||||||
|
};
|
||||||
|
const handleCancel = () => {
|
||||||
|
onCancel?.();
|
||||||
|
closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && handleCancel()}>
|
||||||
|
<DialogContent aria-describedby="confirm-body">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
<DialogDescription id="confirm-body">{body}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="ghost" onClick={handleCancel}>
|
||||||
|
{cancelLabel}
|
||||||
|
</Button>
|
||||||
|
<Button variant={destructive ? 'destructive' : 'default'} onClick={handleConfirm}>
|
||||||
|
{confirmLabel}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Slider } from '@/components/ui/slider';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
|
||||||
|
export function EditorSettings() {
|
||||||
|
const { fontSize, tabSize, lineNumbers, wordWrap, minimap, setSetting } = useSettingsStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="editor-font-size">Font size: {fontSize}px</Label>
|
||||||
|
<Slider id="editor-font-size" min={10} max={24} step={1} value={[fontSize]} onValueChange={([v]) => setSetting('fontSize', v)} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="editor-tab-size">Tab size</Label>
|
||||||
|
<Select value={String(tabSize)} onValueChange={(v) => setSetting('tabSize', Number(v) as 2 | 4 | 8)}>
|
||||||
|
<SelectTrigger id="editor-tab-size" aria-label="Tab size"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="2">2 spaces</SelectItem>
|
||||||
|
<SelectItem value="4">4 spaces</SelectItem>
|
||||||
|
<SelectItem value="8">8 spaces</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center justify-between">
|
||||||
|
<span>Line numbers</span>
|
||||||
|
<Switch checked={lineNumbers} onCheckedChange={(c) => setSetting('lineNumbers', c)} aria-label="Line numbers" />
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center justify-between">
|
||||||
|
<span>Word wrap</span>
|
||||||
|
<Switch checked={wordWrap} onCheckedChange={(c) => setSetting('wordWrap', c)} aria-label="Word wrap" />
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center justify-between">
|
||||||
|
<span>Minimap</span>
|
||||||
|
<Switch checked={minimap} onCheckedChange={(c) => setSetting('minimap', c)} aria-label="Minimap" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { ExportDialogFooter } from './ExportDialogFooter';
|
||||||
|
|
||||||
|
const extFor = (format: 'pdf' | 'docx' | 'html' | 'png') =>
|
||||||
|
format === 'pdf' ? '.pdf' : format === 'docx' ? '.docx' : format === 'png' ? '.png' : '.html';
|
||||||
|
|
||||||
|
export function ExportBatchDialog({ sourcePaths }: { sourcePaths: string[] }) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const [format, setFormat] = useState<'pdf' | 'docx' | 'html' | 'png'>('pdf');
|
||||||
|
const [concurrency, setConcurrency] = useState(4);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
const items = sourcePaths.map((p) => ({
|
||||||
|
inputPath: p,
|
||||||
|
outputPath: p.replace(/\.md$/, extFor(format)),
|
||||||
|
}));
|
||||||
|
const result = await ipc.export.batch(items, { format, concurrency });
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Export failed: ${result.error.message}`);
|
||||||
|
setError(result.error.message);
|
||||||
|
setSubmitting(false);
|
||||||
|
} else {
|
||||||
|
toast.success(`Exported ${sourcePaths.length} files`);
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="batch-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Batch export</DialogTitle>
|
||||||
|
<DialogDescription id="batch-desc">{sourcePaths.length} files</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="batch-format">Format</Label>
|
||||||
|
<Select value={format} onValueChange={(v) => setFormat(v as any)}>
|
||||||
|
<SelectTrigger id="batch-format" aria-label="Format"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="pdf">PDF</SelectItem>
|
||||||
|
<SelectItem value="docx">DOCX</SelectItem>
|
||||||
|
<SelectItem value="html">HTML</SelectItem>
|
||||||
|
<SelectItem value="png">PNG</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="batch-concurrency">Concurrency</Label>
|
||||||
|
<Select value={String(concurrency)} onValueChange={(v) => setConcurrency(Number(v))}>
|
||||||
|
<SelectTrigger id="batch-concurrency" aria-label="Concurrency"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{[1, 2, 4, 8, 16].map((n) => (
|
||||||
|
<SelectItem key={n} value={String(n)}>{n}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-40 overflow-auto rounded border border-border bg-card/20 p-2 text-xs">
|
||||||
|
{sourcePaths.map((p) => <div key={p} className="truncate">{p}</div>)}
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ExportDialogFooter onCancel={closeModal} onSubmit={handleSubmit} submitting={submitting} submitLabel="Export" />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { DialogFooter } from '@/components/ui/dialog';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
onCancel: () => void;
|
||||||
|
onSubmit: () => void;
|
||||||
|
submitting: boolean;
|
||||||
|
submitLabel: string;
|
||||||
|
submitDisabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExportDialogFooter({ onCancel, onSubmit, submitting, submitLabel, submitDisabled }: Props) {
|
||||||
|
return (
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="ghost" onClick={onCancel} disabled={submitting}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={onSubmit} disabled={submitting || submitDisabled}>
|
||||||
|
{submitting ? 'Exporting…' : submitLabel}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { useExportSource } from '@/hooks/use-export-source';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { ExportDialogFooter } from './ExportDialogFooter';
|
||||||
|
|
||||||
|
export function ExportDocxDialog({ sourcePath }: { sourcePath: string }) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const { docxTemplate, renderTablesAsAscii } = useSettingsStore();
|
||||||
|
const source = useExportSource();
|
||||||
|
const [template, setTemplate] = useState<'standard' | 'minimal' | 'modern'>(docxTemplate);
|
||||||
|
const [ascii, setAscii] = useState(renderTablesAsAscii);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!source) { setError('No file open.'); return; }
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
const result = await ipc.export.docx({
|
||||||
|
inputPath: source.path,
|
||||||
|
outputPath: source.path.replace(/\.md$/, '.docx'),
|
||||||
|
template,
|
||||||
|
renderTablesAsAscii: ascii,
|
||||||
|
} as any);
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Export failed: ${result.error.message}`);
|
||||||
|
setError(result.error.message);
|
||||||
|
setSubmitting(false);
|
||||||
|
} else {
|
||||||
|
toast.success(`Exported ${source.title} to ${result.data?.outputPath ?? 'file'}`);
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="docx-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Export to DOCX</DialogTitle>
|
||||||
|
<DialogDescription id="docx-desc">{sourcePath}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="docx-template">Template</Label>
|
||||||
|
<Select value={template} onValueChange={(v) => setTemplate(v as any)}>
|
||||||
|
<SelectTrigger id="docx-template" aria-label="Template"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="standard">Standard</SelectItem>
|
||||||
|
<SelectItem value="minimal">Minimal</SelectItem>
|
||||||
|
<SelectItem value="modern">Modern</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
Bundled with the app. Standard is the default; Modern adds a colored cover page.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<Checkbox checked={ascii} onCheckedChange={(c) => setAscii(!!c)} aria-label="ASCII tables" />
|
||||||
|
Render tables as ASCII
|
||||||
|
</label>
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ExportDialogFooter onCancel={closeModal} onSubmit={handleSubmit} submitting={submitting} submitLabel="Export" />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { useExportSource } from '@/hooks/use-export-source';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { ExportDialogFooter } from './ExportDialogFooter';
|
||||||
|
|
||||||
|
export function ExportHtmlDialog({ sourcePath }: { sourcePath: string }) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const { htmlHighlightStyle, renderTablesAsAscii } = useSettingsStore();
|
||||||
|
const source = useExportSource();
|
||||||
|
const [standalone, setStandalone] = useState(true);
|
||||||
|
const [highlight, setHighlight] = useState(htmlHighlightStyle);
|
||||||
|
const [ascii, setAscii] = useState(renderTablesAsAscii);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!source) { setError('No file open.'); return; }
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
const result = await ipc.export.html({
|
||||||
|
inputPath: source.path,
|
||||||
|
outputPath: source.path.replace(/\.md$/, '.html'),
|
||||||
|
standalone,
|
||||||
|
highlightStyle: highlight,
|
||||||
|
renderTablesAsAscii: ascii,
|
||||||
|
} as any);
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Export failed: ${result.error.message}`);
|
||||||
|
setError(result.error.message);
|
||||||
|
setSubmitting(false);
|
||||||
|
} else {
|
||||||
|
toast.success(`Exported ${source.title} to ${result.data?.outputPath ?? 'file'}`);
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="html-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Export to HTML</DialogTitle>
|
||||||
|
<DialogDescription id="html-desc">{sourcePath}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<Checkbox checked={standalone} onCheckedChange={(c) => setStandalone(!!c)} aria-label="Standalone" />
|
||||||
|
Standalone document (with inline CSS)
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="html-highlight">Syntax highlight style</Label>
|
||||||
|
<Select value={highlight} onValueChange={(v) => setHighlight(v as any)}>
|
||||||
|
<SelectTrigger id="html-highlight" aria-label="Highlight style"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="github">GitHub</SelectItem>
|
||||||
|
<SelectItem value="monokai">Monokai</SelectItem>
|
||||||
|
<SelectItem value="nord">Nord</SelectItem>
|
||||||
|
<SelectItem value="none">None</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<Checkbox checked={ascii} onCheckedChange={(c) => setAscii(!!c)} aria-label="ASCII tables" />
|
||||||
|
Render tables as ASCII
|
||||||
|
</label>
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ExportDialogFooter onCancel={closeModal} onSubmit={handleSubmit} submitting={submitting} submitLabel="Export" />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { useExportSource } from '@/hooks/use-export-source';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { ExportDialogFooter } from './ExportDialogFooter';
|
||||||
|
|
||||||
|
const MARGIN_MAP = {
|
||||||
|
normal: { top: 25, right: 25, bottom: 25, left: 25 },
|
||||||
|
narrow: { top: 15, right: 15, bottom: 15, left: 15 },
|
||||||
|
wide: { top: 35, right: 35, bottom: 35, left: 35 },
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function ExportPdfDialog({ sourcePath }: { sourcePath: string }) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const { fontSize, pdfFormat, pdfMargins, pdfEmbedFonts, renderTablesAsAscii } = useSettingsStore();
|
||||||
|
const [format, setFormat] = useState<'letter' | 'a4' | 'legal'>(pdfFormat);
|
||||||
|
const [margins, setMargins] = useState<'normal' | 'narrow' | 'wide'>(pdfMargins);
|
||||||
|
const [embed, setEmbed] = useState(pdfEmbedFonts);
|
||||||
|
const [ascii, setAscii] = useState(renderTablesAsAscii);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const source = useExportSource();
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!source) {
|
||||||
|
setError('No file open.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
const result = await ipc.export.pdf({
|
||||||
|
inputPath: source.path,
|
||||||
|
outputPath: source.path.replace(/\.md$/, '.pdf'),
|
||||||
|
format,
|
||||||
|
margins: MARGIN_MAP[margins],
|
||||||
|
embedFonts: embed,
|
||||||
|
renderTablesAsAscii: ascii,
|
||||||
|
fontSize,
|
||||||
|
} as any);
|
||||||
|
if (!result.ok) {
|
||||||
|
toast.error(`Export failed: ${result.error?.message ?? 'Export failed'}`);
|
||||||
|
setError(result.error?.message ?? 'Export failed');
|
||||||
|
setSubmitting(false);
|
||||||
|
} else {
|
||||||
|
toast.success(`Exported ${source.title} to ${result.data?.outputPath ?? 'file'}`);
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="pdf-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Export to PDF</DialogTitle>
|
||||||
|
<DialogDescription id="pdf-desc">{sourcePath}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="pdf-format">Format</Label>
|
||||||
|
<Select value={format} onValueChange={(v) => setFormat(v as typeof format)}>
|
||||||
|
<SelectTrigger id="pdf-format" aria-label="Format"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="letter">Letter</SelectItem>
|
||||||
|
<SelectItem value="a4">A4</SelectItem>
|
||||||
|
<SelectItem value="legal">Legal</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="pdf-margins">Margins</Label>
|
||||||
|
<Select value={margins} onValueChange={(v) => setMargins(v as typeof margins)}>
|
||||||
|
<SelectTrigger id="pdf-margins" aria-label="Margins"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="narrow">Narrow</SelectItem>
|
||||||
|
<SelectItem value="normal">Normal</SelectItem>
|
||||||
|
<SelectItem value="wide">Wide</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<Checkbox checked={embed} onCheckedChange={(c) => setEmbed(!!c)} aria-label="Embed fonts" />
|
||||||
|
Embed fonts
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<Checkbox checked={ascii} onCheckedChange={(c) => setAscii(!!c)} aria-label="ASCII tables" />
|
||||||
|
Render tables as ASCII
|
||||||
|
</label>
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ExportDialogFooter onCancel={closeModal} onSubmit={handleSubmit} submitting={submitting} submitLabel="Export" />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
|
||||||
|
export function ExportSettings() {
|
||||||
|
const { pdfFormat, pdfMargins, pdfEmbedFonts, docxTemplate, htmlHighlightStyle, renderTablesAsAscii, setSetting } = useSettingsStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="export-pdf-format">Default PDF format</Label>
|
||||||
|
<Select value={pdfFormat} onValueChange={(v) => setSetting('pdfFormat', v as any)}>
|
||||||
|
<SelectTrigger id="export-pdf-format" aria-label="Default PDF format"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="letter">Letter</SelectItem>
|
||||||
|
<SelectItem value="a4">A4</SelectItem>
|
||||||
|
<SelectItem value="legal">Legal</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="export-pdf-margins">Default PDF margins</Label>
|
||||||
|
<Select value={pdfMargins} onValueChange={(v) => setSetting('pdfMargins', v as any)}>
|
||||||
|
<SelectTrigger id="export-pdf-margins" aria-label="Default PDF margins"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="narrow">Narrow</SelectItem>
|
||||||
|
<SelectItem value="normal">Normal</SelectItem>
|
||||||
|
<SelectItem value="wide">Wide</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center justify-between">
|
||||||
|
<span>Embed fonts in PDFs</span>
|
||||||
|
<Switch checked={pdfEmbedFonts} onCheckedChange={(c) => setSetting('pdfEmbedFonts', c)} aria-label="Embed fonts" />
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="export-docx-template">Default DOCX template</Label>
|
||||||
|
<Select value={docxTemplate} onValueChange={(v) => setSetting('docxTemplate', v as any)}>
|
||||||
|
<SelectTrigger id="export-docx-template" aria-label="Default DOCX template"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="standard">Standard</SelectItem>
|
||||||
|
<SelectItem value="minimal">Minimal</SelectItem>
|
||||||
|
<SelectItem value="modern">Modern</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="export-html-highlight">Default HTML highlight</Label>
|
||||||
|
<Select value={htmlHighlightStyle} onValueChange={(v) => setSetting('htmlHighlightStyle', v as any)}>
|
||||||
|
<SelectTrigger id="export-html-highlight" aria-label="Default HTML highlight"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="github">GitHub</SelectItem>
|
||||||
|
<SelectItem value="monokai">Monokai</SelectItem>
|
||||||
|
<SelectItem value="nord">Nord</SelectItem>
|
||||||
|
<SelectItem value="none">None</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center justify-between">
|
||||||
|
<span>Render tables as ASCII by default</span>
|
||||||
|
<Switch checked={renderTablesAsAscii} onCheckedChange={(c) => setSetting('renderTablesAsAscii', c)} aria-label="ASCII tables by default" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { AboutDialog } from './AboutDialog';
|
||||||
|
import { ConfirmDialog } from './ConfirmDialog';
|
||||||
|
import { ExportBatchDialog } from './ExportBatchDialog';
|
||||||
|
import { ExportDocxDialog } from './ExportDocxDialog';
|
||||||
|
import { ExportHtmlDialog } from './ExportHtmlDialog';
|
||||||
|
import { ExportPdfDialog } from './ExportPdfDialog';
|
||||||
|
import { SettingsSheet } from './SettingsSheet';
|
||||||
|
import { WelcomeDialog } from './WelcomeDialog';
|
||||||
|
|
||||||
|
export function ModalLayer() {
|
||||||
|
const modal = useAppStore((s) => s.modal);
|
||||||
|
switch (modal.kind) {
|
||||||
|
case null:
|
||||||
|
return null;
|
||||||
|
case 'export-pdf':
|
||||||
|
return <ExportPdfDialog sourcePath={modal.props.sourcePath} />;
|
||||||
|
case 'export-docx':
|
||||||
|
return <ExportDocxDialog sourcePath={modal.props.sourcePath} />;
|
||||||
|
case 'export-html':
|
||||||
|
return <ExportHtmlDialog sourcePath={modal.props.sourcePath} />;
|
||||||
|
case 'export-batch':
|
||||||
|
return <ExportBatchDialog sourcePaths={modal.props.sourcePaths} />;
|
||||||
|
case 'settings':
|
||||||
|
return <SettingsSheet />;
|
||||||
|
case 'about':
|
||||||
|
return <AboutDialog />;
|
||||||
|
case 'welcome':
|
||||||
|
return <WelcomeDialog />;
|
||||||
|
case 'confirm':
|
||||||
|
return <ConfirmDialog {...modal.props} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Sparkles } from 'lucide-react';
|
||||||
|
|
||||||
|
export function PluginsSettings() {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-3 py-12 text-center text-muted-foreground">
|
||||||
|
<Sparkles className="h-8 w-8 opacity-50" />
|
||||||
|
<h3 className="text-base font-semibold text-foreground">Coming soon</h3>
|
||||||
|
<p className="max-w-sm text-sm">
|
||||||
|
The plugin system is on the roadmap. You'll be able to extend MarkdownConverter with custom
|
||||||
|
commands, themes, and export formats.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { EditorSettings } from './EditorSettings';
|
||||||
|
import { ThemeSettings } from './ThemeSettings';
|
||||||
|
import { ExportSettings } from './ExportSettings';
|
||||||
|
import { PluginsSettings } from './PluginsSettings';
|
||||||
|
import { AboutSettings } from './AboutSettings';
|
||||||
|
|
||||||
|
export function SettingsSheet() {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const resetToDefaults = useSettingsStore((s) => s.resetToDefaults);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<SheetContent aria-describedby="settings-desc" side="right" className="w-full sm:max-w-[480px]">
|
||||||
|
<SheetHeader>
|
||||||
|
<SheetTitle>Settings</SheetTitle>
|
||||||
|
<SheetDescription id="settings-desc">Editor, theme, and export preferences</SheetDescription>
|
||||||
|
</SheetHeader>
|
||||||
|
<Tabs defaultValue="editor" className="mt-4">
|
||||||
|
<TabsList className="grid w-full grid-cols-5">
|
||||||
|
<TabsTrigger value="editor">Editor</TabsTrigger>
|
||||||
|
<TabsTrigger value="theme">Theme</TabsTrigger>
|
||||||
|
<TabsTrigger value="export">Export</TabsTrigger>
|
||||||
|
<TabsTrigger value="plugins">Plugins</TabsTrigger>
|
||||||
|
<TabsTrigger value="about">About</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<div className="mt-4 max-h-[70vh] overflow-y-auto pr-2">
|
||||||
|
<TabsContent value="editor"><EditorSettings /></TabsContent>
|
||||||
|
<TabsContent value="theme"><ThemeSettings /></TabsContent>
|
||||||
|
<TabsContent value="export"><ExportSettings /></TabsContent>
|
||||||
|
<TabsContent value="plugins"><PluginsSettings /></TabsContent>
|
||||||
|
<TabsContent value="about"><AboutSettings /></TabsContent>
|
||||||
|
</div>
|
||||||
|
</Tabs>
|
||||||
|
<div className="mt-4 flex justify-end border-t border-border pt-4">
|
||||||
|
<Button variant="ghost" onClick={resetToDefaults}>Reset to defaults</Button>
|
||||||
|
</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
|
||||||
|
export function ThemeSettings() {
|
||||||
|
const { theme, accentColor, fontFamily, setSetting } = useSettingsStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label>Mode</Label>
|
||||||
|
<RadioGroup value={theme} onValueChange={(v) => setSetting('theme', v as 'light' | 'dark' | 'auto')}>
|
||||||
|
<div className="flex items-center gap-2"><RadioGroupItem value="light" id="theme-light" /><Label htmlFor="theme-light">Light</Label></div>
|
||||||
|
<div className="flex items-center gap-2"><RadioGroupItem value="dark" id="theme-dark" /><Label htmlFor="theme-dark">Dark</Label></div>
|
||||||
|
<div className="flex items-center gap-2"><RadioGroupItem value="auto" id="theme-auto" /><Label htmlFor="theme-auto">Auto (system)</Label></div>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="theme-accent">Accent color</Label>
|
||||||
|
<Select value={accentColor} onValueChange={(v) => setSetting('accentColor', v as any)}>
|
||||||
|
<SelectTrigger id="theme-accent" aria-label="Accent color"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="brand">Brand (orange)</SelectItem>
|
||||||
|
<SelectItem value="blue">Blue</SelectItem>
|
||||||
|
<SelectItem value="green">Green</SelectItem>
|
||||||
|
<SelectItem value="purple">Purple</SelectItem>
|
||||||
|
<SelectItem value="orange">Orange</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="theme-font-family">Editor font</Label>
|
||||||
|
<Select value={fontFamily} onValueChange={(v) => setSetting('fontFamily', v as any)}>
|
||||||
|
<SelectTrigger id="theme-font-family" aria-label="Editor font"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="system">System (Plus Jakarta Sans)</SelectItem>
|
||||||
|
<SelectItem value="jetbrains">JetBrains Mono</SelectItem>
|
||||||
|
<SelectItem value="fira">Fira Code</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
|
||||||
|
export function WelcomeDialog() {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const setSetting = useSettingsStore((s) => s.setSetting);
|
||||||
|
const [dontShow, setDontShow] = useState(false);
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
if (dontShow) setSetting('welcomeDismissed', true);
|
||||||
|
closeModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && handleClose()}>
|
||||||
|
<DialogContent aria-describedby="welcome-desc" className="max-w-xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Welcome to MarkdownConverter</DialogTitle>
|
||||||
|
<DialogDescription id="welcome-desc">
|
||||||
|
A polished editor for Markdown, with PDF, DOCX, and HTML export.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div className="rounded-md border border-border bg-card/30 p-3">
|
||||||
|
<h3 className="font-semibold">1. Open a folder</h3>
|
||||||
|
<p className="text-muted-foreground">File → Open Folder, or ⌘O. Your tree appears on the left.</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-md border border-border bg-card/30 p-3">
|
||||||
|
<h3 className="font-semibold">2. Edit & preview</h3>
|
||||||
|
<p className="text-muted-foreground">Type on the left, see the rendered preview on the right. Toggle with ⌘\.</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-md border border-border bg-card/30 p-3">
|
||||||
|
<h3 className="font-semibold">3. Export anywhere</h3>
|
||||||
|
<p className="text-muted-foreground">File → Export to PDF / DOCX / HTML, or batch convert a folder.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter className="flex-row items-center justify-between sm:justify-between">
|
||||||
|
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<Checkbox checked={dontShow} onCheckedChange={(c) => setDontShow(!!c)} aria-label="Don't show again" />
|
||||||
|
Don't show again
|
||||||
|
</label>
|
||||||
|
<Button onClick={handleClose}>Get started</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { renderMarkdown } from '@/lib/markdown';
|
||||||
|
import { MermaidLazy } from './MermaidLazy';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
source: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MERMAID_RE = /```mermaid\n([\s\S]*?)```/g;
|
||||||
|
|
||||||
|
function extractMermaidCodes(source: string): string[] {
|
||||||
|
const codes: string[] = [];
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
while ((match = MERMAID_RE.exec(source)) !== null) {
|
||||||
|
codes.push(match[1].trim());
|
||||||
|
}
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MarkdownRenderer({ source }: Props) {
|
||||||
|
const html = renderMarkdown(source);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [mermaidCodes, setMermaidCodes] = useState<string[]>([]);
|
||||||
|
|
||||||
|
// Re-derive mermaid codes from the original source. The renderMarkdown function
|
||||||
|
// replaces mermaid blocks with placeholders (data-mermaid-source="${idx}"), but
|
||||||
|
// it does not return the actual codes. Rather than thread them through the API,
|
||||||
|
// we re-extract from the source. Source is small (single buffer content) so this
|
||||||
|
// cost is negligible.
|
||||||
|
useEffect(() => {
|
||||||
|
setMermaidCodes(extractMermaidCodes(source));
|
||||||
|
}, [source]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="prose prose-neutral dark:prose-invert max-w-none p-6" ref={containerRef}>
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: html }} />
|
||||||
|
{mermaidCodes.map((code, i) => (
|
||||||
|
<div key={i} className="my-4">
|
||||||
|
<MermaidLazy code={code} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mermaidModule: typeof import('mermaid').default | null = null;
|
||||||
|
let initialized = false;
|
||||||
|
|
||||||
|
async function getMermaid() {
|
||||||
|
if (!mermaidModule) {
|
||||||
|
const mod = await import('mermaid');
|
||||||
|
mermaidModule = mod.default;
|
||||||
|
}
|
||||||
|
if (!initialized) {
|
||||||
|
mermaidModule.initialize({ startOnLoad: false, theme: 'default' });
|
||||||
|
initialized = true;
|
||||||
|
}
|
||||||
|
return mermaidModule;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MermaidLazy({ code }: Props) {
|
||||||
|
const [svg, setSvg] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const idRef = useRef(`mermaid-${Math.random().toString(36).slice(2)}`);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
getMermaid()
|
||||||
|
.then((m) => m.render(idRef.current, code))
|
||||||
|
.then((rendered) => {
|
||||||
|
if (!cancelled) setSvg(rendered);
|
||||||
|
})
|
||||||
|
.catch((err: Error) => {
|
||||||
|
if (!cancelled) setError(err.message);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [code]);
|
||||||
|
|
||||||
|
if (error) return <div className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">{error}</div>;
|
||||||
|
if (!svg) return <div className="text-xs text-muted-foreground">Loading diagram…</div>;
|
||||||
|
return <div data-testid="mermaid-output" dangerouslySetInnerHTML={{ __html: svg }} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { MarkdownRenderer } from './MarkdownRenderer';
|
||||||
|
import { usePreviewStore } from '@/stores/preview-store';
|
||||||
|
import { useScrollSync } from '@/hooks/use-scroll-sync';
|
||||||
|
|
||||||
|
export function PreviewPane() {
|
||||||
|
const { source, setScrollRatio } = usePreviewStore();
|
||||||
|
const { handlePreviewScroll } = useScrollSync({ onPreviewScroll: setScrollRatio });
|
||||||
|
|
||||||
|
if (!source) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full items-center justify-center text-muted-foreground">
|
||||||
|
<p>Nothing to preview. Start typing in the editor.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-full overflow-auto bg-card/10" onScroll={handlePreviewScroll}>
|
||||||
|
<MarkdownRenderer source={source} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { ChevronRight, Folder, FolderOpen, File, FileText } from 'lucide-react';
|
||||||
|
import { useFileStore } from '@/stores/file-store';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
function FileTreeNode({ node, depth }: { node: import('@/stores/file-store').FileNode; depth: number }) {
|
||||||
|
const { expanded, activeTabId, loadChildren, toggleExpanded, openFile } = useFileStore();
|
||||||
|
const isExpanded = expanded.has(node.path);
|
||||||
|
const isActive = activeTabId === node.path;
|
||||||
|
|
||||||
|
if (node.isDirectory) {
|
||||||
|
const handleClick = async () => {
|
||||||
|
if (!node.loaded) {
|
||||||
|
await loadChildren(node.path);
|
||||||
|
}
|
||||||
|
toggleExpanded(node.path);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={handleClick}
|
||||||
|
className={cn(
|
||||||
|
'flex w-full items-center gap-1 rounded px-1 py-0.5 text-left text-xs hover:bg-accent',
|
||||||
|
isActive && 'bg-accent'
|
||||||
|
)}
|
||||||
|
style={{ paddingLeft: `${depth * 16 + 4}px` }}
|
||||||
|
>
|
||||||
|
<ChevronRight
|
||||||
|
size={12}
|
||||||
|
className={cn('transition-transform duration-150', isExpanded && 'rotate-90')}
|
||||||
|
/>
|
||||||
|
{isExpanded ? <FolderOpen size={14} /> : <Folder size={14} />}
|
||||||
|
<span className="truncate">{node.name}</span>
|
||||||
|
</button>
|
||||||
|
{isExpanded && node.loaded && node.children && (
|
||||||
|
<div>
|
||||||
|
{node.children.map((child) => (
|
||||||
|
<FileTreeNode key={child.path} node={child} depth={depth + 1} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={() => openFile(node.path)}
|
||||||
|
className={cn(
|
||||||
|
'flex w-full items-center gap-1 rounded px-1 py-0.5 text-left text-xs hover:bg-accent',
|
||||||
|
isActive && 'bg-accent text-accent-foreground'
|
||||||
|
)}
|
||||||
|
style={{ paddingLeft: `${depth * 16 + 4}px` }}
|
||||||
|
>
|
||||||
|
<FileText size={14} />
|
||||||
|
<span className="truncate">{node.name}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FileTree() {
|
||||||
|
const tree = useFileStore((s) => s.tree);
|
||||||
|
|
||||||
|
if (!tree) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="py-1">
|
||||||
|
{tree.children?.map((child) => (
|
||||||
|
<FileTreeNode key={child.path} node={child} depth={0} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
|
||||||
|
const HEADING_RE = /^(#{1,6})\s+(.+)$/gm;
|
||||||
|
|
||||||
|
interface HeadingItem {
|
||||||
|
level: number;
|
||||||
|
text: string;
|
||||||
|
line: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractHeadings(content: string): HeadingItem[] {
|
||||||
|
const headings: HeadingItem[] = [];
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
const re = new RegExp(HEADING_RE.source, 'gm');
|
||||||
|
let lineNum = 1;
|
||||||
|
for (const line of content.split('\n')) {
|
||||||
|
re.lastIndex = 0;
|
||||||
|
match = re.exec(line);
|
||||||
|
if (match) {
|
||||||
|
headings.push({
|
||||||
|
level: match[1].length,
|
||||||
|
text: match[2].trim(),
|
||||||
|
line: lineNum,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
lineNum++;
|
||||||
|
}
|
||||||
|
return headings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Outline() {
|
||||||
|
const activeId = useEditorStore((s) => s.activeId);
|
||||||
|
const buffers = useEditorStore((s) => s.buffers);
|
||||||
|
|
||||||
|
if (!activeId) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-2 py-8 text-xs text-muted-foreground">
|
||||||
|
<span>No file open</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = buffers.get(activeId);
|
||||||
|
if (!buffer) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-2 py-8 text-xs text-muted-foreground">
|
||||||
|
<span>No file open</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const headings = extractHeadings(buffer.content);
|
||||||
|
|
||||||
|
if (headings.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-2 py-8 text-xs text-muted-foreground">
|
||||||
|
<span>No headings</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-0.5 py-1">
|
||||||
|
{headings.map((h, i) => (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
onClick={() => {}}
|
||||||
|
className="flex items-center gap-1 rounded px-2 py-0.5 text-left text-xs hover:bg-accent"
|
||||||
|
style={{ paddingLeft: `${(h.level - 1) * 16 + 8}px` }}
|
||||||
|
>
|
||||||
|
<span className="truncate text-muted-foreground">#{h.level}</span>
|
||||||
|
<span className="truncate">{h.text}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { ChevronRight, FolderOpen } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { useFileStore } from '@/stores/file-store';
|
||||||
|
import { FileTree } from './FileTree';
|
||||||
|
import { Outline } from './Outline';
|
||||||
|
|
||||||
|
export function Sidebar() {
|
||||||
|
const tree = useFileStore((s) => s.tree);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-full flex-col gap-3">
|
||||||
|
{/* Files section */}
|
||||||
|
<Collapsible defaultOpen>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<button className="flex w-full items-center gap-1.5 px-1 py-1.5 text-xs font-medium hover:bg-accent rounded">
|
||||||
|
<ChevronRight size={12} className="rotate-90" />
|
||||||
|
Files
|
||||||
|
</button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<ScrollArea className="h-[calc(100vh-240px)]">
|
||||||
|
{!tree ? (
|
||||||
|
<div className="flex flex-col items-center gap-2 p-4 text-xs text-muted-foreground">
|
||||||
|
<span>No folder opened</span>
|
||||||
|
<Button size="sm" variant="outline" onClick={() => useFileStore.getState().openFolderDialog()}>
|
||||||
|
<FolderOpen className="mr-1" /> Open Folder
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<FileTree />
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
|
||||||
|
{/* Outline section */}
|
||||||
|
<Collapsible defaultOpen>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<button className="flex w-full items-center gap-1.5 px-1 py-1.5 text-xs font-medium hover:bg-accent rounded">
|
||||||
|
<ChevronRight size={12} className="rotate-90" />
|
||||||
|
Outline
|
||||||
|
</button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<ScrollArea className="h-[calc(100vh-240px)]">
|
||||||
|
<Outline />
|
||||||
|
</ScrollArea>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { ThemeProvider as NextThemesProvider } from 'next-themes';
|
||||||
|
import type { ComponentProps } from 'react';
|
||||||
|
|
||||||
|
export function ThemeProvider({ children, ...props }: ComponentProps<typeof NextThemesProvider>) {
|
||||||
|
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user