mirror of
https://github.com/amitwh/markdown-converter.git
synced 2026-08-02 18:10:18 +05:30
Compare commits
221
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f63a678c88 | ||
|
|
5e76d77ece | ||
|
|
f43e34ca2b | ||
|
|
6da2ba7cc7 | ||
|
|
f1f8a16a79 | ||
|
|
772a791d9a | ||
|
|
ec3d53ea7e | ||
|
|
50c6369348 | ||
|
|
81d38160d8 | ||
|
|
28ef350f39 | ||
|
|
d29f19b1f5 | ||
|
|
b2ad8b8326 | ||
|
|
d2f3118bfe | ||
|
|
4cb38cd861 | ||
|
|
65dfdfb307 | ||
|
|
f1c3aaa0ef | ||
|
|
0c37a8ca2d | ||
|
|
992c6b72d6 | ||
|
|
001c9463e3 | ||
|
|
3602bc35a7 | ||
|
|
14b5a38a5a | ||
|
|
33a61e65ef | ||
|
|
857fd8a75a | ||
|
|
b8d26c8d78 | ||
|
|
bb4e874809 | ||
|
|
36422a9ab3 | ||
|
|
7eb90d467a | ||
|
|
809c266e54 | ||
|
|
2e3f4dda0f | ||
|
|
21a00a53a4 | ||
|
|
f2398e6e1a | ||
|
|
6b564a4569 | ||
|
|
2389d4f297 | ||
|
|
50f4f62575 | ||
|
|
9ef5317d71 | ||
|
|
cf6b6817b9 | ||
|
|
e25a5e1d75 | ||
|
|
c5d4b113bd | ||
|
|
1715e26e5f | ||
|
|
81484a8d33 | ||
|
|
6df1389cc8 | ||
|
|
aeadde5f40 | ||
|
|
74dde8d6d1 | ||
|
|
cd57f34c36 | ||
|
|
4da701deb5 | ||
|
|
41c68fcf82 | ||
|
|
9b899b5205 | ||
|
|
691b00a2b8 | ||
|
|
ade6c115b8 | ||
|
|
cc33e6c7a8 | ||
|
|
59fd9b8646 | ||
|
|
d87f175212 | ||
|
|
ef88b6343b | ||
|
|
e8c9f95d25 | ||
|
|
f85c1a8107 | ||
|
|
b1b9aa3727 | ||
|
|
77ad2fdb9d | ||
|
|
c62070304f | ||
|
|
9f4bfbdfee | ||
|
|
2e41b59da5 | ||
|
|
57c8f92f42 | ||
|
|
9da4b96f76 | ||
|
|
5b81988f30 | ||
|
|
a5da5d19bc | ||
|
|
74ff6afb19 | ||
|
|
5ef1610873 | ||
|
|
69afd5fc54 | ||
|
|
9e315af1b9 | ||
|
|
78914a4d65 | ||
|
|
3c4cc985fb | ||
|
|
09d9f6bdd1 | ||
|
|
f36d918871 | ||
|
|
ab16998922 | ||
|
|
58ca3014d8 | ||
|
|
7c1a79c724 | ||
|
|
8027d0b9b5 | ||
|
|
c0988a0108 | ||
|
|
18fc2317ae | ||
|
|
94dd62946a | ||
|
|
054ce2351a | ||
|
|
6651dccfdf | ||
|
|
848102905e | ||
|
|
6c7a86c99b | ||
|
|
b46fa9abaa | ||
|
|
2a32e702f3 | ||
|
|
356cfc5cc8 | ||
|
|
a03144df5b | ||
|
|
7fc11aed3b | ||
|
|
095f77f5f1 | ||
|
|
80afbb136b | ||
|
|
95bbe171b5 | ||
|
|
2d77fa5456 | ||
|
|
fbaff37505 | ||
|
|
1ccde4baa3 | ||
|
|
8822c9a2f9 | ||
|
|
324e5676b8 | ||
|
|
a62511e7ed | ||
|
|
a6c6e3696e | ||
|
|
1b2ab437d1 | ||
|
|
efc7709f66 | ||
|
|
a8f7547c7e | ||
|
|
094b52a2b3 | ||
|
|
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 | ||
|
|
96df5652d6 | ||
|
|
a9e05d2c0f | ||
|
|
c982b3e90f | ||
|
|
cfaafc07b2 | ||
|
|
94ad99dc4d |
@@ -2,9 +2,9 @@ name: CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master, react-electron]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [master]
|
branches: [master, react-electron]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
@@ -24,5 +24,8 @@ jobs:
|
|||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
|
- name: Run renderer tests
|
||||||
|
run: npm run test:renderer
|
||||||
|
|
||||||
- name: Run linter
|
- name: Run linter
|
||||||
run: npm run lint
|
run: npm run lint
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ jobs:
|
|||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
- name: Build Linux packages
|
- name: Build Linux packages
|
||||||
run: npm run build:linux-ci -- --publish=never
|
run: npm run build:linux-ci -- --publish=always
|
||||||
|
|
||||||
- name: Upload Linux artifacts
|
- name: Upload Linux artifacts
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
@@ -77,13 +77,13 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CSC_LINK: code-signing-cert.pfx
|
CSC_LINK: code-signing-cert.pfx
|
||||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||||
run: npm run build:win-signed -- --publish=never
|
run: npm run build:win-signed -- --publish=always
|
||||||
|
|
||||||
- name: Build Windows packages (unsigned)
|
- name: Build Windows packages (unsigned)
|
||||||
if: ${{ env.CERT_AVAILABLE != 'true' }}
|
if: ${{ env.CERT_AVAILABLE != 'true' }}
|
||||||
env:
|
env:
|
||||||
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
||||||
run: npm run build:win-unsigned -- --publish=never
|
run: npm run build:win-unsigned -- --publish=always
|
||||||
|
|
||||||
- name: Upload Windows artifacts
|
- name: Upload Windows artifacts
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
@@ -94,8 +94,42 @@ jobs:
|
|||||||
dist/*.zip
|
dist/*.zip
|
||||||
retention-days: 5
|
retention-days: 5
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Download external tools (pandoc)
|
||||||
|
run: node scripts/download-tools.js
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: npm test
|
||||||
|
|
||||||
|
- name: Build macOS packages (unsigned)
|
||||||
|
env:
|
||||||
|
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
||||||
|
run: npm run build:mac -- --publish=always
|
||||||
|
|
||||||
|
- name: Upload macOS artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: macos-artifacts
|
||||||
|
path: |
|
||||||
|
dist/*.dmg
|
||||||
|
dist/*.zip
|
||||||
|
retention-days: 5
|
||||||
|
|
||||||
release:
|
release:
|
||||||
needs: [build-linux, build-windows]
|
needs: [build-linux, build-windows, build-macos]
|
||||||
if: always()
|
if: always()
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -115,8 +149,28 @@ jobs:
|
|||||||
name: windows-artifacts
|
name: windows-artifacts
|
||||||
path: dist
|
path: dist
|
||||||
|
|
||||||
|
- name: Download macOS artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
name: macos-artifacts
|
||||||
|
path: dist
|
||||||
|
|
||||||
- name: Create GitHub Release
|
- name: Create GitHub Release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
files: dist/*
|
files: dist/*
|
||||||
|
|
||||||
|
- name: Mirror artifacts to ConcreteInfo update feed
|
||||||
|
if: env.CONCRETEINFO_DEPLOY_HOOK != ''
|
||||||
|
env:
|
||||||
|
CONCRETEINFO_DEPLOY_HOOK: ${{ secrets.CONCRETEINFO_DEPLOY_HOOK }}
|
||||||
|
run: |
|
||||||
|
curl -fsSL -X POST \
|
||||||
|
-H "Authorization: Bearer ${{ secrets.CONCRETEINFO_DEPLOY_HOOK }}" \
|
||||||
|
-F "version=${GITHUB_REF_NAME#v}" \
|
||||||
|
-F "artifacts=@dist/latest-mac.yml" \
|
||||||
|
-F "artifacts=@dist/latest-linux.yml" \
|
||||||
|
-F "artifacts=@dist/latest-windows.yml" \
|
||||||
|
https://updates.concreteinfo.co.in/api/v1/ingest
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to markdown-converter will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [5.1.0] - 2026-06-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Auto-update via electron-updater against GitHub Releases (default) or ConcreteInfo self-hosted feed.
|
||||||
|
- Light, skippable first-run wizard: theme, update channel, starter template.
|
||||||
|
- One-shot v4.4.1 → v5 settings migration with backup at `settings.v4.bak.json`.
|
||||||
|
- Local crash dump capture (cap 20, auto-prune) and a CrashReportModal.
|
||||||
|
- "Updates" section in Settings: channel picker, Check now, auto-check toggle.
|
||||||
|
|
||||||
|
## [5.0.0] - 2026-06-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Complete React 19 + Vite + TypeScript renderer** replacing the legacy vanilla-JS UI (Phases 1-9 of the React UI redesign)
|
||||||
|
- Native macOS/Windows/Linux menus with command palette and keyboard shortcuts
|
||||||
|
- Settings sheet with 5 tabs (editor, theme, keybindings, advanced, about) and 17+ persisted fields
|
||||||
|
- Modal layer with 13 modal kinds (export PDF/DOCX/HTML/Word, batch, settings, about, welcome, confirm, ASCII gen, table gen, find in files)
|
||||||
|
- 10 advanced tools: ASCII generator (figlet), table generator, Word export (.docx via `docx` lib), find-in-files (recursive regex), REPL (markdown snippet preview), print preview, zen mode (Esc exits), minimap, breadcrumbs-with-symbols, git status (porcelain parser)
|
||||||
|
- Sonner toast notifications at 4 wire points (file save, open file/folder, 4 export dialogs)
|
||||||
|
- 3 mount strategies: ModalLayer dialogs, App.tsx global overlays, editor/sidebar integrations
|
||||||
|
- `ipc.file.writeBuffer` for renderer-side binary file output (used by Word .docx export)
|
||||||
|
- `ipc.file.search` (recursive regex), `ipc.file.gitStatus`, `ipc.print.show`, `ipc.app.showSaveDialog`
|
||||||
|
- 305 unit + integration tests (vitest + React Testing Library)
|
||||||
|
- Per-package @radix-ui primitives (checkbox, dialog, select, switch, tabs, radio-group, scroll-area, slider, collapsible, label, context-menu)
|
||||||
|
- shadcn/ui (new-york style) primitives, manually pasted (CLI broken on Node 24)
|
||||||
|
- Feature-first main process decomposition: `src/main/{files,menu,window,word-template,utils}/` + glue files
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **BREAKING**: Renderer is now React-only. The legacy `src/renderer.js` (5319 lines) and all vanilla-JS UI scripts/styles are removed.
|
||||||
|
- Main process decomposed from a 4311-line `src/main.js` into feature-first modules under `src/main/`
|
||||||
|
- New entrypoint: `src/main/index.js` (was `src/main.js`)
|
||||||
|
- `src/index.html` (1667-line legacy orphan) removed; renderer served by `src/renderer/index.html` (Vite root)
|
||||||
|
- IPC contract: handlers throw on error, `safeCall` catches → returns `{ ok: false, error }`. `result.ok` is at top level, NOT nested in `result.data.ok`
|
||||||
|
- Settings store: `useSettingsStore` (zustand persist with zod validation), 17+ persisted fields
|
||||||
|
- Modal state: `useAppStore.modal: ModalState` discriminated union with 13 kinds; `openModal` uses TS conditional types to enforce prop requirements
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- `src/renderer.js` (legacy vanilla-JS renderer, 5319 lines)
|
||||||
|
- 8 legacy stylesheets: `src/styles.css`, `src/styles-modern.css`, `src/styles-concreteinfo.css`, `src/styles-sidebar.css`, `src/styles-zen.css`, `src/styles-welcome.css`, `src/fonts.css`
|
||||||
|
- 5 legacy scripts: `src/command-palette.js`, `src/print-preview.js`, `src/welcome.js`, `src/zen-mode.js`, `src/wordTemplateExporter.js`
|
||||||
|
- 2 legacy HTMLs: `src/ascii-generator.html`, `src/table-generator.html`
|
||||||
|
- `src/main.js` (4311-line god file, replaced by `src/main/index.js`)
|
||||||
|
- `src/index.html` (1667-line legacy orphan at project root, replaced by `src/renderer/index.html`)
|
||||||
|
- 9 dead IPC channels from `src/preload.js`: `toggle-command-palette`, `print-preview`, `print-preview-styled`, `open-ascii-generator`, `open-table-generator`, `show-ascii-generator`, `show-ascii-generator-window`, `show-table-generator`, `show-table-generator-window`
|
||||||
|
|
||||||
|
[5.0.0]: https://github.com/amitwh/markdown-converter/releases/tag/v5.0.0
|
||||||
|
|
||||||
|
## [5.1.0] - 2026-07-23 - react-electron parity
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Monospace font embedding** — bundles JetBrains Mono + Fira Code TTFs and embeds the active font into PDF (xelatex fontspec), DOCX (post-pandoc zip patch with `fontTable.xml`), EPUB (`--epub-embed-font` + manifest), and HTML (woff2 base64 in CSS) exports. ASCII art and code blocks now render with the exact same font across machines.
|
||||||
|
- **Monospace settings** — `get-monospace-settings` / `set-monospace-settings` IPC, with `monospaceFont` (`jetbrains-mono` / `fira-code`) and `monospaceLigatures` (boolean).
|
||||||
|
- **Renderer body-class toggle** — `useMonospaceClasses` hook toggles `mono-jetbrains-mono` / `mono-fira-code` and `mono-ligatures-on` / `mono-ligatures-off` on `document.body`, driving `--font-mono-active` and `--font-mono-feature` CSS tokens.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **App renamed to Markdown Converter React** (`com.concreteinfo.markdownconverter.react`, npm name `markdown-converter-react`, deb `markdown-converter-react_*_amd64.deb`) so the dev build coexists with the installed `markdown-converter` deb without single-instance lock conflicts.
|
||||||
|
- Window title shows `Markdown Converter — React Dev` in dev mode.
|
||||||
|
- `download-tools.js` pins Fira Code to release `6.2` with SHA-256 digests verified before atomic rename; downloads refuse to start on digest mismatch.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- `PdfFontHeader` uses `fs.mkdtempSync` for an exclusive temp directory; the caller unlinks it after pandoc consumes the header (no racy `Date.now()+pid` filenames).
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# CLAUDE.md — MarkdownConverter (react-electron)
|
||||||
|
|
||||||
|
> General code-quality, TypeScript, 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, plugin system, and auto-updater.
|
||||||
|
|
||||||
|
- **Version:** 5.0.1
|
||||||
|
- **License:** MIT
|
||||||
|
- **App ID:** `com.concreteinfo.markdownconverter`
|
||||||
|
|
||||||
|
## Branch Specifics
|
||||||
|
|
||||||
|
This is the **React rewrite branch** — the renderer has been rebuilt with React 19 + TypeScript + Tailwind CSS + shadcn/ui, replacing the vanilla JS renderer from master. The main process remains vanilla CommonJS JavaScript. A dual dev workflow runs Vite (renderer) and Electron (main) concurrently.
|
||||||
|
|
||||||
|
Key differences from master:
|
||||||
|
- Renderer: React 19 + TypeScript (TSX) instead of vanilla JS DOM manipulation
|
||||||
|
- Bundler: Vite for the renderer (`vite.renderer.config.ts`)
|
||||||
|
- UI: shadcn/ui (Radix primitives + Tailwind) instead of hand-rolled CSS
|
||||||
|
- State: Zustand 5 stores instead of global mutable state
|
||||||
|
- Security: `contextIsolation: true` + `nodeIntegration: false` (preload with channel whitelisting) instead of master's open renderer
|
||||||
|
- Build: two-stage (Vite build renderer, then electron-builder packages) instead of single electron-builder pass
|
||||||
|
- Testing: dual test runners — Vitest (renderer/React/TS) + Jest (main process/JS)
|
||||||
|
- Main process is now in `src/main/` (modular) instead of flat `src/main.js`
|
||||||
|
- Adds auto-updater via `electron-updater` with GitHub Releases + self-hosted feed support
|
||||||
|
- Adds React Hook Form + Zod for form validation, Lucide React icons, Motion for animations
|
||||||
|
- Legacy sidebar modules (`src/sidebar/*.js`) still exist alongside new React sidebar (`src/renderer/components/sidebar/`)
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Main Process (`src/main/`)
|
||||||
|
Modular structure (improvement over master's monolith):
|
||||||
|
- `src/main/index.js` — IPC handlers, Pandoc invocation, export logic (~3,500 lines)
|
||||||
|
- `src/main/PDFOperations.js` — PDF manipulation via `pdf-lib`
|
||||||
|
- `src/main/GitOperations.js` — Git operations via `simple-git`
|
||||||
|
- `src/main/store.js` — Custom JSON settings store (NOT electron-store)
|
||||||
|
- `src/main/window/index.js` — BrowserWindow creation with three-mode loading (dev/prod/packaged)
|
||||||
|
- `src/main/menu/` — Application menu definitions
|
||||||
|
- `src/main/ipc/` — Crash handlers, updater handlers
|
||||||
|
- `src/main/updater/` — Auto-update service, feed config, migration runner
|
||||||
|
- `src/main/files/` — File operation modules
|
||||||
|
- `src/main/word-template/` — Word template export
|
||||||
|
|
||||||
|
### Preload (`src/preload.js`)
|
||||||
|
Properly isolated. Uses `contextBridge` with **channel whitelisting** (`ALLOWED_SEND_CHANNELS`, `ALLOWED_RECEIVE_CHANNELS` arrays). The renderer has no direct Node access.
|
||||||
|
|
||||||
|
### Renderer (`src/renderer/`)
|
||||||
|
React 19 + TypeScript application bundled by Vite:
|
||||||
|
- `src/renderer/App.tsx` — Root component: assembles AppShell, modals, command palette, toaster
|
||||||
|
- `src/renderer/components/layout/AppShell.tsx` — Three-panel resizable layout (sidebar | editor | preview)
|
||||||
|
- `src/renderer/stores/` — Zustand stores: `app-store`, `editor-store`, `file-store`, `preview-store`, `settings-store`, `command-store`
|
||||||
|
- `src/renderer/hooks/` — Custom hooks: `use-shortcut`, `use-file-shortcuts`, `use-menu-action`, `use-scroll-sync`, `use-zen-mode`, `use-export-source`
|
||||||
|
- `src/renderer/components/modals/` — 30+ modal dialogs as React components
|
||||||
|
- `src/renderer/components/editor/` — CodeMirror 6 editor React wrapper
|
||||||
|
- `src/renderer/components/preview/` — Markdown renderer with Mermaid lazy loading
|
||||||
|
- `src/renderer/components/sidebar/` — React sidebar panels (FileTree, GitStatus, Outline, Snippets, Templates)
|
||||||
|
- `src/renderer/components/ui/` — shadcn/ui primitives (button, dialog, sheet, select, tabs, etc.)
|
||||||
|
- `src/renderer/lib/` — Utilities: typed IPC wrapper (`ipc.ts`), export modules, validators
|
||||||
|
- `src/renderer/types/` — TypeScript declarations: `electron.d.ts` (window.electronAPI), `ipc.ts` (IPC types)
|
||||||
|
|
||||||
|
### Security Model
|
||||||
|
- **`contextIsolation: true` + `nodeIntegration: false`** (properly secured, unlike master)
|
||||||
|
- Preload with explicit channel whitelisting
|
||||||
|
- TypeScript declarations ensure type-safe IPC
|
||||||
|
- Pandoc invoked via `execFile` (not `exec`)
|
||||||
|
- Permission handler: only `clipboard-read`/`clipboard-write` allowed
|
||||||
|
- ESLint enforces `no-eval`, `no-implied-eval`, `no-new-func`
|
||||||
|
- CSP in `index.html` restricts script/style/img/font/connect sources
|
||||||
|
|
||||||
|
### Plugin System (`src/plugins/`)
|
||||||
|
Unchanged from master. Manifest-based discovery, built-in `writing-studio` plugin.
|
||||||
|
|
||||||
|
## System Dependencies
|
||||||
|
|
||||||
|
| Dependency | Required | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| **Node.js** | >= 20 | Electron 41 bundles Node 20.x; Vite 8 requires Node 18+ |
|
||||||
|
| **Pandoc** | Yes (for exports) | Downloaded to `bin/<platform>/pandoc` via `scripts/download-tools.js` (v3.9.0.2). Falls back to system PATH. |
|
||||||
|
| **FFmpeg** | Bundled | `ffmpeg-static` npm package; `asarUnpacked` |
|
||||||
|
| **MiKTeX / TeX Live** | Optional | LaTeX PDF export; MiKTeX PATH injected on Windows |
|
||||||
|
| **ImageMagick** | Optional | Linux image conversion; deb dependency |
|
||||||
|
| **LibreOffice** | Optional | Enhanced document conversion; deb dependency |
|
||||||
|
|
||||||
|
## Development Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev # Start dev mode: Vite dev server (port 5173) + Electron (concurrently)
|
||||||
|
npm run dev:renderer # Vite dev server only (port 5173)
|
||||||
|
npm run dev:electron # Electron only (waits for Vite on tcp:5173)
|
||||||
|
npm start # Launch Electron app (prod mode, requires built renderer)
|
||||||
|
npm run preview # Build renderer then launch Electron
|
||||||
|
npm test # Jest — main process tests (vanilla JS)
|
||||||
|
npm run test:renderer # Vitest — renderer tests (React/TS)
|
||||||
|
npm run lint # ESLint check
|
||||||
|
npm run lint:fix # ESLint auto-fix
|
||||||
|
npm run format # Prettier write
|
||||||
|
npm run format:check # Prettier check
|
||||||
|
npm run download-tools # Download Pandoc binaries
|
||||||
|
npm run generate-icons # Generate app icons
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dev workflow:** `npm run dev` starts Vite (renderer HMR on `:5173`) and Electron concurrently. The main process loads from `http://localhost:5173` in dev mode.
|
||||||
|
|
||||||
|
## Build & Package
|
||||||
|
|
||||||
|
**Two-stage build process:**
|
||||||
|
1. `npm run build:renderer` — Vite builds renderer to `dist/renderer/`
|
||||||
|
2. `npm run build` — electron-builder packages main process + preload + built renderer
|
||||||
|
|
||||||
|
**Tool:** `electron-builder` (v26.0.12), config inline in `package.json`.
|
||||||
|
|
||||||
|
| Target | Platforms |
|
||||||
|
|---|---|
|
||||||
|
| `npm run build:win` | Windows: NSIS + portable + zip (x64) |
|
||||||
|
| `npm run build:mac` | macOS: dmg + zip (x64 + arm64) |
|
||||||
|
| `npm run build:linux` | Linux: deb + AppImage + snap |
|
||||||
|
|
||||||
|
**Packaged files:** `src/main/**`, `src/preload.js`, `src/plugins/**`, `package.json`. Renderer built output copied to resources as `renderer/`.
|
||||||
|
|
||||||
|
**Bundled with builds:** Pandoc binary per platform, FFmpeg (asarUnpacked).
|
||||||
|
|
||||||
|
**Output:** `dist/` directory.
|
||||||
|
|
||||||
|
**Auto-updater:** `electron-updater` with GitHub Releases (default) and optional ConcreteInfo self-hosted feed.
|
||||||
|
|
||||||
|
**CI:** GitHub Actions workflows in `.github/workflows/` (ci.yml, release.yml).
|
||||||
|
|
||||||
|
## Project Conventions / Gotchas
|
||||||
|
|
||||||
|
- **Dual-process architecture.** Main process is vanilla CommonJS JavaScript (`src/main/`). Renderer is React 19 + TypeScript + Tailwind (`src/renderer/`). They are separate build targets.
|
||||||
|
- **Vite for renderer only.** Main process is NOT bundled — Electron loads `src/main/index.js` directly. Do not add TypeScript to main process files.
|
||||||
|
- **Tailwind + shadcn/ui.** Use shadcn/ui components (`src/renderer/components/ui/`) for all UI primitives. Custom theme in `tailwind.config.js`. Path alias `@` maps to `src/renderer/`. Brand color: `#e5461f`.
|
||||||
|
- **Zustand for state.** All renderer state lives in `src/renderer/stores/`. Each store is a separate file. Use immer for immutable updates.
|
||||||
|
- **Typed IPC.** `src/renderer/types/electron.d.ts` declares `window.electronAPI`. `src/renderer/lib/ipc.ts` provides type-safe wrappers. When adding new IPC channels, update both the preload whitelist AND the TypeScript declarations.
|
||||||
|
- **Legacy + new sidebar.** `src/sidebar/*.js` (vanilla JS) and `src/renderer/components/sidebar/` (React TSX) both exist. New sidebar features go in the React version.
|
||||||
|
- **Pandoc is external.** Must be present for non-HTML/PDF exports. Download via `npm run download-tools` or install system-wide.
|
||||||
|
- **PDF export fallback chain:** xelatex -> pdflatex -> lualatex -> Electron built-in `printToPDF()`.
|
||||||
|
- **PDF rendering:** `pdfjs-dist` (viewer). **PDF manipulation:** `pdf-lib` in main process.
|
||||||
|
- **Editor:** CodeMirror 6, configured in `src/editor/codemirror-setup.js`, wrapped as React component in `src/renderer/components/editor/CodeMirrorEditor.tsx`.
|
||||||
|
- **Tests:** Jest (main process, `tests/**/*.test.js`, 15% threshold) + Vitest (renderer, `tests/**/*.{test,spec}.{ts,tsx}`, v8 coverage on `src/renderer/`).
|
||||||
|
- **ESLint flat config** with ECMAScript 2022. Prettier: 2-space, single quotes, semicolons, 100-char width.
|
||||||
|
- **No tsconfig.json at root** — TypeScript is renderer-only, handled by Vite. Do not add `tsconfig.json` for the main process.
|
||||||
|
- **File associations:** `.md`, `.markdown`, `.pdf` registered at install.
|
||||||
|
- **Single instance lock** via `app.requestSingleInstanceLock()`.
|
||||||
@@ -140,6 +140,21 @@ Open PDF files directly in MarkdownConverter:
|
|||||||
- Rotate pages left or right
|
- Rotate pages left or right
|
||||||
- Close PDF to return to editor
|
- Close PDF to return to editor
|
||||||
|
|
||||||
|
## Distribution & Updates
|
||||||
|
|
||||||
|
v5.x uses `electron-updater` against two feeds:
|
||||||
|
|
||||||
|
- **GitHub Releases** (default, public): the public release at `https://github.com/amitwh/markdown-converter/releases`. The CI workflow publishes `latest-{mac,linux,windows}.yml` on every tag.
|
||||||
|
- **ConcreteInfo self-hosted** (opt-in for enterprise deployments): `https://updates.concreteinfo.co.in/v5/`. CI mirrors artifacts on every release when `CONCRETEINFO_DEPLOY_HOOK` is set as a repository secret.
|
||||||
|
|
||||||
|
Users switch the feed in **Settings → Updates → Update channel**. Auto-check is enabled by default; disable it in the same panel.
|
||||||
|
|
||||||
|
### Manual mirror
|
||||||
|
|
||||||
|
```bash
|
||||||
|
CONCRETEINFO_DEPLOY_HOOK=... npm run publish:concreteinfo -- 5.1.0
|
||||||
|
```
|
||||||
|
|
||||||
## Open Source
|
## Open Source
|
||||||
|
|
||||||
MarkdownConverter is 100% open-source. All dependencies are permissively licensed:
|
MarkdownConverter is 100% open-source. All dependencies are permissively licensed:
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,93 @@
|
|||||||
|
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.
@@ -0,0 +1,93 @@
|
|||||||
|
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.
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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
# Packaging — All-Platform Build + GitHub Releases
|
||||||
|
|
||||||
|
**Goal:** Make `npm run dist:all` produce Linux + Windows + macOS artifacts, and have the existing `.github/workflows/release.yml` create a GitHub Release on tag push with those artifacts. No code signing in this iteration.
|
||||||
|
|
||||||
|
**Scope (user decisions 2026-06-06):**
|
||||||
|
- Target platforms: **all three** (Linux .deb/AppImage/snap, Windows NSIS/portable/zip, macOS dmg/zip)
|
||||||
|
- Distribution: **GitHub Releases** (no auto-update; static artifacts only)
|
||||||
|
- Code signing: **skip for now** (unsigned binaries; Windows SmartScreen will warn, macOS Gatekeeper will quarantine)
|
||||||
|
|
||||||
|
**Architecture:** This is mostly about completing the existing scaffold. `electron-builder` 26.0.12, `scripts/download-tools.js`, `scripts/generate-icons.js`, the `package.json` scripts, and `release.yml` are all already in place. We need to (1) close a real bug in the `files` config, (2) add the macOS job to the workflow, and (3) declare macOS targets in the package config.
|
||||||
|
|
||||||
|
**Tech stack:** electron-builder 26.0.12, GitHub Actions `ubuntu-latest`/`windows-latest`/`macos-latest` runners, softprops/action-gh-release@v2 for the release creation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1 — Fix the `files` config in `package.json`
|
||||||
|
|
||||||
|
The current `files: ["src/**/*", ...]` matches `src/renderer/**/*.tsx` and ships dev source into the asar. The shipped renderer should be the built `dist/renderer/**/*` output, not TS source. asarUnpack for ffmpeg-static is correct and stays.
|
||||||
|
|
||||||
|
**Files:** `package.json` (build.files, build.extraResources)
|
||||||
|
|
||||||
|
### Step 1.1 — Replace `files` block
|
||||||
|
|
||||||
|
```json
|
||||||
|
"files": [
|
||||||
|
"src/main/**/*",
|
||||||
|
"src/preload.js",
|
||||||
|
"src/plugins/**/*",
|
||||||
|
"package.json"
|
||||||
|
],
|
||||||
|
"extraResources": [
|
||||||
|
{
|
||||||
|
"from": "dist/renderer",
|
||||||
|
"to": "renderer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
- `src/main/**/*` — main process source (entry point + all main-process modules)
|
||||||
|
- `src/preload.js` — single preload file at the root of `src/`
|
||||||
|
- `src/plugins/**/*` — built-in plugins (referenced from main process; the `extraFiles: []` line in the current config is empty, so this is the right pattern)
|
||||||
|
- `package.json` — required for the asar `app.asar/package.json` lookup electron does at runtime
|
||||||
|
- `dist/renderer` moves to `extraResources` because it should live alongside the asar (not inside it) — the asar is sealed and we want the renderer to be a separately-updatable resource path. Production main loads it via `loadFile(path.join(__dirname, '../../dist/renderer/index.html'))` which, in the packaged app, resolves to `process.resourcesPath/renderer/index.html`. **This requires changing the loadFile path in `src/main/window/index.js` too** — see Task 4.
|
||||||
|
|
||||||
|
### Step 1.2 — Verify
|
||||||
|
|
||||||
|
- `npm run build:linux` should produce a working .AppImage
|
||||||
|
- Inside the .AppImage (extract with `--appimage-extract`), check `resources/` has `app.asar` and a `renderer/` directory containing `index.html` and `assets/`
|
||||||
|
- Inside `app.asar`, check `src/main/index.js` is present and `src/renderer/` is absent
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 2 — Add macOS targets + icon to `package.json` build config
|
||||||
|
|
||||||
|
**Files:** `package.json`
|
||||||
|
|
||||||
|
### Step 2.1 — Replace the existing `mac` block
|
||||||
|
|
||||||
|
```json
|
||||||
|
"mac": {
|
||||||
|
"category": "public.app-category.productivity",
|
||||||
|
"identity": null,
|
||||||
|
"target": [
|
||||||
|
{ "target": "dmg", "arch": ["x64", "arm64"] },
|
||||||
|
{ "target": "zip", "arch": ["x64", "arm64"] }
|
||||||
|
],
|
||||||
|
"icon": "assets/icon.icns",
|
||||||
|
"darkModeSupport": true,
|
||||||
|
"hardenedRuntime": false,
|
||||||
|
"gatekeeperAssess": false,
|
||||||
|
"entitlements": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `identity: null` is intentional for unsigned builds
|
||||||
|
- `darkModeSupport: true` — the app already supports dark mode; this is just metadata
|
||||||
|
- `hardenedRuntime: false` and `gatekeeperAssess: false` — without signing, these are the only way the build succeeds
|
||||||
|
- `entitlements: null` — no entitlements file; some features (jit) won't work but Electron's main process doesn't need them in this app
|
||||||
|
- **`.icns` is missing.** For this iteration we'll use the default Electron icon and add a follow-up to generate one. The build will succeed without it but the produced .app will have the default icon.
|
||||||
|
|
||||||
|
### Step 2.2 — Generate a placeholder `.icns` (optional, can be deferred)
|
||||||
|
|
||||||
|
If we want a proper icon, the path is:
|
||||||
|
1. `npm run generate-icons` to produce `assets/icons/*.png` (already done)
|
||||||
|
2. Use `png2icns` (Linux) or `iconutil` (mac) to bundle them into `assets/icon.icns`
|
||||||
|
3. We don't have either on this Linux container; defer to a follow-up plan
|
||||||
|
|
||||||
|
For this iteration: ship without `.icns` and accept the default icon.
|
||||||
|
|
||||||
|
### Step 2.3 — Add `publish` config
|
||||||
|
|
||||||
|
```json
|
||||||
|
"publish": {
|
||||||
|
"provider": "github",
|
||||||
|
"owner": "amitwh",
|
||||||
|
"repo": "markdown-converter",
|
||||||
|
"releaseType": "release"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Even without auto-update, this tells `electron-builder` to write `latest-mac.yml` / `latest-linux.yml` next to the artifacts. Useful for future auto-update wiring. CI passes `--publish=never` to override.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 3 — Add macOS job to `.github/workflows/release.yml`
|
||||||
|
|
||||||
|
**Files:** `.github/workflows/release.yml`
|
||||||
|
|
||||||
|
### Step 3.1 — Add a third job between `build-windows` and `release`
|
||||||
|
|
||||||
|
Insert after the `build-windows` job (around line 96):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
build-macos:
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Download external tools (pandoc)
|
||||||
|
run: node scripts/download-tools.js
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: npm test
|
||||||
|
|
||||||
|
- name: Build macOS packages (unsigned)
|
||||||
|
env:
|
||||||
|
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
||||||
|
run: npm run build:mac -- --publish=never
|
||||||
|
|
||||||
|
- name: Upload macOS artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: macos-artifacts
|
||||||
|
path: |
|
||||||
|
dist/*.dmg
|
||||||
|
dist/*.zip
|
||||||
|
retention-days: 5
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3.2 — Wire macOS into the `release` job's `needs` and downloads
|
||||||
|
|
||||||
|
Change the `release` job:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
release:
|
||||||
|
needs: [build-linux, build-windows, build-macos]
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
And add a third download step (after the Windows download):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Download macOS artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
name: macos-artifacts
|
||||||
|
path: dist
|
||||||
|
```
|
||||||
|
|
||||||
|
`continue-on-error: true` is intentional — a failed macOS build shouldn't block a release of working Linux+Windows artifacts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 4 — Update `src/main/window/index.js` for the resource path
|
||||||
|
|
||||||
|
**Files:** `src/main/window/index.js`
|
||||||
|
|
||||||
|
### Step 4.1 — Update the loadFile path
|
||||||
|
|
||||||
|
The current code (line 35):
|
||||||
|
```js
|
||||||
|
const prodPath = path.join(__dirname, '../../dist/renderer/index.html');
|
||||||
|
```
|
||||||
|
|
||||||
|
Inside the packaged app, `__dirname` points into the asar. `process.resourcesPath` points to the directory holding `app.asar` + the `renderer/` extraResources dir. Change to:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const rendererIndex = app.isPackaged
|
||||||
|
? path.join(process.resourcesPath, 'renderer', 'index.html')
|
||||||
|
: path.join(__dirname, '../../dist/renderer/index.html');
|
||||||
|
win.loadFile(rendererIndex);
|
||||||
|
```
|
||||||
|
|
||||||
|
This needs to happen after the dev/prod branch is decided. The existing `if (!app.isPackaged && devServerUrl)` block already handles dev mode; the else branch needs this update.
|
||||||
|
|
||||||
|
### Step 4.2 — Add a guard for missing renderer in prod
|
||||||
|
|
||||||
|
```js
|
||||||
|
if (app.isPackaged) {
|
||||||
|
try {
|
||||||
|
fs.accessSync(path.join(process.resourcesPath, 'renderer', 'index.html'));
|
||||||
|
} catch {
|
||||||
|
console.error('[WINDOW] Renderer not found at', process.resourcesPath, '— did you run `npm run build:renderer` before packaging?');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Failure mode: someone runs `npm run build` without first building the renderer. Without this guard, the window opens blank and the user has no idea why.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 5 — Test on this Linux box
|
||||||
|
|
||||||
|
### Step 5.1 — Local verification
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci
|
||||||
|
npm run download-tools # idempotent; bin/linux/pandoc already exists
|
||||||
|
npm run build:renderer
|
||||||
|
npm run build:linux # produces .deb, .AppImage in dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
Inspect the .AppImage:
|
||||||
|
```bash
|
||||||
|
chmod +x dist/*.AppImage
|
||||||
|
./dist/MarkdownConverter-*.AppImage --appimage-extract
|
||||||
|
ls squashfs-root/resources/
|
||||||
|
# Expect: app.asar renderer/
|
||||||
|
ls squashfs-root/resources/renderer/
|
||||||
|
# Expect: index.html assets/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 5.2 — Run the produced app
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./dist/MarkdownConverter-*.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
|
The app should:
|
||||||
|
- Launch with the AppShell, header, sidebar
|
||||||
|
- Allow opening a folder / file
|
||||||
|
- Export to PDF/DOCX/HTML work (pandoc bundled)
|
||||||
|
|
||||||
|
### Step 5.3 — Tag + push to test the release workflow (optional)
|
||||||
|
|
||||||
|
Only do this if the user wants to verify the full pipeline. A dry-run on the CI side via `act` would be cleaner but `act` doesn't run macos-latest jobs locally. If the user wants to verify the workflow, push a `v5.0.1-rc1` tag and watch the Actions tab.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Success criteria
|
||||||
|
|
||||||
|
1. `npm run dist:all` produces all three platform families on this Linux box (or at least Linux + mac, since Windows is built on Windows)
|
||||||
|
2. The .AppImage launches and the app works end-to-end
|
||||||
|
3. `release.yml` runs all three jobs on a tag push and creates a GitHub release with the union of artifacts
|
||||||
|
4. No regressions: 306/306 tests still pass, dev workflow still works
|
||||||
|
5. The `files` bug is fixed: no `.tsx` in the packaged asar
|
||||||
|
|
||||||
|
## Known limitations (intentional, can be follow-ups)
|
||||||
|
|
||||||
|
- **No `.icns`** — the macOS app will have the default Electron icon. Generating a proper `.icns` requires `iconutil` (mac) or `png2icns` (cross-platform); neither is on this Linux box.
|
||||||
|
- **No code signing** — Windows SmartScreen will warn; macOS Gatekeeper will quarantine unsigned `.dmg`. Setting up signing later is a config-only change (no structural rework): add `CSC_LINK`/`CSC_KEY_PASSWORD` for Windows, `CSC_LINK` (Apple Developer ID) for mac.
|
||||||
|
- **No auto-update** — user decisions for this iteration. Wiring `electron-updater` is a follow-up; the `publish` config from Task 2 puts metadata in the right place.
|
||||||
|
- **Cross-build quirks** — building macOS from Linux produces a `.dmg` that is generally usable but may show a "this app is from an unidentified developer" prompt the first time. Right-click → Open to bypass once. Documented in the release notes.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- CHANGELOG.md updates (not part of packaging)
|
||||||
|
- electron-updater wiring
|
||||||
|
- Code signing cert procurement
|
||||||
|
- Snap store / Microsoft Store / Mac App Store submission
|
||||||
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
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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,303 @@
|
|||||||
|
# Phase 9 — Advanced Tools Design
|
||||||
|
|
||||||
|
> Companion to the parent plan: `docs/superpowers/plans/2026-06-05-react-ui-redesign.md` (Phase 9 is sketched at high level; this spec locks architecture, file map, and contracts so it can be planned task-by-task.)
|
||||||
|
|
||||||
|
**Date:** 2026-06-05
|
||||||
|
**Phase:** 9 of 10 (React + shadcn/ui UI redesign)
|
||||||
|
**Tag (on completion):** `phase-9-advanced-tools`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Goal & Non-Goals
|
||||||
|
|
||||||
|
**Goal:** Add 10 advanced tools to the React renderer. Group 1: Standalone dialogs (ASCII generator, Table generator, Word export, Find-in-files). Group 2: Global overlays (Zen mode, REPL, Print preview). Group 3: Editor/sidebar integrations (Minimap, Breadcrumbs-with-symbols, Git status). All triggered via the Phase 6 command store.
|
||||||
|
|
||||||
|
**Non-goals (Phase 9):**
|
||||||
|
- True undo/redo stack (still not in scope)
|
||||||
|
- Snippet/template library
|
||||||
|
- Custom REPL with full JS eval (we chose markdown snippet preview for safety)
|
||||||
|
- Custom diff/merge UI (just shows git status, no in-app diffing)
|
||||||
|
- Plug-in extensions
|
||||||
|
- Multi-cursor editing
|
||||||
|
- LSP / language server integration
|
||||||
|
|
||||||
|
**Decision summary (from brainstorming):**
|
||||||
|
- REPL = **markdown snippet preview** (no JS eval — safe in renderer)
|
||||||
|
- Word export = **`.docx` via `docx` lib in renderer**, with both Standard and Custom .dotx template modes
|
||||||
|
- Find-in-files = **recursive search with result navigation** (new IPC, regex support)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architecture
|
||||||
|
|
||||||
|
### 2.1 Three mount strategies
|
||||||
|
|
||||||
|
| Category | Mount | Examples |
|
||||||
|
|---|---|---|
|
||||||
|
| **Dialogs** | `<ModalLayer />` (Phase 7 pattern) | ASCII gen, Table gen, Word export, Find-in-files |
|
||||||
|
| **Global overlays** | Top-level in `App.tsx` (like `<Toaster />`) | Zen mode, REPL panel, Print preview |
|
||||||
|
| **Editor/sidebar integrations** | Extend existing components | Minimap, Breadcrumbs, Git status |
|
||||||
|
|
||||||
|
The ModalLayer is the dispatcher for dialogs. The global overlays are mounted directly in `App.tsx` because they need to participate in the top-level layout (full-window, or pinned to the bottom).
|
||||||
|
|
||||||
|
### 2.2 ModalState union extension
|
||||||
|
|
||||||
|
The Phase 7 `ModalState` discriminated union (9 kinds) gets 4 new kinds for the new dialogs:
|
||||||
|
|
||||||
|
```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: 'export-word'; props: { sourcePath: string } } // NEW
|
||||||
|
| { kind: 'ascii-generator' } // NEW
|
||||||
|
| { kind: 'table-generator' } // NEW
|
||||||
|
| { kind: 'find-in-files' } // NEW
|
||||||
|
| { kind: 'settings' }
|
||||||
|
| { kind: 'about' }
|
||||||
|
| { kind: 'welcome' }
|
||||||
|
| { kind: 'confirm'; props: ConfirmProps };
|
||||||
|
```
|
||||||
|
|
||||||
|
Three of the four new kinds (ascii, table, find-in-files) take no props — they read from the active buffer via `useExportSource` (for ascii/table) or from `useFileStore.rootPath` (for find-in-files). `export-word` takes `sourcePath` like the other export dialogs.
|
||||||
|
|
||||||
|
### 2.3 New commands in command store
|
||||||
|
|
||||||
|
| Command ID | Trigger | Opens |
|
||||||
|
|---|---|---|
|
||||||
|
| `tools.ascii` | new | `AsciiGeneratorDialog` |
|
||||||
|
| `tools.table` | new | `TableGeneratorDialog` |
|
||||||
|
| `tools.exportWord` | new | `WordExportDialog` |
|
||||||
|
| `tools.findInFiles` | new | `FindInFilesDialog` |
|
||||||
|
| `tools.repl` | new | toggles REPL panel |
|
||||||
|
| `view.zenMode` | existing (Phase 6) | toggles Zen mode overlay |
|
||||||
|
| `file.print` | new | opens `PrintPreview` overlay |
|
||||||
|
| `git.refresh` | new | re-fetches git status |
|
||||||
|
|
||||||
|
All registered in `src/renderer/lib/commands/register-menu-commands.ts`.
|
||||||
|
|
||||||
|
### 2.4 New IPC surface
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// src/renderer/lib/ipc.ts (additions)
|
||||||
|
ipc.file.search({ rootPath, query, isRegex, caseSensitive }: {
|
||||||
|
rootPath: string;
|
||||||
|
query: string;
|
||||||
|
isRegex: boolean;
|
||||||
|
caseSensitive: boolean;
|
||||||
|
}): Promise<IpcResult<Array<{ filePath: string; line: number; content: string }>>>;
|
||||||
|
|
||||||
|
ipc.file.gitStatus({ rootPath }: { rootPath: string }): Promise<IpcResult<Array<{ filePath: string; status: 'modified' | 'added' | 'deleted' | 'untracked' }>>>;
|
||||||
|
|
||||||
|
ipc.file.print({ html }: { html: string }): Promise<IpcResult<void>>;
|
||||||
|
|
||||||
|
ipc.file.writeBuffer({ path, buffer }: { path: string; buffer: Uint8Array }): Promise<IpcResult<void>>;
|
||||||
|
```
|
||||||
|
|
||||||
|
The main process counterparts are added to `src/main.js` (or a new `src/main/files-search.js`, etc.). For Phase 9, the spec covers the renderer-side design; main-process IPC handlers are assumed to follow the same `ipcMain.handle` pattern as the existing handlers.
|
||||||
|
|
||||||
|
### 2.5 Settings additions (`useSettingsStore`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// zod schema additions:
|
||||||
|
docxCustomTemplatePath: z.string().nullable().default(null), // path to user .dotx file
|
||||||
|
replOpen: z.boolean().default(false), // REPL panel visibility
|
||||||
|
breadcrumbSymbols: z.boolean().default(true), // breadcrumbs show code symbols
|
||||||
|
// minimap already exists from Phase 7 (useSettingsStore.minimap: z.boolean().default(true))
|
||||||
|
```
|
||||||
|
|
||||||
|
The `minimap` setting from Phase 7 is now wired (not just stored).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. File Map
|
||||||
|
|
||||||
|
### 3.1 Created files
|
||||||
|
|
||||||
|
**Dialogs (in `src/renderer/components/modals/`):**
|
||||||
|
- `AsciiGeneratorDialog.tsx` — input textarea, font select, output preview with copy button
|
||||||
|
- `TableGeneratorDialog.tsx` — rows × cols inputs, header checkbox, output preview
|
||||||
|
- `WordExportDialog.tsx` — template select (Standard / Custom .dotx), options, preview, export
|
||||||
|
- `FindInFilesDialog.tsx` — query input, regex/case toggles, results list with click-to-navigate
|
||||||
|
|
||||||
|
**Global overlays (in `src/renderer/components/tools/`):**
|
||||||
|
- `ReplPanel.tsx` — bottom-pinned, textarea + rendered preview
|
||||||
|
- `PrintPreview.tsx` — full-window print preview
|
||||||
|
|
||||||
|
**Editor/sidebar integrations:**
|
||||||
|
- `src/renderer/components/layout/ZenMode.tsx` — wraps/controls the editor in zen mode (or modify `AppShell.tsx` to hide chrome)
|
||||||
|
- `src/renderer/components/sidebar/GitStatusPanel.tsx` — file list with status badges
|
||||||
|
|
||||||
|
**Lib:**
|
||||||
|
- `src/renderer/lib/docx-export.ts` — renderer-side `docx` lib integration (markdown → Blob)
|
||||||
|
- `src/renderer/hooks/use-zen-mode.ts` — small hook that reads `useSettingsStore.zenMode`
|
||||||
|
|
||||||
|
**Modifications:**
|
||||||
|
- `src/renderer/App.tsx` — mount `<ReplPanel />` and `<PrintPreview />` alongside `<ModalLayer />` and `<Toaster />`
|
||||||
|
- `src/renderer/components/layout/AppShell.tsx` — when `zenMode === true`, hide all chrome except the editor
|
||||||
|
- `src/renderer/components/editor/CodeMirrorEditor.tsx` — add `@codemirror/minimap` (or `@replit/codemirror-minimap`) when `useSettingsStore.minimap` is true
|
||||||
|
- `src/renderer/components/layout/Breadcrumb.tsx` — extend to show symbols (headings, code blocks) using `@codemirror/langs-data` or a simple markdown AST walk
|
||||||
|
- `src/renderer/components/sidebar/Sidebar.tsx` — add a "Git" tab to the existing tab list
|
||||||
|
- `src/renderer/stores/settings-store.ts` — add 3 new fields
|
||||||
|
- `src/renderer/lib/validators.ts` — add 3 new fields to `settingsSchema`
|
||||||
|
- `src/renderer/lib/ipc.ts` — add 4 new IPC methods
|
||||||
|
- `src/renderer/lib/commands/register-menu-commands.ts` — add 8 new commands
|
||||||
|
- `src/main.js` (or split files) — add 4 main-process IPC handlers
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/component/tools/ReplPanel.test.tsx` — smoke test
|
||||||
|
- `tests/component/tools/PrintPreview.test.tsx` — smoke test
|
||||||
|
- `tests/component/modals/AsciiGeneratorDialog.test.tsx` — 3 tests
|
||||||
|
- `tests/component/modals/TableGeneratorDialog.test.tsx` — 3 tests
|
||||||
|
- `tests/component/modals/WordExportDialog.test.tsx` — 4 tests
|
||||||
|
- `tests/component/modals/FindInFilesDialog.test.tsx` — 4 tests
|
||||||
|
- `tests/component/sidebar/GitStatusPanel.test.tsx` — 3 tests
|
||||||
|
- `tests/component/layout/Breadcrumb.test.tsx` — extend with symbols test
|
||||||
|
- `tests/integration/phase9-tools-smoke.test.tsx` — 6 tests (one per command-triggered tool)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Data Flow
|
||||||
|
|
||||||
|
### 4.1 Word export (most complex)
|
||||||
|
|
||||||
|
1. User triggers `tools.exportWord` → `registerMenuCommands` opens the export-word modal via `useAppStore.openModal('export-word', { sourcePath: activeTabId })`
|
||||||
|
2. **Wait** — we need a new modal kind `export-word` in the `ModalState` union. Add it.
|
||||||
|
3. `WordExportDialog` (mounted by ModalLayer) shows:
|
||||||
|
- Template select: "Standard (bundled)" or "Custom .dotx (your file)" — pre-populated with `useSettingsStore.docxCustomTemplatePath`
|
||||||
|
- "Choose custom template..." button (file picker, saves to settings)
|
||||||
|
- Options: embed images (checkbox), include front matter (checkbox)
|
||||||
|
- Preview area: shows the generated docx structure (sizes, table of contents)
|
||||||
|
4. On submit:
|
||||||
|
- Renderer calls `lib/docx-export.ts#generateDocx(source, templatePath, options)` which uses the `docx` lib
|
||||||
|
- The lib takes a `Document` AST and produces a Blob
|
||||||
|
- ASCII tables are converted to monospace `<w:r>` runs (using `applyAsciiTransform` from Phase 7)
|
||||||
|
- Images are extracted from markdown and embedded as base64
|
||||||
|
- If a custom .dotx path is set, the renderer reads it via `ipc.file.read` and applies its styles (via `docx` lib's style support)
|
||||||
|
- User picks output path via `ipc.app.showSaveDialog`
|
||||||
|
- Writes Blob via `ipc.file.writeBuffer` (new)
|
||||||
|
- Toast success/failure
|
||||||
|
|
||||||
|
### 4.2 Find-in-files
|
||||||
|
|
||||||
|
1. User triggers `tools.findInFiles` → ModalLayer opens `FindInFilesDialog`
|
||||||
|
2. User types query, picks regex/literal, case-sensitive toggle
|
||||||
|
3. On submit: `ipc.file.search({ rootPath: useFileStore.rootPath, query, isRegex, caseSensitive })`
|
||||||
|
4. Backend walks the disk recursively, applies regex/literal match, returns `Array<{ filePath, line, content }>`
|
||||||
|
5. Dialog shows result list (file:line:content, clickable)
|
||||||
|
6. Click a result:
|
||||||
|
- `useFileStore.openFile(filePath)` if not already open
|
||||||
|
- Set the cursor in the editor to the matched line
|
||||||
|
7. Close the dialog
|
||||||
|
|
||||||
|
### 4.3 REPL (markdown snippet preview)
|
||||||
|
|
||||||
|
1. User triggers `tools.repl` → toggles `useSettingsStore.replOpen` (or a new dedicated `useReplStore`)
|
||||||
|
2. `ReplPanel` (mounted in App.tsx) is visible when `replOpen === true`
|
||||||
|
3. The panel has:
|
||||||
|
- Top half: textarea (user types/pastes markdown)
|
||||||
|
- Bottom half: rendered preview (uses `lib/markdown.ts` from Phase 1 + DOMPurify)
|
||||||
|
4. Updates are debounced (300ms) for the preview
|
||||||
|
5. Pure renderer-side, no IPC
|
||||||
|
|
||||||
|
### 4.4 Zen mode
|
||||||
|
|
||||||
|
1. User triggers `view.zenMode` → toggles `useSettingsStore.zenMode`
|
||||||
|
2. `AppShell` reads `zenMode` from store; when true, hides all chrome (header, tabs, toolbar, breadcrumb, status bar, sidebar)
|
||||||
|
3. Editor goes fullscreen
|
||||||
|
4. Pressing Esc exits zen mode (keydown listener in `use-zen-mode` hook)
|
||||||
|
|
||||||
|
### 4.5 Print preview
|
||||||
|
|
||||||
|
1. User triggers `file.print` → opens `PrintPreview` (full-window overlay)
|
||||||
|
2. The preview renders the current buffer's content as it would appear in print
|
||||||
|
3. Two buttons: "Print" (calls `ipc.file.print({ html })` which opens native print dialog) and "Close"
|
||||||
|
|
||||||
|
### 4.6 Minimap
|
||||||
|
|
||||||
|
1. `useSettingsStore.minimap` (existing setting) is read by `CodeMirrorEditor`
|
||||||
|
2. When true, the editor's extension includes `@replit/codemirror-minimap` (or a simpler custom implementation)
|
||||||
|
3. The minimap shows a shrunk version of the document on the right side of the editor
|
||||||
|
4. Toggling the setting adds/removes the extension dynamically
|
||||||
|
|
||||||
|
### 4.7 Breadcrumbs-with-symbols
|
||||||
|
|
||||||
|
1. The current `Breadcrumb` shows the file path. Extend it to also show markdown symbols (headings, code blocks)
|
||||||
|
2. Use a simple AST walk of the current buffer to extract heading levels
|
||||||
|
3. Show as a path-like navigation: `file.md > H1: Title > H2: Section > #line`
|
||||||
|
4. The `useSettingsStore.breadcrumbSymbols` toggle (default true) controls whether symbols are shown
|
||||||
|
|
||||||
|
### 4.8 Git status
|
||||||
|
|
||||||
|
1. On sidebar Git tab open, fetch `ipc.file.gitStatus({ rootPath: useFileStore.rootPath })`
|
||||||
|
2. The main process runs `git status --porcelain` (or equivalent) and returns the list
|
||||||
|
3. Show file list with status badges (M, A, D, ?)
|
||||||
|
4. Click a file opens it via `useFileStore.openFile`
|
||||||
|
5. `git.refresh` re-fetches
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Error Handling
|
||||||
|
|
||||||
|
- **Word export failures:** `lib/docx-export.ts` catches `docx` lib errors → toast.error
|
||||||
|
- **Word export missing .dotx:** if custom template path is set but file doesn't exist, show inline banner in the dialog
|
||||||
|
- **Find-in-files failures:** if `ipc.file.search` throws (regex syntax error, IO error), show inline banner in the dialog
|
||||||
|
- **REPL:** no IPC, no error handling needed
|
||||||
|
- **Git status:** if folder isn't a git repo, return empty array. Panel shows "Not a git repository" message
|
||||||
|
- **Print:** if `ipc.file.print` fails (no printer, user cancels), toast.error or silent close
|
||||||
|
- **Minimap, Breadcrumbs:** renderer-side, no errors
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Testing Strategy
|
||||||
|
|
||||||
|
- **Unit tests:** `lib/docx-export.ts` (markdown → docx conversion, ASCII handling), `lib/ascii-table.ts` (already tested)
|
||||||
|
- **Component tests:** 1-2 smoke tests per new component
|
||||||
|
- **Integration test:** `phase9-tools-smoke.test.tsx` covering the 6 command-triggered tools (dispatch opens correct modal/overlay)
|
||||||
|
- **Editor integrations:** minimap toggle, breadcrumbs render with symbols, git status panel render
|
||||||
|
- **Target: +30-40 new tests**, total ~290
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Risks & Open Questions
|
||||||
|
|
||||||
|
**Risks:**
|
||||||
|
- **`docx` lib bundle size (~500KB).** Acceptable for a desktop app but worth noting. Lazy-load if it becomes a concern.
|
||||||
|
- **Word export custom template parsing** — the `.dotx` format is a zip with XML inside. The `docx` lib may not fully support reading existing templates. v1 may need a simpler "styles only" extraction.
|
||||||
|
- **Find-in-files regex compilation** — invalid regex would throw. Validate on the renderer before calling IPC.
|
||||||
|
- **Minimap performance** — for large files, the minimap can slow down scrolling. CodeMirror's built-in minimap has performance options to configure.
|
||||||
|
|
||||||
|
**Open questions (deferrable):**
|
||||||
|
- **REPL persistence** — should the textarea content survive across modal close/reopen? → Decision: NO for v1. Keep simple.
|
||||||
|
- **Git status auto-refresh** — should it auto-refresh every N seconds? → Decision: NO for v1. Manual via `git.refresh` command.
|
||||||
|
- **Find-in-files result count limit** — what if there are 10,000 matches? → Decision: limit to 500 results for v1, show "X more matches" message.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Out of Scope (deferred to Phase 10 or later)
|
||||||
|
|
||||||
|
- Custom undo/redo (still not in scope)
|
||||||
|
- Snippet/template library
|
||||||
|
- Multi-cursor editing
|
||||||
|
- LSP / language server
|
||||||
|
- Phase 10 will delete legacy files including the old `src/print-preview.js`, `src/wordTemplateExporter.js`, `src/welcome.js`, `src/zen-mode.js`, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Success Criteria
|
||||||
|
|
||||||
|
Phase 9 is complete when:
|
||||||
|
- All 10 features implemented and accessible via the command store
|
||||||
|
- `lib/docx-export.ts` generates valid `.docx` files
|
||||||
|
- Find-in-files returns results from a recursive disk walk
|
||||||
|
- REPL renders markdown snippet previews
|
||||||
|
- Zen mode hides all chrome and Esc exits
|
||||||
|
- Print preview opens native print dialog
|
||||||
|
- Minimap appears when `useSettingsStore.minimap` is true
|
||||||
|
- Breadcrumbs show symbols by default
|
||||||
|
- Git status panel shows modified/added/deleted/untracked files
|
||||||
|
- ~+30-40 new tests, total ~290
|
||||||
|
- `npx vite build` succeeds
|
||||||
|
- Branch tagged `phase-9-advanced-tools` 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
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
# Phase 10 — Polish + Delete Legacy Design
|
||||||
|
|
||||||
|
> Companion to the parent plan: `docs/superpowers/plans/2026-06-05-react-ui-redesign.md` (Phase 10 is sketched at high level; this spec locks architecture, file map, deletion targets, and version strategy.)
|
||||||
|
|
||||||
|
**Date:** 2026-06-06
|
||||||
|
**Phase:** 10 of 10 (React + shadcn/ui UI redesign) — **FINAL**
|
||||||
|
**Tag (on completion):** `v5.0.0` (the first release tag, all prior phases were `phase-N-*` working tags)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Goal & Non-Goals
|
||||||
|
|
||||||
|
**Goal:** Finalize the React UI redesign. Decompose the legacy 146KB `src/main.js` into a feature-first modular structure under `src/main/`, remove the legacy vanilla-JS renderer and all dead IPC bridges, then ship **v5.0.0** with a CHANGELOG.
|
||||||
|
|
||||||
|
**Non-goals (Phase 10):**
|
||||||
|
- Adding new features (Phases 1-9 shipped all of them)
|
||||||
|
- A full main-process test suite (the existing main process is largely untested; adding tests is Phase 11+)
|
||||||
|
- Backwards compat shims for the legacy renderer
|
||||||
|
- Renderer-side refactor (already done)
|
||||||
|
- Migrating the renderer build pipeline further (vite configs are in place)
|
||||||
|
|
||||||
|
**Success criteria:**
|
||||||
|
- `src/main.js` is gone; `src/main/index.js` is the new entrypoint
|
||||||
|
- `package.json#main` points to `src/main/index.js`
|
||||||
|
- All 12 legacy renderer files are deleted
|
||||||
|
- All 9 dead IPC channels are removed from `preload.js` and `main.js`
|
||||||
|
- `src/index.html` is reduced to ~50 lines (just the Vite bootstrap)
|
||||||
|
- `package.json#version` is `5.0.0`
|
||||||
|
- `CHANGELOG.md` exists in Keep a Changelog 1.1.0 format
|
||||||
|
- `git grep -E "renderer\.js|command-palette|print-preview|welcome\.js|zen-mode|wordTemplate|ascii-generator|table-generator|styles\.css"` returns zero results
|
||||||
|
- All 305 tests still pass
|
||||||
|
- `npx vite build --config vite.renderer.config.ts` succeeds
|
||||||
|
- `npx electron .` launches and main window renders
|
||||||
|
- Tag `v5.0.0` pushed to origin
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Target Architecture
|
||||||
|
|
||||||
|
### 2.1 `src/main/` (feature-first decomposition)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/
|
||||||
|
├── index.js # entrypoint: bootstraps store, app, window, ipc
|
||||||
|
├── store.js # electron-store wrapper (preferences + wordTemplatePath)
|
||||||
|
├── ipc.js # ipcMain.handle registration (composes from modules)
|
||||||
|
├── files/
|
||||||
|
│ ├── index.js # file ops facade (read/write/list/pickFolder/pickFile)
|
||||||
|
│ ├── search.js # recursive regex search (used by find-in-files)
|
||||||
|
│ ├── git.js # git status porcelain parser
|
||||||
|
│ └── binary.js # writeBuffer helper (Uint8Array → file)
|
||||||
|
├── menu/
|
||||||
|
│ ├── index.js # buildMenu() — composes the app menu
|
||||||
|
│ └── items.js # individual menu items (File, Edit, View, etc.)
|
||||||
|
├── window/
|
||||||
|
│ ├── index.js # createMainWindow ONLY (createAsciiWindow/createTableWindow are DEAD)
|
||||||
|
│ └── state.js # window state persistence
|
||||||
|
├── word-template/
|
||||||
|
│ ├── index.js # WordTemplateExporter facade
|
||||||
|
│ ├── parser.js # .dotx parsing
|
||||||
|
│ ├── converter.js # markdown → docx
|
||||||
|
│ └── apply.js # apply template styles to converted docx
|
||||||
|
└── utils/
|
||||||
|
├── paths.js # path helpers
|
||||||
|
├── logger.js # structured logging
|
||||||
|
└── download.js # tool downloader
|
||||||
|
```
|
||||||
|
|
||||||
|
**Module rules:**
|
||||||
|
- Each file has one clear responsibility (no god files; CLAUDE.md says >300 lines is the cap)
|
||||||
|
- `index.js` is the public face of a folder; deeper files are private
|
||||||
|
- `src/main/index.js` (top-level) wires everything together
|
||||||
|
- Cross-folder imports go through `index.js`, not directly to internals
|
||||||
|
|
||||||
|
### 2.2 Entry point change
|
||||||
|
|
||||||
|
**Before:**
|
||||||
|
```json
|
||||||
|
// package.json
|
||||||
|
"main": "src/main.js"
|
||||||
|
```
|
||||||
|
|
||||||
|
**After:**
|
||||||
|
```json
|
||||||
|
// package.json
|
||||||
|
"main": "src/main/index.js"
|
||||||
|
```
|
||||||
|
|
||||||
|
The new `src/main/index.js` runs the same `app.whenReady().then(...)` flow that the current `src/main.js` does, but composes the decomposed modules.
|
||||||
|
|
||||||
|
### 2.3 What becomes dead code (removed during decomposition)
|
||||||
|
|
||||||
|
When the legacy renderer files are deleted, these main-process functions become orphaned and are removed too:
|
||||||
|
|
||||||
|
| Function | File | Why dead |
|
||||||
|
|---|---|---|
|
||||||
|
| `createAsciiWindow()` | `src/main/window/index.js` | Loads deleted `src/ascii-generator.html` |
|
||||||
|
| `createTableWindow()` | `src/main/window/index.js` | Loads deleted `src/table-generator.html` |
|
||||||
|
| `ipcMain.on('open-ascii-generator', ...)` | `src/main/index.js` (after decomposition) | Replaced by React `<AsciiGeneratorDialog>` |
|
||||||
|
| `ipcMain.on('open-table-generator', ...)` | `src/main/index.js` (after decomposition) | Replaced by React `<TableGeneratorDialog>` |
|
||||||
|
| `webContents.send('print-preview')` | `src/main/menu/items.js` | Replaced by React `<PrintPreview>` |
|
||||||
|
| `webContents.send('print-preview-styled')` | `src/main/menu/items.js` | Replaced by React `<PrintPreview>` |
|
||||||
|
| `webContents.send('toggle-command-palette')` | `src/main/menu/items.js` | Replaced by `useCommandStore` |
|
||||||
|
| `require('./wordTemplateExporter')` | `src/main/index.js` (after decomposition) | Replaced by `src/main/word-template/` + renderer-side `lib/docx-export.ts` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Legacy Deletion Map
|
||||||
|
|
||||||
|
### 3.1 Files to delete from `src/` (12 files, ~14,426 lines)
|
||||||
|
|
||||||
|
| File | Size | Lines | Replaced by |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `src/renderer.js` | 213KB | 5319 | `src/renderer/` (Phases 1-9) |
|
||||||
|
| `src/styles.css` | 74KB | 3723 | `src/renderer/index.css` + Tailwind |
|
||||||
|
| `src/styles-modern.css` | 71KB | 2625 | Tailwind + shadcn/ui |
|
||||||
|
| `src/styles-concreteinfo.css` | 21KB | 969 | Tailwind theme tokens |
|
||||||
|
| `src/styles-sidebar.css` | 9.7KB | 304 | `<Sidebar>` component |
|
||||||
|
| `src/styles-zen.css` | 2.1KB | 102 | Zen mode in AppShell |
|
||||||
|
| `src/styles-welcome.css` | 2.2KB | 24 | Welcome dialog |
|
||||||
|
| `src/fonts.css` | 1.8KB | (imported elsewhere) | Tailwind font config |
|
||||||
|
| `src/command-palette.js` | (small) | 109 | `useCommandStore` |
|
||||||
|
| `src/print-preview.js` | (small) | 138 | `<PrintPreview>` |
|
||||||
|
| `src/welcome.js` | (small) | 78 | `<Welcome>` modal |
|
||||||
|
| `src/zen-mode.js` | (small) | 292 | `use-zen-mode` hook + AppShell |
|
||||||
|
| `src/wordTemplateExporter.js` | (small) | 743 | `src/main/word-template/` + renderer `lib/docx-export.ts` |
|
||||||
|
| `src/ascii-generator.html` | 34KB | (HTML) | `<AsciiGeneratorDialog>` |
|
||||||
|
| `src/table-generator.html` | 18KB | (HTML) | `<TableGeneratorDialog>` |
|
||||||
|
| `src/index.html` | 103KB | 1667 | `src/renderer/index.html` (already exists, Vite root) |
|
||||||
|
|
||||||
|
**Total: 13 files = ~16,093 lines / ~548KB**
|
||||||
|
|
||||||
|
`src/renderer/index.html` (the live Vite template) is NOT deleted.
|
||||||
|
|
||||||
|
### 3.2 Dead IPC channels to remove from `src/preload.js`
|
||||||
|
|
||||||
|
- `toggle-command-palette` (line 238)
|
||||||
|
- `open-ascii-generator` (line 89)
|
||||||
|
- `open-table-generator` (line 92)
|
||||||
|
- `print-preview` (line 173)
|
||||||
|
- `print-preview-styled` (line 174)
|
||||||
|
- `show-table-generator` (line 180)
|
||||||
|
- `show-ascii-generator-window` (line 217)
|
||||||
|
- `show-ascii-generator` (line 218)
|
||||||
|
- `show-table-generator-window` (line 221)
|
||||||
|
|
||||||
|
And from the exposed API surface:
|
||||||
|
- `openAscii: () => ipcRenderer.send('open-ascii-generator')` (line 445)
|
||||||
|
- `openTable: () => ipcRenderer.send('open-table-generator')` (line 446)
|
||||||
|
|
||||||
|
**9 channel names + 2 API entries to remove.**
|
||||||
|
|
||||||
|
### 3.3 Legacy references in `src/index.html` (16 places) — **the LEGACY file at project root, 1667 lines**
|
||||||
|
|
||||||
|
- `<link rel="stylesheet" href="styles.css">` (line ~6)
|
||||||
|
- `<link rel="stylesheet" href="styles-welcome.css">` (line ~7)
|
||||||
|
- `<div id="print-preview-overlay" class="modal hidden" ...>` block (~10 lines)
|
||||||
|
- `<div class="command-palette-overlay hidden" id="command-palette-overlay">` block (~5 lines)
|
||||||
|
- `<script src="renderer.js"></script>` (final script tag)
|
||||||
|
|
||||||
|
**All of these are removed by deleting the file `src/index.html` entirely.**
|
||||||
|
|
||||||
|
The CURRENT live renderer template is **`src/renderer/index.html`** (already correct: minimal, CSP, Plus Jakarta Sans font, `<script type="module" src="./main.tsx">`). This file is **NOT touched** in Phase 10. Vite's `root` is set to `src/renderer/` in `vite.renderer.config.ts`, so `src/renderer/index.html` is the HTML template Vite uses. The `src/index.html` at the project root is an orphan from the pre-Vite era.
|
||||||
|
|
||||||
|
**Verification:** after deleting `src/index.html`, the renderer build still works because Vite doesn't look at the project root — it uses `src/renderer/index.html`.
|
||||||
|
|
||||||
|
### 3.4 Main process rewiring
|
||||||
|
|
||||||
|
- Remove `require('./wordTemplateExporter')` from main entrypoint
|
||||||
|
- Remove `webContents.send('print-preview*')` and `webContents.send('toggle-command-palette')` from menu items
|
||||||
|
- Remove `ipcMain.on('open-ascii-generator', ...)` and `ipcMain.on('open-table-generator', ...)` handlers
|
||||||
|
- Remove `asciiGeneratorWindow` and `tableGeneratorWindow` global state (and any references to `loadFile(...ascii-generator.html)` / `loadFile(...table-generator.html)`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. `src/index.html` — DELETE (not rewrite)
|
||||||
|
|
||||||
|
The current `src/index.html` is 1667 lines of legacy markup and is **DELETED** (not rewritten). The renderer is already correctly served by `src/renderer/index.html` (the Vite root). Deleting the legacy root-level `src/index.html` is the action — no replacement file is needed.
|
||||||
|
|
||||||
|
`src/renderer/index.html` (already correct) is NOT modified:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; ...">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>MarkdownConverter</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:..." rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body class="font-sans antialiased">
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="./main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Version Bump + CHANGELOG
|
||||||
|
|
||||||
|
### 5.1 `package.json`
|
||||||
|
|
||||||
|
```diff
|
||||||
|
- "version": "4.4.2",
|
||||||
|
+ "version": "5.0.0",
|
||||||
|
```
|
||||||
|
|
||||||
|
Major version bump because the legacy renderer removal is a breaking change for anyone who had plugins/integrations pointing at `src/renderer.js`.
|
||||||
|
|
||||||
|
### 5.2 `CHANGELOG.md` (new file, Keep a Changelog 1.1.0 format)
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to markdown-converter will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [5.0.0] - 2026-06-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Complete React 19 + Vite + TypeScript renderer** replacing the legacy vanilla-JS UI
|
||||||
|
- Native macOS/Windows/Linux menus with command palette and keyboard shortcuts
|
||||||
|
- Settings sheet (5 tabs: editor, theme, keybindings, advanced, about)
|
||||||
|
- Modal layer with 13 modal kinds (export PDF/DOCX/HTML/Word, batch, settings, about, welcome, confirm, ASCII gen, table gen, find in files)
|
||||||
|
- 10 advanced tools: ASCII generator, table generator, Word export, find-in-files, REPL, print preview, zen mode, minimap, breadcrumbs-with-symbols, git status
|
||||||
|
- Sonner toast notifications at 4 wire points
|
||||||
|
- 3 mount strategies: ModalLayer dialogs, App.tsx overlays, editor/sidebar integrations
|
||||||
|
- `ipc.file.writeBuffer` for renderer-side binary output
|
||||||
|
- `ipc.file.search` (recursive regex), `ipc.file.gitStatus`, `ipc.print.show`, `ipc.app.showSaveDialog`
|
||||||
|
- 305 unit + integration tests (vitest + React Testing Library)
|
||||||
|
- Per-package @radix-ui primitives
|
||||||
|
- shadcn/ui (new-york style) primitives
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **BREAKING**: Renderer is now React-only.
|
||||||
|
- Main process decomposed from 146KB `src/main.js` into feature-first modules under `src/main/`
|
||||||
|
- `src/index.html` reduced from 1667 to ~50 lines
|
||||||
|
- IPC contract: handlers throw, `safeCall` catches → `{ ok, error }`
|
||||||
|
- Settings store: `useSettingsStore` (zustand persist with zod)
|
||||||
|
- Modal state: `useAppStore.modal: ModalState` discriminated union
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- `src/renderer.js` (legacy vanilla-JS renderer, 5319 lines) — and `src/index.html` (1667 lines of legacy markup, replaced by `src/renderer/index.html` which is already the live Vite template)
|
||||||
|
- 7 legacy stylesheets (styles.css, styles-modern.css, styles-concreteinfo.css, styles-sidebar.css, styles-zen.css, styles-welcome.css, fonts.css)
|
||||||
|
- 5 legacy scripts (command-palette.js, print-preview.js, welcome.js, zen-mode.js, wordTemplateExporter.js)
|
||||||
|
- 2 legacy HTMLs (ascii-generator.html, table-generator.html)
|
||||||
|
- 9 dead IPC channels (toggle-command-palette, open-*/show-* ascii/table, print-preview*)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Task Decomposition
|
||||||
|
|
||||||
|
**10 tasks** (each independently verifiable, one feature per commit, no bundling):
|
||||||
|
|
||||||
|
1. **Decompose main.js — `src/main/files/`** (file ops facade, search, git, binary)
|
||||||
|
2. **Decompose main.js — `src/main/menu/`** (buildMenu + items, with dead sends removed)
|
||||||
|
3. **Decompose main.js — `src/main/window/`** (createMainWindow ONLY — ascii/table windows removed)
|
||||||
|
4. **Decompose main.js — `src/main/word-template/`** (WordTemplateExporter split into parser/converter/apply)
|
||||||
|
5. **Decompose main.js — `src/main/utils/` + `store.js` + `ipc.js` + `index.js`** (glue + new entrypoint)
|
||||||
|
6. **Trim preload.js** — remove 9 dead IPC channels + 2 exposed API entries
|
||||||
|
7. **Delete legacy renderer files** (13 files: renderer.js, 7 styles, fonts.css, 4 scripts, 3 htmls)
|
||||||
|
8. **Verify src/renderer/index.html is the live template** (no action needed if it's already correct)
|
||||||
|
9. **Bump package.json version to 5.0.0 + write CHANGELOG.md**
|
||||||
|
10. **Final verification + tag v5.0.0** (build, tests, grep, electron smoke)
|
||||||
|
|
||||||
|
Tasks 1-5 are subagent-driven (decomposition is mechanical given a clear target structure). Tasks 6-9 are direct edits. Task 10 is a verification gate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Verification Strategy
|
||||||
|
|
||||||
|
**Per task:**
|
||||||
|
- After each decomposition step: `npx vitest run` (305 still green)
|
||||||
|
- After main.js decomposition: `npx electron .` smoke — app starts, opens a file
|
||||||
|
- After deletions: `git grep -E "renderer\.js|command-palette|print-preview|welcome\.js|zen-mode|wordTemplate|ascii-generator|table-generator|styles\.css"` returns ZERO results
|
||||||
|
|
||||||
|
**Final (Task 10):**
|
||||||
|
- `npx vitest run` — 305 passing
|
||||||
|
- `npx vite build --config vite.renderer.config.ts` — succeeds
|
||||||
|
- `npx vite build --config vite.preload.config.ts` — succeeds
|
||||||
|
- `npx electron .` — app launches, main window renders
|
||||||
|
- Manual smoke: open a `.md` file, edit it, export to PDF/DOCX, use the command palette
|
||||||
|
- `git tag -a v5.0.0 -m "..."` and `git push origin v5.0.0`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Risks & Open Questions
|
||||||
|
|
||||||
|
**Risks:**
|
||||||
|
- **Decomposition regressions.** Splitting a 146KB main.js into 7+ files has surface area for missed imports / circular deps. Mitigation: tests stay green; electron smoke after each step.
|
||||||
|
- **Hidden legacy references.** `git grep` won't catch references inside minified bundles or in node_modules. Mitigation: vite build will fail if there's a dangling import.
|
||||||
|
- **`src/main/index.js` entrypoint change.** Anything in the build pipeline (electron-builder, scripts) that hardcodes `src/main.js` needs to be updated. Mitigation: grep all of `package.json`, `scripts/`, `vite.*.config.ts` for `main.js`.
|
||||||
|
|
||||||
|
**Open questions (resolved during brainstorming):**
|
||||||
|
- ~~Main process scope~~ → Full rewrite
|
||||||
|
- ~~Folder shape~~ → Feature-first
|
||||||
|
- ~~IPC migration~~ → Delete dead channels
|
||||||
|
- ~~Version strategy~~ → v5.0.0 with Keep a Changelog format
|
||||||
|
- ~~Order of work~~ → Decompose first, delete last
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Out of Scope (deferred to Phase 11+)
|
||||||
|
|
||||||
|
- Main process test suite
|
||||||
|
- Renderer-side further refactor
|
||||||
|
- New features
|
||||||
|
- Migration to tauri (separate plan in `docs/plans/2026-03-15-react-tauri-pwa.md`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Success Criteria
|
||||||
|
|
||||||
|
Phase 10 is complete when:
|
||||||
|
- All 10 tasks are committed, one per commit, no bundling
|
||||||
|
- `src/main/index.js` is the new entrypoint
|
||||||
|
- All 12 legacy files are deleted
|
||||||
|
- All 9 dead IPC channels are removed
|
||||||
|
- `package.json#version` is `5.0.0`, `package.json#main` is `src/main/index.js`
|
||||||
|
- `CHANGELOG.md` exists with a complete v5.0.0 entry
|
||||||
|
- 305 tests still pass
|
||||||
|
- `npx vite build` succeeds for both renderer and preload configs
|
||||||
|
- `npx electron .` launches and the app works end-to-end
|
||||||
|
- `git grep` for legacy references returns zero results
|
||||||
|
- Tag `v5.0.0` is created and pushed to origin
|
||||||
|
- Phase 10 is the LAST phase of the React UI redesign
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
# Production polish — v5 shippable build
|
||||||
|
|
||||||
|
**Date:** 2026-06-07
|
||||||
|
**Branch:** `react-electron`
|
||||||
|
**Status:** Draft, pending implementation plan
|
||||||
|
**Author:** Claude (brainstormed with Amit Haridas)
|
||||||
|
|
||||||
|
## 1. Goals & non-goals
|
||||||
|
|
||||||
|
### Goals
|
||||||
|
|
||||||
|
v5 is reliably shippable to two distribution channels:
|
||||||
|
|
||||||
|
- **GitHub Releases** (public, free, existing workflow).
|
||||||
|
- **ConcreteInfo update server** at `https://updates.concreteinfo.co.in/v5/` (self-hosted, for ConcreteInfo's own users).
|
||||||
|
|
||||||
|
Concretely:
|
||||||
|
|
||||||
|
- A non-blocking update banner surfaces "v5.0.2 is available" with a user-confirmed restart-to-install flow. No silent background installs.
|
||||||
|
- A light first-run wizard (theme + update channel + starter template), all skippable.
|
||||||
|
- One-shot auto-migration from v4.4.1 settings, with a v4 backup file and a toast on success/failure.
|
||||||
|
- Local crash dump capture (no third-party). CrashReportModal lets the user open the dump folder and copy/delete dumps.
|
||||||
|
- GitHub Actions CI that builds + uploads artifacts on tag and runs the test suite on every PR.
|
||||||
|
|
||||||
|
### Non-goals (deferred to v5.1+)
|
||||||
|
|
||||||
|
- **Code signing.** macOS Gatekeeper and Windows SmartScreen will warn. Re-evaluated for v5.1.
|
||||||
|
- **Sentry or any third-party crash reporting.** Local dumps only.
|
||||||
|
- **Auto-install on quit.** Always user-confirmed.
|
||||||
|
- **Delta updates** (full downloads only in v5).
|
||||||
|
- **Plugin system, cloud/licensing, perf/a11y** — each is its own subsequent spec.
|
||||||
|
|
||||||
|
## 2. Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
GitHub Releases (public) ConcreteInfo (CI feed)
|
||||||
|
└── *.zip, *.dmg, *.exe, └── *.zip, *.dmg, *.exe,
|
||||||
|
*.deb, *.rpm, *.deb, *.rpm,
|
||||||
|
latest.yml, latest- latest.yml, latest-
|
||||||
|
mac.yml, latest- mac.yml, latest-
|
||||||
|
linux.yml, latest- linux.yml, latest-
|
||||||
|
windows.yml windows.yml
|
||||||
|
▲ ▲
|
||||||
|
│ │
|
||||||
|
└──────┬───────────────────────┘
|
||||||
|
│ electron-updater reads
|
||||||
|
│ the channel chosen in
|
||||||
|
│ Settings (default: GitHub)
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ Main process (src/main/updater/) │
|
||||||
|
│ - Updater service: wraps electron-updater │
|
||||||
|
│ - Channel resolver: returns feed URL from setting │
|
||||||
|
│ - State machine: idle → checking → available → │
|
||||||
|
│ downloading → ready → installing │
|
||||||
|
│ - Crash writer: catches process.on('uncaught…) │
|
||||||
|
│ - Migration runner: idempotent, runs on app start│
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
▲ ▲
|
||||||
|
│ IPC (renderer→main, │ IPC (renderer→main,
|
||||||
|
│ allowlisted SEND) │ allowlisted SEND)
|
||||||
|
│ updater:check, │ crash:read,
|
||||||
|
│ updater:install, │ crash:open-dir,
|
||||||
|
│ updater:get-state │ crash:delete
|
||||||
|
│ │
|
||||||
|
│ IPC (main→renderer, │
|
||||||
|
│ allowlisted RECEIVE) │
|
||||||
|
│ updater:status │
|
||||||
|
▼ ▼
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ Renderer (preload bridge + React) │
|
||||||
|
│ - Update banner: "v5.0.2 available" │
|
||||||
|
│ - Settings: Update channel radio │
|
||||||
|
│ - First-run wizard: skip-links, all optional │
|
||||||
|
│ - Crash dialog: open dump dir, copy file │
|
||||||
|
│ - Migration: first-launch indicator in settings │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key boundaries
|
||||||
|
|
||||||
|
- **`src/main/updater/`** is a single new directory. `updater-service.js` owns the `electron-updater` lifecycle, never the renderer.
|
||||||
|
- **Renderer talks to updater over IPC only.** No direct `autoUpdater` import in preload. Channels must be in `ALLOWED_SEND_CHANNELS` / `ALLOWED_RECEIVE_CHANNELS`.
|
||||||
|
- **Channel switching is a settings change.** No restart required; the next `checkForUpdates()` reads the new feed URL.
|
||||||
|
- **Migration is idempotent.** Stores a `migration.version` key; skips if already at v5.
|
||||||
|
- **Crash writer never blocks startup.** Initialized in main entry, but a write failure is non-fatal.
|
||||||
|
|
||||||
|
## 3. Component breakdown
|
||||||
|
|
||||||
|
| Unit | What it does | How it's used | Depends on |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `main/updater/updater-service.js` | Owns `electron-updater`; exposes check/download/install; emits status events | Main process singleton; started after `app.whenReady()` | `electron-updater`, `electron` |
|
||||||
|
| `main/updater/feed-config.js` | Maps channel setting → feed URL; reads from `app.getPath('userData')/settings.json` | Called by updater-service on each check | settings store |
|
||||||
|
| `main/updater/crash-writer.js` | Hooks `process.on('uncaughtException', …)`; writes minidump + stack to `app.getPath('userData')/crashDumps/{timestamp}.json` | Initialized in main entry, before anything else | `electron`, `app.getPath` |
|
||||||
|
| `main/updater/migration-runner.js` | Reads v4 settings; transforms to v5 schema; writes backup; updates `migration.version` | Run from main entry on `app.whenReady()` | `fs`, settings store |
|
||||||
|
| `main/ipc/updater-handlers.js` | IPC handlers: `updater:check`, `updater:install`, `updater:get-state` | Registered in main entry | updater-service |
|
||||||
|
| `main/ipc/crash-handlers.js` | IPC handlers: `crash:read`, `crash:open-dir` | Registered in main entry | crash-writer |
|
||||||
|
| `preload.js` (extension) | Add `updater.check()`, `updater.install()`, `crash.read()`, `crash.openDir()` to `electronAPI`; add channels to allowlist | Preload runs at boot | existing preload |
|
||||||
|
| `renderer/lib/updater-store.ts` | Zustand store mirroring updater state; subscribes to `updater:status` events | Renderer; consumed by banner, settings, modals | `zustand`, IPC bridge |
|
||||||
|
| `renderer/components/UpdateBanner.tsx` | Non-blocking banner shown when `updater-store.status` is `available | downloading | ready` | Mounted in `App.tsx` next to header | updater-store, sonner |
|
||||||
|
| `renderer/components/FirstRunWizard.tsx` | 3-step modal with skip links; opens on first launch when `app-store.firstRun === true` | Mounted in `App.tsx` | app-store, settings-store, command-store |
|
||||||
|
| `renderer/components/modals/SettingsModal.tsx` (extend) | Add "Updates" section: channel radio, "Check now" button, auto-check toggle | Mounted via `useAppStore.modal` | updater-store, settings-store |
|
||||||
|
| `renderer/components/modals/CrashReportModal.tsx` | List local crash dumps; "Open dump folder", "Copy to clipboard", "Delete" actions | Mounted via `useAppStore.modal` | crash ipc, sonner |
|
||||||
|
| `renderer/lib/migrations/v4-to-v5.ts` | Pure function: `(v4Settings) => v5Settings` | Called from `migration-runner` | zod schemas |
|
||||||
|
|
||||||
|
### Data flow — "user clicks Check for updates"
|
||||||
|
|
||||||
|
1. Settings panel: `useSettingsStore.getState().setSetting('updateChannel', 'github' | 'concreteinfo')`.
|
||||||
|
2. `SettingsModal` calls `await ipc.updater.check()`.
|
||||||
|
3. Preload `safeCall` → `window.electronAPI.updater.check()` → `ipcRenderer.invoke('updater:check')`.
|
||||||
|
4. Main handler asks `updater-service` to `autoUpdater.checkForUpdates()` with the channel's feed URL.
|
||||||
|
5. `updater-service` emits `'updater:status', { state: 'available', version: '5.0.2' }`.
|
||||||
|
6. Preload forwards to `updater-store` via `window.electronAPI.on('updater:status', cb)`.
|
||||||
|
7. `updater-store` state flips to `available`; `UpdateBanner` renders.
|
||||||
|
8. User clicks "View release notes" → opens `https://github.com/.../releases/tag/v5.0.2` via `ipc.app.openExternal`.
|
||||||
|
9. User clicks "Restart to update" → calls `ipc.updater.install()`. `updater-service` calls `autoUpdater.quitAndInstall()`. App quits, relaunches into v5.0.2.
|
||||||
|
|
||||||
|
## 4. Error handling
|
||||||
|
|
||||||
|
### Updater
|
||||||
|
|
||||||
|
- **No network:** `autoUpdater.checkForUpdates()` rejects with `ENOTFOUND` / `ETIMEDOUT`. We catch, log to main log, emit `updater:status { state: 'error', code: 'NETWORK' }`. Banner shows "Couldn't check for updates. Try again." Toast fires inline at the wire point in `UpdateBanner` / `SettingsModal` on retry, matching the existing pattern (`toasts-inline-at-wire-points`).
|
||||||
|
- **Feed 404 / signature missing (N/A in v5 since unsigned):** Treat as configuration error. Log to main log with full URL. Banner shows "Update feed is misconfigured. Report this on GitHub." Crash-log-style entry is written.
|
||||||
|
- **Update available but download fails:** Banner flips to "Download failed. Try again." Clicking "Try again" re-invokes `autoUpdater.downloadUpdate()`. Three consecutive failures show a "Report issue" link in the banner.
|
||||||
|
- **Update installs but launch fails:** Worst case. We catch the post-`quitAndInstall` crash via `crash-writer` and write a marker file `app.getPath('userData')/update-failed.json` with the previous version. On next boot, the user is offered to revert manually by re-downloading from the GitHub release page (a "rolled back" banner instead of the wizard).
|
||||||
|
- **Concurrent checks:** Debounce 60s. A second `checkForUpdates()` within 60s is a no-op; returns the current state. The Check-Now button is disabled during a check.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
|
||||||
|
- **v4 settings file missing/corrupt:** Treat as "nothing to migrate." App starts with v5 defaults. Toast: "Welcome to v5 — using default settings."
|
||||||
|
- **Migration throws mid-transform:** Original v4 file is preserved as `settings.v4.bak.json` (already on disk). App starts with v5 defaults. Toast: "Couldn't migrate v4 settings — your old settings are preserved at {path}."
|
||||||
|
- **`migration.version === 5`:** Skip entirely. No-op.
|
||||||
|
|
||||||
|
### Crash writer
|
||||||
|
|
||||||
|
- **Dump write fails (disk full, permissions):** Print to stderr; do not crash the app. Recovery is "user's problem" — we never block app startup on the crash writer.
|
||||||
|
- **No dumps in dir:** CrashReportModal shows empty state: "No crashes recorded — nice work!"
|
||||||
|
|
||||||
|
### First-run wizard
|
||||||
|
|
||||||
|
- **Skip clicked at any step:** Sets `app-store.firstRun = false` and proceeds. All defaults already match the unselected choice, so this is non-destructive.
|
||||||
|
- **Wizard cannot reach settings (corrupt store):** Falls back to defaults silently. Wizard still closes.
|
||||||
|
|
||||||
|
## 5. Testing
|
||||||
|
|
||||||
|
### Unit (Vitest, renderer-side)
|
||||||
|
|
||||||
|
- `useUpdaterStore`: state transitions on each `updater:status` event; debounce on `check()`; reject on missing channel.
|
||||||
|
- `FirstRunWizard`: each step's CTA writes the right slice; "Skip" leaves defaults; "Skip at step 1" still closes the wizard and sets `firstRun = false`.
|
||||||
|
- `migrations/v4-to-v5`: golden-file tests — every v4 shape we ship transforms to expected v5 output. Idempotency: running twice yields identical v5 settings.
|
||||||
|
- `feed-config`: each channel setting resolves to the right feed URL; missing/unknown channel falls back to GitHub.
|
||||||
|
|
||||||
|
### Component (Vitest + RTL)
|
||||||
|
|
||||||
|
- `UpdateBanner`: hidden when state is `idle` or `error-network`; visible with the right copy in `available`/`downloading`/`ready`; Restart button calls `ipc.updater.install()`; "View release notes" opens the right URL via `ipc.app.openExternal`.
|
||||||
|
- `FirstRunWizard`: skip links work; theme picker updates the store; channel picker persists; template picker inserts into the new buffer.
|
||||||
|
- `CrashReportModal`: lists dumps from the IPC response; "Open folder" invokes `crash.openDir`; delete removes the file.
|
||||||
|
- `SettingsModal > Updates`: channel radio flips `settings-store.updateChannel`; "Check now" fires `ipc.updater.check`; auto-check toggle persists.
|
||||||
|
|
||||||
|
### Integration (Vitest, full app)
|
||||||
|
|
||||||
|
- **Migration end-to-end:** pre-seed a v4 settings file in `app.getPath('userData')/settings.json`, launch the app, verify v5 file is written, v4 backup exists, `migration.version === 5`, and the wizard opens on first run.
|
||||||
|
- **Update flow mock:** stub `electron-updater` to emit `available` → `downloading` → `ready`; verify the banner appears, Restart click triggers `quitAndInstall`, and the IPC sequence matches the allowlist.
|
||||||
|
|
||||||
|
### E2E (Playwright + Electron, runs the live app)
|
||||||
|
|
||||||
|
- Open the app, verify the FirstRun wizard renders. Skip. Verify the editor is visible.
|
||||||
|
- Open Settings, switch update channel from GitHub to ConcreteInfo, click Check now. Stub the feed response. Verify the banner appears with the right version.
|
||||||
|
- Click Restart. Verify the app calls `quitAndInstall` (assert on a mocked `autoUpdater.quitAndInstall`).
|
||||||
|
- Trigger an unhandled rejection in the renderer. Verify a dump is written to `crashDumps/`. Open the CrashReportModal, verify it appears in the list.
|
||||||
|
|
||||||
|
### Coverage targets
|
||||||
|
|
||||||
|
- Updater service: ≥ 90% (small surface, hot path).
|
||||||
|
- Migration runner: 100% of branches (idempotency, corrupt file, missing file, transform failure).
|
||||||
|
- FirstRunWizard: ≥ 80%.
|
||||||
|
- Component tests above any preset.
|
||||||
|
|
||||||
|
## 6. Distribution feed contracts
|
||||||
|
|
||||||
|
### GitHub Releases (default)
|
||||||
|
|
||||||
|
Feed URL pattern:
|
||||||
|
```
|
||||||
|
https://github.com/{owner}/{repo}/releases/download/v{version}/
|
||||||
|
```
|
||||||
|
|
||||||
|
For v5.0.2:
|
||||||
|
```
|
||||||
|
https://github.com/{owner}/{repo}/releases/download/v5.0.2/latest-mac.yml
|
||||||
|
https://github.com/{owner}/{repo}/releases/download/v5.0.2/latest-linux.yml
|
||||||
|
https://github.com/{owner}/{repo}/releases/download/v5.0.2/latest-windows.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
`electron-updater` reads these automatically given the GitHub owner/repo config. The release workflow already exists at `.github/workflows/release.yml` and builds `.dmg`, `.zip`, `.exe`, `.deb`, `.rpm`. We add `latest.yml` generation via `electron-builder --publish always` in the CI.
|
||||||
|
|
||||||
|
### ConcreteInfo feed
|
||||||
|
|
||||||
|
Feed URL:
|
||||||
|
```
|
||||||
|
https://updates.concreteinfo.co.in/v5/latest.yml
|
||||||
|
https://updates.concreteinfo.co.in/v5/latest-mac.yml
|
||||||
|
https://updates.concreteinfo.co.in/v5/latest-linux.yml
|
||||||
|
https://updates.concreteinfo.co.in/v5/latest-windows.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
CI mirrors the GitHub Release artifacts to this path on every release. ConcreteInfo infra is documented in `~/.claude-mmax/CLAUDE.md`; the coolify server is `localhost:8000`. The mirror is a static-file route — no auth, just version-prefixed.
|
||||||
|
|
||||||
|
## 7. First-run wizard contract
|
||||||
|
|
||||||
|
Three steps. Each step has "Skip" and "Back" links. Final step is "Done."
|
||||||
|
|
||||||
|
1. **Theme:** Light / Dark / System. Default: System. Persists to `settings-store.theme`.
|
||||||
|
2. **Update channel:** GitHub Releases / ConcreteInfo. Default: GitHub Releases. Persists to `settings-store.updateChannel`.
|
||||||
|
3. **Starter template:** Blank / README / Meeting notes / Blog post. Default: Blank. On "Done," creates an untitled buffer with the chosen template content.
|
||||||
|
|
||||||
|
`firstRun` lives in `app-store` (not persisted across app data resets) and is checked on every launch. Setting it to `false` either explicitly (skip/done) or implicitly (v4 migration succeeded) prevents re-showing.
|
||||||
|
|
||||||
|
## 8. Settings migration contract (v4.4.1 → v5.0.0)
|
||||||
|
|
||||||
|
`migration-runner` runs once on first v5 launch. It:
|
||||||
|
|
||||||
|
1. Reads `app.getPath('userData')/settings.json` if it exists.
|
||||||
|
2. Validates the v4 shape with a zod schema (`v4SettingsSchema`).
|
||||||
|
3. If valid: transforms via `migrations/v4-to-v5.ts` and writes the v5 settings to `settings.json`. Backs up v4 to `settings.v4.bak.json`. Sets `migration.version = 5` in the v5 file.
|
||||||
|
4. If missing or invalid: writes a fresh v5 settings file with defaults. `migration.version = 5`.
|
||||||
|
5. If transform throws: leaves v4 file in place as the "backup." App starts with defaults. Toast warns the user.
|
||||||
|
|
||||||
|
The transform handles:
|
||||||
|
|
||||||
|
- v4 `theme` ('light' | 'dark' | 'auto') → v5 `theme` ('light' | 'dark' | 'system').
|
||||||
|
- v4 `customCss` string → v5 `customCssPath` file path or `null`.
|
||||||
|
- v4 `recentFiles: string[]` → v5 `recentFiles` (unchanged shape).
|
||||||
|
- v4 `editorFontSize: number` → v5 `editorFontSize` (unchanged shape).
|
||||||
|
- v4 `keyBindings: object` → v5 `userBindings` (keymap).
|
||||||
|
- v4 `snippets: array` → v5 `snippets` (unchanged shape).
|
||||||
|
- v4 `pdfExportOptions` etc. → v5 schema for the new export pipeline.
|
||||||
|
|
||||||
|
Anything not in the v4 schema is dropped. Defaults are taken from the v5 zod schema.
|
||||||
|
|
||||||
|
## 9. IPC allowlist additions
|
||||||
|
|
||||||
|
`src/preload.js` adds these to `ALLOWED_SEND_CHANNELS`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
'updater:check',
|
||||||
|
'updater:install',
|
||||||
|
'updater:get-state',
|
||||||
|
'crash:read',
|
||||||
|
'crash:open-dir',
|
||||||
|
'crash:delete',
|
||||||
|
```
|
||||||
|
|
||||||
|
`ALLOWED_RECEIVE_CHANNELS`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
'updater:status',
|
||||||
|
```
|
||||||
|
|
||||||
|
The `electronAPI` object gets:
|
||||||
|
|
||||||
|
```js
|
||||||
|
updater: {
|
||||||
|
check: () => ipcRenderer.invoke('updater:check'),
|
||||||
|
install: () => ipcRenderer.invoke('updater:install'),
|
||||||
|
getState: () => ipcRenderer.invoke('updater:get-state'),
|
||||||
|
onStatus: (cb) => ipcRenderer.on('updater:status', (_, payload) => cb(payload)),
|
||||||
|
},
|
||||||
|
crash: {
|
||||||
|
read: () => ipcRenderer.invoke('crash:read'),
|
||||||
|
openDir: () => ipcRenderer.send('crash:open-dir'),
|
||||||
|
delete: (filename) => ipcRenderer.invoke('crash:delete', filename),
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
## 10. Risks & mitigations
|
||||||
|
|
||||||
|
| Risk | Mitigation |
|
||||||
|
|---|---|
|
||||||
|
| First-run wizard is annoying to long-time users | Skippable; only shows on first launch. `firstRun = false` is set permanently on first skip/done. |
|
||||||
|
| Auto-migration corrupts settings | Original v4 file is preserved as `settings.v4.bak.json`. Transform errors fall back to defaults and toast the user. |
|
||||||
|
| Crash writer fills disk | Cap at 20 dumps; oldest auto-pruned. |
|
||||||
|
| Update feed mirror drift between GitHub and CI | Mirror runs in CI on every release; manual `npm run publish:concreteinfo` available as fallback. |
|
||||||
|
| `electron-updater` is unsigned, so anyone can publish a "v5.0.2" to a mirror | We do not enable auto-install in v5 — every install is user-confirmed via the release-notes page. v5.1 adds signing. |
|
||||||
|
| First-run wizard blocks app start on a slow renderer | Wizard is non-blocking. App shell mounts and is interactive behind the modal. |
|
||||||
|
| Debounced `checkForUpdates()` may mask real errors | "Check now" button bypasses the debounce; debounce only applies to automatic checks. |
|
||||||
|
| CI release workflow is on a tag — broken tags must be re-tagged manually | Documented in CONTRIBUTING.md; pre-release tag re-runs the workflow. |
|
||||||
|
|
||||||
|
## 11. Out of scope (deferred)
|
||||||
|
|
||||||
|
- Code signing.
|
||||||
|
- Delta updates.
|
||||||
|
- Per-channel pre-release / beta tracks (only stable feeds in v5).
|
||||||
|
- Crash analytics / Sentry.
|
||||||
|
- Squirrel.Windows-specific quirks (we publish NSIS only).
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
# Monospace Font Embedding + Naming Differentiation
|
||||||
|
|
||||||
|
**Date:** 2026-07-22
|
||||||
|
**Branch:** react-electron
|
||||||
|
**Goal:** Bring `react-electron` to feature parity with `master` by porting the v4.5.0 "embedded monospace font" feature, and differentiate the dev build identity from the installed `markdown-converter` deb so the two can coexist on the same machine.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The `react-electron` branch is the active development branch — a major rewrite of the renderer in React 19 + TypeScript + Tailwind/shadcn while keeping the main process in CommonJS. As of commit `bb4e874` it is **ahead** of `master` in nearly every dimension (auto-updater, crash writer, migration runner, command palette, first-run wizard, updates settings, crash report modal, 30+ React modals, large-file mode, scoped CSS).
|
||||||
|
|
||||||
|
A repo-wide diff (`git diff --stat master..react-electron`) shows 301 files changed, +38,293/-26,786 lines. Master is **behind** react-electron.
|
||||||
|
|
||||||
|
The **only** feature present in `master` and absent in `react-electron` is the monospace-font-embedding feature added in master v4.5.0 (commits `3f8679c` through `b218c76`, 19 commits). It bundles JetBrains Mono + Fira Code TTFs and embeds them into PDF/DOCX/EPUB/HTML exports so ASCII art and code blocks render with the exact font the user sees in the preview.
|
||||||
|
|
||||||
|
A second concern: the user has `markdown-converter` installed as a `.deb`. Running `npm run dev` from this repo currently uses the same `appId` (`com.concreteinfo.markdownconverter`) and `productName` (`MarkdownConverter`), which triggers Electron's single-instance lock and confuses file-association routing. We rename this branch's identity to `Markdown Converter React` / `markdown-converter-react` to coexist.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### In scope
|
||||||
|
|
||||||
|
1. Port the monospace font embedding feature from `master` v4.5.0 into the react-electron branch:
|
||||||
|
- All five `src/main/*.js` modules (`MonospaceFontConfig`, `PdfFontHeader`, `DocxFontEmbedder`, `EpubFontEmbedder`, `ExportCss`)
|
||||||
|
- Settings schema module (`src/main/settings/monospaceSettings.js`)
|
||||||
|
- Two new IPC handlers (`get-monospace-settings`, `set-monospace-settings`) plus preload allowlist and TypeScript declaration
|
||||||
|
- Renderer body-class toggle and CSS tokens (`--font-mono-active`, `--font-mono-feature`)
|
||||||
|
- Bundled font assets: `JetBrainsMono-{Regular,Bold}.ttf`, `FiraCode-{Regular,Bold}.ttf` plus LICENSE files
|
||||||
|
- `asarUnpack` directive for `assets/fonts/**`
|
||||||
|
- `download-tools.js` extension to fetch Fira Code
|
||||||
|
- Wire `buildMonospaceExportCss`, `buildPdfFontHeader`, `DocxFontEmbedder.embed`, `EpubFontEmbedder.embed` into `src/main/index.js` export pipelines (PDF, DOCX, EPUB, HTML paths)
|
||||||
|
- Print-preview font integration (`src/renderer/components/preview/PrintPreviewFrame.tsx` or equivalent)
|
||||||
|
- Tests: one test file per new module mirroring master's coverage plus an E2E smoke test
|
||||||
|
|
||||||
|
2. Rename branch identity:
|
||||||
|
- `package.json` `name` → `markdown-converter-react`
|
||||||
|
- `package.json` `build.productName` → `Markdown Converter React`
|
||||||
|
- `package.json` `build.appId` → `com.concreteinfo.markdownconverter.react`
|
||||||
|
- `package.json` `build.linux.executableName` → `markdown-converter-react`
|
||||||
|
- Window title prefix → `Markdown Converter — React Dev` in dev mode (use `process.env.VITE_DEV_SERVER_URL` as the gate)
|
||||||
|
- Settings file path remains `userData/settings.json` (no migration needed) — but add a new key `appVariant: "react"` so the renderer can show the correct title
|
||||||
|
|
||||||
|
### Out of scope
|
||||||
|
|
||||||
|
- React renderer rewrites (already ahead of master)
|
||||||
|
- Auto-updater, crash, migration (already ahead of master)
|
||||||
|
- Tauri / Web migration
|
||||||
|
- Pandoc version bump
|
||||||
|
- Documentation beyond this spec, the implementation plan, and the changelog entry
|
||||||
|
- Changes to v4-to-v5 settings migration (we leave the existing runner alone)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Module layout (new files)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/
|
||||||
|
MonospaceFontConfig.js # path resolver — finds bundled TTF
|
||||||
|
PdfFontHeader.js # builds .tex fontspec header for xelatex/lualatex
|
||||||
|
DocxFontEmbedder.js # injects TTF into pandoc DOCX output (post-process)
|
||||||
|
EpubFontEmbedder.js # EPUB --epub-embed-font + manifest patch
|
||||||
|
ExportCss.js # builds CSS string with woff2 embedded as base64
|
||||||
|
settings/
|
||||||
|
monospaceSettings.js # schema, defaults, family map
|
||||||
|
ipc/
|
||||||
|
monospace-handlers.js # IPC handler registration
|
||||||
|
utils/
|
||||||
|
(existing) # no change
|
||||||
|
|
||||||
|
src/renderer/
|
||||||
|
hooks/
|
||||||
|
use-monospace-classes.ts # toggles body.mono-{jetbrains,fira}{,-ligatures} classes
|
||||||
|
components/preview/
|
||||||
|
PrintPreviewFrame.tsx # wire print preview to monospace settings via IPC
|
||||||
|
styles/globals.css # add --font-mono-active/--font-mono-feature declarations
|
||||||
|
types/electron.d.ts # extend ElectronAPI with monospace.{getSettings,saveSettings}
|
||||||
|
|
||||||
|
src/preload.js # add monospace channels to ALLOWED_SEND_CHANNELS + expose on window.electronAPI.monospace
|
||||||
|
|
||||||
|
assets/fonts/
|
||||||
|
JetBrainsMono-Regular.ttf # bundled, ~270 KB
|
||||||
|
JetBrainsMono-Bold.ttf # bundled, ~278 KB
|
||||||
|
JetBrainsMono-LICENSE.txt
|
||||||
|
FiraCode-Regular.ttf # bundled, ~300 KB
|
||||||
|
FiraCode-Bold.ttf # bundled, ~300 KB
|
||||||
|
FiraCode-LICENSE.txt
|
||||||
|
|
||||||
|
scripts/download-tools.js # extend to fetch Fira Code
|
||||||
|
|
||||||
|
tests/
|
||||||
|
unit/main/monospace/
|
||||||
|
MonospaceFontConfig.test.js
|
||||||
|
monospaceSettings.test.js
|
||||||
|
PdfFontHeader.test.js
|
||||||
|
DocxFontEmbedder.test.js
|
||||||
|
EpubFontEmbedder.test.js
|
||||||
|
ExportCss.test.js
|
||||||
|
monospace-handlers.test.js
|
||||||
|
smoke-e2e-monospace.js # e2e: convert ASCII-art Markdown → PDF/DOCX/EPUB/HTML, assert TTF references appear in output
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key interfaces (TypeScript-style for clarity)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// src/main/settings/monospaceSettings.js
|
||||||
|
type MonoFont = 'jetbrains-mono' | 'fira-code';
|
||||||
|
const FAMILY_BY_KEY: Record<MonoFont, string> = {
|
||||||
|
'jetbrains-mono': 'JetBrains Mono',
|
||||||
|
'fira-code': 'Fira Code',
|
||||||
|
};
|
||||||
|
function getActiveMonoFont(settings): string;
|
||||||
|
function isLigaturesEnabled(settings): boolean;
|
||||||
|
function safeMonospaceSettings(input): { monospaceFont: MonoFont; monospaceLigatures: boolean };
|
||||||
|
|
||||||
|
// src/main/MonospaceFontConfig.js
|
||||||
|
function getMonoFontTtfPath(familyKey, weight = 400): string | null; // null if asset missing
|
||||||
|
function ligaturesEnabled(settings): boolean;
|
||||||
|
function getActiveFamily(settings): string;
|
||||||
|
|
||||||
|
// src/main/PdfFontHeader.js
|
||||||
|
function buildPdfFontHeader(settings, ttfPath, fontFamily): { headerPath: string; familyName: string };
|
||||||
|
|
||||||
|
// src/main/DocxFontEmbedder.js
|
||||||
|
async function embedDocxFont(inputDocxPath, outputDocxPath, ttfPath, fontFamily): Promise<void>;
|
||||||
|
async function buildDocxWithEmbeddedFont(pandocArgs, settings): Promise<{args, postProcess}>;
|
||||||
|
|
||||||
|
// src/main/EpubFontEmbedder.js
|
||||||
|
async function embedEpubFont(epubPath, ttfPath, fontFamily): Promise<void>;
|
||||||
|
function withEpubEmbedFontArgs(pandocArgs, ttfPath, fontFamily): string[];
|
||||||
|
|
||||||
|
// src/main/ExportCss.js
|
||||||
|
function buildExportCss(settings, { woff2Base64, family, ligatures }): string;
|
||||||
|
function buildFontFaceBlock(familyKey, woff2Base64): string;
|
||||||
|
|
||||||
|
// src/main/ipc/monospace-handlers.js
|
||||||
|
function register({ getMainWindow }): void;
|
||||||
|
// ipcMain.handle('get-monospace-settings', () => ({ monospaceFont, monospaceLigatures }))
|
||||||
|
// ipcMain.handle('set-monospace-settings', (_e, partial) => safeMonospaceSettings(partial) → persist + broadcast)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Renderer integration
|
||||||
|
|
||||||
|
- `use-monospace-classes.ts` hook runs once on mount, calls `electronAPI.monospace.getSettings()`, applies `document.body.classList` of:
|
||||||
|
- `mono-jetbrains-mono` | `mono-fira-code`
|
||||||
|
- `mono-ligatures-on` | `mono-ligatures-off`
|
||||||
|
- CSS in `globals.css`:
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--font-mono-active: 'JetBrains Mono', 'SF Mono', Monaco, 'Courier New', monospace;
|
||||||
|
--font-mono-feature: 'liga' 0, 'calt' 0;
|
||||||
|
}
|
||||||
|
body.mono-fira-code { --font-mono-active: 'Fira Code', 'JetBrains Mono', 'SF Mono', monospace; }
|
||||||
|
body.mono-ligatures-on { --font-mono-feature: 'liga' 1, 'calt' 1; }
|
||||||
|
```
|
||||||
|
- All existing `font-family: monospace` and `font-family: var(--font-mono)` usages continue to work; the new tokens sit above them.
|
||||||
|
|
||||||
|
### Wiring into export pipelines
|
||||||
|
|
||||||
|
In `src/main/index.js` `exportWithPandoc` (PDF branch):
|
||||||
|
- Read `monospaceFont` + `monospaceLigatures` from settings
|
||||||
|
- Resolve TTF path via `MonospaceFontConfig.getMonoFontTtfPath`
|
||||||
|
- If path exists: build font header via `PdfFontHeader.buildPdfFontHeader`, pass `--include-in-header=…`
|
||||||
|
- If path missing: log warning, fall back to existing `-V monofont=Consolas` behavior
|
||||||
|
|
||||||
|
In DOCX branch: invoke `DocxFontEmbedder.embedDocxFont` post-pandoc.
|
||||||
|
In EPUB branch: prepend `--epub-embed-font=…` to pandoc args; call `EpubFontEmbedder.embedEpubFont` to patch manifest.
|
||||||
|
In HTML branch: write CSS via `ExportCss.buildExportCss` (embed woff2 as base64) and reference in `<style>`.
|
||||||
|
|
||||||
|
### Naming differentiation
|
||||||
|
|
||||||
|
`package.json` changes:
|
||||||
|
```diff
|
||||||
|
- "name": "markdown-converter"
|
||||||
|
+ "name": "markdown-converter-react"
|
||||||
|
- "productName": "MarkdownConverter"
|
||||||
|
+ "productName": "Markdown Converter React"
|
||||||
|
- "appId": "com.concreteinfo.markdownconverter"
|
||||||
|
+ "appId": "com.concreteinfo.markdownconverter.react"
|
||||||
|
+ "linux": {
|
||||||
|
+ "executableName": "markdown-converter-react",
|
||||||
|
+ "synopsis": "Markdown editor (React build)",
|
||||||
|
+ "description": "Markdown editor and universal file converter — React build"
|
||||||
|
+ }
|
||||||
|
```
|
||||||
|
|
||||||
|
`src/main/window/index.js`:
|
||||||
|
```js
|
||||||
|
const isDev = !!process.env.VITE_DEV_SERVER_URL;
|
||||||
|
const titleSuffix = isDev ? ' — React Dev' : '';
|
||||||
|
mainWindow = new BrowserWindow({
|
||||||
|
title: `Markdown Converter${titleSuffix}`,
|
||||||
|
...
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Settings impact
|
||||||
|
|
||||||
|
Add two keys to `migration-transform.js` v5 schema with safe defaults:
|
||||||
|
- `monospaceFont: z.enum(['jetbrains-mono', 'fira-code']).default('jetbrains-mono')`
|
||||||
|
- `monospaceLigatures: z.boolean().default(false)`
|
||||||
|
- `appVariant: z.enum(['classic', 'react']).default('react')`
|
||||||
|
|
||||||
|
Existing user settings remain valid; the migration just fills in the new defaults.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing strategy (TDD)
|
||||||
|
|
||||||
|
For each new module: red-green-refactor.
|
||||||
|
|
||||||
|
1. `MonospaceFontConfig.test.js` — uses tmpdir + mocked `process.resourcesPath` to assert resolution from `assets/fonts/JetBrainsMono-Regular.ttf`. Covers missing-file fallback.
|
||||||
|
2. `monospaceSettings.test.js` — schema validation: rejects unknown fonts, coerces ligatures boolean, fills defaults.
|
||||||
|
3. `PdfFontHeader.test.js` — writes a temp `.tex` file, asserts `\setmonofont{JetBrainsMono-Regular.ttf}[...]` lines match.
|
||||||
|
4. `DocxFontEmbedder.test.js` — given a minimal DOCX zip, asserts `word/fonts/` contains the TTF and `word/_rels/fontTable.xml.rels` references it.
|
||||||
|
5. `EpubFontEmbedder.test.js` — asserts `META-INF/container.xml` and `content.opf` updated after `--epub-embed-font`.
|
||||||
|
6. `ExportCss.test.js` — base64 round-trip: `atob(css.match(/base64,([A-Za-z0-9+/=]+)/)[1])` returns the original woff2 bytes.
|
||||||
|
7. `monospace-handlers.test.js` — invokes the registered handlers against `ipcMain` mock; asserts settings persistence + broadcast.
|
||||||
|
8. `smoke-e2e-monospace.js` — runs `pandoc` end-to-end against a fixture markdown with ASCII art; greps output for font references.
|
||||||
|
|
||||||
|
Coverage threshold maintained: jest at 15%, vitest at v8 + renderer lines.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- **TTF download license** — Fira Code is OFL-1.1; JetBrains Mono is OFL-1.1. Both allow redistribution; LICENSE files ship alongside TTFs. No risk.
|
||||||
|
- **Pandoc version sensitivity** — `--epub-embed-font` requires pandoc ≥ 2.19. The download-tools script pins to 3.9.0.2; check `pandocVersion` and gracefully fall back if older.
|
||||||
|
- **asarUnpack size** — adding ~1.2 MB of TTFs to packaged builds. Acceptable; matches master.
|
||||||
|
- **Dev/prod appId split** — if a user installs both `markdown-converter` and `markdown-converter-react` debs, their settings files are separate (`userData/com.concreteinfo.markdownconverter.react/settings.json`). Documented in README.
|
||||||
|
- **Test environment** — the e2e smoke test requires pandoc available locally. We'll `test.skip` if `which pandoc` fails.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Definition of done
|
||||||
|
|
||||||
|
- [ ] All planned steps implemented, not just the first/easiest ones
|
||||||
|
- [ ] No forbidden markers (`TODO`, `FIXME`, `XXX`, `HACK`, `not implemented`, `placeholder`, `stub`, `coming soon`) in changed source
|
||||||
|
- [ ] New test suites pass; existing 638 tests still pass
|
||||||
|
- [ ] `npm run build:linux` produces a `.deb` artifact named `markdown-converter-react_*_amd64.deb`
|
||||||
|
- [ ] App launches in dev mode with title `Markdown Converter — React Dev`
|
||||||
|
- [ ] E2E smoke test confirms TTF references in PDF/DOCX/EPUB/HTML output
|
||||||
|
- [ ] CHANGELOG.md updated with a "5.1.0 — react-electron parity" entry
|
||||||
|
- [ ] No unrelated refactors; every changed line traces to the request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Learning collaboration
|
||||||
|
|
||||||
|
Per the project's learning-mode preference, the user will be asked to contribute two 5-10 line decisions during implementation:
|
||||||
|
|
||||||
|
1. **Default monospace family** in `monospaceSettings.js` (`jetbrains-mono` vs `fira-code` vs `system-fallback`).
|
||||||
|
2. **Body-class gating strategy** in `use-monospace-classes.ts` (apply on every settings change vs debounce vs once-on-mount).
|
||||||
|
|
||||||
|
These choices shape the feature's behavior in ways that benefit from the user's domain knowledge.
|
||||||
+1
-1
@@ -85,7 +85,7 @@ module.exports = [
|
|||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
// Error prevention
|
// Error prevention
|
||||||
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
'no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
|
||||||
'no-undef': 'error',
|
'no-undef': 'error',
|
||||||
'no-console': 'off', // Allow console for Electron apps
|
'no-console': 'off', // Allow console for Electron apps
|
||||||
|
|
||||||
|
|||||||
+17
-5
@@ -10,17 +10,29 @@ module.exports = {
|
|||||||
// Root directory
|
// Root directory
|
||||||
rootDir: '.',
|
rootDir: '.',
|
||||||
|
|
||||||
// Test file patterns
|
// Test file patterns — scoped to ./tests/ only so dist/ artifacts like
|
||||||
|
// .snap packages don't get matched as test suites.
|
||||||
testMatch: [
|
testMatch: [
|
||||||
'**/tests/**/*.test.js',
|
'<rootDir>/tests/**/*.test.js',
|
||||||
'**/tests/**/*.spec.js'
|
'<rootDir>/tests/**/*.spec.js'
|
||||||
|
],
|
||||||
|
|
||||||
|
// Ignore build outputs so .snap packages and bundled .asar contents
|
||||||
|
// never enter jest's file discovery.
|
||||||
|
testPathIgnorePatterns: [
|
||||||
|
'/node_modules/',
|
||||||
|
'/dist/',
|
||||||
|
'/\\.git/'
|
||||||
|
],
|
||||||
|
modulePathIgnorePatterns: [
|
||||||
|
'/node_modules/',
|
||||||
|
'/dist/'
|
||||||
],
|
],
|
||||||
|
|
||||||
// Coverage configuration
|
// Coverage configuration
|
||||||
collectCoverageFrom: [
|
collectCoverageFrom: [
|
||||||
'src/**/*.js',
|
'src/**/*.js',
|
||||||
'!src/main.js', // Main process needs electron-mock
|
'!src/main/**', // Main process needs electron-mock
|
||||||
'!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/**'
|
||||||
],
|
],
|
||||||
|
|||||||
Generated
+5034
-615
File diff suppressed because it is too large
Load Diff
+124
-19
@@ -1,13 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "markdown-converter",
|
"name": "markdown-converter-react",
|
||||||
"version": "4.4.1",
|
"version": "5.0.1",
|
||||||
"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 (React build)",
|
||||||
"main": "src/main.js",
|
"main": "src/main/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "electron .",
|
"start": "electron .",
|
||||||
|
"dev:renderer": "vite --config vite.renderer.config.ts",
|
||||||
|
"dev:electron": "wait-on tcp:5173 && cross-env VITE_DEV_SERVER_URL=http://localhost:5173 ELECTRON_DISABLE_SANDBOX=1 electron . -- --no-sandbox --disable-gpu --disable-software-rasterizer --disable-dev-shm-usage",
|
||||||
|
"dev": "concurrently -k -n vite,electron -c blue,green \"npm:dev:renderer\" \"npm:dev:electron\"",
|
||||||
|
"build:renderer": "vite build --config vite.renderer.config.ts",
|
||||||
|
"preview": "npm run build:renderer && electron .",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"test:coverage": "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",
|
||||||
@@ -24,7 +32,9 @@
|
|||||||
"dist": "electron-builder --publish=never",
|
"dist": "electron-builder --publish=never",
|
||||||
"dist:all": "electron-builder -mwl",
|
"dist:all": "electron-builder -mwl",
|
||||||
"download-tools": "node scripts/download-tools.js",
|
"download-tools": "node scripts/download-tools.js",
|
||||||
"generate-icons": "node scripts/generate-icons.js"
|
"generate-icons": "node scripts/generate-icons.js",
|
||||||
|
"build:icon-icns": "node scripts/build-icon-icns.js",
|
||||||
|
"publish:concreteinfo": "node scripts/publish-concreteinfo.js"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"markdown",
|
"markdown",
|
||||||
@@ -43,7 +53,21 @@
|
|||||||
"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/figlet": "^1.7.0",
|
||||||
|
"@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",
|
||||||
|
"concurrently": "^10.0.3",
|
||||||
"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,8 +76,18 @@
|
|||||||
"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",
|
||||||
|
"jsdom": "^29.1.1",
|
||||||
|
"lucide-react": "^1.17.0",
|
||||||
|
"postcss": "^8.5.15",
|
||||||
"prettier": "^3.7.4",
|
"prettier": "^3.7.4",
|
||||||
"sharp": "^0.34.3"
|
"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",
|
||||||
|
"wait-on": "^9.0.10"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.20.1",
|
"@codemirror/autocomplete": "^6.20.1",
|
||||||
@@ -70,25 +104,54 @@
|
|||||||
"@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.7.1",
|
||||||
"docx4js": "^3.3.0",
|
"docx4js": "^2.0.1",
|
||||||
"dompurify": "^3.3.1",
|
"dompurify": "^3.3.1",
|
||||||
"electron-store": "^10.1.0",
|
"electron-store": "^10.1.0",
|
||||||
|
"electron-updater": "^6.8.9",
|
||||||
"ffmpeg-static": "^5.3.0",
|
"ffmpeg-static": "^5.3.0",
|
||||||
|
"figlet": "^1.11.0",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
"html2pdf.js": "^0.14.0",
|
"html2pdf.js": "^0.14.0",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
@@ -98,22 +161,29 @@
|
|||||||
"lodash": "^4.17.21"
|
"lodash": "^4.17.21"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"appId": "com.concreteinfo.markdownconverter",
|
"appId": "com.concreteinfo.markdownconverter.react",
|
||||||
"productName": "MarkdownConverter",
|
"productName": "Markdown Converter React",
|
||||||
"copyright": "Copyright (C) 2024-2025 ConcreteInfo",
|
"copyright": "Copyright (C) 2024-2025 ConcreteInfo",
|
||||||
"directories": {
|
"directories": {
|
||||||
"output": "dist"
|
"output": "dist"
|
||||||
},
|
},
|
||||||
"icon": "assets/icon",
|
"icon": "assets/icon",
|
||||||
"files": [
|
"files": [
|
||||||
"src/**/*",
|
"src/main/**/*",
|
||||||
"assets/**/*",
|
"src/preload.js",
|
||||||
"scripts/**/*",
|
"src/plugins/**/*",
|
||||||
"node_modules/**/*",
|
"assets/fonts/**",
|
||||||
"package.json"
|
"package.json"
|
||||||
],
|
],
|
||||||
"asarUnpack": [
|
"asarUnpack": [
|
||||||
"node_modules/ffmpeg-static/**"
|
"node_modules/ffmpeg-static/**",
|
||||||
|
"assets/fonts/**"
|
||||||
|
],
|
||||||
|
"extraResources": [
|
||||||
|
{
|
||||||
|
"from": "dist/renderer",
|
||||||
|
"to": "renderer"
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"extraFiles": [],
|
"extraFiles": [],
|
||||||
"fileAssociations": [
|
"fileAssociations": [
|
||||||
@@ -141,7 +211,28 @@
|
|||||||
],
|
],
|
||||||
"mac": {
|
"mac": {
|
||||||
"category": "public.app-category.productivity",
|
"category": "public.app-category.productivity",
|
||||||
"identity": null
|
"identity": null,
|
||||||
|
"target": [
|
||||||
|
{
|
||||||
|
"target": "dmg",
|
||||||
|
"arch": [
|
||||||
|
"x64",
|
||||||
|
"arm64"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"target": "zip",
|
||||||
|
"arch": [
|
||||||
|
"x64",
|
||||||
|
"arm64"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"icon": "assets/icon.icns",
|
||||||
|
"darkModeSupport": true,
|
||||||
|
"hardenedRuntime": false,
|
||||||
|
"gatekeeperAssess": false,
|
||||||
|
"entitlements": null
|
||||||
},
|
},
|
||||||
"win": {
|
"win": {
|
||||||
"target": [
|
"target": [
|
||||||
@@ -170,7 +261,10 @@
|
|||||||
"verifyUpdateCodeSignature": false,
|
"verifyUpdateCodeSignature": false,
|
||||||
"signAndEditExecutable": false,
|
"signAndEditExecutable": false,
|
||||||
"extraFiles": [
|
"extraFiles": [
|
||||||
{ "from": "bin/win32/pandoc.exe", "to": "bin/pandoc.exe" }
|
{
|
||||||
|
"from": "bin/win32/pandoc.exe",
|
||||||
|
"to": "bin/pandoc.exe"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"nsis": {
|
"nsis": {
|
||||||
@@ -197,8 +291,13 @@
|
|||||||
],
|
],
|
||||||
"category": "Utility",
|
"category": "Utility",
|
||||||
"maintainer": "ConcreteInfo <amit.wh@gmail.com>",
|
"maintainer": "ConcreteInfo <amit.wh@gmail.com>",
|
||||||
|
"executableName": "markdown-converter-react",
|
||||||
|
"synopsis": "Markdown editor and converter (React build)",
|
||||||
"extraFiles": [
|
"extraFiles": [
|
||||||
{ "from": "bin/linux/pandoc", "to": "bin/pandoc" }
|
{
|
||||||
|
"from": "bin/linux/pandoc",
|
||||||
|
"to": "bin/pandoc"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"deb": {
|
"deb": {
|
||||||
@@ -208,6 +307,12 @@
|
|||||||
],
|
],
|
||||||
"description": "Professional Markdown editor and universal file converter",
|
"description": "Professional Markdown editor and universal file converter",
|
||||||
"maintainer": "ConcreteInfo <amit.wh@gmail.com>"
|
"maintainer": "ConcreteInfo <amit.wh@gmail.com>"
|
||||||
|
},
|
||||||
|
"publish": {
|
||||||
|
"provider": "github",
|
||||||
|
"owner": "amitwh",
|
||||||
|
"repo": "markdown-converter",
|
||||||
|
"releaseType": "release"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
+718
@@ -0,0 +1,718 @@
|
|||||||
|
# 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,TypeScript`.
|
||||||
|
|
||||||
|
```
|
||||||
|
scripts/download-tools.js:
|
||||||
|
L28 function findFile
|
||||||
|
L46 method extract (PANDOC_CONFIG.linux)
|
||||||
|
L61 method extract (PANDOC_CONFIG.win32)
|
||||||
|
L77 method extract (PANDOC_CONFIG.darwin)
|
||||||
|
L90 function download
|
||||||
|
L97 function get (download)
|
||||||
|
L136 function downloadPandoc
|
||||||
|
|
||||||
|
scripts/generate-icons.js:
|
||||||
|
L17 function generateIcons
|
||||||
|
|
||||||
|
scripts/verify-open-export.mjs:
|
||||||
|
L60 function showSaveDialogSync (dialog)
|
||||||
|
|
||||||
|
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/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/GitOperations.js:
|
||||||
|
L3 function getGitInstance
|
||||||
|
L7 function getStatus
|
||||||
|
L31 function stage
|
||||||
|
L56 function commit
|
||||||
|
L66 function log
|
||||||
|
L84 function diff
|
||||||
|
|
||||||
|
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/main/files/binary.js:
|
||||||
|
L6 function register
|
||||||
|
|
||||||
|
src/main/files/git.js:
|
||||||
|
L6 function register
|
||||||
|
|
||||||
|
src/main/files/index.js:
|
||||||
|
L9 function register
|
||||||
|
|
||||||
|
src/main/index.js:
|
||||||
|
L28 function getPandocPath
|
||||||
|
L46 function getFFmpegPath
|
||||||
|
L65 function sanitizeErrorMessage
|
||||||
|
L74 function createRateLimiter
|
||||||
|
L76 function canProceed (createRateLimiter)
|
||||||
|
L86 function convertDataToMarkdown
|
||||||
|
L108 function runPandocCmd
|
||||||
|
L124 function parseCommand
|
||||||
|
L319 function checkPandocAvailability
|
||||||
|
L334 function showAboutDialog
|
||||||
|
L437 function showDependenciesDialog
|
||||||
|
L550 function openFile
|
||||||
|
L580 function openPdfFile
|
||||||
|
L599 function saveAsFile
|
||||||
|
L614 function exportFile
|
||||||
|
L624 function showExportOptionsDialog
|
||||||
|
L628 function showBatchConversionDialog
|
||||||
|
L633 function selectWordTemplate
|
||||||
|
L654 function showTemplateSettings
|
||||||
|
L847 function processDynamicFields
|
||||||
|
L868 function setDocxPageSize
|
||||||
|
L927 function addHeaderFooterToDocx
|
||||||
|
L1060 function exportWordWithTemplate
|
||||||
|
L1100 function exportPDFViaWordTemplate
|
||||||
|
L1180 function showUniversalConverterDialog
|
||||||
|
L1185 function showPDFEditorDialog
|
||||||
|
L1195 function checkConverterAvailable
|
||||||
|
L1336 function collectFiles
|
||||||
|
L1431 function convertWithLibreOffice
|
||||||
|
L1466 function convertWithImageMagick
|
||||||
|
L1475 function convertWithFFmpeg
|
||||||
|
L1483 function convertWithPandoc
|
||||||
|
L1490 function performExportWithOptions
|
||||||
|
L1741 function tryPdfFallback
|
||||||
|
L1818 function showExportSuccess
|
||||||
|
L1828 function exportWithPandoc
|
||||||
|
L1907 function exportToHTML
|
||||||
|
L2026 function exportToPDFElectron
|
||||||
|
L2174 function exportSpreadsheet
|
||||||
|
L2184 function importDocument
|
||||||
|
L2280 function setTheme
|
||||||
|
L2488 function extractTablesFromMarkdown
|
||||||
|
L2530 function performBatchConversion
|
||||||
|
L2552 function findMarkdownFiles (performBatchConversion)
|
||||||
|
L2579 function processNextFile (performBatchConversion)
|
||||||
|
L2855 function handleCLIConversion
|
||||||
|
L2883 function showConversionDialog
|
||||||
|
L2932 function performCLIConversion
|
||||||
|
L2974 function buildPandocCommand
|
||||||
|
L3152 method transform (anonymousObject0b93a19c6805)
|
||||||
|
L3273 function openFileFromPath
|
||||||
|
L3468 function loadSnippets
|
||||||
|
L3479 function saveSnippetsFile
|
||||||
|
|
||||||
|
src/main/ipc/crash-handlers.js:
|
||||||
|
L3 function register
|
||||||
|
|
||||||
|
src/main/ipc/updater-handlers.js:
|
||||||
|
L4 function register
|
||||||
|
|
||||||
|
src/main/menu/index.js:
|
||||||
|
L16 function buildMenu
|
||||||
|
L30 function register
|
||||||
|
|
||||||
|
src/main/menu/items.js:
|
||||||
|
L9 function buildRecentFilesMenu
|
||||||
|
L18 method click (buildRecentFilesMenu.anonymousObject59dd54ea0305)
|
||||||
|
L27 method click (anonymousObject59dd54ea0505)
|
||||||
|
L40 function fileItems
|
||||||
|
L143 method click (fileItems.anonymousObject59dd54ea1005)
|
||||||
|
L150 method click (fileItems.anonymousObject59dd54ea1105)
|
||||||
|
L157 method click (fileItems.anonymousObject59dd54ea1205)
|
||||||
|
L165 method click (fileItems.anonymousObject59dd54ea1305)
|
||||||
|
L172 method click (fileItems.anonymousObject59dd54ea1405)
|
||||||
|
L180 method click (fileItems.anonymousObject59dd54ea1505)
|
||||||
|
L187 method click (fileItems.anonymousObject59dd54ea1605)
|
||||||
|
L194 method click (fileItems.anonymousObject59dd54ea1705)
|
||||||
|
L201 method click (fileItems.anonymousObject59dd54ea1805)
|
||||||
|
L209 method click (fileItems.anonymousObject59dd54ea1a05)
|
||||||
|
L216 method click (fileItems.anonymousObject59dd54ea1b05)
|
||||||
|
L224 method click (fileItems.anonymousObject59dd54ea1d05)
|
||||||
|
L232 method click (fileItems.anonymousObject59dd54ea1f05)
|
||||||
|
L239 method click (fileItems.anonymousObject59dd54ea2005)
|
||||||
|
L246 method click (fileItems.anonymousObject59dd54ea2105)
|
||||||
|
L254 method click (fileItems.anonymousObject59dd54ea2305)
|
||||||
|
L261 method click (fileItems.anonymousObject59dd54ea2405)
|
||||||
|
L300 function editItems
|
||||||
|
L326 function viewItems
|
||||||
|
L372 method click (viewItems.anonymousObject59dd54ea2a05)
|
||||||
|
L379 method click (viewItems.anonymousObject59dd54ea2b05)
|
||||||
|
L386 method click (viewItems.anonymousObject59dd54ea2c05)
|
||||||
|
L393 method click (viewItems.anonymousObject59dd54ea2d05)
|
||||||
|
L400 method click (viewItems.anonymousObject59dd54ea2e05)
|
||||||
|
L407 method click (viewItems.anonymousObject59dd54ea2f05)
|
||||||
|
L414 method click (viewItems.anonymousObject59dd54ea3005)
|
||||||
|
L421 method click (viewItems.anonymousObject59dd54ea3105)
|
||||||
|
L428 method click (viewItems.anonymousObject59dd54ea3205)
|
||||||
|
L435 method click (viewItems.anonymousObject59dd54ea3305)
|
||||||
|
L443 method click (viewItems.anonymousObject59dd54ea3505)
|
||||||
|
L450 method click (viewItems.anonymousObject59dd54ea3605)
|
||||||
|
L457 method click (viewItems.anonymousObject59dd54ea3705)
|
||||||
|
L464 method click (viewItems.anonymousObject59dd54ea3805)
|
||||||
|
L471 method click (viewItems.anonymousObject59dd54ea3905)
|
||||||
|
L478 method click (viewItems.anonymousObject59dd54ea3a05)
|
||||||
|
L485 method click (viewItems.anonymousObject59dd54ea3b05)
|
||||||
|
L492 method click (viewItems.anonymousObject59dd54ea3c05)
|
||||||
|
L499 method click (viewItems.anonymousObject59dd54ea3d05)
|
||||||
|
L506 method click (viewItems.anonymousObject59dd54ea3e05)
|
||||||
|
L513 method click (viewItems.anonymousObject59dd54ea3f05)
|
||||||
|
L520 method click (viewItems.anonymousObject59dd54ea4005)
|
||||||
|
L527 method click (viewItems.anonymousObject59dd54ea4105)
|
||||||
|
L534 method click (viewItems.anonymousObject59dd54ea4205)
|
||||||
|
L541 method click (viewItems.anonymousObject59dd54ea4305)
|
||||||
|
L602 function batchItems
|
||||||
|
L631 function convertItems
|
||||||
|
L644 function pdfEditorItems
|
||||||
|
L712 method click (pdfEditorItems.anonymousObject59dd54ea4905)
|
||||||
|
L719 method click (pdfEditorItems.anonymousObject59dd54ea4a05)
|
||||||
|
L726 method click (pdfEditorItems.anonymousObject59dd54ea4b05)
|
||||||
|
L744 function toolsItems
|
||||||
|
L757 function helpItems
|
||||||
|
|
||||||
|
src/main/store.js:
|
||||||
|
L11 method get (store)
|
||||||
|
L20 method set (store)
|
||||||
|
|
||||||
|
src/main/updater/crash-writer.js:
|
||||||
|
L5 class CrashWriter
|
||||||
|
L6 method constructor (CrashWriter)
|
||||||
|
L12 method handleUncaught (CrashWriter)
|
||||||
|
L28 method _prune (CrashWriter)
|
||||||
|
L40 method list (CrashWriter)
|
||||||
|
L54 method delete (CrashWriter)
|
||||||
|
L59 method path (CrashWriter)
|
||||||
|
|
||||||
|
src/main/updater/feed-config.js:
|
||||||
|
L1 function feedConfigFor
|
||||||
|
|
||||||
|
src/main/updater/migration-runner.js:
|
||||||
|
L4 class MigrationRunner
|
||||||
|
L5 method constructor (MigrationRunner)
|
||||||
|
L12 method run (MigrationRunner)
|
||||||
|
L36 method _writeDefaults (MigrationRunner)
|
||||||
|
|
||||||
|
src/main/updater/migration-transform.js:
|
||||||
|
L49 function isAlreadyV5
|
||||||
|
L56 function normalizeAlreadyV5
|
||||||
|
L95 function migrateV4ToV5
|
||||||
|
|
||||||
|
src/main/updater/updater-service.js:
|
||||||
|
L4 class UpdaterService
|
||||||
|
L5 method constructor (UpdaterService)
|
||||||
|
L13 method _wire (UpdaterService)
|
||||||
|
L27 method _emit (UpdaterService)
|
||||||
|
L32 method check (UpdaterService)
|
||||||
|
L38 method install (UpdaterService)
|
||||||
|
|
||||||
|
src/main/utils/paths.js:
|
||||||
|
L7 function getAllowedDirectories
|
||||||
|
L23 function validatePath
|
||||||
|
L58 function resolveWritablePath
|
||||||
|
L88 function isPathAccessible
|
||||||
|
|
||||||
|
src/main/window/index.js:
|
||||||
|
L10 function createMainWindow
|
||||||
|
|
||||||
|
src/main/window/state.js:
|
||||||
|
L10 function load
|
||||||
|
L18 function save
|
||||||
|
|
||||||
|
src/main/word-template/index.js:
|
||||||
|
L11 class WordTemplateExporter
|
||||||
|
L12 method constructor (WordTemplateExporter)
|
||||||
|
L21 method convert (WordTemplateExporter)
|
||||||
|
L58 method setPageSize (WordTemplateExporter)
|
||||||
|
L111 method insertContentAfterPage (WordTemplateExporter)
|
||||||
|
L140 method markdownToWordXml (WordTemplateExporter)
|
||||||
|
L251 method createHeadingXml (WordTemplateExporter)
|
||||||
|
L266 method createParagraphXml (WordTemplateExporter)
|
||||||
|
L280 method createQuoteXml (WordTemplateExporter)
|
||||||
|
L294 method createListItemXml (WordTemplateExporter)
|
||||||
|
L315 method createCodeBlockXml (WordTemplateExporter)
|
||||||
|
L352 method createHorizontalRuleXml (WordTemplateExporter)
|
||||||
|
L366 method createTableXml (WordTemplateExporter)
|
||||||
|
L502 method isAsciiArt (WordTemplateExporter)
|
||||||
|
L606 method createAsciiArtXml (WordTemplateExporter)
|
||||||
|
L715 method parseInlineFormatting (WordTemplateExporter)
|
||||||
|
L776 method createRunXml (WordTemplateExporter)
|
||||||
|
L797 method escapeXml (WordTemplateExporter)
|
||||||
|
|
||||||
|
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 (anonymousObjectd036aefd0105)
|
||||||
|
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:
|
||||||
|
L275 method send (anonymousObject04f5e4370105)
|
||||||
|
L289 method invoke (anonymousObject04f5e4370105)
|
||||||
|
L308 method on (anonymousObject04f5e4370105)
|
||||||
|
L310 function subscription (anonymousObject04f5e4370105.on)
|
||||||
|
L328 method once (anonymousObject04f5e4370105)
|
||||||
|
L340 method removeAllListeners (anonymousObject04f5e4370105)
|
||||||
|
L488 function subscription
|
||||||
|
|
||||||
|
src/renderer/hooks/use-export-source.ts:
|
||||||
|
L4 interface ExportSource
|
||||||
|
L14 function useExportSource
|
||||||
|
|
||||||
|
src/renderer/hooks/use-file-shortcuts.ts:
|
||||||
|
L15 function useFileShortcuts
|
||||||
|
|
||||||
|
src/renderer/hooks/use-menu-action.ts:
|
||||||
|
L6 alias Transform
|
||||||
|
L17 function useMenuAction
|
||||||
|
|
||||||
|
src/renderer/hooks/use-restore-last-folder.ts:
|
||||||
|
L9 function useRestoreLastFolder
|
||||||
|
|
||||||
|
src/renderer/hooks/use-scroll-sync.ts:
|
||||||
|
L3 interface Options
|
||||||
|
L8 function useScrollSync
|
||||||
|
|
||||||
|
src/renderer/hooks/use-shortcut.ts:
|
||||||
|
L20 function useShortcut
|
||||||
|
L44 interface ComboSpec
|
||||||
|
L53 function parseCombo
|
||||||
|
L71 function matchCombo
|
||||||
|
|
||||||
|
src/renderer/hooks/use-welcome-trigger.ts:
|
||||||
|
L9 function useWelcomeTrigger
|
||||||
|
|
||||||
|
src/renderer/hooks/use-zen-mode.ts:
|
||||||
|
L8 function useZenMode
|
||||||
|
|
||||||
|
src/renderer/hooks/useAutoUpdateCheck.ts:
|
||||||
|
L5 function useAutoUpdateCheck
|
||||||
|
|
||||||
|
src/renderer/lib/ascii-table.ts:
|
||||||
|
L5 function toAsciiTable
|
||||||
|
L36 function applyAsciiTransform
|
||||||
|
|
||||||
|
src/renderer/lib/commands/register-menu-commands.ts:
|
||||||
|
L24 alias HeadingItem
|
||||||
|
L26 alias OpenModal
|
||||||
|
L28 function confirmCloseFlow
|
||||||
|
L45 function registerMenuCommands
|
||||||
|
L411 function useRegisterMenuCommands
|
||||||
|
L421 function useBridgeNativeMenu
|
||||||
|
|
||||||
|
src/renderer/lib/docx-export.ts:
|
||||||
|
L4 interface DocxOptions
|
||||||
|
L10 function generateDocx
|
||||||
|
|
||||||
|
src/renderer/lib/editor-commands.ts:
|
||||||
|
L18 function setActiveView
|
||||||
|
L22 function getActiveView
|
||||||
|
L27 function wrap
|
||||||
|
L57 function setLineHeading
|
||||||
|
L76 function toggleLinePrefix
|
||||||
|
L103 function toggleBold
|
||||||
|
L107 function toggleItalic
|
||||||
|
L111 function toggleCode
|
||||||
|
L115 function toggleCodeBlock
|
||||||
|
L143 function toggleUnorderedList
|
||||||
|
L147 function toggleOrderedList
|
||||||
|
L151 function insertLink
|
||||||
|
L167 function setHeadingLevel
|
||||||
|
L171 function scrollToLine
|
||||||
|
L185 function undo
|
||||||
|
L192 function redo
|
||||||
|
L199 function selectCurrentLine
|
||||||
|
L210 function insertSnippet
|
||||||
|
|
||||||
|
src/renderer/lib/figlet.ts:
|
||||||
|
L13 alias FigletFont
|
||||||
|
L15 function figletText
|
||||||
|
|
||||||
|
src/renderer/lib/headings.ts:
|
||||||
|
L1 interface HeadingItem
|
||||||
|
L13 function extractHeadings
|
||||||
|
|
||||||
|
src/renderer/lib/html-export.ts:
|
||||||
|
L11 interface HtmlExportOptions
|
||||||
|
L101 function generateHtml
|
||||||
|
L125 function escapeHtml
|
||||||
|
|
||||||
|
src/renderer/lib/ipc.ts:
|
||||||
|
L14 alias ChannelMissing
|
||||||
|
L16 function wrap
|
||||||
|
|
||||||
|
src/renderer/lib/markdown.ts:
|
||||||
|
L11 function renderMarkdown
|
||||||
|
|
||||||
|
src/renderer/lib/migrations/v4-to-v5.ts:
|
||||||
|
L16 function isAlreadyV5
|
||||||
|
L22 function normalizeAlreadyV5
|
||||||
|
L37 function migrateV4ToV5
|
||||||
|
|
||||||
|
src/renderer/lib/pdf-export.ts:
|
||||||
|
L13 interface PdfExportOptions
|
||||||
|
L28 function generatePdf
|
||||||
|
|
||||||
|
src/renderer/lib/updater-store.ts:
|
||||||
|
L4 alias State
|
||||||
|
L6 interface UpdaterState
|
||||||
|
|
||||||
|
src/renderer/lib/utils.ts:
|
||||||
|
L1 alias ClassValue
|
||||||
|
L4 function cn
|
||||||
|
|
||||||
|
src/renderer/lib/validators.ts:
|
||||||
|
L30 alias Settings
|
||||||
|
L38 alias ExportPdfOptions
|
||||||
|
L44 alias ExportDocxOptions
|
||||||
|
L51 alias ExportHtmlOptions
|
||||||
|
L58 alias ExportBatchOptions
|
||||||
|
|
||||||
|
src/renderer/lib/writing-analytics.ts:
|
||||||
|
L115 function countSyllables
|
||||||
|
L122 function extractWords
|
||||||
|
L126 function getReadabilityLabel
|
||||||
|
L134 interface WritingMetrics
|
||||||
|
L151 function analyzeText
|
||||||
|
|
||||||
|
src/renderer/stores/app-store.ts:
|
||||||
|
L4 interface PaneSizes
|
||||||
|
L10 interface ConfirmProps
|
||||||
|
L20 alias ModalState
|
||||||
|
L42 alias ModalKind
|
||||||
|
L44 interface AppState
|
||||||
|
L57 method openModal (AppState)
|
||||||
|
|
||||||
|
src/renderer/stores/command-store.ts:
|
||||||
|
L4 alias CommandId
|
||||||
|
L6 alias CommandHandler
|
||||||
|
L13 alias UserBindings
|
||||||
|
L15 interface CommandState
|
||||||
|
|
||||||
|
src/renderer/stores/editor-store.ts:
|
||||||
|
L7 interface Buffer
|
||||||
|
L15 interface EditorState
|
||||||
|
|
||||||
|
src/renderer/stores/file-store.ts:
|
||||||
|
L12 interface FileNode
|
||||||
|
L21 interface OpenTab
|
||||||
|
L28 interface FileState
|
||||||
|
L50 function entryToNode
|
||||||
|
L60 function updateNode
|
||||||
|
|
||||||
|
src/renderer/stores/preview-store.ts:
|
||||||
|
L3 interface PreviewState
|
||||||
|
|
||||||
|
src/renderer/stores/settings-store.ts:
|
||||||
|
L3 alias Settings
|
||||||
|
L5 alias Omit
|
||||||
|
L5 alias SettingsLeaf
|
||||||
|
L7 interface SettingsState
|
||||||
|
L8 method setSetting (SettingsState)
|
||||||
|
|
||||||
|
src/renderer/test/setup.ts:
|
||||||
|
L7 interface Window
|
||||||
|
L119 class ResizeObserver
|
||||||
|
L120 method observe (ResizeObserver)
|
||||||
|
L121 method unobserve (ResizeObserver)
|
||||||
|
L122 method disconnect (ResizeObserver)
|
||||||
|
L141 class DOMMatrix
|
||||||
|
|
||||||
|
src/renderer/types/electron.d.ts:
|
||||||
|
L1 interface ElectronAPI
|
||||||
|
L134 interface Window
|
||||||
|
|
||||||
|
src/renderer/types/ipc.ts:
|
||||||
|
L1 alias IpcResult
|
||||||
|
L5 interface FileEntry
|
||||||
|
L13 interface FileResult
|
||||||
|
L18 interface PdfOptions
|
||||||
|
L27 interface DocxOptions
|
||||||
|
L34 interface HtmlOptions
|
||||||
|
L41 interface ExportResult
|
||||||
|
L47 interface BatchItem
|
||||||
|
L52 interface BatchOptions
|
||||||
|
L57 interface BatchResult
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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 (anonymousObject7c2818c30105)
|
||||||
|
L52 method render (anonymousObject7c2818c30205)
|
||||||
|
L62 method render (anonymousObject7c2818c30305)
|
||||||
|
L68 method render (anonymousObject7c2818c30405)
|
||||||
|
L80 method render (anonymousObject7c2818c30505)
|
||||||
|
L88 method render (anonymousObject7c2818c30605)
|
||||||
|
L96 method render (anonymousObject7c2818c30705)
|
||||||
|
L120 method render (anonymousObject7c2818c30905)
|
||||||
|
L130 method render (anonymousObject7c2818c30a05)
|
||||||
|
|
||||||
|
tests/unit/hooks/use-menu-action.test.ts:
|
||||||
|
L6 alias Cleanup
|
||||||
|
L27 function fireMenu
|
||||||
|
|
||||||
|
tests/unit/main/updater/crash-writer.test.js:
|
||||||
|
L6 function tmpDir
|
||||||
|
|
||||||
|
tests/unit/main/updater/migration-runner.test.js:
|
||||||
|
L6 function tmpDir
|
||||||
|
L47 method transform (anonymousObject196c14410c05)
|
||||||
|
L63 method transform (anonymousObject196c14410d05)
|
||||||
|
|
||||||
|
tests/unit/stores/file-store.test.ts:
|
||||||
|
L26 function fakeFileEntry
|
||||||
|
|
||||||
|
tests/utils.test.js:
|
||||||
|
L9 function parseCommand
|
||||||
|
L78 function hexToRgb
|
||||||
|
L121 function getExtension
|
||||||
|
L133 function replaceExtension
|
||||||
|
```
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* Build assets/icon.icns from the PNGs in assets/icons/.
|
||||||
|
*
|
||||||
|
* ICNS file format (Apple Icon Image):
|
||||||
|
* Header: 'icns' (4 bytes) + total file length (uint32 BE, includes header)
|
||||||
|
* For each size:
|
||||||
|
* Type tag (4 bytes) + length (uint32 BE, includes the 8-byte entry header) + PNG data
|
||||||
|
*
|
||||||
|
* Standard PNG type tags we'll include:
|
||||||
|
* icp4 = 16x16, icp5 = 32x32, icp6 = 64x64
|
||||||
|
* ic07 = 128x128, ic08 = 256x256, ic09 = 512x512, ic10 = 1024x1024
|
||||||
|
* icsb = 48x48 (small)
|
||||||
|
* ic11 = 16x16@2x (32x32 retina), ic12 = 32x32@2x (64x64 retina)
|
||||||
|
* ic13 = 128x128@2x (256x256 retina), ic14 = 256x256@2x (512x512 retina)
|
||||||
|
*/
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const iconsDir = path.join(__dirname, '..', 'assets', 'icons');
|
||||||
|
const outFile = path.join(__dirname, '..', 'assets', 'icon.icns');
|
||||||
|
|
||||||
|
// (size-in-pixels, icns type tag) — we skip sizes we don't have on disk
|
||||||
|
const sizes = [
|
||||||
|
{ size: 16, type: 'icp4' },
|
||||||
|
{ size: 32, type: 'icp5' },
|
||||||
|
{ size: 64, type: 'icp6' },
|
||||||
|
{ size: 128, type: 'ic07' },
|
||||||
|
{ size: 256, type: 'ic08' },
|
||||||
|
{ size: 512, type: 'ic09' },
|
||||||
|
{ size: 1024, type: 'ic10' },
|
||||||
|
{ size: 48, type: 'icsb' },
|
||||||
|
{ size: 32, type: 'ic11' }, // 16@2x
|
||||||
|
{ size: 64, type: 'ic12' }, // 32@2x
|
||||||
|
{ size: 256, type: 'ic13' }, // 128@2x
|
||||||
|
{ size: 512, type: 'ic14' }, // 256@2x
|
||||||
|
];
|
||||||
|
|
||||||
|
const entries = [];
|
||||||
|
for (const { size, type } of sizes) {
|
||||||
|
const pngPath = path.join(iconsDir, `${size}x${size}.png`);
|
||||||
|
if (!fs.existsSync(pngPath)) continue;
|
||||||
|
const png = fs.readFileSync(pngPath);
|
||||||
|
// ICNS requires 8-byte alignment per entry. paddedLen is the TOTAL entry size
|
||||||
|
// (8-byte type+length header + PNG + padding), rounded up to a multiple of 8.
|
||||||
|
const paddedLen = 8 + Math.ceil(png.length / 8) * 8;
|
||||||
|
entries.push({ type, png, paddedLen });
|
||||||
|
console.log(` ${type} (${size}x${size}) — ${png.length} bytes`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries.length === 0) {
|
||||||
|
console.error('No source PNGs found in', iconsDir);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalLen = 8 + entries.reduce((s, e) => s + e.paddedLen, 0);
|
||||||
|
const buf = Buffer.alloc(totalLen);
|
||||||
|
let off = 0;
|
||||||
|
|
||||||
|
// Header
|
||||||
|
buf.write('icns', off, 4, 'ascii'); off += 4;
|
||||||
|
buf.writeUInt32BE(totalLen, off); off += 4;
|
||||||
|
|
||||||
|
// Entries
|
||||||
|
for (const { type, png, paddedLen } of entries) {
|
||||||
|
buf.write(type, off, 4, 'ascii'); off += 4;
|
||||||
|
buf.writeUInt32BE(paddedLen, off); off += 4;
|
||||||
|
png.copy(buf, off);
|
||||||
|
off += png.length;
|
||||||
|
// Pad to 8-byte boundary within the entry. paddedLen already includes the 8-byte header.
|
||||||
|
const pad = paddedLen - 8 - png.length;
|
||||||
|
if (pad > 0) off += pad;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(outFile, buf);
|
||||||
|
console.log(`\nWrote ${outFile} (${buf.length} bytes, ${entries.length} sizes)`);
|
||||||
@@ -14,6 +14,30 @@ const { execSync } = require('child_process');
|
|||||||
|
|
||||||
const PANDOC_VERSION = '3.9.0.2';
|
const PANDOC_VERSION = '3.9.0.2';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pandoc's archive inner layout has shifted across releases and platforms:
|
||||||
|
* linux tarball: pandoc-3.9.0.2/bin/pandoc
|
||||||
|
* win32 zip: pandoc-3.9.0.2/pandoc.exe
|
||||||
|
* darwin zip: pandoc-3.9.0.2-x86_64/bin/pandoc (arch-suffixed inner dir)
|
||||||
|
* pandoc-3.9.0.2-arm64/bin/pandoc (on Apple Silicon builds)
|
||||||
|
* Rather than hard-coding the intermediate path — which has already broken
|
||||||
|
* once when pandoc 3.9 added the arch suffix to the macOS archive — we walk
|
||||||
|
* the extracted tree and find the binary by name. This is robust to future
|
||||||
|
* layout shifts (e.g., universal binaries renaming the inner dir).
|
||||||
|
*/
|
||||||
|
function findFile(rootDir, targetName) {
|
||||||
|
const entries = fs.readdirSync(rootDir, { withFileTypes: true });
|
||||||
|
for (const entry of entries) {
|
||||||
|
const full = path.join(rootDir, entry.name);
|
||||||
|
if (entry.isFile() && entry.name === targetName) return full;
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
const found = findFile(full, targetName);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const PANDOC_CONFIG = {
|
const PANDOC_CONFIG = {
|
||||||
linux: {
|
linux: {
|
||||||
url: `https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz`,
|
url: `https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz`,
|
||||||
@@ -22,8 +46,9 @@ const PANDOC_CONFIG = {
|
|||||||
extract(archivePath, destDir) {
|
extract(archivePath, destDir) {
|
||||||
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
|
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
|
||||||
fs.mkdirSync(tmpDir, { recursive: true });
|
fs.mkdirSync(tmpDir, { recursive: true });
|
||||||
execSync(`tar -xzf "${archivePath}" -C "${tmpDir}" pandoc-${PANDOC_VERSION}/bin/pandoc`);
|
execSync(`tar -xzf "${archivePath}" -C "${tmpDir}"`);
|
||||||
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'bin', 'pandoc');
|
const src = findFile(tmpDir, 'pandoc');
|
||||||
|
if (!src) throw new Error(`pandoc binary not found under ${tmpDir}`);
|
||||||
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
|
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
|
||||||
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
|
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
|
||||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
@@ -39,7 +64,8 @@ const PANDOC_CONFIG = {
|
|||||||
execSync(
|
execSync(
|
||||||
`powershell -Command "Expand-Archive -Force '${archivePath}' '${tmpDir}'"`,
|
`powershell -Command "Expand-Archive -Force '${archivePath}' '${tmpDir}'"`,
|
||||||
);
|
);
|
||||||
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'pandoc.exe');
|
const src = findFile(tmpDir, 'pandoc.exe');
|
||||||
|
if (!src) throw new Error(`pandoc.exe not found under ${tmpDir}`);
|
||||||
fs.copyFileSync(src, path.join(destDir, 'pandoc.exe'));
|
fs.copyFileSync(src, path.join(destDir, 'pandoc.exe'));
|
||||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
},
|
},
|
||||||
@@ -52,7 +78,8 @@ const PANDOC_CONFIG = {
|
|||||||
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
|
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
|
||||||
fs.mkdirSync(tmpDir, { recursive: true });
|
fs.mkdirSync(tmpDir, { recursive: true });
|
||||||
execSync(`unzip -o "${archivePath}" -d "${tmpDir}"`);
|
execSync(`unzip -o "${archivePath}" -d "${tmpDir}"`);
|
||||||
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'bin', 'pandoc');
|
const src = findFile(tmpDir, 'pandoc');
|
||||||
|
if (!src) throw new Error(`pandoc binary not found under ${tmpDir}`);
|
||||||
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
|
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
|
||||||
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
|
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
|
||||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
@@ -142,7 +169,47 @@ async function downloadPandoc() {
|
|||||||
console.log(`[download-tools] pandoc ready: ${destFile}`);
|
console.log(`[download-tools] pandoc ready: ${destFile}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
downloadPandoc().catch((err) => {
|
async function downloadFiraCode() {
|
||||||
|
const targetDir = path.resolve(__dirname, '..', 'assets', 'fonts');
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
// Pinned to an immutable release tag with explicit SHA-256 digests so the
|
||||||
|
// build fails loudly on any upstream tampering or accidental change.
|
||||||
|
// Update the version + digests together when bumping Fira Code.
|
||||||
|
const FIRA_CODE_VERSION = '6.2';
|
||||||
|
const baseUrl = `https://github.com/tonsky/FiraCode/releases/download/${FIRA_CODE_VERSION}`;
|
||||||
|
const files = [
|
||||||
|
{ url: `${baseUrl}/FiraCode-Regular.ttf`, out: 'FiraCode-Regular.ttf', sha256: '3c79d234a9161c790410ebb2a80de7efb7c15f581062c130e0fa78503ccdd0da' },
|
||||||
|
{ url: `${baseUrl}/FiraCode-Bold.ttf`, out: 'FiraCode-Bold.ttf', sha256: '975f26779fac1029c2cbdac1e9fac7e9ddeec05e064675e4aac63bffa121742f' },
|
||||||
|
{ url: `${baseUrl}/FiraCode-LICENSE.txt`, out: 'FiraCode-LICENSE.txt', sha256: null },
|
||||||
|
];
|
||||||
|
for (const f of files) {
|
||||||
|
const dest = path.join(targetDir, f.out);
|
||||||
|
if (fs.existsSync(dest)) {
|
||||||
|
console.log(`[download-tools] Fira Code asset already present at ${dest} — skipping.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!f.sha256 || !/^[a-f0-9]{64}$/i.test(f.sha256)) {
|
||||||
|
throw new Error(
|
||||||
|
`[download-tools] Refusing to download ${f.url}: SHA-256 digest not pinned. ` +
|
||||||
|
'Update scripts/download-tools.js with the digest from the official Fira Code release before building.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const tmp = `${dest}.tmp`;
|
||||||
|
console.log(`[download-tools] Downloading ${f.url}...`);
|
||||||
|
await download(f.url, tmp);
|
||||||
|
const actual = require('crypto').createHash('sha256').update(fs.readFileSync(tmp)).digest('hex');
|
||||||
|
if (actual !== f.sha256) {
|
||||||
|
fs.unlinkSync(tmp);
|
||||||
|
throw new Error(
|
||||||
|
`[download-tools] SHA-256 mismatch for ${f.url}: expected ${f.sha256}, got ${actual}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fs.renameSync(tmp, dest);
|
||||||
|
}
|
||||||
|
console.log('[download-tools] Fira Code ready');
|
||||||
|
}
|
||||||
|
|
||||||
|
Promise.all([downloadPandoc(), downloadFiraCode()]).catch((err) => {
|
||||||
console.error('[download-tools] FAILED:', err.message);
|
console.error('[download-tools] FAILED:', err.message);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const version = process.argv[2] || require('../package.json').version;
|
||||||
|
const hook = process.env.CONCRETEINFO_DEPLOY_HOOK;
|
||||||
|
if (!hook) {
|
||||||
|
console.error('CONCRETEINFO_DEPLOY_HOOK not set');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates = [
|
||||||
|
'latest-mac.yml',
|
||||||
|
'latest-linux.yml',
|
||||||
|
'latest-windows.yml',
|
||||||
|
`MarkdownConverter-${version}.dmg`,
|
||||||
|
`markdown-converter_${version}_amd64.deb`,
|
||||||
|
`MarkdownConverter-Setup-${version}.exe`,
|
||||||
|
];
|
||||||
|
|
||||||
|
const dist = path.resolve(__dirname, '..', 'dist');
|
||||||
|
for (const f of candidates) {
|
||||||
|
if (!fs.existsSync(path.join(dist, f))) {
|
||||||
|
console.error(`missing ${f} — run electron-builder first`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('version', version);
|
||||||
|
for (const f of candidates) {
|
||||||
|
if (fs.existsSync(path.join(dist, f))) {
|
||||||
|
form.append('artifacts', fs.createReadStream(path.join(dist, f)), f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch('https://updates.concreteinfo.co.in/api/v1/ingest', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${hook}` },
|
||||||
|
body: form,
|
||||||
|
})
|
||||||
|
.then((r) => {
|
||||||
|
console.log('ingest status', r.status);
|
||||||
|
process.exit(r.ok ? 0 : 1);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('ingest failed:', e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { _electron as electron } from 'playwright-core';
|
||||||
|
import * as fs from 'node:fs';
|
||||||
|
import * as path from 'node:path';
|
||||||
|
|
||||||
|
const APP_DIR = '/home/amith/apps/markdown-converter';
|
||||||
|
const electronBin = path.join(APP_DIR, 'node_modules/electron/dist/electron');
|
||||||
|
|
||||||
|
const testMd = '/tmp/verify-test.md';
|
||||||
|
const outputDocx = '/tmp/verify-output.docx';
|
||||||
|
const outputHtml = '/tmp/verify-output.html';
|
||||||
|
|
||||||
|
// Cleanup previous outputs
|
||||||
|
if (fs.existsSync(testMd)) fs.unlinkSync(testMd);
|
||||||
|
if (fs.existsSync(outputDocx)) fs.unlinkSync(outputDocx);
|
||||||
|
if (fs.existsSync(outputHtml)) fs.unlinkSync(outputHtml);
|
||||||
|
|
||||||
|
// Write test Markdown file
|
||||||
|
fs.writeFileSync(
|
||||||
|
testMd,
|
||||||
|
'# Test Document\n\nThis is a verification test for opening and exporting.\n\n- Point A\n- Point B\n'
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('Launching Electron...');
|
||||||
|
const app = await electron.launch({
|
||||||
|
executablePath: electronBin,
|
||||||
|
args: [
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-gpu',
|
||||||
|
'--disable-software-rasterizer',
|
||||||
|
'--disable-dev-shm-usage',
|
||||||
|
'.',
|
||||||
|
],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
DISPLAY: ':0',
|
||||||
|
ELECTRON_DISABLE_SANDBOX: '1',
|
||||||
|
VITE_DEV_SERVER_URL: 'http://localhost:5173',
|
||||||
|
},
|
||||||
|
cwd: APP_DIR,
|
||||||
|
});
|
||||||
|
|
||||||
|
app.process().stdout.on('data', (data) => console.log('[MAIN-OUT]', data.toString().trim()));
|
||||||
|
app.process().stderr.on('data', (data) => console.log('[MAIN-ERR]', data.toString().trim()));
|
||||||
|
|
||||||
|
const win = await app.firstWindow();
|
||||||
|
await win.waitForLoadState('domcontentloaded');
|
||||||
|
await win.waitForSelector('.cm-editor, [role="toolbar"]', { timeout: 10000 });
|
||||||
|
console.log('App loaded.');
|
||||||
|
|
||||||
|
// Dismiss welcome wizard if present
|
||||||
|
const wizardCount = await win.locator('[data-testid="first-run-wizard"]').count();
|
||||||
|
if (wizardCount > 0) {
|
||||||
|
console.log('Dismissing first run wizard...');
|
||||||
|
await win.click('[data-testid="first-run-wizard"] >> text=Skip');
|
||||||
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stub dialog.showSaveDialogSync in main process to automatically return output paths
|
||||||
|
await app.evaluate(({ dialog }, { outputDocx, outputHtml }) => {
|
||||||
|
dialog.showSaveDialogSync = (window, options) => {
|
||||||
|
const filters = options?.filters || [];
|
||||||
|
if (filters.some(f => f.extensions.includes('docx'))) {
|
||||||
|
return outputDocx;
|
||||||
|
}
|
||||||
|
return outputHtml;
|
||||||
|
};
|
||||||
|
}, { outputDocx, outputHtml });
|
||||||
|
|
||||||
|
// Simulate opening the test Md file by sending IPC from main
|
||||||
|
console.log('Opening test markdown file...');
|
||||||
|
const fileContent = fs.readFileSync(testMd, 'utf-8');
|
||||||
|
await app.evaluate(({ BrowserWindow }, { filePath, content }) => {
|
||||||
|
const wins = BrowserWindow.getAllWindows();
|
||||||
|
const main = wins.find((w) => !w.isDestroyed());
|
||||||
|
if (!main) throw new Error('No main window');
|
||||||
|
main.webContents.send('file-opened', { path: filePath, content });
|
||||||
|
}, { filePath: testMd, content: fileContent });
|
||||||
|
|
||||||
|
// Wait for editor to display the content
|
||||||
|
await win.waitForFunction(
|
||||||
|
(content) => {
|
||||||
|
const editor = document.querySelector('.cm-content');
|
||||||
|
return editor && editor.textContent.includes('Test Document');
|
||||||
|
},
|
||||||
|
fileContent,
|
||||||
|
{ timeout: 5000 }
|
||||||
|
);
|
||||||
|
console.log('File successfully opened in editor.');
|
||||||
|
|
||||||
|
// Let's wait a moment for currentFile synchronization to trigger in the main process
|
||||||
|
await new Promise((r) => setTimeout(r, 500));
|
||||||
|
|
||||||
|
|
||||||
|
// Trigger DOCX Export (calls performExportWithOptions under the hood)
|
||||||
|
console.log('Exporting to DOCX...');
|
||||||
|
await win.evaluate(() => {
|
||||||
|
window.electronAPI.export.withOptions('docx', {});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for file to be written to disk
|
||||||
|
let docxExported = false;
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
if (fs.existsSync(outputDocx) && fs.statSync(outputDocx).size > 0) {
|
||||||
|
docxExported = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 250));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (docxExported) {
|
||||||
|
console.log('✅ DOCX exported successfully.');
|
||||||
|
} else {
|
||||||
|
console.error('❌ DOCX export failed (file not created or empty).');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait 2.5 seconds to bypass the conversion rate limiter (2000ms debounce)
|
||||||
|
console.log('Waiting for rate limiter...');
|
||||||
|
await new Promise((r) => setTimeout(r, 2500));
|
||||||
|
|
||||||
|
// Trigger HTML Export
|
||||||
|
console.log('Exporting to HTML...');
|
||||||
|
await win.evaluate(() => {
|
||||||
|
window.electronAPI.export.withOptions('html', {});
|
||||||
|
});
|
||||||
|
|
||||||
|
let htmlExported = false;
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
if (fs.existsSync(outputHtml) && fs.statSync(outputHtml).size > 0) {
|
||||||
|
htmlExported = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 250));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (htmlExported) {
|
||||||
|
console.log('✅ HTML exported successfully.');
|
||||||
|
} else {
|
||||||
|
console.error('❌ HTML export failed (file not created or empty).');
|
||||||
|
}
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
console.log('Verification completed.');
|
||||||
|
|
||||||
|
if (docxExported && htmlExported) {
|
||||||
|
process.exit(0);
|
||||||
|
} else {
|
||||||
|
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,11 +61,15 @@ 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">
|
||||||
@@ -74,39 +78,45 @@ 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.map(w => {
|
${metrics.topWords
|
||||||
|
.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('')}
|
})
|
||||||
</div>` : ''}
|
.join('')}
|
||||||
|
</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 };
|
||||||
|
|||||||
+177
-104
@@ -4,124 +4,197 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const STOP_WORDS = new Set([
|
const STOP_WORDS = new Set([
|
||||||
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been',
|
'the',
|
||||||
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
|
'a',
|
||||||
'could', 'should', 'to', 'of', 'in', 'for', 'on', 'with',
|
'an',
|
||||||
'at', 'by', 'from', 'as', 'and', 'or', 'but', 'if', 'it',
|
'is',
|
||||||
'its', 'this', 'that', 'these', 'those', 'i', 'me', 'my',
|
'are',
|
||||||
'we', 'our', 'you', 'your', 'he', 'him', 'his', 'she', 'her',
|
'was',
|
||||||
'they', 'them', 'their', 'not', 'no', 'so', 'than', 'too',
|
'were',
|
||||||
'very', 'also', 'just', 'about', 'up', 'out', 'what', 'which', 'who'
|
'be',
|
||||||
|
'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,
|
wordCount: 0,
|
||||||
sentenceCount,
|
sentenceCount: 0,
|
||||||
paragraphCount,
|
paragraphCount: 0,
|
||||||
fleschEase,
|
fleschEase: 0,
|
||||||
fleschGrade,
|
fleschGrade: 0,
|
||||||
readabilityLabel,
|
readabilityLabel: 'N/A',
|
||||||
readingTime,
|
readingTime: 0,
|
||||||
speakingTime,
|
speakingTime: 0,
|
||||||
uniqueWordCount,
|
uniqueWordCount: 0,
|
||||||
lexicalDiversity,
|
lexicalDiversity: 0,
|
||||||
avgSentenceLength,
|
avgSentenceLength: 0,
|
||||||
longestSentence,
|
longestSentence: '',
|
||||||
longestSentenceLength,
|
longestSentenceLength: 0,
|
||||||
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 };
|
||||||
|
|||||||
@@ -1,601 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>ASCII Art Generator - MarkdownConverter</title>
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
|
||||||
<style>
|
|
||||||
:root {
|
|
||||||
--ci-dark-gray: #464646;
|
|
||||||
--ci-medium-gray: #9a9696;
|
|
||||||
--ci-accent: #e5461f;
|
|
||||||
--ci-light-gray: #e3e3e3;
|
|
||||||
--ci-black: #0d0b09;
|
|
||||||
--ci-white: #ffffff;
|
|
||||||
--ci-bg: #f5f5f5;
|
|
||||||
}
|
|
||||||
|
|
||||||
* {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
font-family: 'Inter', system-ui, sans-serif;
|
|
||||||
background: var(--ci-bg);
|
|
||||||
color: var(--ci-dark-gray);
|
|
||||||
min-height: 100vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header {
|
|
||||||
background: linear-gradient(135deg, var(--ci-dark-gray) 0%, var(--ci-black) 100%);
|
|
||||||
padding: 16px 24px;
|
|
||||||
border-bottom: 3px solid var(--ci-accent);
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header h1 {
|
|
||||||
color: var(--ci-white);
|
|
||||||
font-size: 1.25rem;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.container {
|
|
||||||
padding: 24px;
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.section {
|
|
||||||
background: var(--ci-white);
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 20px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
|
|
||||||
}
|
|
||||||
|
|
||||||
.section-title {
|
|
||||||
font-weight: 600;
|
|
||||||
margin-bottom: 16px;
|
|
||||||
color: var(--ci-dark-gray);
|
|
||||||
font-size: 0.95rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-tabs {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-tab {
|
|
||||||
padding: 10px 20px;
|
|
||||||
border: 2px solid var(--ci-light-gray);
|
|
||||||
background: var(--ci-white);
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
font-weight: 500;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-tab:hover {
|
|
||||||
border-color: var(--ci-accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-tab.active {
|
|
||||||
background: var(--ci-accent);
|
|
||||||
border-color: var(--ci-accent);
|
|
||||||
color: var(--ci-white);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-group {
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-label {
|
|
||||||
display: block;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
font-weight: 500;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
color: var(--ci-dark-gray);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-input, .form-select, .form-textarea {
|
|
||||||
width: 100%;
|
|
||||||
padding: 10px 14px;
|
|
||||||
border: 2px solid var(--ci-light-gray);
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
font-family: inherit;
|
|
||||||
transition: border-color 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-input:focus, .form-select:focus, .form-textarea:focus {
|
|
||||||
outline: none;
|
|
||||||
border-color: var(--ci-accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-textarea {
|
|
||||||
min-height: 80px;
|
|
||||||
resize: vertical;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-container {
|
|
||||||
background: var(--ci-black);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 16px;
|
|
||||||
min-height: 200px;
|
|
||||||
max-height: 350px;
|
|
||||||
overflow: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-content {
|
|
||||||
font-family: 'JetBrains Mono', monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.3;
|
|
||||||
color: #00ff00;
|
|
||||||
white-space: pre;
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(4, 1fr);
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-btn {
|
|
||||||
padding: 8px 12px;
|
|
||||||
border: 2px solid var(--ci-light-gray);
|
|
||||||
background: var(--ci-white);
|
|
||||||
border-radius: 6px;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-btn:hover {
|
|
||||||
border-color: var(--ci-accent);
|
|
||||||
background: rgba(229, 70, 31, 0.05);
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-btn.active {
|
|
||||||
border-color: var(--ci-accent);
|
|
||||||
background: rgba(229, 70, 31, 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.footer {
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 12px;
|
|
||||||
padding: 16px 24px;
|
|
||||||
background: var(--ci-white);
|
|
||||||
border-top: 1px solid var(--ci-light-gray);
|
|
||||||
position: sticky;
|
|
||||||
bottom: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn {
|
|
||||||
padding: 10px 24px;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
font-weight: 500;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s;
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary {
|
|
||||||
background: var(--ci-accent);
|
|
||||||
color: var(--ci-white);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary:hover {
|
|
||||||
background: #c93a18;
|
|
||||||
transform: translateY(-1px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-secondary {
|
|
||||||
background: var(--ci-light-gray);
|
|
||||||
color: var(--ci-dark-gray);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-secondary:hover {
|
|
||||||
background: #d0d0d0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-section {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-section.active {
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-category {
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.template-category-title {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
color: var(--ci-medium-gray);
|
|
||||||
margin-bottom: 8px;
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.05em;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="header">
|
|
||||||
<h1>ASCII Art Generator</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="container">
|
|
||||||
<div class="section">
|
|
||||||
<div class="mode-tabs">
|
|
||||||
<button class="mode-tab active" data-mode="text">Text Banner</button>
|
|
||||||
<button class="mode-tab" data-mode="box">Box/Frame</button>
|
|
||||||
<button class="mode-tab" data-mode="templates">Templates</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Text Banner Mode -->
|
|
||||||
<div id="text-mode" class="mode-section active">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Text to Convert</label>
|
|
||||||
<input type="text" id="text-input" class="form-input" placeholder="Enter your text..." maxlength="30">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Style</label>
|
|
||||||
<select id="font-style" class="form-select">
|
|
||||||
<option value="standard">Standard</option>
|
|
||||||
<option value="banner">Banner</option>
|
|
||||||
<option value="block">Block</option>
|
|
||||||
<option value="bubble">Bubble</option>
|
|
||||||
<option value="digital">Digital</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Box/Frame Mode -->
|
|
||||||
<div id="box-mode" class="mode-section">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Text Content</label>
|
|
||||||
<textarea id="box-text" class="form-textarea" placeholder="Enter text for the box..."></textarea>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Box Style</label>
|
|
||||||
<select id="box-style" class="form-select">
|
|
||||||
<option value="single">Single Line</option>
|
|
||||||
<option value="double">Double Line</option>
|
|
||||||
<option value="rounded">Rounded</option>
|
|
||||||
<option value="bold">Bold</option>
|
|
||||||
<option value="ascii">ASCII (+|-)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Padding</label>
|
|
||||||
<input type="number" id="box-padding" class="form-input" min="0" max="10" value="2" style="width: 100px;">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Templates Mode -->
|
|
||||||
<div id="templates-mode" class="mode-section">
|
|
||||||
<div class="template-category">
|
|
||||||
<div class="template-category-title">Arrows & Flow</div>
|
|
||||||
<div class="template-grid">
|
|
||||||
<button class="template-btn" data-template="arrow-right">Arrow Right</button>
|
|
||||||
<button class="template-btn" data-template="arrow-down">Arrow Down</button>
|
|
||||||
<button class="template-btn" data-template="decision">Decision</button>
|
|
||||||
<button class="template-btn" data-template="process">Process Flow</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="template-category">
|
|
||||||
<div class="template-category-title">Diagrams</div>
|
|
||||||
<div class="template-grid">
|
|
||||||
<button class="template-btn" data-template="flowchart">Flowchart</button>
|
|
||||||
<button class="template-btn" data-template="sequence">Sequence</button>
|
|
||||||
<button class="template-btn" data-template="network">Network</button>
|
|
||||||
<button class="template-btn" data-template="hierarchy">Hierarchy</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="template-category">
|
|
||||||
<div class="template-category-title">Boxes & Containers</div>
|
|
||||||
<div class="template-grid">
|
|
||||||
<button class="template-btn" data-template="header">Header</button>
|
|
||||||
<button class="template-btn" data-template="note">Note Box</button>
|
|
||||||
<button class="template-btn" data-template="warning">Warning</button>
|
|
||||||
<button class="template-btn" data-template="info">Info Box</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="template-category">
|
|
||||||
<div class="template-category-title">Decorative</div>
|
|
||||||
<div class="template-grid">
|
|
||||||
<button class="template-btn" data-template="divider">Divider</button>
|
|
||||||
<button class="template-btn" data-template="separator">Separator</button>
|
|
||||||
<button class="template-btn" data-template="banner">Banner</button>
|
|
||||||
<button class="template-btn" data-template="checklist">Checklist</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">Preview</div>
|
|
||||||
<div class="preview-container">
|
|
||||||
<div id="preview" class="preview-content"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="footer">
|
|
||||||
<button class="btn btn-secondary" id="btn-generate">Generate Preview</button>
|
|
||||||
<button class="btn btn-primary" id="btn-insert">Insert to Editor</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
// ASCII Art Generator Logic
|
|
||||||
const FONTS = {
|
|
||||||
standard: {
|
|
||||||
height: 5,
|
|
||||||
chars: {
|
|
||||||
'A': [' /\\ ', ' / \\ ', '/----\\', '| |', '| |'],
|
|
||||||
'B': ['|----\\', '| |', '|----/', '| \\', '|----/'],
|
|
||||||
'C': ['/----\\', '| ', '| ', '| ', '\\----/'],
|
|
||||||
'D': ['|----\\', '| |', '| |', '| |', '|----/'],
|
|
||||||
'E': ['|----', '| ', '|--- ', '| ', '|----'],
|
|
||||||
'F': ['|----', '| ', '|--- ', '| ', '| '],
|
|
||||||
'G': ['/----\\', '| ', '| |--\\', '| |', '\\----/'],
|
|
||||||
'H': ['| |', '| |', '|----/', '| |', '| |'],
|
|
||||||
'I': ['|---|', ' | ', ' | ', ' | ', '|---|'],
|
|
||||||
'J': [' |', ' |', ' |', '| |', '\\---/'],
|
|
||||||
'K': ['| /', '| / ', '|-- ', '| \\ ', '| \\'],
|
|
||||||
'L': ['| ', '| ', '| ', '| ', '|----'],
|
|
||||||
'M': ['|\\ /|', '| \\/ |', '| |', '| |', '| |'],
|
|
||||||
'N': ['|\\ |', '| \\ |', '| \\ |', '| \\|', '| |'],
|
|
||||||
'O': ['/----\\', '| |', '| |', '| |', '\\----/'],
|
|
||||||
'P': ['|----\\', '| |', '|----/', '| ', '| '],
|
|
||||||
'Q': ['/----\\', '| |', '| \\ |', '| \\|', '\\----\\'],
|
|
||||||
'R': ['|----\\', '| |', '|----/', '| \\ ', '| \\ '],
|
|
||||||
'S': ['/----\\', '| ', '\\----\\', ' |', '\\----/'],
|
|
||||||
'T': ['-----', ' | ', ' | ', ' | ', ' | '],
|
|
||||||
'U': ['| |', '| |', '| |', '| |', '\\----/'],
|
|
||||||
'V': ['| |', '| |', ' \\ / ', ' \\/ ', ' '],
|
|
||||||
'W': ['| |', '| |', '| |', '| /\\ |', '|/ \\|'],
|
|
||||||
'X': ['\\ /', ' \\ / ', ' \\/ ', ' /\\ ', ' / \\ '],
|
|
||||||
'Y': ['\\ /', ' \\ / ', ' | ', ' | ', ' | '],
|
|
||||||
'Z': ['-----', ' / ', ' / ', ' / ', '-----'],
|
|
||||||
' ': [' ', ' ', ' ', ' ', ' '],
|
|
||||||
'0': ['/---\\', '| |', '| / |', '|/ |', '\\---/'],
|
|
||||||
'1': [' /| ', ' / | ', ' | ', ' | ', ' ----'],
|
|
||||||
'2': ['/---\\', ' |', ' ---/', '/ ', '-----'],
|
|
||||||
'3': ['----\\', ' |', ' ---/', ' |', '----/'],
|
|
||||||
'4': ['| |', '| |', '-----', ' |', ' |'],
|
|
||||||
'5': ['-----', '| ', '----\\', ' |', '----/'],
|
|
||||||
'6': ['/----', '| ', '|---\\', '| |', '\\---/'],
|
|
||||||
'7': ['-----', ' / ', ' / ', ' / ', '/ '],
|
|
||||||
'8': ['/---\\', '| |', ' --- ', '| |', '\\---/'],
|
|
||||||
'9': ['/---\\', '| |', '\\----', ' |', '----/']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
banner: {
|
|
||||||
height: 7,
|
|
||||||
chars: {
|
|
||||||
'A': [' ##### ', ' ## ##', '## ##', '#########', '## ##', '## ##', '## ##'],
|
|
||||||
'B': ['######## ', '## ##', '## ##', '######## ', '## ##', '## ##', '######## '],
|
|
||||||
'C': [' ###### ', '## ##', '## ', '## ', '## ', '## ##', ' ###### '],
|
|
||||||
'D': ['######## ', '## ##', '## ##', '## ##', '## ##', '## ##', '######## '],
|
|
||||||
'E': ['########', '## ', '## ', '###### ', '## ', '## ', '########'],
|
|
||||||
'F': ['########', '## ', '## ', '###### ', '## ', '## ', '## '],
|
|
||||||
'G': [' ###### ', '## ##', '## ', '## ####', '## ##', '## ##', ' ###### '],
|
|
||||||
'H': ['## ##', '## ##', '## ##', '#########', '## ##', '## ##', '## ##'],
|
|
||||||
'I': ['####', ' ## ', ' ## ', ' ## ', ' ## ', ' ## ', '####'],
|
|
||||||
'J': [' ##', ' ##', ' ##', ' ##', '## ##', '## ##', ' ###### '],
|
|
||||||
'K': ['## ##', '## ## ', '## ## ', '##### ', '## ## ', '## ## ', '## ##'],
|
|
||||||
'L': ['## ', '## ', '## ', '## ', '## ', '## ', '########'],
|
|
||||||
'M': ['## ##', '### ###', '#### ####', '## ### ##', '## ##', '## ##', '## ##'],
|
|
||||||
'N': ['## ##', '### ##', '#### ##', '## ## ##', '## ####', '## ###', '## ##'],
|
|
||||||
'O': [' ####### ', '## ##', '## ##', '## ##', '## ##', '## ##', ' ####### '],
|
|
||||||
'P': ['######## ', '## ##', '## ##', '######## ', '## ', '## ', '## '],
|
|
||||||
'Q': [' ####### ', '## ##', '## ##', '## ##', '## ## ##', '## ## ', ' ##### ##'],
|
|
||||||
'R': ['######## ', '## ##', '## ##', '######## ', '## ## ', '## ## ', '## ##'],
|
|
||||||
'S': [' ###### ', '## ##', '## ', ' ###### ', ' ##', '## ##', ' ###### '],
|
|
||||||
'T': ['########', ' ## ', ' ## ', ' ## ', ' ## ', ' ## ', ' ## '],
|
|
||||||
'U': ['## ##', '## ##', '## ##', '## ##', '## ##', '## ##', ' ####### '],
|
|
||||||
'V': ['## ##', '## ##', '## ##', '## ##', ' ## ## ', ' ## ## ', ' ### '],
|
|
||||||
'W': ['## ##', '## ## ##', '## ## ##', '## ## ##', '## ## ##', '## ## ##', ' ### ### '],
|
|
||||||
'X': ['## ##', ' ## ## ', ' ## ## ', ' ### ', ' ## ## ', ' ## ## ', '## ##'],
|
|
||||||
'Y': ['## ##', ' ## ## ', ' #### ', ' ## ', ' ## ', ' ## ', ' ## '],
|
|
||||||
'Z': ['########', ' ## ', ' ## ', ' ## ', ' ## ', ' ## ', '########'],
|
|
||||||
' ': [' ', ' ', ' ', ' ', ' ', ' ', ' '],
|
|
||||||
'0': [' ###### ', '## ##', '## ##', '## ##', '## ##', '## ##', ' ###### '],
|
|
||||||
'1': [' ## ', ' #### ', ' ## ', ' ## ', ' ## ', ' ## ', ' ###### '],
|
|
||||||
'2': [' ###### ', '## ##', ' ## ', ' ## ', ' ## ', ' ## ', '########'],
|
|
||||||
'3': [' ###### ', '## ##', ' ## ', ' #### ', ' ## ', '## ##', ' ###### '],
|
|
||||||
'4': [' ## ', ' ### ', ' # ## ', ' # ## ', '########', ' ## ', ' ## '],
|
|
||||||
'5': ['########', '## ', '####### ', ' ##', ' ##', '## ##', ' ###### '],
|
|
||||||
'6': [' ###### ', '## ', '####### ', '## ##', '## ##', '## ##', ' ###### '],
|
|
||||||
'7': ['########', '## ## ', ' ## ', ' ## ', ' ## ', ' ## ', ' ## '],
|
|
||||||
'8': [' ###### ', '## ##', '## ##', ' ###### ', '## ##', '## ##', ' ###### '],
|
|
||||||
'9': [' ###### ', '## ##', '## ##', ' #######', ' ##', '## ##', ' ###### ']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
block: {
|
|
||||||
height: 6,
|
|
||||||
chars: {
|
|
||||||
'A': ['█████╗ ', '██╔══██╗', '███████║', '██╔══██║', '██║ ██║', '╚═╝ ╚═╝'],
|
|
||||||
'B': ['██████╗ ', '██╔══██╗', '██████╔╝', '██╔══██╗', '██████╔╝', '╚═════╝ '],
|
|
||||||
'C': ['█████╗ ', '██╔══██╗', '██║ ', '██║ ', '╚█████╔╝', ' ╚════╝ '],
|
|
||||||
'D': ['██████╗ ', '██╔══██╗', '██║ ██║', '██║ ██║', '██████╔╝', '╚═════╝ '],
|
|
||||||
'E': ['███████╗', '██╔════╝', '█████╗ ', '██╔══╝ ', '███████╗', '╚══════╝'],
|
|
||||||
'F': ['███████╗', '██╔════╝', '█████╗ ', '██╔══╝ ', '██║ ', '╚═╝ '],
|
|
||||||
'G': ['█████╗ ', '██╔══██╗', '██║ ███', '██║ ██', '╚█████╔╝', ' ╚════╝ '],
|
|
||||||
'H': ['██╗ ██╗', '██║ ██║', '███████║', '██╔══██║', '██║ ██║', '╚═╝ ╚═╝'],
|
|
||||||
'I': ['██╗', '██║', '██║', '██║', '██║', '╚═╝'],
|
|
||||||
'J': [' ██╗', ' ██║', ' ██║', '██ ██║', '╚████╔╝', ' ╚═══╝ '],
|
|
||||||
'K': ['██╗ ██╗', '██║ ██╔╝', '█████╔╝ ', '██╔═██╗ ', '██║ ██╗', '╚═╝ ╚═╝'],
|
|
||||||
'L': ['██╗ ', '██║ ', '██║ ', '██║ ', '███████╗', '╚══════╝'],
|
|
||||||
'M': ['███╗ ███╗', '████╗ ████║', '██╔████╔██║', '██║╚██╔╝██║', '██║ ╚═╝ ██║', '╚═╝ ╚═╝'],
|
|
||||||
'N': ['███╗ ██╗', '████╗ ██║', '██╔██╗ ██║', '██║╚██╗██║', '██║ ╚████║', '╚═╝ ╚═══╝'],
|
|
||||||
'O': ['█████╗ ', '██╔══██╗', '██║ ██║', '██║ ██║', '╚█████╔╝', ' ╚════╝ '],
|
|
||||||
'P': ['██████╗ ', '██╔══██╗', '██████╔╝', '██╔═══╝ ', '██║ ', '╚═╝ '],
|
|
||||||
'Q': ['█████╗ ', '██╔══██╗', '██║ ██║', '██║ ██║', '╚██████╗', ' ╚═══██╝'],
|
|
||||||
'R': ['██████╗ ', '██╔══██╗', '██████╔╝', '██╔══██╗', '██║ ██║', '╚═╝ ╚═╝'],
|
|
||||||
'S': ['█████╗ ', '██╔══╝ ', '█████╗ ', '╚══██║ ', '█████║ ', '╚════╝ '],
|
|
||||||
'T': ['████████╗', '╚══██╔══╝', ' ██║ ', ' ██║ ', ' ██║ ', ' ╚═╝ '],
|
|
||||||
'U': ['██╗ ██╗', '██║ ██║', '██║ ██║', '██║ ██║', '╚█████╔╝', ' ╚════╝ '],
|
|
||||||
'V': ['██╗ ██╗', '██║ ██║', '██║ ██║', '╚██╗ ██╔╝', ' ╚████╔╝ ', ' ╚═══╝ '],
|
|
||||||
'W': ['██╗ ██╗', '██║ ██║', '██║ █╗ ██║', '██║███╗██║', '╚███╔███╔╝', ' ╚══╝╚══╝ '],
|
|
||||||
'X': ['██╗ ██╗', '╚██╗██╔╝', ' ╚███╔╝ ', ' ██╔██╗ ', '██╔╝ ██╗', '╚═╝ ╚═╝'],
|
|
||||||
'Y': ['██╗ ██╗', '╚██╗ ██╔╝', ' ╚████╔╝ ', ' ╚██╔╝ ', ' ██║ ', ' ╚═╝ '],
|
|
||||||
'Z': ['███████╗', '╚════██║', ' ███╔═╝', ' ██╔══╝ ', '███████╗', '╚══════╝'],
|
|
||||||
' ': [' ', ' ', ' ', ' ', ' ', ' ']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const TEMPLATES = {
|
|
||||||
'arrow-right': ' ┌─────────────────────┐\n──▶│ Process or Action │──▶\n └─────────────────────┘',
|
|
||||||
'arrow-down': ' │\n ▼\n┌───────────────┐\n│ Process │\n└───────────────┘\n │\n ▼',
|
|
||||||
'decision': ' ╱╲\n ╱ ╲\n ╱ ? ╲\n ╱ ╲\n ╱────────╲\n ╱ ╲\n YES NO\n │ │\n ▼ ▼',
|
|
||||||
'process': '┌─────┐ ┌─────┐ ┌─────┐\n│ 1 │──▶│ 2 │──▶│ 3 │\n└─────┘ └─────┘ └─────┘',
|
|
||||||
'flowchart': '┌─────────────┐\n│ START │\n└──────┬──────┘\n │\n ▼\n┌─────────────┐\n│ Process A │\n└──────┬──────┘\n │\n ▼\n ╱────────╲\n ╱ Decision ╲\n ╲ ? ╱\n ╲────────╱\n │ │\n YES NO\n │ │\n ▼ ▼\n┌──────┐ ┌──────┐\n│ B │ │ C │\n└──────┘ └──────┘',
|
|
||||||
'sequence': ' User System Database\n │ │ │\n │ Request │ │\n ├──────────►│ │\n │ │ Query │\n │ ├──────────►│\n │ │ │\n │ │ Result │\n │ │◄──────────┤\n │ Response │ │\n │◄──────────┤ │\n │ │ │',
|
|
||||||
'network': ' ┌─────────┐\n │ Server │\n └────┬────┘\n │\n ┌─────────┼─────────┐\n │ │ │\n┌────┴────┐ ┌──┴──┐ ┌────┴────┐\n│ Client1 │ │ DB │ │ Client2 │\n└─────────┘ └─────┘ └─────────┘',
|
|
||||||
'hierarchy': ' ┌─────────┐\n │ CEO │\n └────┬────┘\n ┌─────────┼─────────┐\n │ │ │\n ┌───┴───┐ ┌───┴───┐ ┌───┴───┐\n │ VP1 │ │ VP2 │ │ VP3 │\n └───┬───┘ └───┬───┘ └───┬───┘\n │ │ │\n ┌───┴───┐ ┌───┴───┐ ┌───┴───┐\n │ Team1 │ │ Team2 │ │ Team3 │\n └───────┘ └───────┘ └───────┘',
|
|
||||||
'header': '╔════════════════════════════════════╗\n║ SECTION TITLE ║\n╚════════════════════════════════════╝',
|
|
||||||
'note': '┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ NOTE: ┃\n┃ This is an important note ┃\n┃ that requires attention! ┃\n┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛',
|
|
||||||
'warning': '╔════════════════════════════════════╗\n║ ⚠️ WARNING ║\n║ ║\n║ Critical information here! ║\n╚════════════════════════════════════╝',
|
|
||||||
'info': '╭────────────────────────────────────╮\n│ ℹ️ INFO │\n│ │\n│ Helpful information here. │\n╰────────────────────────────────────╯',
|
|
||||||
'divider': '════════════════════════════════════════',
|
|
||||||
'separator': '╭──────────────────────────────────────╮\n│ │\n╰──────────────────────────────────────╯',
|
|
||||||
'banner': '★══════════════════════════════════════★\n║ YOUR TITLE HERE ║\n★══════════════════════════════════════★',
|
|
||||||
'checklist': '☐ Task 1 - Not completed\n☑ Task 2 - Completed \n☐ Task 3 - Not completed\n☐ Task 4 - Not completed'
|
|
||||||
};
|
|
||||||
|
|
||||||
const BOX_STYLES = {
|
|
||||||
single: { tl: '┌', tr: '┐', bl: '└', br: '┘', h: '─', v: '│' },
|
|
||||||
double: { tl: '╔', tr: '╗', bl: '╚', br: '╝', h: '═', v: '║' },
|
|
||||||
rounded: { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' },
|
|
||||||
bold: { tl: '┏', tr: '┓', bl: '┗', br: '┛', h: '━', v: '┃' },
|
|
||||||
ascii: { tl: '+', tr: '+', bl: '+', br: '+', h: '-', v: '|' }
|
|
||||||
};
|
|
||||||
|
|
||||||
let currentMode = 'text';
|
|
||||||
let currentTemplate = null;
|
|
||||||
|
|
||||||
// Mode switching
|
|
||||||
document.querySelectorAll('.mode-tab').forEach(tab => {
|
|
||||||
tab.addEventListener('click', () => {
|
|
||||||
document.querySelectorAll('.mode-tab').forEach(t => t.classList.remove('active'));
|
|
||||||
tab.classList.add('active');
|
|
||||||
currentMode = tab.dataset.mode;
|
|
||||||
|
|
||||||
document.querySelectorAll('.mode-section').forEach(s => s.classList.remove('active'));
|
|
||||||
document.getElementById(currentMode + '-mode').classList.add('active');
|
|
||||||
|
|
||||||
generatePreview();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Template selection
|
|
||||||
document.querySelectorAll('.template-btn').forEach(btn => {
|
|
||||||
btn.addEventListener('click', () => {
|
|
||||||
document.querySelectorAll('.template-btn').forEach(b => b.classList.remove('active'));
|
|
||||||
btn.classList.add('active');
|
|
||||||
currentTemplate = btn.dataset.template;
|
|
||||||
generatePreview();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Generate text banner
|
|
||||||
function generateTextBanner(text, style) {
|
|
||||||
const font = FONTS[style] || FONTS.standard;
|
|
||||||
const lines = Array(font.height).fill('');
|
|
||||||
|
|
||||||
for (const char of text.toUpperCase()) {
|
|
||||||
const charArt = font.chars[char] || font.chars[' '];
|
|
||||||
if (charArt) {
|
|
||||||
for (let i = 0; i < font.height; i++) {
|
|
||||||
lines[i] += charArt[i] + ' ';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate box
|
|
||||||
function generateBox(text, style, padding) {
|
|
||||||
const box = BOX_STYLES[style] || BOX_STYLES.single;
|
|
||||||
const lines = text.split('\n');
|
|
||||||
const maxLen = Math.max(...lines.map(l => l.length)) + padding * 2;
|
|
||||||
|
|
||||||
let result = box.tl + box.h.repeat(maxLen + 2) + box.tr + '\n';
|
|
||||||
|
|
||||||
// Add padding lines at top
|
|
||||||
for (let i = 0; i < Math.floor(padding / 2); i++) {
|
|
||||||
result += box.v + ' '.repeat(maxLen + 2) + box.v + '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add text lines
|
|
||||||
for (const line of lines) {
|
|
||||||
const paddedLine = ' '.repeat(padding) + line.padEnd(maxLen - padding) + ' ';
|
|
||||||
result += box.v + ' ' + paddedLine + box.v + '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add padding lines at bottom
|
|
||||||
for (let i = 0; i < Math.floor(padding / 2); i++) {
|
|
||||||
result += box.v + ' '.repeat(maxLen + 2) + box.v + '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
result += box.bl + box.h.repeat(maxLen + 2) + box.br;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate preview
|
|
||||||
function generatePreview() {
|
|
||||||
let result = '';
|
|
||||||
|
|
||||||
if (currentMode === 'text') {
|
|
||||||
const text = document.getElementById('text-input').value || 'HELLO';
|
|
||||||
const style = document.getElementById('font-style').value;
|
|
||||||
result = generateTextBanner(text, style);
|
|
||||||
} else if (currentMode === 'box') {
|
|
||||||
const text = document.getElementById('box-text').value || 'Your text here';
|
|
||||||
const style = document.getElementById('box-style').value;
|
|
||||||
const padding = parseInt(document.getElementById('box-padding').value) || 2;
|
|
||||||
result = generateBox(text, style, padding);
|
|
||||||
} else if (currentMode === 'templates') {
|
|
||||||
result = currentTemplate ? TEMPLATES[currentTemplate] : 'Select a template...';
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById('preview').textContent = result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Event listeners for live preview
|
|
||||||
document.getElementById('text-input').addEventListener('input', generatePreview);
|
|
||||||
document.getElementById('font-style').addEventListener('change', generatePreview);
|
|
||||||
document.getElementById('box-text').addEventListener('input', generatePreview);
|
|
||||||
document.getElementById('box-style').addEventListener('change', generatePreview);
|
|
||||||
document.getElementById('box-padding').addEventListener('input', generatePreview);
|
|
||||||
|
|
||||||
document.getElementById('btn-generate').addEventListener('click', generatePreview);
|
|
||||||
|
|
||||||
document.getElementById('btn-insert').addEventListener('click', () => {
|
|
||||||
const content = document.getElementById('preview').textContent;
|
|
||||||
if (content && window.electronAPI) {
|
|
||||||
// Wrap in code block for markdown
|
|
||||||
const wrapped = '```\n' + content + '\n```';
|
|
||||||
window.electronAPI.send('insert-generated-content', wrapped);
|
|
||||||
window.close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Initial preview
|
|
||||||
generatePreview();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
class CommandPalette {
|
|
||||||
constructor() {
|
|
||||||
this.overlay = document.getElementById('command-palette-overlay');
|
|
||||||
this.input = document.getElementById('command-palette-input');
|
|
||||||
this.results = document.getElementById('command-palette-results');
|
|
||||||
this.commands = [];
|
|
||||||
this.selectedIndex = 0;
|
|
||||||
this.filteredCommands = [];
|
|
||||||
this.setupEventListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
register(label, shortcut, action) {
|
|
||||||
this.commands.push({ label, shortcut, action });
|
|
||||||
}
|
|
||||||
|
|
||||||
open() {
|
|
||||||
this.overlay.classList.remove('hidden');
|
|
||||||
this.input.value = '';
|
|
||||||
this.input.focus();
|
|
||||||
this.selectedIndex = 0;
|
|
||||||
this.renderResults('');
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
this.overlay.classList.add('hidden');
|
|
||||||
}
|
|
||||||
|
|
||||||
isOpen() {
|
|
||||||
return !this.overlay.classList.contains('hidden');
|
|
||||||
}
|
|
||||||
|
|
||||||
setupEventListeners() {
|
|
||||||
this.input.addEventListener('input', () => {
|
|
||||||
this.selectedIndex = 0;
|
|
||||||
this.renderResults(this.input.value);
|
|
||||||
});
|
|
||||||
|
|
||||||
this.overlay.addEventListener('click', (e) => {
|
|
||||||
if (e.target === this.overlay) this.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
this.input.addEventListener('keydown', (e) => {
|
|
||||||
if (e.key === 'Escape') {
|
|
||||||
e.preventDefault();
|
|
||||||
this.close();
|
|
||||||
} else if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
this.executeSelected();
|
|
||||||
} else if (e.key === 'ArrowDown') {
|
|
||||||
e.preventDefault();
|
|
||||||
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCommands.length - 1);
|
|
||||||
this.updateSelection();
|
|
||||||
} else if (e.key === 'ArrowUp') {
|
|
||||||
e.preventDefault();
|
|
||||||
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
|
|
||||||
this.updateSelection();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
renderResults(query) {
|
|
||||||
this.filteredCommands = query
|
|
||||||
? this.commands.filter(cmd => cmd.label.toLowerCase().includes(query.toLowerCase()))
|
|
||||||
: [...this.commands];
|
|
||||||
|
|
||||||
this.results.innerHTML = this.filteredCommands.map((cmd, i) => `
|
|
||||||
<div class="command-item ${i === this.selectedIndex ? 'selected' : ''}" data-index="${i}">
|
|
||||||
<span class="command-label">${this.highlightMatch(cmd.label, query)}</span>
|
|
||||||
${cmd.shortcut ? `<span class="command-shortcut">${cmd.shortcut}</span>` : ''}
|
|
||||||
</div>
|
|
||||||
`).join('');
|
|
||||||
|
|
||||||
this.results.querySelectorAll('.command-item').forEach((el) => {
|
|
||||||
el.addEventListener('click', () => {
|
|
||||||
const idx = parseInt(el.dataset.index);
|
|
||||||
this.filteredCommands[idx].action();
|
|
||||||
this.close();
|
|
||||||
});
|
|
||||||
el.addEventListener('mouseenter', () => {
|
|
||||||
this.selectedIndex = parseInt(el.dataset.index);
|
|
||||||
this.updateSelection();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
highlightMatch(text, query) {
|
|
||||||
if (!query) return text;
|
|
||||||
const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
|
|
||||||
return text.replace(regex, '<strong>$1</strong>');
|
|
||||||
}
|
|
||||||
|
|
||||||
updateSelection() {
|
|
||||||
this.results.querySelectorAll('.command-item').forEach((el, i) => {
|
|
||||||
el.classList.toggle('selected', i === this.selectedIndex);
|
|
||||||
});
|
|
||||||
// Scroll selected into view
|
|
||||||
const selected = this.results.querySelector('.command-item.selected');
|
|
||||||
if (selected) selected.scrollIntoView({ block: 'nearest' });
|
|
||||||
}
|
|
||||||
|
|
||||||
executeSelected() {
|
|
||||||
if (this.filteredCommands[this.selectedIndex]) {
|
|
||||||
this.filteredCommands[this.selectedIndex].action();
|
|
||||||
this.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { CommandPalette };
|
|
||||||
@@ -12,38 +12,23 @@ 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 {
|
const { defaultKeymap, history, historyKeymap, indentWithTab } = require('@codemirror/commands');
|
||||||
defaultKeymap,
|
const { searchKeymap, highlightSelectionMatches } = require('@codemirror/search');
|
||||||
history,
|
const { autocompletion, completionKeymap } = require('@codemirror/autocomplete');
|
||||||
historyKeymap,
|
const { bracketMatching, foldGutter, indentOnInput } = require('@codemirror/language');
|
||||||
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',
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,7 +44,14 @@ 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('[createEditor] Called with parentElement:', parentElement?.id, 'dimensions:', parentElement?.clientWidth, 'x', parentElement?.clientHeight);
|
console.log(
|
||||||
|
'[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;
|
||||||
@@ -125,11 +117,26 @@ function createEditor(parentElement, options = {}) {
|
|||||||
*/
|
*/
|
||||||
function getLanguageExtension(lang) {
|
function getLanguageExtension(lang) {
|
||||||
const loaders = {
|
const loaders = {
|
||||||
javascript: () => { if (!_javascript) _javascript = require('@codemirror/lang-javascript').javascript; return _javascript(); },
|
javascript: () => {
|
||||||
html: () => { if (!_html) _html = require('@codemirror/lang-html').html; return _html(); },
|
if (!_javascript) _javascript = require('@codemirror/lang-javascript').javascript;
|
||||||
css: () => { if (!_css) _css = require('@codemirror/lang-css').css; return _css(); },
|
return _javascript();
|
||||||
json: () => { if (!_json) _json = require('@codemirror/lang-json').json; return _json(); },
|
},
|
||||||
python: () => { if (!_python) _python = require('@codemirror/lang-python').python; return _python(); },
|
html: () => {
|
||||||
|
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;
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
/* Local Font Definitions for MarkdownConverter */
|
|
||||||
|
|
||||||
/* Inter Font Family */
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Inter';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 300;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/Inter-Light.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Inter';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 400;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/Inter-Regular.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Inter';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 500;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/Inter-Medium.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Inter';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 600;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/Inter-SemiBold.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'Inter';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 700;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/Inter-Bold.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
/* JetBrains Mono Font Family - For code, markdown editor, and ASCII art */
|
|
||||||
@font-face {
|
|
||||||
font-family: 'JetBrains Mono';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 400;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/JetBrainsMono-Regular.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'JetBrains Mono';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 500;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/JetBrainsMono-Medium.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'JetBrains Mono';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 600;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/JetBrainsMono-SemiBold.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
|
|
||||||
@font-face {
|
|
||||||
font-family: 'JetBrains Mono';
|
|
||||||
font-style: normal;
|
|
||||||
font-weight: 700;
|
|
||||||
font-display: swap;
|
|
||||||
src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2');
|
|
||||||
}
|
|
||||||
-1610
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const JSZip = require('jszip');
|
||||||
|
|
||||||
|
const FONT_TABLE_PATH = 'word/fontTable.xml';
|
||||||
|
const FONT_TABLE_RELS_PATH = 'word/_rels/fontTable.xml.rels';
|
||||||
|
|
||||||
|
function fontTableXml(family) {
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
|
<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
|
||||||
|
<w:font w:name="${family}">
|
||||||
|
<w:panose1 w:val="020F0502020204030204"/>
|
||||||
|
<w:charset w:val="00"/>
|
||||||
|
<w:family w:val="modern"/>
|
||||||
|
<w:pitch w:val="fixed"/>
|
||||||
|
<w:embedRegular r:id="rId1"/>
|
||||||
|
</w:font>
|
||||||
|
</w:fonts>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fontTableRels(fontFilename) {
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
|
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||||
|
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" Target="${fontFilename}"/>
|
||||||
|
</Relationships>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function embedDocxFont(inputDocxPath, outputDocxPath, ttfPath, fontFamily) {
|
||||||
|
if (!ttfPath || !fs.existsSync(ttfPath)) {
|
||||||
|
throw new Error(`DocxFontEmbedder: TTF not found at ${ttfPath}`);
|
||||||
|
}
|
||||||
|
const inputBytes = fs.readFileSync(inputDocxPath);
|
||||||
|
const zip = await JSZip.loadAsync(inputBytes);
|
||||||
|
const safeFamily = String(fontFamily).replace(/[^A-Za-z0-9]/g, '');
|
||||||
|
const fontFilename = `${safeFamily}.ttf`;
|
||||||
|
const fontBytes = fs.readFileSync(ttfPath);
|
||||||
|
zip.file(`word/fonts/${fontFilename}`, fontBytes);
|
||||||
|
zip.file(FONT_TABLE_PATH, fontTableXml(safeFamily));
|
||||||
|
zip.file(FONT_TABLE_RELS_PATH, fontTableRels(fontFilename));
|
||||||
|
const out = await zip.generateAsync({ type: 'nodebuffer' });
|
||||||
|
fs.writeFileSync(outputDocxPath, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { embedDocxFont };
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const JSZip = require('jszip');
|
||||||
|
|
||||||
|
function withEpubEmbedFontArgs(pandocArgs, ttfPath, _fontFamily) {
|
||||||
|
return [`--epub-embed-font=${ttfPath}`, ...pandocArgs];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function embedEpubFont(epubPath, ttfPath, _fontFamily) {
|
||||||
|
if (!ttfPath || !fs.existsSync(ttfPath)) {
|
||||||
|
throw new Error(`EpubFontEmbedder: TTF not found at ${ttfPath}`);
|
||||||
|
}
|
||||||
|
const bytes = fs.readFileSync(epubPath);
|
||||||
|
const zip = await JSZip.loadAsync(bytes);
|
||||||
|
const ttfBytes = fs.readFileSync(ttfPath);
|
||||||
|
const fontName = path.basename(ttfPath);
|
||||||
|
zip.file(`OEBPS/${fontName}`, ttfBytes);
|
||||||
|
const opfPath = 'OEBPS/content.opf';
|
||||||
|
const opfFile = zip.file(opfPath);
|
||||||
|
if (!opfFile) {
|
||||||
|
fs.writeFileSync(epubPath, await zip.generateAsync({ type: 'nodebuffer' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let opf = await opfFile.async('string');
|
||||||
|
const manifestEntry = `<item id="font-${path.basename(fontName, '.ttf')}" href="${fontName}" media-type="application/x-font-ttf"/>`;
|
||||||
|
if (!opf.includes('manifest')) {
|
||||||
|
opf = opf.replace('</package>', `<manifest>${manifestEntry}</manifest></package>`);
|
||||||
|
} else if (!opf.includes(fontName)) {
|
||||||
|
opf = opf.replace('</manifest>', `${manifestEntry}</manifest>`);
|
||||||
|
}
|
||||||
|
zip.file(opfPath, opf);
|
||||||
|
fs.writeFileSync(epubPath, await zip.generateAsync({ type: 'nodebuffer' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { withEpubEmbedFontArgs, embedEpubFont };
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { FAMILY_BY_KEY } = require('./settings/monospaceSettings');
|
||||||
|
|
||||||
|
function buildFontFaceBlock(family, woff2Bytes) {
|
||||||
|
const safeFamily = family.replace(/'/g, "\\'");
|
||||||
|
const b64 = Buffer.from(woff2Bytes).toString('base64');
|
||||||
|
return `@font-face {
|
||||||
|
font-family: '${safeFamily}';
|
||||||
|
src: url(data:font/woff2;base64,${b64}) format('woff2');
|
||||||
|
font-weight: 100 900;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildExportCss(settings, { woff2 } = {}) {
|
||||||
|
const family = (settings && FAMILY_BY_KEY[settings.monospaceFont]) || 'JetBrains Mono';
|
||||||
|
const ligatures = !!(settings && settings.monospaceLigatures === true);
|
||||||
|
const face = buildFontFaceBlock(family, woff2 || Buffer.alloc(0));
|
||||||
|
const feature = ligatures ? `code, pre, kbd, samp { font-feature-settings: 'liga' 1, 'calt' 1; }` : '';
|
||||||
|
return [face, feature].filter(Boolean).join('\n\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildExportCss, buildFontFaceBlock };
|
||||||
@@ -7,9 +7,24 @@ function getGitInstance(dir) {
|
|||||||
async function getStatus(dir) {
|
async function getStatus(dir) {
|
||||||
try {
|
try {
|
||||||
const git = getGitInstance(dir);
|
const git = getGitInstance(dir);
|
||||||
return await git.status();
|
const result = await git.status();
|
||||||
} catch (err) {
|
const files = [];
|
||||||
return { error: 'Not a git repository' };
|
for (const [filePath, status] of Object.entries(result.files || {})) {
|
||||||
|
files.push({
|
||||||
|
filePath,
|
||||||
|
status:
|
||||||
|
status.working_dir === 'M'
|
||||||
|
? 'modified'
|
||||||
|
: status.working_dir === 'A' || status.index === 'A'
|
||||||
|
? 'added'
|
||||||
|
: status.working_dir === 'D' || status.index === 'D'
|
||||||
|
? 'deleted'
|
||||||
|
: 'untracked',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { files };
|
||||||
|
} catch (_err) {
|
||||||
|
return { files: [], error: 'Not a git repository' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,16 +32,32 @@ async function stage(dir, files) {
|
|||||||
try {
|
try {
|
||||||
const git = getGitInstance(dir);
|
const git = getGitInstance(dir);
|
||||||
await git.add(files);
|
await git.add(files);
|
||||||
return await git.status();
|
const result = await git.status();
|
||||||
|
const staged = [];
|
||||||
|
for (const [filePath, status] of Object.entries(result.files || {})) {
|
||||||
|
staged.push({
|
||||||
|
filePath,
|
||||||
|
status:
|
||||||
|
status.index === 'A'
|
||||||
|
? 'added'
|
||||||
|
: status.index === 'M'
|
||||||
|
? 'modified'
|
||||||
|
: status.index === 'D'
|
||||||
|
? 'deleted'
|
||||||
|
: 'untracked',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { files: staged };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { error: err.message };
|
return { files: [], error: err.message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function commit(dir, message) {
|
async function commit(dir, message) {
|
||||||
try {
|
try {
|
||||||
const git = getGitInstance(dir);
|
const git = getGitInstance(dir);
|
||||||
return await git.commit(message);
|
const result = await git.commit(message);
|
||||||
|
return { summary: result?.summary || 'Committed' };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { error: err.message };
|
return { error: err.message };
|
||||||
}
|
}
|
||||||
@@ -35,10 +66,29 @@ async function commit(dir, message) {
|
|||||||
async function log(dir, maxCount = 20) {
|
async function log(dir, maxCount = 20) {
|
||||||
try {
|
try {
|
||||||
const git = getGitInstance(dir);
|
const git = getGitInstance(dir);
|
||||||
return await git.log({ maxCount });
|
const result = await git.log({ maxCount });
|
||||||
|
return {
|
||||||
|
latest: result?.latest || null,
|
||||||
|
all: (result?.all || []).map((entry) => ({
|
||||||
|
hash: entry.hash,
|
||||||
|
message: entry.message,
|
||||||
|
author: entry.author_name,
|
||||||
|
date: entry.date,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
return { all: [], error: err.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function diff(dir, filePath) {
|
||||||
|
try {
|
||||||
|
const git = getGitInstance(dir);
|
||||||
|
const args = filePath ? ['--', filePath] : [];
|
||||||
|
return await git.diff(args);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { error: err.message };
|
return { error: err.message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { getStatus, stage, commit, log };
|
module.exports = { getStatus, stage, commit, log, diff };
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
'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 };
|
||||||
+64
-45
@@ -4,11 +4,11 @@ const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
|
|||||||
|
|
||||||
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);
|
||||||
@@ -27,11 +27,13 @@ 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,
|
? {
|
||||||
g: parseInt(result[2], 16) / 255,
|
r: parseInt(result[1], 16) / 255,
|
||||||
b: parseInt(result[3], 16) / 255
|
g: parseInt(result[2], 16) / 255,
|
||||||
} : { r: 0, g: 0, b: 0 };
|
b: parseInt(result[3], 16) / 255,
|
||||||
|
}
|
||||||
|
: { r: 0, g: 0, b: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pdfMerge(data) {
|
async function pdfMerge(data) {
|
||||||
@@ -42,7 +44,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();
|
||||||
@@ -60,16 +62,16 @@ async function pdfSplit(data) {
|
|||||||
const pdf = await PDFDocument.load(pdfBytes);
|
const pdf = await PDFDocument.load(pdfBytes);
|
||||||
const totalPages = pdf.getPageCount();
|
const totalPages = pdf.getPageCount();
|
||||||
|
|
||||||
let 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];
|
||||||
let 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);
|
||||||
}
|
}
|
||||||
@@ -108,7 +110,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();
|
||||||
@@ -129,18 +131,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 };
|
||||||
@@ -160,7 +162,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));
|
||||||
});
|
});
|
||||||
@@ -170,7 +172,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 };
|
||||||
@@ -185,16 +187,18 @@ async function pdfDeletePages(data) {
|
|||||||
|
|
||||||
const pagesToDelete = parsePageRanges(data.pages, totalPages);
|
const pagesToDelete = parsePageRanges(data.pages, totalPages);
|
||||||
|
|
||||||
pagesToDelete.sort((a, b) => b - a).forEach(pageIndex => {
|
pagesToDelete
|
||||||
pdf.removePage(pageIndex);
|
.sort((a, b) => b - a)
|
||||||
});
|
.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 };
|
||||||
@@ -207,7 +211,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` };
|
||||||
@@ -215,7 +219,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);
|
||||||
@@ -246,7 +250,9 @@ async function pdfWatermark(data) {
|
|||||||
const page = pdf.getPage(pageIndex);
|
const page = pdf.getPage(pageIndex);
|
||||||
const { width, height } = page.getSize();
|
const { width, height } = page.getSize();
|
||||||
|
|
||||||
let x, y, rotation = 0;
|
let x,
|
||||||
|
y,
|
||||||
|
rotation = 0;
|
||||||
|
|
||||||
switch (data.position) {
|
switch (data.position) {
|
||||||
case 'center':
|
case 'center':
|
||||||
@@ -294,7 +300,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),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,7 +309,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 };
|
||||||
@@ -325,8 +331,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);
|
||||||
@@ -336,7 +342,8 @@ 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: 'PDF encryption requires pdf-lib with encryption support. This feature may not be available in the current version.'
|
error:
|
||||||
|
'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 };
|
||||||
@@ -375,8 +382,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);
|
||||||
@@ -386,7 +393,8 @@ 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: 'PDF permissions require pdf-lib with encryption support. This feature may not be available in the current version.'
|
error:
|
||||||
|
'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 };
|
||||||
@@ -395,17 +403,28 @@ async function pdfSetPermissions(data) {
|
|||||||
|
|
||||||
function executeOperation(operation, data) {
|
function executeOperation(operation, data) {
|
||||||
switch (operation) {
|
switch (operation) {
|
||||||
case 'merge': return pdfMerge(data);
|
case 'merge':
|
||||||
case 'split': return pdfSplit(data);
|
return pdfMerge(data);
|
||||||
case 'compress': return pdfCompress(data);
|
case 'split':
|
||||||
case 'rotate': return pdfRotate(data);
|
return pdfSplit(data);
|
||||||
case 'delete': return pdfDeletePages(data);
|
case 'compress':
|
||||||
case 'reorder': return pdfReorder(data);
|
return pdfCompress(data);
|
||||||
case 'watermark': return pdfWatermark(data);
|
case 'rotate':
|
||||||
case 'encrypt': return pdfEncrypt(data);
|
return pdfRotate(data);
|
||||||
case 'decrypt': return pdfDecrypt(data);
|
case 'delete':
|
||||||
case 'permissions': return pdfSetPermissions(data);
|
return pdfDeletePages(data);
|
||||||
default: return Promise.resolve({ success: false, error: `Unknown operation: ${operation}` });
|
case 'reorder':
|
||||||
|
return pdfReorder(data);
|
||||||
|
case 'watermark':
|
||||||
|
return pdfWatermark(data);
|
||||||
|
case 'encrypt':
|
||||||
|
return pdfEncrypt(data);
|
||||||
|
case 'decrypt':
|
||||||
|
return pdfDecrypt(data);
|
||||||
|
case 'permissions':
|
||||||
|
return pdfSetPermissions(data);
|
||||||
|
default:
|
||||||
|
return Promise.resolve({ success: false, error: `Unknown operation: ${operation}` });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,5 +448,5 @@ module.exports = {
|
|||||||
pdfDecrypt,
|
pdfDecrypt,
|
||||||
pdfSetPermissions,
|
pdfSetPermissions,
|
||||||
executeOperation,
|
executeOperation,
|
||||||
getPageCount
|
getPageCount,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a xelatex/lualatex fontspec header referencing the bundled TTF.
|
||||||
|
*
|
||||||
|
* Uses an exclusive temp directory (mkdtempSync) to avoid the racy
|
||||||
|
* Date.now()+pid filename pattern. Returns the directory along with the
|
||||||
|
* header path; callers MUST `unlinkSync(headerPath)` and `rmdirSync(dir)`
|
||||||
|
* after pandoc consumes the file.
|
||||||
|
*/
|
||||||
|
function buildPdfFontHeader(settings, ttfPath, fontFamily) {
|
||||||
|
if (!ttfPath || !fs.existsSync(ttfPath)) {
|
||||||
|
throw new Error(`PdfFontHeader: TTF not found at ${ttfPath}`);
|
||||||
|
}
|
||||||
|
const ligatures = !!(settings && settings.monospaceLigatures === true);
|
||||||
|
const fontDir = path.dirname(ttfPath);
|
||||||
|
const basename = path.basename(ttfPath);
|
||||||
|
const boldName = basename.replace('Regular', 'Bold').replace('Medium', 'Bold');
|
||||||
|
const lines = [
|
||||||
|
`\\setmonofont[Path = ${fontDir}/,`,
|
||||||
|
` Extension = .ttf,`,
|
||||||
|
` UprightFont = ${basename},`,
|
||||||
|
` BoldFont = ${boldName},`,
|
||||||
|
ligatures ? ' Ligatures=TeX,' : '',
|
||||||
|
` Scale = 0.9]`,
|
||||||
|
`{${fontFamily}}`,
|
||||||
|
].filter(Boolean);
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mono-pdf-'));
|
||||||
|
const headerPath = path.join(dir, 'monospace.tex');
|
||||||
|
fs.writeFileSync(headerPath, lines.join('\n'), 'utf-8');
|
||||||
|
return { headerPath, dir, familyName: fontFamily };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildPdfFontHeader };
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// src/main/files/binary.js
|
||||||
|
// Binary file write handler (used by Word .docx export)
|
||||||
|
const { ipcMain } = require('electron');
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
|
||||||
|
function register() {
|
||||||
|
ipcMain.handle('write-buffer', async (_event, { path: filePath, buffer }) => {
|
||||||
|
await fs.writeFile(filePath, Buffer.from(buffer));
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('read-buffer', async (_event, { path: filePath }) => {
|
||||||
|
const data = await fs.readFile(filePath);
|
||||||
|
return { ok: true, data };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
// src/main/files/git.js
|
||||||
|
// Git IPC handlers — thin wrapper over GitOperations
|
||||||
|
const { ipcMain } = require('electron');
|
||||||
|
const GitOperations = require('../GitOperations');
|
||||||
|
|
||||||
|
function register(currentFileRef) {
|
||||||
|
ipcMain.handle('git-status', async (_event, rootPath) => {
|
||||||
|
const dir =
|
||||||
|
rootPath ||
|
||||||
|
(currentFileRef.current ? require('path').dirname(currentFileRef.current) : process.cwd());
|
||||||
|
const result = GitOperations.getStatus(dir);
|
||||||
|
return Array.isArray(result?.files) ? result.files : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('git-stage', async (_event, { rootPath, files }) => {
|
||||||
|
const dir =
|
||||||
|
rootPath ||
|
||||||
|
(currentFileRef.current ? require('path').dirname(currentFileRef.current) : process.cwd());
|
||||||
|
return GitOperations.stage(dir, files);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('git-commit', async (_event, { rootPath, message }) => {
|
||||||
|
const dir =
|
||||||
|
rootPath ||
|
||||||
|
(currentFileRef.current ? require('path').dirname(currentFileRef.current) : process.cwd());
|
||||||
|
return GitOperations.commit(dir, message);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('git-log', async (_event, rootPath) => {
|
||||||
|
const dir =
|
||||||
|
rootPath ||
|
||||||
|
(currentFileRef.current ? require('path').dirname(currentFileRef.current) : process.cwd());
|
||||||
|
return GitOperations.log(dir);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('git-diff', async (_event, filePath) => {
|
||||||
|
const dir = filePath
|
||||||
|
? require('path').dirname(filePath)
|
||||||
|
: currentFileRef.current
|
||||||
|
? require('path').dirname(currentFileRef.current)
|
||||||
|
: process.cwd();
|
||||||
|
return GitOperations.diff(dir, filePath);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
// src/main/files/index.js
|
||||||
|
// File ops facade — registers all file-related IPC handlers
|
||||||
|
const { ipcMain, dialog } = require('electron');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { register: registerGit } = require('./git');
|
||||||
|
const { register: registerBinary } = require('./binary');
|
||||||
|
const { searchInFiles } = require('./search-in-files');
|
||||||
|
|
||||||
|
function register({
|
||||||
|
validatePath,
|
||||||
|
resolveWritablePath,
|
||||||
|
isPathAccessible,
|
||||||
|
currentFileRef,
|
||||||
|
mainWindow,
|
||||||
|
}) {
|
||||||
|
// pick-folder
|
||||||
|
ipcMain.handle('pick-folder', async () => {
|
||||||
|
const result = await dialog.showOpenDialog(mainWindow, {
|
||||||
|
properties: ['openDirectory'],
|
||||||
|
});
|
||||||
|
if (result.canceled || result.filePaths.length === 0) return null;
|
||||||
|
return result.filePaths[0];
|
||||||
|
});
|
||||||
|
|
||||||
|
// pick-file
|
||||||
|
ipcMain.handle('pick-file', async () => {
|
||||||
|
const result = await dialog.showOpenDialog(mainWindow, {
|
||||||
|
properties: ['openFile'],
|
||||||
|
filters: [{ name: 'Markdown', extensions: ['md', 'markdown', 'mdown', 'mkd'] }],
|
||||||
|
});
|
||||||
|
if (result.canceled || result.filePaths.length === 0) return null;
|
||||||
|
return result.filePaths[0];
|
||||||
|
});
|
||||||
|
|
||||||
|
// read-file
|
||||||
|
ipcMain.handle('read-file', async (event, filePath) => {
|
||||||
|
const validation = validatePath(filePath);
|
||||||
|
if (!validation.valid || !isPathAccessible(validation.resolved)) {
|
||||||
|
throw new Error(validation.error || 'Invalid file path');
|
||||||
|
}
|
||||||
|
return fs.readFileSync(validation.resolved, 'utf-8');
|
||||||
|
});
|
||||||
|
|
||||||
|
// write-file
|
||||||
|
ipcMain.handle('write-file', async (event, payload) => {
|
||||||
|
const validation = resolveWritablePath(payload?.path);
|
||||||
|
if (!validation.valid) {
|
||||||
|
throw new Error(validation.error || 'Invalid file path');
|
||||||
|
}
|
||||||
|
fs.mkdirSync(path.dirname(validation.resolved), { recursive: true });
|
||||||
|
fs.writeFileSync(validation.resolved, payload?.content ?? '', 'utf-8');
|
||||||
|
return { path: validation.resolved };
|
||||||
|
});
|
||||||
|
|
||||||
|
// delete-file
|
||||||
|
ipcMain.handle('delete-file', async (event, filePath) => {
|
||||||
|
const validation = validatePath(filePath);
|
||||||
|
if (!validation.valid || !isPathAccessible(validation.resolved)) {
|
||||||
|
throw new Error(validation.error || 'Invalid file path');
|
||||||
|
}
|
||||||
|
fs.rmSync(validation.resolved, { recursive: true, force: false });
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// ensure-directory
|
||||||
|
ipcMain.handle('ensure-directory', async (event, dirPath) => {
|
||||||
|
const validation = resolveWritablePath(dirPath);
|
||||||
|
if (!validation.valid) {
|
||||||
|
throw new Error(validation.error || 'Invalid directory path');
|
||||||
|
}
|
||||||
|
fs.mkdirSync(validation.resolved, { recursive: true });
|
||||||
|
return validation.resolved;
|
||||||
|
});
|
||||||
|
|
||||||
|
// path-exists
|
||||||
|
ipcMain.handle('path-exists', async (event, filePath) => {
|
||||||
|
const validation = resolveWritablePath(filePath);
|
||||||
|
return validation.valid ? fs.existsSync(validation.resolved) : false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// is-directory
|
||||||
|
ipcMain.handle('is-directory', async (event, filePath) => {
|
||||||
|
const validation = validatePath(filePath);
|
||||||
|
if (!validation.valid || !isPathAccessible(validation.resolved)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return fs.statSync(validation.resolved).isDirectory();
|
||||||
|
});
|
||||||
|
|
||||||
|
// copy-path
|
||||||
|
ipcMain.handle('copy-path', async (event, payload) => {
|
||||||
|
const sourceValidation = validatePath(payload?.source);
|
||||||
|
const destinationValidation = resolveWritablePath(payload?.destination);
|
||||||
|
|
||||||
|
if (!sourceValidation.valid || !isPathAccessible(sourceValidation.resolved)) {
|
||||||
|
throw new Error(sourceValidation.error || 'Invalid source path');
|
||||||
|
}
|
||||||
|
if (!destinationValidation.valid) {
|
||||||
|
throw new Error(destinationValidation.error || 'Invalid destination path');
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(destinationValidation.resolved), { recursive: true });
|
||||||
|
fs.cpSync(sourceValidation.resolved, destinationValidation.resolved, { recursive: true });
|
||||||
|
return { source: sourceValidation.resolved, destination: destinationValidation.resolved };
|
||||||
|
});
|
||||||
|
|
||||||
|
// move-path
|
||||||
|
ipcMain.handle('move-path', async (event, payload) => {
|
||||||
|
const sourceValidation = validatePath(payload?.source);
|
||||||
|
const destinationValidation = resolveWritablePath(payload?.destination);
|
||||||
|
|
||||||
|
if (!sourceValidation.valid || !isPathAccessible(sourceValidation.resolved)) {
|
||||||
|
throw new Error(sourceValidation.error || 'Invalid source path');
|
||||||
|
}
|
||||||
|
if (!destinationValidation.valid) {
|
||||||
|
throw new Error(destinationValidation.error || 'Invalid destination path');
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(destinationValidation.resolved), { recursive: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.renameSync(sourceValidation.resolved, destinationValidation.resolved);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'EXDEV') {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
fs.cpSync(sourceValidation.resolved, destinationValidation.resolved, { recursive: true });
|
||||||
|
fs.rmSync(sourceValidation.resolved, { recursive: true, force: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { source: sourceValidation.resolved, destination: destinationValidation.resolved };
|
||||||
|
});
|
||||||
|
|
||||||
|
// search-in-files
|
||||||
|
ipcMain.handle('search-in-files', async (_event, payload) => {
|
||||||
|
const validation = validatePath(payload?.rootPath);
|
||||||
|
if (!validation.valid || !isPathAccessible(validation.resolved)) {
|
||||||
|
console.error('[SECURITY] Invalid search rootPath:', validation.error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return searchInFiles({ ...(payload || {}), rootPath: validation.resolved });
|
||||||
|
});
|
||||||
|
|
||||||
|
// open-file-path
|
||||||
|
ipcMain.on('open-file-path', (event, filePath) => {
|
||||||
|
try {
|
||||||
|
const validation = validatePath(filePath);
|
||||||
|
if (!validation.valid) {
|
||||||
|
console.error('[SECURITY] Invalid file path:', validation.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isPathAccessible(validation.resolved)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const stat = fs.statSync(validation.resolved);
|
||||||
|
if (stat.size > 50 * 1024 * 1024) return;
|
||||||
|
const content = fs.readFileSync(validation.resolved, 'utf-8');
|
||||||
|
// Emit set-current-file back to main process so it updates its currentFile variable
|
||||||
|
mainWindow.webContents.send('set-current-file', validation.resolved);
|
||||||
|
mainWindow.webContents.send('file-opened', { path: validation.resolved, content });
|
||||||
|
} catch (err) {
|
||||||
|
console.error('open-file-path error:', err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register sub-modules
|
||||||
|
registerGit(currentFileRef);
|
||||||
|
registerBinary();
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List a directory's entries (excluding dotfiles), sorted directories-first
|
||||||
|
* then alphabetically. Returns a flat array of FileEntry-shaped objects,
|
||||||
|
* matching the renderer type declaration in `src/renderer/lib/ipc.ts`.
|
||||||
|
*
|
||||||
|
* Skips entries that cannot be stat'd (permission errors, broken symlinks)
|
||||||
|
* instead of throwing — keeps the UI responsive on partially-readable dirs.
|
||||||
|
*/
|
||||||
|
function listDirectoryEntries(dirPath) {
|
||||||
|
const dirents = fs.readdirSync(dirPath, { withFileTypes: true });
|
||||||
|
const entries = [];
|
||||||
|
for (const d of dirents) {
|
||||||
|
if (d.name.startsWith('.')) continue;
|
||||||
|
const full = path.join(dirPath, d.name);
|
||||||
|
let size = 0;
|
||||||
|
let modified = 0;
|
||||||
|
try {
|
||||||
|
const s = fs.statSync(full);
|
||||||
|
size = d.isDirectory() ? 0 : s.size;
|
||||||
|
modified = s.mtimeMs;
|
||||||
|
} catch (_err) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
entries.push({
|
||||||
|
name: d.name,
|
||||||
|
isDirectory: d.isDirectory(),
|
||||||
|
size,
|
||||||
|
modifiedAt: modified,
|
||||||
|
path: full,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
entries.sort((a, b) => {
|
||||||
|
if (a.isDirectory && !b.isDirectory) return -1;
|
||||||
|
if (!a.isDirectory && b.isDirectory) return 1;
|
||||||
|
return a.name.localeCompare(b.name);
|
||||||
|
});
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { listDirectoryEntries };
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const MAX_RESULTS = 1000;
|
||||||
|
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
||||||
|
const MAX_FILES = 10000;
|
||||||
|
const MAX_QUERY_LENGTH = 1024;
|
||||||
|
const MAX_REGEX_LENGTH = 200;
|
||||||
|
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.next', '.cache']);
|
||||||
|
|
||||||
|
// Reject regexes with classic ReDoS shapes. This is a defense-in-depth
|
||||||
|
// denylist, not a proof of safety — the hard caps on length, files, and
|
||||||
|
// results are the primary defense.
|
||||||
|
const UNSAFE_REGEX = new RegExp(
|
||||||
|
// nested quantifiers: (a+)+, [a-z]*+
|
||||||
|
'\\([^)]*[+*][^)]*\\)[+*?]' +
|
||||||
|
'|' +
|
||||||
|
// class with quantifier: [a-z]+
|
||||||
|
'\\[[^\\]]*\\][+*]' +
|
||||||
|
'|' +
|
||||||
|
// dot-quantifier followed by dot-quantifier
|
||||||
|
'\\.[+*]\\s*\\.[+*]' +
|
||||||
|
'|' +
|
||||||
|
// lookahead / lookbehind
|
||||||
|
'\\(\\?[=!]' +
|
||||||
|
'|' +
|
||||||
|
// backrefs
|
||||||
|
'\\\\[1-9]' +
|
||||||
|
'|' +
|
||||||
|
// alternation with quantifier
|
||||||
|
'\\([^)]*\\|[^)]*\\)[+*]'
|
||||||
|
);
|
||||||
|
|
||||||
|
function listFiles(rootPath) {
|
||||||
|
const out = [];
|
||||||
|
const stack = [rootPath];
|
||||||
|
const visited = new Set();
|
||||||
|
while (stack.length && out.length < MAX_FILES) {
|
||||||
|
const dir = stack.pop();
|
||||||
|
// Resolve symlinks and verify we haven't escaped the root.
|
||||||
|
let real;
|
||||||
|
try {
|
||||||
|
real = fs.realpathSync(dir);
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (visited.has(real)) continue;
|
||||||
|
visited.add(real);
|
||||||
|
const rootReal = fs.realpathSync(rootPath);
|
||||||
|
if (!real.startsWith(rootReal + path.sep) && real !== rootReal) continue;
|
||||||
|
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = fs.readdirSync(real, { withFileTypes: true });
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
if (e.name.startsWith('.')) continue;
|
||||||
|
const full = path.join(real, e.name);
|
||||||
|
// Follow symlinks but verify containment again.
|
||||||
|
try {
|
||||||
|
const s = fs.lstatSync(full);
|
||||||
|
if (s.isSymbolicLink()) {
|
||||||
|
const linkTarget = fs.realpathSync(full);
|
||||||
|
if (!linkTarget.startsWith(rootReal + path.sep) && linkTarget !== rootReal) continue;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const s = fs.statSync(full);
|
||||||
|
if (s.isDirectory()) {
|
||||||
|
if (SKIP_DIRS.has(e.name)) continue;
|
||||||
|
stack.push(full);
|
||||||
|
} else if (s.isFile()) {
|
||||||
|
out.push(full);
|
||||||
|
if (out.length >= MAX_FILES) break;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeMatcher(query, isRegex, caseSensitive) {
|
||||||
|
if (isRegex) {
|
||||||
|
if (query.length > MAX_REGEX_LENGTH) return null;
|
||||||
|
if (UNSAFE_REGEX.test(query)) return null;
|
||||||
|
try {
|
||||||
|
const re = new RegExp(query, caseSensitive ? '' : 'i');
|
||||||
|
return (line) => re.test(line);
|
||||||
|
} catch (_err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const needle = caseSensitive ? query : query.toLowerCase();
|
||||||
|
return (line) => (caseSensitive ? line : line.toLowerCase()).includes(needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recursively search `rootPath` for files containing `query`.
|
||||||
|
* Returns up to MAX_RESULTS matches of the form
|
||||||
|
* { filePath, line, content }.
|
||||||
|
*
|
||||||
|
* Hardened against:
|
||||||
|
* - Path traversal via symlinks (verified after realpathSync)
|
||||||
|
* - ReDoS via nested-quantifier regex (rejected at match time)
|
||||||
|
* - Resource exhaustion via MAX_FILES + MAX_FILE_BYTES + MAX_RESULTS
|
||||||
|
* - Empty / oversized queries via MAX_QUERY_LENGTH
|
||||||
|
*/
|
||||||
|
function searchInFiles({ rootPath, query, isRegex = false, caseSensitive = false }) {
|
||||||
|
if (!rootPath || !query) return [];
|
||||||
|
if (typeof query !== 'string' || query.length > MAX_QUERY_LENGTH) return [];
|
||||||
|
const matcher = makeMatcher(query, isRegex, caseSensitive);
|
||||||
|
if (!matcher) return [];
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
for (const filePath of listFiles(rootPath)) {
|
||||||
|
if (results.length >= MAX_RESULTS) break;
|
||||||
|
let stat;
|
||||||
|
try {
|
||||||
|
stat = fs.statSync(filePath);
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) continue;
|
||||||
|
|
||||||
|
let content;
|
||||||
|
try {
|
||||||
|
content = fs.readFileSync(filePath, 'utf-8');
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const lines = content.split(/\r?\n/);
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
if (matcher(lines[i])) {
|
||||||
|
results.push({ filePath, line: i + 1, content: lines[i] });
|
||||||
|
if (results.length >= MAX_RESULTS) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { searchInFiles };
|
||||||
+913
-1479
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
|||||||
|
const { ipcMain, shell } = require('electron');
|
||||||
|
|
||||||
|
function register({ crash, getMainWindow: _getMainWindow }) {
|
||||||
|
ipcMain.handle('crash:read', () => {
|
||||||
|
return crash.list();
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.on('crash:open-dir', () => {
|
||||||
|
shell.openPath(crash.path());
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('crash:delete', (_event, filename) => {
|
||||||
|
if (
|
||||||
|
typeof filename === 'string' &&
|
||||||
|
/^\d+(-\d+)?-(uncaughtException|unhandledRejection)\.json$/.test(filename)
|
||||||
|
) {
|
||||||
|
crash.delete(filename);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { ipcMain } = require('electron');
|
||||||
|
const store = require('../store');
|
||||||
|
const { safeMonospaceSettings, DEFAULT_SETTINGS } = require('../settings/monospaceSettings');
|
||||||
|
|
||||||
|
function readCurrent() {
|
||||||
|
return {
|
||||||
|
monospaceFont: store.get('monospaceFont', DEFAULT_SETTINGS.monospaceFont),
|
||||||
|
monospaceLigatures: store.get('monospaceLigatures', DEFAULT_SETTINGS.monospaceLigatures),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function register() {
|
||||||
|
ipcMain.handle('get-monospace-settings', () => readCurrent());
|
||||||
|
|
||||||
|
ipcMain.handle('set-monospace-settings', (_event, partial) => {
|
||||||
|
const safe = safeMonospaceSettings(partial || {});
|
||||||
|
if (Object.prototype.hasOwnProperty.call(partial || {}, 'monospaceFont')) {
|
||||||
|
store.set('monospaceFont', safe.monospaceFont);
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(partial || {}, 'monospaceLigatures')) {
|
||||||
|
store.set('monospaceLigatures', safe.monospaceLigatures);
|
||||||
|
}
|
||||||
|
return readCurrent();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register, readCurrent };
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
const { ipcMain } = require('electron');
|
||||||
|
const { feedConfigFor } = require('../updater/feed-config');
|
||||||
|
|
||||||
|
function register({ updater, getMainWindow, getChannel }) {
|
||||||
|
ipcMain.handle('updater:check', async () => {
|
||||||
|
const channel = getChannel();
|
||||||
|
updater.autoUpdater.setFeedURL(feedConfigFor(channel));
|
||||||
|
await updater.check();
|
||||||
|
return { state: updater.state };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('updater:install', () => {
|
||||||
|
updater.install();
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('updater:get-state', () => {
|
||||||
|
return { state: updater.state };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Forward status events to renderer
|
||||||
|
updater.on('status', (payload) => {
|
||||||
|
const win = getMainWindow();
|
||||||
|
if (win && !win.isDestroyed()) {
|
||||||
|
win.webContents.send('updater:status', payload);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// src/main/menu/index.js
|
||||||
|
// buildMenu() composes the app menu from items; register() sets it on the app
|
||||||
|
|
||||||
|
const { Menu } = require('electron');
|
||||||
|
const {
|
||||||
|
fileItems,
|
||||||
|
editItems,
|
||||||
|
viewItems,
|
||||||
|
batchItems,
|
||||||
|
convertItems,
|
||||||
|
pdfEditorItems,
|
||||||
|
toolsItems,
|
||||||
|
helpItems,
|
||||||
|
} = require('./items');
|
||||||
|
|
||||||
|
function buildMenu(mainWindow) {
|
||||||
|
const template = [
|
||||||
|
{ label: '&File', submenu: fileItems(mainWindow) },
|
||||||
|
{ label: '&Edit', submenu: editItems(mainWindow) },
|
||||||
|
{ label: '&View', submenu: viewItems(mainWindow) },
|
||||||
|
{ label: '&Batch', submenu: batchItems(mainWindow) },
|
||||||
|
{ label: '&Convert', submenu: convertItems(mainWindow) },
|
||||||
|
{ label: 'PDF Editor', submenu: pdfEditorItems(mainWindow) },
|
||||||
|
{ label: '&Tools', submenu: toolsItems(mainWindow) },
|
||||||
|
{ label: '&Help', submenu: helpItems(mainWindow) },
|
||||||
|
];
|
||||||
|
return Menu.buildFromTemplate(template);
|
||||||
|
}
|
||||||
|
|
||||||
|
function register(mainWindow) {
|
||||||
|
Menu.setApplicationMenu(buildMenu(mainWindow));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register, buildMenu };
|
||||||
@@ -0,0 +1,799 @@
|
|||||||
|
// src/main/menu/items.js
|
||||||
|
// Individual menu items — pure functions that take (mainWindow) and return menu item arrays
|
||||||
|
|
||||||
|
const { app, shell } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
// Helper: build recent files submenu
|
||||||
|
function buildRecentFilesMenu(mainWindow) {
|
||||||
|
try {
|
||||||
|
const recentFilesPath = path.join(app.getPath('userData'), 'recent-files.json');
|
||||||
|
if (!fs.existsSync(recentFilesPath)) return [{ label: 'No Recent Files', enabled: false }];
|
||||||
|
const recentFiles = JSON.parse(fs.readFileSync(recentFilesPath, 'utf-8'));
|
||||||
|
const existing = recentFiles.filter((file) => fs.existsSync(file));
|
||||||
|
if (existing.length === 0) return [{ label: 'No Recent Files', enabled: false }];
|
||||||
|
const items = existing.map((file) => ({
|
||||||
|
label: path.basename(file),
|
||||||
|
click: () => {
|
||||||
|
const { openFileFromPath } = require('../index');
|
||||||
|
openFileFromPath(file);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
items.push(
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Clear Recent Files',
|
||||||
|
click: () => {
|
||||||
|
if (mainWindow) {
|
||||||
|
mainWindow.webContents.send('clear-recent-files');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return items;
|
||||||
|
} catch (_e) {
|
||||||
|
return [{ label: 'No Recent Files', enabled: false }];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileItems(mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'New',
|
||||||
|
accelerator: 'CmdOrCtrl+N',
|
||||||
|
click: () => mainWindow.webContents.send('file-new'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Open',
|
||||||
|
accelerator: 'CmdOrCtrl+O',
|
||||||
|
click: () => {
|
||||||
|
const { openFile } = require('../index');
|
||||||
|
openFile();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Open PDF',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+O',
|
||||||
|
click: () => {
|
||||||
|
const { openPdfFile } = require('../index');
|
||||||
|
openPdfFile();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Save',
|
||||||
|
accelerator: 'CmdOrCtrl+S',
|
||||||
|
click: () => mainWindow.webContents.send('file-save'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Save As',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+S',
|
||||||
|
click: () => {
|
||||||
|
const { saveAsFile } = require('../index');
|
||||||
|
saveAsFile();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
// NOTE: Print Preview submenu removed — handled by React <PrintPreview> overlay
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Recent Files',
|
||||||
|
submenu: buildRecentFilesMenu(mainWindow),
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'New from Template',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Blog Post',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'blog-post.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Meeting Notes',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'meeting-notes.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Technical Spec',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'technical-spec.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Changelog',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'changelog.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'README',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'readme.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Project Plan',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'project-plan.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'API Documentation',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'api-docs.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Tutorial',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'tutorial.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Release Notes',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'release-notes.md'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Comparison',
|
||||||
|
click: () => mainWindow.webContents.send('load-template-menu', 'comparison.md'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Import Document...',
|
||||||
|
accelerator: 'CmdOrCtrl+I',
|
||||||
|
click: () => {
|
||||||
|
const { importDocument } = require('../index');
|
||||||
|
importDocument();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Export',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'HTML',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('html');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'PDF',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('pdf');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'PDF (Enhanced)',
|
||||||
|
click: () => {
|
||||||
|
const { exportPDFViaWordTemplate } = require('../index');
|
||||||
|
exportPDFViaWordTemplate();
|
||||||
|
},
|
||||||
|
accelerator: 'Ctrl+Shift+P',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'DOCX',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('docx');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'DOCX (Enhanced)',
|
||||||
|
click: () => {
|
||||||
|
const { exportWordWithTemplate } = require('../index');
|
||||||
|
exportWordWithTemplate();
|
||||||
|
},
|
||||||
|
accelerator: 'Ctrl+Shift+W',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'LaTeX',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('latex');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'RTF',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('rtf');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'ODT',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('odt');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'EPUB',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('epub');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'PowerPoint (PPTX)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('pptx');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'OpenDocument Presentation (ODP)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('odp');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'CSV (Tables)',
|
||||||
|
click: () => {
|
||||||
|
const { exportSpreadsheet } = require('../index');
|
||||||
|
exportSpreadsheet('csv');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'JSON (.json)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('json');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'YAML (.yaml)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('yaml');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'XML (.xml)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('xml');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Confluence Wiki (.txt)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('confluence');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'MOBI E-book (.mobi)',
|
||||||
|
click: () => {
|
||||||
|
const { exportFile } = require('../index');
|
||||||
|
exportFile('mobi');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Select Word Template...',
|
||||||
|
click: () => {
|
||||||
|
const { selectWordTemplate } = require('../index');
|
||||||
|
selectWordTemplate();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Template Settings...',
|
||||||
|
click: () => {
|
||||||
|
const { showTemplateSettings } = require('../index');
|
||||||
|
showTemplateSettings();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Header & Footer Settings...',
|
||||||
|
click: () => {
|
||||||
|
if (mainWindow) {
|
||||||
|
mainWindow.webContents.send('open-header-footer-dialog');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Quit',
|
||||||
|
accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
|
||||||
|
click: () => app.quit(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function editItems(mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Undo',
|
||||||
|
accelerator: 'CmdOrCtrl+Z',
|
||||||
|
click: () => mainWindow.webContents.send('undo'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Redo',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+Z',
|
||||||
|
click: () => mainWindow.webContents.send('redo'),
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' },
|
||||||
|
{ label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' },
|
||||||
|
{ label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' },
|
||||||
|
{ label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectAll' },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Find & Replace',
|
||||||
|
accelerator: 'CmdOrCtrl+F',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-find'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function viewItems(mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Toggle Preview',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+V',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-preview'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Writing Analytics',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+A',
|
||||||
|
click: () => mainWindow.webContents.send('show-analytics-dialog'),
|
||||||
|
},
|
||||||
|
// NOTE: Command Palette removed — handled by useCommandStore
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Sidebar',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Files',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-sidebar-panel', 'explorer'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Outline',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-sidebar-panel', 'outline'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Snippets',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-sidebar-panel', 'snippets'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Templates',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-sidebar-panel', 'templates'),
|
||||||
|
},
|
||||||
|
{ label: 'Git', click: () => mainWindow.webContents.send('toggle-sidebar-panel', 'git') },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Bottom Panel (REPL)',
|
||||||
|
click: () => mainWindow.webContents.send('toggle-bottom-panel'),
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Theme',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Atom One Light (Default)',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('atomonelight');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'GitHub Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('github');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('light');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Solarized Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('solarized');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Gruvbox Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('gruvbox-light');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Ayu Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('ayu-light');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Sepia',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('sepia');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Paper',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('paper');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Rose Pine Dawn',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('rosepine-dawn');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Concrete Light',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('concrete-light');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Dark',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('dark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'One Dark',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('onedark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Dracula',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('dracula');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Nord',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('nord');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Monokai',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('monokai');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Material',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('material');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Gruvbox Dark',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('gruvbox-dark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Tokyo Night',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('tokyonight');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Palenight',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('palenight');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Ayu Dark',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('ayu-dark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Ayu Mirage',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('ayu-mirage');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Oceanic Next',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('oceanic-next');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Cobalt2',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('cobalt2');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Concrete Dark',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('concrete-dark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Concrete Warm',
|
||||||
|
click: () => {
|
||||||
|
const { setTheme } = require('../index');
|
||||||
|
setTheme('concrete-warm');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Font Size',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Increase Font Size',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+Plus',
|
||||||
|
click: () => mainWindow.webContents.send('adjust-font-size', 'increase'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Decrease Font Size',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+-',
|
||||||
|
click: () => mainWindow.webContents.send('adjust-font-size', 'decrease'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Reset Font Size',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+0',
|
||||||
|
click: () => mainWindow.webContents.send('adjust-font-size', 'reset'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Spell Check',
|
||||||
|
type: 'checkbox',
|
||||||
|
checked: true,
|
||||||
|
click: (menuItem) => {
|
||||||
|
mainWindow.webContents.session.setSpellCheckerEnabled(menuItem.checked);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Custom Preview CSS',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Load Custom Preview CSS...',
|
||||||
|
click: () => mainWindow.webContents.send('load-custom-css'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Clear Custom Preview CSS',
|
||||||
|
click: () => mainWindow.webContents.send('clear-custom-css'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: 'Reload', accelerator: 'CmdOrCtrl+R', role: 'reload' },
|
||||||
|
{ label: 'Toggle DevTools', accelerator: 'F12', role: 'toggleDevTools' },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
|
||||||
|
{ label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
|
||||||
|
{ label: 'Reset Zoom', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function batchItems(mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Convert Markdown Folder...',
|
||||||
|
click: () => {
|
||||||
|
const { showBatchConversionDialog } = require('../index');
|
||||||
|
showBatchConversionDialog();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Batch Image Conversion...',
|
||||||
|
click: () => mainWindow.webContents.send('show-batch-converter', 'image'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Batch Audio Conversion...',
|
||||||
|
click: () => mainWindow.webContents.send('show-batch-converter', 'audio'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Batch Video Conversion...',
|
||||||
|
click: () => mainWindow.webContents.send('show-batch-converter', 'video'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Batch PDF Conversion...',
|
||||||
|
click: () => mainWindow.webContents.send('show-batch-converter', 'pdf'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function convertItems(_mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Universal File Converter...',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+C',
|
||||||
|
click: () => {
|
||||||
|
const { showUniversalConverterDialog } = require('../index');
|
||||||
|
showUniversalConverterDialog();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function pdfEditorItems(_mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Open PDF File...',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+O',
|
||||||
|
click: () => {
|
||||||
|
const { openPdfFile } = require('../index');
|
||||||
|
openPdfFile();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Merge PDFs...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('merge');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Split PDF...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('split');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Compress PDF...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('compress');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Rotate Pages...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('rotate');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Delete Pages...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('delete');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Reorder Pages...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('reorder');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Add Watermark...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('watermark');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Security',
|
||||||
|
submenu: [
|
||||||
|
{
|
||||||
|
label: 'Add Password Protection...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('encrypt');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Remove Password...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('decrypt');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Set Permissions...',
|
||||||
|
click: () => {
|
||||||
|
const { showPDFEditorDialog } = require('../index');
|
||||||
|
showPDFEditorDialog('permissions');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'About PDF Editor',
|
||||||
|
click: () => {
|
||||||
|
const { showAboutDialog } = require('../index');
|
||||||
|
showAboutDialog();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toolsItems(mainWindow) {
|
||||||
|
// NOTE: Table Generator and ASCII Art Generator removed — handled by React dialogs
|
||||||
|
return [
|
||||||
|
// Removed: Table Generator (Cmd+Ctrl+Shift+T) — now React <TableGeneratorDialog>
|
||||||
|
// Removed: ASCII Art Generator (Cmd+Ctrl+Shift+A) — now React <AsciiGeneratorDialog>
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Document Compare',
|
||||||
|
click: () => mainWindow.webContents.send('show-document-compare'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function helpItems(_mainWindow) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'About MarkdownConverter',
|
||||||
|
click: () => {
|
||||||
|
const { showAboutDialog } = require('../index');
|
||||||
|
showAboutDialog();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Dependencies & Requirements',
|
||||||
|
click: () => {
|
||||||
|
const { showDependenciesDialog } = require('../index');
|
||||||
|
showDependenciesDialog();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Documentation',
|
||||||
|
click: () => shell.openExternal('https://github.com/amitwh/markdown-converter'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Report Issue',
|
||||||
|
click: () => shell.openExternal('https://github.com/amitwh/markdown-converter/issues'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Check for Updates',
|
||||||
|
click: () => shell.openExternal('https://github.com/amitwh/markdown-converter/releases'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
fileItems,
|
||||||
|
editItems,
|
||||||
|
viewItems,
|
||||||
|
batchItems,
|
||||||
|
convertItems,
|
||||||
|
pdfEditorItems,
|
||||||
|
toolsItems,
|
||||||
|
helpItems,
|
||||||
|
};
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const FAMILY_BY_KEY = {
|
||||||
|
'jetbrains-mono': 'JetBrains Mono',
|
||||||
|
'fira-code': 'Fira Code',
|
||||||
|
};
|
||||||
|
|
||||||
|
const ALLOWED_FONTS = Object.keys(FAMILY_BY_KEY);
|
||||||
|
|
||||||
|
const DEFAULT_SETTINGS = Object.freeze({
|
||||||
|
monospaceFont: 'jetbrains-mono',
|
||||||
|
monospaceLigatures: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
function getActiveMonoFont(settings) {
|
||||||
|
const key = settings && settings.monospaceFont;
|
||||||
|
if (typeof key === 'string' && Object.prototype.hasOwnProperty.call(FAMILY_BY_KEY, key)) {
|
||||||
|
return FAMILY_BY_KEY[key];
|
||||||
|
}
|
||||||
|
return FAMILY_BY_KEY[DEFAULT_SETTINGS.monospaceFont];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLigaturesEnabled(settings) {
|
||||||
|
return !!(settings && settings.monospaceLigatures === true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeMonospaceSettings(input) {
|
||||||
|
const safe = { ...DEFAULT_SETTINGS };
|
||||||
|
if (input && typeof input === 'object') {
|
||||||
|
if (ALLOWED_FONTS.includes(input.monospaceFont)) {
|
||||||
|
safe.monospaceFont = input.monospaceFont;
|
||||||
|
}
|
||||||
|
if (typeof input.monospaceLigatures === 'boolean') {
|
||||||
|
safe.monospaceLigatures = input.monospaceLigatures;
|
||||||
|
} else if (input.monospaceLigatures === 1 || input.monospaceLigatures === 'true') {
|
||||||
|
safe.monospaceLigatures = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
FAMILY_BY_KEY,
|
||||||
|
ALLOWED_FONTS,
|
||||||
|
DEFAULT_SETTINGS,
|
||||||
|
getActiveMonoFont,
|
||||||
|
isLigaturesEnabled,
|
||||||
|
safeMonospaceSettings,
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// src/main/store.js
|
||||||
|
// Simple JSON-file preferences store (replaces electron-store)
|
||||||
|
|
||||||
|
const { app } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
|
||||||
|
|
||||||
|
const store = {
|
||||||
|
get(key, defaultValue) {
|
||||||
|
try {
|
||||||
|
const data = fs.readFileSync(settingsPath, 'utf-8');
|
||||||
|
const settings = JSON.parse(data);
|
||||||
|
return settings[key] !== undefined ? settings[key] : defaultValue;
|
||||||
|
} catch {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
set(key, value) {
|
||||||
|
let settings = {};
|
||||||
|
try {
|
||||||
|
const data = fs.readFileSync(settingsPath, 'utf-8');
|
||||||
|
settings = JSON.parse(data);
|
||||||
|
} catch {}
|
||||||
|
settings[key] = value;
|
||||||
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = store;
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const MAX_DUMPS = 20;
|
||||||
|
|
||||||
|
class CrashWriter {
|
||||||
|
constructor(dir) {
|
||||||
|
this.dir = dir;
|
||||||
|
this._counter = 0;
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
handleUncaught(err, kind) {
|
||||||
|
try {
|
||||||
|
const filename = `${Date.now()}-${++this._counter}-${kind}.json`;
|
||||||
|
const payload = {
|
||||||
|
kind,
|
||||||
|
message: err && err.message,
|
||||||
|
stack: err && err.stack,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
fs.writeFileSync(path.join(this.dir, filename), JSON.stringify(payload, null, 2));
|
||||||
|
this._prune();
|
||||||
|
} catch (writeErr) {
|
||||||
|
console.error('[crash-writer] dump write failed:', writeErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_prune() {
|
||||||
|
const files = fs.readdirSync(this.dir).sort();
|
||||||
|
while (files.length > MAX_DUMPS) {
|
||||||
|
const oldest = files.shift();
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(path.join(this.dir, oldest));
|
||||||
|
} catch (_unlinkErr) {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
list() {
|
||||||
|
if (!fs.existsSync(this.dir)) return [];
|
||||||
|
return fs
|
||||||
|
.readdirSync(this.dir)
|
||||||
|
.filter((f) => f.endsWith('.json'))
|
||||||
|
.sort()
|
||||||
|
.reverse()
|
||||||
|
.map((filename) => {
|
||||||
|
const full = path.join(this.dir, filename);
|
||||||
|
const data = JSON.parse(fs.readFileSync(full, 'utf-8'));
|
||||||
|
return { filename, ...data };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(filename) {
|
||||||
|
const full = path.join(this.dir, filename);
|
||||||
|
if (fs.existsSync(full)) fs.unlinkSync(full);
|
||||||
|
}
|
||||||
|
|
||||||
|
path() {
|
||||||
|
return this.dir;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { CrashWriter };
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
function feedConfigFor(channel) {
|
||||||
|
if (channel === 'github') {
|
||||||
|
return { provider: 'github', owner: 'amitwh', repo: 'markdown-converter' };
|
||||||
|
}
|
||||||
|
return { provider: 'generic', url: 'https://updates.concreteinfo.co.in/v5' };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { feedConfigFor };
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
class MigrationRunner {
|
||||||
|
constructor({ dir, transform }) {
|
||||||
|
this.dir = dir;
|
||||||
|
this.transform = transform;
|
||||||
|
this.file = path.join(dir, 'settings.json');
|
||||||
|
this.backup = path.join(dir, 'settings.v4.bak.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
run() {
|
||||||
|
if (!fs.existsSync(this.file)) {
|
||||||
|
this._writeDefaults();
|
||||||
|
return 'fresh';
|
||||||
|
}
|
||||||
|
const raw = JSON.parse(fs.readFileSync(this.file, 'utf-8'));
|
||||||
|
if (raw && raw['migration.version'] === 5) {
|
||||||
|
return 'skipped';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const v5 = this.transform(raw);
|
||||||
|
fs.copyFileSync(this.file, this.backup);
|
||||||
|
fs.writeFileSync(this.file, JSON.stringify({ ...v5, 'migration.version': 5 }, null, 2));
|
||||||
|
return 'migrated';
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[migration-runner] transform failed:', err.message);
|
||||||
|
// Back up the original and write v5 marker so future launches skip migration.
|
||||||
|
// Without this, every launch would fail again and the user stays on defaults.
|
||||||
|
fs.copyFileSync(this.file, this.backup);
|
||||||
|
fs.writeFileSync(this.file, JSON.stringify({ ...raw, 'migration.version': 5 }, null, 2));
|
||||||
|
return 'failed';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_writeDefaults() {
|
||||||
|
const v5 = this.transform({});
|
||||||
|
fs.writeFileSync(this.file, JSON.stringify({ ...v5, 'migration.version': 5 }, null, 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { MigrationRunner };
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Mirror of src/renderer/lib/migrations/v4-to-v5.ts, plain JS, for main-process use.
|
||||||
|
// Kept in sync manually; if the renderer transform changes, update this too.
|
||||||
|
const { z } = require('zod');
|
||||||
|
|
||||||
|
const v4SettingsSchema = z
|
||||||
|
.object({
|
||||||
|
theme: z.enum(['light', 'dark', 'auto']).default('auto'),
|
||||||
|
customCss: z.string().optional().nullable(),
|
||||||
|
recentFiles: z.array(z.string()).default([]),
|
||||||
|
editorFontSize: z.number().min(10).max(28).default(14),
|
||||||
|
keyBindings: z.record(z.string(), z.string()).optional(),
|
||||||
|
snippets: z.array(z.unknown()).default([]),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
const v5SettingsSchema = z
|
||||||
|
.object({
|
||||||
|
fontSize: z.number().default(14),
|
||||||
|
tabSize: z.number().default(4),
|
||||||
|
lineNumbers: z.boolean().default(true),
|
||||||
|
wordWrap: z.boolean().default(true),
|
||||||
|
minimap: z.boolean().default(true),
|
||||||
|
theme: z.enum(['light', 'dark', 'system']).default('system'),
|
||||||
|
accentColor: z.string().default('brand'),
|
||||||
|
fontFamily: z.string().default('system'),
|
||||||
|
pdfFormat: z.string().default('a4'),
|
||||||
|
pdfMargins: z.string().default('normal'),
|
||||||
|
pdfEmbedFonts: z.boolean().default(true),
|
||||||
|
docxTemplate: z.string().default('standard'),
|
||||||
|
docxCustomTemplatePath: z.string().nullable().default(null),
|
||||||
|
replOpen: z.boolean().default(false),
|
||||||
|
breadcrumbSymbols: z.boolean().default(true),
|
||||||
|
htmlHighlightStyle: z.string().default('github'),
|
||||||
|
renderTablesAsAscii: z.boolean().default(false),
|
||||||
|
welcomeDismissed: z.boolean().default(false),
|
||||||
|
editorFontSize: z.number().default(14),
|
||||||
|
customCssPath: z.string().nullable().default(null),
|
||||||
|
userBindings: z.record(z.string(), z.string()).default({}),
|
||||||
|
updateChannel: z.enum(['github', 'concreteinfo']).default('github'),
|
||||||
|
autoCheckUpdates: z.boolean().default(true),
|
||||||
|
firstRun: z.boolean().default(true),
|
||||||
|
monospaceFont: z.enum(['jetbrains-mono', 'fira-code']).default('jetbrains-mono'),
|
||||||
|
monospaceLigatures: z.boolean().default(false),
|
||||||
|
appVariant: z.enum(['classic', 'react']).default('react'),
|
||||||
|
'migration.version': z.literal(5).optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
const v5OnlyFields = ['updateChannel', 'autoCheckUpdates', 'firstRun'];
|
||||||
|
const v5ThemeValues = ['light', 'dark', 'system'];
|
||||||
|
|
||||||
|
function isAlreadyV5(data) {
|
||||||
|
if (!data || typeof data !== 'object') return false;
|
||||||
|
if (data['migration.version'] === 5) return true;
|
||||||
|
// Check for v5-only fields — a v4 file would never have these
|
||||||
|
return v5OnlyFields.some((f) => f in data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeAlreadyV5(data) {
|
||||||
|
// Some earlier v5 builds wrote a legacy theme value (e.g. "ayu-light")
|
||||||
|
// under the v5 marker. Trusting the marker blindly broke the renderer's
|
||||||
|
// zod schema on every launch. Always normalize theme against the v5 enum
|
||||||
|
// before returning, so persisted files are always valid v5.
|
||||||
|
const out = { ...data };
|
||||||
|
if (typeof out.theme !== 'string' || !v5ThemeValues.includes(out.theme)) {
|
||||||
|
out.theme = 'system';
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const v5SettingsShape = {
|
||||||
|
fontSize: 14,
|
||||||
|
tabSize: 4,
|
||||||
|
lineNumbers: true,
|
||||||
|
wordWrap: true,
|
||||||
|
minimap: true,
|
||||||
|
theme: 'system',
|
||||||
|
accentColor: 'brand',
|
||||||
|
fontFamily: 'system',
|
||||||
|
pdfFormat: 'a4',
|
||||||
|
pdfMargins: 'normal',
|
||||||
|
pdfEmbedFonts: true,
|
||||||
|
docxTemplate: 'standard',
|
||||||
|
docxCustomTemplatePath: null,
|
||||||
|
replOpen: false,
|
||||||
|
breadcrumbSymbols: true,
|
||||||
|
htmlHighlightStyle: 'github',
|
||||||
|
renderTablesAsAscii: false,
|
||||||
|
welcomeDismissed: false,
|
||||||
|
editorFontSize: 14,
|
||||||
|
customCssPath: null,
|
||||||
|
userBindings: {},
|
||||||
|
updateChannel: 'github',
|
||||||
|
autoCheckUpdates: true,
|
||||||
|
firstRun: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
function migrateV4ToV5(v4) {
|
||||||
|
// If data already looks like v5 (has migration.version=5 or v5-only fields),
|
||||||
|
// normalize and validate against the v5 schema. This handles the case where
|
||||||
|
// a buggy v5 run wrote v5 fields without the marker, AND the case where a
|
||||||
|
// v5 file has a legacy theme value (e.g. "ayu-light") that would otherwise
|
||||||
|
// be rejected by the renderer.
|
||||||
|
if (isAlreadyV5(v4)) {
|
||||||
|
return v5SettingsSchema.parse(normalizeAlreadyV5(v4));
|
||||||
|
}
|
||||||
|
const parsed = v4SettingsSchema.parse(v4 || {});
|
||||||
|
return {
|
||||||
|
...v5SettingsShape,
|
||||||
|
...parsed,
|
||||||
|
theme: parsed.theme === 'auto' ? 'system' : parsed.theme,
|
||||||
|
customCssPath: parsed.customCss ?? null,
|
||||||
|
recentFiles: parsed.recentFiles,
|
||||||
|
editorFontSize: parsed.editorFontSize,
|
||||||
|
userBindings: parsed.keyBindings ?? v5SettingsShape.userBindings,
|
||||||
|
snippets: parsed.snippets,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { migrateV4ToV5, v5SettingsShape };
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
const { EventEmitter } = require('events');
|
||||||
|
const DEBOUNCE_MS = 60_000;
|
||||||
|
|
||||||
|
class UpdaterService extends EventEmitter {
|
||||||
|
constructor(autoUpdater) {
|
||||||
|
super();
|
||||||
|
this.autoUpdater = autoUpdater;
|
||||||
|
this.state = 'idle';
|
||||||
|
this.lastCheckAt = 0;
|
||||||
|
this._wire();
|
||||||
|
}
|
||||||
|
|
||||||
|
_wire() {
|
||||||
|
const au = this.autoUpdater;
|
||||||
|
au.on('checking-for-update', () => this._emit({ state: 'checking' }));
|
||||||
|
au.on('update-available', (info) => this._emit({ state: 'available', version: info.version }));
|
||||||
|
au.on('download-progress', (p) => this._emit({ state: 'downloading', percent: p.percent }));
|
||||||
|
au.on('update-downloaded', (info) => this._emit({ state: 'ready', version: info.version }));
|
||||||
|
au.on('update-not-available', () => this._emit({ state: 'idle' }));
|
||||||
|
au.on('error', (err) => {
|
||||||
|
const code =
|
||||||
|
err && /ENOTFOUND|ETIMEDOUT|ECONNREFUSED/.test(err.message) ? 'NETWORK' : 'UNKNOWN';
|
||||||
|
this._emit({ state: 'error', code });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_emit(payload) {
|
||||||
|
this.state = payload.state;
|
||||||
|
this.emit('status', payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
async check() {
|
||||||
|
if (Date.now() - this.lastCheckAt < DEBOUNCE_MS) return;
|
||||||
|
this.lastCheckAt = Date.now();
|
||||||
|
await this.autoUpdater.checkForUpdates();
|
||||||
|
}
|
||||||
|
|
||||||
|
install() {
|
||||||
|
this.autoUpdater.quitAndInstall();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { UpdaterService };
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
// src/main/utils/paths.js
|
||||||
|
// Path helpers — extracted from src/main.js lines 109-207
|
||||||
|
const { app } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
function getAllowedDirectories() {
|
||||||
|
const dirs = [
|
||||||
|
app.getPath('documents'),
|
||||||
|
app.getPath('desktop'),
|
||||||
|
app.getPath('downloads'),
|
||||||
|
app.getPath('home'),
|
||||||
|
process.cwd(), // Current working directory
|
||||||
|
].filter(Boolean); // Remove any undefined paths
|
||||||
|
return dirs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates that a file path is safe and doesn't attempt path traversal
|
||||||
|
* @param {string} filePath - The path to validate
|
||||||
|
* @returns {{ valid: boolean, resolved: string, error?: string }}
|
||||||
|
*/
|
||||||
|
function validatePath(filePath) {
|
||||||
|
if (!filePath || typeof filePath !== 'string') {
|
||||||
|
return { valid: false, resolved: '', error: 'Invalid path' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve to absolute path (handles .., ., symlinks)
|
||||||
|
let resolved;
|
||||||
|
try {
|
||||||
|
resolved = path.resolve(filePath);
|
||||||
|
} catch (_err) {
|
||||||
|
return { valid: false, resolved: '', error: 'Invalid path format' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize path separators
|
||||||
|
resolved = path.normalize(resolved);
|
||||||
|
|
||||||
|
// Check for null bytes (path injection)
|
||||||
|
if (resolved.includes('\0')) {
|
||||||
|
return { valid: false, resolved: '', error: 'Null byte in path' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if path exists
|
||||||
|
if (!fs.existsSync(resolved)) {
|
||||||
|
return { valid: false, resolved, error: 'Path does not exist' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true, resolved };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a path for operations where the target may not exist yet.
|
||||||
|
* Validates string shape and blocks obviously sensitive locations.
|
||||||
|
* @param {string} filePath
|
||||||
|
* @returns {{ valid: boolean, resolved: string, error?: string }}
|
||||||
|
*/
|
||||||
|
function resolveWritablePath(filePath) {
|
||||||
|
if (!filePath || typeof filePath !== 'string') {
|
||||||
|
return { valid: false, resolved: '', error: 'Invalid path' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let resolved;
|
||||||
|
try {
|
||||||
|
resolved = path.normalize(path.resolve(filePath));
|
||||||
|
} catch (_err2) {
|
||||||
|
return { valid: false, resolved: '', error: 'Invalid path format' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolved.includes('\0')) {
|
||||||
|
return { valid: false, resolved: '', error: 'Null byte in path' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isPathAccessible(resolved)) {
|
||||||
|
return { valid: false, resolved, error: 'Path is not accessible' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true, resolved };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a resolved path is within allowed directories
|
||||||
|
* For an editor app, we allow access to all user-accessible paths
|
||||||
|
* but log any suspicious access attempts
|
||||||
|
* @param {string} resolvedPath - The resolved absolute path
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isPathAccessible(resolvedPath) {
|
||||||
|
// Block access to sensitive system directories
|
||||||
|
const blockedPaths = [
|
||||||
|
'/etc/passwd',
|
||||||
|
'/etc/shadow',
|
||||||
|
'/root',
|
||||||
|
'C:\\Windows\\System32',
|
||||||
|
'C:\\Windows\\System',
|
||||||
|
'/System',
|
||||||
|
'/private/etc',
|
||||||
|
];
|
||||||
|
|
||||||
|
const normalizedPath = resolvedPath.toLowerCase();
|
||||||
|
for (const blocked of blockedPaths) {
|
||||||
|
if (normalizedPath.startsWith(blocked.toLowerCase())) {
|
||||||
|
console.warn('[SECURITY] Blocked access to sensitive path:', resolvedPath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { getAllowedDirectories, validatePath, resolveWritablePath, isPathAccessible };
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
// src/main/window/index.js
|
||||||
|
// Main window creation
|
||||||
|
|
||||||
|
const { app, BrowserWindow } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
const state = require('./state');
|
||||||
|
const menu = require('../menu');
|
||||||
|
|
||||||
|
function createMainWindow() {
|
||||||
|
const bounds = state.load();
|
||||||
|
const isDev = !!process.env.VITE_DEV_SERVER_URL;
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: bounds.width,
|
||||||
|
height: bounds.height,
|
||||||
|
x: bounds.x,
|
||||||
|
y: bounds.y,
|
||||||
|
show: true,
|
||||||
|
title: `Markdown Converter${isDev ? ' — React Dev' : ''}`,
|
||||||
|
webPreferences: {
|
||||||
|
// The preload script exposes `window.electronAPI` — the only IPC
|
||||||
|
// bridge the renderer uses. Without this, every renderer call returns
|
||||||
|
// CHANNEL_MISSING and file/folder/save all silently no-op.
|
||||||
|
preload: path.join(__dirname, '../../preload.js'),
|
||||||
|
// contextIsolation MUST be true for the preload's contextBridge
|
||||||
|
// exposeInMainWorld call to succeed. Without it, the preload throws
|
||||||
|
// on load and the renderer never gets the IPC bridge.
|
||||||
|
contextIsolation: true,
|
||||||
|
nodeIntegration: false,
|
||||||
|
spellcheck: true,
|
||||||
|
},
|
||||||
|
icon: path.join(__dirname, '../../../assets/icon.png'),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dev (Vite): load the running dev server so .tsx is transformed on the fly.
|
||||||
|
// Production (running from dist/ directly): load the built renderer at the
|
||||||
|
// relative path from this file.
|
||||||
|
// Production (packaged installer build): the renderer ships under
|
||||||
|
// process.resourcesPath/renderer (configured via build.extraResources in
|
||||||
|
// package.json) — not inside the asar.
|
||||||
|
// VITE_DEV_SERVER_URL is set by `npm run dev` via cross-env.
|
||||||
|
// app.isPackaged is set by electron-builder for installer builds.
|
||||||
|
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
|
||||||
|
if (!app.isPackaged && devServerUrl) {
|
||||||
|
console.log('[WINDOW] Dev mode — loading', devServerUrl);
|
||||||
|
win.loadURL(devServerUrl);
|
||||||
|
} else {
|
||||||
|
const rendererIndex = app.isPackaged
|
||||||
|
? path.join(process.resourcesPath, 'renderer', 'index.html')
|
||||||
|
: path.join(__dirname, '../../../dist/renderer/index.html');
|
||||||
|
|
||||||
|
if (app.isPackaged) {
|
||||||
|
try {
|
||||||
|
fs.accessSync(rendererIndex);
|
||||||
|
} catch {
|
||||||
|
console.error(
|
||||||
|
'[WINDOW] Renderer not found at',
|
||||||
|
rendererIndex,
|
||||||
|
'— did you run `npm run build:renderer` before packaging?'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[WINDOW] Production mode — loading', rendererIndex);
|
||||||
|
win.loadFile(rendererIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show window only after content is ready — avoids blank flash
|
||||||
|
win.once('ready-to-show', () => {
|
||||||
|
win.show();
|
||||||
|
});
|
||||||
|
|
||||||
|
menu.register(win);
|
||||||
|
|
||||||
|
// Use 'close' (fires before destruction) — 'closed' fires after the
|
||||||
|
// BrowserWindow object is destroyed, so getBounds() would throw.
|
||||||
|
win.on('close', () => {
|
||||||
|
if (!win.isDestroyed()) state.save(win);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Spell check context menu
|
||||||
|
win.webContents.on('context-menu', (event, params) => {
|
||||||
|
const { Menu, MenuItem } = require('electron');
|
||||||
|
const ctxMenu = new Menu();
|
||||||
|
|
||||||
|
// Add spell check suggestions
|
||||||
|
if (params.misspelledWord) {
|
||||||
|
for (const suggestion of params.dictionarySuggestions) {
|
||||||
|
ctxMenu.append(
|
||||||
|
new MenuItem({
|
||||||
|
label: suggestion,
|
||||||
|
click: () => win.webContents.replaceMisspelling(suggestion),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (params.dictionarySuggestions.length > 0) {
|
||||||
|
ctxMenu.append(new MenuItem({ type: 'separator' }));
|
||||||
|
}
|
||||||
|
ctxMenu.append(
|
||||||
|
new MenuItem({
|
||||||
|
label: 'Add to Dictionary',
|
||||||
|
click: () =>
|
||||||
|
win.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
ctxMenu.append(new MenuItem({ type: 'separator' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard context menu items
|
||||||
|
ctxMenu.append(new MenuItem({ role: 'cut' }));
|
||||||
|
ctxMenu.append(new MenuItem({ role: 'copy' }));
|
||||||
|
ctxMenu.append(new MenuItem({ role: 'paste' }));
|
||||||
|
ctxMenu.append(new MenuItem({ role: 'selectAll' }));
|
||||||
|
|
||||||
|
ctxMenu.popup();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for the page to fully load before sending file data
|
||||||
|
win.webContents.on('did-finish-load', () => {
|
||||||
|
console.log('Window finished loading');
|
||||||
|
// Don't open file here - wait for renderer-ready signal
|
||||||
|
// The renderer will send renderer-ready when TabManager is initialized
|
||||||
|
});
|
||||||
|
|
||||||
|
return win;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createMainWindow };
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// src/main/window/state.js
|
||||||
|
// Window state persistence (size, position)
|
||||||
|
|
||||||
|
const { app } = require('electron');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
const stateFile = path.join(app.getPath('userData'), 'window-state.json');
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
try {
|
||||||
|
return JSON.parse(fs.readFileSync(stateFile, 'utf8'));
|
||||||
|
} catch {
|
||||||
|
return { width: 1200, height: 800 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function save(win) {
|
||||||
|
const bounds = win.getBounds();
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(stateFile, JSON.stringify(bounds));
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { load, save };
|
||||||
@@ -0,0 +1,807 @@
|
|||||||
|
/**
|
||||||
|
* Word Template Exporter
|
||||||
|
* Loads word_template.docx, preserves first 2 pages (cover + TOC),
|
||||||
|
* and adds markdown content starting from page 3 using template styles
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const PizZip = require('pizzip');
|
||||||
|
|
||||||
|
class WordTemplateExporter {
|
||||||
|
constructor(templatePath, startPage = 3, pageSettings = null) {
|
||||||
|
this.templatePath = templatePath || path.join(__dirname, '../word_template.docx');
|
||||||
|
this.startPage = startPage; // Which page to start inserting content
|
||||||
|
this.pageSettings = pageSettings; // Page size and orientation settings
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert markdown to Word document using template
|
||||||
|
*/
|
||||||
|
async convert(markdownContent, outputPath) {
|
||||||
|
try {
|
||||||
|
// Load template
|
||||||
|
const templateBuffer = fs.readFileSync(this.templatePath);
|
||||||
|
const zip = new PizZip(templateBuffer);
|
||||||
|
|
||||||
|
// Extract document.xml
|
||||||
|
let documentXml = zip.file('word/document.xml').asText();
|
||||||
|
|
||||||
|
// Set page size if settings provided
|
||||||
|
if (this.pageSettings) {
|
||||||
|
documentXml = this.setPageSize(documentXml);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse markdown and generate Word XML
|
||||||
|
const newContentXml = this.markdownToWordXml(markdownContent);
|
||||||
|
|
||||||
|
// Insert new content after the specified start page
|
||||||
|
const modifiedXml = this.insertContentAfterPage(documentXml, newContentXml, this.startPage);
|
||||||
|
|
||||||
|
// Update the zip with modified XML
|
||||||
|
zip.file('word/document.xml', modifiedXml);
|
||||||
|
|
||||||
|
// Generate and save the new document
|
||||||
|
const newDocBuffer = zip.generate({ type: 'nodebuffer' });
|
||||||
|
fs.writeFileSync(outputPath, newDocBuffer);
|
||||||
|
|
||||||
|
return outputPath;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in Word export:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set page size in document XML
|
||||||
|
*/
|
||||||
|
setPageSize(documentXml) {
|
||||||
|
// Import PAGE_SIZES from main process (need to pass as parameter)
|
||||||
|
const PAGE_SIZES = {
|
||||||
|
a4: { width: 11906, height: 16838 },
|
||||||
|
a3: { width: 16838, height: 23811 },
|
||||||
|
a5: { width: 8391, height: 11906 },
|
||||||
|
b4: { width: 14170, height: 20015 },
|
||||||
|
b5: { width: 9979, height: 14170 },
|
||||||
|
letter: { width: 12240, height: 15840 },
|
||||||
|
legal: { width: 12240, height: 20160 },
|
||||||
|
tabloid: { width: 15840, height: 24480 },
|
||||||
|
};
|
||||||
|
|
||||||
|
let width, height;
|
||||||
|
const pageSize = PAGE_SIZES[this.pageSettings.size];
|
||||||
|
|
||||||
|
if (pageSize) {
|
||||||
|
width = pageSize.width;
|
||||||
|
height = pageSize.height;
|
||||||
|
} else {
|
||||||
|
// Default to A4
|
||||||
|
width = 11906;
|
||||||
|
height = 16838;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Swap dimensions for landscape
|
||||||
|
if (this.pageSettings.orientation === 'landscape') {
|
||||||
|
[width, height] = [height, width];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update all <w:pgSz> elements in section properties
|
||||||
|
const pgSzRegex = /<w:pgSz[^>]*\/>/g;
|
||||||
|
let modifiedXml = documentXml.replace(pgSzRegex, () => {
|
||||||
|
return `<w:pgSz w:w="${width}" w:h="${height}" w:orient="${this.pageSettings.orientation}"/>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// If no pgSz found, add it to all sectPr elements
|
||||||
|
if (!pgSzRegex.test(documentXml)) {
|
||||||
|
const sectPrRegex = /<w:sectPr[^>]*>/g;
|
||||||
|
modifiedXml = modifiedXml.replace(sectPrRegex, (match) => {
|
||||||
|
return `${match}<w:pgSz w:w="${width}" w:h="${height}" w:orient="${this.pageSettings.orientation}"/>`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return modifiedXml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert markdown content after the specified page in the document
|
||||||
|
* @param {string} documentXml - The document XML
|
||||||
|
* @param {string} newContentXml - The new content to insert
|
||||||
|
* @param {number} afterPage - Insert content after this page number (1-based)
|
||||||
|
*/
|
||||||
|
insertContentAfterPage(documentXml, newContentXml, afterPage) {
|
||||||
|
// Find section breaks that mark page boundaries
|
||||||
|
// Look for the section properties tag that marks page breaks
|
||||||
|
const sectionBreakRegex = /<w:sectPr[^>]*>[\s\S]*?<\/w:sectPr>/g;
|
||||||
|
const matches = [...documentXml.matchAll(sectionBreakRegex)];
|
||||||
|
|
||||||
|
// Calculate which section break to insert after
|
||||||
|
// Page 1 = before 1st section break
|
||||||
|
// Page 2 = after 1st section break
|
||||||
|
// Page 3 = after 2nd section break, etc.
|
||||||
|
const sectionIndex = afterPage - 1;
|
||||||
|
|
||||||
|
if (matches.length >= sectionIndex && sectionIndex > 0) {
|
||||||
|
// Insert after the specified section break
|
||||||
|
const insertPoint = matches[sectionIndex - 1].index + matches[sectionIndex - 1][0].length;
|
||||||
|
return documentXml.slice(0, insertPoint) + newContentXml + documentXml.slice(insertPoint);
|
||||||
|
} else if (afterPage === 1 || matches.length === 0) {
|
||||||
|
// Insert at the beginning (after <w:body>) or if no section breaks found
|
||||||
|
const bodyStart = documentXml.indexOf('<w:body>') + 8;
|
||||||
|
return documentXml.slice(0, bodyStart) + newContentXml + documentXml.slice(bodyStart);
|
||||||
|
} else {
|
||||||
|
// If not enough section breaks, insert before closing body tag
|
||||||
|
return documentXml.replace('</w:body>', newContentXml + '</w:body>');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert markdown to Word XML format
|
||||||
|
*/
|
||||||
|
markdownToWordXml(markdown) {
|
||||||
|
const lines = markdown.split('\n');
|
||||||
|
let xml = '';
|
||||||
|
let inCodeBlock = false;
|
||||||
|
let codeLines = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
|
||||||
|
// Handle code blocks
|
||||||
|
if (line.trim().startsWith('```')) {
|
||||||
|
if (inCodeBlock) {
|
||||||
|
// End code block
|
||||||
|
xml += this.createCodeBlockXml(codeLines.join('\n'));
|
||||||
|
codeLines = [];
|
||||||
|
inCodeBlock = false;
|
||||||
|
} else {
|
||||||
|
inCodeBlock = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inCodeBlock) {
|
||||||
|
codeLines.push(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty lines
|
||||||
|
if (!line.trim()) {
|
||||||
|
xml += '<w:p><w:pPr></w:pPr></w:p>';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tables - detect table lines
|
||||||
|
if (line.includes('|') && line.trim().startsWith('|')) {
|
||||||
|
const tableLines = [line];
|
||||||
|
i++;
|
||||||
|
// Collect all consecutive table lines
|
||||||
|
while (i < lines.length && lines[i].includes('|')) {
|
||||||
|
tableLines.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
i--; // Back up one line
|
||||||
|
xml += this.createTableXml(tableLines);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ASCII flowcharts/diagrams - detect box drawing characters
|
||||||
|
if (this.isAsciiArt(line)) {
|
||||||
|
const asciiLines = [line];
|
||||||
|
i++;
|
||||||
|
// Collect all consecutive ASCII art lines
|
||||||
|
while (i < lines.length && (this.isAsciiArt(lines[i]) || !lines[i].trim())) {
|
||||||
|
asciiLines.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
if (i < lines.length && lines[i].trim() && !this.isAsciiArt(lines[i])) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i--; // Back up one line
|
||||||
|
xml += this.createAsciiArtXml(asciiLines.join('\n'));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Headings - strip markdown numbering
|
||||||
|
if (line.trim().startsWith('#')) {
|
||||||
|
const level = (line.match(/^#+/) || [''])[0].length;
|
||||||
|
let text = line.replace(/^#+\s*/, '').trim();
|
||||||
|
// Remove markdown numbering like "1.1 Title" -> "Title"
|
||||||
|
text = text.replace(/^\d+(\.\d+)*\.?\s+/, '');
|
||||||
|
xml += this.createHeadingXml(text, level);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blockquotes
|
||||||
|
if (line.trim().startsWith('>')) {
|
||||||
|
const text = line.replace(/^>\s*/, '').trim();
|
||||||
|
xml += this.createQuoteXml(text);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordered lists - strip markdown numbering, use template numbering
|
||||||
|
if (/^\s*\d+\.\s+/.test(line)) {
|
||||||
|
const text = line.replace(/^\s*\d+\.\s+/, '');
|
||||||
|
xml += this.createListItemXml(text, true);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unordered lists
|
||||||
|
if (/^\s*[-*+]\s+/.test(line)) {
|
||||||
|
const text = line.replace(/^\s*[-*+]\s+/, '');
|
||||||
|
xml += this.createListItemXml(text, false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Horizontal rule
|
||||||
|
if (/^[-*_]{3,}$/.test(line.trim())) {
|
||||||
|
xml += this.createHorizontalRuleXml();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal paragraph
|
||||||
|
xml += this.createParagraphXml(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create heading XML using template styles
|
||||||
|
*/
|
||||||
|
createHeadingXml(text, level) {
|
||||||
|
const styleName = `Heading${level}`;
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="${styleName}"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create paragraph XML with Normal style
|
||||||
|
*/
|
||||||
|
createParagraphXml(text) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Normal"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create quote XML
|
||||||
|
*/
|
||||||
|
createQuoteXml(text) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Quote"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create list item XML using template numbering
|
||||||
|
*/
|
||||||
|
createListItemXml(text, numbered) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
const numId = numbered ? '1' : '2'; // Template numbering IDs
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="${numbered ? 'ListNumber' : 'ListBullet'}"/>
|
||||||
|
<w:numPr>
|
||||||
|
<w:ilvl w:val="0"/>
|
||||||
|
<w:numId w:val="${numId}"/>
|
||||||
|
</w:numPr>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create code block XML - renders each line as separate paragraph
|
||||||
|
* to preserve exact formatting like in preview (monospace, no wrapping)
|
||||||
|
* Background shading applied at paragraph level to extend full width
|
||||||
|
*/
|
||||||
|
createCodeBlockXml(code) {
|
||||||
|
const lines = code.split('\n');
|
||||||
|
let xml = '';
|
||||||
|
|
||||||
|
lines.forEach((line, index) => {
|
||||||
|
const escapedLine = this.escapeXml(line);
|
||||||
|
|
||||||
|
// Each line gets its own paragraph with exact spacing and no wrapping
|
||||||
|
// Shading (shd) is at paragraph level so background extends full width
|
||||||
|
xml += `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Normal"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:spacing w:before="${index === 0 ? '120' : '0'}" w:after="${index === lines.length - 1 ? '120' : '0'}" w:line="240" w:lineRule="exact"/>
|
||||||
|
<w:ind w:left="284" w:right="284"/>
|
||||||
|
<w:jc w:val="left"/>
|
||||||
|
<w:keepLines/>
|
||||||
|
<w:wordWrap w:val="0"/>
|
||||||
|
</w:pPr>
|
||||||
|
<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="18"/>
|
||||||
|
<w:szCs w:val="18"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedLine}</w:t>
|
||||||
|
</w:r>
|
||||||
|
</w:p>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create horizontal rule XML
|
||||||
|
*/
|
||||||
|
createHorizontalRuleXml() {
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pBdr>
|
||||||
|
<w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/>
|
||||||
|
</w:pBdr>
|
||||||
|
</w:pPr>
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create table XML from markdown table lines with template styling
|
||||||
|
* Uses full-width tables with equal column distribution matching template style
|
||||||
|
*/
|
||||||
|
createTableXml(tableLines) {
|
||||||
|
// Parse table
|
||||||
|
const rows = [];
|
||||||
|
for (const line of tableLines) {
|
||||||
|
// Skip separator lines (e.g., |---|---|)
|
||||||
|
if (/^\s*\|[\s\-:]+\|\s*$/.test(line)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Split by | and trim
|
||||||
|
const cells = line
|
||||||
|
.split('|')
|
||||||
|
.filter((cell) => cell.trim())
|
||||||
|
.map((cell) => cell.trim());
|
||||||
|
if (cells.length > 0) {
|
||||||
|
rows.push(cells);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rows.length === 0) return '';
|
||||||
|
|
||||||
|
// Calculate number of columns
|
||||||
|
const numCols = Math.max(...rows.map((row) => row.length));
|
||||||
|
|
||||||
|
// Calculate column width in twips (1440 twips = 1 inch)
|
||||||
|
// Assume standard page width of 9360 twips (6.5 inches usable)
|
||||||
|
const totalTableWidth = 9360;
|
||||||
|
const colWidth = Math.floor(totalTableWidth / numCols);
|
||||||
|
|
||||||
|
// Build table XML
|
||||||
|
let tableXml = '<w:tbl>';
|
||||||
|
|
||||||
|
// Table properties - use template table style with full width
|
||||||
|
tableXml += `<w:tblPr>
|
||||||
|
<w:tblStyle w:val="TableGrid"/>
|
||||||
|
<w:tblW w:w="0" w:type="auto"/>
|
||||||
|
<w:tblLayout w:type="fixed"/>
|
||||||
|
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
|
||||||
|
<w:tblBorders>
|
||||||
|
<w:top w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:left w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:bottom w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:right w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:insideH w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:insideV w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
</w:tblBorders>
|
||||||
|
</w:tblPr>`;
|
||||||
|
|
||||||
|
// Table grid with explicit column widths
|
||||||
|
tableXml += '<w:tblGrid>';
|
||||||
|
for (let i = 0; i < numCols; i++) {
|
||||||
|
tableXml += `<w:gridCol w:w="${colWidth}"/>`;
|
||||||
|
}
|
||||||
|
tableXml += '</w:tblGrid>';
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
rows.forEach((rowCells, rowIndex) => {
|
||||||
|
const isHeader = rowIndex === 0;
|
||||||
|
|
||||||
|
tableXml += '<w:tr>';
|
||||||
|
|
||||||
|
// Row properties for consistent height
|
||||||
|
tableXml += '<w:trPr><w:trHeight w:val="0" w:hRule="atLeast"/></w:trPr>';
|
||||||
|
|
||||||
|
// Pad row to have same number of columns
|
||||||
|
while (rowCells.length < numCols) {
|
||||||
|
rowCells.push('');
|
||||||
|
}
|
||||||
|
|
||||||
|
rowCells.forEach((cellText, _colIndex) => {
|
||||||
|
tableXml += '<w:tc>';
|
||||||
|
tableXml += '<w:tcPr>';
|
||||||
|
|
||||||
|
// Cell width
|
||||||
|
tableXml += `<w:tcW w:w="${colWidth}" w:type="dxa"/>`;
|
||||||
|
|
||||||
|
// Cell shading - orange for header, white for data rows
|
||||||
|
if (isHeader) {
|
||||||
|
tableXml += '<w:shd w:val="clear" w:color="auto" w:fill="F58220"/>';
|
||||||
|
} else {
|
||||||
|
tableXml += '<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cell borders
|
||||||
|
tableXml +=
|
||||||
|
'<w:tcBorders>' +
|
||||||
|
'<w:top w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:left w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:bottom w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:right w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'</w:tcBorders>';
|
||||||
|
|
||||||
|
// Cell margins for proper padding
|
||||||
|
tableXml +=
|
||||||
|
'<w:tcMar>' +
|
||||||
|
'<w:top w:w="80" w:type="dxa"/>' +
|
||||||
|
'<w:left w:w="120" w:type="dxa"/>' +
|
||||||
|
'<w:bottom w:w="80" w:type="dxa"/>' +
|
||||||
|
'<w:right w:w="120" w:type="dxa"/>' +
|
||||||
|
'</w:tcMar>';
|
||||||
|
|
||||||
|
tableXml += '</w:tcPr>';
|
||||||
|
|
||||||
|
// Cell content
|
||||||
|
tableXml += '<w:p>';
|
||||||
|
tableXml += '<w:pPr>';
|
||||||
|
tableXml += '<w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/>';
|
||||||
|
tableXml += '</w:pPr>';
|
||||||
|
|
||||||
|
const runs = this.parseInlineFormatting(cellText);
|
||||||
|
|
||||||
|
if (isHeader) {
|
||||||
|
// Header: bold white text
|
||||||
|
tableXml += runs.replace(/<w:rPr>/g, '<w:rPr><w:b/><w:color w:val="FFFFFF"/>');
|
||||||
|
} else {
|
||||||
|
// Data rows: normal black text
|
||||||
|
tableXml += runs;
|
||||||
|
}
|
||||||
|
|
||||||
|
tableXml += '</w:p>';
|
||||||
|
tableXml += '</w:tc>';
|
||||||
|
});
|
||||||
|
|
||||||
|
tableXml += '</w:tr>';
|
||||||
|
});
|
||||||
|
|
||||||
|
tableXml += '</w:tbl>';
|
||||||
|
|
||||||
|
// Add spacing after table
|
||||||
|
tableXml += '<w:p><w:pPr><w:spacing w:before="120" w:after="0"/></w:pPr></w:p>';
|
||||||
|
|
||||||
|
return tableXml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect if line contains ASCII art/flowchart characters
|
||||||
|
*/
|
||||||
|
isAsciiArt(line) {
|
||||||
|
// Don't treat markdown tables as ASCII art
|
||||||
|
if (line.trim().startsWith('|') && line.trim().endsWith('|')) {
|
||||||
|
// Check if it's a proper markdown table (has multiple cells)
|
||||||
|
const cells = line.split('|').filter((c) => c.trim());
|
||||||
|
if (cells.length >= 2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common ASCII art characters (Unicode box drawing and symbols)
|
||||||
|
const asciiArtChars = [
|
||||||
|
'─',
|
||||||
|
'│',
|
||||||
|
'┌',
|
||||||
|
'┐',
|
||||||
|
'└',
|
||||||
|
'┘',
|
||||||
|
'├',
|
||||||
|
'┤',
|
||||||
|
'┬',
|
||||||
|
'┴',
|
||||||
|
'┼', // Box drawing
|
||||||
|
'═',
|
||||||
|
'║',
|
||||||
|
'╔',
|
||||||
|
'╗',
|
||||||
|
'╚',
|
||||||
|
'╝',
|
||||||
|
'╠',
|
||||||
|
'╣',
|
||||||
|
'╦',
|
||||||
|
'╩',
|
||||||
|
'╬', // Double box
|
||||||
|
'╭',
|
||||||
|
'╮',
|
||||||
|
'╯',
|
||||||
|
'╰', // Rounded corners
|
||||||
|
'▲',
|
||||||
|
'▼',
|
||||||
|
'◄',
|
||||||
|
'►',
|
||||||
|
'♦',
|
||||||
|
'●',
|
||||||
|
'○',
|
||||||
|
'■',
|
||||||
|
'□',
|
||||||
|
'◆',
|
||||||
|
'◇', // Shapes
|
||||||
|
'↓',
|
||||||
|
'→',
|
||||||
|
'←',
|
||||||
|
'↑',
|
||||||
|
'↔',
|
||||||
|
'↕',
|
||||||
|
'⇒',
|
||||||
|
'⇐',
|
||||||
|
'⇓',
|
||||||
|
'⇑', // Arrows
|
||||||
|
'┃',
|
||||||
|
'━',
|
||||||
|
'┏',
|
||||||
|
'┓',
|
||||||
|
'┗',
|
||||||
|
'┛',
|
||||||
|
'┣',
|
||||||
|
'┫',
|
||||||
|
'┳',
|
||||||
|
'┻',
|
||||||
|
'╋', // Heavy box
|
||||||
|
'░',
|
||||||
|
'▒',
|
||||||
|
'▓',
|
||||||
|
'█', // Shading
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check for box drawing characters
|
||||||
|
if (asciiArtChars.some((char) => line.includes(char))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for ASCII box patterns with regular characters
|
||||||
|
const asciiPatterns = [
|
||||||
|
/^\s*\+[-=_+]+\+/, // +-----+ or +=====+
|
||||||
|
/^\s*\|[-=_]{3,}\|/, // |-----|
|
||||||
|
/^\s*[-=_]{5,}$/, // -----
|
||||||
|
/^\s*\+[-]+\+[-]+\+/, // +---+---+
|
||||||
|
/^\s*\([A-Z][a-z]+\)\s*\|\|/, // (Deformable) ||
|
||||||
|
/^\s*\|\s+[A-Z\s]+[-:]\s+[A-Z]/, // | TILE ADHESIVE - TYPE
|
||||||
|
/^\s*\|\s*\[[^\]]+\]/, // | [BIS Mark / CE Mark]
|
||||||
|
/^\s*\|\s{2,}\w+.*\|\|/, // || text ||
|
||||||
|
/^\s*\[[^\]]+\]\s*$/, // [Step in brackets]
|
||||||
|
/^\s*<[-=]+>/, // <----> or <====>
|
||||||
|
/^\s*\/[-_\\\/]+\//, // /----/
|
||||||
|
/^\s*\*[-=\*]+\*/, // *----*
|
||||||
|
];
|
||||||
|
|
||||||
|
return asciiPatterns.some((pattern) => pattern.test(line));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create ASCII art XML with monospace font
|
||||||
|
* Background shading applied at paragraph level to extend full width
|
||||||
|
*/
|
||||||
|
createAsciiArtXml(asciiContent) {
|
||||||
|
// Split ASCII art into individual lines and create a paragraph for each
|
||||||
|
const lines = asciiContent.split('\n');
|
||||||
|
let xml = '';
|
||||||
|
|
||||||
|
lines.forEach((line, index) => {
|
||||||
|
// Shading (shd) is at paragraph level so background extends full width
|
||||||
|
xml += `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Normal"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:spacing w:before="${index === 0 ? '120' : '0'}" w:after="${index === lines.length - 1 ? '120' : '0'}" w:line="240" w:lineRule="exact"/>
|
||||||
|
<w:ind w:left="284" w:right="284"/>
|
||||||
|
<w:jc w:val="left"/>
|
||||||
|
<w:keepLines/>
|
||||||
|
<w:wordWrap w:val="0"/>
|
||||||
|
</w:pPr>`;
|
||||||
|
|
||||||
|
// Check if line contains arrow characters and color them red
|
||||||
|
const arrowChars = ['↓', '→', '←', '↑', '▼', '►', '◄', '▲'];
|
||||||
|
const hasArrow = arrowChars.some((arrow) => line.includes(arrow));
|
||||||
|
|
||||||
|
if (hasArrow) {
|
||||||
|
// Split line into parts and color arrows red
|
||||||
|
let remainingLine = line;
|
||||||
|
|
||||||
|
while (remainingLine.length > 0) {
|
||||||
|
let foundArrow = false;
|
||||||
|
let arrowIndex = -1;
|
||||||
|
let foundArrowChar = '';
|
||||||
|
|
||||||
|
// Find the first arrow in the remaining text
|
||||||
|
for (const arrow of arrowChars) {
|
||||||
|
const idx = remainingLine.indexOf(arrow);
|
||||||
|
if (idx !== -1 && (arrowIndex === -1 || idx < arrowIndex)) {
|
||||||
|
arrowIndex = idx;
|
||||||
|
foundArrowChar = arrow;
|
||||||
|
foundArrow = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foundArrow) {
|
||||||
|
// Add text before arrow (if any)
|
||||||
|
if (arrowIndex > 0) {
|
||||||
|
const beforeArrow = this.escapeXml(remainingLine.substring(0, arrowIndex));
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${beforeArrow}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add arrow in red
|
||||||
|
const escapedArrow = this.escapeXml(foundArrowChar);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:color w:val="FF0000"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedArrow}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
|
||||||
|
// Continue with remaining text
|
||||||
|
remainingLine = remainingLine.substring(arrowIndex + foundArrowChar.length);
|
||||||
|
} else {
|
||||||
|
// No more arrows, add remaining text
|
||||||
|
const escapedRemaining = this.escapeXml(remainingLine);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedRemaining}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
remainingLine = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No arrows, just add the line normally
|
||||||
|
const escapedLine = this.escapeXml(line);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedLine}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
xml += `</w:p>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse inline formatting (bold, italic, code)
|
||||||
|
*/
|
||||||
|
parseInlineFormatting(text) {
|
||||||
|
let xml = '';
|
||||||
|
const _pos = 0;
|
||||||
|
|
||||||
|
// Patterns for inline formatting
|
||||||
|
const patterns = [
|
||||||
|
{ regex: /\*\*\*(.+?)\*\*\*/g, bold: true, italic: true },
|
||||||
|
{ regex: /\*\*(.+?)\*\*/g, bold: true },
|
||||||
|
{ regex: /\*(.+?)\*/g, italic: true },
|
||||||
|
{ regex: /`(.+?)`/g, code: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Simple approach: process text sequentially
|
||||||
|
let remaining = text;
|
||||||
|
|
||||||
|
while (remaining.length > 0) {
|
||||||
|
let foundMatch = false;
|
||||||
|
let earliestPos = remaining.length;
|
||||||
|
let matchedPattern = null;
|
||||||
|
let match = null;
|
||||||
|
|
||||||
|
// Find earliest match
|
||||||
|
for (const pattern of patterns) {
|
||||||
|
pattern.regex.lastIndex = 0;
|
||||||
|
const m = pattern.regex.exec(remaining);
|
||||||
|
if (m && m.index < earliestPos) {
|
||||||
|
earliestPos = m.index;
|
||||||
|
matchedPattern = pattern;
|
||||||
|
match = m;
|
||||||
|
foundMatch = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foundMatch) {
|
||||||
|
// Add text before match
|
||||||
|
if (earliestPos > 0) {
|
||||||
|
xml += this.createRunXml(remaining.substring(0, earliestPos));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add formatted text
|
||||||
|
xml += this.createRunXml(
|
||||||
|
match[1],
|
||||||
|
matchedPattern.bold,
|
||||||
|
matchedPattern.italic,
|
||||||
|
matchedPattern.code
|
||||||
|
);
|
||||||
|
|
||||||
|
remaining = remaining.substring(earliestPos + match[0].length);
|
||||||
|
} else {
|
||||||
|
// No more matches, add remaining text
|
||||||
|
xml += this.createRunXml(remaining);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a run (text segment) XML
|
||||||
|
*/
|
||||||
|
createRunXml(text, bold = false, italic = false, code = false) {
|
||||||
|
if (!text) return '';
|
||||||
|
|
||||||
|
const escapedText = this.escapeXml(text);
|
||||||
|
let propsXml = '<w:rPr>';
|
||||||
|
|
||||||
|
if (bold) propsXml += '<w:b/>';
|
||||||
|
if (italic) propsXml += '<w:i/>';
|
||||||
|
if (code) {
|
||||||
|
propsXml += '<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/>';
|
||||||
|
propsXml += '<w:sz w:val="20"/>';
|
||||||
|
}
|
||||||
|
|
||||||
|
propsXml += '</w:rPr>';
|
||||||
|
|
||||||
|
return `<w:r>${propsXml}<w:t xml:space="preserve">${escapedText}</w:t></w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape XML special characters
|
||||||
|
*/
|
||||||
|
escapeXml(text) {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = WordTemplateExporter;
|
||||||
@@ -5,9 +5,7 @@
|
|||||||
"description": "Demonstrates the plugin system. Safe to delete.",
|
"description": "Demonstrates the plugin system. Safe to delete.",
|
||||||
"icon": "puzzle",
|
"icon": "puzzle",
|
||||||
"extensionPoints": {
|
"extensionPoints": {
|
||||||
"commands": [
|
"commands": [{ "id": "hello", "label": "Sample: Hello World", "shortcut": "" }]
|
||||||
{ "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,14 +17,14 @@ 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);
|
||||||
@@ -34,59 +34,89 @@ class WritingStudioPlugin extends PluginAPI {
|
|||||||
_registerCommands(context) {
|
_registerCommands(context) {
|
||||||
const { sprintEngine, snapshotManager, goalTracker } = this;
|
const { sprintEngine, snapshotManager, goalTracker } = this;
|
||||||
|
|
||||||
context.commands.register('start-sprint', 'Studio: Start Sprint', () => {
|
context.commands.register(
|
||||||
const duration = context.settings.get('sprintDuration') || 25;
|
'start-sprint',
|
||||||
const content = context.editor.getContent() || '';
|
'Studio: Start Sprint',
|
||||||
const words = content.split(/\s+/).filter(Boolean).length;
|
() => {
|
||||||
sprintEngine.start(duration, words);
|
const duration = context.settings.get('sprintDuration') || 25;
|
||||||
}, 'Ctrl+Alt+S');
|
const content = context.editor.getContent() || '';
|
||||||
|
const words = content.split(/\s+/).filter(Boolean).length;
|
||||||
|
sprintEngine.start(duration, words);
|
||||||
|
},
|
||||||
|
'Ctrl+Alt+S'
|
||||||
|
);
|
||||||
|
|
||||||
context.commands.register('stop-sprint', 'Studio: Stop Sprint', () => {
|
context.commands.register(
|
||||||
if (!sprintEngine.isActive()) return;
|
'stop-sprint',
|
||||||
const content = context.editor.getContent() || '';
|
'Studio: Stop Sprint',
|
||||||
const words = content.split(/\s+/).filter(Boolean).length;
|
() => {
|
||||||
const result = sprintEngine.stop(words);
|
if (!sprintEngine.isActive()) return;
|
||||||
goalTracker.addWords(result.wordDelta);
|
const content = context.editor.getContent() || '';
|
||||||
context.events.emit('sprint:stopped', result);
|
const words = content.split(/\s+/).filter(Boolean).length;
|
||||||
}, 'Ctrl+Alt+Shift+S');
|
const result = sprintEngine.stop(words);
|
||||||
|
goalTracker.addWords(result.wordDelta);
|
||||||
|
context.events.emit('sprint:stopped', result);
|
||||||
|
},
|
||||||
|
'Ctrl+Alt+Shift+S'
|
||||||
|
);
|
||||||
|
|
||||||
context.commands.register('take-snapshot', 'Studio: Take Snapshot', () => {
|
context.commands.register(
|
||||||
const content = context.editor.getContent() || '';
|
'take-snapshot',
|
||||||
snapshotManager.create(content, 'manual');
|
'Studio: Take Snapshot',
|
||||||
context.events.emit('snapshot:created', {});
|
() => {
|
||||||
}, 'Ctrl+Alt+N');
|
const content = context.editor.getContent() || '';
|
||||||
|
snapshotManager.create(content, 'manual');
|
||||||
|
context.events.emit('snapshot:created', {});
|
||||||
|
},
|
||||||
|
'Ctrl+Alt+N'
|
||||||
|
);
|
||||||
|
|
||||||
context.commands.register('restore-last-snapshot', 'Studio: Restore Last Snapshot', () => {
|
context.commands.register(
|
||||||
const snaps = snapshotManager.list();
|
'restore-last-snapshot',
|
||||||
if (snaps.length === 0) return;
|
'Studio: Restore Last Snapshot',
|
||||||
const content = snapshotManager.restore(snaps[0].id);
|
() => {
|
||||||
context.editor.insertAtCursor(content);
|
const snaps = snapshotManager.list();
|
||||||
}, 'Ctrl+Alt+Z');
|
if (snaps.length === 0) return;
|
||||||
|
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('compile-manuscript', 'Studio: Compile Manuscript', () => {
|
context.commands.register(
|
||||||
context.events.emit('studio:compile', {});
|
'compile-manuscript',
|
||||||
}, 'Ctrl+Alt+E');
|
'Studio: Compile Manuscript',
|
||||||
|
() => {
|
||||||
|
context.events.emit('studio:compile', {});
|
||||||
|
},
|
||||||
|
'Ctrl+Alt+E'
|
||||||
|
);
|
||||||
|
|
||||||
context.commands.register('proofread-document', 'Studio: Proofread Document', () => {
|
context.commands.register(
|
||||||
if (context.events.hasHandler('ai:analyze')) {
|
'proofread-document',
|
||||||
const content = context.editor.getContent() || '';
|
'Studio: Proofread Document',
|
||||||
context.events.emit('ai:analyze', { text: content, type: 'grammar' });
|
() => {
|
||||||
}
|
if (context.events.hasHandler('ai:analyze')) {
|
||||||
}, 'Ctrl+Alt+G');
|
const content = context.editor.getContent() || '';
|
||||||
|
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',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,17 +15,34 @@
|
|||||||
{ "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": "proofread-document", "label": "Studio: Proofread Document", "shortcut": "Ctrl+Alt+G" }
|
"id": "compile-manuscript",
|
||||||
|
"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"] }
|
||||||
},
|
},
|
||||||
"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,7 +29,8 @@ 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 = progress.written.toLocaleString() + ' / ' + dailyGoal.toLocaleString() + ' words';
|
label.textContent =
|
||||||
|
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 + '%';
|
||||||
@@ -81,7 +82,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,7 +69,8 @@ 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 = stats.totalWords.toLocaleString() + ' / ' + stats.targetWords.toLocaleString() + ' words';
|
label.textContent =
|
||||||
|
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,7 +80,10 @@ 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 [action, label] of [['accept', 'Accept'], ['dismiss', 'Dismiss']]) {
|
for (const [_action, label] of [
|
||||||
|
['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,7 +45,11 @@ 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 [['restore', 'Restore', ''], ['diff', 'Diff', ''], ['delete', 'Delete', 'ws-btn-danger']]) {
|
for (const [action, text, cls] of [
|
||||||
|
['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,8 +59,12 @@ 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) { if (!oldSet.has(line)) added++; }
|
for (const line of newLines) {
|
||||||
for (const line of oldLines) { if (!newSet.has(line)) removed++; }
|
if (!oldSet.has(line)) added++;
|
||||||
|
}
|
||||||
|
for (const line of oldLines) {
|
||||||
|
if (!newSet.has(line)) removed++;
|
||||||
|
}
|
||||||
return { added, removed };
|
return { added, removed };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ class SprintEngine {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isActive() { return this._active; }
|
isActive() {
|
||||||
|
return this._active;
|
||||||
|
}
|
||||||
|
|
||||||
getRemaining() {
|
getRemaining() {
|
||||||
if (!this._active) return 0;
|
if (!this._active) return 0;
|
||||||
|
|||||||
@@ -12,10 +12,11 @@ class PluginContext {
|
|||||||
* @param {object} deps.exportHooks - { preHooks: [], postHooks: [] }
|
* @param {object} deps.exportHooks - { preHooks: [], postHooks: [] }
|
||||||
*/
|
*/
|
||||||
constructor(deps) {
|
constructor(deps) {
|
||||||
const { pluginId, sidebar, commands, statusBar, eventBus, settings, editor, ipc, exportHooks } = deps;
|
const { pluginId, sidebar, commands, statusBar, eventBus, settings, editor, ipc, exportHooks } =
|
||||||
|
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 = {
|
||||||
@@ -28,41 +29,45 @@ 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) => { if (exportHooks) exportHooks.preHooks.push(handler); },
|
registerPreHook: (handler) => {
|
||||||
registerPostHook: (handler) => { if (exportHooks) exportHooks.postHooks.push(handler); }
|
if (exportHooks) exportHooks.preHooks.push(handler);
|
||||||
|
},
|
||||||
|
registerPostHook: (handler) => {
|
||||||
|
if (exportHooks) exportHooks.postHooks.push(handler);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,10 @@ 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(`[PluginLoader] Failed to load index.js for "${manifest.id}":`, err.message);
|
console.error(
|
||||||
|
`[PluginLoader] Failed to load index.js for "${manifest.id}":`,
|
||||||
|
err.message
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +49,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,7 +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,
|
||||||
});
|
});
|
||||||
|
|
||||||
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.
|
||||||
}
|
}
|
||||||
|
|||||||
+109
-38
@@ -23,6 +23,7 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'save-recent-files',
|
'save-recent-files',
|
||||||
'clear-recent-files',
|
'clear-recent-files',
|
||||||
'renderer-ready',
|
'renderer-ready',
|
||||||
|
'select-custom-css',
|
||||||
|
|
||||||
// Theme
|
// Theme
|
||||||
'get-theme',
|
'get-theme',
|
||||||
@@ -84,12 +85,6 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'get-pdf-page-count',
|
'get-pdf-page-count',
|
||||||
'select-pdf-folder',
|
'select-pdf-folder',
|
||||||
|
|
||||||
// ASCII generator (separate window)
|
|
||||||
'open-ascii-generator',
|
|
||||||
|
|
||||||
// Table generator (separate window)
|
|
||||||
'open-table-generator',
|
|
||||||
|
|
||||||
// Insert generated content
|
// Insert generated content
|
||||||
'insert-generated-content',
|
'insert-generated-content',
|
||||||
|
|
||||||
@@ -103,12 +98,17 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'list-directory',
|
'list-directory',
|
||||||
'read-file',
|
'read-file',
|
||||||
'write-file',
|
'write-file',
|
||||||
|
'write-buffer',
|
||||||
|
'read-buffer',
|
||||||
'delete-file',
|
'delete-file',
|
||||||
'ensure-directory',
|
'ensure-directory',
|
||||||
'path-exists',
|
'path-exists',
|
||||||
'is-directory',
|
'is-directory',
|
||||||
'copy-path',
|
'copy-path',
|
||||||
'move-path',
|
'move-path',
|
||||||
|
'pick-folder',
|
||||||
|
'pick-file',
|
||||||
|
'search-in-files',
|
||||||
|
|
||||||
// Git
|
// Git
|
||||||
'git-status',
|
'git-status',
|
||||||
@@ -134,12 +134,32 @@ const ALLOWED_SEND_CHANNELS = [
|
|||||||
'menu-open',
|
'menu-open',
|
||||||
'export',
|
'export',
|
||||||
|
|
||||||
|
// App lifecycle
|
||||||
|
'app:quit',
|
||||||
|
'app:open-external',
|
||||||
|
'app:show-save-dialog',
|
||||||
|
'get-app-version',
|
||||||
|
|
||||||
|
// Updater
|
||||||
|
'updater:check',
|
||||||
|
'updater:install',
|
||||||
|
'updater:get-state',
|
||||||
|
|
||||||
|
// Crash reporter
|
||||||
|
'crash:read',
|
||||||
|
'crash:open-dir',
|
||||||
|
'crash:delete',
|
||||||
|
|
||||||
|
// Monospace font settings
|
||||||
|
'get-monospace-settings',
|
||||||
|
'set-monospace-settings',
|
||||||
|
|
||||||
// Git diff
|
// Git diff
|
||||||
'git-diff',
|
'git-diff',
|
||||||
|
|
||||||
// Plugin settings
|
// Plugin settings
|
||||||
'plugin-settings:get',
|
'plugin-settings:get',
|
||||||
'plugin-settings:set'
|
'plugin-settings:set',
|
||||||
];
|
];
|
||||||
|
|
||||||
const ALLOWED_RECEIVE_CHANNELS = [
|
const ALLOWED_RECEIVE_CHANNELS = [
|
||||||
@@ -150,6 +170,8 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
'get-content-for-save',
|
'get-content-for-save',
|
||||||
'get-content-for-spreadsheet',
|
'get-content-for-spreadsheet',
|
||||||
'recent-files-cleared',
|
'recent-files-cleared',
|
||||||
|
'load-custom-css',
|
||||||
|
'clear-custom-css',
|
||||||
|
|
||||||
// UI toggles
|
// UI toggles
|
||||||
'toggle-preview',
|
'toggle-preview',
|
||||||
@@ -166,15 +188,10 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
// Font
|
// Font
|
||||||
'adjust-font-size',
|
'adjust-font-size',
|
||||||
|
|
||||||
// Print
|
|
||||||
'print-preview',
|
|
||||||
'print-preview-styled',
|
|
||||||
|
|
||||||
// Export dialogs
|
// Export dialogs
|
||||||
'show-export-dialog',
|
'show-export-dialog',
|
||||||
'show-batch-dialog',
|
'show-batch-dialog',
|
||||||
'show-universal-converter-dialog',
|
'show-universal-converter-dialog',
|
||||||
'show-table-generator',
|
|
||||||
'show-pdf-editor-dialog',
|
'show-pdf-editor-dialog',
|
||||||
|
|
||||||
// Converter dialogs
|
// Converter dialogs
|
||||||
@@ -210,12 +227,7 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
'pdf-operation-complete',
|
'pdf-operation-complete',
|
||||||
'pdf-operation-error',
|
'pdf-operation-error',
|
||||||
|
|
||||||
// ASCII Art Generator
|
|
||||||
'show-ascii-generator-window',
|
|
||||||
'show-ascii-generator',
|
|
||||||
|
|
||||||
// Table Generator
|
// Table Generator
|
||||||
'show-table-generator-window',
|
|
||||||
|
|
||||||
// Header/Footer dialog
|
// Header/Footer dialog
|
||||||
'open-header-footer-dialog',
|
'open-header-footer-dialog',
|
||||||
@@ -230,11 +242,25 @@ const ALLOWED_RECEIVE_CHANNELS = [
|
|||||||
// Batch converter
|
// Batch converter
|
||||||
'show-batch-converter',
|
'show-batch-converter',
|
||||||
|
|
||||||
|
// Document compare
|
||||||
|
'show-document-compare',
|
||||||
|
|
||||||
// v4 menu-triggered events
|
// v4 menu-triggered events
|
||||||
'load-template-menu',
|
'load-template-menu',
|
||||||
'toggle-command-palette',
|
|
||||||
'toggle-sidebar-panel',
|
'toggle-sidebar-panel',
|
||||||
'toggle-bottom-panel'
|
'toggle-bottom-panel',
|
||||||
|
'print-preview',
|
||||||
|
'print-preview-styled',
|
||||||
|
'clear-recent-files',
|
||||||
|
|
||||||
|
// Updater
|
||||||
|
'updater:status',
|
||||||
|
'show-analytics-dialog',
|
||||||
|
|
||||||
|
// File dialog / directory listing
|
||||||
|
'list-directory',
|
||||||
|
'pick-folder',
|
||||||
|
'pick-file',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -336,28 +362,35 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
rendererReady: () => ipcRenderer.send('renderer-ready'),
|
rendererReady: () => ipcRenderer.send('renderer-ready'),
|
||||||
read: (filePath) => ipcRenderer.invoke('read-file', filePath),
|
read: (filePath) => ipcRenderer.invoke('read-file', filePath),
|
||||||
write: (filePath, content) => ipcRenderer.invoke('write-file', { path: filePath, content }),
|
write: (filePath, content) => ipcRenderer.invoke('write-file', { path: filePath, content }),
|
||||||
|
readBuffer: (filePath) => ipcRenderer.invoke('read-buffer', { path: filePath }),
|
||||||
|
writeBuffer: (filePath, buffer) => ipcRenderer.invoke('write-buffer', { path: filePath, buffer }),
|
||||||
delete: (filePath) => ipcRenderer.invoke('delete-file', filePath),
|
delete: (filePath) => ipcRenderer.invoke('delete-file', filePath),
|
||||||
ensureDir: (dirPath) => ipcRenderer.invoke('ensure-directory', dirPath),
|
ensureDir: (dirPath) => ipcRenderer.invoke('ensure-directory', dirPath),
|
||||||
exists: (filePath) => ipcRenderer.invoke('path-exists', filePath),
|
exists: (filePath) => ipcRenderer.invoke('path-exists', filePath),
|
||||||
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'),
|
||||||
|
search: (args) => ipcRenderer.invoke('search-in-files', args),
|
||||||
},
|
},
|
||||||
|
|
||||||
// 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),
|
||||||
|
show: (payload) => ipcRenderer.send('do-print', payload),
|
||||||
},
|
},
|
||||||
|
|
||||||
// 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
|
||||||
@@ -365,7 +398,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
|
||||||
@@ -374,8 +407,14 @@ 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', { tool, fromFormat, toFormat, inputFolder, outputFolder });
|
ipcRenderer.send('universal-convert-batch', {
|
||||||
}
|
tool,
|
||||||
|
fromFormat,
|
||||||
|
toFormat,
|
||||||
|
inputFolder,
|
||||||
|
outputFolder,
|
||||||
|
});
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
// Header/Footer Operations
|
// Header/Footer Operations
|
||||||
@@ -383,22 +422,23 @@ 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) => ipcRenderer.send('save-header-footer-logo', { position, filePath }),
|
saveLogo: (position, filePath) =>
|
||||||
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position)
|
ipcRenderer.send('save-header-footer-logo', { position, filePath }),
|
||||||
|
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)
|
setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber),
|
||||||
},
|
},
|
||||||
|
|
||||||
// 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 Converter Operations
|
||||||
@@ -407,7 +447,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
batchConvert: (data) => ipcRenderer.send('image-batch-convert', data),
|
batchConvert: (data) => ipcRenderer.send('image-batch-convert', data),
|
||||||
resize: (data) => ipcRenderer.send('image-resize', data),
|
resize: (data) => ipcRenderer.send('image-resize', data),
|
||||||
compress: (data) => ipcRenderer.send('image-compress', data),
|
compress: (data) => ipcRenderer.send('image-compress', data),
|
||||||
rotate: (data) => ipcRenderer.send('image-rotate', data)
|
rotate: (data) => ipcRenderer.send('image-rotate', data),
|
||||||
},
|
},
|
||||||
|
|
||||||
// Audio Converter Operations
|
// Audio Converter Operations
|
||||||
@@ -416,7 +456,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
|
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
|
||||||
extract: (data) => ipcRenderer.send('audio-extract', data),
|
extract: (data) => ipcRenderer.send('audio-extract', data),
|
||||||
trim: (data) => ipcRenderer.send('audio-trim', data),
|
trim: (data) => ipcRenderer.send('audio-trim', data),
|
||||||
merge: (data) => ipcRenderer.send('audio-merge', data)
|
merge: (data) => ipcRenderer.send('audio-merge', data),
|
||||||
},
|
},
|
||||||
|
|
||||||
// Video Converter Operations
|
// Video Converter Operations
|
||||||
@@ -426,16 +466,47 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
compress: (data) => ipcRenderer.send('video-compress', data),
|
compress: (data) => ipcRenderer.send('video-compress', data),
|
||||||
trim: (data) => ipcRenderer.send('video-trim', data),
|
trim: (data) => ipcRenderer.send('video-trim', data),
|
||||||
extractFrames: (data) => ipcRenderer.send('video-frames', data),
|
extractFrames: (data) => ipcRenderer.send('video-frames', data),
|
||||||
toGif: (data) => ipcRenderer.send('video-gif', data)
|
toGif: (data) => ipcRenderer.send('video-gif', data),
|
||||||
},
|
},
|
||||||
|
|
||||||
// Generator Windows
|
getAppVersion: () => ipcRenderer.invoke('get-app-version'),
|
||||||
generators: {
|
|
||||||
openAscii: () => ipcRenderer.send('open-ascii-generator'),
|
// Git Operations
|
||||||
openTable: () => ipcRenderer.send('open-table-generator')
|
git: {
|
||||||
|
status: (rootPath) => ipcRenderer.invoke('git-status', rootPath),
|
||||||
|
stage: (args) => ipcRenderer.invoke('git-stage', args),
|
||||||
|
commit: (args) => ipcRenderer.invoke('git-commit', args),
|
||||||
|
log: (rootPath) => ipcRenderer.invoke('git-log', rootPath),
|
||||||
|
diff: (filePath) => ipcRenderer.invoke('git-diff', filePath),
|
||||||
},
|
},
|
||||||
|
|
||||||
getAppVersion: () => ipcRenderer.invoke('get-app-version')
|
app: {
|
||||||
|
quit: () => ipcRenderer.send('app:quit'),
|
||||||
|
openExternal: (url) => ipcRenderer.send('app:open-external', url),
|
||||||
|
showSaveDialog: (args) => ipcRenderer.invoke('app:show-save-dialog', args),
|
||||||
|
},
|
||||||
|
|
||||||
|
updater: {
|
||||||
|
check: () => ipcRenderer.invoke('updater:check'),
|
||||||
|
install: () => ipcRenderer.invoke('updater:install'),
|
||||||
|
getState: () => ipcRenderer.invoke('updater:get-state'),
|
||||||
|
onStatus: (cb) => {
|
||||||
|
const subscription = (_event, payload) => cb(payload);
|
||||||
|
ipcRenderer.on('updater:status', subscription);
|
||||||
|
return () => ipcRenderer.removeListener('updater:status', subscription);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
crash: {
|
||||||
|
read: () => ipcRenderer.invoke('crash:read'),
|
||||||
|
openDir: () => ipcRenderer.send('crash:open-dir'),
|
||||||
|
delete: (filename) => ipcRenderer.invoke('crash:delete', filename),
|
||||||
|
},
|
||||||
|
|
||||||
|
monospace: {
|
||||||
|
getSettings: () => ipcRenderer.invoke('get-monospace-settings'),
|
||||||
|
saveSettings: (partial) => ipcRenderer.invoke('set-monospace-settings', partial),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Log successful preload initialization
|
// Log successful preload initialization
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
class PrintPreview {
|
|
||||||
constructor() {
|
|
||||||
this.overlay = document.getElementById('print-preview-overlay');
|
|
||||||
this.modal = window.modals?.printPreviewModal;
|
|
||||||
this._lastContent = '';
|
|
||||||
this.setupEventListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
open(htmlContent) {
|
|
||||||
this._lastContent = htmlContent;
|
|
||||||
if (this.modal) {
|
|
||||||
this.modal.open();
|
|
||||||
} else {
|
|
||||||
this.overlay.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
this.updatePreview(htmlContent);
|
|
||||||
this.updateScaleLabel();
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
if (this.modal) {
|
|
||||||
this.modal.close();
|
|
||||||
} else {
|
|
||||||
this.overlay.classList.add('hidden');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setupEventListeners() {
|
|
||||||
document.getElementById('print-preview-close')?.addEventListener('click', () => this.close());
|
|
||||||
document.getElementById('print-cancel')?.addEventListener('click', () => this.close());
|
|
||||||
document.getElementById('print-execute')?.addEventListener('click', () => this.executePrint());
|
|
||||||
|
|
||||||
// Update preview on option changes
|
|
||||||
['print-paper-size', 'print-orientation', 'print-margins'].forEach(id => {
|
|
||||||
document.getElementById(id)?.addEventListener('change', () => this.refreshPreview());
|
|
||||||
});
|
|
||||||
|
|
||||||
// Scale slider
|
|
||||||
const scaleSlider = document.getElementById('print-scale');
|
|
||||||
scaleSlider?.addEventListener('input', () => this.updateScaleLabel());
|
|
||||||
|
|
||||||
// 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');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Note: Backdrop click and Escape key are now handled by ModalManager
|
|
||||||
}
|
|
||||||
|
|
||||||
updateScaleLabel() {
|
|
||||||
const scale = document.getElementById('print-scale')?.value || 100;
|
|
||||||
const label = document.getElementById('print-scale-value');
|
|
||||||
if (label) label.textContent = `${scale}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
updatePreview(htmlContent) {
|
|
||||||
const frame = document.getElementById('print-preview-frame');
|
|
||||||
if (!frame) return;
|
|
||||||
|
|
||||||
this._lastContent = htmlContent;
|
|
||||||
|
|
||||||
const orientation = document.getElementById('print-orientation')?.value || 'portrait';
|
|
||||||
const paperSize = document.getElementById('print-paper-size')?.value || 'A4';
|
|
||||||
|
|
||||||
// Get dimensions for paper size
|
|
||||||
const sizes = {
|
|
||||||
'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'];
|
|
||||||
const width = orientation === 'landscape' ? size.height : size.width;
|
|
||||||
const height = orientation === 'landscape' ? size.width : size.height;
|
|
||||||
|
|
||||||
const previewHtml = `
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<style>
|
|
||||||
body {
|
|
||||||
margin: 20px;
|
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.6;
|
|
||||||
}
|
|
||||||
@page { size: ${width} ${height}; }
|
|
||||||
pre { background: #f5f5f5; padding: 12px; border-radius: 6px; overflow-x: auto; }
|
|
||||||
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
|
|
||||||
pre code { background: none; padding: 0; }
|
|
||||||
table { border-collapse: collapse; width: 100%; }
|
|
||||||
th, td { border: 1px solid #ddd; padding: 8px; }
|
|
||||||
blockquote { border-left: 4px solid #ddd; margin-left: 0; padding-left: 16px; color: #666; }
|
|
||||||
img { max-width: 100%; }
|
|
||||||
h1, h2, h3 { margin-top: 1.5em; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>${htmlContent || ''}</body>
|
|
||||||
</html>
|
|
||||||
`;
|
|
||||||
|
|
||||||
frame.srcdoc = previewHtml;
|
|
||||||
}
|
|
||||||
|
|
||||||
refreshPreview() {
|
|
||||||
if (this._lastContent) {
|
|
||||||
this.updatePreview(this._lastContent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getOptions() {
|
|
||||||
return {
|
|
||||||
paperSize: document.getElementById('print-paper-size')?.value || 'A4',
|
|
||||||
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() {
|
|
||||||
const options = this.getOptions();
|
|
||||||
const { ipcRenderer } = require('electron');
|
|
||||||
ipcRenderer.send('do-print-with-options', options);
|
|
||||||
this.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { PrintPreview };
|
|
||||||
-4863
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { AppShell } from './components/layout/AppShell';
|
||||||
|
import { ModalLayer } from './components/modals/ModalLayer';
|
||||||
|
import { CommandPalette } from './components/modals/CommandPalette';
|
||||||
|
import { Toaster } from './components/ui/sonner';
|
||||||
|
import { ReplPanel } from './components/tools/ReplPanel';
|
||||||
|
import { PrintPreview } from './components/tools/PrintPreview';
|
||||||
|
import { UpdateBanner } from './components/UpdateBanner';
|
||||||
|
import { FirstRunWizard } from './components/FirstRunWizard';
|
||||||
|
import { useWelcomeTrigger } from './hooks/use-welcome-trigger';
|
||||||
|
import { useAutoUpdateCheck } from './hooks/useAutoUpdateCheck';
|
||||||
|
import { useMonospaceClasses } from './hooks/use-monospace-classes';
|
||||||
|
|
||||||
|
import { useSettingsStore } from './stores/settings-store';
|
||||||
|
import { ipc } from './lib/ipc';
|
||||||
|
import { toast } from './lib/toast';
|
||||||
|
|
||||||
|
function scopeCSS(cssText: string, scopeSelector: string) {
|
||||||
|
if (!cssText) return '';
|
||||||
|
return cssText.replace(/([^\r\n,{}]+)(,(?=[^}]*{)|(?=[^{]*{))/g, (match, selector, separator) => {
|
||||||
|
const trimmed = selector.trim();
|
||||||
|
if (
|
||||||
|
!trimmed ||
|
||||||
|
trimmed.startsWith('@') ||
|
||||||
|
trimmed.startsWith(':root') ||
|
||||||
|
trimmed.startsWith('from') ||
|
||||||
|
trimmed.startsWith('to') ||
|
||||||
|
/^\d+%$/.test(trimmed)
|
||||||
|
) {
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
return scopeSelector + ' ' + trimmed + (separator || '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
useWelcomeTrigger();
|
||||||
|
useAutoUpdateCheck();
|
||||||
|
useMonospaceClasses();
|
||||||
|
const [printOpen, setPrintOpen] = useState(false);
|
||||||
|
const customCssPath = useSettingsStore((s) => s.customCssPath);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
const styleId = 'custom-preview-style';
|
||||||
|
|
||||||
|
async function applyCSS() {
|
||||||
|
if (!customCssPath) {
|
||||||
|
const styleTag = document.getElementById(styleId);
|
||||||
|
if (styleTag) styleTag.remove();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = await ipc.file.read(customCssPath);
|
||||||
|
if (!active) return;
|
||||||
|
if (r.ok && r.data) {
|
||||||
|
let styleTag = document.getElementById(styleId);
|
||||||
|
if (!styleTag) {
|
||||||
|
styleTag = document.createElement('style');
|
||||||
|
styleTag.id = styleId;
|
||||||
|
document.head.appendChild(styleTag);
|
||||||
|
}
|
||||||
|
styleTag.textContent = scopeCSS(r.data, '.preview-content');
|
||||||
|
} else {
|
||||||
|
toast.error('Failed to load custom CSS file');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void applyCSS();
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [customCssPath]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.electronAPI?.file?.rendererReady?.();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => setPrintOpen(true);
|
||||||
|
window.addEventListener('mc:print', handler);
|
||||||
|
window.addEventListener('mc:print-preview', handler);
|
||||||
|
window.addEventListener('mc:print-preview-styled', handler);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('mc:print', handler);
|
||||||
|
window.removeEventListener('mc:print-preview', handler);
|
||||||
|
window.removeEventListener('mc:print-preview-styled', handler);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AppShell />
|
||||||
|
<ModalLayer />
|
||||||
|
<CommandPalette />
|
||||||
|
<Toaster />
|
||||||
|
<UpdateBanner />
|
||||||
|
<FirstRunWizard />
|
||||||
|
<ReplPanel />
|
||||||
|
{printOpen && <PrintPreview onClose={() => setPrintOpen(false)} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export default App;
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
|
||||||
|
const TEMPLATES = {
|
||||||
|
blank: '',
|
||||||
|
readme: '# Project\n\nDescription.\n\n## Usage\n\n```\nnpm install\n```\n',
|
||||||
|
meeting:
|
||||||
|
'# Meeting Notes — YYYY-MM-DD\n\n## Attendees\n\n- \n## Agenda\n\n1. \n\n## Action items\n\n- [ ] \n',
|
||||||
|
blog: '# Title\n\n*Subtitle*\n\nLorem ipsum.\n\n---\n\n## Section 1\n',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function FirstRunWizard() {
|
||||||
|
const firstRun = useAppStore((s) => s.firstRun);
|
||||||
|
const setFirstRun = useAppStore((s) => s.setFirstRun);
|
||||||
|
const theme = useSettingsStore((s) => s.theme);
|
||||||
|
const setSetting = useSettingsStore((s) => s.setSetting);
|
||||||
|
const updateChannel = useSettingsStore((s) => s.updateChannel);
|
||||||
|
const [step, setStep] = useState(0);
|
||||||
|
const [template, setTemplate] = useState<keyof typeof TEMPLATES>('blank');
|
||||||
|
|
||||||
|
if (!firstRun) return null;
|
||||||
|
|
||||||
|
const close = () => setFirstRun(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="first-run-wizard"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<div className="bg-white dark:bg-neutral-900 rounded-lg p-6 w-[28rem] shadow-xl">
|
||||||
|
{step === 0 && (
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Pick a theme</h2>
|
||||||
|
<div className="flex gap-2 mb-4">
|
||||||
|
{(['light', 'dark', 'system'] as const).map((t) => (
|
||||||
|
<label key={t} className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="theme"
|
||||||
|
checked={theme === t}
|
||||||
|
onChange={() => setSetting('theme', t)}
|
||||||
|
/>
|
||||||
|
{t}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 1 && (
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Update channel</h2>
|
||||||
|
<div className="flex flex-col gap-2 mb-4">
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="channel"
|
||||||
|
checked={updateChannel === 'github'}
|
||||||
|
onChange={() => setSetting('updateChannel', 'github')}
|
||||||
|
/>
|
||||||
|
GitHub Releases (public)
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="channel"
|
||||||
|
checked={updateChannel === 'concreteinfo'}
|
||||||
|
onChange={() => setSetting('updateChannel', 'concreteinfo')}
|
||||||
|
/>
|
||||||
|
ConcreteInfo self-hosted
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{step === 2 && (
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Starter template</h2>
|
||||||
|
<select
|
||||||
|
value={template}
|
||||||
|
onChange={(e) => setTemplate(e.target.value as any)}
|
||||||
|
className="border rounded px-2 py-1 w-full mb-4"
|
||||||
|
>
|
||||||
|
<option value="blank">Blank</option>
|
||||||
|
<option value="readme">README</option>
|
||||||
|
<option value="meeting">Meeting notes</option>
|
||||||
|
<option value="blog">Blog post</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-between items-center mt-4">
|
||||||
|
<button onClick={close} className="text-sm text-neutral-500">
|
||||||
|
Skip
|
||||||
|
</button>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{step > 0 && <button onClick={() => setStep(step - 1)}>Back</button>}
|
||||||
|
{step < 2 ? (
|
||||||
|
<button
|
||||||
|
onClick={() => setStep(step + 1)}
|
||||||
|
className="px-3 py-1 rounded bg-brand text-white"
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
useAppStore.getState().newBuffer(TEMPLATES[template]);
|
||||||
|
close();
|
||||||
|
}}
|
||||||
|
className="px-3 py-1 rounded bg-brand text-white"
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { useUpdaterStore } from '@/lib/updater-store';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
export function UpdateBanner() {
|
||||||
|
const { state, version, percent, install, check } = useUpdaterStore();
|
||||||
|
|
||||||
|
if (state === 'idle' || state === 'checking') return null;
|
||||||
|
|
||||||
|
if (state === 'error') {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="update-banner"
|
||||||
|
role="status"
|
||||||
|
className="bg-amber-50 border-b border-amber-200 px-4 py-2 text-sm"
|
||||||
|
>
|
||||||
|
Couldn't check for updates.{' '}
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await check();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.error(e.message);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="underline"
|
||||||
|
>
|
||||||
|
Try again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state === 'available') {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="update-banner"
|
||||||
|
className="bg-blue-50 border-b border-blue-200 px-4 py-2 text-sm"
|
||||||
|
>
|
||||||
|
A new version (v{version}) is available.{' '}
|
||||||
|
<button onClick={() => useUpdaterStore.getState().check()} className="underline">
|
||||||
|
Download now
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state === 'downloading') {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="update-banner"
|
||||||
|
className="bg-blue-50 border-b border-blue-200 px-4 py-2 text-sm"
|
||||||
|
>
|
||||||
|
Downloading update… {Math.round(percent)}%
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state === 'ready') {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="update-banner"
|
||||||
|
className="bg-green-50 border-b border-green-200 px-4 py-2 text-sm flex items-center gap-3"
|
||||||
|
>
|
||||||
|
<span>v{version} is ready.</span>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
ipc.app.openExternal(
|
||||||
|
`https://github.com/amitwh/markdown-converter/releases/tag/v${version}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
className="underline"
|
||||||
|
>
|
||||||
|
View release notes
|
||||||
|
</button>
|
||||||
|
<button onClick={install} className="px-3 py-1 rounded bg-brand text-white">
|
||||||
|
Restart to update
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { useEffect, useRef, useState, useCallback } 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';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { setActiveView, insertSnippet } from '@/lib/editor-commands';
|
||||||
|
import { Minimap } from './Minimap';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
bufferId: string;
|
||||||
|
initialContent: string;
|
||||||
|
onChange?: (content: string) => void;
|
||||||
|
onCursorChange?: (line: number, column: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const IMAGE_TYPES = new Set([
|
||||||
|
'image/png',
|
||||||
|
'image/jpeg',
|
||||||
|
'image/gif',
|
||||||
|
'image/webp',
|
||||||
|
'image/svg+xml',
|
||||||
|
'image/bmp',
|
||||||
|
'image/avif',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function guessExt(mimeType: string): string {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
'image/png': 'png',
|
||||||
|
'image/jpeg': 'jpg',
|
||||||
|
'image/gif': 'gif',
|
||||||
|
'image/webp': 'webp',
|
||||||
|
'image/svg+xml': 'svg',
|
||||||
|
'image/bmp': 'bmp',
|
||||||
|
'image/avif': 'avif',
|
||||||
|
};
|
||||||
|
return map[mimeType] ?? 'png';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleImageFile(file: File): Promise<void> {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async () => {
|
||||||
|
const base64 = (reader.result as string).split(',')[1];
|
||||||
|
if (!base64) return;
|
||||||
|
const ext = guessExt(file.type);
|
||||||
|
const result = await window.electronAPI.invoke('save-pasted-image', { base64, ext });
|
||||||
|
if (result) {
|
||||||
|
insertSnippet(``);
|
||||||
|
toast.success('Image pasted');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPasteHandler() {
|
||||||
|
return EditorView.domEventHandlers({
|
||||||
|
paste(event: ClipboardEvent, _view: EditorView) {
|
||||||
|
const items = event.clipboardData?.items;
|
||||||
|
if (!items) return false;
|
||||||
|
for (let i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i];
|
||||||
|
if (IMAGE_TYPES.has(item.type)) {
|
||||||
|
event.preventDefault();
|
||||||
|
const file = item.getAsFile();
|
||||||
|
if (file) handleImageFile(file);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
const minimap = useSettingsStore((s) => s.minimap);
|
||||||
|
const editorFontSize = useSettingsStore((s) => s.editorFontSize);
|
||||||
|
const buffer = useEditorStore((s) => s.buffers.get(bufferId));
|
||||||
|
const content = buffer?.content ?? initialContent;
|
||||||
|
const [scrollRatio, setScrollRatio] = useState(0);
|
||||||
|
const [visibleRatio, setVisibleRatio] = useState(1);
|
||||||
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
EditorView.theme({
|
||||||
|
'&': { fontSize: `${editorFontSize}px` },
|
||||||
|
}),
|
||||||
|
EditorView.domEventHandlers({
|
||||||
|
scroll(_event, view) {
|
||||||
|
const el = view.scrollDOM;
|
||||||
|
const denom = el.scrollHeight - el.clientHeight;
|
||||||
|
setScrollRatio(denom > 0 ? el.scrollTop / denom : 0);
|
||||||
|
setVisibleRatio(
|
||||||
|
el.clientHeight > 0 ? Math.min(1, el.clientHeight / el.scrollHeight) : 1
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
createPasteHandler(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const view = new EditorView({ state, parent: ref.current });
|
||||||
|
viewRef.current = view;
|
||||||
|
setActiveView(view);
|
||||||
|
return () => {
|
||||||
|
setActiveView(null);
|
||||||
|
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]);
|
||||||
|
|
||||||
|
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||||
|
if (e.dataTransfer.types.includes('Files')) {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(true);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDrop = useCallback(async (e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
const files = Array.from(e.dataTransfer.files);
|
||||||
|
const imageFiles = files.filter((f) => IMAGE_TYPES.has(f.type));
|
||||||
|
for (const file of imageFiles) {
|
||||||
|
await handleImageFile(file);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative h-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'h-full overflow-hidden transition-colors duration-150',
|
||||||
|
isDragOver && 'ring-2 ring-primary bg-primary/5'
|
||||||
|
)}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
/>
|
||||||
|
{minimap && (
|
||||||
|
<Minimap content={content} scrollRatio={scrollRatio} visibleRatio={visibleRatio} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { CodeMirrorEditor } from './CodeMirrorEditor';
|
||||||
|
import { FindReplaceBar } from './FindReplaceBar';
|
||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
import { usePreviewStore } from '@/stores/preview-store';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
|
||||||
|
export function EditorPane() {
|
||||||
|
const { buffers, activeId } = useEditorStore();
|
||||||
|
const buf = activeId ? buffers.get(activeId) : null;
|
||||||
|
const setPreviewSource = usePreviewStore((s) => s.setSource);
|
||||||
|
const lastActiveId = useRef<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!buf) return;
|
||||||
|
const isNewFile = lastActiveId.current !== buf.id;
|
||||||
|
lastActiveId.current = buf.id;
|
||||||
|
|
||||||
|
const isLarge = buf.content.length > 1024 * 1024;
|
||||||
|
|
||||||
|
if (isLarge) {
|
||||||
|
if (!usePreviewStore.getState().largeFileMode) {
|
||||||
|
usePreviewStore.setState({ largeFileMode: true });
|
||||||
|
useAppStore.setState({ previewVisible: false });
|
||||||
|
toast.warning(
|
||||||
|
'Large content detected (>1MB). Large File Mode enabled to maintain peak responsiveness. Live preview auto-render is disabled.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only render on initial load / tab switch, not on edits
|
||||||
|
if (isNewFile) {
|
||||||
|
usePreviewStore.getState().forceRender(buf.content);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (usePreviewStore.getState().largeFileMode) {
|
||||||
|
usePreviewStore.setState({ largeFileMode: false });
|
||||||
|
}
|
||||||
|
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="flex h-full flex-col">
|
||||||
|
<FindReplaceBar />
|
||||||
|
<div className="flex-1 overflow-hidden">
|
||||||
|
<CodeMirrorEditor key={buf.id} bufferId={buf.id} initialContent={buf.content} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
import { useEffect, useRef, useCallback, useState } from 'react';
|
||||||
|
import {
|
||||||
|
findNext,
|
||||||
|
findPrevious,
|
||||||
|
replaceNext,
|
||||||
|
replaceAll,
|
||||||
|
closeSearchPanel,
|
||||||
|
getSearchQuery,
|
||||||
|
setSearchQuery,
|
||||||
|
} from '@codemirror/search';
|
||||||
|
import type { EditorView } from '@codemirror/view';
|
||||||
|
import { getActiveView } from '@/lib/editor-commands';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { X, ChevronDown, ChevronUp, Replace, ReplaceAll, CaseSensitive, Regex } from 'lucide-react';
|
||||||
|
|
||||||
|
export function FindReplaceBar() {
|
||||||
|
const findBarOpen = useAppStore((s) => s.findBarOpen);
|
||||||
|
const toggleFindBar = useAppStore((s) => s.toggleFindBar);
|
||||||
|
const searchRef = useRef<HTMLInputElement>(null);
|
||||||
|
const replaceRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [caseSensitive, setCaseSensitive] = useState(false);
|
||||||
|
const [useRegex, setUseRegex] = useState(false);
|
||||||
|
const [matchInfo, setMatchInfo] = useState<{ current: number; total: number } | null>(null);
|
||||||
|
|
||||||
|
const updateMatchCount = useCallback(() => {
|
||||||
|
const view = getActiveView();
|
||||||
|
if (!view) {
|
||||||
|
setMatchInfo(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const query = getSearchQuery(view.state);
|
||||||
|
if (!query || !query.search) {
|
||||||
|
setMatchInfo(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const docText = view.state.doc.toString();
|
||||||
|
const searchStr = query.regexp
|
||||||
|
? query.search
|
||||||
|
: query.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
const flags = `g${query.caseSensitive ? '' : 'i'}`;
|
||||||
|
const regex = new RegExp(searchStr, flags);
|
||||||
|
const matches = docText.match(regex);
|
||||||
|
if (!matches) {
|
||||||
|
setMatchInfo({ current: 0, total: 0 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const selectionHead = view.state.selection.main.head;
|
||||||
|
let currentMatch = 0;
|
||||||
|
const matchPositions: number[] = [];
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(docText)) !== null) {
|
||||||
|
matchPositions.push(match.index);
|
||||||
|
if (match.index <= selectionHead && selectionHead <= match.index + match[0].length) {
|
||||||
|
currentMatch = matchPositions.length;
|
||||||
|
}
|
||||||
|
if (matchPositions.length > 10000) break;
|
||||||
|
}
|
||||||
|
setMatchInfo({ current: currentMatch || 1, total: matchPositions.length });
|
||||||
|
} catch {
|
||||||
|
setMatchInfo(null);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const executeCommand = useCallback(
|
||||||
|
(fn: (view: EditorView) => boolean | void) => {
|
||||||
|
const view = getActiveView();
|
||||||
|
if (!view) return false;
|
||||||
|
const result = fn(view);
|
||||||
|
updateMatchCount();
|
||||||
|
view.focus();
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
[updateMatchCount]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleFindNext = useCallback(() => {
|
||||||
|
executeCommand(findNext);
|
||||||
|
}, [executeCommand]);
|
||||||
|
|
||||||
|
const handleFindPrev = useCallback(() => {
|
||||||
|
executeCommand(findPrevious);
|
||||||
|
}, [executeCommand]);
|
||||||
|
|
||||||
|
const handleReplace = useCallback(() => {
|
||||||
|
executeCommand(replaceNext);
|
||||||
|
}, [executeCommand]);
|
||||||
|
|
||||||
|
const handleReplaceAll = useCallback(() => {
|
||||||
|
executeCommand(replaceAll);
|
||||||
|
}, [executeCommand]);
|
||||||
|
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
const view = getActiveView();
|
||||||
|
if (view) closeSearchPanel(view);
|
||||||
|
toggleFindBar();
|
||||||
|
view?.focus();
|
||||||
|
}, [toggleFindBar]);
|
||||||
|
|
||||||
|
const handleSearchChange = useCallback(
|
||||||
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const value = e.target.value;
|
||||||
|
const view = getActiveView();
|
||||||
|
if (!view) return;
|
||||||
|
setSearchQuery(view, {
|
||||||
|
search: value,
|
||||||
|
caseSensitive,
|
||||||
|
regexp: useRegex,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[caseSensitive, useRegex]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleReplaceChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const view = getActiveView();
|
||||||
|
if (!view) return;
|
||||||
|
const query = getSearchQuery(view.state);
|
||||||
|
if (query) {
|
||||||
|
setSearchQuery(view, {
|
||||||
|
search: query.search,
|
||||||
|
caseSensitive: query.caseSensitive ?? false,
|
||||||
|
regexp: query.regexp ?? false,
|
||||||
|
replace: e.target.value,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (findBarOpen) {
|
||||||
|
setTimeout(() => searchRef.current?.focus(), 50);
|
||||||
|
}
|
||||||
|
}, [findBarOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => {
|
||||||
|
if (!useAppStore.getState().findBarOpen) {
|
||||||
|
useAppStore.getState().toggleFindBar();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('mc:find-toggle', handler);
|
||||||
|
return () => window.removeEventListener('mc:find-toggle', handler);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!findBarOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5 border-b border-border bg-background px-2 py-1">
|
||||||
|
<Input
|
||||||
|
ref={searchRef}
|
||||||
|
placeholder="Find..."
|
||||||
|
className="h-7 w-48 text-xs"
|
||||||
|
onChange={handleSearchChange}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.shiftKey ? handleFindPrev() : handleFindNext();
|
||||||
|
}
|
||||||
|
if (e.key === 'Escape') handleClose();
|
||||||
|
if (e.key === 'Tab' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
replaceRef.current?.focus();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
data-testid="find-input"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'rounded p-0.5 hover:bg-accent',
|
||||||
|
caseSensitive && 'bg-accent text-accent-foreground'
|
||||||
|
)}
|
||||||
|
onClick={() => {
|
||||||
|
setCaseSensitive((v) => {
|
||||||
|
const next = !v;
|
||||||
|
const view = getActiveView();
|
||||||
|
if (view) {
|
||||||
|
const query = getSearchQuery(view.state);
|
||||||
|
if (query) {
|
||||||
|
setSearchQuery(view, {
|
||||||
|
search: query.search,
|
||||||
|
caseSensitive: next,
|
||||||
|
regexp: useRegex,
|
||||||
|
replace: query.replace,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
aria-label="Case sensitive"
|
||||||
|
data-testid="find-case-sensitive"
|
||||||
|
>
|
||||||
|
<CaseSensitive className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'rounded p-0.5 hover:bg-accent',
|
||||||
|
useRegex && 'bg-accent text-accent-foreground'
|
||||||
|
)}
|
||||||
|
onClick={() => {
|
||||||
|
setUseRegex((v) => {
|
||||||
|
const next = !v;
|
||||||
|
const view = getActiveView();
|
||||||
|
if (view) {
|
||||||
|
const query = getSearchQuery(view.state);
|
||||||
|
if (query) {
|
||||||
|
setSearchQuery(view, {
|
||||||
|
search: query.search,
|
||||||
|
caseSensitive,
|
||||||
|
regexp: next,
|
||||||
|
replace: query.replace,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
aria-label="Use regex"
|
||||||
|
data-testid="find-regex"
|
||||||
|
>
|
||||||
|
<Regex className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{matchInfo && matchInfo.total > 0 && (
|
||||||
|
<span className="min-w-[4rem] text-center text-[10px] text-muted-foreground">
|
||||||
|
{matchInfo.current}/{matchInfo.total}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Input
|
||||||
|
ref={replaceRef}
|
||||||
|
placeholder="Replace..."
|
||||||
|
className="h-7 w-48 text-xs"
|
||||||
|
onChange={handleReplaceChange}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') handleReplace();
|
||||||
|
if (e.key === 'Escape') handleClose();
|
||||||
|
if (e.key === 'Tab' && e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
searchRef.current?.focus();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
data-testid="replace-input"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button size="sm" variant="ghost" onClick={handleFindPrev} aria-label="Find previous">
|
||||||
|
<ChevronUp className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={handleFindNext} aria-label="Find next">
|
||||||
|
<ChevronDown className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={handleReplace} aria-label="Replace">
|
||||||
|
<Replace className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={handleReplaceAll} aria-label="Replace all">
|
||||||
|
<ReplaceAll className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={handleClose} aria-label="Close">
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
interface Props {
|
||||||
|
content: string;
|
||||||
|
scrollRatio?: number; // 0-1, where the viewport is
|
||||||
|
visibleRatio?: number; // 0-1, what fraction of content is visible
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Minimap({ content, scrollRatio = 0, visibleRatio = 1 }: Props) {
|
||||||
|
const lines = content.split('\n');
|
||||||
|
// Compute viewport position in the minimap
|
||||||
|
const viewportTop = Math.round(scrollRatio * 100);
|
||||||
|
const viewportHeight = Math.round(visibleRatio * 100);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="minimap"
|
||||||
|
className="pointer-events-none absolute right-0 top-0 h-full w-[100px] overflow-hidden border-l border-border bg-card/30 p-1 font-mono text-[6px] leading-[8px] text-muted-foreground"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<pre className="w-full truncate whitespace-pre">
|
||||||
|
{lines.map((line, i) => (
|
||||||
|
<div key={i} data-testid="minimap-line">
|
||||||
|
{line || ' '}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</pre>
|
||||||
|
<div
|
||||||
|
data-testid="minimap-viewport"
|
||||||
|
className="pointer-events-none absolute left-0 right-0 bg-brand/15"
|
||||||
|
style={{ top: `${viewportTop}%`, height: `${Math.max(viewportHeight, 5)}%` }}
|
||||||
|
/>
|
||||||
|
</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);
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user