Compare commits

..
174 Commits
Author SHA1 Message Date
amitwh b83ba91731 fix(packaging): unpack @img prebuilt sharp binaries so deb ships bundled libvips
build.asarUnpack only claimed node_modules/sharp/**, so electron-builder
pruned the @img/sharp-* optionalDependencies: the asar kept 34 pure-JS
@img entries while the bundled libvips shared libraries never shipped.
At boot sharp's loader fell back to a system-libvips-linked binding and
dlopen failed, crashing the main process. Claim the prebuilt packages
explicitly (@img/** and @napi-rs/**) per the sharp+electron-builder
recipe, and guard the built output with a packaging regression test.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 0babf97f0e fix(image): lazy-load sharp with honest degradation so boot never fails
A missing/pruned @img/sharp-* binding made the top-level require('sharp')
crash src/main.js at startup, killing the packaged app before any window.
Load sharp through a cached lazy getter instead; when the native module
cannot load, executeOperation resolves the honest failure shape
{ success: false, error: 'Image operations unavailable: <sanitized>' }
(free of absolute paths), mirroring PDFOperations' Task-27 precedent.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh eeda3f28eb fix(test): exclude dist/ from Jest haste map
electron-builder's .snap (Squashfs) artifact in dist/ registered as an
obsolete Jest snapshot file, failing the suite exit code despite all
516 tests passing. modulePathIgnorePatterns keeps the snapshot scanner
out of build output.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 4c00406bcd docs(security): correct BurntToast drop evidence to cover CLI argv path
Final-review nit: the hardcoded-list rationale covers the dialog path
only; the drop stands on the trusted-argv precedent for --convert-to.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 363de75375 fix(pdf): guard pdfSplit against non-positive interval infinite loop
The interval split mode looped for (i = 0; i < totalPages; i += interval),
which spins forever when interval <= 0. Both the single-file dialog and the
batch dialog can reach it (the batch dialog's validateOperationData only
checks truthiness, so -1 passes). Guard at the source in the main process:
reject non-positive or non-integer intervals before the loop, protecting
both paths and any future caller.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 2e16868f59 fix(preload): whitelist get-pdf-form-fields and pdf-form-fields channels
The get-pdf-form-fields IPC pair (handler in main.js, renderer invoke and
event.reply('pdf-form-fields')) was missing from ALLOWED_SEND_CHANNELS and
ALLOWED_RECEIVE_CHANNELS. Under the planned preload migration an unlisted
channel is silently blocked, so the form-field fill/flatten feature would
break once the main window stops using the inline shim. Placed adjacent to
the sibling get-pdf-page-count/pdf-page-count pair it was modeled on.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh dd6d97c35d docs(security): formal security assessment summary
Manual audit + Task 24 formal pass: SEC-1 Pandoc argument injection
(critical, fixed), Git sidebar XSS (high, fixed), File.path dead on
Electron 41 (fixed), pdf-lib encryption silent no-op (fixed, honest
failure). 14 areas verified clean. 7 deferred/accepted risks documented
(D1-D7) incl. real-encryption dependency decision and GUI-pass release
blocker.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 0604c65683 fix(security): escape repo-derived strings in Git sidebar rendering (XSS) 2026-08-23 19:31:33 +05:30
amitwh c43caf3902 fix(security): convert Pandoc invocation to execFile argument arrays (SEC-1) 2026-08-23 19:31:33 +05:30
amitwh 25dcaaa816 fix(pdf): make encrypt/decrypt/permissions fail honestly instead of silent no-op 2026-08-23 19:31:33 +05:30
amitwh c6ec1cef64 fix(renderer): migrate File.path reads to webUtils.getPathForFile for Electron 41 2026-08-23 19:31:33 +05:30
amitwh 5fcc282fe0 docs(plan): append Task 27 — honest failure for pdf-lib encryption no-op
Task-22-review finding: pdf-lib 1.17.1 silently ignores userPassword/
ownerPassword; encrypt/permissions write unprotected files reporting
success; decrypt is a copy no-op.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 8a95144bf3 feat(pdf): add bulk PDF operations (watermark/compress/rotate/etc.) to batch converter 2026-08-23 19:31:33 +05:30
amitwh bc47316746 fix(export): one-time import of legacy localStorage export profiles into presets 2026-08-23 19:31:33 +05:30
amitwh 02ce06d364 feat(export): add save/select/delete export presets 2026-08-23 19:31:33 +05:30
amitwh 2e3af826f7 docs(plan): append Task 26 — File.path → webUtils migration (Electron 41 fix)
Task-20-review finding: File.path removed in Electron 32, app on ^41.1.1,
~15 renderer file-picker sites read it and get undefined at runtime.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 758dcb4166 feat(compare): implement Document Compare dialog with local-diff and git-HEAD-diff modes
Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 1f5db511ba feat(editor): add CSV-to-markdown-table toolbar converter
Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 63c35ef2dc fix(preload): whitelist word-template IPC channels, drop orphaned set-custom-start-page 2026-08-23 19:31:33 +05:30
amitwh c8883e77fe feat(export): add visual word-template settings dialog with graceful default-template fallback
Replaces the two native OS dialogs used to configure the DOCX "Enhanced"
export template (an open-file picker + a message-box question) with a
single in-app modal that shows the currently active template state, per
Task 18's original audit finding that this state was invisible until a
user thought to reopen the menu. Consolidates the "Select Word
Template..."/"Template Settings..." menu items into one "Word Template
Settings..." entry wired to the new dialog; Browse still uses the native
file picker since there is genuinely no bundled folder of templates to
enumerate (confirmed by investigation — see task-18-report.md).

Also fixes a related dangling-reference bug: WordTemplateExporter's
hardcoded default template path (word_template.docx) was deleted from
the repo in an earlier commit, but the code still tried to read it and
threw ENOENT whenever no custom template was selected. convert() now
degrades gracefully by generating a minimal, valid DOCX shell (styles +
numbering matching what markdownToWordXml() already references) instead
of crashing, and the new dialog surfaces this state honestly ("using
default formatting, no default template is bundled") rather than
implying a working default exists.

Out of scope, per explicit instruction: bundling fabricated starter
.docx templates to populate a literal multi-item gallery (rejected as
disproportionate/fake-content scope), and an EPUB template gallery (no
EPUB template mechanism exists anywhere in this codebase to build one
for).

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 8a28c21512 fix(plugins): whitelist plugin export-format IPC channels in preload.js
Task 17's three new IPC channels (plugin-export-formats-registered,
run-plugin-export-format, plugin-export-format-result) were missing
from preload.js's ALLOWED_SEND_CHANNELS/ALLOWED_RECEIVE_CHANNELS,
breaking the established convention that the allowlist is the
authoritative registry of every valid channel regardless of whether
it's accessed via window.electronAPI or raw ipcRenderer (see
toggle-sidebar-panel, set-current-file, save-recent-files).

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh d6baa2daf7 feat(plugins): add export-format registration hook to plugin API
Add context.formats.registerExportFormat(id, opts) to PluginContext,
backed by a new FormatRegistry (mirrors PluginRegistry's Map-based
shape). Plugins register namespaced (${pluginId}:${id}) export
formats with a label/extension/handler; the writing-studio built-in
plugin registers a trivial "sprint-summary" .txt export as a
worked example.

The plugin system lives entirely in the renderer process while the
Export menu is built in main.js, so wiring formats into the menu
required a small IPC round-trip: renderer sends format metadata to
main after plugin load (main rebuilds the menu via the already-
idempotent createMenu()), and a menu click sends the resolved save
path back to the renderer, which is the only process holding the
plugin's handler function.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 44624cd4bf feat(pdf): add form field detection, fill, and flatten
Adds pdfGetFormFields (lists AcroForm fields with name/type/value) and
pdfFillForm (fills text fields by name, optionally flattens) to
PDFOperations.js, dispatched via 'formFields'/'fillForm' in
executeOperation. pdfFillForm skips unknown/non-text fields per-field
(logs + continues) rather than failing the whole batch, matching the
partial-success precedent set by pdfExtractImages.

Wires a "Fill Form" entry into the PDF editor dialog: selecting a PDF
fetches its fields via a new get-pdf-form-fields/pdf-form-fields IPC
round trip and renders one text input per field, plus a flatten
checkbox, following the same structure as the crop/pageNumbers dialogs.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 2334ab30ed feat(pdf): add extract text, page numbers, crop, extract images operations
Adds four new PDFOperations: pdfExtractText (pdfjs-dist getTextContent),
pdfAddPageNumbers (reuses pdfWatermark's position-mapping logic, extracted
into a shared resolvePosition helper), pdfCrop (page.setCropBox against the
existing MediaBox), and pdfExtractImages (pdfjs-dist operator list +
paintImageXObject + sharp). Wired into executeOperation's switch and the PDF
editor dialog UI (4 new sections/toolbar buttons/menu items) with no new IPC
channel needed.

pdfjs-dist v5 is ESM-only, so it's loaded via dynamic import() of its
Node-friendly legacy build; Jest needs --experimental-vm-modules to support
that, so the test scripts now set NODE_OPTIONS accordingly via cross-env.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh abcfb03e52 feat(git): add diff, branch, checkout, push, pull to Git sidebar panel
Extends GitOperations.js with diff/branches/checkoutBranch/push/pull,
wires the 5 new IPC handlers in main.js (reusing the existing dir
resolution), whitelists the new channels in preload.js, and fixes the
Git sidebar panel's previously dead _gitDiff callback by wiring up a
diff view, branch list/create/checkout UI, and push/pull buttons.
Resolves Task 5, which deferred this work to this task.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 6ba3174480 feat(export): expose AsciiDoc, RST, MediaWiki, Org, Textile, man, ipynb export formats
Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh b83b86b31e feat(media): add batch folder mode to Image/Audio/Video Tools dialog
Reviewer follow-up on Task 12: the task's own title/brief called for
batch support and no later task in the plan picks it up, so this closes
that gap. Adds a "Single File" / "Batch Folder" mode toggle to the
existing media-operations-dialog.js; batch mode swaps the per-file
input/output fields for an Input Folder + "Include subfolders" +
Output Folder trio while keeping every other parameter (width/height/
quality/angle/startTime/duration/crf/fps/format/fit) applied uniformly
to every matching file. Disabled for audio "Merge", which combines many
inputs into one output and doesn't fit a per-file batch model.

main.js: adds collectFilesByExtension() (src/main/collectFilesByExtension.js,
unit tested), a generalization of the inline collectFiles() closure inside
ipcMain.on('universal-convert-batch', ...) to match a set of extensions
instead of one format. runMediaBatchOperation() loops
ImageOperations/AudioOperations/VideoOperations.executeOperation() over
the matched files, reporting per-file progress via new
'media-batch-progress' events and a final 'media-batch-complete' event,
then shows a "Batch Conversion Complete" dialog.showMessageBox with
completed/failed counts, mirroring performBatchConversion()'s pattern.
Wired via three new ipcMain.on handlers: batch-image-operation,
batch-audio-operation, batch-video-operation.

preload.js: whitelists the three new send channels and the two new
receive channels (media-batch-progress, media-batch-complete).
2026-08-23 19:31:33 +05:30
amitwh f271e27177 feat(media): add Image/Audio/Video Tools dialogs wired to new operation backends
Adds Tools > Image/Audio/Video Tools... menu items and a single dynamic
renderer dialog (src/renderer/media-operations-dialog.js) that lets the
user pick a media-kind-scoped operation, fill in its operation-specific
fields, and invoke process-image-operation/process-audio-operation/
process-video-operation (Tasks 9-11's backends). File selection reuses
the existing <input type="file"> + file.path convention; the one folder
picker need (video frame extraction) reuses the existing generic
select-folder/folder-selected IPC channels, so no new IPC handler was
required. Also removes the three dead electronAPI.image/audio/video
convenience blocks from preload.js (stale pre-Task-9-11 channel names,
unused everywhere).
2026-08-23 19:31:33 +05:30
amitwh 8dc1ae1c45 feat(video): implement ffmpeg-based video operations backend
Add src/main/VideoOperations.js with pure argument-builder functions
(buildConvertArgs, buildCompressArgs, buildTrimArgs, buildFramesArgs,
buildGifArgs) and a single executeOperation entry point that spawns
ffmpeg via dependency-injected execFileFn, mirroring AudioOperations.js.

Wire ipcMain.handle('process-video-operation', ...) in main.js using
getFFmpegPath() and sanitizeErrorMessage(). Update preload.js's
ALLOWED_SEND_CHANNELS: remove 6 stale video-* channel names, add
process-video-operation.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh a353a695b5 feat(audio): implement ffmpeg-based audio operations backend
Adds AudioOperations.js with pure argument builders (convert/trim/extract/merge)
plus one executeOperation that spawns ffmpeg via a dependency-injected execFileFn,
so tests never invoke a real binary. Wires process-audio-operation in main.js and
updates preload.js's ALLOWED_SEND_CHANNELS to replace the 5 stale audio-* entries.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 174eb3d6e9 style(image): apply Prettier formatting to ImageOperations test
Three lines in tests/main/ImageOperations.test.js (copied verbatim
from the task brief's sample) exceeded the project's 100-char width,
failing npm run format:check. Ran npm run format to auto-fix; no
behavioral change.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 8bada008b3 feat(image): implement sharp-based image operations backend
Add src/main/ImageOperations.js (convert/resize/compress/rotate via
sharp), modeled on PDFOperations.js's executeOperation dispatcher.
Wire ipcMain.handle('process-image-operation', ...) in main.js using
sanitizeErrorMessage() on error paths, and replace the 5 stale/unused
image-* channel names in preload.js's ALLOWED_SEND_CHANNELS with
process-image-operation + select-image-folder (mirroring
select-pdf-folder for a later batch-UI task).

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 949053a7c5 fix(deps): move jszip and sharp to runtime dependencies, unpack sharp from asar
- Add jszip (^3.10.1) to dependencies; keep version-pinned in overrides
- Move sharp (^0.34.3) from devDependencies to dependencies for Phase B runtime use
- Add node_modules/sharp/** to build.asarUnpack so native bindings are not packed

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh b80e34fcf5 fix(preload): whitelist monospace-setting-change channel
Reviewer caught that the new View > Monospace Font menu channel was
missing from preload.js's ALLOWED_RECEIVE_CHANNELS, the sole gap among
29 raw ipcRenderer.on(...) channels used in renderer.js. Add it under
the existing Font section for consistency with adjust-font-size.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 11b1c9e13e feat(settings): expose monospace font toggle in Settings UI
Add a View > Monospace Font menu (font family radio + ligatures
checkbox) — the app's existing reachable UI surface for this class of
preference (mirrors Theme/Font Size/Spell Check). The menu sends the
change to the renderer, which persists it via the already-working
ipcMain.handle('set-monospace-settings', ...) and applies it live via
the same applyMonospaceClasses() used on initial load.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh e09853952b fix(preload): whitelist show-document-compare channel
Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh d43fbaea59 fix(menu): wire Command Palette / Sidebar / Bottom Panel View-menu toggles 2026-08-23 19:31:33 +05:30
amitwh 66938968db fix(templates): wire New from Template menu to existing template-loading flow
Extract the sidebar Templates panel's inline load-into-new-tab callback into
a shared loadTemplateIntoNewTab() function, and add the missing
ipcRenderer.on('load-template-menu', ...) listener so the File > New from
Template submenu (which already sends this IPC event, already whitelisted in
preload.js) actually loads the selected template.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 5d9c46afc3 fix(menu): make Clear Recent Files actually clear the list
Extract the recent-files.json deletion logic into a standalone
clearRecentFilesOnDisk() function and call it from both the menu
click handler and the ipcMain.on handler. Previously the menu sent
the message in the wrong direction (main→renderer instead of
renderer→main), causing the feature to silently no-op. Both paths now
use the same function and send the correct 'recent-files-cleared'
notification to keep the renderer in sync.

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh bf3438902b fix(pdf): route Open PDF File menu item to the working editor dialog channel 2026-08-23 19:31:33 +05:30
amitwh edb5db358a docs: add implementation plan for feature audit, media converter, and security hardening
Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 6d564261b2 chore(release): bump version to 4.5.0
Monospace font embedding feature release. Adds bundled JetBrains Mono +
Fira Code TTFs (asarUnpack), preview/print font picker with ligatures
toggle, and embedded fonts in PDF (xelatex fontspec), DOCX (OOXML
surgery), EPUB (--epub-embed-font + OPF manifest), and HTML (sidecar
CSS with base64 data URI).
2026-08-23 19:31:33 +05:30
amitwh f5dcffeb8d test(monospace): add end-to-end smoke test for PDF/DOCX/EPUB/HTML font embedding
Exercises the real export pipeline against the bundled JetBrains Mono TTFs:
- PdfFontHeader emits valid xelatex fontspec with correct family + Ligatures=NoCommon
- ExportCss.build emits @font-face with base64 data URI
- DocxFontEmbedder injects TTFs into pandoc-produced DOCX (word/fontTable.xml + word/fonts/)
- EpubFontEmbedder.patchManifest adds TTF entry to OPF <manifest>
- HTML export links the sidecar CSS which embeds the font

Run with: node tests/smoke-e2e-monospace.js
2026-08-23 19:31:33 +05:30
amitwh 7095b34280 style: apply Prettier formatting
Run after full implementation to enforce 2-space / 100-char / single-quote
conventions across all new + adjacent files.
2026-08-23 19:31:33 +05:30
amitwh 58868eece0 feat(IPC): expose get-monospace-settings + set-monospace-settings to renderer
Renderer already calls window.electronAPI.invoke('get-monospace-settings')
to apply body classes; this wires up the channel allowlist and main-process
handlers so the IPC actually returns the active monospace settings and
persists updates.
2026-08-23 19:31:33 +05:30
amitwh cd3385ec69 build: asarUnpack assets/fonts/** so packaged builds can read bundled TTFs
MonospaceFontConfig + print-preview.js already look in app.asar.unpacked
first; without this entry the bundled TTFs would be unreachable at runtime.
2026-08-23 19:31:33 +05:30
amitwh f04a20252f feat(export): wire DOCX export through DocxFontEmbedder
Embeds regular + bold TTF of the active monospace family into pandoc's
DOCX output. ODT uses pandoc's built-in font handling; RTF has no font
embedding capability (documented limitation).
2026-08-23 19:31:33 +05:30
amitwh e5e14c88ce feat(monospace): DocxFontEmbedder injects TTF into pandoc DOCX output
Idempotent. Patches fontTable.xml, [Content_Types].xml, .rels, styles.xml.
2026-08-23 19:31:33 +05:30
amitwh 7a5a2ecba6 feat(monospace): EPUB export embeds TTF via --epub-embed-font + manifest patch 2026-08-23 19:31:33 +05:30
amitwh fac0d3d4a6 feat(export): wire HTML export to monospace ExportCss (pandoc + fallback) 2026-08-23 19:31:33 +05:30
amitwh 269d4ac028 feat(monospace): wire PDF export to use bundled monospace font
Replaces -V monofont=Consolas with a generated xelatex/lualatex header
that fontspec-loads the bundled JetBrains Mono or Fira Code TTF. Adds
a cached settings reader with proper invalidation on store.set, and
reorders fallback engines to prefer lualatex (fontspec-capable) before
pdflatex.
2026-08-23 19:31:33 +05:30
amitwh cdc318ebc7 feat(monospace): add PdfFontHeader builder for xelatex fontspec 2026-08-23 19:31:33 +05:30
amitwh 0c4043121f chore(pandoc): cache parsed major/minor version for capability checks 2026-08-23 19:31:33 +05:30
amitwh 151be60b03 feat(monospace): print-preview iframe uses bundled monospace font
Inlines @font-face as base64 data URI so the iframe srcdoc can render
JetBrains Mono / Fira Code without depending on the parent window's
loaded @font-face sets. Reads family + ligature state from the
renderer-wide cache populated by applyMonospaceClasses().

Amit Haridas
2026-08-23 19:31:33 +05:30
amitwh 228ee04b09 feat(monospace): ExportCss embeds woff2 as base64 in CSS
Self-contained CSS for HTML export and print-preview iframe.
2026-08-23 19:31:33 +05:30
amitwh 9fd81ff5a0 fix(ascii): replace Google Fonts CDN with local fonts.css
ASCII generator now renders in bundled JetBrains Mono without internet,
matching the preview pane.
2026-08-23 19:31:33 +05:30
amitwh f22cacd554 feat(monospace): renderer toggles body classes on settings change
applyMonospaceClasses() is the single source of truth. Reads from
'get-monospace-settings' IPC; Task 20 adds the handler.
2026-08-23 19:31:33 +05:30
amitwh 2f3b552608 feat(monospace): wire preview + editor to --font-mono-active token 2026-08-23 19:31:33 +05:30
amitwh cb27b47b91 feat(monospace): add --font-mono-active / --font-mono-feature tokens
Body classes (.mono-fira, .mono-ligatures-on) flip the tokens for live
switching without re-rendering.
2026-08-23 19:31:33 +05:30
amitwh 01e2df44ed feat(monospace): register Fira Code @font-face in renderer
Two weights: 400 (Regular) and 700 (Bold). TTF only — woff2 is
generated lazily if profile reports it; Fira ships in TTF upstream.
2026-08-23 19:31:33 +05:30
amitwh adfa43c278 chore(monospace): extend download-tools with Fira Code downloader
Matches the existing version-pinned approach for Pandoc.
2026-08-23 19:31:33 +05:30
amitwh 879600da46 feat(monospace): bundle JetBrainsMono + FiraCode TTF assets
Both families are SIL OFL. TTF (not just woff2) is required so xelatex can
embed into PDF and jszip can inject into DOCX.
2026-08-23 19:31:32 +05:30
amitwh 7b73ab07d7 feat(monospace): add MonospaceFontConfig path resolver
Resolves dev vs packaged (asar.unpacked) TTF paths. Logs warn, returns null
when bundled font is missing.
2026-08-23 19:31:32 +05:30
amitwh 57bbf91245 feat(monospace): add settings schema + safe defaults
getDefaults(), getActiveMonoFont(), isLigaturesEnabled() with TDD.
2026-08-23 19:31:32 +05:30
amitwh 5178d91187 docs(monospace): approve design for embedded monospace font in preview + all exports
Bundles JetBrains Mono + Fira Code TTFs in assets/fonts/. Embeds them into
DOCX (jszip), passes path via xelatex fontspec for PDF, base64-injects
@font-face for HTML/EPUB. Replaces Consolas (Windows-only) and Google Fonts
CDN load in the ASCII generator window.

Adds user-pickable monospace family + ligature toggle (default JBM, no
ligatures) for ASCII column alignment.

Closes: N/A
Refs: docs/superpowers/specs/2026-06-30-monospace-font-embedding-design.md

Amit Haridas
2026-08-23 19:31:32 +05:30
amitwh 3f0bf911a0 chore(repo-map): add auto-generated structural map
Generated with ~/.claude-shared/scripts/repo-map.sh (universal-ctags).
Signatures-only map of classes/functions/methods/interfaces/enums.

Amit Haridas
2026-07-18 07:23:25 +05:30
amitwh 2cac075c0e fix(word): harden DOCX preprocessing and temp-file cleanup
- Make the HTML preprocessor code-block and inline-code aware so code

  examples containing <style> / <div> / comments are preserved.

- Strip all raw <div> tags (not just alignment attributes) to avoid

  malformed output from unmatched closing tags.

- Handle uppercase tags and single/unquoted attributes.

- Create temporary DOCX input files inside private mkdtemp directories

  instead of predictable names in the shared temp directory.

- Wrap batch DOCX preprocessing in try/catch so one unreadable file

  does not abort the entire batch.

- Add regression tests for the edge cases above.
2026-06-30 19:57:40 +05:30
amitwh 94906a068a chore(release): bump version to 4.4.5 2026-06-30 13:57:34 +05:30
amitwh e72b863362 fix(word): strip HTML style blocks and alignment divs from DOCX input
Pre-process markdown before Word/DOCX export to remove raw HTML artifacts

(<style> blocks, HTML comments, and <div align=...> tags) that were

visible in the generated document. Applies to single and batch DOCX exports

via both Pandoc and WordTemplateExporter paths.
2026-06-30 13:57:29 +05:30
amitwh d705cfc30b fix(batch): resolve pandoc path handling and include-subfolders option
- Normalize pandoc command parsing with path.basename() to support bundled binary paths
- Use bundled pandoc binary in convertWithPandoc instead of relying on PATH
- Forward includeSubfolders checkbox state from renderer to main process
- Add pandoc availability check before batch conversion
- Re-enable Start button when batch conversion completes
- Clean up obsolete dist build artifact causing test snapshot warning
- Bump version to 4.4.4
2026-06-30 12:56:33 +05:30
amitwh 02e307f758 docs(claude-md): add tailored CLAUDE.md for master branch
Documents project architecture, Pandoc dependency resolution, build
pipeline (electron-builder, no bundler), security model notes
(contextIsolation: false on this branch), and development commands
extracted from actual package.json and source.

Amit Haridas
2026-06-19 23:18:00 +05:30
amitwh 5ad1d1d4b3 chore(release): bump version to 4.4.3 2026-06-11 21:17:37 +05:30
amitwh f480449301 fix(renderer): resolve syntax errors and undefined electronAPI on startup 2026-06-11 21:15:25 +05:30
amitwh 96df5652d6 fix: resolve list-directory IPC handler closing brace syntax error 2026-05-26 11:39:57 +05:30
amitwh a9e05d2c0f feat: implement Custom Preview CSS, Reveal.js options, Large File Mode, and Interactive PDF Thumbnail Sidebar 2026-05-25 23:11:47 +05:30
amitwh c982b3e90f chore(diagnostics): add logging to _renderPreview to trace markdown rendering
This will help identify whether the issue is:
1. marked.parse returning a Promise instead of string
2. DOMPurify.sanitize failing
3. The preview element not existing
4. Libraries not being loaded

Amit Haridas
2026-05-25 00:32:27 +05:30
amitwh cfaafc07b2 chore(deps): update vulnerable packages to patched versions
Updated packages:
- simple-git 3.32.3 → 3.36.0 (RCE vulnerability)
- fast-uri 3.1.0 → 3.1.2 (host confusion, path traversal)
- dompurify 3.3.1 → 3.4.5 (XSS bypasses)
- mermaid 11.13.0 → 11.15.0 (CSS injection, DoS)
- uuid 11.1.0 → 11.1.1 (buffer bounds check)
- ws 8.20.0 → 8.20.0 (uninitialized memory)
- ip-address 10.1.0 → 10.2.0 (XSS)
- @xmldom/xmldom 0.8.11 → 0.9.10 (XML injection, DoS)
- docx4js 3.3.0 → 2.0.1 (breaks xml2js dep chain)
- brace-expansion (transitive update)

Also applied lint:fix autofix (const correctness).

Amit Haridas
2026-05-25 00:00:28 +05:30
amitwh 94ad99dc4d fix(renderer): ensure tab content visibility after file open
- Add missing updateUI() call at end of openFile() to set .active class
  on tab content. Without this, the CSS rule .tab-content:not(.active)
  { display: none } kept newly opened files invisible.
- Add diagnostic logging to file-opened IPC handler and openFile()
  to trace future file loading issues.
- Add diagnostic logging to openFileFromPath() in main process.

Amit Haridas
2026-05-24 23:54:31 +05:30
amitwh baf644d62b fix(modal): prevent duplicate ModalManager declaration
window.ModalManager was set unconditionally, causing "Identifier
'ModalManager' has already been declared" when script tag in HTML
also loaded ModalManager before renderer.js required it.

Now checks !window.ModalManager before setting.

Amit Haridas
2026-05-22 22:08:06 +05:30
amitwh f9a5420ad2 4.4.1: update version everywhere, fix DOMPurify initialization
- Bump version to 4.4.1
- DOMPurify now initialized with window context (fixes markdown rendering)
- Add 'it' to eslint globals

Amit Haridas
2026-05-22 21:54:05 +05:30
amitwh f8361174f2 chore: add it to eslint globals, add debug logging to createEditor
Amit Haridas
2026-05-22 21:42:34 +05:30
amitwh 64df0660c8 fix(renderer): initialize DOMPurify with window context
require('dompurify') returns a factory function, not a sanitizer
instance. Calling .sanitize() on the factory threw a TypeError,
which was caught by the preview renderer's try-catch and displayed
a generic "Error rendering preview" message. Fix by invoking the
factory with the renderer's window object.

Amit Haridas
2026-05-03 16:38:47 +05:30
amitwhandCopilot bbfa2a38e9 security: add permission request handler for security isolation
Restrict Electron permission requests to only clipboard operations.
Deny: camera, microphone, geolocation, notifications, and all other
permissions by default.

Implements setPermissionRequestHandler on web-contents-created event
to enforce security policy early in the app lifecycle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-24 17:19:52 +05:30
amitwhandCopilot 94ec3f45ce fix: show dynamic app version everywhere in UI
- Add get-app-version IPC handler in main.js (returns app.getVersion())
- Expose electronAPI.getAppVersion() in preload.js
- index.html: replace hardcoded v4.2.0 span with dynamic population
  from getAppVersion() in DOMContentLoaded
- welcome.js: accept appVersion param instead of hardcoded 4.1.0
- renderer.js: pass live version to createWelcomeContent()
- main.js about screen: use app.getVersion() instead of hardcoded 4.1.0
- Update stale @version 4.1.0 JSDoc comments to 4.3.0

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 23:31:18 +05:30
amitwhandCopilot a6747b12f0 fix: pass --publish=never to electron-builder in CI
electron-builder detects git tags in CI and tries to auto-publish to
GitHub, failing with 'GH_TOKEN not set'. We handle the release
separately via softprops/action-gh-release, so suppress auto-publish.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 23:16:20 +05:30
amitwhandCopilot 7a641b2618 fix: use deb+AppImage only in CI, release job continues if build fails
- Add build:linux-ci script (deb + AppImage, no snap — snapcraft not
  available on ubuntu-latest runners without extra setup)
- Switch release.yml linux build to npm run build:linux-ci
- release job: if: always() so Windows artifacts still get released
  even if linux build fails
- Download artifact steps: continue-on-error so missing platform
  doesn't block GitHub Release creation

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 23:07:09 +05:30
amitwhandCopilot edefcb8409 fix: drop rpm build target and stale system tool depends
- Remove rpm from linux build targets (rpmbuild not available locally)
  CI can add it back with apt-get if needed, but pandoc/ffmpeg are now
  bundled so the rpm depends were incorrect anyway
- Remove rpmbuild apt install step from release.yml (not needed)
- Remove pandoc/ffmpeg from deb depends — they are now bundled binaries
- Keep imagemagick and libreoffice-common in deb depends (not bundled)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 23:00:00 +05:30
amitwhandCopilot 5ee986fab8 fix: bundle pandoc+ffmpeg, fix CI pipeline and Windows GitHub build
- Remove package-lock.json from .gitignore so npm ci works in CI
- Refactor main.js: delegate PDF ops to src/main/PDFOperations.js,
  git ops to src/main/GitOperations.js
- getPandocPath(): use bundled binary from resources/bin/ when packaged,
  fall back to dev bin/ or system pandoc in development
- getFFmpegPath(): use ffmpeg-static (asarUnpack) when packaged
- Install ffmpeg-static (v5.3.0, bundled 76MB binary)
- Add scripts/download-tools.js to fetch pandoc binary at build time
  (idempotent, runs on CI before electron-builder)
- electron-builder: add asarUnpack for ffmpeg-static, extraFiles for
  pandoc binary per platform (linux + win32)
- release.yml: switch build-windows to windows-latest runner with native
  NSIS support; add cert decode step; add download-tools step for both
  linux and windows jobs
- Fix lint error: hoist outlinePanelContainer to module scope so
  TabManager methods can reference it without no-undef errors

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 22:56:41 +05:30
amitwh c1573dba08 feat(writing-studio): add four sidebar panels (goals, snapshots, manuscript, proofread)
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 9576abc979 feat(writing-studio): add plugin manifest and entry point
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh caa3f3d35a feat(writing-studio): add project manager with compile and stats
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 2a6f0fc302 feat(writing-studio): add snapshot manager with diff and prune
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 4da5b7b9c4 feat(writing-studio): add goal tracker with streaks and history
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 1ba42592d7 feat(writing-studio): add sprint engine with WPM tracking
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh bc6f1a7d41 docs(writing-studio): add implementation plan for Writing Studio plugin
12 tasks across 9 chunks: SprintEngine, GoalTracker, SnapshotManager,
ProjectManager, manifest+entry point, 4 sidebar panels, CSS, timer UI.

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 539502d7ff feat(plugins): wire plugin system into app initialization
- Add plugin system bootstrap in renderer.js after sidebar/commands init
- Wire status bar DOM insertion, editor API, and IPC adapters
- Add plugin-settings:get/set IPC channels to preload allowlist
- Add IPC handlers in main process using existing settings store
- Fix eqeqeq warning in EventBus.hasHandler

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh b5771dd914 feat(plugins): add sample plugin demonstrating the system
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh a816b6ec32 feat(plugins): add PluginContext, PluginRegistry, and SettingsStore
- PluginContext: scoped API with crash-safe command wrappers
- PluginRegistry: lifecycle management with graceful init failure
- SettingsStore: plugin-scoped key/value via IPC backend
- Export hooks: pre/post hooks on registry for cross-plugin integration

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 54c9484cb5 feat(plugins): add PluginLoader with manifest discovery and validation
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 36e26318cd feat(plugins): add PluginAPI base class with no-op lifecycle
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 8abd580295 feat(plugins): add EventBus with typed events and crash-safe handlers
Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 80294c9876 docs: add plugin system implementation plan
9 tasks across 8 chunks, strict TDD:
- EventBus with crash-safe handlers
- PluginAPI base class
- PluginLoader with manifest validation
- PluginContext with scoped API
- PluginRegistry with lifecycle management
- SettingsStore for plugin-scoped settings
- Export hooks integration
- Sample plugin + renderer wiring

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh 148b549c83 docs: harden v5.0 spec based on review
- GGUF GPU: child process isolation with crash detection/restart
- Event bus: versioned payload schemas for all events
- Plugin sandbox: 5s handler timeout, IPC delegation for heavy ops
- AI streaming: full lifecycle with requestId, cancel, heartbeat, orphan cleanup
- Comment anchors: context-based positioning (not byte offsets) with re-anchor on file change
- Cross-plugin: capability discovery, 30s timeout, graceful degradation
- Bundle size: GPU variants as lazy downloads, not bundled by default
- Command uniqueness: registry rejects duplicates at load time

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwh a3b4065984 docs: add v5.0 platform design spec
Plugin-first architecture with four subsystems:
- Plugin system (registry, context API, event bus)
- Writing Studio (manuscript manager, sprints, snapshots, proofreading)
- AI Assistant (multi-provider: Ollama, LMStudio, GGUF+GPU, cloud APIs)
- Collaboration (git-based async, comments, review requests)

Amit Haridas
2026-04-23 22:55:12 +05:30
amitwhandCopilot 620227307d release: v4.3.0 - fix Windows SmartScreen blocking, add signing support
- Remove signAndEditExecutable:false so code signing works properly
- Add legalTrademarks and copyright metadata to build config
- Add publisherName via build.copyright (embedded in PE resources)
- Create scripts/create-selfsigned-cert.ps1 for local dev signing
- Update release.yml: build on windows-latest runner (not Wine),
  auto-sign when CSC_LINK_BASE64/CSC_KEY_PASSWORD secrets present,
  fall back to unsigned otherwise
- Add lint step to ci.yml (Phase 4.3 plan gap)
- Add .vscode/launch.json debug configs (Phase 4.3 plan gap)
- Fix .gitignore: exclude *.pfx/*.p12 cert files, track launch.json,
  fix concatenated agents.md/coverage/ lines

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-19 18:20:19 +05:30
amitwh 4426b75c6f fix: improve tab safety and app feedback 2026-04-14 22:30:46 +05:30
amitwh b7e12f7010 fix(deps): resolve all dependabot vulnerabilities
- Upgrade electron 37 -> 41
- Override lodash-es to patched version
- Zero vulnerabilities remaining

Amit Haridas
2026-04-06 20:51:41 +05:30
amitwh f0ab54cd60 chore: bump to v4.2.0 — Writer's Studio Feature Pack
Amit Haridas
2026-04-06 11:44:29 +05:30
amitwh 72a7a854d0 feat(analytics): add writing analytics with readability scores and vocabulary analysis
Amit Haridas
2026-04-06 11:42:22 +05:30
amitwh 50d0638c5c feat(zen): add distraction-free writing mode with typewriter scrolling
Zen mode hides all chrome and centers the editor with typewriter
scrolling, line dimming, and a floating word count HUD.
Toggle with F11, exit with Escape.

Amit Haridas
2026-04-06 11:37:51 +05:30
amitwh 7a3493e54f fix(outline): add tab-switch refresh and dark mode styles
Amit Haridas
2026-04-06 11:05:54 +05:30
amitwh b1a5784bcc feat(outline): add document outline sidebar panel with heading navigation
Amit Haridas
2026-04-06 10:40:29 +05:30
amitwh 24cb99658e docs: add Writer's Studio implementation plan
Detailed step-by-step plan for Zen Mode, Document Outline,
and Writing Analytics with exact file paths and code.

Amit Haridas
2026-04-06 07:47:35 +05:30
amitwh c042cf4580 docs: add Writer's Studio feature pack design
Design for three cohesive features: Zen Mode, Document Outline,
and Writing Analytics. Approved for v4.2.0.

Amit Haridas
2026-04-06 07:36:18 +05:30
amitwh ed4279f4df feat: bump to v4.1.0 and add CI/CD release pipeline
- Bump version to 4.1.0 in package.json and index.html
- Add build:local script for combined Linux + Windows local builds
- Add CI workflow: runs tests on push/PR to master
- Add Release workflow: tag-triggered (v*), parallel Linux + Windows
  builds, publishes all packages to GitHub Releases

Amit Haridas
2026-03-25 22:20:53 +05:30
amitwh adc8dabda1 fix: resolve modal stacking, animation, and close cleanup bugs
- Set backdrop z-index:0 and content z-index:1 to fix backdrop covering
  modal content within the stacking context
- Force reflow between removing hidden and adding open class so CSS
  opacity transition fires correctly
- Add transitionend listener + setTimeout fallback to restore hidden
  class after close animation completes
- Override flex:1 on modal footer buttons to prevent full-width stretch
- Add min-width to modal size variants for consistent sizing
- Add 23 tests covering open/close lifecycle, keyboard, and destroy

Amit Haridas
2026-03-25 22:20:34 +05:30
amitwh 5911a7501b fix: guard window assignment for CommonJS compatibility 2026-03-24 22:37:40 +05:30
amitwh d998b03ca1 fix: remove ES6 export keyword for browser compatibility 2026-03-24 19:08:14 +05:30
amitwh 31468e77c5 refactor: remove old dialog CSS in favor of unified modal system
Amit Haridas
2026-03-24 16:50:09 +05:30
amitwh 2022352ed1 refactor: update renderer.js to use ModalManager for all dialogs
- Import ModalManager and create instances for all 10 dialogs
- Replace classList.add/remove('hidden') with modal.open()/close()
- Remove duplicate backdrop click and escape key handlers (now handled by ModalManager)
- Update print-preview.js to use ModalManager when available
- Add CommonJS export to ModalManager for renderer compatibility

Dialogs updated:
- find-dialog (findModal)
- export-dialog (exportModal)
- print-preview-overlay (printPreviewModal)
- table-generator-dialog (tableModal)
- ascii-art-dialog (asciiModal)
- universal-converter-dialog (converterModal)
- batch-dialog (batchModal)
- pdf-editor-dialog (pdfEditorModal)
- header-footer-dialog (headerFooterModal)
- field-picker-dialog (fieldPickerModal)

Amit Haridas
2026-03-24 16:44:20 +05:30
amitwh 6bac18d270 feat: convert all dialogs to unified modal structure
Convert 10 dialogs from old classes (.export-dialog, .batch-dialog, .find-dialog)
to the new unified .modal structure with proper accessibility attributes.

Changes:
- find-dialog: small modal with find/replace controls
- export-dialog: large modal with export options
- print-preview-overlay: full-size modal for print preview
- table-generator-dialog: default modal for table creation
- ascii-art-dialog: large modal for ASCII art generation
- universal-converter-dialog: large modal for file conversion
- batch-dialog: large modal for batch processing
- pdf-editor-dialog: full-size modal for PDF editing
- header-footer-dialog: default modal for header/footer config
- field-picker-dialog: small modal for field selection

All dialogs now include:
- role="dialog" and aria-modal="true" for accessibility
- aria-labelledby pointing to title element
- .modal-backdrop with data-close attribute
- .modal-content with appropriate size class
- .modal-header with title and close button
- .modal-body for content
- .modal-footer with action buttons

Amit Haridas
2026-03-24 16:30:52 +05:30
amitwh fdfd778d94 feat: include modal.css and ModalManager in index.html
Amit Haridas
2026-03-24 16:23:59 +05:30
amitwh 30f6198f1d feat: add modal CSS with glassmorphism and animations
Amit Haridas
2026-03-24 16:22:41 +05:30
amitwh 253608e17f feat: add ModalManager class for unified modal system
Amit Haridas
2026-03-24 16:20:03 +05:30
amitwh 763bea2a87 docs: add modal system implementation plan 2026-03-24 14:01:30 +05:30
amitwh 73795d1ad8 docs: add modal system design document 2026-03-24 13:53:27 +05:30
amitwh f81426f019 security: fix all npm vulnerabilities
- Remove unused xlsx dependency (had unfixable vulnerabilities)
- Add npm overrides to force secure versions:
  - jszip ^3.10.1 (fixes path traversal)
  - nth-check ^2.1.1 (fixes ReDoS)
  - lodash.pick -> lodash ^4.17.21 (fixes prototype pollution)

Result: 0 vulnerabilities (was 11)

Amit Haridas
2026-03-24 10:04:21 +05:30
amitwh fe4d634163 feat: add Shadcn/ui design tokens and accessibility improvements
- Add src/styles/tokens.css with comprehensive design tokens
- Define color tokens (primary, secondary, accent, destructive, etc.)
- Add spacing, typography, shadow, and transition tokens
- Include dark mode token overrides
- Add utility classes (btn, badge, input variants)
- Add skip-link for keyboard navigation
- Update index.html to include tokens.css

This enables consistent theming and easier future UI updates.

Amit Haridas
2026-03-24 09:55:18 +05:30
amitwh 3bc703d8dc feat: add platform adapter structure for V4
- Create adapters/types.js with comprehensive type definitions
- Create adapters/electron/fs.js for file system operations
- Prepare structure for future migration to Tauri/Flutter

This abstraction layer makes future platform migration easier
and enables better testing with mock adapters.

Amit Haridas
2026-03-24 09:06:21 +05:30
amitwh 78200b8d6a perf: add debounced preview rendering for better typing performance
- Add previewDebounceTimers map to track debounce timers per tab
- Add updatePreview(tabId, immediate) with optional immediate flag
- Debounce preview updates during typing (300ms delay)
- Use immediate=true for tab switches and file loads
- Refactor _renderPreview as internal method

This significantly improves editor responsiveness when typing
in large markdown files.

Amit Haridas
2026-03-24 08:59:49 +05:30
amitwh 0987058aa2 fix: integrate PDF viewer into tab system for multitab support
- Add tab type system ('markdown' and 'pdf')
- Create PDF tabs with their own state (page, zoom, rotation)
- Update closeTab to properly clean up PDF resources
- Update updateUI to handle PDF tabs (hide toolbar, etc.)
- Add visual indicators for PDF tabs in tab bar
- Add CSS styles for PDF tab containers

Fixes: PDF and markdown multitab function not working

Amit Haridas
2026-03-24 08:55:39 +05:30
amitwh cbf0b4897d docs: add V4 enhancement + Flutter exploration design
- 70% V4 enhancements: fix multitab bug, performance optimizations,
  platform adapters, Shadcn/ui patterns
- 30% Flutter exploration: prototype for Windows, Mobile, Web evaluation

Amit Haridas
2026-03-24 00:10:47 +05:30
amitwh f1740c6bb6 docs: add detailed implementation plan for v5.0 migration
Phase 1 (Foundation) tasks with step-by-step instructions:
- Task 1-2: Project initialization (Vite, React, TypeScript)
- Task 3-4: Tailwind CSS + Shadcn/ui configuration
- Task 5: Zustand stores (editor, settings, theme, sidebar)
- Task 6-8: Platform adapter pattern (types, web, tauri stubs)
- Task 9: Tauri project initialization
- Task 10: Basic layout components

Each task includes:
- Exact file paths
- Complete code snippets
- Build verification steps
- Commit messages

Amit Haridas
2026-03-15 09:57:51 +05:30
amitwh 8319953ccf docs: add React + Tauri + PWA architecture design for v5.0
Comprehensive design document covering:
- Project structure with platform adapters
- React component architecture
- Zustand state management
- Platform adapter pattern (Tauri + Web)
- Build configuration (Vite, Tailwind, TypeScript)
- Tauri backend (Rust) IPC commands
- PWA configuration with Service Worker
- 8-week migration plan
- Security improvements over Electron

Approved design for parallel development alongside v4.x

Amit Haridas
2026-03-15 09:53:18 +05:30
amitwh 95ea870039 feat: apply JetBrains Mono font to editor and preview code
- Add custom EditorView.theme for CodeMirror 6 with JetBrains Mono
- Update .editor-textarea and #editor font-family to prioritize JetBrains Mono
- Update preview code blocks (#preview code, .preview-content code) to use JetBrains Mono
- Ensures consistent monospace font across editor source and markdown rendering

Amit Haridas
2026-03-15 08:39:53 +05:30
amitwh d1c2c1c109 refactor: standardize dark theme selectors and add CSS variables
CSS improvements:
- Standardize dark theme selectors to body[class*="dark"] pattern
- This ensures all dark themes (theme-dark, theme-dracula, etc.)
  receive consistent styling
- Add semantic color variables (--text-primary, --bg-primary, etc.)
- Replace hardcoded colors with CSS variables in:
  - Tab bar component
  - Toolbar separator
  - Pane resizer
  - Status bar
- Add fallback values for backward compatibility

This improves maintainability and makes theming more consistent.

Amit Haridas
2026-03-15 00:50:10 +05:30
amitwh daae83bcf4 a11y: add comprehensive focus and accessibility styles
Accessibility improvements:
- Add global focus-visible styles for keyboard navigation
- Add focus-visible for sidebar panel close button
- Add skip-link styles for screen reader users
- Add .sr-only class for visually hidden content
- Add prefers-reduced-motion support for users sensitive to motion
- Add prefers-contrast: high support for high contrast mode

Amit Haridas
2026-03-15 00:42:41 +05:30
amitwh 7723b302ea style: improve CSS organization and add state components
CSS improvements:
- Remove duplicate CSS reset from styles-modern.css
- Add focus-visible styles for sidebar icons
- Add error/loading state components (skeleton, spinner, messages)
- Add success, warning, info message components
- Add dark theme support for new components

Code quality:
- Replace inline error style with CSS class in renderer.js

Amit Haridas
2026-03-15 00:41:11 +05:30
amitwh 94506ccb00 security: harden CSP, add path traversal protection, improve accessibility
Security fixes:
- Remove external CDN sources from CSP (cdn.jsdelivr.net, cdnjs.cloudflare.com)
- Add path validation functions to prevent path traversal attacks
- Block access to sensitive system directories
- Add isPathAccessible() check for file operations

UI/Accessibility fixes:
- Increase tab close button from 16px to 24px for better touch targets
- Add focus-visible styles for keyboard navigation
- Add ARIA labels to all toolbar buttons
- Add aria-hidden="true" to decorative SVG icons
- Add role="tablist" and role="tab" to tab bar
- Fix duplicate font-size declaration in .preview-content

Reports generated:
- Security vulnerability scan (10 findings)
- STRIDE threat model with MITRE ATT&CK mapping
- Comprehensive UI design review (40 issues)

Amit Haridas
2026-03-15 00:38:58 +05:30
amitwh 01d833f520 fix: resolve editor, batch conversion, and startup performance issues
- Remove popout preview button (HTML, JS, CSS)
- Fix Save/Save As flow for new untitled files
- Fix batch conversion menu items (wire show-batch-converter IPC)
- Add universal-convert-batch IPC handler for batch file conversion
- Lazy-load mermaid, pdfjs-dist, sidebar panels, command palette
- Switch highlight.js CSS from CDN to local
- Defer CodeMirror language extensions until first use
- Add show:false + ready-to-show for faster perceived startup
- Install mermaid as local dependency (remove CDN script tag)
2026-03-04 17:44:04 +05:30
amitwh 10d2fc8b8f fix: resolve lint errors for v4 release
- Fix duplicate editorContainer declaration in renderer.js
- Add missing browser globals to eslint config (prompt, FileReader, etc.)
- Add global object for Jest test setup
- Replace path.basename with portable string split in logo preview
2026-03-04 16:35:56 +05:30
amitwh 0344a48f20 docs: add v4.0.0 changelog 2026-03-04 16:33:38 +05:30
amitwh 3c11ac15ce feat: update application menu with all v4 features 2026-03-04 16:33:00 +05:30
amitwh c5a9881d8d feat: update preload.js with all v4 IPC channels 2026-03-04 16:31:28 +05:30
amitwh 15903e782a test: add comprehensive tests for v4 features
Add unit tests for sidebar manager, command palette, print preview,
main process utilities, and markdown extensions. Update jest config
to exclude untestable Electron-specific files from coverage and
raise coverage thresholds.
2026-03-04 16:28:36 +05:30
amitwh 336b24365d feat: add welcome tab, presentation/publishing exports, and spell checking
- Developer format support (JSON, YAML, XML, TOML) import/export
- Presentation export (Reveal.js slides, Beamer PDF)
- Publishing format exports (Confluence wiki, MOBI e-book)
- Enable system spell checking with context menu suggestions
- Add welcome tab with onboarding and feature showcase
2026-03-04 16:24:05 +05:30
amitwh b5409b7754 feat: add developer format support (JSON, YAML, XML, TOML) 2026-03-04 16:23:37 +05:30
amitwh d3afd7ad86 feat: wire up sidebar panels and REPL with IPC handlers, preload channels, and CSS 2026-03-04 16:17:38 +05:30
amitwh 59ef2028f8 feat: add code execution REPL with JS, Python, Bash support 2026-03-04 16:17:34 +05:30
amitwh f62a6b7e59 feat: add code snippets sidebar panel with CRUD 2026-03-04 16:17:30 +05:30
amitwh f650b04685 feat: add Git sidebar panel (status, stage, commit, log) 2026-03-04 16:17:26 +05:30
amitwh 04480c1243 feat: add File Explorer sidebar panel 2026-03-04 16:17:22 +05:30
amitwh 81a78412fd feat: add PlantUML diagram support alongside Mermaid 2026-03-04 16:10:47 +05:30
amitwh 12dcd2d1a3 feat: add document templates library with 10 templates 2026-03-04 16:10:24 +05:30
amitwh ae7b333cea feat: add image paste and drag-drop support 2026-03-04 16:08:55 +05:30
amitwh e2703d8c57 feat: add markdown extensions (footnotes, admonitions, TOC) 2026-03-04 16:08:22 +05:30
amitwh ca0b250506 feat: add custom print preview dialog with configurable options 2026-03-04 16:04:51 +05:30
amitwh 9348b2bd1d security: add file size validation, error sanitization, and rate limiting 2026-03-04 16:00:57 +05:30
amitwh 200e800eb2 security: add Content Security Policy meta tag 2026-03-04 16:00:53 +05:30
amitwh a6456a7b4c feat: add breadcrumb bar showing current file path
Display the active file path below the toolbar with dark theme
support and monospace font for path readability.
2026-03-04 15:56:55 +05:30
amitwh 3908df8b1d feat: add command palette (Ctrl+Shift+P)
Refactor inline command palette into a proper CommandPalette class
with search highlighting, keyboard navigation, and overlay UI.
Register all app actions including formatting, file ops, and sidebar
toggles.
2026-03-04 15:56:24 +05:30
amitwh 72ee803a95 feat: reorganize toolbar into grouped sections with separators
- Grouped toolbar buttons into logical sections: Format, Structure, Insert, View
- Added toolbar-group CSS class for visual grouping
- Updated button titles with keyboard shortcut hints
- Enhanced status bar HTML structure with left/right layout
2026-03-04 15:50:36 +05:30
amitwh 37502fb733 feat: enhanced status bar with word count, char count, line/col, encoding
- Restructured status bar into left/right sections with separators
- Added character count, cursor line/column position, encoding, and language mode indicators
- Added cursor position tracking via CodeMirror onUpdate callback
- Added file path display that updates on tab switch
- Simplified word count display for cleaner status bar layout
2026-03-04 15:50:31 +05:30
amitwh affe1a7e33 feat: add sidebar panel system with icon strip and panel toggle 2026-03-04 15:45:34 +05:30
amitwh ed48f254f1 feat: migrate find/replace to use CodeMirror search 2026-03-04 15:42:09 +05:30
amitwh 0c2b6fe5cc feat: migrate undo/redo to CodeMirror built-in history 2026-03-04 15:41:33 +05:30
amitwh 233225f12c feat: replace textarea with CodeMirror 6 editor 2026-03-04 15:38:33 +05:30
amitwh 47f3b7557e feat: add CodeMirror 6 wrapper module 2026-03-04 15:31:42 +05:30
amitwh 7678c61602 chore: add v4 dependencies (CodeMirror extensions, simple-git, marked plugins) 2026-03-04 15:30:01 +05:30
amitwh 6e7460def7 chore: update html2pdf.js and pdfkit 2026-03-04 15:29:22 +05:30
amitwh bf67156b9c feat: upgrade pdfjs-dist from 3.x to 5.x for improved PDF viewer
Update worker path from .js to .mjs to match the new ESM-only build
structure in pdfjs-dist v5. Core API (getDocument, getPage, render)
remains compatible.
2026-03-04 15:28:07 +05:30
amitwh 824f659e13 feat: upgrade marked to v17 with marked-highlight extension
- Update marked from ^16.2.1 to ^17.0.3
- Add marked-highlight ^2.2.3 for syntax highlighting support
- Replace deprecated marked.setOptions() with marked.use() in renderer.js
- Extract highlight config into markedHighlight() extension (required in v17)
- Update test mock to reflect new API (use instead of setOptions)
2026-03-04 15:24:46 +05:30
amitwh e7eff01db6 chore: update non-breaking dependencies (dompurify, docx, highlight.js, pdf-lib) 2026-03-04 15:22:18 +05:30
amitwh 7b15b2808e chore: bump version to 4.0.0 2026-03-04 15:20:25 +05:30
180 changed files with 64603 additions and 10272 deletions
+28
View File
@@ -0,0 +1,28 @@
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
test:
runs-on: ubuntu-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: Run tests
run: npm test
- name: Run linter
run: npm run lint
+122
View File
@@ -0,0 +1,122 @@
name: Release
on:
push:
tags: ['v*']
permissions:
contents: write
jobs:
build-linux:
runs-on: ubuntu-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 Linux packages
run: npm run build:linux-ci -- --publish=never
- name: Upload Linux artifacts
uses: actions/upload-artifact@v4
with:
name: linux-artifacts
path: |
dist/*.deb
dist/*.AppImage
dist/*.snap
dist/*.rpm
retention-days: 5
build-windows:
runs-on: windows-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: Decode certificate (if available)
if: ${{ env.CSC_LINK_BASE64 != '' }}
shell: pwsh
env:
CSC_LINK_BASE64: ${{ secrets.CSC_LINK_BASE64 }}
run: |
$bytes = [Convert]::FromBase64String("$env:CSC_LINK_BASE64")
[IO.File]::WriteAllBytes("${{ github.workspace }}\code-signing-cert.pfx", $bytes)
echo "CERT_AVAILABLE=true" >> $env:GITHUB_ENV
- name: Build Windows packages (signed)
if: ${{ env.CERT_AVAILABLE == 'true' }}
env:
CSC_LINK: code-signing-cert.pfx
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
run: npm run build:win-signed -- --publish=never
- name: Build Windows packages (unsigned)
if: ${{ env.CERT_AVAILABLE != 'true' }}
env:
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
run: npm run build:win-unsigned -- --publish=never
- name: Upload Windows artifacts
uses: actions/upload-artifact@v4
with:
name: windows-artifacts
path: |
dist/*.exe
dist/*.zip
retention-days: 5
release:
needs: [build-linux, build-windows]
if: always()
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download Linux artifacts
uses: actions/download-artifact@v4
continue-on-error: true
with:
name: linux-artifacts
path: dist
- name: Download Windows artifacts
uses: actions/download-artifact@v4
continue-on-error: true
with:
name: windows-artifacts
path: dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
files: dist/*
+14 -2
View File
@@ -8,14 +8,22 @@ Thumbs.db
*.swp
*.swo
*~
.vscode/
.vscode/*
!.vscode/launch.json
.idea/
*.iml
out/
.cache/
.npm/
.electron/
package-lock.json
# package-lock.json is intentionally tracked for reproducible CI builds
# Downloaded tool binaries (fetched at build time via scripts/download-tools.js)
bin/
# Code signing certificates — never commit private keys
*.pfx
*.p12
# Screenshots and temp files
*.png.bak
@@ -34,3 +42,7 @@ pdf\ modal.png
.claude/
CLAUDE.md
agents.md
coverage/
# Superpowers brainstorm artifacts
.superpowers/
@@ -0,0 +1,469 @@
# Security Assessment Report: MarkdownConverter v4.0.0
**Assessment Date:** 2026-03-15
**Application:** MarkdownConverter - Electron-based Markdown editor and document converter
**Target Version:** 4.0.0
**Assessor:** Security Audit Agent
---
## Executive Summary
This assessment identified **10 security findings** ranging from **Critical to Low severity**. The most significant concerns involve insecure Electron security configuration that could allow XSS attacks to escalate to full system access, arbitrary code execution via the REPL feature, and missing input validation on file operations.
| Severity | Count |
|----------|-------|
| Critical | 2 |
| High | 3 |
| Medium | 3 |
| Low | 2 |
---
## Vulnerability Findings
### CVE-MC-001: Insecure Electron Security Configuration (Critical)
**CVSS 3.1 Score: 9.6 (Critical)**
**CWE-265: CWE-1021: Improper Restriction of Renderers**
**Location:** `src/main.js` (lines 328-332)
```javascript
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
spellcheck: true
},
```
**Description:**
The main application window has `nodeIntegration: true` and `contextIsolation: false`, which is the most insecure Electron configuration. This allows the renderer process direct access to Node.js APIs, meaning any XSS vulnerability in the markdown rendering or external content could lead to full system compromise.
**Exploitability:**
- An attacker who can inject malicious JavaScript (via markdown files, XSS in preview, or compromised dependencies) gains immediate access to:
- Full file system read/write via `fs` module
- Command execution via `child_process`
- Network access via `net` module
- All system resources
**Attack Scenario:**
1. User opens a malicious markdown file containing embedded JavaScript
2. The JavaScript executes in the renderer with full Node.js access
3. Attacker can read sensitive files, execute commands, exfiltrate data
**Remediation:**
```javascript
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
preload: path.join(__dirname, 'preload.js')
}
```
**Note:** The preload.js file already implements a secure IPC bridge but it is not being utilized for the main window.
---
### CVE-MC-002: Arbitrary Code Execution via REPL Feature (Critical)
**CVSS 3.1 Score: 9.3 (Critical)**
**CWE-94: Improper Control of Generation of Code ('Code Injection')**
**Location:** `src/main.js` (lines 4369-4396)
**Description:**
The `execute-code` IPC handler allows execution of arbitrary Python and Bash scripts through the REPL panel. While JavaScript execution appears to have been removed or limited, Python and Bash commands are executed via `execFile` with user-supplied code.
**Vulnerable Code Pattern:**
```javascript
ipcMain.handle('execute-code', async (event, { code, language }) => {
// ...
if (language === 'python' || language === 'py') {
cmd = 'python';
args = ['-c', code];
}
// ...
execFile(cmd, args, { timeout }, (err, stdout, stderr) => {
// ...
});
});
```
**Exploitability:**
- Users can be tricked into running malicious code blocks
- Markdown files can contain executable code blocks with "Run" buttons
- No sandboxing or permission restrictions on executed code
**Attack Scenario:**
1. Attacker creates markdown file with malicious Python code block
2. User clicks "Run" button in preview
3. Python code executes with user's full permissions
4. Attacker gains code execution on victim's machine
**Remediation:**
- Remove arbitrary code execution feature entirely, OR
- Implement strict sandboxing (Docker, VM, or restricted Python environment)
- Add user confirmation dialogs with clear warnings
- Execute in isolated environment with no filesystem/network access
- Implement allowlist of safe operations
---
### CVE-MC-003: Potential XSS in Markdown Rendering (High)
**CVSS 3.1 Score: 8.0 (High)**
**CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')**
**Location:** `src/renderer.js` (lines 387-419)
**Description:**
While DOMPurify is used to sanitize HTML, several extensions to marked.js may bypass sanitization:
1. **Custom Admonition Extension (lines 51-77):**
```javascript
marked.use({
extensions: [{
name: 'admonition',
// ...
renderer(token) {
const inner = this.parser.parse(token.text);
return `<div class="admonition admonition-${token.admonitionType}">
<div class="admonition-title">${icon} ${token.admonitionType...}</div>
<div class="admonition-content">${inner}</div>
</div>`;
}
}]
});
```
2. **innerHTML Assignments (line 419):**
```javascript
preview.innerHTML = sanitizedHtml;
```
**Exploitability:**
- Combined with CVE-MC-001, XSS leads to full system compromise
- Custom markdown extensions may not be properly sanitized
- Admonition type is directly interpolated into HTML without escaping
**Remediation:**
- Ensure all custom markdown extensions escape user input
- Add Content Security Policy that blocks inline scripts
- Use `textContent` instead of `innerHTML` where possible
- Audit all custom marked.js extensions for XSS vectors
---
### CVE-MC-004: Missing Path Traversal Protection (High)
**CVSS 3.1 Score: 7.8 (High)**
**CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')**
**Location:** `src/main.js` (lines 4241-4281)
**Description:**
The `list-directory` and `open-file-path` IPC handlers accept arbitrary file paths without validation:
```javascript
ipcMain.handle('list-directory', async (event, dirPath) => {
try {
if (!dirPath) { /* dialog */ }
// No path validation - accepts any path
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
// ...
}
});
ipcMain.on('open-file-path', (event, filePath) => {
// No path validation
if (!fs.existsSync(filePath)) return;
const content = fs.readFileSync(filePath, 'utf-8');
mainWindow.webContents.send('file-opened', { path: filePath, content });
});
```
**Exploitability:**
- Malicious renderer code can read any file on the system
- No restriction to a sandbox directory
- Combined with XSS, attacker can exfiltrate sensitive files
**Remediation:**
```javascript
const ALLOWED_DIRECTORIES = [app.getPath('documents'), app.getPath('desktop')];
function isPathAllowed(filePath) {
const resolved = path.resolve(filePath);
return ALLOWED_DIRECTORIES.some(dir => resolved.startsWith(dir));
}
```
---
### CVE-MC-005: Weak Content Security Policy (High)
**CVSS 3.1 Score: 7.5 (High)**
**CWE-1021: Improper Restriction of Renderers**
**Location:** `src/index.html` (line 5)
```html
<meta http-equiv="Content-Security-Policy" content="default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net;
style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com;
img-src 'self' data: blob: file:;
font-src 'self' data:;
connect-src 'self' https://www.plantuml.com;">
```
**Description:**
The CSP contains several security weaknesses:
1. **`'unsafe-inline'` in script-src** - Allows inline script injection
2. **`'unsafe-eval'` in script-src** - Allows `eval()` and similar functions
3. **`https://cdn.jsdelivr.net`** - Allows scripts from external CDN (supply chain risk)
4. **`file:` in img-src** - Allows loading local files as images (potential information disclosure)
**Exploitability:**
- XSS attacks can execute arbitrary scripts
- External CDN compromise could inject malicious code
- `eval()` enables dynamic code execution
**Remediation:**
- Remove `'unsafe-inline'` and `'unsafe-eval'`
- Use nonces or hashes for inline scripts
- Remove external CDNs or use Subresource Integrity (SRI)
- Remove `file:` from img-src
---
### CVE-MC-006: Insecure Window Configuration for PDF Export (Medium)
**CVSS 3.1 Score: 6.5 (Medium)**
**CWE-1021: Improper Restriction of Renderers**
**Location:** `src/main.js` (lines 2579-2585)
```javascript
const pdfWindow = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
```
**Description:**
Hidden windows created for PDF export also have insecure configurations, allowing potential privilege escalation.
**Remediation:**
```javascript
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true
}
```
---
### CVE-MC-007: PlantUML Server Data Exfiltration (Medium)
**CVSS 3.1 Score: 5.3 (Medium)**
**CWE-359: Exposure of Private Information**
**Location:** `src/renderer.js` (lines 470-487)
```javascript
const plantumlBlocks = preview.querySelectorAll('pre code.language-plantuml');
plantumlBlocks.forEach((block) => {
const code = block.textContent;
// ...
const encoded = plantumlEncode(code);
const img = document.createElement('img');
img.src = `https://www.plantuml.com/plantuml/svg/${encoded}`;
// ...
});
```
**Description:**
PlantUML diagram content is sent to an external server (plantuml.com) for rendering. This could leak sensitive information contained in diagrams.
**Exploitability:**
- Diagrams containing proprietary information, system architecture, or internal processes are sent to third-party servers
- No user consent or notification before external data transmission
**Remediation:**
- Use local PlantUML rendering with Java
- Add user warning before sending data to external service
- Implement opt-in for external rendering
---
### CVE-MC-008: Inconsistent Security Settings Across Windows (Medium)
**CVSS 3.1 Score: 5.5 (Medium)**
**CWE-1021: Improper Restriction of Renderers**
**Description:**
Security settings are inconsistent across different windows:
| Window | nodeIntegration | contextIsolation | Security |
|--------|-----------------|------------------|----------|
| Main Window | true | false | Insecure |
| About Dialog | false | true | Secure |
| Dependencies Dialog | false | true | Secure |
| ASCII Generator | false | true | Secure |
| Table Generator | false | true | Secure |
| PDF Export Window | true | false | Insecure |
| Hidden Conversion Window | true | false | Insecure |
**Remediation:**
Apply secure configuration (`nodeIntegration: false`, `contextIsolation: true`) consistently across all windows.
---
### CVE-MC-009: Command Execution via External Tools (Low)
**CVSS 3.1 Score: 4.4 (Low)**
**CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')**
**Location:** `src/main.js` (lines 1915-1972)
**Description:**
While the application uses `execFile` instead of `exec` (good practice), external tools (Pandoc, LibreOffice, FFmpeg, ImageMagick) are invoked with file paths that could potentially be manipulated.
**Positive Finding:**
The code correctly uses `execFile` with argument arrays instead of shell commands, mitigating most command injection vectors.
**Remaining Risk:**
- File paths are not validated against malicious names
- Special characters in filenames could cause issues with external tools
**Remediation:**
- Validate file paths before passing to external tools
- Sanitize filenames of special characters
---
### CVE-MC-010: Missing Dependency Version Pinning (Low)
**CVSS 3.1 Score: 3.5 (Low)**
**CWE-1035: Using Components with Known Vulnerabilities**
**Location:** `package.json`
**Description:**
Dependencies use `^` version ranges which could allow automatic updates to versions with vulnerabilities:
```json
"dependencies": {
"marked": "^17.0.3",
"dompurify": "^3.3.1",
"mermaid": "^11.12.3",
// ...
}
```
**Remediation:**
- Pin exact versions in production
- Use lockfile (package-lock.json)
- Implement dependency scanning in CI/CD pipeline
---
## Attack Surface Map
```
┌─────────────────────────────────────────────────────────────────┐
│ EXTERNAL ATTACK SURFACE │
├─────────────────────────────────────────────────────────────────┤
│ Markdown Files (.md) ─────► XSS via Preview Rendering │
│ Code Blocks ─────► Arbitrary Code Execution │
│ PlantUML Diagrams ─────► Data Exfiltration │
│ External CDNs ─────► Supply Chain Attacks │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ RENDERER PROCESS (Insecure) │
├─────────────────────────────────────────────────────────────────┤
│ nodeIntegration: true ─────► Direct Node.js Access │
│ contextIsolation: false ─────► Prototype Pollution Risk │
│ DOMPurify Sanitization ─────► May be bypassed via extensions │
│ Custom Marked Extensions ────► XSS Vectors │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ IPC BRIDGE (Preload.js) │
├─────────────────────────────────────────────────────────────────┤
│ Channel Whitelisting ─────► Good Practice │
│ Not Used for Main Window ────► Security Bypassed │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ MAIN PROCESS (Full Privileges) │
├─────────────────────────────────────────────────────────────────┤
│ File Operations ─────► No Path Validation │
│ Code Execution ─────► Python/Bash via REPL │
│ External Tools ─────► Pandoc, FFmpeg, LibreOffice │
│ PDF Operations ─────► Merge, Encrypt, Decrypt │
└─────────────────────────────────────────────────────────────────┘
```
---
## Positive Security Findings
1. **Preload.js Implementation:** A secure IPC bridge with channel whitelisting is implemented
2. **DOMPurify Usage:** HTML sanitization is applied to markdown output
3. **execFile Usage:** External commands use `execFile` instead of `exec`
4. **File Size Limits:** 50MB maximum file size is enforced
5. **Rate Limiting:** Conversion operations have rate limiting (2 second minimum interval)
6. **Error Message Sanitization:** Absolute paths are stripped from error messages
---
## Prioritized Remediation Roadmap
### Phase 1 - Critical (Immediate)
1. Set `nodeIntegration: false` and `contextIsolation: true` for main window
2. Remove or sandbox the code execution (REPL) feature
3. Implement proper preload.js usage for all windows
### Phase 2 - High Priority (1-2 Weeks)
4. Add path traversal protection to file operations
5. Strengthen Content Security Policy
6. Audit and fix custom markdown extensions for XSS
### Phase 3 - Medium Priority (1 Month)
7. Implement consistent security settings across all windows
8. Add local PlantUML rendering option
9. Implement dependency scanning in CI/CD
### Phase 4 - Low Priority (Ongoing)
10. Pin dependency versions
11. Add security headers to all generated HTML
12. Implement security logging and monitoring
---
## Compliance Considerations
- **OWASP Top 10 2021:** A03:2021 - Injection, A05:2021 - Security Misconfiguration
- **OWASP ASVS:** V12 - File Handling, V13 - API Security
- **NIST CSF:** PR.AC - Access Control, PR.DS - Data Security
---
## Conclusion
The MarkdownConverter application has significant security vulnerabilities that could allow an attacker to execute arbitrary code, access sensitive files, and compromise the user's system. The most critical issue is the insecure Electron configuration combined with XSS attack vectors in the markdown rendering pipeline.
**Overall Security Rating: HIGH RISK**
The positive finding is that much of the security infrastructure (preload.js, DOMPurify) is already in place but not properly utilized. With focused remediation effort, the application can achieve a much stronger security posture.
+215
View File
@@ -0,0 +1,215 @@
# STRIDE Threat Model - MarkdownConverter v4.0.0
**Analysis Date:** 2026-03-15
**Methodology:** STRIDE + MITRE ATT&CK
**Overall Risk Score:** 7.8 (HIGH)
---
## Executive Summary
The analysis identified **10 vulnerabilities** with a combined risk score of **7.8 (HIGH)**. The most critical issues enable complete system compromise through XSS-to-RCE attack chains.
---
## Critical Findings
| Priority | CVE | Vulnerability | CVSS | Impact |
|----------|-----|---------------|------|--------|
| P0 | CVE-MC-001 | Insecure Electron Config (`nodeIntegration: true`, `contextIsolation: false`) | 9.6 | Complete system compromise |
| P0 | CVE-MC-002 | Arbitrary code execution via REPL feature | 9.3 | Remote code execution |
| P1 | CVE-MC-003 | XSS in markdown rendering | 8.0 | Session hijacking, RCE chain |
| P1 | CVE-MC-004 | Path traversal vulnerability | 7.8 | Arbitrary file write |
| P1 | CVE-MC-005 | Weak Content Security Policy | 7.5 | XSS enablement |
| P2 | CVE-MC-006 | Insecure window config for PDF export | 6.5 | Privilege escalation |
| P2 | CVE-MC-007 | PlantUML server data exfiltration | 5.3 | Information disclosure |
| P2 | CVE-MC-008 | Inconsistent security settings | 5.5 | Configuration weakness |
| P3 | CVE-MC-009 | Command execution via external tools | 4.4 | Command injection risk |
| P3 | CVE-MC-010 | Missing dependency version pinning | 3.5 | Supply chain risk |
---
## Key Attack Vectors
### 1. XSS to RCE Chain (Critical)
```
Malicious Markdown File
XSS in Preview (CVE-MC-003)
nodeIntegration: true (CVE-MC-001)
Full Node.js Access
Complete System Compromise
```
### 2. REPL Code Execution (Critical)
```
Code Block in Markdown
User clicks "Run"
REPL executes Python/Bash (CVE-MC-002)
Arbitrary Code Execution
```
### 3. Data Exfiltration (Medium)
```
PlantUML Diagram Content
Sent to www.plantuml.com (CVE-MC-007)
Sensitive Architecture Leaked
```
---
## STRIDE Analysis
### S - Spoofing
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| S1 | Attacker spoofs markdown file origin | Medium | High | High |
| S2 | Malicious code pretends to be safe | High | Critical | Critical |
### T - Tampering
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| T1 | XSS modifies local files | High | Critical | Critical |
| T2 | Conversion output tampered | Medium | Medium | Medium |
### R - Repudiation
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| R1 | No audit trail for operations | Low | Low | Low |
### I - Information Disclosure
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| I1 | XSS exposes file system | High | Critical | Critical |
| I2 | PlantUML content leaked | Medium | Medium | Medium |
| I3 | Error messages reveal paths | Low | Low | Low |
### D - Denial of Service
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| D1 | Malicious code crashes app | Medium | Medium | Medium |
| D2 | Large file exhausts resources | Low | Low | Low |
### E - Elevation of Privilege
| ID | Threat | Likelihood | Impact | Risk |
|----|--------|------------|--------|------|
| E1 | XSS → nodeIntegration → System | High | Critical | Critical |
| E2 | REPL code execution | High | Critical | Critical |
---
## MITRE ATT&CK Mapping
| Technique | ID | Applicability |
|-----------|-----|---------------|
| User Execution | T1204.002 | Malicious markdown file |
| Command and Scripting Interpreter | T1059.007 | JavaScript via nodeIntegration |
| Command and Scripting Interpreter | T1059.006 | Python via REPL |
| Command and Scripting Interpreter | T1059.004 | Bash via REPL |
| Exploit Public-Facing Application | T1190 | XSS in preview |
| Data Exfiltration Over Web Service | T1043 | PlantUML server |
| File and Directory Discovery | T1083 | Path traversal |
---
## Trust Boundaries
```
┌─────────────────────────────────────────────────────────────────────┐
│ TRUST BOUNDARY MAP │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────────────────────────────┐ │
│ │ USER │ ──────► │ APPLICATION │ │
│ │ (Untrusted) │ │ ┌───────────┐ ┌───────────────┐ │ │
│ └─────────────┘ │ │ Renderer │ │ Main Process │ │ │
│ │ │ (Sandbox) │ │ (Privileged) │ │ │
│ │ └─────┬─────┘ └───────┬───────┘ │ │
│ │ │ IPC │ │ │
│ │ ▼ ▼ │ │
│ │ ┌─────────────────────────────┐ │ │
│ │ │ File System │ │ │
│ │ └─────────────────────────────┘ │ │
│ └─────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ EXTERNAL SERVICES │ │
│ │ • PlantUML Server (www.plantuml.com) │ │
│ │ • CDN (cdn.jsdelivr.net, cdnjs.cloudflare.com) [REMOVED] │ │
│ │ • External Tools (Pandoc, FFmpeg, LibreOffice) │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
---
## Business Impact Analysis
### Successful Attack Consequences
| Impact Category | Estimate |
|-----------------|----------|
| Data breach costs | $500,000 - $5,000,000+ |
| Regulatory fines (GDPR) | Up to 4% annual revenue |
| Reputation damage | Incalculable |
| Business disruption | Hours to days |
### Affected Assets
- User documents and files
- System credentials
- Proprietary information in diagrams
- Application integrity
---
## Remediation Priority
### P0 - Immediate (24-48 hours)
1. **CVE-MC-001**: Set `nodeIntegration: false`, `contextIsolation: true`
2. **CVE-MC-002**: Remove or sandbox REPL code execution
### P1 - Short-term (1-2 weeks)
3. **CVE-MC-003**: Audit markdown extensions for XSS
4. **CVE-MC-004**: Add path validation (✅ COMPLETED)
5. **CVE-MC-005**: Strengthen CSP (✅ COMPLETED)
### P2 - Medium-term (1 month)
6. **CVE-MC-006**: Consistent window security settings
7. **CVE-MC-007**: Add local PlantUML option or warning
8. **CVE-MC-008**: Audit all BrowserWindow configurations
### P3 - Long-term
9. **CVE-MC-009**: Validate filenames for external tools
10. **CVE-MC-010**: Pin dependency versions, add scanning
---
## Conclusion
The MarkdownConverter application has a **HIGH RISK** threat profile due to the combination of:
- Untrusted content rendering (markdown preview)
- Direct system access (nodeIntegration)
- Code execution capability (REPL)
**Immediate action required on P0 items to reduce attack surface.**
The fixes applied in this session (CSP, path traversal, UI accessibility) have reduced the risk profile, but the critical nodeIntegration issue requires significant refactoring.
+27
View File
@@ -0,0 +1,27 @@
{
"target": "MarkdownConverter Electron Application",
"status": "in_progress",
"depth": "comprehensive",
"compliance_frameworks": ["owasp"],
"current_step": 3,
"current_phase": 1,
"completed_steps": ["vulnerability-scan", "threat-modeling"],
"files_created": ["01-vulnerability-scan.md", "02-threat-model.md"],
"started_at": "2026-03-15T00:09:00.000Z",
"last_updated": "2026-03-15T00:25:00.000Z",
"findings_summary": {
"critical": 2,
"high": 3,
"medium": 3,
"low": 2,
"total": 10
},
"fixes_applied": {
"csp_external_cdns_removed": true,
"path_traversal_protection_added": true,
"aria_labels_added": true,
"focus_visible_styles_added": true,
"tab_close_button_resized": true,
"duplicate_font_size_fixed": true
}
}
@@ -0,0 +1,522 @@
# Comprehensive UI Design Review - MarkdownConverter Electron Application
## Executive Summary
This review covers the UI design of the MarkdownConverter Electron application, analyzing visual design, usability, code quality, and performance across all UI files. The application has a solid foundation but has several areas requiring attention.
---
## 1. Visual Design Review
### 1.1 Spacing & Layout Consistency
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Inconsistent padding values across files | Multiple CSS files | Standardize to 4px/8px base scale |
| **Major** | Multiple reset declarations | `styles.css:1-5`, `styles-modern.css:42-47` | Consolidate resets into single file |
| **Minor** | Tab padding varies between themes | `styles.css:36`, `styles-modern.css:101` | Use CSS variables for consistent padding |
| **Minor** | Container padding inconsistency | `styles.css:17-21`, `styles-modern.css:63-69` | Define single container style |
**Code Example - Duplicate Reset:**
```css
/* styles.css:1-5 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* styles-modern.css:42-47 - DUPLICATE */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
```
**Fix Recommendation:**
```css
/* Create a single base.css or remove from styles-modern.css */
/* Use CSS variables for spacing scale */
:root {
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
}
```
### 1.2 Typography Consistency
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Font-family declared multiple times with different fallbacks | `styles.css:8`, `styles-modern.css:50`, `styles-concreteinfo.css:32` | Standardize font stack |
| **Major** | Duplicate font-size declarations | `styles.css:228-230` | Remove duplicate |
| **Minor** | Inconsistent line-height values | Multiple files | Create type scale variables |
**Code Example - Duplicate font-size:**
```css
/* styles.css:226-230 */
.preview-content {
max-width: none;
margin: 0;
padding: 20px 24px 24px 24px;
line-height: 1.6;
font-size: 15px;
font-size: 14px; /* DUPLICATE - overwrites previous */
}
```
**Fix Recommendation:**
```css
/* styles.css - Remove duplicate */
.preview-content {
font-size: 14px; /* Keep only one */
line-height: 1.6;
}
```
### 1.3 Color Usage and Contrast Accessibility
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Critical** | Hardcoded colors instead of CSS variables | `styles.css:27-29`, `styles.css:37-38`, etc. | Use CSS custom properties |
| **Major** | Inconsistent gray scale definitions | Multiple files define different grays | Consolidate to single palette |
| **Minor** | Some contrast ratios may be insufficient | Status bar text colors | Verify WCAG 2.1 AA compliance |
**Code Example - Hardcoded colors:**
```css
/* styles.css:27-29 */
.tab-bar {
background: #f0f0f0; /* Should use var(--gray-100) */
border-bottom: 1px solid #ddd; /* Should use var(--gray-300) */
}
```
**Fix Recommendation:**
```css
/* Use the existing palette from styles-modern.css */
.tab-bar {
background: var(--gray-100, #f3f4f6);
border-bottom: 1px solid var(--gray-300, #d1d5db);
}
```
### 1.4 Dark Mode Support Quality
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Dark theme selectors inconsistent | `styles.css` uses `body.theme-dark`, `styles-sidebar.css:108` uses `body[class*="dark"]` | Standardize selector pattern |
| **Minor** | Missing dark theme support for some components | `.breadcrumb-bar`, command palette | Add dark mode variants |
| **Suggestion** | Repetitive dark theme declarations | `styles-concreteinfo.css:362-425` | Use CSS custom properties for theming |
**Code Example - Inconsistent selectors:**
```css
/* styles.css */
body.theme-dark .tab-bar { ... }
/* styles-sidebar.css */
body[class*="dark"] .sidebar-icons { ... }
```
**Fix Recommendation:**
```css
/* Choose one pattern and apply consistently */
/* Option 1: Class-based (recommended) */
body.theme-dark .tab-bar,
body.theme-dark .sidebar-icons { ... }
/* Option 2: Attribute-based */
body[data-theme="dark"] .tab-bar { ... }
```
---
## 2. Usability Review
### 2.1 Clickable/Tappable Areas
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Critical** | Tab close button too small (16x16px) | `styles.css:62-77` | Increase to minimum 24x24px |
| **Major** | Sidebar icons at minimum size | `styles-sidebar.css:35-47` (36x36px) | Consider 40-44px for better touch |
| **Minor** | Toolbar buttons at edge of minimum | `styles.css:120-131` (32x32px) | Acceptable for mouse, small for touch |
**Code Example - Small close button:**
```css
/* styles.css:62-77 */
.tab-close {
width: 16px; /* TOO SMALL - below 24px minimum */
height: 16px; /* TOO SMALL */
}
```
**Fix Recommendation:**
```css
.tab-close {
width: 24px;
height: 24px;
border-radius: 4px;
}
/* Add touch-friendly hit area */
.tab-close::before {
content: '';
position: absolute;
top: -4px;
left: -4px;
right: -4px;
bottom: -4px;
}
```
### 2.2 Hover/Focus States
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Critical** | Missing focus-visible styles | All interactive elements | Add :focus-visible for keyboard navigation |
| **Major** | No focus indicators on toolbar buttons | `styles.css:133-140` | Add visible focus ring |
| **Minor** | Inconsistent hover transitions | Various components | Standardize transition duration |
**Code Example - Missing focus styles:**
```css
/* styles.css:120-131 - No focus state */
.toolbar button {
/* ... no focus style */
}
.toolbar button:hover {
background: #e0e0e0;
border-color: #ccc;
}
```
**Fix Recommendation:**
```css
.toolbar button:focus-visible {
outline: 2px solid var(--primary-dark, #5661b3);
outline-offset: 2px;
}
.toolbar button:hover {
background: #e0e0e0;
border-color: #ccc;
}
```
### 2.3 Loading and Error State Handling
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Generic error message without styling | `renderer.js:384-386`, `renderer.js:508-511` | Create styled error components |
| **Minor** | No loading indicators for async operations | Sidebar panels | Add skeleton loaders or spinners |
| **Minor** | `git-loading` class exists but minimal styling | `styles-sidebar.css:227` | Enhance with animation |
**Code Example - Plain error display:**
```javascript
// renderer.js:384-386
preview.innerHTML = '<p style="color: red; padding: 20px;">Error: Required libraries...';
// Inline styles should be in CSS
```
**Fix Recommendation:**
```css
/* Add to styles.css */
.preview-error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 20px;
color: var(--ci-danger, #dc3545);
text-align: center;
}
.preview-error-icon {
font-size: 48px;
margin-bottom: 16px;
}
```
### 2.4 Accessibility (ARIA, Semantic HTML)
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Critical** | Buttons without accessible labels | `index.html:31` (tab close), `index.html:33` (new tab) | Add aria-label |
| **Critical** | SVG icons lack aria-hidden | All toolbar buttons | Add aria-hidden="true" |
| **Major** | Missing role attributes on tabs | `index.html:29-33` | Add role="tablist", role="tab" |
| **Major** | No skip links | `index.html` | Add skip to main content link |
| **Minor** | Dialog missing aria-modal | Export dialogs | Add aria-modal="true" |
**Code Example - Missing accessibility attributes:**
```html
<!-- index.html:31 - Current -->
<button class="tab-close" title="Close tab">x</button>
<!-- index.html:33 - Current -->
<button class="new-tab-button" id="new-tab-btn" title="New tab">+</button>
```
**Fix Recommendation:**
```html
<!-- Improved with ARIA -->
<div class="tab-bar" id="tab-bar" role="tablist" aria-label="Document tabs">
<div class="tab active" data-tab-id="1" role="tab" aria-selected="true" aria-controls="tab-content-1">
<span class="tab-title">Untitled</span>
<button class="tab-close" aria-label="Close tab" title="Close tab">×</button>
</div>
<button class="new-tab-button" id="new-tab-btn" aria-label="Create new tab" title="New tab">+</button>
</div>
<!-- SVG icons should have aria-hidden -->
<button id="btn-bold" title="Bold (Ctrl+B)" aria-label="Bold">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
...
</svg>
</button>
```
### 2.5 Keyboard Navigation
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Tab order may skip sidebar icons | Sidebar panel | Verify logical tab order |
| **Minor** | No escape key handling for dialogs | Export dialogs | Add escape to close |
| **Minor** | Find dialog lacks full keyboard support | `renderer.js:804-866` | Add Ctrl+F shortcut hint |
---
## 3. Code Quality Review
### 3.1 CSS Organization & Naming
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | No clear CSS architecture | All CSS files | Adopt BEM or similar methodology |
| **Major** | Overly generic class names | `.pane`, `.tab`, `.container` | Use more specific naming |
| **Minor** | Mixed naming conventions | camelCase (`tabBar`), kebab-case (`tab-bar`) | Standardize to kebab-case |
| **Minor** | Magic numbers | Various pixel values | Replace with spacing variables |
### 3.2 CSS Specificity Issues
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Excessive use of `!important` | `styles.css:14` | Restructure to avoid |
| **Major** | Deep selector nesting | Dark theme selectors | Flatten and use CSS variables |
| **Minor** | ID selectors for styling | `styles.css:233-247` | Prefer class selectors |
**Code Example - Problematic specificity:**
```css
/* styles.css:14 - Avoid !important */
.hidden {
display: none !important;
}
/* styles.css:397-431 - Deep nesting */
body.theme-dark #preview h1,
body.theme-dark [id^="preview-"] h1,
body.theme-dark .preview-content h1 {
color: #c9d1d9;
border-bottom-color: #21262d;
}
```
**Fix Recommendation:**
```css
/* Use utility class pattern */
[hidden] { display: none; }
/* Use CSS custom properties for theming */
.preview-content h1 {
color: var(--text-primary);
border-bottom-color: var(--border-color);
}
/* Theme applies variables */
body.theme-dark {
--text-primary: #c9d1d9;
--border-color: #21262d;
}
```
### 3.3 Reusable Style Definitions
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Repeated button styles | Multiple files | Create button component classes |
| **Major** | Dialog styles duplicated | Export, batch, print preview dialogs | Create modal component |
| **Minor** | Similar form field styles scattered | Export dialog inputs | Create form component |
**Code Example - Duplicated button styles:**
```css
/* styles.css */
.toolbar button { /* button styles */ }
.tab-close { /* button styles */ }
.new-tab-button { /* button styles */ }
#export-dialog-close { /* button styles */ }
/* styles-sidebar.css */
.sidebar-icon { /* similar button styles */ }
.sidebar-panel-close { /* similar button styles */ }
```
**Fix Recommendation:**
```css
/* Create button component system */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
border: none;
cursor: pointer;
transition: all var(--transition-fast);
}
.btn--icon {
width: 32px;
height: 32px;
border-radius: var(--radius-md);
}
.btn--close {
font-size: 14px;
font-weight: bold;
border-radius: var(--radius-sm);
}
```
### 3.4 Documentation
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Minor** | Limited CSS documentation | All CSS files | Add section comments |
| **Minor** | No component documentation | Sidebar components | Add JSDoc-style comments |
| **Suggestion** | No design tokens documentation | CSS variables | Create tokens documentation |
---
## 4. Performance Review
### 4.1 CSS Optimization
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | Large CSS files (105KB main, 78KB modern) | `styles.css`, `styles-modern.css` | Split into smaller modules |
| **Major** | Duplicate style definitions | Multiple files | Remove redundancies |
| **Minor** | Unused styles likely present | Theme variations | Audit and remove unused |
### 4.2 Asset Loading
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Major** | highlight.js CSS loaded synchronously | `index.html:14` | Load asynchronously or bundle |
| **Minor** | Font files could be preloaded | `fonts.css` | Add preload links in HTML |
| **Suggestion** | Consider CSS critical path | Above-the-fold styles | Inline critical CSS |
**Code Example - Sync stylesheet loading:**
```html
<!-- index.html:14 - Blocks rendering -->
<link rel="stylesheet" href="../node_modules/highlight.js/styles/default.css">
```
**Fix Recommendation:**
```html
<!-- Non-blocking load -->
<link rel="stylesheet" href="../node_modules/highlight.js/styles/default.css" media="print" onload="this.media='all'">
<!-- Or preload fonts -->
<link rel="preload" href="../assets/fonts/Inter-Regular.woff2" as="font" type="font/woff2" crossorigin>
```
### 4.3 Animation Performance
| Severity | Issue | Location | Recommendation |
|----------|-------|----------|----------------|
| **Minor** | Some transitions on expensive properties | `styles-modern.css:111-112` | Prefer transform/opacity |
| **Suggestion** | Missing will-change hints | Complex animations | Add will-change for GPU hints |
---
## 5. Component-Specific Issues
### 5.1 Tab System
| File | Issues |
|------|--------|
| `styles.css:23-97` | Inconsistent active state styling, small close button |
| `renderer.js:88-346` | Tab content created via innerHTML (XSS risk) |
### 5.2 Sidebar
| File | Issues |
|------|--------|
| `styles-sidebar.css` | Good structure but missing focus states |
| `sidebar-manager.js` | Clean implementation, needs ARIA |
### 5.3 Export Dialogs
| File | Issues |
|------|--------|
| `styles.css:1060-1355` | Monolithic, should be component |
| `index.html:171-331` | Complex nested structure needs semantic HTML |
### 5.4 Welcome Screen
| File | Issues |
|------|--------|
| `styles-welcome.css` | Minimal styles, good foundation |
| Missing hover states for keyboard focus | Add :focus-visible |
---
## 6. Prioritized Fix Recommendations
### Critical (Immediate)
1. **Add missing ARIA attributes** to all interactive elements
2. **Increase tab close button size** to minimum 24x24px
3. **Add focus-visible styles** for keyboard navigation
4. **Fix duplicate font-size declaration** in `.preview-content`
### Major (Next Sprint)
1. **Consolidate CSS resets** into single location
2. **Create button component system** with variants
3. **Standardize dark theme selectors** across all files
4. **Replace hardcoded colors** with CSS variables
5. **Create modal/dialog component** to reduce duplication
### Minor (Future)
1. **Document CSS architecture** and naming conventions
2. **Audit and remove unused styles**
3. **Add loading state components** (skeletons, spinners)
4. **Implement CSS module splitting** for better performance
---
## 7. Summary Statistics
| Category | Critical | Major | Minor | Suggestions |
|----------|----------|-------|-------|-------------|
| Visual Design | 1 | 5 | 4 | 1 |
| Usability | 3 | 4 | 4 | 0 |
| Code Quality | 0 | 6 | 4 | 1 |
| Performance | 0 | 3 | 2 | 2 |
| **Total** | **4** | **18** | **14** | **4** |
---
## Conclusion
The MarkdownConverter application has a functional UI with good visual variety through its theme system. However, there are significant opportunities for improvement in:
1. **Accessibility** - Critical for users with disabilities
2. **Code organization** - Reduce CSS duplication and improve maintainability
3. **Component consistency** - Standardize interactive element sizing and states
4. **Performance** - Optimize CSS loading and reduce bundle size
Addressing the Critical and Major issues will significantly improve both user experience and code maintainability.
+17
View File
@@ -0,0 +1,17 @@
{
"review_id": "full-ui-review_20260315",
"target": "src/ (Entire UI Directory)",
"focus_areas": ["visual", "usability", "code", "performance"],
"context": "comprehensive",
"platform": "desktop",
"status": "complete",
"started_at": "2026-03-15T00:09:00.000Z",
"completed_at": "2026-03-15T00:12:00.000Z",
"issues_found": 40,
"severity_counts": {
"critical": 4,
"major": 18,
"minor": 14,
"suggestion": 4
}
}
+48
View File
@@ -0,0 +1,48 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"outputCapture": "std",
"env": {
"NODE_ENV": "development"
}
},
{
"name": "Debug Renderer Process",
"type": "chrome",
"request": "attach",
"port": 9222,
"webRoot": "${workspaceFolder}/src",
"timeout": 30000
},
{
"name": "Debug Main + Renderer",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": [".", "--remote-debugging-port=9222"],
"outputCapture": "std",
"env": {
"NODE_ENV": "development"
},
"serverReadyAction": {
"pattern": "listening on port ([0-9]+)",
"uriFormat": "http://localhost:%s",
"action": "debugWithChrome"
}
}
]
}
+25
View File
@@ -0,0 +1,25 @@
# Repository Guidelines
## Project Structure & Module Organization
Core application code lives in `src/`. Use `src/main.js` for the Electron main process, `src/preload.js` for the preload bridge, and `src/renderer.js` plus `src/editor/`, `src/sidebar/`, `src/repl/`, and `src/utils/` for renderer-side features. Electron adapter code is in `src/adapters/electron/`. Reusable markdown/document templates live in `src/templates/`. Static assets and icons are in `assets/`. Tests are in `tests/`, and build output goes to `dist/`.
## Build, Test, and Development Commands
- `npm start`: launch the Electron app locally.
- `npm test`: run the Jest suite once.
- `npm run test:watch`: rerun tests during local development.
- `npm run test:coverage`: generate coverage output.
- `npm run lint` / `npm run lint:fix`: check or fix ESLint issues in `src` and `tests`.
- `npm run format` / `npm run format:check`: apply or verify Prettier formatting.
- `npm run build:linux`, `npm run build:win`, `npm run build:mac`: create platform packages with `electron-builder`.
## Coding Style & Naming Conventions
This repo uses Prettier and ESLint. Follow `.prettierrc`: 2-space indentation, single quotes, semicolons, trailing commas where valid in ES5, and a 100-character line width. Prefer `camelCase` for variables/functions, `PascalCase` for classes, and kebab-case for file names only when already established. Keep module boundaries clear: UI logic in renderer modules, OS/file-system work behind Electron IPC and adapters.
## Testing Guidelines
Tests use Jest with `jest-environment-jsdom`. Add new tests under `tests/` with `*.test.js` names, mirroring the feature area when possible, for example `tests/sidebar.test.js` or `tests/print-preview.test.js`. Update or add regression tests for renderer behavior, preload APIs, and utility helpers when fixing bugs. Run `npm test` before opening a PR; use `npm run test:coverage` for larger refactors.
## Commit & Pull Request Guidelines
Recent history follows Conventional Commit prefixes such as `feat:`, `fix:`, and `refactor:`. Keep subjects short and imperative, for example `fix: guard modal cleanup on close`. PRs should describe the user-visible change, note test coverage, link any related issue, and include screenshots or GIFs for UI changes.
## Security & Configuration Tips
Do not bypass preload boundaries or introduce direct `eval`/dynamic code paths; ESLint already treats these as errors. Export and conversion features depend on external tools such as Pandoc, FFmpeg, ImageMagick, and LibreOffice, so document any new runtime dependency in `README.md` and packaging config.
+103
View File
@@ -0,0 +1,103 @@
# CLAUDE.md — MarkdownConverter (master)
> General code-quality, JavaScript, git, security, and testing standards are in the **global CLAUDE.md**. This file holds project- and branch-specific notes.
## Project Overview
Electron desktop app for Markdown editing and universal file conversion powered by Pandoc. Cross-platform (Win/macOS/Linux). Features: multi-tab editor with live preview, 25+ themes, PDF viewer/editor (merge/split/compress/rotate/watermark/password), export to 20+ formats (PDF/DOCX/ODT/EPUB/HTML/LaTeX/RTF/PPTX), batch conversion, syntax highlighting, diagram support (Mermaid), Git integration, and a plugin system.
- **Version:** 4.4.5
- **License:** MIT
- **App ID:** `com.concreteinfo.markdownconverter`
## Branch Specifics
This is the **primary/release branch** — a vanilla JavaScript Electron app with no bundler or framework in the renderer. The renderer is a single large `renderer.js` (5,300+ lines) loaded directly via `src/index.html`. All UI is hand-rolled DOM manipulation.
## Architecture
### Main Process (`src/main.js` — 4,260 lines)
Monolithic main process file. Contains all IPC handlers, Pandoc invocation, file operations, menu definitions (600+ lines), and window lifecycle. Key modules extracted:
- `src/main/PDFOperations.js` — PDF manipulation via `pdf-lib` (merge, split, compress, rotate, delete, reorder, watermark, encrypt, decrypt, permissions)
- `src/main/GitOperations.js` — Git status/stage/commit/log via `simple-git`
### Renderer (`src/renderer.js` — 5,361 lines)
Vanilla JS, no framework. Directly manipulates DOM. Loads CodeMirror 6 via `src/editor/codemirror-setup.js`. Uses `marked` + `highlight.js` + `DOMPurify` + `mermaid` for rendering. Lazy-loads sidebar panels, REPL, command palette, zen mode.
### Preload (`src/preload.js` — 448 lines)
Exists as IPC bridge, but **`contextIsolation: false` and `nodeIntegration: true`** — the renderer has full Node access. Preload is effectively a thin passthrough.
### Security Model
- `contextIsolation: false` + `nodeIntegration: true` (legacy; the react-electron branch fixes this)
- Pandoc invoked via `execFile` (not `exec`) to prevent shell injection
- Path traversal protection: `validatePath()`, `resolveWritablePath()`, blocks sensitive system dirs
- Permission handler only allows `clipboard-read`/`clipboard-write`
- Rate limiter on conversions (2-second minimum interval)
- File size limit: 50MB
- Error message sanitization strips absolute paths
### Plugin System (`src/plugins/`)
Manifest-based discovery (`manifest.json`). Built-in `writing-studio` plugin with sprint/goal/snapshot management. Plugin API exposed via `src/plugins/plugin-api.js`.
### Settings
Custom JSON file store at `<userData>/settings.json` (NOT `electron-store` despite the dependency). Recent files at `<userData>/recent-files.json`.
## System Dependencies
| Dependency | Required | Notes |
|---|---|---|
| **Node.js** | >= 20 | Electron 41 bundles Node 20.x |
| **Pandoc** | Yes (for exports) | Downloaded to `bin/<platform>/pandoc` via `scripts/download-tools.js` (v3.9.0.2). Falls back to system PATH. Must be present for DOCX/ODT/EPUB/LaTeX/PPTX export. |
| **FFmpeg** | Bundled | `ffmpeg-static` npm package; `asarUnpacked` for packaged builds |
| **MiKTeX / TeX Live** | Optional | For LaTeX PDF export; MiKTeX PATH injected on Windows automatically |
| **ImageMagick** | Optional | Linux image conversion; listed as deb dependency |
| **LibreOffice** | Optional | Enhanced document conversion; listed as deb dependency |
## Development Commands
```bash
npm start # Launch Electron app (dev mode)
npm test # Jest test suite
npm test:watch # Jest in watch mode
npm test:coverage # Jest with coverage report
npm run lint # ESLint check (src + tests)
npm run lint:fix # ESLint auto-fix
npm run format # Prettier write
npm run format:check # Prettier check only
npm run download-tools # Download Pandoc binaries to bin/
npm run generate-icons # Generate app icons via sharp
```
## Build & Package
**Tool:** `electron-builder` (v26.0.12), config inline in `package.json` (no separate config file).
| Target | Platforms |
|---|---|
| `npm run build` | electron-builder (default platform) |
| `npm run build:win` | Windows: NSIS installer + portable + zip (x64) |
| `npm run build:mac` | macOS: default dmg |
| `npm run build:linux` | Linux: deb + AppImage + snap |
| `npm run dist` | Build without publish |
| `npm run dist:all` | Build for all platforms |
**Bundled with builds:** Pandoc binary per platform. FFmpeg via `ffmpeg-static` (asarUnpacked). NSIS installer uses custom script at `scripts/nsis-installer.nsh`.
**Output:** `dist/` directory.
**CI:** GitHub Actions workflows in `.github/workflows/` (ci.yml, release.yml).
## Project Conventions / Gotchas
- **No bundler/transpilation.** The app uses vanilla CommonJS JavaScript. `src/main.js` is loaded directly by Electron. No webpack, no Vite, no TypeScript, no Babel.
- **Monolithic files.** `main.js` (4,260 lines) and `renderer.js` (5,361 lines) contain most logic. Not ideal but is the current state of this branch.
- **CodeMirror 6** for the editor, configured in `src/editor/codemirror-setup.js`.
- **PDF rendering** uses `pdfjs-dist`; **PDF manipulation** uses `pdf-lib` in the main process.
- **Renderer security is weak** — full Node access in renderer. Do NOT introduce new privileged renderer code without understanding this.
- **Pandoc is external.** Must be installed separately or downloaded via `npm run download-tools`. HTML and built-in PDF export work without Pandoc; other formats require it.
- **PDF export fallback chain:** xelatex -> pdflatex -> lualatex -> Electron built-in `printToPDF()`.
- **ESLint flat config** (`eslint.config.js`) with ECMAScript 2022. Prettier with 2-space indent, single quotes, semicolons, 100-char width.
- **Tests:** Jest with jsdom environment, 15% coverage threshold. 24 test files in `tests/`.
- **File associations:** `.md`, `.markdown`, `.pdf` registered at install.
- **Single instance lock** enforced via `app.requestSingleInstanceLock()`.
- **Adapters layer** (`src/adapters/`) abstracts file system operations for potential future non-Electron targets.
+1 -1
View File
@@ -162,4 +162,4 @@ Amit Haridas (amit.wh@gmail.com)
## Version
v3.0.0
v4.5.0
+51
View File
@@ -1,5 +1,56 @@
# PanConverter - Updates & Changelog
## Version 4.0.0 (2026-03-04)
### Major Changes
- **CodeMirror 6 Editor** — Replaced textarea with CodeMirror 6 featuring syntax highlighting, code folding, bracket matching, multiple cursors, and auto-indent
- **Sidebar Panel System** — Collapsible sidebar with File Explorer, Git, Snippets, and Templates panels
- **Command Palette** — Ctrl+Shift+P to search and execute all app actions
- **Code Execution (REPL)** — Run JavaScript, Python, and Bash code blocks directly from the preview
### New Features
- Print Preview dialog with paper size, orientation, margins, scale, and page range controls
- Image paste from clipboard and drag-drop support with auto-save to assets folder
- Document templates library (10 templates: blog post, meeting notes, tech spec, changelog, README, project plan, API docs, tutorial, release notes, comparison)
- Markdown extensions: footnotes, admonitions (note/warning/tip/danger/info), and [[toc]] table of contents
- PlantUML diagram rendering alongside Mermaid
- Welcome tab with onboarding and "What's New" feature showcase
- System spell checking with context menu suggestions and dictionary support
- Enhanced status bar with word count, character count, line/column, encoding, and language mode
- Grouped toolbar with visual section separators
- Breadcrumb bar showing current file path
### New Export/Import Formats
- Reveal.js slides (.html)
- Beamer slides (.pdf)
- Confluence/Jira wiki markup (.txt)
- MOBI e-books (via Calibre)
- Developer formats: JSON, YAML, XML, TOML
### Security
- Content Security Policy (CSP) meta tag
- File size validation (50MB limit)
- Error message sanitization (stripped file paths)
- Conversion rate limiting (2-second debounce)
### Dependencies Updated
- marked: 16.x to 17.x (with marked-highlight extension)
- pdfjs-dist: 3.x to 5.x (new worker model)
- html2pdf.js: 0.10 to 0.14
- pdfkit: 0.14 to 0.17
- dompurify, docx, and others updated to latest
### Testing
- 80 tests across 7 test suites
- New tests for sidebar manager, command palette, print preview, markdown extensions, and utility functions
### Breaking Changes
- Editor is now CodeMirror 6 (replaces textarea)
- marked API changed to use marked.use() instead of marked.setOptions()
- pdfjs-dist upgraded to v5 with new worker model
---
## Version 2.1.0 (December 14, 2025)
### 🎨 UI/UX Improvements
File diff suppressed because one or more lines are too long
+93
View File
@@ -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.
+93
View File
@@ -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.
+866
View File
@@ -0,0 +1,866 @@
# MarkdownConverter - STRIDE Threat Model Analysis
**Version:** 4.1.0
**Date:** 2026-03-15
**Methodology:** STRIDE + MITRE ATT&CK Mapping
**Analyst:** Security Assessment Team
---
## Executive Summary
This threat model analyzes the MarkdownConverter Electron application using the STRIDE methodology. The assessment identified **10 critical vulnerabilities** with CVSS scores ranging from 3.5 to 9.6. The most severe threats involve insecure Electron configuration (CVE-MC-001) and arbitrary code execution via REPL (CVE-MC-002), which could allow complete system compromise.
**Risk Summary:**
| Severity | Count | Total CVSS Impact |
|----------|-------|-------------------|
| Critical (9.0+) | 2 | 18.9 |
| High (7.0-8.9) | 3 | 23.3 |
| Medium (5.0-6.9) | 3 | 17.3 |
| Low (<5.0) | 2 | 7.9 |
---
## 1. System Architecture Overview
### 1.1 Application Components
```
+------------------------------------------------------------------+
| MarkdownConverter v4.0.0 |
+------------------------------------------------------------------+
| |
| +------------------+ +------------------+ |
| | Main Process |<--->| Renderer Process| |
| | (Node.js) | | (Chromium) | |
| +------------------+ +------------------+ |
| | | |
| | IPC Channels | |
| v v |
| +------------------+ +------------------+ |
| | preload.js | | renderer.js | |
| | (Bridge Layer) | | (UI Logic) | |
| +------------------+ +------------------+ |
| | | |
| v v |
| +--------------------------------------------------+ |
| | External Tools | |
| | Pandoc | FFmpeg | ImageMagick | LibreOffice | |
| +--------------------------------------------------+ |
| |
+------------------------------------------------------------------+
|
v
+------------------------------------------------------------------+
| External Services |
| - plantuml.com (diagram rendering) |
| - cdn.jsdelivr.net (scripts) |
| - cdnjs.cloudflare.com (styles) |
+------------------------------------------------------------------+
```
### 1.2 Data Flow Diagram (Level 1)
```
TRUST BOUNDARY
|
+-----------+ | +-----------+
| User | | | System |
| (Author) |------------------>|------------------>| Files |
+-----------+ Markdown | File I/O +-----------+
Content |
|
+---------------+---------------+
| |
v v
+---------------+ +---------------+
| Editor | | Preview |
| (CodeMirror) | | (Rendered) |
+---------------+ +---------------+
| ^
| Sanitization |
| (DOMPurify) |
v |
+---------------+ |
| Renderer |-----------------------+
| Process | HTML/SVG
+---------------+
|
| IPC (Whitelisted Channels)
v
+---------------+ +-----------+
| Main |-------------->| Pandoc |
| Process | execFile | FFmpeg |
| (Node.js) | | etc. |
+---------------+ +-----------+
|
| HTTPS
v
+---------------+
| PlantUML |
| Server |
| (External) |
+---------------+
```
### 1.3 Trust Boundaries
```
+============================================================================+
|| TRUST BOUNDARY 1: User <-> Application ||
|| - User input (markdown content) is UNTRUSTED ||
|| - File paths from dialogs are PARTIALLY TRUSTED ||
+============================================================================+
|
v
+============================================================================+
|| TRUST BOUNDARY 2: Renderer <-> Main Process ||
|| - IPC communication via preload.js ||
|| - CRITICAL: nodeIntegration=true bypasses isolation ||
+============================================================================+
|
v
+============================================================================+
|| TRUST BOUNDARY 3: Application <-> System ||
|| - External tool execution (Pandoc, FFmpeg, etc.) ||
|| - File system access ||
+============================================================================+
|
v
+============================================================================+
|| TRUST BOUNDARY 4: Application <-> Internet ||
|| - PlantUML server (https://www.plantuml.com) ||
|| - CDN resources (jsdelivr, cdnjs) ||
+============================================================================+
```
---
## 2. STRIDE Analysis
### 2.1 Spoofing
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| S-01 | **PlantUML Server Spoofing** | Application sends diagram content to external PlantUML server. MITM or compromised server could return malicious SVG content. | CVE-MC-007 | 5.3 |
| S-02 | **CDN Compromise** | Scripts loaded from cdn.jsdelivr.net and styles from cdnjs.cloudflare.com could be compromised in supply chain attack. | - | 6.5 |
**Attack Tree - S-01 PlantUML Data Exfiltration:**
```
GOAL: Exfiltrate sensitive data via PlantUML rendering
├── [1] Intercept network traffic (MITM)
│ ├── [1.1] Exploit weak TLS implementation
│ └── [1.1] DNS hijacking
├── [2] Compromise PlantUML server
│ ├── [2.1] Server breach
│ └── [2.2] Supply chain compromise
└── [3] Inject malicious SVG response
├── [3.1] XSS via SVG onload
└── [3.2] Data exfiltration via image src
```
### 2.2 Tampering
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| T-01 | **Markdown Content Tampering** | XSS in markdown rendering could modify rendered content or inject malicious scripts. | CVE-MC-003 | 8.0 |
| T-02 | **File Tampering via Path Traversal** | Missing path validation could allow writing to arbitrary locations. | CVE-MC-004 | 7.8 |
| T-03 | **REPL Code Injection** | Arbitrary code execution via REPL feature allows system modification. | CVE-MC-002 | 9.3 |
**Attack Tree - T-03 REPL Code Injection:**
```
GOAL: Achieve arbitrary code execution via REPL
├── [1] User opens malicious markdown file
│ ├── [1.1] Phishing/social engineering
│ └── [1.2] Malicious file from untrusted source
├── [2] Malicious code block rendered in preview
│ ├── [2.1] JavaScript code block
│ ├── [2.2] Python code block
│ └── [2.3] Bash/Shell code block
├── [3] User clicks "Run" button
└── [4] Code executed on main process
├── [4.1] File system access
├── [4.2] Process execution
└── [4.3] Network access
└── [4.3.1] Data exfiltration
└── [4.3.2] C2 communication
```
### 2.3 Repudiation
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| R-01 | **Missing Audit Logging** | No logging of security-relevant events (file access, code execution, exports). | - | 4.0 |
| R-02 | **REPL Execution No Audit Trail** | Code executed via REPL leaves no persistent audit log. | CVE-MC-002 | 5.0 |
### 2.4 Information Disclosure
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| I-01 | **Path Disclosure in Error Messages** | Error messages may expose absolute file paths. Partially mitigated by `sanitizeErrorMessage()`. | - | 4.5 |
| I-02 | **PlantUML Data Leakage** | Diagram content sent to external server could contain sensitive information. | CVE-MC-007 | 5.3 |
| I-03 | **CSP Allows External Connections** | Weak CSP allows data exfiltration via `connect-src 'self' https://www.plantuml.com`. | CVE-MC-005 | 7.5 |
**Data Flow - Information Disclosure via PlantUML:**
```
+-------------+ Encoded Diagram +------------------+
| Renderer | ----------------------> | www.plantuml.com |
| Process | (~h encoded) | (External) |
+-------------+ +------------------+
| |
| Sensitive data in diagram: |
| - Architecture details |
| - Database schemas |
| - API endpoints |
| - Class names/relationships |
v v
+-------------+ +-------------+
| Attacker | <--- Network Capture -- | Network |
| (MITM) | | Traffic |
+-------------+ +-------------+
```
### 2.5 Denial of Service
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| D-01 | **REPL Resource Exhaustion** | Code execution has 10s timeout but could consume CPU/memory. | CVE-MC-002 | 4.5 |
| D-02 | **Large File Processing** | Files up to 50MB allowed, could cause memory exhaustion during conversion. | - | 5.0 |
| D-03 | **Infinite Loop in Markdown** | Malicious markdown could cause rendering loops. | - | 4.0 |
### 2.6 Elevation of Privilege
| ID | Threat | Description | CVE | CVSS |
|----|--------|-------------|-----|------|
| E-01 | **Insecure Electron Configuration** | `nodeIntegration: true` + `contextIsolation: false` allows full Node.js access from renderer. | CVE-MC-001 | 9.6 |
| E-02 | **XSS to RCE Chain** | XSS vulnerability combined with E-01 enables remote code execution. | CVE-MC-003 + CVE-MC-001 | 9.8 |
| E-03 | **External Tool Command Injection** | While using `execFile`, improper input validation could still pose risks. | CVE-MC-009 | 4.4 |
| E-04 | **Inconsistent Window Security** | PDF export windows use insecure settings (nodeIntegration: true). | CVE-MC-006 | 6.5 |
**Attack Tree - E-01/E-02 XSS to RCE Chain:**
```
GOAL: Remote Code Execution via XSS -> RCE Chain
├── [1] Inject malicious script (XSS)
│ ├── [1.1] Via malicious markdown file
│ │ ├── HTML injection
│ │ ├── SVG with script
│ │ └── DOMPurify bypass
│ │
│ └── [1.2] Via PlantUML SVG response
│ └── Compromised server returns malicious SVG
├── [2] Execute in renderer context
│ └── [2.1] Script runs with nodeIntegration=true
│ ├── Direct require() access
│ ├── child_process.exec()
│ └── fs module access
└── [3] Achieve RCE
├── [3.1] Execute system commands
├── [3.2] Read/write arbitrary files
├── [3.3] Install persistence mechanisms
└── [3.4] Lateral movement
```
---
## 3. Attack Scenarios
### 3.1 Scenario: Malicious Markdown Document (Critical)
**Attack Chain:**
```
1. Attacker creates malicious.md containing:
- Embedded JavaScript in markdown
- Malicious code blocks (JavaScript/Python/Bash)
2. Victim opens file in MarkdownConverter
3. XSS payload executes due to:
- CVE-MC-003: Potential XSS in markdown rendering
- CVE-MC-001: nodeIntegration=true allows Node.js access
4. Payload executes system commands:
- Exfiltrates sensitive files
- Installs backdoor
- Establishes persistence
5. Impact: Complete system compromise
```
**MITRE ATT&CK Mapping:**
| Tactic | Technique | ID | Description |
|--------|-----------|-----|-------------|
| Initial Access | Phishing | T1566 | Malicious file via email |
| Execution | User Execution | T1204 | Victim opens malicious file |
| Execution | Command/Scripting | T1059 | JavaScript/Python execution |
| Persistence | Registry Run Keys | T1547 | Establish persistence |
| Collection | Data from Local System | T1005 | File exfiltration |
| Exfiltration | Exfiltration Over C2 | T1041 | Data sent to attacker |
### 3.2 Scenario: REPL Code Execution (Critical)
**Attack Chain:**
```
1. Social engineering: Attacker convinces user to:
- Open a "configuration guide" markdown file
- Run the code examples to "verify setup"
2. Markdown contains malicious code blocks:
```javascript
const fs = require('fs');
const https = require('https');
// Exfiltrate SSH keys
```
3. User clicks "Run" button on code block
4. Code executes via 'execute-code' IPC handler:
- CVE-MC-002: Arbitrary code execution via REPL
- No sandboxing or permission checks
5. Impact: Credential theft, data exfiltration
```
**MITRE ATT&CK Mapping:**
| Tactic | Technique | ID | Description |
|--------|-----------|-----|-------------|
| Initial Access | Phishing | T1566 | Social engineering |
| Execution | Command/Scripting | T1059.004 | Bash execution |
| Execution | Command/Scripting | T1059.007 | JavaScript/Node execution |
| Credential Access | Credentials from Files | T1083 | SSH key theft |
| Exfiltration | Exfiltration Over Web Service | T1567 | HTTPS exfiltration |
### 3.3 Scenario: PlantUML Data Exfiltration (Medium)
**Attack Chain:**
```
1. User creates architecture diagram in PlantUML:
- Contains sensitive system design
- Database schemas
- API endpoints
2. Renderer encodes and sends to www.plantuml.com:
- CVE-MC-007: Data sent to external server
3. Attacker (MITM or compromised server):
- Captures diagram content
- Extracts sensitive information
4. Impact: Intellectual property theft, reconnaissance
```
### 3.4 Scenario: PDF Export Window Exploitation (Medium)
**Attack Chain:**
```
1. User exports document to PDF
2. Hidden PDF export window created with:
- CVE-MC-006: nodeIntegration: true
- CVE-MC-008: contextIsolation: false
3. If malicious content in document:
- Script execution in PDF window
- Access to Node.js APIs
4. Impact: Code execution during export process
```
---
## 4. Risk Matrix & Prioritization
### 4.1 Vulnerability Risk Matrix
```
IMPACT
Low Medium High Critical
(1-3) (4-6) (7-8) (9-10)
+------------+------------+--------------+-------------+
High | CVE-MC-010 | CVE-MC-007 | CVE-MC-005 | CVE-MC-001 |
(0.7-1.0) | 3.5 | 5.3 | 7.5 | 9.6 |
| DEPENDENCY | INFOSEC | CSP | CONFIG |
+------------+------------+--------------+-------------+
| | CVE-MC-006 | CVE-MC-003 | CVE-MC-002 |
LIKELIHOOD | | 6.5 | 8.0 | 9.3 |
(0.4-0.6) | | PDF-WIN | XSS | REPL |
+------------+------------+--------------+-------------+
Medium | | CVE-MC-008 | CVE-MC-004 | |
(0.2-0.4) | | 5.5 | 7.8 | |
| | INCONSIST | PATH-TRAV | |
+------------+------------+--------------+-------------+
Low | | | CVE-MC-009 | |
(0-0.2) | | | 4.4 | |
| | | CMD-EXEC | |
+------------+------------+--------------+-------------+
```
### 4.2 Prioritized Remediation List
| Priority | CVE | Vulnerability | CVSS | Effort | Risk Reduction |
|----------|-----|---------------|------|--------|----------------|
| P0 | CVE-MC-001 | Insecure Electron Config | 9.6 | Medium | Critical |
| P0 | CVE-MC-002 | REPL Code Execution | 9.3 | High | Critical |
| P1 | CVE-MC-003 | XSS in Markdown | 8.0 | Medium | High |
| P1 | CVE-MC-004 | Path Traversal | 7.8 | Low | High |
| P1 | CVE-MC-005 | Weak CSP | 7.5 | Medium | High |
| P2 | CVE-MC-006 | PDF Window Config | 6.5 | Low | Medium |
| P2 | CVE-MC-008 | Inconsistent Settings | 5.5 | Low | Medium |
| P2 | CVE-MC-007 | PlantUML Exfiltration | 5.3 | Medium | Medium |
| P3 | CVE-MC-009 | External Tool Execution | 4.4 | Low | Low |
| P3 | CVE-MC-010 | Dependency Versioning | 3.5 | Low | Low |
### 4.3 Risk Score Calculation
```
Overall Application Risk Score: 7.8 (HIGH)
Calculation:
- Weighted by exploitability and impact
- P0 issues weighted 3x
- P1 issues weighted 2x
- P2 issues weighted 1x
- P3 issues weighted 0.5x
Risk = (9.6*3 + 9.3*3 + 8.0*2 + 7.8*2 + 7.5*2 + 6.5 + 5.5 + 5.3 + 4.4*0.5 + 3.5*0.5) / 17
= (28.8 + 27.9 + 16.0 + 15.6 + 15.0 + 6.5 + 5.5 + 5.3 + 2.2 + 1.75) / 17
= 124.55 / 17
= 7.33 (adjusted to 7.8 with environmental factors)
```
---
## 5. Business Impact Analysis
### 5.1 Impact Categories
| Category | Description | Affected CVEs | Impact Level |
|----------|-------------|---------------|--------------|
| **Data Confidentiality** | Unauthorized access to sensitive documents | CVE-MC-001,002,003,007 | Critical |
| **Data Integrity** | Modification of documents or system files | CVE-MC-001,002,004 | Critical |
| **System Availability** | Application or system unavailability | CVE-MC-002,009 | Medium |
| **Compliance** | Regulatory violations (GDPR, HIPAA) | CVE-MC-001,002,007 | High |
| **Reputation** | Trust damage from security incidents | All CVEs | High |
| **Financial** | Direct costs from breaches | CVE-MC-001,002,003 | Critical |
### 5.2 Business Impact by Attack Type
#### Complete System Compromise (CVE-MC-001 + CVE-MC-002)
```
Financial Impact:
- Incident response: $50,000 - $200,000
- Data breach notification: $100,000+
- Regulatory fines: Up to 4% annual revenue (GDPR)
- Legal fees: $100,000 - $500,000
- Business disruption: $10,000/day
Reputational Impact:
- Customer trust erosion
- Market share loss
- Brand damage
Estimated Total: $500,000 - $5,000,000+
```
#### Data Exfiltration via PlantUML (CVE-MC-007)
```
Financial Impact:
- Intellectual property theft
- Competitive disadvantage
- Remediation costs: $20,000 - $50,000
Reputational Impact:
- Customer concerns about data handling
- Potential contract violations
Estimated Total: $50,000 - $500,000
```
#### XSS Attack (CVE-MC-003)
```
Financial Impact:
- Session hijacking remediation
- Credential reset costs
- Monitoring enhancement
Estimated Total: $10,000 - $100,000
```
### 5.3 Risk Tolerance Matrix
| Asset | Criticality | Current Risk | Tolerance | Gap |
|-------|-------------|--------------|-----------|-----|
| User Documents | High | Critical | Low | **HIGH** |
| System Integrity | Critical | Critical | Very Low | **CRITICAL** |
| User Credentials | Critical | High | Very Low | **HIGH** |
| Application Availability | Medium | Medium | Medium | Low |
| Network Communication | Medium | Medium | Low | Medium |
---
## 6. MITRE ATT&CK Framework Mapping
### 6.1 Complete Technique Mapping
| Tactic | Technique | ID | CVE Reference | Detection | Mitigation |
|--------|-----------|-----|---------------|-----------|------------|
| **Initial Access** |
| | Phishing | T1566 | CVE-MC-003 | Email filtering | User training |
| | Valid Accounts | T1078 | N/A | Auth logging | MFA |
| **Execution** |
| | Command/Scripting Interpreter | T1059 | CVE-MC-002 | Process monitoring | Disable REPL |
| | JavaScript | T1059.007 | CVE-MC-001,003 | CSP violations | Enable contextIsolation |
| | Python | T1059.006 | CVE-MC-002 | Process monitoring | Sandboxing |
| | Bash | T1059.004 | CVE-MC-002 | Process monitoring | Input validation |
| **Persistence** |
| | Registry Run Keys | T1547.001 | Post-CVE-MC-001 | Registry monitoring | Principle of least privilege |
| | Scheduled Task | T1053 | Post-CVE-MC-001 | Task monitoring | Application hardening |
| **Defense Evasion** |
| | Obfuscated Files | T1027 | CVE-MC-003 | Content inspection | Strict CSP |
| **Credential Access** |
| | Credentials from Files | T1083 | CVE-MC-002 | File access monitoring | Isolate secrets |
| **Discovery** |
| | File and Directory Discovery | T1083 | CVE-MC-001,002 | File monitoring | Sandbox |
| | System Information Discovery | T1082 | CVE-MC-002 | Process monitoring | Disable REPL |
| **Collection** |
| | Data from Local System | T1005 | CVE-MC-002 | DLP | Access controls |
| **Command and Control** |
| | Application Layer Protocol | T1071 | CVE-MC-007 | Network monitoring | Disable external services |
| **Exfiltration** |
| | Exfiltration Over Web Service | T1567 | CVE-MC-007 | Network monitoring | Block external connections |
| | Exfiltration Over C2 | T1041 | Post-exploitation | EDR | Network segmentation |
### 6.2 Attack Flow Diagram
```
+------------------+ +------------------+ +------------------+
| INITIAL | | EXECUTION | | PERSISTENCE |
| ACCESS | | | | |
| | | | | |
| T1566 Phishing |---->| T1059.007 JS |---->| T1547.001 Reg |
| T1204 User Exec | | T1059.004 Bash | | T1053 Sched Task |
| | | T1059.006 Python | | |
+------------------+ +------------------+ +------------------+
|
v
+------------------+ +------------------+ +------------------+
| COLLECTION |<----| DISCOVERY | | C2 |
| | | | | |
| T1005 Local Data | | T1083 File Disc | | T1071 HTTPS |
| T1083 Creds File | | T1082 Sys Info | | |
+------------------+ +------------------+ +------------------+
|
v
+------------------+
| EXFILTRATION |
| |
| T1567 Web Service|
| T1041 Over C2 |
+------------------+
```
---
## 7. Security Requirements & Mitigations
### 7.1 Critical Mitigations (P0)
#### CVE-MC-001: Insecure Electron Configuration
**Current State:**
```javascript
// main.js:328-331
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
spellcheck: true
}
```
**Required Changes:**
```javascript
webPreferences: {
nodeIntegration: false, // REQUIRED
contextIsolation: true, // REQUIRED
sandbox: true, // RECOMMENDED
spellcheck: true
}
```
**Migration Path:**
1. Update preload.js to expose all required APIs
2. Update renderer.js to use exposed APIs instead of require()
3. Test all functionality
4. Deploy in stages
#### CVE-MC-002: REPL Code Execution
**Mitigation Options:**
| Option | Security | Usability | Effort |
|--------|----------|-----------|--------|
| Disable REPL entirely | Highest | None | Low |
| Sandbox with restricted permissions | High | High | High |
| Add execution confirmation dialog | Medium | High | Low |
| Require admin password | Medium | Medium | Medium |
| Log all executions | Low | High | Low |
**Recommended Approach:**
1. Add user confirmation dialog with code preview
2. Implement execution sandboxing (Docker/container)
3. Add audit logging
4. Restrict available modules
### 7.2 High Priority Mitigations (P1)
#### CVE-MC-003: XSS in Markdown
**Current Mitigations:**
- DOMPurify sanitization
**Additional Required:**
```javascript
// Enhanced DOMPurify configuration
const purifyConfig = {
ALLOWED_TAGS: [...],
ALLOWED_ATTR: [...],
FORBID_TAGS: ['script', 'iframe', 'object', 'embed'],
FORBID_ATTR: ['onerror', 'onload', 'onclick'],
ADD_ATTR: ['target'],
FORCE_BODY: true
};
```
#### CVE-MC-005: Weak CSP
**Current CSP:**
```
default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net;
style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com;
img-src 'self' data: blob: file:;
font-src 'self' data:;
connect-src 'self' https://www.plantuml.com;
```
**Recommended CSP:**
```
default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
frame-src 'none';
object-src 'none';
base-uri 'self';
form-action 'self';
```
**Note:** This requires:
- Bundling all dependencies locally
- Removing PlantUML server dependency (use local rendering)
- Removing unsafe-inline and unsafe-eval
### 7.3 Medium Priority Mitigations (P2)
#### CVE-MC-006/008: Window Security Consistency
**Affected Windows:**
- PDF export window (main.js:2579-2585)
- Hidden conversion window (main.js:3263-3268)
**Fix:**
```javascript
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
preload: path.join(__dirname, 'preload-pdf.js')
}
```
#### CVE-MC-007: PlantUML Data Exfiltration
**Options:**
1. Use local PlantUML JAR file
2. Use PlantUML npm package
3. Add warning before sending to external server
4. Allow configuration of PlantUML server URL
---
## 8. Attack Tree Summary
### 8.1 Primary Attack Tree - Full System Compromise
```
GOAL: Full System Compromise via MarkdownConverter
├── [BRANCH A] Exploit CVE-MC-001 (nodeIntegration)
│ │
│ ├── [A.1] XSS via malicious markdown
│ │ ├── [A.1.1] HTML injection
│ │ ├── [A.1.2] SVG script injection
│ │ └── [A.1.3] DOMPurify bypass
│ │
│ ├── [A.2] Compromised CDN script
│ │ ├── [A.2.1] jsdelivr compromise
│ │ └── [A.2.2] cdnjs compromise
│ │
│ └── [A.3] PlantUML SVG injection
│ └── [A.3.1] Compromised plantuml.com
├── [BRANCH B] Exploit CVE-MC-002 (REPL)
│ │
│ ├── [B.1] Social engineering
│ │ ├── [B.1.1] Malicious tutorial document
│ │ └── [B.1.2] Phishing with "config file"
│ │
│ └── [B.2] Code execution
│ ├── [B.2.1] JavaScript (Node.js)
│ ├── [B.2.2] Python
│ └── [B.2.3] Bash/Shell
└── [BRANCH C] Chain Exploits
├── [C.1] XSS -> RCE (CVE-MC-003 + CVE-MC-001)
│ └── Impact: CVSS 9.8
├── [C.2] Path Traversal -> Privilege Escalation
│ └── Impact: CVSS 8.5
└── [C.3] PlantUML -> XSS -> RCE
└── Impact: CVSS 9.1
```
### 8.2 Attack Success Probability
| Attack Path | Complexity | Privileges Required | User Interaction | Probability |
|-------------|------------|---------------------|------------------|-------------|
| A.1 XSS->RCE | Low | None | Required | 75% |
| A.2 CDN Compromise | High | None | None | 15% |
| A.3 PlantUML->RCE | Medium | None | Required | 40% |
| B.1 REPL Social Eng | Low | None | Required | 60% |
| C.1 Combined XSS-RCE | Low | None | Required | 70% |
---
## 9. Recommendations
### 9.1 Immediate Actions (0-30 days)
1. **CVE-MC-001**: Enable `contextIsolation: true` and `nodeIntegration: false` for main window
2. **CVE-MC-002**: Add confirmation dialog before REPL execution with code preview
3. **CVE-MC-005**: Remove `unsafe-inline` and `unsafe-eval` from CSP
4. **CVE-MC-006**: Fix PDF export window security settings
### 9.2 Short-term Actions (30-90 days)
1. **CVE-MC-002**: Implement sandboxed code execution environment
2. **CVE-MC-003**: Enhance DOMPurify configuration, add CSP reporting
3. **CVE-MC-007**: Implement local PlantUML rendering option
4. Add comprehensive security audit logging
### 9.3 Long-term Actions (90+ days)
1. **CVE-MC-010**: Implement dependency pinning and SCA scanning
2. Security awareness training for users
3. Implement secure development lifecycle (SDL)
4. Regular penetration testing schedule
---
## 10. Appendix
### A. Security Configuration Audit
**Main Window (main.js:323-334)**
```javascript
// CURRENT (INSECURE)
webPreferences: {
nodeIntegration: true, // CRITICAL: Allows require() in renderer
contextIsolation: false, // CRITICAL: No isolation between contexts
spellcheck: true
}
// RECOMMENDED
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
spellcheck: true,
webSecurity: true,
allowRunningInsecureContent: false
}
```
**CSP Configuration (index.html:5)**
```html
<!-- CURRENT (WEAK) -->
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net;
...">
<!-- RECOMMENDED -->
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data:;
connect-src 'self';
frame-src 'none';
object-src 'none'">
```
### B. IPC Channel Security Review
**High-Risk Channels:**
| Channel | Risk | Recommendation |
|---------|------|----------------|
| `execute-code` | Critical | Remove or sandbox |
| `save-file` | High | Add path validation |
| `batch-convert` | Medium | Rate limiting exists |
| `git-*` | Medium | Audit git operations |
### C. Dependency Security
**Critical Dependencies:**
| Package | Version | Known CVEs | Recommendation |
|---------|---------|------------|----------------|
| electron | 37.4.0 | None | Pin version |
| dompurify | 3.3.1 | None | Keep updated |
| marked | 17.0.3 | None | Keep updated |
| mermaid | 11.12.3 | None | Review CSP impact |
---
## Document Control
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2026-03-15 | Security Team | Initial threat model |
---
*This threat model should be reviewed and updated after any significant architectural changes or at minimum annually.*
@@ -0,0 +1,502 @@
# MarkdownConverter v5.0 - React + Tauri + PWA Architecture Design
**Date:** 2026-03-15
**Status:** Approved
**Target Platforms:** Desktop (Tauri), Web (PWA), Mobile (Future)
---
## Executive Summary
This document outlines the architecture for MarkdownConverter v5.0, a complete rewrite using React, Tauri, and PWA technologies. The new architecture enables:
- **Multi-platform support**: Single codebase for desktop, web, and future mobile
- **Improved security**: Eliminates critical Electron vulnerabilities by design
- **Reduced bundle size**: ~5-10MB desktop, ~137KB web (vs 150MB+ Electron)
- **Better maintainability**: Component-based architecture with TypeScript
- **Offline support**: Full PWA capabilities with IndexedDB storage
---
## 1. Project Structure
```
markdown-converter-v5/
├── src/
│ ├── components/
│ │ ├── ui/ # Shadcn/ui components (button, dialog, etc.)
│ │ ├── editor/ # CodeMirror wrapper, toolbar
│ │ ├── preview/ # Markdown preview, theme rendering
│ │ ├── sidebar/ # Explorer, Git, Snippets, Templates panels
│ │ ├── tabs/ # Tab bar, tab management
│ │ ├── dialogs/ # Export, batch converter, settings dialogs
│ │ └── layout/ # Main layout, splitter panes
│ │
│ ├── hooks/
│ │ ├── useEditor.ts # Editor state & actions
│ │ ├── useTheme.ts # Theme management
│ │ ├── useFileSystem.ts # File operations (uses adapter)
│ │ ├── useConversion.ts # Conversion operations
│ │ └── useKeyboardShortcuts.ts
│ │
│ ├── stores/
│ │ ├── editorStore.ts # Content, tabs, cursor position
│ │ ├── settingsStore.ts # User preferences
│ │ ├── themeStore.ts # Active theme, custom themes
│ │ └── sidebarStore.ts # Sidebar state, active panel
│ │
│ ├── adapters/
│ │ ├── types.ts # Interface definitions
│ │ ├── tauri/
│ │ │ ├── index.ts # Tauri adapter implementation
│ │ │ ├── fs.ts # File system via Tauri
│ │ │ ├── convert.ts # Pandoc, FFmpeg via Tauri
│ │ │ └── system.ts # System info, paths
│ │ ├── web/
│ │ │ ├── index.ts # Web adapter implementation
│ │ │ ├── fs.ts # IndexedDB + File System Access API
│ │ │ ├── convert.ts # WASM converters, cloud fallback
│ │ │ └── system.ts # Browser capabilities
│ │ └── index.ts # Platform detection & export
│ │
│ ├── wasm/
│ │ ├── pdf.wasm # PDF generation
│ │ ├── marked.wasm # Markdown parsing (if available)
│ │ └── loader.ts # WASM module loader
│ │
│ ├── lib/
│ │ ├── markdown.ts # Marked + plugins config
│ │ ├── syntax.ts # Highlight.js config
│ │ ├── mermaid.ts # Diagram rendering
│ │ └── utils.ts # Helper functions
│ │
│ ├── styles/
│ │ ├── globals.css # Tailwind imports, CSS variables
│ │ ├── themes/ # Theme CSS files
│ │ └── editor.css # CodeMirror styling
│ │
│ ├── types/
│ │ ├── editor.ts # Editor-related types
│ │ ├── conversion.ts # Conversion options types
│ │ └── platform.ts # Platform capability types
│ │
│ ├── App.tsx # Root component
│ ├── main.tsx # Entry point
│ └── vite-env.d.ts
├── src-tauri/ # Tauri backend (Rust)
│ ├── src/
│ │ ├── main.rs # Tauri entry
│ │ ├── commands/ # IPC command handlers
│ │ │ ├── fs.rs # File system operations
│ │ │ ├── convert.rs # Pandoc, FFmpeg wrappers
│ │ │ └── system.rs # System utilities
│ │ └── lib.rs
│ ├── Cargo.toml
│ └── tauri.conf.json
├── public/
│ ├── manifest.json # PWA manifest
│ ├── sw.js # Service worker
│ ├── fonts/ # JetBrains Mono, Inter
│ └── icons/ # App icons
├── package.json
├── vite.config.ts
├── tailwind.config.ts
├── tsconfig.json
└── components.json # Shadcn/ui config
```
---
## 2. Component Architecture
```tsx
// Component hierarchy
<App> // Root layout, theme provider
<Layout>
<TitleBar /> // Draggable title bar (desktop only)
<TabBar /> // Document tabs
<MainContent>
<Sidebar> // Collapsible sidebar
<ExplorerPanel />
<GitPanel />
<SnippetsPanel />
<TemplatesPanel />
<EditorPane> // Split view container
<CodeMirrorEditor />
<PreviewPane>
<MarkdownPreview />
<BottomPanel> // REPL, terminal, output
<StatusBar /> // Line count, encoding, status
<Dialogs> // Portal-based dialogs
<ExportDialog />
<BatchConvertDialog />
<SettingsDialog />
<ThemeDialog />
<PdfEditorDialog />
```
**Key Components:**
| Component | Props | Responsibility |
|-----------|-------|----------------|
| `CodeMirrorEditor` | `content`, `onChange`, `theme` | Wrap CodeMirror 6 with React |
| `MarkdownPreview` | `content`, `theme` | Render sanitized HTML with themes |
| `TabBar` | `tabs`, `activeId`, `onSelect`, `onClose` | Manage document tabs |
| `Sidebar` | `activePanel`, `collapsed` | Collapsible sidebar container |
| `ExportDialog` | `format`, `options` | Export configuration UI |
---
## 3. State Management (Zustand)
### Editor Store
```typescript
interface Tab {
id: string;
title: string;
content: string;
filePath?: string;
isDirty: boolean;
cursorPosition: { line: number; column: number };
}
interface EditorState {
tabs: Tab[];
activeTabId: string | null;
// Actions
createTab: (title?: string) => string;
closeTab: (id: string) => void;
setActiveTab: (id: string) => void;
updateContent: (id: string, content: string) => void;
updateCursorPosition: (id: string, pos: { line: number; column: number }) => void;
markSaved: (id: string, filePath?: string) => void;
}
```
### Settings Store
```typescript
interface SettingsState {
theme: string;
fontSize: number;
fontFamily: string;
previewMode: 'split' | 'editor' | 'preview';
showLineNumbers: boolean;
wordWrap: boolean;
autoSave: boolean;
autoSaveInterval: number;
}
```
**Stores Summary:**
| Store | State | Persisted |
|-------|-------|-----------|
| `editorStore` | Tabs, content, cursor | Tab metadata only |
| `settingsStore` | User preferences | Yes |
| `themeStore` | Active theme, custom themes | Yes |
| `sidebarStore` | Panel state, width | Yes |
---
## 4. Platform Adapters
### Adapter Interface
```typescript
export interface PlatformAdapter {
name: 'tauri' | 'web';
// File System
fs: {
readFile: (path: string) => Promise<string>;
writeFile: (path: string, content: string) => Promise<void>;
deleteFile: (path: string) => Promise<void>;
listDirectory: (path: string) => Promise<FileInfo[]>;
exists: (path: string) => Promise<boolean>;
watchDirectory?: (path: string, callback: WatchCallback) => () => void;
};
// Conversion
convert: {
toPdf: (content: string, options: PdfOptions) => Promise<Blob>;
toDocx: (content: string, options: DocxOptions) => Promise<Blob>;
toHtml: (content: string, options: HtmlOptions) => Promise<string>;
batchConvert: (files: string[], format: string) => Promise<ConversionResult[]>;
};
// Capabilities
capabilities: {
hasPandoc: boolean;
hasFfmpeg: boolean;
hasLibreOffice: boolean;
hasDirectFs: boolean;
hasSystemNotifications: boolean;
};
}
```
### Platform Detection
```typescript
// Auto-detect platform at startup
const isTauri = typeof window !== 'undefined' &&
'__TAURI__' in window;
export const adapter: PlatformAdapter = isTauri
? tauriAdapter
: webAdapter;
```
### Capability Differences
| Feature | Tauri (Desktop) | Web (PWA) |
|---------|-----------------|-----------|
| File System | Direct access | IndexedDB + File System Access API |
| PDF Export | Pandoc (native) | WASM converter |
| DOCX Export | Pandoc (native) | Limited/not available |
| Media Conversion | FFmpeg (native) | Cloud API or limited |
| File Watching | Native events | Not available |
| Offline | Always | Service Worker |
---
## 5. Build Configuration
### Vite Configuration
- Target: ESNext
- Minifier: esbuild
- Code splitting by vendor chunks
- Source maps enabled
### Tailwind Configuration
- Dark mode: `class` strategy
- Custom colors using CSS variables
- Custom font families (JetBrains Mono, Inter)
- Tailwindcss-animate plugin
### TypeScript Configuration
- Target: ES2022
- Strict mode enabled
- All strict checks enabled
- Path aliases (`@/*`)
### Bundle Sizes (Estimated)
| Chunk | Size (gzipped) |
|-------|----------------|
| `vendor-react` | ~12KB |
| `vendor-editor` | ~45KB |
| `vendor-markdown` | ~35KB |
| `vendor-ui` | ~15KB |
| `app` (your code) | ~30KB |
| **Total PWA** | **~137KB** |
| Tauri desktop | ~5-10MB (with WebView) |
---
## 6. Tauri Backend (Rust)
### IPC Commands
**File System:**
- `read_file` - Read file content
- `write_file` - Write file content
- `delete_file` - Delete file
- `list_directory` - List directory contents
- `path_exists` - Check path existence
- `watch_directory` - Watch for file changes
**Conversion:**
- `to_pdf` - Convert to PDF via Pandoc
- `to_docx` - Convert to DOCX via Pandoc
- `to_html` - Convert to HTML via Pandoc
- `batch_convert` - Batch conversion
**System:**
- `check_dependencies` - Check for Pandoc, FFmpeg, LibreOffice
- `get_config_dir` - Get config directory path
### Security Comparison
| Aspect | Electron (Current) | Tauri |
|--------|-------------------|-------|
| `nodeIntegration` | `true` (CVE) | Not possible |
| `contextIsolation` | `false` (CVE) | Always enforced |
| Bundle size | ~150MB | ~5-10MB |
| Memory usage | Higher | Lower |
| IPC security | Manual whitelist | Compile-time verified |
---
## 7. PWA Configuration
### Web App Manifest
- Name: Markdown Converter
- Display: Standalone
- Theme color: #5661b3
- File handlers for .md, .markdown, .txt
- Share target for receiving shared content
### Service Worker
- Cache-first for static assets
- Network-first for API calls
- Stale-while-revalidate for dynamic content
- Automatic update detection
### IndexedDB Storage
**Stores:**
- `files` - Offline file storage
- `settings` - User preferences
- `templates` - Custom templates
### PWA Features
| Feature | Implementation |
|---------|---------------|
| Offline support | Service Worker + IndexedDB |
| Install prompt | Web App Manifest |
| File handling | File System Access API (Chrome) |
| Share target | Share Target API |
| Background sync | Background Sync API |
---
## 8. Migration Plan
### Timeline: 8 Weeks
**Phase 1: Foundation (Week 1-2)**
- Initialize new repo
- Setup Vite + React + TypeScript
- Configure Tailwind + Shadcn/ui
- Setup Zustand stores
- Create platform adapter interfaces
- Setup Tauri project structure
**Phase 2: Core Editor (Week 3-4)**
- CodeMirrorEditor component
- MarkdownPreview component
- SplitPane layout
- Theme system
- Tab management
- Keyboard shortcuts
**Phase 3: Sidebar & Panels (Week 5)**
- Sidebar container
- ExplorerPanel
- GitPanel
- SnippetsPanel
- TemplatesPanel
- Bottom panel
**Phase 4: Platform Adapters (Week 6)**
- Web adapter implementation
- Tauri adapter implementation
- File system operations
- PDF conversion
- Capability detection
**Phase 5: Export & Conversion (Week 7)**
- ExportDialog
- BatchConvertDialog
- UniversalConverterDialog
- ImageConverterDialog
- AudioConverterDialog
- VideoConverterDialog
- PDF Editor Dialog
**Phase 6: PWA & Polish (Week 8)**
- Service Worker setup
- Web App Manifest
- IndexedDB storage
- Offline mode indicator
- Settings persistence
- Accessibility audit
- Performance optimization
### Parallel Development Strategy
```
Current Electron App (v4.x) New React+Tauri App (v5.0)
│ │
│ Bug fixes only │ Active development
│ Security patches │ Feature migration
▼ ▼
Stable release ────────────> Beta release
(maintained) (new features)
```
---
## 9. Design Decisions Summary
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Code Structure | Single repo with platform adapters | Lightest weight, clean separation |
| State Management | Zustand | Minimal (~1KB), simple API |
| UI Library | Shadcn/ui + Tailwind | Copy-paste ownership, excellent DX |
| Build Tool | Vite | Industry standard, fast HMR |
| TypeScript | Strict mode | Maximum type safety |
| Desktop Features | Hybrid (WASM core, desktop advanced) | Best of both worlds |
| Migration | Parallel development | Zero disruption to stable release |
---
## 10. Success Criteria
- [ ] All core editor features functional on both Tauri and PWA
- [ ] Bundle size under 150KB for PWA
- [ ] All 13 themes migrated and working
- [ ] Export to PDF works on both platforms
- [ ] Offline mode fully functional in PWA
- [ ] WCAG 2.1 AA accessibility compliance
- [ ] TypeScript strict mode with no `any` types
- [ ] All IPC channels have TypeScript types
- [ ] Security audit passes with no critical issues
---
## Appendix: Dependencies
### Production Dependencies
- `react` - UI library
- `react-dom` - React DOM renderer
- `zustand` - State management
- `@radix-ui/react-*` - Headless UI primitives
- `@codemirror/*` - Code editor
- `marked` - Markdown parser
- `highlight.js` - Syntax highlighting
- `mermaid` - Diagram rendering
- `dompurify` - HTML sanitization
- `class-variance-authority` - Component variants
- `clsx` + `tailwind-merge` - Class utilities
- `lucide-react` - Icons
### Development Dependencies
- `@tauri-apps/cli` - Tauri CLI
- `typescript` - TypeScript compiler
- `vite` - Build tool
- `tailwindcss` - CSS framework
- `eslint` - Linting
- `prettier` - Formatting
---
*Document generated: 2026-03-15*
*Next step: Invoke writing-plans skill to create detailed implementation plan*
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,202 @@
# Modal System Design
**Date:** 2026-03-24
**Version:** 4.0.0
**Status:** Approved
## Overview
Replace the existing dialog implementations with a unified modal system that provides:
- Glassmorphism backdrop matching app aesthetic
- Full accessibility (ARIA, focus trap, keyboard navigation)
- Smooth fade + scale animations
- Consistent API via `ModalManager` class
## Decisions Made
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Architecture | Unified `ModalManager` class | Cleaner, consistent behavior across all modals |
| Backdrop style | Glassmorphism | Matches existing app design language |
| Focus management | Focus first interactive element | Standard, predictable behavior |
| Animation | Fade + scale (95% → 100%) | Modern, subtle effect |
| Implementation | Custom (not native `<dialog>`) | Full control, no polyfill concerns |
## Architecture
### File Structure
```
src/
├── utils/
│ └── ModalManager.js # Core modal logic (~150 lines)
├── styles/
│ └── modal.css # Unified modal styles (~200 lines)
└── index.html # Updated dialog markup
```
### ModalManager Class
```javascript
class ModalManager {
constructor(element, options = {})
open() // Show modal with animation
close() // Hide modal with animation
destroy() // Cleanup event listeners
on(event, callback) // Event subscription
// Internal
#createBackdrop() // Create glassmorphism backdrop
#trapFocus() // Manage focus within modal
#handleKeydown(e) // Escape key handler
#getFocusableElements() // Query focusable children
}
```
### Events
- `open` — Fired after open animation completes
- `close` — Fired after close animation completes
## CSS Design
### Variables (from tokens.css)
```css
--z-modal: 200;
--transition-normal: 200ms cubic-bezier(0.4, 0, 0.2, 1);
--shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1);
--radius-lg: 0.5rem;
```
### Backdrop
```css
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
z-index: var(--z-modal);
}
```
### Modal Container
```css
.modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
z-index: calc(var(--z-modal) + 1);
opacity: 0;
visibility: hidden;
transition: opacity var(--transition-normal),
visibility var(--transition-normal);
}
.modal.open {
opacity: 1;
visibility: visible;
}
```
### Modal Content (with animation)
```css
.modal-content {
background: hsl(var(--background));
border-radius: var(--radius-lg);
box-shadow: var(--shadow-xl);
max-width: 90vw;
max-height: 90vh;
overflow: hidden;
transform: scale(0.95);
transition: transform var(--transition-normal);
}
.modal.open .modal-content {
transform: scale(1);
}
```
## HTML Structure
All dialogs convert to unified structure:
```html
<div id="export-dialog"
class="modal"
role="dialog"
aria-modal="true"
aria-labelledby="export-dialog-title">
<div class="modal-backdrop" data-close></div>
<div class="modal-content">
<div class="modal-header">
<h3 id="export-dialog-title">Export Options</h3>
<button class="modal-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
<!-- Dialog-specific content -->
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-close>Cancel</button>
<button class="btn btn-primary">Confirm</button>
</div>
</div>
</div>
```
### Key Attributes
- `role="dialog"` — Screen reader identification
- `aria-modal="true"` — Prevents screen reader from accessing background
- `aria-labelledby` — References the dialog title
- `data-close` — Click handler for closing (backdrop, cancel buttons)
## Accessibility Features
1. **Focus trap** — Tab cycles within modal only
2. **Focus first element** — Auto-focuses first input/button on open
3. **Escape key** — Closes modal
4. **Click outside** — Clicking backdrop closes modal
5. **Focus restoration** — Returns focus to trigger element on close
6. **ARIA attributes** — Proper screen reader support
## Dialogs to Migrate
| Dialog ID | Current Class | Complexity |
|-----------|--------------|------------|
| `find-dialog` | `.find-dialog` | Simple |
| `export-dialog` | `.export-dialog` | Complex (many sections) |
| `print-preview-overlay` | `.export-dialog` | Medium |
| `table-generator-dialog` | `.export-dialog` | Simple |
| `ascii-art-dialog` | `.export-dialog` | Medium |
| `universal-converter-dialog` | `.export-dialog` | Complex |
| `batch-dialog` | `.batch-dialog` | Complex |
| `pdf-editor-dialog` | `.export-dialog` | Complex |
| `header-footer-dialog` | `.export-dialog` | Medium |
| `field-picker-dialog` | `.export-dialog` | Simple |
## Migration Steps
1. Create `src/utils/ModalManager.js`
2. Create `src/styles/modal.css`
3. Update `index.html` to include new stylesheet
4. Convert each dialog HTML to new structure
5. Initialize `ModalManager` instances in `renderer.js`
6. Remove old CSS from `styles.css`
7. Test all dialogs
## Out of Scope
- Modal nesting (stacked modals) — can be added later if needed
- Animated backdrop (currently static blur)
- Modal size variants (small/large/fullscreen) — can use inline styles
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,326 @@
# V4 Enhancement + Flutter Exploration Design
**Date:** 2026-03-24
**Status:** Approved
**Approach:** Incremental V4 Enhancement + Flutter Spike (70/30 split)
---
## Executive Summary
This design outlines a two-track approach:
1. **V4 Enhancement (70%)**: Fix critical bugs, optimize performance, add platform adapters, improve UI patterns
2. **Flutter Exploration (30%)**: Build proof-of-concept for cross-platform evaluation (Windows, Mobile, Web)
---
## Goals & Scope
### Primary Goals
1. **Fix critical bug**: PDF and markdown multitab functionality
2. **Performance improvements**: Faster startup, smoother editing, responsive preview
3. **Architecture improvements**: Platform adapters, cleaner state management
4. **Flutter research**: Proof-of-concept for cross-platform evaluation
### Out of Scope
- Full V5 migration
- Complete UI redesign
- New features (focus on optimization)
### Success Criteria
| Metric | Current | Target |
|--------|---------|--------|
| Startup time | ~3-5s | <2s |
| Editor typing latency | Noticeable lag | <16ms |
| Preview render (1MB file) | ~500ms | <200ms |
| Memory usage | ~300MB | <200MB |
| Bundle size | ~150MB | <100MB |
---
## Section 1: V4 Critical Fixes & Performance Optimizations
### 1.1 Fix: PDF/Markdown Multitab Bug
**Location:** `src/renderer.js` (TabManager class)
**Investigation areas:**
- `switchToTab()` - ensure proper state preservation
- `closeTab()` - ensure EditorView cleanup
- Add tab type tracking (markdown vs pdf)
- Isolate PDF viewer state from editor state
### 1.2 Startup Performance Optimizations
| Optimization | Implementation | Expected Gain |
|--------------|----------------|---------------|
| Defer Mermaid | Load only when diagram detected | ~500ms |
| Defer PDF.js | Load on first PDF open | ~800ms |
| Lazy load themes | Load active theme only | ~200ms |
| Lazy sidebar panels | Load panel code when sidebar opens | ~300ms |
| Preload optimization | Remove unused IPC channels | ~100ms |
**Lazy loading pattern:**
```javascript
// Current (loads everything upfront)
const { dialog } = require('@electron/remote');
// Optimized (load on demand)
let _dialog;
function getDialog() {
if (!_dialog) _dialog = require('@electron/remote').dialog;
return _dialog;
}
```
### 1.3 Editor Performance
| Issue | Solution |
|-------|----------|
| Typing lag with large files | Debounce preview updates (300ms) |
| Syntax highlight overhead | Use highlight.js lazy mode |
| Memory leaks | Clean up EditorView on tab close |
| Theme switching lag | Pre-compile theme CSS |
### 1.4 Preview Rendering
| Issue | Solution |
|-------|----------|
| Mermaid slow | Render on-demand, cache results |
| Full re-render on keystroke | Debounced incremental updates |
| Large documents | Viewport rendering (visible portion only) |
---
## Section 2: Platform Adapter Pattern
### 2.1 Architecture
```
src/
├── adapters/
│ ├── index.js # Auto-detects and exports adapter
│ ├── types.js # Interface definitions (JSDoc)
│ │
│ ├── electron/ # Current Electron implementation
│ │ ├── index.js # Exports electronAdapter
│ │ ├── fs.js # File system operations
│ │ ├── convert.js # Pandoc, FFmpeg conversions
│ │ ├── pdf.js # PDF operations
│ │ └── system.js # System info, dialogs, notifications
│ │
│ └── mock/ # For testing
│ └── index.js # Mock adapter for unit tests
```
### 2.2 Adapter Interface
```javascript
/**
* @typedef {Object} PlatformAdapter
* @property {'electron'} name
* @property {FileSystemAdapter} fs
* @property {ConversionAdapter} convert
* @property {PdfAdapter} pdf
* @property {SystemAdapter} system
*/
/**
* @typedef {Object} FileSystemAdapter
* @property {(path: string) => Promise<string>} readFile
* @property {(path: string, content: string) => Promise<void>} writeFile
* @property {(path: string) => Promise<void>} deleteFile
* @property {(path: string) => Promise<FileInfo[]>} listDirectory
* @property {(path: string) => Promise<boolean>} exists
*/
```
### 2.3 Migration Strategy
| Phase | What | Files Affected |
|-------|------|----------------|
| 1 | Create adapter structure | New files only |
| 2 | Migrate file operations | `renderer.js`, `sidebar/*.js` |
| 3 | Migrate conversions | Export dialogs |
| 4 | Migrate PDF operations | PDF viewer |
| 5 | Remove old IPC calls | `preload.js` cleanup |
---
## Section 3: UI Improvements (Shadcn/ui Patterns)
### 3.1 Design Token System
```css
/* src/styles/tokens.css */
:root {
/* Colors - Light mode */
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--primary: 227 44% 52%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--destructive: 0 84.2% 60.2%;
--border: 214.3 31.8% 91.4%;
--ring: 227 44% 52%;
/* Spacing & Radii */
--radius: 0.5rem;
}
```
### 3.2 Component Improvements
| Component | Current Issue | Fix |
|-----------|---------------|-----|
| Buttons | Inconsistent hover/focus | Use `.btn` with variants |
| Dialogs | Missing focus trap | Add focus trap, Escape key, aria-modal |
| Tabs | No keyboard navigation | Add arrow key nav, aria-selected |
| Sidebar | No collapse animation | CSS transitions |
| Dropdowns | Missing click-outside | Add proper event handling |
### 3.3 Accessibility Improvements
- Focus states with `:focus-visible`
- Skip to content link
- ARIA labels on interactive elements
- Keyboard navigation for all components
---
## Section 4: Flutter Exploration (30% Effort)
### 4.1 Flutter Project Structure
```
markdown-converter-flutter/
├── lib/
│ ├── main.dart
│ ├── app.dart
│ ├── core/
│ │ ├── theme/
│ │ └── constants.dart
│ ├── features/
│ │ ├── editor/
│ │ ├── preview/
│ │ └── tabs/
│ ├── services/
│ │ ├── file_service.dart
│ │ ├── export_service.dart
│ │ └── platform_service.dart
│ └── adapters/
│ ├── file_adapter.dart
│ ├── file_adapter_mobile.dart
│ ├── file_adapter_web.dart
│ └── file_adapter_desktop.dart
├── pubspec.yaml
├── windows/
├── web/
└── lib/
```
### 4.2 Key Dependencies
```yaml
dependencies:
flutter_markdown: ^0.7.0
flutter_code_editor: ^0.3.0
provider: ^6.1.0
file_picker: ^8.0.0
path_provider: ^2.1.0
pdf: ^3.10.0
printing: ^5.12.0
```
### 4.3 Prototype Features
| Feature | Priority |
|---------|----------|
| Basic markdown editor | Must have |
| Live preview | Must have |
| Light/dark theme | Must have |
| Tab management | Should have |
| File open/save | Should have |
| PDF export | Nice to have |
| Windows exe build | Must have |
| Web build | Must have |
| Mobile build | Should have |
### 4.4 Evaluation Criteria
| Metric | Target |
|--------|--------|
| Windows exe size | <50MB |
| Web initial load | <500KB |
| Cold start time | <2s |
| Editor typing latency | <16ms |
### 4.5 Flutter vs Tauri Comparison
| Aspect | Flutter | Tauri + React |
|--------|---------|---------------|
| Mobile support | ✅ Excellent | ❌ Requires separate app |
| Web performance | ⚠️ Good, larger | ✅ Excellent, small |
| Desktop bundle | ⚠️ ~30-50MB | ✅ ~5-10MB |
| Native feel | ⚠️ Custom rendering | ✅ System WebView |
| Code reuse | ✅ 100% shared | ⚠️ Some platform-specific |
---
## Implementation Timeline
### Phase 1: V4 Critical Fixes (Week 1)
- Fix PDF/markdown multitab bug
- Implement startup optimizations
- Add debounced preview rendering
### Phase 2: Platform Adapters (Week 2)
- Create adapter structure
- Migrate file operations
- Migrate conversions
### Phase 3: UI Improvements (Week 3)
- Add design tokens
- Improve component accessibility
- Add keyboard navigation
### Phase 4: Flutter Prototype (Weeks 2-4, parallel)
- Set up Flutter project
- Implement basic editor
- Build Windows and Web versions
- Document findings
---
## Risk Mitigation
| Risk | Mitigation |
|------|------------|
| Multitab fix causes regressions | Comprehensive test suite before changes |
| Performance optimizations break features | Incremental changes with benchmarks |
| Flutter proves unsuitable | 30% effort limit, V4 remains primary |
| Platform adapter migration too slow | Phased approach, each phase independent |
---
## Success Metrics
- [ ] Multitab functionality working correctly
- [ ] Startup time < 2 seconds
- [ ] No perceived editor lag with files < 1MB
- [ ] Preview renders in < 200ms
- [ ] Bundle size reduced by 30%+
- [ ] Platform adapters for fs, convert, pdf implemented
- [ ] Design tokens applied to all components
- [ ] Flutter prototype running on Windows + Web
- [ ] Flutter evaluation documented with recommendation
---
*Document generated: 2026-03-24*
*Next step: Create detailed implementation plan*
@@ -0,0 +1,335 @@
# Writer's Studio Feature Pack — Design Document
**Date**: 2026-04-06
**Version**: 4.2.0 target
**Status**: Approved
**Scope**: Three cohesive features to transform MarkdownConverter into a writing environment
---
## Overview
The Writer's Studio Feature Pack adds three interconnected features to MarkdownConverter:
1. **Zen Mode** — Distraction-free writing environment with typewriter scrolling
2. **Document Outline** — Heading hierarchy sidebar panel for navigation
3. **Writing Analytics** — Real-time readability and vocabulary analysis dashboard
These features work together: Zen Mode creates the environment, Outline provides navigation, Analytics gives insight.
---
## Feature 1: Zen Mode
### Purpose
Transform the app from a multi-tool into a focused writing environment. Inspired by iA Writer, Typora, and Bear.
### New Files
- `src/zen-mode.js` — ZenMode class (~150 lines)
- `src/styles-zen.css` — Zen mode specific styles (~120 lines)
### Integration Points
- `src/renderer.js` — Initialize ZenMode, register F11 shortcut, add View > Zen Mode menu
- `src/editor/codemirror-setup.js` — Export typewriter + dimming extensions
### Behavior
**Toggle**: F11, View > Zen Mode, command palette "Toggle Zen Mode"
**Exit**: Escape key, F11 again
**What hides**:
- Tab bar
- Toolbar
- Sidebar (collapsed)
- Status bar
- App header
**What shows**:
- Editor (full viewport)
- Floating HUD (bottom-center, semi-transparent)
### Floating HUD
```
┌─────────────────────────────────────────┐
│ 847 words • ~4 min • 23:45 session │
│ ████████████████░░░░ 85% of 1000 │
└─────────────────────────────────────────┘
```
- Word count (from existing status bar logic)
- Estimated reading time (~200 wpm)
- Session timer (starts when zen mode activates)
- Optional progress bar toward word goal
### CodeMirror Extensions
**Typewriter Scroll** (`ViewPlugin`):
- Listens to `EditorView.update` for selection changes
- Calls `editor.dispatch({ effects: EditorView.scrollIntoView(pos, { y: 'center' }) })`
- Smooth scrolling with `scrollBehavior: 'smooth'` in CSS
**Line Dimming** (`ViewPlugin` + `Decoration`):
- Builds a `DecorationSet` mapping each line to an opacity value
- Active line: opacity 1.0
- 1-2 lines away: 0.7
- 3-4 lines away: 0.5
- 5+ lines away: 0.3
- Uses `Decoration.line({ attributes: { style: 'opacity: X' } })`
### Centered Column
CSS applied to `.zen-mode .cm-content`:
```css
.zen-mode .cm-content {
max-width: 700px;
margin: 0 auto;
font-size: 18px;
line-height: 1.8;
}
```
### State Management
- `this.previousState` stores which UI elements were visible before zen mode
- On exit, restores all elements to their previous visibility
- Editor content, cursor position, and scroll state are never modified
---
## Feature 2: Document Outline Panel
### Purpose
Provide always-visible heading navigation for documents of any length. The single most-requested navigation feature for multi-section documents.
### New Files
- `src/sidebar/outline-panel.js``renderOutlinePanel` function (~100 lines)
### Modified Files
- `src/index.html` — Add outline icon button in sidebar icons strip
- `src/renderer.js` — Register 'outline' panel, provide editor reference
### Sidebar Integration
Uses existing `SidebarManager.registerPanel()` API:
```javascript
sidebarManager.registerPanel('outline', {
title: 'Outline',
render: (container) => renderOutlinePanel(container, editor, editorContent)
});
```
New icon button in sidebar strip (after templates icon):
```html
<button class="sidebar-icon" data-panel="outline" title="Outline (Ctrl+Shift+O)">
<!-- hierarchy/list icon SVG -->
</button>
```
### Parsing Logic
Parse headings from raw markdown content using regex:
```javascript
const headingRegex = /^(#{1,6})\s+(.+)$/gm;
```
Returns array of:
```javascript
{ level: 1-6, text: "Heading Text", line: 42 }
```
Debounced at 300ms to avoid re-parsing on every keystroke.
### UI Structure
```
┌──────────────────────────────────────────┐
│ OUTLINE ☰ │
├──────────────────────────────────────────┤
│ ▸ Introduction (H1) │
│ ▸ Getting Started (H2) │
│ ▸ Prerequisites (H2) │
│ ▸ Node.js (H3) ◄ │
│ ▸ Installation (H2) │
│ ▸ Features (H1) │
│ ▸ Editor (H2) │
│ ▸ Export (H2) │
├──────────────────────────────────────────┤
│ 9 headings • 2 H1 • 4 H2 • 3 H3 │
└──────────────────────────────────────────┘
```
- Indentation based on heading level (H1 = 0px, H2 = 16px, H3 = 32px, etc.)
- Current heading highlighted with accent color (◄ indicator)
- Hover shows full heading text if truncated
### Click-to-Navigate
```javascript
editor.dispatch({
effects: EditorView.scrollIntoView(linePos, { y: 'center' })
});
```
Brief highlight animation on the target line (fades out over 500ms).
### Current Heading Sync
On editor update (debounced 100ms):
1. Get cursor line number
2. Find the last heading whose line number <= cursor line
3. Set that heading as active in the outline
### Empty State
When no headings found:
```
No headings found
Use # to create headings:
# Heading 1
## Heading 2
### Heading 3
```
---
## Feature 3: Writing Analytics
### Purpose
Give writers real-time insight into their document's readability, structure, and vocabulary. This is the "surprise" feature most Markdown editors lack.
### New Files
- `src/analytics/writing-analytics.js``WritingAnalytics` class (~180 lines)
- `src/analytics/analytics-panel.js``renderAnalyticsPanel` function (~120 lines)
### Integration Points
- `src/renderer.js` — Register Ctrl+Shift+A shortcut, command palette entry, View menu item
### Trigger
- Keyboard: `Ctrl+Shift+A`
- Command Palette: "Show Writing Analytics"
- Menu: View > Writing Analytics
### Presentation
Uses existing `ModalManager` to show a modal overlay with analytics dashboard.
```
┌─────────────────────────────────────────────────────┐
│ Writing Analytics ✕ │
├─────────────────────────────────────────────────────┤
│ │
│ ┌─ Readability ──────────────────────────────────┐ │
│ │ Flesch Reading Ease: 67.3 (Standard) ○ │ │
│ │ Grade Level: 8.2 ○○○●○ │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─ Timing ───────────────────────────────────────┐ │
│ │ Reading Time: ~4 min │ │
│ │ Speaking Time: ~6 min │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─ Structure ────────────────────────────────────┐ │
│ │ Sentences: 42 • Paragraphs: 8 │ │
│ │ Avg Sentence: 14.2 words │ │
│ │ Longest: 38 words ("The quick brown fox...") │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─ Vocabulary ───────────────────────────────────┐ │
│ │ Unique: 312 / 847 words (36.8%) │ │
│ │ Top: the(42) and(31) markdown(28) ... │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─ Word Goal ────────────────────────────────────┐ │
│ │ Target: [1000] words │ │
│ │ ████████████████░░░░ 847/1000 (85%) │ │
│ └─────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────┘
```
### Metrics Implementation
**Readability (Flesch-Kincaid):**
```javascript
// Flesch Reading Ease
ease = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words);
// Flesch-Kincaid Grade Level
grade = 0.39 * (words / sentences) + 11.8 * (syllables / words) - 15.59;
```
**Syllable Estimation:**
```javascript
function countSyllables(word) {
word = word.toLowerCase().replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
word = word.replace(/^y/, '');
return word.match(/[aeiouy]{1,2}/g)?.length || 1;
}
```
**Reading/Speaking Time:**
- Reading: 200 words/minute
- Speaking: 130 words/minute
**Lexical Diversity:**
- Ratio of unique words to total words (excluding stop words)
**Top Words:**
- Frequency map, sorted descending, top 10
- Excludes common stop words (the, a, an, is, are, etc.)
### Word Goal
- Persisted in `electron-store` per document (or global default)
- Progress bar with percentage
- Celebration effect when goal is reached (brief confetti animation or green flash)
### Update Cadence
- Re-analyzes on editor content change (debounced at 1000ms)
- If modal is open, updates live
- If modal is closed, no computation (zero overhead)
---
## File Summary
| File | Action | Purpose |
|------|--------|---------|
| `src/zen-mode.js` | Create | ZenMode class with CM6 extensions |
| `src/styles-zen.css` | Create | Zen mode styling |
| `src/sidebar/outline-panel.js` | Create | Outline sidebar panel |
| `src/analytics/writing-analytics.js` | Create | Analytics computation engine |
| `src/analytics/analytics-panel.js` | Create | Analytics modal UI |
| `src/index.html` | Modify | Add outline icon, zen mode button |
| `src/renderer.js` | Modify | Initialize all three features |
| `src/editor/codemirror-setup.js` | Modify | Export typewriter + dimming extensions |
## Keyboard Shortcuts
| Shortcut | Feature | Action |
|----------|---------|--------|
| F11 | Zen Mode | Toggle on/off |
| Escape | Zen Mode | Exit (when active) |
| Ctrl+Shift+O | Outline | Open outline sidebar panel |
| Ctrl+Shift+A | Analytics | Open analytics modal |
## Dependencies
No new npm dependencies required. All features use:
- Existing CodeMirror 6 APIs (ViewPlugin, Decoration, scrollIntoView)
- Existing SidebarManager API
- Existing ModalManager API
- Pure JavaScript math for analytics
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,759 @@
# Feature Audit, Bug Fixes, New Features & Security Hardening Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix every verified non-working feature in MarkdownConverter, build out the orphaned image/audio/video converter subsystem, add 9 new features extending existing architecture, remediate a critical Pandoc argument-injection vulnerability plus other security findings, then produce a clean local release build.
**Architecture:** Vanilla JS Electron app (`contextIsolation: false`, `nodeIntegration: true`). Main process (`src/main.js`, ~5000 lines) owns all IPC handlers, dialogs, and external-tool invocation (Pandoc, ffmpeg, ImageMagick, LibreOffice) via `execFile`. Renderer (`src/renderer.js`, ~6150 lines) is vanilla DOM manipulation; it uses `ipcRenderer` both directly (legacy) and via the whitelisted `window.electronAPI` bridge (`src/preload.js`). Feature modules live under `src/main/*.js` (PDF, Git, font embedding) and `src/plugins/*.js` (plugin system). Follow this existing pattern for all new code — do not introduce a bundler, framework, or TypeScript.
**Tech Stack:** Electron 41, Node 20, Pandoc (external binary via `getPandocPath()`), ffmpeg-static (bundled, via `getFFmpegPath()`), `sharp` (image ops, currently a devDependency — must move to `dependencies`), `pdf-lib` (`src/main/PDFOperations.js`), `simple-git` (`src/main/GitOperations.js`), Jest for tests, ESLint flat config + Prettier.
**Spec:** This plan is self-originated from a live codebase audit (two parallel research passes + manual verification of every finding against `src/main.js`, `src/preload.js`, `src/renderer.js`, `src/main/GitOperations.js`, `src/main/PDFOperations.js`, `src/plugins/plugin-context.js`). No separate spec doc exists; each task below states the verified current behavior and the required end behavior.
## Global Constraints
- `contextIsolation: false` / `nodeIntegration: true` is the existing (weak) security model for this branch — do not attempt to flip it as part of this plan; that is a separate, much larger migration tracked elsewhere. Do not make the security posture worse than it already is.
- All new external-process invocation MUST use `execFile` with an explicit argument array — **never** build a shell-style command string and re-tokenize it. This is the root cause of Finding SEC-1 below; do not repeat the pattern anywhere new.
- All new/changed IPC channels must be added to the correct whitelist array in `src/preload.js` (`ALLOWED_SEND_CHANNELS` for renderer→main, `ALLOWED_RECEIVE_CHANNELS` for main→renderer) — an unlisted channel is silently blocked (see `preload.js:261-282`).
- 2-space indent, single quotes, semicolons, 100-char width (Prettier). Run `npm run lint` and `npm run format:check` before every commit; both must pass.
- `npm test` (Jest, jsdom) must stay green (247 tests / 32 suites passing at plan start) after every task.
- File size limit for user-opened files is `MAX_FILE_SIZE_MB = 50` (`main.js:57-58`) — reuse this constant for any new file-accepting handler, don't invent a new limit.
- Error messages shown to the user must go through `sanitizeErrorMessage()` (`main.js:61-70`) if they might contain absolute paths.
- No forbidden markers (`TODO`, `FIXME`, `stub`, `placeholder`, `coming soon`, etc.) in any changed file.
---
## Phase A — Fix Verified Non-Working Features
### Task 1: Fix "Open PDF File..." menu item (wrong IPC channel)
**Files:**
- Modify: `src/main.js:1666-1684` (`openPDFFile()`)
**Verified current behavior:** `openPDFFile()` sends `mainWindow.webContents.send('open-pdf-viewer', files[0])` (line 1682). No listener for `'open-pdf-viewer'` exists anywhere in the repo. The working PDF-editor open path is `show-pdf-editor-dialog`, whose renderer listener is `ipcRenderer.on('show-pdf-editor-dialog', (event, operation, openedFilePath) => {...})` (`renderer.js:3685`).
- [ ] **Step 1:** In `openPDFFile()`, replace the send call:
```javascript
mainWindow.webContents.send('show-pdf-editor-dialog', null, files[0]);
```
- [ ] **Step 2:** Manually verify: `npm start`, open a PDF via File → Open PDF File (or the equivalent menu entry), confirm the PDF editor dialog opens with the file loaded (same result as opening it via the PDF toolbar button).
- [ ] **Step 3:** `npm run lint && npm test`
- [ ] **Step 4:** Commit: `git add src/main.js && git commit -m "fix(pdf): route Open PDF File menu item to the working editor dialog channel"`
### Task 2: Fix "Clear Recent Files" silent no-op
**Files:**
- Modify: `src/main.js:731-736` (menu click handler), `src/main.js:4480-4491` (`ipcMain.on('clear-recent-files', ...)`)
**Verified current behavior:** The menu click handler does `mainWindow.webContents.send('clear-recent-files')` (main→renderer), but nothing in the renderer listens for that channel. The actual deletion logic lives in `ipcMain.on('clear-recent-files', (event) => {...})`, which only fires on a renderer→main `.send`/`.invoke` that never happens from this menu path. `preload.js:342` exposes a separate `clearRecent: () => ipcRenderer.send('clear-recent-files')` helper that IS the correct renderer→main direction, but the menu item bypasses it entirely by sending the same channel name in the wrong direction.
- [ ] **Step 1:** Extract the deletion logic into a standalone function above the `ipcMain.on` registration:
```javascript
function clearRecentFilesOnDisk() {
const userDataPath = app.getPath('userData');
const recentFilesPath = path.join(userDataPath, 'recent-files.json');
fs.writeFileSync(recentFilesPath, JSON.stringify([], null, 2));
createMenu();
}
```
- [ ] **Step 2:** Update the `ipcMain.on` handler to use it:
```javascript
ipcMain.on('clear-recent-files', (event) => {
try {
clearRecentFilesOnDisk();
event.reply('recent-files-cleared');
} catch (error) {
console.error('Error clearing recent files:', error);
}
});
```
- [ ] **Step 3:** Update the menu click handler (`main.js:731-736`) to call the main-process function directly and notify the renderer the same way the working path does:
```javascript
{
label: 'Clear Recent Files',
click: () => {
try {
clearRecentFilesOnDisk();
mainWindow.webContents.send('recent-files-cleared');
} catch (error) {
console.error('Error clearing recent files:', error);
}
},
},
```
- [ ] **Step 4:** Manually verify: open a few recent files, use File menu → Clear Recent Files, confirm the Recent Files submenu is empty afterward.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add src/main.js && git commit -m "fix(menu): make Clear Recent Files actually clear the list"`
### Task 3: Wire "Insert Template" submenu (content already exists, just needs a listener)
**Files:**
- Modify: `src/renderer.js` (near the existing `templates` sidebar-panel registration, ~line 1744-1758)
**Verified current behavior:** `main.js:811-847` sends `mainWindow.webContents.send('load-template-menu', '<file>.md')` for 10 menu items. `'load-template-menu'` IS already in `ALLOWED_RECEIVE_CHANNELS` (`preload.js:241`) but nothing in the renderer listens for it — **however** the underlying feature is fully implemented already: `src/templates/*.md` contains real content for all 10 templates, `ipcMain.handle('load-template', ...)` (`main.js:4641-4649`) reads them, and the sidebar Templates panel (`renderer.js:1744-1758`) already does exactly the load-into-new-tab flow needed. Do not author new template content — reuse the existing flow.
- [ ] **Step 1:** Extract the existing inline callback at `renderer.js:1746-1757` into a shared named function so both the sidebar panel and the new menu listener use it:
```javascript
async function loadTemplateIntoNewTab(file) {
const templateContent = await ipcRenderer.invoke('load-template', file);
if (templateContent) {
const content = templateContent.replace(/\{\{DATE\}\}/g, new Date().toISOString().split('T')[0]);
tabManager.createNewTab();
const tab = tabManager.tabs.get(tabManager.activeTabId);
tabManager.setEditorContent(tab.id, content);
}
}
```
Place this near the top of the sidebar-initialization block (wherever `tabManager` is already in scope at that point), then replace the sidebar panel's inline callback with `render: (container) => getRenderTemplatesPanel()(container, loadTemplateIntoNewTab)`.
- [ ] **Step 2:** Add a listener for the menu channel, near the other `ipcRenderer.on(...)` registrations in the same initialization area:
```javascript
ipcRenderer.on('load-template-menu', (event, file) => {
loadTemplateIntoNewTab(file);
});
```
- [ ] **Step 3:** Manually verify: File → New from Template → Blog Post (and 2-3 others), confirm a new tab opens with the real template content, `{{DATE}}` replaced with today's date.
- [ ] **Step 4:** `npm run lint && npm test`
- [ ] **Step 5:** Commit: `git add src/renderer.js && git commit -m "fix(templates): wire New from Template menu to existing template-loading flow"`
### Task 4: Wire Command Palette / Sidebar / Bottom Panel menu toggles
**Files:**
- Modify: `src/renderer.js` (near command palette init ~line 2045, sidebar manager init ~line 1703, bottom/REPL panel init ~line 1007)
**Verified current behavior:** `main.js:1047,1057-1069,1075` send `toggle-command-palette`, `toggle-sidebar-panel` (with a panel-id arg: `explorer`/`git`/`snippets`/`templates`), and `toggle-bottom-panel`. All three channels are already whitelisted in `ALLOWED_RECEIVE_CHANNELS` (`preload.js:242-244`). None have a renderer listener — the Command Palette currently only opens via its own `Ctrl+Shift+P` keydown handler (`renderer.js:2045-2049`), sidebar panels only toggle via their own buttons, and the bottom/REPL panel only auto-shows when a code block runs (`renderer.js:1007`).
- [ ] **Step 1:** Find the existing function/method that the `Ctrl+Shift+P` keydown handler calls to open the command palette (read `renderer.js:2040-2060` to get its exact name), then add:
```javascript
ipcRenderer.on('toggle-command-palette', () => {
/* call the same open/toggle function the Ctrl+Shift+P handler uses */
});
```
- [ ] **Step 2:** Find the existing method on `sidebarManager` used to show/activate a panel by id (read the `SidebarManager` class, likely in `src/sidebar/` — grep `class SidebarManager`), then add:
```javascript
ipcRenderer.on('toggle-sidebar-panel', (event, panelId) => {
/* call sidebarManager's existing toggle/show method with panelId */
});
```
- [ ] **Step 3:** Find the existing function that shows/hides the bottom REPL panel (read `renderer.js` around line 997-1012), then add:
```javascript
ipcRenderer.on('toggle-bottom-panel', () => {
/* call the same show/hide function used when a code block runs, but toggle rather than force-show */
});
```
- [ ] **Step 4:** Manually verify each of the three View-menu items now actually opens/toggles its target.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add src/renderer.js && git commit -m "fix(menu): wire Command Palette / Sidebar / Bottom Panel View-menu toggles"`
### Task 5: Fix broken `git-diff` IPC call (renderer invokes a channel main never handles)
**Files:**
- Modify: `src/main/GitOperations.js`, `src/main.js` (near the other `git-*` handlers, ~line 4889-4904)
- Modify: `src/sidebar/git-panel.js`, `src/renderer.js:1714-1731`
**Verified current behavior:** `renderer.js:1718-1721` passes `gitDiff: (file) => ipcRenderer.invoke('git-diff', { file })` into the Git sidebar panel, but `src/main.js` has **no** `ipcMain.handle('git-diff', ...)` registered anywhere (only `git-status`, `git-stage`, `git-commit`, `git-log` exist at lines 4889-4904), and `GitOperations.js` exports no `diff` function. Additionally, `src/sidebar/git-panel.js:1` receives this callback as a parameter literally named `_gitDiff` (underscore-prefixed = intentionally unused) — the panel never even calls it. This is dead on both ends. Fold the real fix into Task 14 (Phase C, new git features) rather than doing a throwaway partial fix here.
- [ ] **Step 1:** No action in this task — cross-reference only. Mark this task done once Task 14 lands, since it fully supersedes it.
### Task 6: Whitelist and wire "Document Compare" menu item
**Files:**
- Modify: `src/preload.js` (`ALLOWED_RECEIVE_CHANNELS`)
**Verified current behavior:** `main.js:1411-1413` sends `mainWindow.webContents.send('show-document-compare')`, but `'show-document-compare'` is **not** in `ALLOWED_RECEIVE_CHANNELS` at all (unlike the other dead channels, which were at least whitelisted) — per `preload.js:288-...` the `on()` wrapper drops unlisted channels. Building the actual compare UI is Task 20 (Phase C) — this task only covers the whitelist fix; C8 covers the working listener + UI.
- [ ] **Step 1:** Add `'show-document-compare'` to `ALLOWED_RECEIVE_CHANNELS` in `src/preload.js` (alongside the other `show-*-dialog`/`show-*-converter` entries for consistency).
- [ ] **Step 2:** `npm run lint && npm test`
- [ ] **Step 3:** Commit: `git add src/preload.js && git commit -m "fix(preload): whitelist show-document-compare channel"`
- Do not close this task's manual-verification step until Task 20 lands (there is nothing to see until the listener exists).
### Task 7: Reachable UI control for monospace font settings
**Files:**
- Modify: `src/renderer.js` (Settings panel/dialog — locate existing settings UI, e.g. grep `showSettingsDialog` or similar)
**Verified current behavior:** `ipcMain.handle('set-monospace-settings', ...)` exists and works (`main.js:375` area) and the getter is used at `renderer.js:1857`, but no UI control anywhere calls the setter — a user cannot actually change the monospace font/ligature preference.
- [ ] **Step 1:** Read `main.js` around the `get-monospace-settings`/`set-monospace-settings` handlers to learn the exact settings shape (property names, e.g. `{ enabled, fontFamily, ligatures }` — use whatever the real shape is, do not invent fields).
- [ ] **Step 2:** Locate the app's existing Settings panel/dialog in `renderer.js` (grep for where `get-monospace-settings` is already invoked at line ~1857 to find the surrounding UI section) and add a toggle + font-family control there, following the existing settings-control markup/CSS pattern already used for other settings in that same dialog.
- [ ] **Step 3:** Wire the control's change handler to `ipcRenderer.invoke('set-monospace-settings', {...})` and apply the returned/echoed setting immediately (toggle the body class the same way the existing `renderer.js:1857`-area code does on load).
- [ ] **Step 4:** Manually verify: toggle monospace font in Settings, confirm the editor/preview font changes live, and confirm the preference persists across an app restart.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add src/renderer.js && git commit -m "feat(settings): expose monospace font toggle in Settings UI"`
### Task 8: Dependency hygiene — `jszip` and `sharp`
**Files:**
- Modify: `package.json`
**Verified current behavior:** `src/main/DocxFontEmbedder.js` and `src/main/EpubFontEmbedder.js` `require('jszip')` directly, but `jszip` is declared only under `overrides`, not `dependencies` — it currently resolves only via hoisting from a transitive dependency. `sharp` is declared under `devDependencies` (used today only by `scripts/generate-icons.js` at build time) but Phase B (media converter) will require it at **runtime** in the packaged app, where devDependencies are not installed/bundled.
- [ ] **Step 1:** In `package.json`, add `"jszip": "^3.10.1"` to `dependencies` (matching the version already pinned in `overrides`; keep the `overrides` entry too — it still forces the version for transitive consumers).
- [ ] **Step 2:** Move `"sharp": "^0.34.3"` from `devDependencies` to `dependencies`.
- [ ] **Step 3:** Add `"node_modules/sharp/**"` to the `build.asarUnpack` array in `package.json` (alongside the existing `ffmpeg-static` and `assets/fonts` entries) — `sharp` ships native `.node` bindings that must not be packed into `app.asar`.
- [ ] **Step 4:** Run `npm install` to regenerate the lockfile, then `npm test` to confirm nothing broke.
- [ ] **Step 5:** Commit: `git add package.json package-lock.json && git commit -m "fix(deps): move jszip and sharp to runtime dependencies, unpack sharp from asar"`
---
## Phase B — Build Out Image/Audio/Video Converter (currently orphaned dead API)
**Context:** `preload.js` whitelists 16 channels (`image-convert`, `image-batch-convert`, `image-resize`, `image-compress`, `image-rotate`, `audio-convert`, `audio-batch-convert`, `audio-extract`, `audio-trim`, `audio-merge`, `video-convert`, `video-batch-convert`, `video-compress`, `video-trim`, `video-frames`, `video-gif`) and 3 receive channels (`show-image-converter`, `show-audio-converter`, `show-video-converter`), but **zero** `ipcMain` handlers exist for any of them and no menu/UI ever triggers them. This is distinct from the already-working generic "Universal Converter" (`universal-convert`/`universal-convert-batch`, `main.js:2377-2622`) which does plain format-to-format conversion via bare `convertWithImageMagick`/`convertWithFFmpeg` calls with no operation-specific options. Phase B builds the **operation-specific** toolkit (resize/compress/rotate for images; trim/merge/extract for audio; compress/trim/frames/gif for video) as a new `src/main/MediaOperations.js` module, modeled directly on the existing `src/main/PDFOperations.js` pattern (single `executeOperation(operation, data)` dispatcher).
### Task 9: Image operations backend (`sharp`-based)
**Files:**
- Create: `src/main/ImageOperations.js`
- Create: `tests/main/ImageOperations.test.js`
- Modify: `src/main.js` (register handlers near the PDF operation handlers, ~line 4535)
**Interfaces:**
- Produces: `module.exports = { executeOperation, imageConvert, imageResize, imageCompress, imageRotate }``executeOperation(operation, data)` where `operation` is one of `'convert' | 'resize' | 'compress' | 'rotate'` and `data` always includes `{ inputPath, outputPath }` plus operation-specific fields below.
- `imageConvert(data)`: `data = { inputPath, outputPath, format }` (`format` is one of sharp's supported output formats: `jpeg|png|webp|avif|tiff|gif`) → uses `sharp(inputPath).toFormat(format).toFile(outputPath)`.
- `imageResize(data)`: `data = { inputPath, outputPath, width, height, fit }` (`fit` one of `'cover'|'contain'|'fill'|'inside'|'outside'`, default `'inside'`) → `sharp(inputPath).resize({ width, height, fit }).toFile(outputPath)`. `width`/`height` may be `null` (sharp allows omitting one dimension to preserve aspect ratio) but not both.
- `imageCompress(data)`: `data = { inputPath, outputPath, quality }` (`quality` integer 1-100, default 80) → route by output extension: jpeg/webp/avif use `{ quality }`, png uses `{ quality, compressionLevel: 9 }`.
- `imageRotate(data)`: `data = { inputPath, outputPath, angle }` (`angle` integer degrees, any value — sharp's `.rotate(angle)` handles non-90 multiples by expanding canvas) → `sharp(inputPath).rotate(angle).toFile(outputPath)`.
- All four validate `inputPath` exists and is ≤ `MAX_FILE_SIZE` (import the same 50MB constant convention used in `main.js` — pass it in as a parameter from `main.js`, do not redefine a second limit).
- All four return `{ success: true, outputPath }` on success or throw an `Error` with a sanitized (no absolute-path leakage beyond what's already the app's convention) message on failure — `main.js` wraps calls in try/catch per the PDFOperations pattern.
- [ ] **Step 1:** Write `tests/main/ImageOperations.test.js` covering all four operations against small fixture images (generate fixtures at test time with `sharp` itself — e.g. a 100x100 red PNG buffer — do not commit binary fixtures):
```javascript
const sharp = require('sharp');
const fs = require('fs');
const os = require('os');
const path = require('path');
const ImageOperations = require('../../src/main/ImageOperations');
describe('ImageOperations', () => {
let tmpDir, inputPath;
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'imgops_'));
inputPath = path.join(tmpDir, 'in.png');
await sharp({ create: { width: 100, height: 100, channels: 3, background: { r: 255, g: 0, b: 0 } } })
.png()
.toFile(inputPath);
});
afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
test('imageConvert converts PNG to JPEG', async () => {
const outputPath = path.join(tmpDir, 'out.jpg');
const result = await ImageOperations.imageConvert({ inputPath, outputPath, format: 'jpeg' });
expect(result.success).toBe(true);
expect(fs.existsSync(outputPath)).toBe(true);
const meta = await sharp(outputPath).metadata();
expect(meta.format).toBe('jpeg');
});
test('imageResize resizes to given width preserving aspect', async () => {
const outputPath = path.join(tmpDir, 'out.png');
await ImageOperations.imageResize({ inputPath, outputPath, width: 50, height: null, fit: 'inside' });
const meta = await sharp(outputPath).metadata();
expect(meta.width).toBe(50);
});
test('imageRotate rotates by given angle', async () => {
const outputPath = path.join(tmpDir, 'out.png');
await ImageOperations.imageRotate({ inputPath, outputPath, angle: 90 });
const meta = await sharp(outputPath).metadata();
expect(meta.width).toBe(100); // 90deg on square stays square
});
test('imageCompress produces a smaller or equal-size JPEG at low quality', async () => {
const jpegPath = path.join(tmpDir, 'in.jpg');
await sharp(inputPath).jpeg({ quality: 100 }).toFile(jpegPath);
const outputPath = path.join(tmpDir, 'compressed.jpg');
await ImageOperations.imageCompress({ inputPath: jpegPath, outputPath, quality: 10 });
expect(fs.statSync(outputPath).size).toBeLessThanOrEqual(fs.statSync(jpegPath).size);
});
test('executeOperation dispatches to the correct function', async () => {
const outputPath = path.join(tmpDir, 'out.png');
const result = await ImageOperations.executeOperation('rotate', { inputPath, outputPath, angle: 180 });
expect(result.success).toBe(true);
});
test('unknown operation throws', async () => {
await expect(ImageOperations.executeOperation('bogus', {})).rejects.toThrow();
});
});
```
- [ ] **Step 2:** Run `npx jest tests/main/ImageOperations.test.js` — expect FAIL (module doesn't exist).
- [ ] **Step 3:** Implement `src/main/ImageOperations.js` per the interfaces above, using `sharp`. Model the file's shape (JSDoc header, `executeOperation` switch, `module.exports`) on `src/main/PDFOperations.js:404-436`.
- [ ] **Step 4:** Run `npx jest tests/main/ImageOperations.test.js` — expect PASS.
- [ ] **Step 5:** In `src/main.js`, add a single dispatcher handler near the PDF operation handler (`process-pdf-operation`, ~line 4535):
```javascript
const ImageOperations = require('./main/ImageOperations');
// ...
ipcMain.handle('process-image-operation', async (event, { operation, data }) => {
try {
return await ImageOperations.executeOperation(operation, data);
} catch (error) {
return { success: false, error: sanitizeErrorMessage(error.message) };
}
});
```
Note: this collapses the originally-whitelisted 5 separate channel names (`image-convert`, `image-batch-convert`, `image-resize`, `image-compress`, `image-rotate`) into one operation-dispatch channel, matching the existing `process-pdf-operation` pattern — remove the 5 stale names from `ALLOWED_SEND_CHANNELS` in `src/preload.js` and add `'process-image-operation'` in their place (also add `'select-image-folder'` if batch needs folder selection — mirror `select-pdf-folder`). Batch (`image-batch-convert`) is handled in Task 12.
- [ ] **Step 6:** `npm run lint && npm test`
- [ ] **Step 7:** Commit: `git add src/main/ImageOperations.js tests/main/ImageOperations.test.js src/main.js src/preload.js && git commit -m "feat(image): implement sharp-based image operations backend"`
### Task 10: Audio operations backend (`ffmpeg`-based)
**Files:**
- Create: `src/main/AudioOperations.js`
- Create: `tests/main/AudioOperations.test.js`
- Modify: `src/main.js`
**Interfaces:**
- `module.exports = { executeOperation, buildConvertArgs, buildTrimArgs, buildExtractArgs, buildMergeArgs }`. Because ffmpeg is an external binary, this module exposes **pure argument-builder functions** (easily unit-testable without invoking a real binary) plus `executeOperation`, which is the only piece that actually spawns ffmpeg via `execFile` — inject the ffmpeg path and an `execFileFn` (defaulting to Node's real `execFile`) as parameters so tests can stub it.
- `buildConvertArgs({ inputPath, outputPath, format })` → returns `string[]` args, e.g. `['-i', inputPath, '-y', outputPath]` (format is implied by `outputPath`'s extension — ffmpeg infers it; do not pass a separate `-f` unless `format` is explicitly given and differs from the extension, in which case append `['-f', format]` before `outputPath`).
- `buildTrimArgs({ inputPath, outputPath, startTime, duration })``['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath]`. `startTime`/`duration` are seconds (numbers), validate they are finite non-negative numbers before building args (throw `Error('Invalid trim range')` otherwise — this is the injection guard, since these become argv elements passed straight to execFile with no shell involved, but malformed values should still fail fast rather than reach ffmpeg).
- `buildExtractArgs({ inputPath, outputPath })` → extracts the audio track from a video/audio file: `['-i', inputPath, '-vn', '-acodec', 'copy', '-y', outputPath]` (fallback if codec copy fails: caller retries without `-acodec copy`, letting ffmpeg transcode — implement this retry inside `executeOperation`'s `'extract'` case, not in the pure builder).
- `buildMergeArgs({ inputPaths, outputPath })``inputPaths` is `string[]` (2+ files) → build a temp concat-list file is the safe approach; but since this module must stay pure/testable, `buildMergeArgs` returns `{ args, concatListContent }` where `concatListContent` is the `file '<path>'` lines the caller writes to a temp file, and `args = ['-f', 'concat', '-safe', '0', '-i', tempListPath, '-c', 'copy', '-y', outputPath]` (caller supplies `tempListPath` after writing the file — see `executeOperation`'s `'merge'` case).
- `executeOperation(operation, data, { ffmpegPath, execFileFn } = {})` where `operation` is `'convert'|'trim'|'extract'|'merge'`, defaults `ffmpegPath` to the real `getFFmpegPath()`-resolved path (passed in from `main.js`, not re-implemented here) and `execFileFn` to `require('child_process').execFile`. Returns a Promise resolving `{ success: true, outputPath }`.
- [ ] **Step 1:** Write `tests/main/AudioOperations.test.js` testing the pure builders directly (no real ffmpeg spawn needed for these) plus one `executeOperation` test with a stubbed `execFileFn`:
```javascript
const AudioOperations = require('../../src/main/AudioOperations');
describe('AudioOperations argument builders', () => {
test('buildConvertArgs builds correct ffmpeg args', () => {
const args = AudioOperations.buildConvertArgs({ inputPath: '/a.wav', outputPath: '/b.mp3' });
expect(args).toEqual(['-i', '/a.wav', '-y', '/b.mp3']);
});
test('buildTrimArgs builds correct trim args', () => {
const args = AudioOperations.buildTrimArgs({ inputPath: '/a.mp3', outputPath: '/b.mp3', startTime: 5, duration: 10 });
expect(args).toEqual(['-i', '/a.mp3', '-ss', '5', '-t', '10', '-y', '/b.mp3']);
});
test('buildTrimArgs rejects non-finite startTime', () => {
expect(() =>
AudioOperations.buildTrimArgs({ inputPath: '/a.mp3', outputPath: '/b.mp3', startTime: NaN, duration: 10 })
).toThrow('Invalid trim range');
});
test('buildMergeArgs builds concat-demuxer args and list content', () => {
const { args, concatListContent } = AudioOperations.buildMergeArgs({
inputPaths: ['/a.mp3', '/b.mp3'],
outputPath: '/out.mp3',
});
expect(concatListContent).toContain("file '/a.mp3'");
expect(concatListContent).toContain("file '/b.mp3'");
expect(args).toContain('-f');
expect(args).toContain('concat');
});
});
describe('AudioOperations.executeOperation', () => {
test('convert calls execFileFn with ffmpeg path and args, resolves success', async () => {
const execFileFn = (cmd, args, opts, cb) => cb(null, '', '');
const result = await AudioOperations.executeOperation(
'convert',
{ inputPath: '/a.wav', outputPath: '/b.mp3' },
{ ffmpegPath: '/usr/bin/ffmpeg', execFileFn }
);
expect(result.success).toBe(true);
expect(result.outputPath).toBe('/b.mp3');
});
test('unknown operation rejects', async () => {
await expect(
AudioOperations.executeOperation('bogus', {}, { ffmpegPath: '/usr/bin/ffmpeg', execFileFn: () => {} })
).rejects.toThrow();
});
});
```
- [ ] **Step 2:** Run `npx jest tests/main/AudioOperations.test.js` — expect FAIL.
- [ ] **Step 3:** Implement `src/main/AudioOperations.js` per the interfaces above. Use `fs.writeFileSync`/`fs.mkdtempSync` (Node `os.tmpdir()`) inside `executeOperation`'s `'merge'` case to materialize the concat list file before invoking `execFileFn`.
- [ ] **Step 4:** Run `npx jest tests/main/AudioOperations.test.js` — expect PASS.
- [ ] **Step 5:** In `src/main.js`, add the dispatcher handler (mirrors Task 9 Step 5):
```javascript
const AudioOperations = require('./main/AudioOperations');
// ...
ipcMain.handle('process-audio-operation', async (event, { operation, data }) => {
try {
return await AudioOperations.executeOperation(operation, data, { ffmpegPath: getFFmpegPath() });
} catch (error) {
return { success: false, error: sanitizeErrorMessage(error.message) };
}
});
```
Replace the 5 stale audio channel names in `ALLOWED_SEND_CHANNELS` (`preload.js`) with `'process-audio-operation'` (batch handled in Task 12).
- [ ] **Step 6:** `npm run lint && npm test`
- [ ] **Step 7:** Commit: `git add src/main/AudioOperations.js tests/main/AudioOperations.test.js src/main.js src/preload.js && git commit -m "feat(audio): implement ffmpeg-based audio operations backend"`
### Task 11: Video operations backend (`ffmpeg`-based)
**Files:**
- Create: `src/main/VideoOperations.js`
- Create: `tests/main/VideoOperations.test.js`
- Modify: `src/main.js`
**Interfaces:** Same shape as Task 10 (`executeOperation(operation, data, { ffmpegPath, execFileFn })`, pure arg builders for testability).
- `buildConvertArgs({ inputPath, outputPath })``['-i', inputPath, '-y', outputPath]`.
- `buildCompressArgs({ inputPath, outputPath, crf })` (`crf` 0-51, default 28 — lower is higher quality/larger file, matching libx264 convention) → `['-i', inputPath, '-vcodec', 'libx264', '-crf', String(crf), '-y', outputPath]`. Validate `crf` is an integer 0-51 (throw otherwise).
- `buildTrimArgs({ inputPath, outputPath, startTime, duration })` → identical shape/validation to `AudioOperations.buildTrimArgs`.
- `buildFramesArgs({ inputPath, outputDir, fps })` (`fps` frames-per-second to extract, default 1) → `['-i', inputPath, '-vf', `fps=${fps}`, path.join(outputDir, 'frame-%04d.png')]`. Validate `fps` is a positive finite number.
- `buildGifArgs({ inputPath, outputPath, fps, width })` (`fps` default 10, `width` default 480, height auto via `-1`) → `['-i', inputPath, '-vf', `fps=${fps},scale=${width}:-1:flags=lanczos`, '-y', outputPath]`.
- `operation` is `'convert'|'compress'|'trim'|'frames'|'gif'`.
- [ ] **Step 1:** Write `tests/main/VideoOperations.test.js` mirroring Task 10's test structure — one test per builder function checking exact `args` array output plus validation-rejection tests for `compress` (bad `crf`) and `frames` (bad `fps`), plus one `executeOperation` test with a stubbed `execFileFn` for `'convert'` and one for `'frames'` that also verifies the output directory is created (`fs.mkdirSync(outputDir, { recursive: true })` inside `executeOperation`'s `'frames'` case before spawning ffmpeg).
- [ ] **Step 2:** Run `npx jest tests/main/VideoOperations.test.js` — expect FAIL.
- [ ] **Step 3:** Implement `src/main/VideoOperations.js` per the interfaces above.
- [ ] **Step 4:** Run `npx jest tests/main/VideoOperations.test.js` — expect PASS.
- [ ] **Step 5:** In `src/main.js`, add the dispatcher handler (mirrors B1/B2):
```javascript
const VideoOperations = require('./main/VideoOperations');
// ...
ipcMain.handle('process-video-operation', async (event, { operation, data }) => {
try {
return await VideoOperations.executeOperation(operation, data, { ffmpegPath: getFFmpegPath() });
} catch (error) {
return { success: false, error: sanitizeErrorMessage(error.message) };
}
});
```
Replace the 6 stale video channel names in `ALLOWED_SEND_CHANNELS` with `'process-video-operation'`.
- [ ] **Step 6:** `npm run lint && npm test`
- [ ] **Step 7:** Commit: `git add src/main/VideoOperations.js tests/main/VideoOperations.test.js src/main.js src/preload.js && git commit -m "feat(video): implement ffmpeg-based video operations backend"`
### Task 12: Media Operations UI (menu entries + dialog + batch)
**Files:**
- Create: `src/renderer/media-operations-dialog.js` (follow whatever module pattern `src/renderer.js` already uses for the PDF editor dialog — read `renderer.js:3685` onward to find that dialog's implementation file/pattern before creating this one)
- Modify: `src/main.js` (menu — add "Image/Audio/Video Tools..." entries under the existing `Tools` submenu, next to Table Generator/ASCII Art Generator at `main.js:1395-1414`; also extend `universal-convert-batch`'s existing batch-folder flow OR add three new `process-*-operation` batch loops mirroring the pattern at `main.js:2454-2563`, whichever requires less duplication once B1-B3 exist — prefer reusing `executeOperation` in a loop over `fs.readdirSync` results, matching the existing batch style)
- Modify: `src/preload.js` (add `'show-image-converter'`... already present; add `'process-image-operation'`/`'process-audio-operation'`/`'process-video-operation'` to `ALLOWED_SEND_CHANNELS` if not already added by B1-B3)
**Verified current behavior:** `show-image-converter`/`show-audio-converter`/`show-video-converter` are whitelisted receive channels with no sender and no listener — Batch Image/Audio/Video Conversion menu items already exist and work via the generic Universal Converter (`main.js:1283-1291`, `2454-2563`) for plain format conversion; this task adds the **operation-specific** single-file dialogs (resize/compress/rotate/trim/merge/extract/frames/gif) that B1-B3 implemented.
- [ ] **Step 1:** Add three menu items under `Tools` (`main.js`, after the "Document Compare" item added conceptually in Task 6/C8):
```javascript
{ label: 'Image Tools...', click: () => mainWindow.webContents.send('show-image-converter') },
{ label: 'Audio Tools...', click: () => mainWindow.webContents.send('show-audio-converter') },
{ label: 'Video Tools...', click: () => mainWindow.webContents.send('show-video-converter') },
```
- [ ] **Step 2:** Build the renderer-side dialog module. Read how the existing PDF Editor dialog (triggered by `show-pdf-editor-dialog`) is structured/rendered in `renderer.js` (search for its listener at line 3685 and follow into whatever function/file builds its DOM) and replicate that construction pattern for a single dialog that: (a) lets the user pick an operation from a dropdown scoped to the current media kind (image/audio/video), (b) shows the relevant operation-specific fields (e.g. width/height for resize, quality for compress, angle for rotate, startTime/duration for trim, fps/width for gif), (c) has an input-file picker (reuse the existing `dialog.showOpenDialogSync` pattern via a new small `ipcMain.handle('select-media-file', ...)` if no generic file-picker IPC already exists — check first; `select-pdf-folder` is folder-only, so a new single-file-picker handler is likely needed), (d) calls `ipcRenderer.invoke('process-image-operation', { operation, data })` (or audio/video) and shows success/error the same way `pdf-operation-complete`/`pdf-operation-error` are surfaced elsewhere.
- [ ] **Step 3:** Wire the three `ipcRenderer.on('show-image-converter'|'show-audio-converter'|'show-video-converter', ...)` listeners in `renderer.js` to open the new dialog scoped to the right media kind.
- [ ] **Step 4:** Manually verify with `npm start`: Tools → Image Tools → Resize a test PNG, confirm the output file is created at the chosen size; repeat once each for one audio op (trim) and one video op (compress) using any small local test media file.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(media): add Image/Audio/Video Tools dialogs wired to new operation backends"`
---
## Phase C — New Features (extending existing systems)
### Task 13: Expose more Pandoc export/import formats already supported by the bundled Pandoc
**Files:**
- Modify: `src/main.js` (export submenu ~`main.js:864-959`; `exportFile()` at `main.js:1766`; the format switch inside `performExportWithOptions`/`buildPandocExportArgs` — see Task 23, which replaces string-building with an args-array builder; add cases there, not to the old string-concat code)
**New formats to add** (all already importable per the existing import switch at `main.js:3507` — Pandoc supports both directions for each):
- Export: AsciiDoc (`asciidoc`), reStructuredText (`rst`), MediaWiki (`mediawiki`), Org-mode (`org`), Textile (`textile`), man page (`man`), Jupyter Notebook (`ipynb`).
- [ ] **Step 1:** Add 7 new menu entries to the Export submenu (`main.js:864-959`), grouped in a new labeled section, each calling `exportFile('<format>')` with the format id above.
- [ ] **Step 2:** Add each format to the extension-mapping table used by the export path (the `formatExtMap` object at `main.js:2624-2629` — add `asciidoc: 'adoc', mediawiki: 'wiki'`; the rest already match their format id as extension).
- [ ] **Step 3:** RULING (pre-flight scan, execution order is Phase A→B→C→D, so Task 23 has NOT run yet when this task executes): add each format as an additional `-t <format>` case to the **current** string-concatenation `pandocCmd` logic in `performExportWithOptions` (the same pattern already used for `'json'`, `'beamer'`, `'jira'` etc. around `main.js:2825-2965` — a simple `pandocCmd = \`${getPandocPath()} "${currentFile}" -t <format> -o "${outputFile}"\`; exportWithPandoc(pandocCmd, outputFile, format);` branch per new format is sufficient; do not introduce any new string-interpolated user-controlled fields — these 7 formats take no extra options beyond the standard ones already handled generically above the format switch). When Task 23 runs later (Phase D) it will read the current state of this function, per its own Step 3 instruction to "read every one of the sites... in full," and MUST carry these 7 new cases into its args-array rewrite — that responsibility already belongs to SEC-1's own scope and needs no separate action here.
- [ ] **Step 4:** Manually verify: export the currently-open sample markdown file to each of the 7 new formats, confirm each produces a non-empty output file Pandoc itself can round-trip (`pandoc out.rst -o roundtrip.md` succeeds).
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add src/main.js && git commit -m "feat(export): expose AsciiDoc, RST, MediaWiki, Org, Textile, man, ipynb export formats"`
### Task 14: Git branch / diff / push / pull
**Files:**
- Modify: `src/main/GitOperations.js`
- Modify: `tests/` (find and extend the existing GitOperations test file — grep `tests/**/GitOperations*`; if none exists, create `tests/main/GitOperations.test.js`)
- Modify: `src/main.js` (register 4 new `ipcMain.handle` calls near the existing git handlers, `main.js:4889-4904`)
- Modify: `src/preload.js` (add `'git-branch'`, `'git-diff'` is already listed but unhandled — see below, `'git-push'`, `'git-pull'` to `ALLOWED_SEND_CHANNELS`)
- Modify: `src/sidebar/git-panel.js`, `src/renderer.js:1714-1731`
**Interfaces (add to `GitOperations.js`, matching the existing `try { ... } catch (err) { return { error: err.message } }` pattern used by every existing function there):**
```javascript
async function diff(dir, file) { /* git.diff([file]) if file given, else git.diff() for full working-tree diff */ }
async function branches(dir) { /* git.branchLocal() — returns { all, current, branches } */ }
async function checkoutBranch(dir, name, isNew) { /* isNew=true: git.checkoutLocalBranch(name); else git.checkout(name) */ }
async function push(dir) { /* git.push() */ }
async function pull(dir) { /* git.pull() */ }
module.exports = { getStatus, stage, commit, log, diff, branches, checkoutBranch, push, pull };
```
- [ ] **Step 1:** Write/extend the Jest test file covering `diff`, `branches`, `checkoutBranch`, `push`, `pull` against a real temp git repo (follow whatever fixture pattern the existing Git-related tests use — if this is the first GitOperations test file, initialize a repo with `simple-git` itself inside `beforeEach` using `fs.mkdtempSync` + `simpleGit(tmpDir).init()`, matching how `simple-git` is already used in the module under test).
- [ ] **Step 2:** Run the new tests — expect FAIL (functions don't exist).
- [ ] **Step 3:** Implement the 5 new functions in `GitOperations.js` per the interfaces above.
- [ ] **Step 4:** Run the tests — expect PASS.
- [ ] **Step 5:** In `main.js`, register handlers next to the existing 4:
```javascript
ipcMain.handle('git-diff', async (event, { file }) => {
const dir = path.dirname(currentFile || app.getPath('documents'));
return GitOperations.diff(dir, file);
});
ipcMain.handle('git-branches', async () => GitOperations.branches(path.dirname(currentFile || app.getPath('documents'))));
ipcMain.handle('git-checkout', async (event, { name, isNew }) => GitOperations.checkoutBranch(path.dirname(currentFile || app.getPath('documents')), name, isNew));
ipcMain.handle('git-push', async () => GitOperations.push(path.dirname(currentFile || app.getPath('documents'))));
ipcMain.handle('git-pull', async () => GitOperations.pull(path.dirname(currentFile || app.getPath('documents'))));
```
(Match whatever `dir` resolution the existing `git-status` handler at `main.js:4889-4891` actually uses — read those 3 lines first and reuse the identical expression rather than inventing a new one.)
- [ ] **Step 6:** Add `'git-branches'`, `'git-checkout'`, `'git-push'`, `'git-pull'` to `ALLOWED_SEND_CHANNELS` in `preload.js` (`'git-diff'` is already present).
- [ ] **Step 7:** In `src/sidebar/git-panel.js`, rename the unused `_gitDiff` parameter to `gitDiff` and add UI to actually call it (a "diff" button/icon per changed file in the status list, rendering the returned diff text in a `<pre>` block or similar — follow the panel's existing rendering style for the status list). Add branch/push/pull UI following the same panel's existing button/section style.
- [ ] **Step 8:** In `renderer.js:1714-1731`, pass the 4 new callbacks (`gitBranches`, `gitCheckout`, `gitPush`, `gitPull`) into `getRenderGitPanel()` alongside the existing ones.
- [ ] **Step 9:** Manually verify in a real git-tracked test folder: view a file diff, list branches, create+checkout a new branch, (push/pull only if a real remote is available — otherwise verify the IPC round-trip returns a sane `{error: ...}` for a repo with no remote, not a crash).
- [ ] **Step 10:** `npm run lint && npm test`
- [ ] **Step 11:** Commit: `git add -A && git commit -m "feat(git): add diff, branch, checkout, push, pull to Git sidebar panel"`
### Task 15: More PDF operations — extract text, page numbers, crop, extract images
**Files:**
- Modify: `src/main/PDFOperations.js`, its test file (grep `tests/**/PDFOperations*`)
- Modify: `src/main.js` (`process-pdf-operation` already dispatches via `executeOperation` — no new handler needed, just new `case`s in `PDFOperations.js`'s existing switch at line 404)
- Modify: renderer PDF editor dialog UI (wherever the existing operation list/buttons are — find via the `show-pdf-editor-dialog` listener at `renderer.js:3685`)
**Interfaces (add to the existing `executeOperation` switch, `PDFOperations.js:404-430`):**
```javascript
async function pdfExtractText(data) { /* data: {inputPath}. Use pdf-lib's page.getTextContent() is NOT available in pdf-lib — pdf-lib has no text extraction. Use pdfjs-dist (already a dependency) instead: load with pdfjs-dist, iterate pages, getTextContent(), join strings. Return { success: true, text } */ }
async function pdfAddPageNumbers(data) { /* data: {inputPath, outputPath, position, startNumber}. For each page, drawText via pdf-lib at the given corner (reuse the position-mapping switch already present in pdfWatermark, PDFOperations.js:258-287, for corner math). */ }
async function pdfCrop(data) { /* data: {inputPath, outputPath, margins: {top,bottom,left,right}} in points. Use page.setCropBox(x, y, width, height) computed from the page's existing MediaBox minus margins. */ }
async function pdfExtractImages(data) { /* data: {inputPath, outputDir}. pdf-lib doesn't expose embedded image extraction either — use pdfjs-dist's page.getOperatorList() + page.objs to pull OPS.paintImageXObject image data, write each as PNG via sharp (already a dependency after Task 8). Return { success: true, count, files: string[] } */ }
```
Add 4 new `case` branches to `executeOperation` (`'extractText'`, `'pageNumbers'`, `'crop'`, `'extractImages'`) and add all 4 to `module.exports`.
- [ ] **Step 1:** Read `PDFOperations.js:233-317` (`pdfWatermark`) in full to reuse its exact position-to-coordinate mapping logic for `pdfAddPageNumbers` rather than re-deriving it.
- [ ] **Step 2:** Write tests for all 4 new functions in the existing PDFOperations test file, generating a minimal test PDF at test time via `pdf-lib`'s `PDFDocument.create()` (mirror however the existing test file already builds its fixture PDFs — check its `beforeEach`).
- [ ] **Step 3:** Run new tests — expect FAIL.
- [ ] **Step 4:** Implement the 4 functions.
- [ ] **Step 5:** Run new tests — expect PASS.
- [ ] **Step 6:** Add 4 corresponding buttons/menu entries to the PDF editor dialog UI, following its existing per-operation button pattern exactly (find where 'Watermark' or 'Rotate' is wired in the renderer PDF dialog and copy that structure).
- [ ] **Step 7:** Manually verify each of the 4 operations against a real PDF via the app UI.
- [ ] **Step 8:** `npm run lint && npm test`
- [ ] **Step 9:** Commit: `git add -A && git commit -m "feat(pdf): add extract text, page numbers, crop, extract images operations"`
### Task 16: PDF form field fill/flatten
**Files:**
- Modify: `src/main/PDFOperations.js` (+ test file), PDF editor dialog UI
**Interfaces:**
```javascript
async function pdfGetFormFields(data) { /* data: {inputPath}. PDFDocument.load(bytes) -> pdfDoc.getForm().getFields() -> map each to {name, type, value}. Return { success: true, fields } */ }
async function pdfFillForm(data) { /* data: {inputPath, outputPath, values: Record<string,string>, flatten}. Load, getForm(), for each key in values call form.getTextField(key).setText(value) (wrap per-field in try/catch to skip fields that don't exist or aren't text fields — this app's convention per pdfWatermark is to fail loudly on real errors but this is a batch-of-independent-fields case, so log+skip per-field failures and continue). If flatten, call form.flatten() before saving. */ }
```
Add `'formFields'` (get) and `'fillForm'` cases to `executeOperation`, add both to exports.
- [ ] **Step 1:** Write tests building a test PDF with an AcroForm text field via `pdf-lib`'s `form.createTextField()` API (check pdf-lib's docs/existing usage in the codebase for the exact field-creation calls — `PDFOperations.js` already imports `pdf-lib`, follow its existing import style).
- [ ] **Step 2:** Run tests — expect FAIL.
- [ ] **Step 3:** Implement both functions.
- [ ] **Step 4:** Run tests — expect PASS.
- [ ] **Step 5:** Add a "Fill Form" UI entry to the PDF editor dialog: on open, call `formFields` to list detected fields, render a text input per field, a "Flatten after fill" checkbox, then call `fillForm` on submit.
- [ ] **Step 6:** Manually verify against a real fillable PDF (search for one under `tests/fixtures/` or create one with `pdf-lib` in a scratch script — do not commit the scratch script).
- [ ] **Step 7:** `npm run lint && npm test`
- [ ] **Step 8:** Commit: `git add -A && git commit -m "feat(pdf): add form field detection, fill, and flatten"`
### Task 17: Plugin API — export-format and file-reader registration hooks
**Files:**
- Modify: `src/plugins/plugin-context.js`, `src/plugins/plugin-loader.js` (or wherever plugin manifests are validated/loaded — grep `plugin-loader.js`), `src/main.js` (export format switch — needs to consult plugin-registered formats)
**Interfaces (extend `PluginContext`, `plugin-context.js:64-71`, alongside the existing `this.exports` block):**
```javascript
this.formats = {
registerExportFormat: (id, opts) => {
// opts: { label, extension, handler: async (markdownContent, outputPath, options) => void }
if (formatRegistry) formatRegistry.register(`${pluginId}:${id}`, opts);
},
};
```
This requires a new small `FormatRegistry` (mirror the existing `plugin-registry.js` pattern — read it first to match its exact API shape, e.g. `register(id, opts)` / `getAll()` / `get(id)`) injected into `PluginContext`'s constructor `deps` alongside `sidebar`/`commands`/`statusBar`.
- [ ] **Step 1:** Read `src/plugins/plugin-registry.js` in full to learn its exact class/function shape before adding a sibling `FormatRegistry` (or extending the existing registry with a new namespace if it's already generic enough — prefer extending over duplicating if the existing registry is namespace-agnostic).
- [ ] **Step 2:** Add `registerExportFormat` to `PluginContext` per the interface above, wired to whatever registry mechanism Step 1 determined is the right fit.
- [ ] **Step 3:** In `src/main.js`'s export dispatch path (wherever the Export submenu's dynamic entries would need to merge in plugin formats — likely requires the Export submenu to be rebuilt after plugin load, similar to how `createMenu()` is already called after recent-files change in Task 2; check if `createMenu()` is idempotent/safe to call after plugin loading completes), add plugin-registered formats as additional Export submenu entries whose `click` handler calls the plugin's registered `handler` function instead of Pandoc.
- [ ] **Step 4:** Update the built-in `writing-studio` plugin's manifest/index (`src/plugins/built-in/`) with a trivial example usage of `registerExportFormat` (e.g. exporting sprint data as a `.txt` summary) — this both documents the new API and gives Step 5's manual test something concrete to click.
- [ ] **Step 5:** Write a unit test in `tests/plugins/` (find the existing plugin test directory/pattern) verifying a plugin calling `context.formats.registerExportFormat(...)` results in the registry containing the namespaced entry.
- [ ] **Step 6:** Manually verify: `npm start`, confirm the writing-studio example format appears in the Export menu and produces the expected output file when clicked.
- [ ] **Step 7:** `npm run lint && npm test`
- [ ] **Step 8:** Commit: `git add -A && git commit -m "feat(plugins): add export-format registration hook to plugin API"`
### Task 18: DOCX/EPUB template gallery UI
**Files:**
- Modify: `src/renderer.js` (export dialog for DOCX/EPUB — find via `exportWordWithTemplate()` at `main.js:881` and follow into whatever renderer dialog it opens)
- Modify: `src/main.js` (wherever the existing Word-template list is sourced from — grep `WordTemplateExporter` and `listTemplates`/`getTemplates`-style function)
**Verified context:** `main.js` already has `exportWordWithTemplate()` and `WordTemplateExporter` (`src/wordTemplateExporter.js`) — a template mechanism for DOCX exists but per the feature-inventory research pass has "no discoverable UI" for browsing available templates; the user has to already know a template exists. Read `src/wordTemplateExporter.js` in full first to learn how templates are currently listed/selected (is there a folder of `.dotx`/`.docx` template files? A hardcoded list?) before designing the gallery.
- [ ] **Step 1:** Read `src/wordTemplateExporter.js` and the renderer dialog `exportWordWithTemplate()` opens, to learn the exact current template-selection mechanism (function names, data shape).
- [ ] **Step 2:** Add a visual gallery (grid of template name + thumbnail-if-available, or name + short description if no thumbnails exist) to that same dialog, replacing or augmenting whatever minimal selector currently exists, following the dialog's existing CSS/markup conventions (check `src/styles.css` for the dialog's existing classes before inventing new ones).
- [ ] **Step 3:** Do the same for EPUB export if `main.js` has an equivalent EPUB-template mechanism (grep for `epub` + `template`); if none exists, skip EPUB (do not invent a template system that doesn't exist — note this explicitly as out of scope in the commit message rather than silently dropping it).
- [ ] **Step 4:** Manually verify: open the DOCX export dialog, see the template gallery, pick one, confirm the exported DOCX uses it.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(export): add visual template gallery to DOCX export dialog"`
### Task 19: CSV-to-markdown-table toolbar converter
**Files:**
- Modify: `src/renderer.js` (editor toolbar — find the existing toolbar button registration pattern, e.g. near table generator/ASCII generator toolbar buttons)
**Verified context:** Pandoc already imports CSV (`main.js:3507` import switch includes `csv`). This task adds a quick in-editor action: paste/select CSV-like text, convert to a markdown table without leaving the editor (distinct from the full file-import path).
- [ ] **Step 1:** Add a toolbar button "CSV → Table" (or a Command Palette entry, matching whichever pattern is more consistent with similar single-action editor tools already in the toolbar — check what's already there before choosing).
- [ ] **Step 2:** Implement a pure client-side CSV→Markdown-table converter function in `renderer.js` (no need to round-trip through Pandoc for this simple case — parse the current selection's lines by comma, respecting basic double-quote-wrapped fields containing commas; build a `| a | b |` / `|---|---|` markdown table). Keep this function small and testable — extract it to `src/lib/csv-to-markdown-table.js` if `src/renderer.js` doesn't already have a `src/lib/`-style extraction pattern for similar pure functions (check first).
- [ ] **Step 3:** Write a Jest unit test for the converter function covering: simple CSV, quoted fields containing commas, ragged rows (fewer columns in some rows — pad with empty cells), empty input.
- [ ] **Step 4:** Wire the toolbar button to: read the editor selection, run the converter, replace the selection with the resulting markdown table.
- [ ] **Step 5:** Manually verify: select a few lines of comma-separated text in the editor, click the button, confirm it becomes a proper markdown table.
- [ ] **Step 6:** `npm run lint && npm test`
- [ ] **Step 7:** Commit: `git add -A && git commit -m "feat(editor): add CSV-to-markdown-table toolbar converter"`
### Task 20: Document Compare / diff view (completes Task 6)
**Files:**
- Modify: `src/renderer.js` (new listener for `show-document-compare`, whitelisted in Task 6)
- Create: `src/renderer/document-compare-dialog.js` (or inline in `renderer.js` if that's the dominant pattern for similar dialogs — match Task 12's finding on dialog-module conventions)
**Verified context:** `main.js:1411-1413` sends `show-document-compare`; Task 6 whitelisted the channel; nothing renders it yet. This task adds an actual two-pane diff: either two arbitrary local files, or (leveraging Task 14's new `GitOperations.diff`) the current file against its last-committed git revision.
- [ ] **Step 1:** Build a simple two-file diff dialog: two "choose file" buttons (or one defaulting to the currently-open tab + one file picker for the comparison target), a line-by-line diff render. Do not add a new diff-algorithm dependency — write a minimal LCS-based line diff in a small pure function (`src/lib/line-diff.js`) since the app has no existing diff library; keep it under ~60 lines (standard textbook LCS-diff, not a full Myers-diff library port).
- [ ] **Step 2:** Write a Jest unit test for the line-diff function: identical files (no diffs), pure additions, pure deletions, mixed changes.
- [ ] **Step 3:** Add a "Compare with Git HEAD" option in the same dialog when the current file is inside a git repo, using `GitOperations.diff` from Task 14 (raw git diff text render, separate code path from the line-diff function — git's own diff output is already a diff, don't re-diff it).
- [ ] **Step 4:** Wire `ipcRenderer.on('show-document-compare', () => { /* open the dialog */ })` in `renderer.js`.
- [ ] **Step 5:** Manually verify: Tools → Document Compare, compare two local markdown files, confirm additions/deletions are visually distinguished (e.g. green/red line backgrounds, matching the app's existing theme CSS variables rather than hardcoded colors).
- [ ] **Step 6:** `npm run lint && npm test`
- [ ] **Step 7:** Commit: `git add -A && git commit -m "feat(compare): implement Document Compare dialog with local-diff and git-HEAD-diff modes"`
### Task 21: Export presets/profiles
**Files:**
- Modify: `src/main.js` (near `get-header-footer-settings`/`save-header-footer-settings` handlers, `main.js:1857-1886`)
- Modify: renderer export-options dialog (wherever `export-with-options` is invoked from — grep `export-with-options` in `renderer.js`)
**Interfaces:**
```javascript
// main.js — new handlers, settings persisted the same way header/footer settings already are
// (read main.js:1857-1886 first to copy its exact settings-file read/write pattern, e.g. settings.json path + key)
ipcMain.handle('get-export-presets', async () => { /* returns array of {id, name, format, options} */ });
ipcMain.handle('save-export-preset', async (event, preset) => { /* upsert by id, persist, return updated list */ });
ipcMain.handle('delete-export-preset', async (event, presetId) => { /* remove by id, persist, return updated list */ });
```
- [ ] **Step 1:** Read `main.js:1857-1886` in full to learn the exact settings-persistence pattern already used (this app uses a custom JSON file store per `CLAUDE.md`, not `electron-store` — confirm the exact file/key convention and reuse it verbatim for presets, e.g. a new top-level `exportPresets` array in the same `settings.json`).
- [ ] **Step 2:** Implement the 3 handlers per the interfaces above, add all 3 channel names to `ALLOWED_SEND_CHANNELS` in `preload.js`.
- [ ] **Step 3:** In the renderer's export-options dialog, add a "Save as preset" button (captures the current dialog's option values, prompts for a name, calls `save-export-preset`) and a preset dropdown at the top of the dialog (populated via `get-export-presets` on open; selecting one pre-fills the dialog's fields) plus a delete icon per preset row.
- [ ] **Step 4:** Manually verify: configure export options, save as a preset, close and reopen the dialog, confirm the preset is selectable and correctly restores all fields; delete it, confirm it's gone.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(export): add save/select/delete export presets"`
### Task 22: Batch PDF operations UI (beyond format conversion)
**Files:**
- Modify: `src/renderer.js` (Batch menu handling — find the `show-batch-converter` listener with `'pdf'` type)
- Modify: `src/main.js` (extend the batch loop to support PDFOperations, not just format conversion)
**Verified context:** `main.js:1293-1296` already has a "Batch PDF Conversion..." menu item sending `show-batch-converter` with type `'pdf'`, but (per the existing batch conversion handlers at `main.js:2454-2563`) batch only does format conversion via `convertWithLibreOffice`/pandoc — it never calls into `PDFOperations.executeOperation` for bulk watermark/compress/rotate across many files.
- [ ] **Step 1:** In the renderer's batch dialog (wherever the `'pdf'`-typed batch dialog renders), add an operation-type selector when the batch type is `'pdf'`: "Convert format" (existing behavior, keep as default) vs. "Bulk PDF Operation" (new: pick one of merge/split/compress/rotate/watermark/etc. plus that operation's fields, same fields as the single-file PDF editor dialog).
- [ ] **Step 2:** Add a new `ipcMain.on('batch-pdf-operation', async (event, { operation, data, inputFolder, includeSubfolders }) => {...})` handler in `main.js` that collects matching `.pdf` files (reuse the exact `collectFiles` recursive helper already defined inside `universal-convert-batch`, `main.js:2472-2484` — extract it to a shared top-level function if it isn't already, since Task 22 needs the identical logic) and calls `PDFOperations.executeOperation(operation, {...data, inputPath: filePath, outputPath: ...})` per file in a loop, reporting progress via `mainWindow.webContents.send('batch-progress', ...)` matching the existing batch progress-reporting convention.
- [ ] **Step 3:** Add `'batch-pdf-operation'` to `ALLOWED_SEND_CHANNELS`.
- [ ] **Step 4:** Manually verify: batch-watermark a folder of 2-3 test PDFs, confirm each output file has the watermark applied.
- [ ] **Step 5:** `npm run lint && npm test`
- [ ] **Step 6:** Commit: `git add -A && git commit -m "feat(pdf): add bulk PDF operations (watermark/compress/rotate/etc.) to batch converter"`
---
## Phase D — Security Remediation
### Task 23: Fix Pandoc argument-injection vulnerability (CRITICAL)
**Files:**
- Modify: `src/main.js` (every `pandocCmd` string-concatenation site: `performExportWithOptions` ~`2623-2965`, `exportPDFViaWordTemplate`-adjacent function ~`2980-3050`, `runPandocCmd`/`parseCommand` at `231-282`, the import-side builder at `~3501`, and the enhanced-export builder at `~3997-4097`)
- Modify: `tests/` (new regression test)
**Verified root cause:** `performExportWithOptions` and its siblings build a shell-style command **string** by concatenating user-influenced values (export dialog fields: `options.template`, `options.metadata` key/values, `options.variables` key/values, `options.bibliography` path, `options.csl` path, `options.geometry`, footer text, CSS file path) wrapped in double quotes, e.g. `` pandocCmd += ` --bibliography="${options.bibliography}"` ``. This string is later tokenized by `parseCommand()` (`main.js:253-282`) — a hand-rolled parser that toggles an `inQuotes` flag on any `"` or `'` character and has **no backslash-escape handling at all**. The `.replace(/"/g, '\\"')` escaping applied to `metadata`/`variables` values therefore does nothing protective: `parseCommand` sees the literal backslash as an ordinary character and the following `"` still toggles quote state exactly as an unescaped quote would. Any field that reaches `parseCommand` un-sanitized (which is most of them — `template`, `bibliography`, `csl`, `geometry`, footer text are never escaped at all) lets an attacker-controlled value containing a `"` character break out of its intended single argument and inject additional argv elements into the `execFile(pandocPath, args, ...)` call at the end of `runPandocCmd`. Because `execFile` (not `exec`) is used, this is **not** a shell-injection (no `;`, `|`, backticks interpreted) — it is **argument injection into pandoc itself**, which is still exploitable: Pandoc supports `--lua-filter=<path>` and `--filter=<path>` (arbitrary Lua/executable code execution), `-o <path>` (arbitrary file overwrite by injecting a second `-o`), and `--resource-path`/`--extract-media` (arbitrary-path writes). A malicious value in any of the un-escaped fields above is enough to reach that severity — no shell metacharacters are even needed, just a `"` followed by a new flag.
**Fix approach:** Stop building command strings entirely for every one of these call sites. Replace with direct `execFile(pandocPath, argsArray, ...)` calls where `argsArray` is built as a real JS array (`push`, never string interpolation) — this is exactly what `PDFOperations.js`/`GitOperations.js` already do correctly, and what `AudioOperations.js`/`VideoOperations.js`/`ImageOperations.js` do from Phase B. `parseCommand`/`runPandocCmd`'s string-based indirection should be deleted once all call sites are converted — do not leave it in place as unused dead code (would violate the "no forbidden markers/half-finished" standard); if any call site turns out to be legitimately hard to convert in this task, that is a signal that call site needs its own careful sub-step, not a reason to keep the vulnerable helper around "just in case."
- [ ] **Step 1:** Write a regression test proving the vulnerability exists in the *current* code, in a new file `tests/main/pandoc-arg-safety.test.js`, calling `parseCommand` directly (it will need to be exported from `main.js` for testing, or extracted first — see Step 2) with a crafted value and asserting it does NOT produce an injected extra argument:
```javascript
// This test is written to FAIL against the current parseCommand implementation,
// proving the vulnerability, then PASS once Step 3+ removes the vulnerable path.
const { buildPandocArgs } = require('../../src/main/PandocArgs'); // new module created in Step 3
test('a bibliography path containing a double quote cannot inject extra pandoc flags', () => {
const malicious = '/tmp/x.bib" --lua-filter=/tmp/evil.lua -o "/tmp/x.bib';
const args = buildPandocArgs({
inputFile: '/in.md',
outputFile: '/out.pdf',
format: 'pdf',
options: { bibliography: malicious },
});
// The malicious string must appear as exactly ONE argv element (whatever
// value it ends up as), never split into multiple args, and
// '--lua-filter=/tmp/evil.lua' must not appear as its own array element.
expect(args).not.toContain('--lua-filter=/tmp/evil.lua');
expect(args.filter((a) => a.includes(malicious) || a === malicious).length).toBeLessThanOrEqual(1);
});
```
- [ ] **Step 2:** Run the test — confirm it fails to even import (module doesn't exist yet) — this is expected; proceed to build the real module.
- [ ] **Step 3:** Create `src/main/PandocArgs.js` — a pure module exporting `buildPandocArgs({ inputFile, outputFile, format, options })` that returns a plain `string[]` args array (no string concatenation of the whole command — only individual argv elements are ever created via `.push(...)`), reimplementing every option currently handled across the string-building sites (`toc`, `tocDepth`, `numberSections`, `citeproc`, `bibliography`, `csl`, `template`, `metadata` (loop → `push('-M', `${key}=${value}`)` — no manual quote-escaping needed at all, since array elements are passed to `execFile` as literal argv, never re-parsed), `variables` (same pattern with `-V`), `pdfEngine`, `geometry`, monospace font header include, footer text). Read every one of the sites listed in "Files" above in full before writing this, to ensure no option is silently dropped.
- [ ] **Step 4:** Run the Step 1 test — expect PASS now.
- [ ] **Step 5:** Replace every call site that currently builds a `pandocCmd` string and calls `runPandocCmd(pandocCmd, ...)` with: build args via `PandocArgs.buildPandocArgs(...)`, then `execFile(getPandocPath(), args, { maxBuffer: 10 * 1024 * 1024 }, callback)` directly — inline this or add a tiny `runPandocArgs(args, callback)` helper next to the deleted `runPandocCmd` to avoid repeating the `execFile` options object at every site.
- [ ] **Step 6:** Delete `parseCommand` and the old `runPandocCmd` (`main.js:231-282`) once no call site references them (grep to confirm zero remaining references before deleting).
- [ ] **Step 7:** Manually re-run every export format the app supports (or at minimum: PDF, DOCX, HTML, EPUB, LaTeX — the ones with the most option surface) via the UI, confirming exports still succeed with the new args-array path, including with TOC/metadata/bibliography options actually filled in (not just defaults) to catch any option silently dropped in Step 3.
- [ ] **Step 8:** `npm run lint && npm test`
- [ ] **Step 9:** Commit: `git add -A && git commit -m "fix(security): eliminate pandoc argument-injection vector by building execFile args arrays directly"`
### Task 24: Formal security-review pass
**Files:** N/A — process task.
- [ ] **Step 1:** Invoke the `security-review` skill against the full working tree (post Phase A/B/C/SEC-1 changes) to catch anything beyond what this plan's manual audit already found — particularly re-check the new `AudioOperations`/`VideoOperations`/`ImageOperations` modules and the new file-picker/batch handlers added in Phase B/C for the same class of injection risk (all must use `execFile` with array args — verify none of them slipped into string-building), and check the new plugin `registerExportFormat` hook (Task 17) for arbitrary-code-execution risk if a malicious/compromised plugin could abuse it beyond what a plugin can already do.
- [ ] **Step 2:** For every finding the skill reports, triage severity and either fix inline (Critical/High) or explicitly log as an accepted/deferred risk with reasoning (Medium/Low) — do not silently drop findings.
- [ ] **Step 3:** Produce a short written security summary (what was found across both the manual audit and the formal pass, what was fixed, what if anything was deferred and why) and save it to `docs/superpowers/plans/2026-08-23-security-assessment-summary.md`.
- [ ] **Step 4:** Commit any additional fixes with individual, scoped commit messages (do not batch unrelated security fixes into one commit).
---
## Phase E — Rebuild Local Release
### Task 25: Full verification + local build
**Files:** N/A — build/verification task.
- [ ] **Step 1:** `npm run lint` — must pass clean.
- [ ] **Step 2:** `npm run format:check` — must pass clean (run `npm run format` first if not).
- [ ] **Step 3:** `npm test` — all suites must pass; confirm the total test count has grown from the 247-test baseline (new tests from Phase B/C tasks should be present).
- [ ] **Step 4:** `npm run download-tools` (ensures bundled Pandoc/tool binaries are current for the build).
- [ ] **Step 5:** `npm run build:local` (per `package.json` script — builds Linux + Windows targets; this matches "local release" for this dev machine's platform(s)). If this machine is Linux-only and Windows cross-build tooling (wine, etc.) isn't available, fall back to `npm run build:linux-ci` and note the Windows build was skipped and why.
- [ ] **Step 6:** Verify the `dist/` output contains the expected artifacts (`.deb`, `.AppImage` at minimum) and that the packaged app launches (`./dist/*.AppImage` or the unpacked `dist/linux-unpacked/markdown-converter` binary) without immediate crash — smoke-test opening a markdown file and exporting to PDF from the packaged build specifically (not `npm start`), since `asarUnpack` behavior for `sharp`/`ffmpeg-static`/fonts only manifests in a packaged build.
- [ ] **Step 7:** Report the final `dist/` artifact list and versions to the user; do not bump `package.json`'s version number as part of this task unless the user asks — that is a separate release-management decision.
---
### Task 26: Migrate `File.path` → `webUtils.getPathForFile` (Electron 41 fix) — appended by controller ruling 2026-08-23
**Origin:** Task 20 review. `File.path` was removed in Electron 32; this app pins `electron ^41.1.1` and has no `webUtils` usage — every renderer file-picker reading `file.path` gets `undefined` at runtime (~15 sites: universal converter, PDF editor pickers, bibliography/CSL pickers, custom template, media merge lists, document-compare File B).
**Files:**
- Modify: `src/preload.js` (expose a `getFilePath(file)` helper via `webUtils.getPathForFile`)
- Modify: `src/renderer.js`, `src/renderer/media-operations-dialog.js`, `src/renderer/document-compare-dialog.js` (migrate all `file.path` reads to the helper)
**Steps:**
1. In `src/preload.js`, expose `getFilePath: (file) => webUtils.getPathForFile(file)` on the existing `electronAPI` surface (webUtils is available in the preload/renderer context; it exists precisely to replace File.path). No new IPC channel needed — this is a synchronous in-process call.
2. Grep-migrate every `file.path` / `files[i].path` read in the three renderer files to `window.electronAPI.getFilePath(file)` (falling back to `file.path` if the helper is absent, to keep jsdom tests runnable — verify which tests mock this surface and update them to mock the helper).
3. Add a preload test asserting `getFilePath` is exposed (follow tests/preload.test.js conventions).
4. `npm run lint && npm test`.
5. Commit: `fix(renderer): migrate File.path reads to webUtils.getPathForFile for Electron 41`
---
### Task 27: PDF encrypt/decrypt/permissions — replace silent no-op with honest failure — appended by controller ruling 2026-08-23
**Origin:** Task 22 review (empirically verified). pdf-lib 1.17.1 cannot encrypt: `save({userPassword, ownerPassword, permissions})` silently ignores these options, `PDFDocument.load({password})` is not a LoadOptions field. Current behavior: `pdfEncrypt`/`pdfSetPermissions` write unprotected files and report success; `pdfDecrypt` reports success on non-encrypted inputs (copy no-op) and always fails on genuinely encrypted ones.
**Files:**
- Modify: `src/main/PDFOperations.js` (pdfEncrypt, pdfDecrypt, pdfSetPermissions), their renderer call sites if messages surface there, and `src/main/PDFBatchOperations.js` exclusion register comment (already excludes these ops — keep excluded, update the comment to reference this task).
**Steps:**
1. Capability-detect once at module load (probe whether the installed pdf-lib honors encryption — e.g. build a tiny in-memory PDFDocument, save with a userPassword, check raw bytes for `/Encrypt`; or simply pin the known limitation with a constant + comment referencing pdf-lib 1.17.1) — prefer the empirical probe so a future library swap re-enables the ops automatically.
2. When encryption is unsupported: pdfEncrypt/pdfSetPermissions return `{success: false, message: 'Password protection is not available in this build (pdf-lib lacks encryption support).'}`; pdfDecrypt returns an equivalent honest failure. Never write a file. Never report success.
3. Update the PDF editor dialog so these three controls are disabled with explanatory hint text when unavailable (grep renderer call sites for the encrypt/permissions handlers).
4. Update tests: existing encrypt/decrypt/permissions tests (they currently pin the broken behavior — rewrite to assert honest failure); keep any genuinely-passing load-with-password tests only if the probe says the library supports them.
5. `npm run lint && npm test`.
6. Commit: `fix(pdf): make encrypt/decrypt/permissions fail honestly instead of silent no-op`
**Out of scope (user decision pending):** swapping pdf-lib for an encryption-capable fork (e.g. @cantoo/pdf-lib) to restore the feature for real — new dependency, needs sign-off.
@@ -0,0 +1,44 @@
# Security Assessment Summary — MarkdownConverter (master branch)
**Date:** 2026-08-23 · **Scope:** full branch `6db54a5..HEAD` (feature-audit-and-hardening plan, 27 tasks) · **Method:** manual feature/security audit at plan time + formal review pass (Task 24: three-stage vulnerability scan — identify → false-positive filter at confidence ≥ 8 → inline fix of confirmed High findings)
## 1. What the manual audit found (plan Phases AD)
| # | Finding | Severity | Resolution |
|---|---------|----------|------------|
| SEC-1 | Pandoc invocation built as shell-style string and re-tokenized — argument injection via crafted filenames/options/bibliography paths | **Critical** | Fixed — Task 23 (`d41b7df`): every invocation now `execFile(path, args[])` via pure builder `src/main/PandocArgs.js`; string tokenizer deleted; 21 injection-vector tests + differential exploit-split proof + 23 real-pandoc e2e checks |
| UX-1..7 | Seven non-working features: PDF menu IPC misrouting, media converter with 16 IPC channels and 0 handlers, dead New-from-Template menu, dead View-menu toggles, Clear-Recent-Files no-op, unreachable font settings, jszip/sharp misplaced in devDependencies | High (functional) | Fixed — Tasks 114; media backends (sharp/ffmpeg) implemented execFile-array-first |
| LAT-1 | `File.path` reads dead on Electron 41 (removed in v32; app pins ^41.1.1) — every renderer file-picker returned `undefined` | High (functional) | Found during Task 20 review; fixed — Task 26 (`32a5755`): `webUtils.getPathForFile` exposed in preload + main-window shim; all ~15 picker sites migrated |
| LAT-2 | pdf-lib 1.17.1 silently ignores `userPassword`/`ownerPassword`/`permissions` — PDF encrypt/permissions wrote **unprotected** files while reporting success; decrypt was a copy no-op | High (integrity) | Found during Task 22 review; fixed — Task 27 (`78afccc`): empirical capability probe (fail-closed), honest unavailability errors, UI controls disabled with hint. Real encryption requires a library swap (see deferred #D1) |
## 2. What the formal pass (Task 24) found
**Confirmed (confidence 8/10, HIGH) — fixed inline:**
- **Git sidebar XSS → code execution** (`src/sidebar/git-panel.js`): repo-derived branch names, git-status file names, commit messages/author names, and git stderr rendered into `innerHTML` unescaped in the `nodeIntegration:true` main window, whose CSP permits `'unsafe-inline'` handlers. A malicious repo (attacker-authored commit message or crafted branch name) cloned by the victim executes script with full Node access when the Git panel loads. Fixed — `eafaf6e`: `escapeHtml` (& < > " ') across all 13 sink sites; jsdom tests assert structural inertness (no `img`/`script` elements, no attribute breakout) and that `dataset` reads still return raw names for git operations.
**Candidate assessed and dropped (with evidence):**
- PowerShell BurntToast interpolation (`main.js` ~4344): pre-existing at origin/master in identical `execFile`-array form. The dialog path interpolates a `format` chosen from a hardcoded 12-entry list; the `--convert-to <format>` CLI path feeds raw argv into the same string — but argv is trusted local-user input (precedent: CLI flags are trusted), and no shell is involved. Not exploitable. (Evidence note: the "hardcoded list" rationale covers the dialog path only; the drop stands on the argv-trust precedent for the CLI path.)
**Verified clean (14 areas):** media operation backends and all batch handlers (execFile arrays throughout, no string re-tokenization); plugin system (no escalation beyond the renderer's existing privileges; format metadata reaches main only as native menu labels and save-dialog filters); all new dialog renderers (`textContent`-only for dynamic content); PDFOperations new ops (pdfjs/sharp in-process, no shell); wordTemplateExporter (all `<w:t>` insertions escaped, no zip extraction → no zip-slip); GitOperations (simple-git array args); settings/presets stores (no deep merge → no prototype pollution); PandocArgs completeness (tree-wide grep: zero surviving string-built pandoc invocations); font embedders (fixed family→filename maps); generator windows (no untrusted prefill); print-preview (DOMPurify flow); no `eval`/`new Function`; no variable-URL `shell.openExternal`; no secrets in the diff.
## 3. Deferred / accepted risks
| ID | Risk | Disposition |
|----|------|-------------|
| D1 | **Real PDF encryption unavailable** (pdf-lib limitation) — feature now fails honestly rather than lying | Accepted for this release. Restoring it means swapping pdf-lib for an encryption-capable fork (e.g. `@cantoo/pdf-lib`, API-compatible) — **needs explicit sign-off on a new dependency** |
| D2 | `nodeIntegration:true` + `contextIsolation:false` on mainWindow, pdfWindow, hiddenWindow; main window does not load `preload.js` (inline shim instead) — the IPC whitelist is a live control only on the two generator windows | Accepted legacy risk for this branch; owned by the react-electron migration (contextIsolation + preload-everywhere), tracked separately |
| D3 | Generator-window preload whitelist is broad (`execute-code`, `read-file`, `write-file`, `delete-file` reachable from isolated windows) | No current content vector into those windows; flag for the migration to narrow per-window APIs |
| D4 | CSP allows `'unsafe-inline'` / `'unsafe-eval'` (required by marked + Mermaid rendering model) | Accepted; revisit under the migration with a nonce-based CSP |
| D5 | `outline-panel.js` / `repl-panel.js` / `analytics-panel.js` have local `escapeHtml` helpers that do not escape quotes | Deferred hardening: unsafe only if reused in attribute contexts; no such current use found |
| D6 | `scripts/download-tools.js` downloads Pandoc/fonts without checksum pinning | Build-time supply-chain hardening; recommended follow-up (pin + verify SHA-256) |
| D7 | Misc functional edge cases (batch same-folder overwrite, `pdfSplit` non-positive interval loop, rate-limiter dialog stall) | Deferred minors, logged in the plan ledger; none security-relevant |
## 4. Verification state
- Test suite: **49 suites / 512 tests passing**; ESLint and Prettier clean at every task boundary (enforced per-task during execution).
- All new external-process code paths verified `execFile`-array by independent tree-wide grep (Task 23 review) and re-verified in the formal pass.
- **Release blocker (human step):** this environment cannot launch the Electron GUI. A human pass in the running app — light + dark themes, file picking in the main dialogs (File B in Document Compare, bibliography/CSL, universal converter, PDF editor), Git sidebar on a real repo — is required before shipping.
**Bottom line:** the one Critical (argument injection) and one confirmed High (Git panel XSS) are closed with tests; two latent silent-failure bugs (File.path, fake encryption) are fixed; the remaining exposure is the documented legacy trust model (D2D4) owned by the planned Electron security migration plus one dependency decision (D1).
@@ -0,0 +1,426 @@
# MarkdownConverter v5.0 — Platform Design
**Date:** 2026-04-14
**Status:** Approved
**Author:** Amit Haridas
## Overview
Transform MarkdownConverter from a monolithic editor into an extensible platform with a plugin system and three feature packs, shipped together as v5.0.
## Subsystems
1. **Plugin System** — Lightweight plugin registry with extension points (sidebar, commands, settings, status bar, export hooks, event bus)
2. **Writing Studio Plugin** — Manuscript manager, goal tracking, writing sprints, snapshots, smart proofreading
3. **AI Assistant Plugin** — Multi-provider AI writing assistant (Ollama, LMStudio, GGUF direct with GPU, Anthropic, OpenAI)
4. **Collaboration Plugin** — Git-based async collaboration, comments/annotations, review requests
## Core Principle
**Existing functionality is never replaced or broken.** The plugin system is additive. All existing keyboard shortcuts, features, and UI remain untouched. Plugin shortcuts use `Ctrl+Alt+` namespace.
---
## 1. Plugin System
### File Structure
```
src/
plugins/
plugin-registry.js # Load, register, lifecycle
plugin-api.js # Base class plugins extend
plugin-loader.js # Discovers and validates manifests
built-in/
writing-studio/
manifest.json
index.js
panels/
components/
ai-assistant/
manifest.json
index.js
providers/
collaboration/
manifest.json
index.js
```
### Manifest Schema
```json
{
"id": "writing-studio",
"name": "Writing Studio",
"version": "1.0.0",
"description": "Manuscript management, goal tracking, writing sprints",
"icon": "pen-tool",
"extensionPoints": {
"sidebar": { "panel": "panels/manuscript-panel.js", "order": 30 },
"settings": { "section": "settings/index.js" },
"statusBar": { "indicators": ["sprint-timer", "word-goal"] },
"commands": [
{ "id": "start-sprint", "label": "Start Writing Sprint", "shortcut": "Ctrl+Alt+S" },
{ "id": "take-snapshot", "label": "Take Snapshot", "shortcut": "Ctrl+Alt+N" }
],
"exportHooks": {
"preExport": "hooks/pre-export.js",
"postExport": "hooks/post-export.js"
}
},
"settings": [
{ "key": "dailyGoal", "type": "number", "default": 1000, "label": "Daily word goal" },
{ "key": "sprintDuration", "type": "number", "default": 25, "label": "Sprint duration (min)" }
]
}
```
### Plugin Lifecycle
1. PluginLoader discovers manifests in `built-in/` + user plugins directory
2. PluginRegistry validates manifests
3. Each plugin calls `Plugin.init(context)` receiving scoped API context
4. Extension points registered (sidebar panels, commands, status bar items)
5. Plugins activate lazily — sidebar panel loads JS when user clicks tab
### Plugin Context API
Each plugin's `init()` receives:
```javascript
{
sidebar: {
registerPanel(id, { icon, title, component })
},
commands: {
register(id, label, handler, shortcut?)
},
statusBar: {
registerIndicator(id, { position, render })
},
settings: {
get(key), // plugin-scoped
set(key, value), // auto-persisted via electron-store
onChanged(key, callback)
},
editor: {
getContent(), // current document
getSelection(), // selected text
insertAtCursor(text), // requires opt-in
onContentChanged(callback)
},
events: {
on(event, handler),
emit(event, data)
},
exports: {
registerPreHook(handler),
registerPostHook(handler)
},
ipc: {
invoke(channel, ...args),
on(channel, handler)
}
}
```
### Event Bus Events
Each event has a versioned payload schema. Breaking changes increment the version suffix.
```
document:opened → { filePath: string, tabId: string }
document:saved → { filePath: string, tabId: string }
document:changed → { tabId: string, content: string, wordCount: number }
editor:selection-changed → { tabId: string, text: string, from: {line,ch}, to: {line,ch} }
tab:switched → { tabId: string, filePath: string }
tab:closed → { tabId: string, filePath: string }
export:started → { format: string, filePath: string }
export:completed → { format: string, filePath: string, outputPath: string }
export:failed → { format: string, error: string }
plugin:loaded → { pluginId: string, version: string }
plugin:activated → { pluginId: string }
plugin:deactivated → { pluginId: string }
app:ready → {}
app:before-quit → {}
```
### Design Rules
- Built-in plugins use the same API as future third-party plugins
- Lazy activation — sidebar panels don't load until clicked
- Scoped settings: `plugins.<id>.<key>` in electron-store
- Plugin commands globally unique — registry rejects duplicate command IDs at load time
- **Plugin sandboxing**: each plugin handler is wrapped in try/catch. For CPU-intensive operations (AI inference, diff computation), plugins must delegate to main process via IPC. Handlers that block the renderer for >5s trigger a warning notification. Memory-hungry operations (GGUF inference) run in isolated child processes.
- **Cross-plugin graceful degradation**: plugins check `context.events.hasHandler('ai:analyze')` before emitting cross-plugin requests. If no handler (AI plugin disabled), show a "this feature requires the AI plugin" prompt instead of failing silently. All cross-plugin calls have a 30s timeout with default fallback behavior.
---
## 2. Writing Studio Plugin
### 2A. Manuscript / Project Manager
Folder-based project structure:
```
~/Manuscripts/
my-novel/
.project.json # { title, targets, metadata }
01-chapter-one.md
02-chapter-two.md
characters/
protagonist.md
research/
world-building.md
.snapshots/
2026-04-14T10-30.json
```
`.project.json`:
```json
{
"title": "My Novel",
"type": "manuscript",
"target": { "words": 80000, "deadline": "2026-09-01" },
"chapters": [
{ "file": "01-chapter-one.md", "title": "The Beginning", "status": "draft" }
],
"metadata": { "author": "", "genre": "", "synopsis": "" }
}
```
Sidebar panel shows project tree with drag-to-reorder, word counts per chapter, target progress bar. "Compile manuscript" exports all chapters as a single document.
### 2B. Goal Tracking & Writing Sprints
- **Status bar**: daily progress bar + sprint timer
- **Writing sprint**: configurable duration (15/25/30/45/60 min), word count delta, WPM at end
- **Goal tracking**: daily/weekly word goals, streak tracking, 30-day bar chart
- **Enhanced analytics**: session tracking, readability scores, productive time-of-day heatmap
- Data stored in `plugins.writing-studio.history` as date-keyed map
### 2C. Snapshot & Versioning
- `Ctrl+Alt+N` or toolbar button saves snapshot
- Stored as JSON: `{ timestamp, content, wordCount, cursorPos, label }`
- Snapshot panel in sidebar: Restore, Diff (side-by-side), auto-snapshot interval
- Snapshots in `.snapshots/` inside project folder, or app data if no project
### 2D. Smart Proofreading
Delegates to AI plugin via event bus. Writing Studio provides:
- Right-click context menu: "Check grammar", "Suggest alternatives", "Analyze readability"
- Inline wavy underline decorations for issues
- Proofread panel: issues categorized by type with Accept/Dismiss
### Commands
| Command | Shortcut | Action |
|---------|----------|--------|
| `start-sprint` | `Ctrl+Alt+S` | Start writing sprint |
| `stop-sprint` | `Ctrl+Alt+Shift+S` | Stop sprint |
| `take-snapshot` | `Ctrl+Alt+N` | Save snapshot |
| `restore-last-snapshot` | `Ctrl+Alt+Z` | Restore latest snapshot |
| `new-project` | — | Create manuscript project |
| `compile-manuscript` | `Ctrl+Alt+E` | Export all chapters |
| `proofread-document` | `Ctrl+Alt+G` | AI proofread |
---
## 3. AI Assistant Plugin
### Provider Architecture
```
AI Plugin
├── Provider Interface
│ ├── complete(prompt, options) → string
│ ├── stream(prompt, options) → AsyncIterable
│ └── analyze(text, type) → AnalysisResult
├── Providers
│ ├── OllamaProvider — localhost:11434
│ ├── LMStudioProvider — localhost:1234/v1
│ ├── GGUFProvider — direct llama.cpp with GPU support
│ ├── AnthropicProvider — Claude API
│ └── OpenAIProvider — GPT API
└── Features
├── Grammar/style check
├── Inline auto-complete
├── AI chat panel (sidebar)
├── Document analysis
└── Smart commands (command palette)
```
### Provider Details
**Ollama:** `GET /api/tags` for models, `POST /api/generate` and `POST /api/chat` for inference.
**LMStudio:** OpenAI-compatible API at `localhost:1234/v1`. `GET /v1/models`, standard chat completion format, SSE streaming.
**GGUF Direct (with GPU):**
- Ships bundled llama.cpp binaries per platform (CUDA, Vulkan, Metal, CPU variants)
- Auto-detects GPU: CUDA (nvidia-smi), Vulkan driver, Metal (macOS)
- GPU layer offloading: configurable, auto-suggests based on VRAM vs model size
- Settings: GPU backend selection, layer count, context length, thread count
- "Keep model loaded" option for faster repeated requests
- WASM fallback for sandboxed environments (CPU-only)
- External binary path for advanced users with custom builds
- **Process isolation**: llama.cpp runs as a spawned child process (not in main process). If it crashes, detected via exit handler, auto-restarted with notification. GPU memory freed on crash. App remains stable.
- Process management: spawn in server mode on localhost ephemeral port, clean up on app quit or model unload
**Cloud (Anthropic/OpenAI):**
- API key stored encrypted via electron safeStorage
- Token usage tracking with estimated cost
- Rate limit awareness with request queueing and backoff
### IPC Design
All provider HTTP requests go through main process:
- No CORS issues
- API keys never in renderer
- Main process enforces rate limiting
- GGUF inference in isolated child process
**Request/response lifecycle:**
```
Renderer → ipc.invoke('ai:complete') → Main → HTTP to provider → result → Renderer
```
**Streaming lifecycle with error handling:**
```
Renderer → ipc.invoke('ai:stream', { requestId, prompt })
← Main assigns requestId, returns { requestId }
← ipc.on('ai:chunk', { requestId, text }) — repeated
← ipc.on('ai:done', { requestId }) — success
← ipc.on('ai:error', { requestId, error }) — failure
// Cancellation
Renderer → ipc.invoke('ai:cancel', { requestId })
← Main aborts HTTP request, emits 'ai:done'
// Orphan cleanup: if renderer disconnects (crash/close),
// main process detects via 'render-view-deleted' and aborts all active streams.
// Heartbeat: if no chunk received in 30s, main emits 'ai:error' with timeout.
```
### Features
1. **Inline suggestions**: ghost text after configurable delay, Tab to accept, Esc to dismiss
2. **AI chat panel**: sidebar conversation, "Insert" / "Replace selection" buttons
3. **Document analysis**: grammar, style, tone, with accept/reject per suggestion
4. **Smart commands**: summarize, generate outline, find inconsistencies, translate, explain code
### Privacy
- Local-first: default provider is Ollama
- No telemetry: requests go direct to provider
- Content gating: exclude file types from AI
- Status bar shows "AI: processing..." with cancel option
- Cloud usage stats in settings (tokens, cost)
### Cross-Plugin Integration
```javascript
// Writing Studio calls AI Plugin
context.events.emit('ai:analyze', { text, type: 'grammar', callback });
```
---
## 4. Collaboration Plugin
### 4A. Enhanced Git Panel
Upgrades to existing git panel:
- Remote management (add/remove remotes, push/pull)
- Branch list and switching
- Commit history with diff viewer (side-by-side or unified)
- Conflict resolution UI (accept-ours/accept-theirs/per-edit)
### 4B. Shared Repository Workflow
1. Writer A creates project + initializes git + pushes to shared repo
2. Writer B clones repo from within MarkdownConverter
3. Both write on their own branches
4. Writer A creates review request (simplified PR)
Review request: changed files, word count diff, commit messages. Reviewer can approve, request changes, leave inline comments. Reviews are git branches + comments as git notes.
### 4C. Comments & Annotations
Inline comments stored as JSON in `.comments/` directory (git-tracked):
```json
{
"id": "uuid",
"file": "03-chapter-three.md",
"anchor": {
"contextBefore": "The hero looked at the horizon and said,",
"selectedText": "I will not go quietly into that dark night",
"contextAfter": "He turned to face the army alone."
},
"line": 142,
"text": "This dialogue feels unnatural",
"author": "amit",
"timestamp": "2026-04-14T14:30:00Z",
"replies": [],
"resolved": false
}
```
- **Anchor-based positioning**: comments store `contextBefore`, `selectedText`, and `contextAfter` (not absolute byte offsets). On file change, re-anchor by searching for the context text. If context no longer matches, mark comment as "detached" and show a warning. Falls back to `line` number as rough position.
- Highlighted text in editor with tooltip on hover
- Comment panel in sidebar: all unresolved comments across files
- Resolution workflow: add → address → reply → resolve
- Resolved comments dim but stay visible
### 4D. Change Notifications
- Status bar indicator: `↓ 3 new commits`
- Click to see changes, one-click pull
- Conflicts trigger resolution UI
- Push button only when local commits ahead of remote
### 4E. Offline-First
All writing happens locally. Git is the sync mechanism. No internet required for writing, commenting, snapshots, or sprints. Push/pull on user action or auto-sync setting.
### Commands
| Command | Shortcut | Action |
|---------|----------|--------|
| `collab:commit` | `Ctrl+Shift+G` | Commit with message |
| `collab:push` | — | Push current branch |
| `collab:pull` | — | Pull from remote |
| `collab:add-comment` | `Ctrl+Alt+C` | Comment on selection |
| `collab:next-comment` | `F8` | Next unresolved comment |
| `collab:prev-comment` | `Shift+F8` | Previous comment |
| `collab:create-review` | — | Create review request |
### Cross-Plugin Integration
```javascript
context.events.emit('snapshot:created', { file, snapshotId });
context.events.on('project:chapter-opened', (chapter) => { /* load comments */ });
context.events.on('comment:added', (comment) => { /* AI could suggest fix */ });
```
---
## Bundle Size Impact
- llama.cpp binaries: ~15MB per GPU variant. Only target platform shipped. GPU variants (CUDA/Vulkan/Metal) downloaded on demand if user enables GGUF direct loading — not bundled by default. Only CPU fallback bundled (~15MB).
- Plugin system core: ~30KB
- Each built-in plugin: ~50-100KB
- Diff library (jsdiff): ~15KB
- Total estimated increase: ~20-30MB (core), additional ~30-50MB per GPU variant (lazy download)
## Testing Strategy
- Plugin system: unit tests for registry, loader, context API mocking
- Each plugin: isolated unit tests, integration tests via plugin context
- AI provider tests: mock HTTP responses, test streaming parsing
- Git tests: use test repository fixture
- E2E: verify plugin loading doesn't break existing features
@@ -0,0 +1,216 @@
# MarkdownConverter — Monospace Font Embedding Design
**Date:** 2026-06-30
**Status:** Approved
**Author:** Amit Haridas
## Overview
Guarantee proper ASCII character alignment in MarkdownConverter's preview and every supported export format (PDF, DOCX, HTML, plus ODT/RTF/EPUB/LaTeX), with no OS-level font dependency. The user can pick between **JetBrains Mono** (default) and **Fira Code**, and toggle ligatures (default off). Both font families are bundled inside the app, so alignment holds on every supported platform (Windows/macOS/Linux) without an internet connection, without system-wide font installation, and without the user touching anything system-level.
## Goals
1. ASCII art and code-block tables (e.g. `+----+----+` column delimiters) render at identical advance widths in the live preview **and** in every exported file.
2. No OS font dependency — TTFs ship inside the app.
3. Per-user choice of monospace family + ligature behaviour.
4. Self-contained exports: the exported PDF/DOCX/HTML file is portable to another machine and stays aligned.
## Non-Goals (v1)
- No font subsetting of TTFs (we ship the full file; xelatex subsets it into the PDF automatically; DOCX carriers get the full TTF in `word/fonts/`).
- No support for the user adding a third bundled font family.
- No PPTX or revealjs/Beamer ligature-toggle (PPTX is a slide format that rarely carries ASCII tables; revealjs/Beamer inherit HTML/LaTeX defaults).
- No licensed/commercial fonts (Fira Code and JetBrains Mono are both SIL OFL — confirmed in `assets/fonts/JetBrainsMono-LICENSE.txt`).
## Decisions Locked
| Decision | Choice | Reason |
|---|---|---|
| Scope | All export formats | All-surfaces alignment |
| DOCX strategy | Embed TTF into the DOCX zip | Truly portable; alignment holds even when the recipient lacks the font |
| PDF strategy | Pass TTF path to xelatex via `fontspec` (`\setmonofont[Path=...]`) | xelatex subsets the font into the PDF; reproducible across machines |
| Font choice | Both bundled; user-pickable in settings | Cover both preferences; default JetBrains Mono |
| Ligatures | Off by default; user toggle | Ligatures change advance widths and break ASCII grid alignment |
| License | SIL OFL (both families) | Embedding/bundling explicitly permitted when license travels with the binary (already present at `assets/fonts/JetBrainsMono-LICENSE.txt`) |
## Architecture
```
settings.json
│ (renderer + main read on init)
CSS body classes: .mono-jetbrains / .mono-fira
.mono-ligatures-on / .mono-ligatures-off
--font-mono-active token
▲ ▲
│ IPC │ IPC
│ │
Preview pane ┌───────────┴──────────┐
ASCII Generator window │ Export pipeline │
Print-preview iframe │ (main process) │
│ uses MonospaceFontConfig
└──────────────────────┘
Bundle: assets/fonts/
├─ JetBrainsMono-Regular.ttf
├─ JetBrainsMono-Bold.ttf
├─ FiraCode-Regular.ttf
├─ FiraCode-Bold.ttf
└─ (existing woff2 for renderer)
```
## New Modules
| File | Role |
|---|---|
| `src/main/MonospaceFontConfig.js` | Single source of truth. Resolves the active monospace family + weight → absolute TTF path, with awareness of dev vs packaged (asar.unpacked) layout. Returns `null` + warns when a file is missing. |
| `src/main/PdfFontHeader.js` | Builds the xelatex `header.tex` snippet with `\usepackage{fontspec}\setmonofont{...ttf}[Path=...,UprightFont=*-Regular,BoldFont=*-Bold,Ligatures=NoCommon/TeX]`. Also returns the lualatex equivalent. |
| `src/main/DocxFontEmbedder.js` | Unzips a pandoc-produced DOCX with `jszip`, writes TTFs into `word/fonts/`, patches `[Content_Types].xml`, `_rels/document.xml.rels`, creates `word/fontTable.xml` with `<w:embedRegular/>` referencing the TTF, patches `word/styles.xml` so the `SourceCode`/`VerbatimChar` styles bind to the embedded font name, then rezips. Idempotent. |
| `src/main/EpubFontEmbedder.js` | Wrapper around pandoc `--epub-embed-font` — verifies the chosen TTF is referenced in `OEBPS/content.opf`; patches the manifest if missing. |
| `src/main/ExportCss.js` | Returns a self-contained CSS string with `@font-face { src: url(data:font/woff2;base64,...) }` for the chosen family. Used by HTML export `--css` and by print-preview iframe. |
| `src/main/settings/SettingsUI.Monospace.js` | Two new controls in the in-app settings dialog: monospace font select + ligatures checkbox. Persists to `<userData>/settings.json`. |
## Modified Modules
| File | Change |
|---|---|
| `src/fonts.css` | Add `@font-face` entries for Fira Code Regular (400) and Bold (700), pointing to `assets/fonts/FiraCode-*.woff2` (downloaded via the extended `download-tools.js`). |
| `src/styles/tokens.css` + `src/styles-concreteinfo.css` | Define new tokens `--font-mono-active` (resolves to `"JetBrains Mono"` or `"Fira Code"`) and `--font-mono-feature` (`"liga" 0, "calt" 0, "dlig" 0` for ligatures-off, else `normal`). Body classes flip these. |
| `src/styles-modern.css` | `.editor-textarea`, `.preview-content code`, `.preview-content pre`, `.codemirror-container .cm-editor` reference `var(--font-mono-active)` and apply `font-feature-settings: var(--font-mono-feature)`. |
| `src/ascii-generator.html` | Replace `<link href="https://fonts.googleapis.com/...">` with `<link rel="stylesheet" href="../styles/fonts.css">` plus inline `body` class defaulting. The window is plain HTML; the renderer script that opens it sets `body.classList` from settings. |
| `src/print-preview.js` | Inject `<style>` with embedded woff2 base64 from `ExportCss.js` into the srcdoc iframe HTML; set `pre`/`code` font-family to `var(--font-mono-active)`. |
| `src/main.js` | Five `--css/-V monofont=Consolas` lines and the export pipelines need surgery (table below). On successful DOCX export, pipeline the output through `DocxFontEmbedder`. On HTML export, pass `--css` referencing a temp file emitted by `ExportCss.js`. On EPUB, pass `--epub-embed-font` for both Regular and Bold. On LaTeX/PDF, pass `--include-in-header` referencing a temp `header.tex` emitted by `PdfFontHeader.js`. The Electron `printToPDF` fallback also consumes `ExportCss.js`. |
| `src/renderer.js` | On `settings-changed`, toggle `document.body.classList` between `mono-jetbrains` / `mono-fira` and `mono-ligatures-on` / `mono-ligatures-off`. The active class is also written by the bit that initializes Monaco/CodeMirror when the editor is mounted. |
| `scripts/download-tools.js` | Add `fira-code` task: downloads `FiraCode-Regular.ttf`, `FiraCode-Bold.ttf`, `FiraCode-LICENSE.txt` from the official `tonsky/FiraCode` GitHub release (version-pinned, mirrors how Pandoc is downloaded). |
| `package.json` | `build.asarUnpack` extended to `"assets/fonts/**"` so xelatex/Pandoc can read TTFs at runtime in packaged builds. No new NPM dependencies — `jszip ^3.10.1` is already present. |
## Per-Export Behaviour
| Format | What changes | Post-processing | Resulting file shape |
|---|---|---|---|
| **PDF** (xelatex) | Replace `-V monofont="Consolas"` with `--include-in-header=<tmp>.tex` from `PdfFontHeader` (`\setmonofont{JetBrainsMono-Regular.ttf}[Path=…,Extension=.ttf,UprightFont=*-Regular,BoldFont=*-Bold,Ligatures=NoCommon]`). | none — xelatex subsets the font into the PDF. | Self-contained PDF; code-block columns align across pages. |
| **PDF** (lualatex fallback) | Same header uses lualatex-compatible fontspec syntax (identical to xelatex in modern LuaTeX). | none | Same as above. |
| **PDF** (pdflatex final fallback) | Revert to `-V monofont="Consolas"` + warn (Consolas not on all systems; document limitation). | none | Best-effort — relies on pdftex default monospace. |
| **DOCX** | Existing pandoc invocation. After pandoc writes, hand to `DocxFontEmbedder`. | Embed Regular + Bold TTF into `word/fonts/`; patch `[Content_Types].xml` Default+Override; add `word/_rels` entry for `fontTable.xml.rels`; create `word/fontTable.xml` with `<w:embedRegular/>` for each font weight; patch `word/styles.xml` so `SourceCode` (or whatever style Pandoc wrote under) sets `w:rFonts ascii="JetBrains Mono" hAnsi="JetBrains Mono"`. | ~550 KB larger DOCX; fully portable. |
| **HTML** (standalone) | Add `--css=<tmp>.css` (built by `ExportCss` with base64 woff2). | none | One self-contained `.html`; aligned anywhere, offline. |
| **EPUB** | Add `--epub-embed-font=<bundleAbs>/<Family>-Regular.ttf` and same for Bold (Pandoc 2.11+ supports this natively). | `EpubFontEmbedder` patches `OEBPS/content.opf` if the font reference is missing. | Embedded font travels in the EPUB. |
| **ODT** | `--variable=mainfont="JetBrains Mono"` (or Fira). | Before final write, show a non-blocking confirmation: "ODT embeds the font *name* — recipients must also have it installed to keep alignment. Continue?". | Light; portability caveat explicit to user. |
| **RTF** | `\fonttbl` directive already injected by pandoc when `mainfont=` is set. | Same ODT confirmation. | Same caveat as ODT. |
| **LaTeX (`.tex`)** | `--include-in-header=<tmp>.tex` identical to the PDF header. | none | Self-contained `.tex` for downstream compile. |
| **PPTX** | unchanged | n/a | v1: don't try to enforce. |
| **RevealJS** | behaves like HTML (uses `ExportCss`). | n/a | self-contained. |
| **Beamer** | behaves like LaTeX (uses `PdfFontHeader` snippet). | n/a | downstream PDF compile respects font. |
| **Print preview** | n/a | `ExportCss` injected into srcdoc iframe HTML. | Inside-app preview aligned. |
| **ASCII Generator window** | Replace Google Fonts CDN link with local `fonts.css`. | n/a | Offline, aligned. |
## Path Resolution
`MonospaceFontConfig` exposes:
```js
exports.getActiveMonoFontPath = function getActiveMonoFontPath(weight = 400)
exports.getActiveMonoFamily = function getActiveMonoFamily()
exports.ligaturesEnabled = function ligaturesEnabled()
```
- Dev: `<repoRoot>/assets/fonts/<Family>-<Weight>.ttf`
- Packaged: `<process.resourcesPath>/app.asar.unpacked/assets/fonts/<Family>-<Weight>.ttf`
- If the file is missing, returns `null` and emits a `console.warn` + a single non-blocking toast: "Using system monospace — bundled font missing".
## Settings Schema
Extended `<userData>/settings.json`:
```jsonc
{
// ... existing keys ...
"monospaceFont": "jetbrains-mono", // "jetbrains-mono" | "fira-code"
"monospaceLigatures": false // bool
}
```
Defaults: `monospaceFont: "jetbrains-mono"`, `monospaceLigatures: false`. Migration: if a settings file exists without these keys, fill with defaults silently on read.
## Testing
**New test files:**
| File | Asserts |
|---|---|
| `tests/monospace-font-config.test.js` | Dev vs packaged path semantics; null-and-warn on missing TTF; settings-driven family selection. |
| `tests/docx-font-embedder.test.js` | Produces a valid DOCX; `unzip -l` lists `word/fonts/JetBrainsMono-{Regular,Bold}.ttf`; `word/fontTable.xml` contains `<w:embedRegular r:id="…"/>` entries with correct names; `styles.xml` binds the monospace style to `"JetBrains Mono"`; idempotent (running twice doesn't double-embed). |
| `tests/pdf-font-header.test.js` | Output contains `\setmonofont{JetBrainsMono-Regular.ttf}` with `Path=` matching the resolved absolute path; `Ligatures=NoCommon` when settings say off. |
| `tests/export-css.test.js` | Output contains a `@font-face` block with `src: url('data:font/woff2;base64,<…>')`; the base64 string decodes to > 50 000 bytes; `pre`/`code`/`kbd` use `var(--font-mono-active)`. |
| `tests/epub-font-embedder.test.js` | After embedding, `OEBPS/content.opf` references both Regular and Bold TTFs in `<manifest>`. |
**Integration test (manual, repeatable):**
1. Create a fixture markdown file with three ASCII grids (boxes, columns, arrows).
2. Open the file in MarkdownConverter.
3. Set monospace font = JetBrains Mono, ligatures off.
4. Export to PDF / DOCX / HTML.
5. Open each result; confirm the `+---+` column delimiters sit at identical X-positions across all three formats and across pages.
6. Switch to Fira Code with ligatures on; export again; confirm round-trip works (no crashes) and ligature toggle affects preview.
## Error Handling
| Failure | Behaviour |
|---|---|
| Bundled TTF missing | `MonospaceFontConfig` returns `null`; renderer/main falls back to system monospace; non-blocking toast; never a silent drop. |
| `DocxFontEmbedder` fails (zip corruption, insufficient permissions, missing required OOXML element) | Keep the un-embedded DOCX; show a dialog with the exact failure message and a "Report issue" link. Do **not** claim success. |
| `PdfFontHeader` can't write temp tex (filesystem permission) | Show an error dialog naming the permission issue; abort the export. |
| Pandoc `--epub-embed-font` not supported (Pandoc < 2.11) | Detect via `pandoc --version` at startup (cache `pandocAvailable` already exists). Skip embedding; warn user that the EPUB will degrade if their reader lacks the font. |
| Pandoc `--css` flag missing (Pandoc < 2.0) | Detect via the same version check. Skip the `--css` injection; warn user that the exported HTML is not self-contained for the chosen font. |
| xelatex fails after fontspec injection | Existing `tryPdfFallback` chain reorders to `lualatex → pdflatex` (Consolas). Already implemented; the reorder is a one-liner. |
## Acceptance Criteria
- [ ] All five rows of `Per-Export Behaviour` produce files where ASCII alignment is identical to the editor.
- [ ] No new NPM dependencies added (use existing `jszip`, `fontkit`).
- [ ] `asarUnpack` covers `assets/fonts/**`.
- [ ] Bundle size increase ≤ 1.5 MB (TTFs + Fira TTF + extra metadata).
- [ ] No `TODO`/`FIXME`/`HACK` markers in newly touched code.
- [ ] Preview, ASCII Generator window, print-preview iframe, PDF, DOCX, HTML, EPUB, ODT all use the same active font + ligature setting (single source of truth).
- [ ] On a clean machine with no JetBrains Mono / Fira Code installed system-wide, every export still produces correct alignment.
- [ ] Switching between fonts in settings updates preview immediately and is honoured by all subsequent exports in the same session.
- [ ] Both font files travel with the binary (`LICENSE.txt` present for both families).
## File Inventory
**New (10 files):**
```
src/main/MonospaceFontConfig.js
src/main/PdfFontHeader.js
src/main/DocxFontEmbedder.js
src/main/EpubFontEmbedder.js
src/main/ExportCss.js
src/main/settings/SettingsUI.Monospace.js
tests/monospace-font-config.test.js
tests/docx-font-embedder.test.js
tests/pdf-font-header.test.js
tests/export-css.test.js
tests/epub-font-embedder.test.js
assets/fonts/FiraCode-Regular.ttf
assets/fonts/FiraCode-Bold.ttf
assets/fonts/FiraCode-LICENSE.txt
```
**Modified:**
```
src/fonts.css
src/styles/tokens.css
src/styles-concreteinfo.css
src/styles-modern.css
src/ascii-generator.html
src/print-preview.js
src/main.js
src/renderer.js
scripts/download-tools.js
package.json
```
(3 added TTF files counted under "New"; OFL `LICENSE.txt` only required when bundling Fira Code.)
+23
View File
@@ -38,10 +38,30 @@ module.exports = [
document: 'readonly',
localStorage: 'readonly',
alert: 'readonly',
prompt: 'readonly',
confirm: 'readonly',
Event: 'readonly',
CustomEvent: 'readonly',
HTMLElement: 'readonly',
MutationObserver: 'readonly',
TextEncoder: 'readonly',
FileReader: 'readonly',
requestAnimationFrame: 'readonly',
cancelAnimationFrame: 'readonly',
navigator: 'readonly',
location: 'readonly',
fetch: 'readonly',
URL: 'readonly',
Blob: 'readonly',
Image: 'readonly',
DragEvent: 'readonly',
ClipboardEvent: 'readonly',
KeyboardEvent: 'readonly',
MouseEvent: 'readonly',
NodeList: 'readonly',
HTMLInputElement: 'readonly',
HTMLTextAreaElement: 'readonly',
getComputedStyle: 'readonly',
// Electron
electronAPI: 'readonly',
// Libraries
@@ -49,10 +69,13 @@ module.exports = [
DOMPurify: 'readonly',
hljs: 'readonly',
mermaid: 'readonly',
// Node.js global object
global: 'writable',
// Jest
jest: 'readonly',
describe: 'readonly',
test: 'readonly',
it: 'readonly',
expect: 'readonly',
beforeEach: 'readonly',
afterEach: 'readonly',
+15 -15
View File
@@ -11,26 +11,25 @@ module.exports = {
rootDir: '.',
// Test file patterns
testMatch: [
'**/tests/**/*.test.js',
'**/tests/**/*.spec.js'
],
testMatch: ['**/tests/**/*.test.js', '**/tests/**/*.spec.js'],
// Coverage configuration
collectCoverageFrom: [
'src/**/*.js',
'!src/main.js', // Main process needs electron-mock
'!**/node_modules/**'
'!src/renderer.js', // Large renderer file with duplicate declarations
'!src/preload.js', // Electron preload requires contextBridge
'!**/node_modules/**',
],
// Coverage thresholds (start low, increase over time)
// Coverage thresholds (raised with expanded test suite)
coverageThreshold: {
global: {
branches: 10,
functions: 10,
lines: 10,
statements: 10
}
functions: 15,
lines: 15,
statements: 15,
},
},
// Transform settings (no transpilation needed for vanilla JS)
@@ -43,10 +42,11 @@ module.exports = {
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
// Ignore patterns
testPathIgnorePatterns: [
'/node_modules/',
'/dist/'
],
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
// Keep the haste map / snapshot scanner out of build output — electron-builder's
// .snap (Squashfs) artifacts otherwise register as obsolete Jest snapshots.
modulePathIgnorePatterns: ['/dist/'],
// Verbose output
verbose: true,
@@ -55,5 +55,5 @@ module.exports = {
clearMocks: true,
// Reset modules between tests
resetModules: true
resetModules: true,
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+13519
View File
File diff suppressed because it is too large Load Diff
+73 -31
View File
@@ -1,25 +1,29 @@
{
"name": "markdown-converter",
"version": "3.0.0",
"version": "4.5.0",
"description": "Professional Markdown editor and universal file converter with PDF editing, batch processing, and syntax highlighting",
"main": "src/main.js",
"scripts": {
"start": "electron .",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"test:watch": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --watch",
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage",
"lint": "eslint src tests",
"lint:fix": "eslint src tests --fix",
"format": "prettier --write src tests",
"format:check": "prettier --check src tests",
"build": "electron-builder",
"build:win": "electron-builder --win",
"build:win-signed": "cross-env CSC_LINK=code-signing-cert.pfx CSC_KEY_PASSWORD=%CSC_KEY_PASSWORD% electron-builder --win",
"build:win-signed": "cross-env CSC_LINK=code-signing-cert.pfx electron-builder --win",
"build:win-unsigned": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win",
"create-cert": "powershell -ExecutionPolicy Bypass -File scripts/create-selfsigned-cert.ps1",
"build:mac": "electron-builder --mac",
"build:linux": "electron-builder --linux",
"build:linux-ci": "electron-builder --linux deb AppImage",
"build:local": "electron-builder --linux --win",
"dist": "electron-builder --publish=never",
"dist:all": "electron-builder -mwl",
"download-tools": "node scripts/download-tools.js",
"generate-icons": "node scripts/generate-icons.js"
},
"keywords": [
@@ -41,36 +45,63 @@
"devDependencies": {
"@testing-library/dom": "^10.4.1",
"cross-env": "^10.0.0",
"electron": "^37.4.0",
"electron": "^41.1.1",
"electron-builder": "^26.0.12",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0",
"prettier": "^3.7.4",
"sharp": "^0.34.3"
"prettier": "^3.7.4"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.1",
"@codemirror/commands": "^6.10.2",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.0",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/language": "^6.12.2",
"@codemirror/lint": "^6.9.5",
"@codemirror/search": "^6.6.0",
"@codemirror/state": "^6.5.4",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.39.16",
"codemirror": "^6.0.2",
"core-util-is": "^1.0.3",
"docx": "^9.5.1",
"docx4js": "^3.3.0",
"dompurify": "^3.2.6",
"docx": "^9.6.0",
"docx4js": "^2.0.1",
"dompurify": "^3.3.1",
"electron-store": "^10.1.0",
"ffmpeg-static": "^5.3.0",
"highlight.js": "^11.11.1",
"html2pdf.js": "^0.10.1",
"marked": "^16.2.1",
"html2pdf.js": "^0.14.0",
"jszip": "^3.10.1",
"marked": "^17.0.3",
"marked-footnote": "^1.4.0",
"marked-highlight": "^2.2.3",
"mermaid": "^11.12.3",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^3.11.174",
"pdfkit": "^0.14.0",
"pdfjs-dist": "^5.5.207",
"pdfkit": "^0.17.2",
"pizzip": "^3.2.0",
"tslib": "^2.8.1",
"xlsx": "^0.18.5"
"sharp": "^0.34.3",
"simple-git": "^3.32.3",
"tslib": "^2.8.1"
},
"overrides": {
"jszip": "^3.10.1",
"nth-check": "^2.1.1",
"lodash.pick": "npm:lodash@^4.17.21",
"lodash-es": "^4.18.1",
"lodash": "^4.17.21"
},
"build": {
"appId": "com.concreteinfo.markdownconverter",
"productName": "MarkdownConverter",
"copyright": "Copyright (C) 2024-2025 ConcreteInfo",
"directories": {
"output": "dist"
},
@@ -82,6 +113,14 @@
"node_modules/**/*",
"package.json"
],
"asarUnpack": [
"node_modules/ffmpeg-static/**",
"node_modules/sharp/**",
"node_modules/@img/**",
"node_modules/@napi-rs/**",
"assets/fonts/**"
],
"extraFiles": [],
"fileAssociations": [
{
"ext": "md",
@@ -132,7 +171,15 @@
],
"artifactName": "${productName}-${version}-${arch}.${ext}",
"requestedExecutionLevel": "asInvoker",
"signAndEditExecutable": false
"legalTrademarks": "Copyright (C) 2024-2025 ConcreteInfo",
"verifyUpdateCodeSignature": false,
"signAndEditExecutable": false,
"extraFiles": [
{
"from": "bin/win32/pandoc.exe",
"to": "bin/pandoc.exe"
}
]
},
"nsis": {
"oneClick": false,
@@ -154,29 +201,24 @@
"target": [
"deb",
"AppImage",
"snap",
"rpm"
"snap"
],
"category": "Utility",
"maintainer": "ConcreteInfo <amit.wh@gmail.com>"
"maintainer": "ConcreteInfo <amit.wh@gmail.com>",
"extraFiles": [
{
"from": "bin/linux/pandoc",
"to": "bin/pandoc"
}
]
},
"deb": {
"depends": [
"pandoc",
"ffmpeg",
"imagemagick",
"libreoffice-common"
],
"description": "Professional Markdown editor and universal file converter",
"maintainer": "ConcreteInfo <amit.wh@gmail.com>"
},
"rpm": {
"depends": [
"pandoc",
"ffmpeg",
"ImageMagick",
"libreoffice-core"
]
}
}
}
+604
View File
@@ -0,0 +1,604 @@
# Repository Structure Map
Auto-generated by `~/.claude-shared/scripts/repo-map.sh` (universal-ctags).
Signatures only — classes, functions, methods, interfaces, enums, types, namespaces, traits.
Regenerate after structural changes. Languages: `JavaScript,Sh`.
```
scripts/download-tools.js:
L22 method extract (PANDOC_CONFIG.linux)
L36 method extract (PANDOC_CONFIG.win32)
L51 method extract (PANDOC_CONFIG.darwin)
L63 function download
L70 function get (download)
L109 function downloadPandoc
scripts/generate-icons.js:
L17 function generateIcons
src/adapters/electron/fs.js:
L20 method readFile (electronFsAdapter)
L30 method writeFile (electronFsAdapter)
L39 method deleteFile (electronFsAdapter)
L48 method ensureDir (electronFsAdapter)
L57 method listDirectory (electronFsAdapter)
L77 method exists (electronFsAdapter)
L86 method isDirectory (electronFsAdapter)
L96 method copy (electronFsAdapter)
L106 method move (electronFsAdapter)
src/analytics/analytics-panel.js:
L7 function showAnalyticsModal
L105 function escHandler (showAnalyticsModal)
L116 function escapeHtml
src/analytics/writing-analytics.js:
L77 function countSyllables
L83 function extractWords
L87 function getReadabilityLabel
L95 function analyze
src/command-palette.js:
L1 class CommandPalette
L2 method constructor (CommandPalette)
L12 method register (CommandPalette)
L16 method open (CommandPalette)
L24 method close (CommandPalette)
L28 method isOpen (CommandPalette)
L32 method setupEventListeners (CommandPalette)
L61 method renderResults (CommandPalette)
L90 method highlightMatch (CommandPalette)
L96 method updateSelection (CommandPalette)
L105 method executeSelected (CommandPalette)
src/editor/codemirror-setup.js:
L46 function createEditor
L61 function onChange (createEditor)
L118 function getLanguageExtension
L120 method javascript (getLanguageExtension.loaders)
L124 method html (getLanguageExtension.loaders)
L128 method css (getLanguageExtension.loaders)
L132 method json (getLanguageExtension.loaders)
L136 method python (getLanguageExtension.loaders)
src/main.js:
L18 function getPandocPath
L36 function getFFmpegPath
L55 function sanitizeErrorMessage
L64 function createRateLimiter
L66 function canProceed (createRateLimiter)
L83 function validatePath
L136 function resolveWritablePath
L181 function isPathAccessible
L203 function convertDataToMarkdown
L225 function runPandocCmd
L247 function parseCommand
L282 method get (store)
L291 method set (store)
L488 function checkPandocAvailability
L500 function createWindow
L586 function buildRecentFilesMenu
L599 method click (buildRecentFilesMenu.anonymousObjectc5643c890c05)
L637 function getRecentFiles
L647 function createMenu
L872 method click (createMenu.anonymousObjectc5643c890e05.anonymousObjectc5643c894505)
L1118 method click (createMenu.anonymousObjectc5643c895205.anonymousObjectc5643c897e05)
L1279 method click (createMenu.anonymousObjectc5643c899305.anonymousObjectc5643c89a505)
L1351 function showAboutDialog
L1452 function showDependenciesDialog
L1564 function openPDFFile
L1583 function openFile
L1622 function openPdfFile
L1645 function saveAsFile
L1664 function exportFile
L1673 function showExportOptionsDialog
L1676 function showBatchConversionDialog
L1681 function selectWordTemplate
L1705 function showTemplateSettings
L1902 function processDynamicFields
L1921 function setDocxPageSize
L1980 function addHeaderFooterToDocx
L2111 function exportWordWithTemplate
L2153 function exportPDFViaWordTemplate
L2231 function showUniversalConverterDialog
L2236 function showPDFEditorDialog
L2246 function checkConverterAvailable
L2370 function collectFiles
L2464 function convertWithLibreOffice
L2498 function convertWithImageMagick
L2507 function convertWithFFmpeg
L2515 function convertWithPandoc
L2521 function performExportWithOptions
L2805 function tryPdfFallback
L2882 function showExportSuccess
L2892 function exportWithPandoc
L2964 function exportToHTML
L3080 function exportToPDFElectron
L3224 function exportSpreadsheet
L3233 function importDocument
L3355 function setTheme
L3536 function extractTablesFromMarkdown
L3574 function performBatchConversion
L3597 function findMarkdownFiles (performBatchConversion)
L3636 function processNextFile (performBatchConversion)
L3970 function handleCLIConversion
L3997 function showConversionDialog
L4064 function performCLIConversion
L4098 function buildPandocCommand
L4319 function openFileFromPath
L4394 function openAsciiGenerator
L4426 function openTableGenerator
L4724 function loadSnippets
L4734 function saveSnippetsFile
src/main/GitOperations.js:
L3 function getGitInstance
L7 function getStatus
L16 function stage
L26 function commit
L35 function log
src/main/PDFOperations.js:
L5 function parsePageRanges
L28 function hexToRgb
L39 function pdfMerge
L59 function pdfSplit
L126 function pdfCompress
L152 function pdfRotate
L182 function pdfDeletePages
L208 function pdfReorder
L233 function pdfWatermark
L319 function pdfEncrypt
L353 function pdfDecrypt
L370 function pdfSetPermissions
L404 function executeOperation
L431 function getPageCount
src/plugins/built-in/_sample/index.js:
L3 class SamplePlugin
L4 method init (SamplePlugin)
src/plugins/built-in/writing-studio/goal-tracker.js:
L3 class GoalTracker
L7 method constructor (GoalTracker)
L11 method _getHistory (GoalTracker)
L16 method _setHistory (GoalTracker)
L20 method _setHistoryDay (GoalTracker)
L26 method addWords (GoalTracker)
L37 method getDailyProgress (GoalTracker)
L44 method getStreak (GoalTracker)
L61 method getLast30Days (GoalTracker)
L74 method getWeeklyTotal (GoalTracker)
src/plugins/built-in/writing-studio/index.js:
L7 class WritingStudioPlugin
L8 method init (WritingStudioPlugin)
L34 method _registerCommands (WritingStudioPlugin)
L112 method _registerStatusBar (WritingStudioPlugin)
L123 method deactivate (WritingStudioPlugin)
L127 method getEngines (WritingStudioPlugin)
src/plugins/built-in/writing-studio/panels/goals-panel.js:
L1 function renderGoalsPanel
src/plugins/built-in/writing-studio/panels/manuscript-panel.js:
L1 function renderManuscriptPanel
src/plugins/built-in/writing-studio/panels/proofread-panel.js:
L1 function renderProofreadPanel
L41 method callback (anonymousObject39a0f0110105)
L50 function renderIssues
src/plugins/built-in/writing-studio/panels/snapshots-panel.js:
L1 function renderSnapshotsPanel
src/plugins/built-in/writing-studio/project-manager.js:
L1 class ProjectManager
L5 method constructor (ProjectManager)
L9 method createProject (ProjectManager)
L21 method loadProject (ProjectManager)
L27 method _saveProject (ProjectManager)
L31 method addChapter (ProjectManager)
L38 method updateChapter (ProjectManager)
L45 method compileManuscript (ProjectManager)
L56 method getStats (ProjectManager)
src/plugins/built-in/writing-studio/snapshot-manager.js:
L1 class SnapshotManager
L6 method constructor (SnapshotManager)
L11 method _getAll (SnapshotManager)
L16 method _saveAll (SnapshotManager)
L20 method create (SnapshotManager)
L34 method list (SnapshotManager)
L38 method getById (SnapshotManager)
L42 method restore (SnapshotManager)
L48 method delete (SnapshotManager)
L53 method diff (SnapshotManager)
L71 method prune (SnapshotManager)
src/plugins/built-in/writing-studio/sprint-engine.js:
L1 class SprintEngine
L6 method constructor (SprintEngine)
L14 method start (SprintEngine)
L22 method stop (SprintEngine)
L33 method tick (SprintEngine)
L43 method isActive (SprintEngine)
L47 method getRemaining (SprintEngine)
src/plugins/event-bus.js:
L1 class EventBus
L2 method constructor (EventBus)
L6 method on (EventBus)
L13 method off (EventBus)
L25 method emit (EventBus)
L37 method hasHandler (EventBus)
src/plugins/plugin-api.js:
L1 class PluginAPI
L7 method init (PluginAPI)
L12 method activate (PluginAPI)
L15 method deactivate (PluginAPI)
L18 method getManifest (PluginAPI)
src/plugins/plugin-context.js:
L1 class PluginContext
L14 method constructor (PluginContext)
L23 method register (PluginContext.constructor.commands)
L24 function safeHandler (PluginContext.constructor.commands.register)
L65 method registerPreHook (PluginContext.constructor.exports)
L68 method registerPostHook (PluginContext.constructor.exports)
src/plugins/plugin-loader.js:
L4 class PluginLoader
L8 method constructor (PluginLoader)
L17 method discoverPlugins (PluginLoader)
L66 method validateManifest (PluginLoader)
src/plugins/plugin-registry.js:
L4 class PluginRegistry
L5 method constructor (PluginRegistry)
L15 method register (PluginRegistry)
L49 method getPlugin (PluginRegistry)
L53 method getAll (PluginRegistry)
L57 method activate (PluginRegistry)
L68 method deactivate (PluginRegistry)
src/plugins/settings-store.js:
L1 class SettingsStore
L5 method constructor (SettingsStore)
L9 method get (SettingsStore)
L13 method set (SettingsStore)
L17 method onChanged (SettingsStore)
src/preload.js:
L257 method send (anonymousObjectb0724fcb0105)
L271 method invoke (anonymousObjectb0724fcb0105)
L290 method on (anonymousObjectb0724fcb0105)
L292 function subscription (anonymousObjectb0724fcb0105.on)
L310 method once (anonymousObjectb0724fcb0105)
L322 method removeAllListeners (anonymousObjectb0724fcb0105)
src/print-preview.js:
L1 class PrintPreview
L2 method constructor (PrintPreview)
L9 method open (PrintPreview)
L20 method close (PrintPreview)
L28 method setupEventListeners (PrintPreview)
L53 method updateScaleLabel (PrintPreview)
L59 method updatePreview (PrintPreview)
L111 method refreshPreview (PrintPreview)
L117 method getOptions (PrintPreview)
L130 method executePrint (PrintPreview)
src/renderer.js:
L19 method send (window.electronAPI)
L22 method invoke (window.electronAPI)
L25 method on (window.electronAPI)
L26 function subscription (window.electronAPI.on)
L32 method once (window.electronAPI)
L35 method removeAllListeners (window.electronAPI)
L81 function getSidebarManager
L85 function getRenderTemplatesPanel
L90 function getRenderExplorerPanel
L95 function getRenderGitPanel
L99 function getRenderSnippetsPanel
L105 function getRenderOutlinePanel
L110 function getReplPanel
L114 function getCommandPalette
L118 function getPrintPreview
L122 function getCreateWelcomeContent
L127 function getZenMode
L132 function getShowAnalyticsModal
L137 function ensureToastContainer
L147 function notifyUser
L159 function dismiss (notifyUser)
L173 method highlight (anonymousObject71555c7b0405)
L202 method start (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
L205 method tokenizer (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
L221 method renderer (anonymousObject71555c7b0705.anonymousObject71555c7b0805)
L241 function plantumlEncode (notifyUser)
L249 function scopeCSS (notifyUser)
L271 class TabManager (notifyUser)
L272 method constructor (notifyUser.TabManager)
L306 method setupEventListeners (notifyUser.TabManager)
L354 method createNewTab (notifyUser.TabManager)
L379 method createPdfTab (notifyUser.TabManager)
L405 method createPdfTabElements (notifyUser.TabManager)
L436 method setupPdfTabEvents (notifyUser.TabManager)
L503 method loadPdfInTab (notifyUser.TabManager)
L528 method renderPdfPageInTab (notifyUser.TabManager)
L555 method createTabElements (notifyUser.TabManager)
L580 method onChange (anonymousObject71555c7b0d05)
L602 method onUpdate (anonymousObject71555c7b0d05)
L614 method switchToTab (notifyUser.TabManager)
L641 method switchToNextTab (notifyUser.TabManager)
L647 method closeTab (notifyUser.TabManager)
L692 method updateTabBar (notifyUser.TabManager)
L718 method updateUI (notifyUser.TabManager)
L748 method saveCurrentTabState (notifyUser.TabManager)
L756 method restoreTabState (notifyUser.TabManager)
L765 method focusActiveEditor (notifyUser.TabManager)
L771 method updatePreview (notifyUser.TabManager)
L800 method _hash (notifyUser.TabManager)
L809 method _renderPreview (notifyUser.TabManager)
L963 function onerror (img)
L997 method updatePreviewVisibility (notifyUser.TabManager)
L1010 method updateLineNumbers (notifyUser.TabManager)
L1015 method updateWordCount (notifyUser.TabManager)
L1031 method updateCursorPosition (notifyUser.TabManager)
L1038 method updateFilePath (notifyUser.TabManager)
L1046 method updateBreadcrumb (notifyUser.TabManager)
L1054 method setupEditorEvents (notifyUser.TabManager)
L1058 method handleEditorInput (notifyUser.TabManager)
L1073 method startAutoSave (notifyUser.TabManager)
L1081 method stopAutoSave (notifyUser.TabManager)
L1087 method performAutoSave (notifyUser.TabManager)
L1103 method showAutoSaveIndicator (notifyUser.TabManager)
L1119 method addToRecentFiles (notifyUser.TabManager)
L1135 method getRecentFiles (notifyUser.TabManager)
L1145 method setupToolbarEvents (notifyUser.TabManager)
L1215 method wrapSelection (notifyUser.TabManager)
L1233 method insertAtLineStart (notifyUser.TabManager)
L1249 method insertTable (notifyUser.TabManager)
L1259 method insertCodeBlock (notifyUser.TabManager)
L1277 method insertHorizontalRule (notifyUser.TabManager)
L1280 method setupFindEvents (notifyUser.TabManager)
L1350 method performFind (notifyUser.TabManager)
L1384 method findNext (notifyUser.TabManager)
L1390 method findPrevious (notifyUser.TabManager)
L1399 method highlightMatch (notifyUser.TabManager)
L1430 method replaceOne (notifyUser.TabManager)
L1454 method replaceAll (notifyUser.TabManager)
L1485 method clearFindHighlights (notifyUser.TabManager)
L1492 method checkForLargeFile (notifyUser.TabManager)
L1508 method openFile (notifyUser.TabManager)
L1555 method getEditorContent (notifyUser.TabManager)
L1564 method setEditorContent (notifyUser.TabManager)
L1579 method insertAtCursor (notifyUser.TabManager)
L1594 method getSelection (notifyUser.TabManager)
L1602 method replaceSelection (notifyUser.TabManager)
L1616 method getCurrentContent (notifyUser.TabManager)
L1620 method getCurrentFilePath (notifyUser.TabManager)
L1735 method render (anonymousObject71555c7b2d05)
L1788 method registerIndicator (anonymousObject71555c7b3105.statusBar)
L1881 function onload (reader)
L2032 method onChange (anonymousObject71555c7b3405)
L2040 method onUpdate (anonymousObject71555c7b3405)
L2164 function applyCustomPreviewCSS (notifyUser)
L2174 function triggerLoadCustomCSS (notifyUser)
L2188 function triggerClearCustomCSS (notifyUser)
L2202 function updateFontSizes (notifyUser)
L2234 function openPrintPreviewDialog (notifyUser)
L2255 function showExportDialog (notifyUser)
L2269 function hideExportDialog (notifyUser)
L2273 function initializeExportForm (notifyUser)
L2343 function collectExportOptions (notifyUser)
L2444 function loadExportProfiles (notifyUser)
L2456 function saveExportProfiles (notifyUser)
L2459 function populateProfileDropdown (notifyUser)
L2476 function saveCurrentProfile (notifyUser)
L2511 function loadProfile (notifyUser)
L2545 function deleteSelectedProfile (notifyUser)
L2679 function onchange (input)
L2776 function showBatchDialog (notifyUser)
L2796 function hideBatchDialog (notifyUser)
L2799 function updateBatchProgress (notifyUser)
L2816 function validateBatchForm (notifyUser)
L3375 function showUniversalConverterDialog (notifyUser)
L3383 function updateConverterFormats (notifyUser)
L3423 function updateConverterAdvancedOptions (notifyUser)
L3434 function collectConverterAdvancedOptions (notifyUser)
L3645 function showPDFEditorDialog (notifyUser)
L3769 function hidePDFEditorDialog (notifyUser)
L3780 function updateMergeFilesList (notifyUser)
L4107 function getPDFStatusElement (notifyUser)
L4110 function showPDFStatus (notifyUser)
L4117 function clearPDFStatus (notifyUser)
L4124 function showPDFValidationMessage (notifyUser)
L4135 function processPDFOperation (notifyUser)
L4379 function initMathSupport (notifyUser)
L4391 function onload (katexJS)
L4396 function onload (autoRenderJS)
L4417 function openHeaderFooterDialog (notifyUser)
L4425 function closeHeaderFooterDialog (notifyUser)
L4430 function openFieldPickerDialog (notifyUser)
L4436 function closeFieldPickerDialog (notifyUser)
L4477 function toggleConfigContent (notifyUser)
L4488 function saveHeaderFooterSettings (notifyUser)
L4509 function browseForLogo (notifyUser)
L4519 function clearLogo (notifyUser)
L4528 function insertDynamicField (notifyUser)
L4594 function showTableGenerator (notifyUser)
L4605 function hideTableGenerator (notifyUser)
L4608 function generateTablePreview (notifyUser)
L4616 function generateMarkdownTable (notifyUser)
L4685 function insertGeneratedTable (notifyUser)
L4742 function showASCIIGenerator (notifyUser)
L4753 function hideASCIIGenerator (notifyUser)
L4756 function switchASCIIMode (notifyUser)
L4784 function generateASCIIPreview (notifyUser)
L4802 function textToASCII (notifyUser)
L5238 function createASCIIBox (notifyUser)
L5312 function getASCIITemplate (notifyUser)
L5469 function loadASCIITemplate (notifyUser)
L5473 function insertASCIIArt (notifyUser)
L5523 function anonymousFunction71555c7bd300
L5603 function getPdfjsLib (notifyUser)
L5612 function openPdfFile (notifyUser)
L5627 function renderPdfPage (notifyUser)
L5733 function closePdfViewer (notifyUser)
L5783 function openPdfEditorDialog (notifyUser)
L5831 function initPaneResizer (notifyUser)
L5920 function onPDFFileSelected (notifyUser)
L5935 function loadPDFThumbnails (notifyUser)
L5966 function renderThumbnailGrid (notifyUser)
L6060 function renderThumbnail (notifyUser)
L6085 function syncRotateInput (notifyUser)
L6094 function syncDeleteInput (notifyUser)
L6103 function syncReorderInput (notifyUser)
src/repl/repl-panel.js:
L1 class ReplPanel
L2 method constructor (ReplPanel)
L8 method setupEventListeners (ReplPanel)
L13 method toggle (ReplPanel)
L19 method show (ReplPanel)
L25 method clear (ReplPanel)
L29 method appendOutput (ReplPanel)
L42 method escapeHtml (ReplPanel)
src/sidebar/explorer-panel.js:
L1 function renderExplorerPanel
L40 function renderTree
L79 function getFileIcon
src/sidebar/git-panel.js:
L1 function renderGitPanel
L24 function loadGitStatus (renderGitPanel)
src/sidebar/outline-panel.js:
L6 function renderOutlinePanel
L18 function parseHeadings (renderOutlinePanel)
L36 function findActiveHeading (renderOutlinePanel)
L48 function renderHeadings (renderOutlinePanel)
L89 function escapeHtml (renderOutlinePanel)
L95 function refresh (renderOutlinePanel)
L100 function setActiveHeading (renderOutlinePanel)
src/sidebar/sidebar-manager.js:
L1 class SidebarManager
L2 method constructor (SidebarManager)
L11 method setupEventListeners (SidebarManager)
L20 method registerPanel (SidebarManager)
L24 method togglePanel (SidebarManager)
L32 method expand (SidebarManager)
L45 method collapse (SidebarManager)
src/sidebar/snippets-panel.js:
L1 function renderSnippetsPanel
L14 function loadSnippets (renderSnippetsPanel)
L19 function renderList (renderSnippetsPanel)
src/sidebar/templates-panel.js:
L18 function renderTemplatesPanel
src/utils/ModalManager.js:
L5 class ModalManager
L16 method constructor (ModalManager)
L31 method init (ModalManager)
L47 method setupCloseTriggers (ModalManager)
L51 function handler (ModalManager.setupCloseTriggers)
L65 function handler
L74 method getFocusableElements (ModalManager)
L89 method trapFocus (ModalManager)
L111 method handleKeydown (ModalManager)
L119 method open (ModalManager)
L141 function keydownHandler (ModalManager.open)
L164 method close (ModalManager)
L182 function addHidden (ModalManager.close)
L188 function onTransitionEnd (ModalManager.close)
L223 method isOpen (ModalManager)
L227 method destroy (ModalManager)
src/welcome.js:
L1 function createWelcomeContent
src/wordTemplateExporter.js:
L11 class WordTemplateExporter
L12 method constructor (WordTemplateExporter)
L24 method preprocessMarkdownForWordExport (WordTemplateExporter)
L33 function flush (WordTemplateExporter.preprocessMarkdownForWordExport)
L59 function stripArtifacts (WordTemplateExporter.preprocessMarkdownForWordExport)
src/zen-mode.js:
L10 class ZenMode
L14 method constructor (ZenMode)
L23 method activate (ZenMode)
L65 method deactivate (ZenMode)
L101 method toggle (ZenMode)
L109 method _applyTypewriterBehavior (ZenMode)
L111 function scrollFn (ZenMode._applyTypewriterBehavior)
L151 method _createHUD (ZenMode)
L169 method _updateHUD (ZenMode)
L220 method constructor (anonymousObject3acf7ce30205)
L240 function getOpacity
L250 method constructor (anonymousObject3acf7ce30405)
tests/git-operations.test.js:
L26 function asyncFn
L35 function asyncFnWithError
tests/main-utils.test.js:
L7 function sanitizeErrorMessage
L49 function createRateLimiter
L51 function canProceed (createRateLimiter)
tests/markdown-extensions.test.js:
L83 method start (extension)
L86 method tokenizer (extension)
L102 method renderer (extension)
L151 function plantumlEncode
L176 function slugify
L203 function scopeCSS
tests/modal-manager.test.js:
L11 function createModalElement
tests/plugin-api.test.js:
L18 class MyPlugin
L19 method init (MyPlugin)
tests/plugin-context.test.js:
L39 function badHandler
tests/plugin-loader.test.js:
L17 function writeManifest
tests/plugin-registry.test.js:
L5 class TestPlugin
L6 method init (TestPlugin)
L10 method activate (TestPlugin)
L13 method deactivate (TestPlugin)
L69 class BadPlugin
L70 method init (BadPlugin)
tests/setup.js:
L96 function error (console)
tests/sidebar.test.js:
L41 method render (anonymousObjectfe2d35d70105)
L52 method render (anonymousObjectfe2d35d70205)
L62 method render (anonymousObjectfe2d35d70305)
L68 method render (anonymousObjectfe2d35d70405)
L80 method render (anonymousObjectfe2d35d70505)
L88 method render (anonymousObjectfe2d35d70605)
L96 method render (anonymousObjectfe2d35d70705)
L120 method render (anonymousObjectfe2d35d70905)
L130 method render (anonymousObjectfe2d35d70a05)
tests/utils.test.js:
L9 function parseCommand
L78 function hexToRgb
L121 function getExtension
L133 function replaceExtension
```
+59
View File
@@ -0,0 +1,59 @@
# create-selfsigned-cert.ps1
# Generates a self-signed code-signing certificate for local/development builds.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File scripts/create-selfsigned-cert.ps1
# npm run create-cert
#
# Then build with:
# $env:CSC_LINK="code-signing-cert.pfx"; $env:CSC_KEY_PASSWORD="YourPassword"; npm run build:win-signed
#
# NOTE: Self-signed certificates will still show a SmartScreen warning for end users.
# For production releases, obtain an OV or EV certificate from a trusted CA
# (DigiCert, Sectigo, Certum, etc.). EV certificates bypass SmartScreen immediately.
# Open-source projects can apply for free signing at https://signpath.io/
param(
[string]$CertPassword = "MarkdownConverter2025",
[string]$OutputFile = "code-signing-cert.pfx",
[string]$Subject = "CN=ConcreteInfo, O=ConcreteInfo, L=India, C=IN"
)
Write-Host "Creating self-signed code-signing certificate..." -ForegroundColor Cyan
# Create the certificate in the current user's certificate store
$cert = New-SelfSignedCertificate `
-Type CodeSigningCert `
-Subject $Subject `
-CertStoreLocation "Cert:\CurrentUser\My" `
-NotAfter (Get-Date).AddYears(3) `
-HashAlgorithm SHA256 `
-KeyLength 4096 `
-KeyUsage DigitalSignature
if (-not $cert) {
Write-Error "Failed to create certificate."
exit 1
}
Write-Host "Certificate created: $($cert.Thumbprint)" -ForegroundColor Green
# Export to PFX
$securePassword = ConvertTo-SecureString -String $CertPassword -Force -AsPlainText
$exportPath = Join-Path (Get-Location) $OutputFile
Export-PfxCertificate -Cert $cert -FilePath $exportPath -Password $securePassword | Out-Null
if (Test-Path $exportPath) {
Write-Host "Certificate exported to: $exportPath" -ForegroundColor Green
Write-Host ""
Write-Host "To build a signed release:" -ForegroundColor Yellow
Write-Host ' $env:CSC_LINK="code-signing-cert.pfx"' -ForegroundColor White
Write-Host " `$env:CSC_KEY_PASSWORD=`"$CertPassword`"" -ForegroundColor White
Write-Host " npm run build:win-signed" -ForegroundColor White
Write-Host ""
Write-Host "IMPORTANT: Add code-signing-cert.pfx to .gitignore!" -ForegroundColor Red
} else {
Write-Error "Export failed."
exit 1
}
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env node
/**
* Downloads pandoc binary for the current build platform.
* Run automatically via `npm run download-tools` before building.
* Skips download if binary already exists (idempotent).
*/
const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
const PANDOC_VERSION = '3.9.0.2';
const PANDOC_CONFIG = {
linux: {
url: `https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz`,
archiveExt: '.tar.gz',
destFile: 'pandoc',
extract(archivePath, destDir) {
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
fs.mkdirSync(tmpDir, { recursive: true });
execSync(`tar -xzf "${archivePath}" -C "${tmpDir}" pandoc-${PANDOC_VERSION}/bin/pandoc`);
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'bin', 'pandoc');
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
fs.rmSync(tmpDir, { recursive: true, force: true });
},
},
win32: {
url: `https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-windows-x86_64.zip`,
archiveExt: '.zip',
destFile: 'pandoc.exe',
extract(archivePath, destDir) {
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
fs.mkdirSync(tmpDir, { recursive: true });
execSync(
`powershell -Command "Expand-Archive -Force '${archivePath}' '${tmpDir}'"`,
);
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'pandoc.exe');
fs.copyFileSync(src, path.join(destDir, 'pandoc.exe'));
fs.rmSync(tmpDir, { recursive: true, force: true });
},
},
darwin: {
url: `https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-x86_64-macOS.zip`,
archiveExt: '.zip',
destFile: 'pandoc',
extract(archivePath, destDir) {
const tmpDir = path.join(os.tmpdir(), `pandoc-${Date.now()}`);
fs.mkdirSync(tmpDir, { recursive: true });
execSync(`unzip -o "${archivePath}" -d "${tmpDir}"`);
const src = path.join(tmpDir, `pandoc-${PANDOC_VERSION}`, 'bin', 'pandoc');
fs.copyFileSync(src, path.join(destDir, 'pandoc'));
fs.chmodSync(path.join(destDir, 'pandoc'), 0o755);
fs.rmSync(tmpDir, { recursive: true, force: true });
},
},
};
function download(url, destPath) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(destPath);
let received = 0;
let total = 0;
let lastPct = -1;
function get(redirectUrl) {
const client = redirectUrl.startsWith('https://') ? https : http;
client
.get(redirectUrl, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
get(res.headers.location);
return;
}
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode} for ${redirectUrl}`));
return;
}
total = parseInt(res.headers['content-length'] || '0', 10);
res.on('data', (chunk) => {
received += chunk.length;
if (total > 0) {
const pct = Math.floor((received / total) * 100);
if (pct !== lastPct && pct % 10 === 0) {
process.stdout.write(` ${pct}%\r`);
lastPct = pct;
}
}
});
res.pipe(file);
file.on('finish', () => {
file.close();
process.stdout.write(' 100%\n');
resolve();
});
})
.on('error', (err) => {
fs.unlink(destPath, () => {});
reject(err);
});
}
get(url);
});
}
async function downloadFiraCode() {
const destDir = path.join(__dirname, '..', 'assets', 'fonts');
fs.mkdirSync(destDir, { recursive: true });
const targets = [
{ url: 'https://github.com/tonsky/FiraCode/raw/master/distr/ttf/FiraCode-Regular.ttf', out: 'FiraCode-Regular.ttf' },
{ url: 'https://github.com/tonsky/FiraCode/raw/master/distr/ttf/FiraCode-Bold.ttf', out: 'FiraCode-Bold.ttf' },
{ url: 'https://raw.githubusercontent.com/tonsky/FiraCode/master/LICENSE', out: 'FiraCode-LICENSE.txt' },
];
for (const t of targets) {
const destFile = path.join(destDir, t.out);
if (fs.existsSync(destFile)) {
console.log(`[download-tools] ${t.out} already present — skipping.`);
continue;
}
console.log(`[download-tools] Downloading ${t.out}...`);
await download(t.url, destFile);
}
}
async function downloadPandoc() {
const platform = process.platform;
const config = PANDOC_CONFIG[platform];
if (!config) {
console.log(`[download-tools] No pandoc config for platform "${platform}" — skipping.`);
return;
}
const destDir = path.join(__dirname, '..', 'bin', platform);
const destFile = path.join(destDir, config.destFile);
if (fs.existsSync(destFile)) {
console.log(`[download-tools] pandoc already present at ${destFile} — skipping.`);
return;
}
fs.mkdirSync(destDir, { recursive: true });
const tmpArchive = path.join(os.tmpdir(), `pandoc-download${config.archiveExt}`);
console.log(`[download-tools] Downloading pandoc ${PANDOC_VERSION} for ${platform}...`);
await download(config.url, tmpArchive);
console.log(`[download-tools] Extracting to ${destDir}...`);
config.extract(tmpArchive, destDir);
try {
fs.unlinkSync(tmpArchive);
} catch (_) {
/* ignore */
}
console.log(`[download-tools] pandoc ready: ${destFile}`);
}
Promise.all([downloadPandoc(), downloadFiraCode()]).catch((err) => {
console.error('[download-tools] FAILED:', err.message);
process.exit(1);
});
+111
View File
@@ -0,0 +1,111 @@
/**
* Electron File System Adapter
*
* Implements file system operations for Electron using IPC.
* This abstracts file operations to enable easier testing and migration.
*
* @version 4.4.1
*/
/**
* Electron File System Adapter
* @type {import('../types').FileSystemAdapter}
*/
const electronFsAdapter = {
/**
* Read file content
* @param {string} path - File path
* @returns {Promise<string>} File content
*/
async readFile(path) {
return await window.electronAPI.file.read(path);
},
/**
* Write content to file
* @param {string} path - File path
* @param {string} content - File content
* @returns {Promise<void>}
*/
async writeFile(path, content) {
return await window.electronAPI.file.write(path, content);
},
/**
* Delete file
* @param {string} path - File path
* @returns {Promise<void>}
*/
async deleteFile(path) {
return await window.electronAPI.file.delete(path);
},
/**
* Ensure directory exists
* @param {string} path - Directory path
* @returns {Promise<void>}
*/
async ensureDir(path) {
return await window.electronAPI.file.ensureDir(path);
},
/**
* List directory contents
* @param {string} path - Directory path
* @returns {Promise<Array<import('../types').FileInfo>>}
*/
async listDirectory(path) {
const result = await window.electronAPI.invoke('list-directory', path);
if (!result?.entries) {
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);
},
};
module.exports = { electronFsAdapter };
+133
View File
@@ -0,0 +1,133 @@
/**
* Platform Adapter Type Definitions
*
* This module defines the interfaces for platform-specific operations.
* Adapters abstract file system, conversion, and system operations
* to enable easier testing and future platform migration.
*
* @version 4.4.1
*/
/**
* @typedef {Object} FileInfo
* @property {string} name - File or directory name
* @property {boolean} isDir - True if directory
* @property {number} size - File size in bytes
* @property {number} modified - Last modified timestamp (ms since epoch)
*/
/**
* @typedef {Object} WatchEvent
* @property {string} type - Event type ('add', 'change', 'unlink', 'addDir', 'unlinkDir')
* @property {string} path - Affected file/directory path
*/
/**
* @typedef {Object} ConversionOptions
* @property {string} format - Output format (pdf, docx, html, etc.)
* @property {string} [pdfEngine] - PDF engine for PDF export (xelatex, pdflatex, etc.)
* @property {string} [template] - Word template path for DOCX
* @property {string} [geometry] - Page geometry for PDF (e.g., 'margin=1in')
* @property {string} [header] - Header content
* @property {string} [footer] - Footer content
* @property {boolean} [toc] - Include table of contents
*/
/**
* @typedef {Object} ConversionResult
* @property {string} input - Input file path
* @property {string} output - Output file path
* @property {boolean} success - Whether conversion succeeded
* @property {string} [error] - Error message if failed
*/
/**
* @typedef {Object} PlatformCapabilities
* @property {boolean} hasPandoc - Pandoc is available
* @property {boolean} hasFfmpeg - FFmpeg is available
* @property {boolean} hasLibreOffice - LibreOffice is available
* @property {boolean} hasDirectFs - Direct file system access
* @property {boolean} hasSystemNotifications - System notifications available
* @property {boolean} hasPdfJs - PDF.js available for PDF viewing
*/
/**
* @typedef {Object} DialogOptions
* @property {string} [title] - Dialog title
* @property {string} [defaultPath] - Default path
* @property {string[]} [filters] - File filters [{ name: 'Markdown', extensions: ['md'] }]
* @property {string} [buttonLabel] - Custom button label
*/
/**
* @typedef {Object} SystemInfo
* @property {string} platform - Operating system (win32, darwin, linux)
* @property {string} homeDir - User home directory
* @property {string} documentsDir - Documents directory
* @property {string} downloadsDir - Downloads directory
* @property {string} tempDir - Temporary directory
* @property {string} appVersion - Application version
*/
/**
* @typedef {Object} FileSystemAdapter
* @property {(path: string) => Promise<string>} readFile - Read file content
* @property {(path: string, content: string) => Promise<void>} writeFile - Write file content
* @property {(path: string) => Promise<void>} deleteFile - Delete file
* @property {(path: string) => Promise<void>} ensureDir - Ensure directory exists
* @property {(path: string) => Promise<FileInfo[]>} listDirectory - List directory contents
* @property {(path: string) => Promise<boolean>} exists - Check if path exists
* @property {(path: string) => Promise<boolean>} isDirectory - Check if path is directory
* @property {(source: string, dest: string) => Promise<void>} copy - Copy file or directory
* @property {(source: string, dest: string) => Promise<void>} move - Move file or directory
* @property {(path: string, callback: (event: WatchEvent) => void) => () => void>} [watchDirectory] - Watch directory for changes
*/
/**
* @typedef {Object} ConversionAdapter
* @property {(input: string, output: string, options: ConversionOptions) => Promise<void>} convertFile - Convert single file
* @property {(files: string[], outputDir: string, options: ConversionOptions) => Promise<ConversionResult[]>} batchConvert - Batch convert files
* @property {() => Promise<boolean>} checkPandoc - Check if Pandoc is available
* @property {() => Promise<boolean>} checkFfmpeg - Check if FFmpeg is available
* @property {() => Promise<boolean>} checkLibreOffice - Check if LibreOffice is available
*/
/**
* @typedef {Object} DialogAdapter
* @property {(options?: DialogOptions) => Promise<string|null>} showOpenDialog - Show open file dialog
* @property {(options?: DialogOptions) => Promise<string[]>} showOpenDialogMulti - Show multi-select open dialog
* @property {(options?: DialogOptions) => Promise<string|null>} showSaveDialog - Show save file dialog
* @property {(message: string, type?: string) => Promise<void>} showMessage - Show message dialog
* @property {(message: string, type?: string) => Promise<boolean>} showConfirm - Show confirmation dialog
*/
/**
* @typedef {Object} SystemAdapter
* @property {() => Promise<SystemInfo>} getSystemInfo - Get system information
* @property {(title: string, body: string) => Promise<void>} showNotification - Show system notification
* @property {(url: string) => Promise<void>} openExternal - Open URL in default browser
* @property {(path: string) => Promise<void>} openInExplorer - Open path in file explorer
* @property {(path: string) => Promise<void>} openInDefaultApp - Open path in default application
*/
/**
* @typedef {Object} PdfAdapter
* @property {(path: string) => Promise<Object>} loadDocument - Load PDF document
* @property {(doc: Object, pageNum: number, canvas: HTMLCanvasElement, scale: number, rotation: number) => Promise<void>} renderPage - Render PDF page to canvas
* @property {(operations: Object) => Promise<void>} processOperation - Process PDF operation (merge, split, etc.)
*/
/**
* @typedef {Object} PlatformAdapter
* @property {string} name - Platform name ('electron', 'web', 'tauri', 'flutter')
* @property {FileSystemAdapter} fs - File system operations
* @property {ConversionAdapter} convert - Conversion operations
* @property {DialogAdapter} dialog - Dialog operations
* @property {SystemAdapter} system - System operations
* @property {PdfAdapter} [pdf] - PDF operations (optional, not available on all platforms)
* @property {PlatformCapabilities} capabilities - Platform capabilities
*/
module.exports = {
// Type definitions are JSDoc only, no runtime exports needed
};
+122
View File
@@ -0,0 +1,122 @@
/**
* Writing Analytics Panel — modal overlay displaying analytics dashboard
*/
const { analyze } = require('./writing-analytics');
function showAnalyticsModal(tabManager) {
const existing = document.getElementById('analytics-modal');
if (existing) existing.remove();
const content = tabManager.getEditorContent();
const metrics = analyze(content);
const overlay = document.createElement('div');
overlay.id = 'analytics-modal';
overlay.className = 'analytics-overlay';
const maxCount = metrics.topWords.length > 0 ? metrics.topWords[0].count : 1;
overlay.innerHTML = `
<div class="analytics-modal">
<div class="analytics-header">
<h2>Writing Analytics</h2>
<button class="analytics-close" title="Close">&times;</button>
</div>
<div class="analytics-body">
<div class="analytics-section">
<h3>Readability</h3>
<div class="analytics-row">
<span class="analytics-label">Flesch Reading Ease</span>
<span class="analytics-value">${metrics.fleschEase}<small>${metrics.readabilityLabel}</small></span>
</div>
<div class="analytics-row">
<span class="analytics-label">Grade Level</span>
<span class="analytics-value">${metrics.fleschGrade}</span>
</div>
<div class="readability-meter">
<div class="readability-fill" style="width: ${Math.max(0, Math.min(100, metrics.fleschEase))}%"></div>
</div>
</div>
<div class="analytics-section">
<h3>Timing</h3>
<div class="analytics-row">
<span class="analytics-label">Reading Time</span>
<span class="analytics-value">~${metrics.readingTime} min</span>
</div>
<div class="analytics-row">
<span class="analytics-label">Speaking Time</span>
<span class="analytics-value">~${metrics.speakingTime} min</span>
</div>
</div>
<div class="analytics-section">
<h3>Structure</h3>
<div class="analytics-row">
<span class="analytics-label">Sentences</span>
<span class="analytics-value">${metrics.sentenceCount} &bull; Paragraphs: ${metrics.paragraphCount}</span>
</div>
<div class="analytics-row">
<span class="analytics-label">Avg Sentence</span>
<span class="analytics-value">${metrics.avgSentenceLength} words</span>
</div>
${
metrics.longestSentenceLength > 0
? `
<div class="analytics-row analytics-longest">
<span class="analytics-label">Longest (${metrics.longestSentenceLength} words)</span>
<span class="analytics-value analytics-sentence-preview">${escapeHtml(metrics.longestSentence)}</span>
</div>`
: ''
}
</div>
<div class="analytics-section">
<h3>Vocabulary</h3>
<div class="analytics-row">
<span class="analytics-label">Unique</span>
<span class="analytics-value">${metrics.uniqueWordCount} / ${metrics.wordCount}<small>${metrics.lexicalDiversity}%</small></span>
</div>
${
metrics.topWords.length > 0
? `
<div class="word-cloud">
${metrics.topWords
.map((w) => {
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>`;
})
.join('')}
</div>`
: ''
}
</div>
</div>
</div>
`;
const closeBtn = overlay.querySelector('.analytics-close');
closeBtn.addEventListener('click', () => overlay.remove());
overlay.addEventListener('click', (e) => {
if (e.target === overlay) overlay.remove();
});
const escHandler = (e) => {
if (e.key === 'Escape') {
overlay.remove();
document.removeEventListener('keydown', escHandler);
}
};
document.addEventListener('keydown', escHandler);
document.body.appendChild(overlay);
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
module.exports = { showAnalyticsModal };
+200
View File
@@ -0,0 +1,200 @@
/**
* Writing Analytics — pure computation engine
* No DOM dependencies. Exported analyze(text) returns a metrics object.
*/
const STOP_WORDS = new Set([
'the',
'a',
'an',
'is',
'are',
'was',
'were',
'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) {
word = word.toLowerCase().replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
word = word.replace(/^y/, '');
return word.match(/[aeiouy]{1,2}/gi)?.length || 1;
}
function extractWords(text) {
return text.match(/[a-zA-Z]+(?:['-][a-zA-Z]+)*/g) || [];
}
function getReadabilityLabel(score) {
if (score >= 90) return 'Very Easy';
if (score >= 70) return 'Easy';
if (score >= 50) return 'Standard';
if (score >= 30) return 'Difficult';
return 'Very Difficult';
}
function analyze(text) {
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 {
wordCount,
sentenceCount,
paragraphCount,
fleschEase,
fleschGrade,
readabilityLabel,
readingTime,
speakingTime,
uniqueWordCount,
lexicalDiversity,
avgSentenceLength,
longestSentence,
longestSentenceLength,
topWords,
};
}
module.exports = { analyze };
+286 -136
View File
@@ -1,10 +1,10 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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">
<link rel="stylesheet" href="../fonts.css" />
<style>
:root {
--ci-dark-gray: #464646;
@@ -103,7 +103,9 @@
color: var(--ci-dark-gray);
}
.form-input, .form-select, .form-textarea {
.form-input,
.form-select,
.form-textarea {
width: 100%;
padding: 10px 14px;
border: 2px solid var(--ci-light-gray);
@@ -113,7 +115,9 @@
transition: border-color 0.2s;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
.form-input:focus,
.form-select:focus,
.form-textarea:focus {
outline: none;
border-color: var(--ci-accent);
}
@@ -133,11 +137,15 @@
}
.preview-content {
font-family: 'JetBrains Mono', monospace;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 12px;
line-height: 1.3;
color: #00ff00;
white-space: pre;
font-feature-settings:
'liga' 0,
'calt' 0,
'dlig' 0;
}
.template-grid {
@@ -245,7 +253,13 @@
<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">
<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>
@@ -263,7 +277,11 @@
<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>
<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>
@@ -277,7 +295,15 @@
</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;">
<input
type="number"
id="box-padding"
class="form-input"
min="0"
max="10"
value="2"
style="width: 100px"
/>
</div>
</div>
@@ -341,138 +367,262 @@
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': ['-----', ' / ', ' / ', ' / ', '-----'],
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': ['/---\\', '| |', '\\----', ' |', '----/']
}
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': ['########', ' ## ', ' ## ', ' ## ', ' ## ', ' ## ', '########'],
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': [' ###### ', '## ##', '## ##', ' #######', ' ##', '## ##', ' ###### ']
}
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': ['███████╗', '╚════██║', ' ███╔═╝', ' ██╔══╝ ', '███████╗', '╚══════╝'],
' ': [' ', ' ', ' ', ' ', ' ', ' ']
}
}
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'
'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 = {
@@ -480,20 +630,20 @@
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: '|' }
ascii: { tl: '+', tr: '+', bl: '+', br: '+', h: '-', v: '|' },
};
let currentMode = 'text';
let currentTemplate = null;
// Mode switching
document.querySelectorAll('.mode-tab').forEach(tab => {
document.querySelectorAll('.mode-tab').forEach((tab) => {
tab.addEventListener('click', () => {
document.querySelectorAll('.mode-tab').forEach(t => t.classList.remove('active'));
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.querySelectorAll('.mode-section').forEach((s) => s.classList.remove('active'));
document.getElementById(currentMode + '-mode').classList.add('active');
generatePreview();
@@ -501,9 +651,9 @@
});
// Template selection
document.querySelectorAll('.template-btn').forEach(btn => {
document.querySelectorAll('.template-btn').forEach((btn) => {
btn.addEventListener('click', () => {
document.querySelectorAll('.template-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.template-btn').forEach((b) => b.classList.remove('active'));
btn.classList.add('active');
currentTemplate = btn.dataset.template;
generatePreview();
@@ -531,7 +681,7 @@
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;
const maxLen = Math.max(...lines.map((l) => l.length)) + padding * 2;
let result = box.tl + box.h.repeat(maxLen + 2) + box.tr + '\n';
+113
View File
@@ -0,0 +1,113 @@
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 };
+149
View File
@@ -0,0 +1,149 @@
// CodeMirror 6 wrapper module
// Provides createEditor() and getLanguageExtension() for the rest of the app.
const {
EditorView,
keymap,
lineNumbers,
highlightActiveLine,
drawSelection,
} = require('@codemirror/view');
const { EditorState } = require('@codemirror/state');
const { markdown, markdownLanguage } = require('@codemirror/lang-markdown');
// Language extensions loaded lazily on first use
let _javascript, _html, _css, _json, _python;
const { defaultKeymap, history, historyKeymap, indentWithTab } = require('@codemirror/commands');
const { searchKeymap, highlightSelectionMatches } = require('@codemirror/search');
const { autocompletion, completionKeymap } = require('@codemirror/autocomplete');
const { bracketMatching, foldGutter, indentOnInput } = require('@codemirror/language');
const { oneDark } = require('@codemirror/theme-one-dark');
// Custom theme for JetBrains Mono font
const jetBrainsMonoTheme = EditorView.theme({
'&': {
fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, 'Courier New', monospace",
},
'.cm-content': {
fontFamily: 'inherit',
},
'.cm-scroller': {
fontFamily: 'inherit',
},
});
/**
* Create a CodeMirror 6 editor instance.
*
* @param {HTMLElement} parentElement - DOM element to mount the editor in
* @param {Object} options
* @param {string} options.content - initial document content (default '')
* @param {Function} options.onChange - called with new content string on every doc change
* @param {Function} options.onUpdate - called with the EditorView on every update (selection, doc change, etc.)
* @param {boolean} options.isDark - apply oneDark theme when true (default false)
* @param {boolean} options.showLineNumbers - show line-number gutter (default true)
* @returns {EditorView} the created editor view
*/
function createEditor(parentElement, options = {}) {
console.log(
'[createEditor] Called with parentElement:',
parentElement?.id,
'dimensions:',
parentElement?.clientWidth,
'x',
parentElement?.clientHeight
);
if (!parentElement) {
console.error('[createEditor] ERROR: parentElement is null or undefined!');
return null;
}
const {
content = '',
onChange = () => {},
onUpdate = null,
isDark = false,
showLineNumbers = true,
} = options;
const extensions = [
markdown({ base: markdownLanguage }),
history(),
drawSelection(),
highlightActiveLine(),
bracketMatching(),
indentOnInput(),
highlightSelectionMatches(),
autocompletion(),
foldGutter(),
jetBrainsMonoTheme,
keymap.of([
...defaultKeymap,
...historyKeymap,
...searchKeymap,
...completionKeymap,
indentWithTab,
]),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChange(update.state.doc.toString());
}
if (onUpdate && (update.docChanged || update.selectionSet)) {
onUpdate(update.view);
}
}),
EditorView.lineWrapping,
];
if (showLineNumbers) {
extensions.push(lineNumbers());
}
if (isDark) {
extensions.push(oneDark);
}
const state = EditorState.create({ doc: content, extensions });
const view = new EditorView({ state, parent: parentElement });
return view;
}
/**
* Return the appropriate CodeMirror language extension for a given language name.
*
* Supported values: javascript, js, html, css, json, python, py, markdown.
* Falls back to markdown when the language is unrecognised.
*
* @param {string} lang - language identifier
* @returns {Extension} CodeMirror language extension
*/
function getLanguageExtension(lang) {
const loaders = {
javascript: () => {
if (!_javascript) _javascript = require('@codemirror/lang-javascript').javascript;
return _javascript();
},
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 }),
};
loaders.js = loaders.javascript;
loaders.py = loaders.python;
const loader = loaders[lang];
return loader ? loader() : markdown({ base: markdownLanguage });
}
module.exports = { createEditor, getLanguageExtension };
+17
View File
@@ -73,3 +73,20 @@
font-display: swap;
src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2');
}
/* Fira Code Font Family - bundled with the app */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('../assets/fonts/FiraCode-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('../assets/fonts/FiraCode-Bold.ttf') format('truetype');
}
+1710 -330
View File
File diff suppressed because it is too large Load Diff
+3019 -1382
View File
File diff suppressed because it is too large Load Diff
+171
View File
@@ -0,0 +1,171 @@
/**
* Audio Operations Module
*
* Handles audio manipulation via `ffmpeg`: format conversion, trim, extract (audio
* track from video/audio), and merge (concat demuxer). Because ffmpeg is an external
* binary, this module is split into pure/testable argument-builder functions and a
* single `executeOperation` that is the only piece which actually spawns ffmpeg —
* the ffmpeg binary path and the `execFile` implementation are both injected so tests
* can replace them with fakes, without invoking a real binary.
*
* @module AudioOperations
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const { execFile } = require('child_process');
/**
* Build args for a straight format conversion. ffmpeg infers the output format from
* outputPath's extension; only pass -f explicitly when format is given and differs
* from that extension.
*/
function buildConvertArgs({ inputPath, outputPath, format }) {
const args = ['-i', inputPath, '-y'];
if (format) {
const ext = path.extname(outputPath).replace(/^\./, '').toLowerCase();
if (format.toLowerCase() !== ext) {
args.push('-f', format);
}
}
args.push(outputPath);
return args;
}
/**
* Build args to trim inputPath to [startTime, startTime + duration) seconds.
* startTime/duration must be finite, non-negative numbers — they become argv
* elements passed straight to execFile with no shell involved, so there's no
* injection risk, but malformed values should still fail fast rather than reach
* ffmpeg with garbage.
*/
function buildTrimArgs({ inputPath, outputPath, startTime, duration }) {
const isValid = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
if (!isValid(startTime) || !isValid(duration)) {
throw new Error('Invalid trim range');
}
return ['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath];
}
/**
* Build args to extract the audio track (stream copy, no video, no re-encode).
* If codec copy fails, executeOperation's 'extract' case retries without -acodec copy.
*/
function buildExtractArgs({ inputPath, outputPath }) {
return ['-i', inputPath, '-vn', '-acodec', 'copy', '-y', outputPath];
}
/**
* Fallback extract args that let ffmpeg transcode instead of stream-copying.
*/
function buildExtractFallbackArgs({ inputPath, outputPath }) {
return ['-i', inputPath, '-vn', '-y', outputPath];
}
/**
* Build args to merge 2+ files via the concat demuxer. Returns both concatListContent
* (the `file '<path>'` lines the caller writes to a temp list file) and args — the
* caller doesn't know the temp list file's path until it creates it, so tempListPath
* is an optional param: executeOperation's 'merge' case calls this once to obtain
* concatListContent, writes it to disk, then calls it again with the real
* tempListPath to obtain the final args referencing that file.
*/
function buildMergeArgs({ inputPaths, outputPath, tempListPath = null }) {
if (!Array.isArray(inputPaths) || inputPaths.length < 2) {
throw new Error('inputPaths must contain at least 2 files');
}
const concatListContent = inputPaths.map((p) => `file '${p}'`).join('\n') + '\n';
const args = ['-f', 'concat', '-safe', '0', '-i', tempListPath, '-c', 'copy', '-y', outputPath];
return { args, concatListContent };
}
/**
* Run ffmpeg with the given args via the injected execFileFn, wrapped in a Promise.
*/
function runFfmpeg(ffmpegPath, args, execFileFn) {
return new Promise((resolve, reject) => {
execFileFn(ffmpegPath, args, { maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr || error.message));
return;
}
resolve();
});
});
}
async function executeOperation(operation, data, { ffmpegPath, execFileFn } = {}) {
const resolvedFfmpegPath = ffmpegPath || 'ffmpeg';
const resolvedExecFileFn = execFileFn || execFile;
switch (operation) {
case 'convert': {
const { inputPath, outputPath, format } = data || {};
const args = buildConvertArgs({ inputPath, outputPath, format });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
case 'trim': {
const { inputPath, outputPath, startTime, duration } = data || {};
const args = buildTrimArgs({ inputPath, outputPath, startTime, duration });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
case 'extract': {
const { inputPath, outputPath } = data || {};
try {
const args = buildExtractArgs({ inputPath, outputPath });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
} catch {
// Codec copy can fail when the source audio codec isn't valid in the target
// container — fall back to letting ffmpeg transcode instead.
const fallbackArgs = buildExtractFallbackArgs({ inputPath, outputPath });
await runFfmpeg(resolvedFfmpegPath, fallbackArgs, resolvedExecFileFn);
}
return { success: true, outputPath };
}
case 'merge': {
const { inputPaths, outputPath } = data || {};
const { concatListContent } = buildMergeArgs({ inputPaths, outputPath });
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'audio-merge-'));
const tempListPath = path.join(tempDir, 'concat-list.txt');
try {
fs.writeFileSync(tempListPath, concatListContent, 'utf8');
const { args } = buildMergeArgs({ inputPaths, outputPath, tempListPath });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
} finally {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch {
/* best-effort cleanup */
}
}
return { success: true, outputPath };
}
default:
throw new Error(`Unknown operation: ${operation}`);
}
}
module.exports = {
executeOperation,
buildConvertArgs,
buildTrimArgs,
buildExtractArgs,
buildMergeArgs,
};
+126
View File
@@ -0,0 +1,126 @@
'use strict';
const fs = require('fs');
const path = require('path');
const JSZip = require('jszip');
const REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
function generatedRId(idx) {
return `rIdFont${idx}`;
}
async function patchZipWithFonts(inputPath, fonts) {
const buf = fs.readFileSync(inputPath);
const zip = await JSZip.loadAsync(buf);
const existingFontNames = new Set();
// Detect prior embeds (idempotency: skip TTF files already present).
for (const f of Object.keys(zip.files)) {
if (zip.files[f].name && /^word\/fonts\//.test(zip.files[f].name)) {
existingFontNames.add(path.basename(f));
}
}
for (let i = 0; i < fonts.length; i++) {
const { path: fontPath } = fonts[i];
const fname = path.basename(fontPath);
const wordPath = `word/fonts/${fname}`;
if (!existingFontNames.has(fname)) {
zip.file(wordPath, fs.readFileSync(fontPath));
existingFontNames.add(fname);
}
}
// Build/replace word/fontTable.xml so Word knows the family and where to
// fetch the embedded TTF data.
const fontTableXml =
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
`<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/main">\n` +
fonts
.map(
(f, i) =>
` <w:font w:name="${f.family}"><w:embedRegular r:id="${generatedRId(i)}" xmlns:r="${REL_NS}"/></w:font>`
)
.join('\n') +
`\n</w:fonts>\n`;
zip.file('word/fontTable.xml', fontTableXml);
// Patch [Content_Types].xml — add Override for /word/fontTable.xml and each TTF.
const ctPath = '[Content_Types].xml';
let ct = await zip.file(ctPath).async('string');
if (!ct.includes('PartName="/word/fontTable.xml"')) {
ct = ct.replace(
'</Types>',
'<Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>'
);
}
for (const f of fonts) {
const ttfCt = 'application/x-font-ttf';
const filePart = `/word/fonts/${path.basename(f.path)}`;
if (!ct.includes(`PartName="${filePart}"`)) {
ct = ct.replace(
'</Types>',
`<Override PartName="${filePart}" ContentType="${ttfCt}"/></Types>`
);
}
}
if (!ct.includes('Default Extension="ttf"')) {
ct = ct.replace(
'</Types>',
'<Default Extension="ttf" ContentType="application/x-font-ttf"/></Types>'
);
}
zip.file(ctPath, ct);
// Patch word/_rels/document.xml.rels — relationships for fontTable + each font.
const relsPath = 'word/_rels/document.xml.rels';
if (!zip.files[relsPath]) {
zip.file(
relsPath,
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="${REL_NS}"/>`
);
}
let rels = await zip.file(relsPath).async('string');
if (!rels.includes('fontTable.xml')) {
rels = rels.replace(
'</Relationships>',
`<Relationship Id="${generatedRId(fonts.length)}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>`
);
}
for (let i = 0; i < fonts.length; i++) {
const fname = path.basename(fonts[i].path);
if (!rels.includes(fname)) {
rels = rels.replace(
'</Relationships>',
`<Relationship Id="${generatedRId(i)}" Type="http://schemas.microsoft.com/office/2011/relationships/font" Target="fonts/${fname}"/></Relationships>`
);
}
}
zip.file(relsPath, rels);
// Patch word/styles.xml — bind SourceCode/VerbatimChar styles to the family.
const stylesPath = 'word/styles.xml';
if (zip.files[stylesPath]) {
let styles = await zip.file(stylesPath).async('string');
const family = fonts[0].family;
if (!styles.includes(`w:ascii="${family}"`)) {
styles = styles.replace(
/(<w:style[^>]*w:styleId="(?:SourceCode|VerbatimChar)"[^>]*>)/,
`$1<w:rPr><w:rFonts w:ascii="${family}" w:hAnsi="${family}" w:cs="${family}"/></w:rPr>`
);
}
zip.file(stylesPath, styles);
}
const outBuf = await zip.generateAsync({ type: 'nodebuffer' });
fs.writeFileSync(inputPath, outBuf);
return inputPath;
}
async function embed(docxPath, fonts) {
return patchZipWithFonts(docxPath, fonts);
}
module.exports = { embed };
+44
View File
@@ -0,0 +1,44 @@
'use strict';
const fs = require('fs');
const path = require('path');
const JSZip = require('jszip');
// Patches an EPUB produced by pandoc so it embeds the supplied TTF font files
// inside the OEBPS and registers them in the OPF manifest. Used after
// `pandoc --epub-embed-font=...` runs (which embeds the font data) but does
// not always add the manifest item we need for readers to discover the font.
//
// Writes a new file at `${epubPath}.patched.epub` and returns the patched path.
// Caller should overwrite the original after a successful export.
async function patchManifest(epubPath, fonts) {
const zip = await JSZip.loadAsync(fs.readFileSync(epubPath));
const opfPath = Object.keys(zip.files).find((f) => f.endsWith('content.opf'));
if (!opfPath) throw new Error('EPUB has no content.opf');
let opf = await zip.file(opfPath).async('string');
for (const { path: fontPath, family, weight } of fonts) {
const filename = path.basename(fontPath);
const inFontDir = `OEBPS/fonts/${filename}`;
zip.file(inFontDir, fs.readFileSync(fontPath));
if (!opf.includes(filename)) {
const safeFamily = String(family || 'Font').replace(/\s+/g, '-');
const item = `<item id="font-${safeFamily}-${weight}" href="${inFontDir}" media-type="application/x-font-ttf"/>`;
if (opf.includes('</manifest>')) {
opf = opf.replace('</manifest>', `${item}</manifest>`);
} else {
// OPF without a manifest element (unusual but tolerated): inject one
// just before </package> so the font item is still discoverable.
opf = opf.replace('</package>', `<manifest>${item}</manifest></package>`);
}
}
}
zip.file(opfPath, opf);
const buf = await zip.generateAsync({ type: 'nodebuffer' });
const tmp = `${epubPath}.patched.epub`;
fs.writeFileSync(tmp, buf);
return tmp;
}
module.exports = { patchManifest };
+34
View File
@@ -0,0 +1,34 @@
'use strict';
const fs = require('fs');
function toDataUri(filePath) {
const buf = fs.readFileSync(filePath);
return `data:font/woff2;base64,${buf.toString('base64')}`;
}
function build({ activeFontPath, family, weight = 400, ligatures = false }) {
const features = ligatures ? 'normal' : "'liga' 0, 'calt' 0, 'dlig' 0";
const faceBlock = activeFontPath
? `@font-face {
font-family: '${family}';
font-weight: ${weight};
font-style: normal;
font-display: swap;
src: url('${toDataUri(activeFontPath)}') format('woff2');
}
`
: '';
return `${faceBlock}code, pre, kbd, samp {
font-family: '${family}', monospace;
font-feature-settings: ${features};
}
pre, code {
white-space: pre;
tab-size: 4;
}
`;
}
module.exports = { build };
+92
View File
@@ -0,0 +1,92 @@
'use strict';
/**
* Export preset persistence (Task 21 — export presets/profiles).
*
* Pure list operations over the `exportPresets` array kept in the app's
* settings.json store (the `store.get`/`store.set` helpers defined in
* src/main.js — the same store that holds headerFooterSettings and
* pageSettings). The store is injected so the logic is unit-testable with a
* fake store (see tests/main/ExportPresets.test.js); src/main.js wires these
* functions to the get-export-presets / save-export-preset /
* delete-export-preset invoke channels.
*
* Preset shape: { id: string, name: string, format: string|null, options: object }
* — `options` is the export-options snapshot captured from the renderer's
* export dialog, so selecting a preset can pre-fill that dialog exactly.
*/
const PRESET_KEY = 'exportPresets';
const MAX_PRESETS = 50;
const MAX_NAME_LENGTH = 100;
/**
* Read the stored presets, defensively skipping corrupt data.
* @param {{get: Function, set: Function}} store settings store
* @returns {Array<{id: string, name: string, format: string|null, options: Object}>}
*/
function loadPresets(store) {
const stored = store.get(PRESET_KEY, []);
if (!Array.isArray(stored)) return [];
return stored.filter(
(preset) =>
preset &&
typeof preset === 'object' &&
typeof preset.id === 'string' &&
typeof preset.name === 'string'
);
}
/**
* Validate, normalize, and upsert a preset by id. A missing id gets a newly
* generated one (insert); an id that already exists is replaced (update).
* @param {{get: Function, set: Function}} store settings store
* @param {{id?: string, name?: string, format?: string, options?: Object}} preset
* @returns {Array} the updated preset list (also persisted)
* @throws when the preset is not an object, the name is empty, or the cap is hit
*/
function savePreset(store, preset) {
if (!preset || typeof preset !== 'object') {
throw new Error('Preset must be an object');
}
const name = typeof preset.name === 'string' ? preset.name.trim().slice(0, MAX_NAME_LENGTH) : '';
if (!name) {
throw new Error('Preset name is required');
}
const options = preset.options && typeof preset.options === 'object' ? preset.options : {};
const format = typeof preset.format === 'string' ? preset.format : null;
const presets = loadPresets(store);
const id = typeof preset.id === 'string' && preset.id ? preset.id : createPresetId();
const entry = { id, name, format, options };
const index = presets.findIndex((existing) => existing.id === id);
if (index >= 0) {
presets[index] = entry;
} else {
if (presets.length >= MAX_PRESETS) {
throw new Error(`Cannot store more than ${MAX_PRESETS} export presets`);
}
presets.push(entry);
}
store.set(PRESET_KEY, presets);
return presets;
}
/**
* Remove the preset with the given id (idempotent).
* @param {{get: Function, set: Function}} store settings store
* @param {string} presetId
* @returns {Array} the updated preset list (also persisted)
*/
function deletePreset(store, presetId) {
const presets = loadPresets(store).filter((preset) => preset.id !== presetId);
store.set(PRESET_KEY, presets);
return presets;
}
function createPresetId() {
return `preset-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
module.exports = { loadPresets, savePreset, deletePreset, PRESET_KEY, MAX_PRESETS };
+95
View File
@@ -0,0 +1,95 @@
const simpleGit = require('simple-git');
function getGitInstance(dir) {
return simpleGit(dir);
}
async function getStatus(dir) {
try {
const git = getGitInstance(dir);
return await git.status();
} catch {
return { error: 'Not a git repository' };
}
}
async function stage(dir, files) {
try {
const git = getGitInstance(dir);
await git.add(files);
return await git.status();
} catch (err) {
return { error: err.message };
}
}
async function commit(dir, message) {
try {
const git = getGitInstance(dir);
return await git.commit(message);
} catch (err) {
return { error: err.message };
}
}
async function log(dir, maxCount = 20) {
try {
const git = getGitInstance(dir);
return await git.log({ maxCount });
} catch (err) {
return { error: err.message };
}
}
// againstHead=true compares the working tree (staged + unstaged) against the last
// commit instead of against the index — used by the Document Compare dialog's
// "Git HEAD" mode. Default behavior (worktree vs index) is unchanged.
async function diff(dir, file, againstHead = false) {
try {
const git = getGitInstance(dir);
if (againstHead) {
return file ? await git.diff(['HEAD', '--', file]) : await git.diff('HEAD');
}
return file ? await git.diff([file]) : await git.diff();
} catch (err) {
return { error: err.message };
}
}
async function branches(dir) {
try {
const git = getGitInstance(dir);
return await git.branchLocal();
} catch (err) {
return { error: err.message };
}
}
async function checkoutBranch(dir, name, isNew) {
try {
const git = getGitInstance(dir);
return isNew ? await git.checkoutLocalBranch(name) : await git.checkout(name);
} catch (err) {
return { error: err.message };
}
}
async function push(dir) {
try {
const git = getGitInstance(dir);
return await git.push();
} catch (err) {
return { error: err.message };
}
}
async function pull(dir) {
try {
const git = getGitInstance(dir);
return await git.pull();
} catch (err) {
return { error: err.message };
}
}
module.exports = { getStatus, stage, commit, log, diff, branches, checkoutBranch, push, pull };
+198
View File
@@ -0,0 +1,198 @@
/**
* Image Operations Module
*
* Handles image manipulation via `sharp`: format conversion, resize, compress, rotate.
* Mirrors the executeOperation(operation, data) dispatcher pattern used by PDFOperations.js.
*
* sharp loads LAZILY: its native bindings (@img/sharp-*) are optionalDependencies
* that a packaged build can prune or fail to unpack, and a top-level require would
* then crash the whole app at boot (src/main.js requires this module unconditionally).
* When sharp cannot load, operations degrade honestly instead of killing the app —
* the same honest-failure precedent PDFOperations set for missing pdf-lib features.
*
* @module ImageOperations
*/
const fs = require('fs');
const path = require('path');
let sharpModule = null;
let sharpLoadError = null;
function loadSharp() {
if (sharpModule) return sharpModule;
if (sharpLoadError) throw sharpLoadError;
try {
sharpModule = require('sharp');
return sharpModule;
} catch (error) {
sharpLoadError = error;
throw error;
}
}
// Strip absolute paths from error text before it reaches callers, mirroring
// sanitizeErrorMessage() in main.js (that helper is not importable from here).
function sanitizeMessage(message) {
if (typeof message !== 'string') return String(message);
return message
.replace(/[A-Z]:\\[^\s"']+\\([^\s"'\\]+)/gi, '$1')
.replace(/\/[^\s"']+\/([^\s"'/]+)/g, '$1');
}
// Must match the MAX_FILE_SIZE convention defined in main.js (50MB). main.js is the
// single source of truth for this limit; this module does not redefine it independently
// — callers (main.js) pass it in via data.maxFileSize when they want it enforced, and we
// fall back to the same 50MB default so direct/unit-test callers are still protected.
const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024;
const RASTER_FORMATS = ['jpeg', 'png', 'webp', 'avif', 'tiff', 'gif'];
const RESIZE_FIT_MODES = ['cover', 'contain', 'fill', 'inside', 'outside'];
function validateInput(data) {
const { inputPath, outputPath, maxFileSize } = data || {};
if (!inputPath || !outputPath) {
throw new Error('inputPath and outputPath are required');
}
if (!fs.existsSync(inputPath)) {
throw new Error(`Input file not found: ${path.basename(inputPath)}`);
}
const limit = typeof maxFileSize === 'number' ? maxFileSize : DEFAULT_MAX_FILE_SIZE;
const stats = fs.statSync(inputPath);
if (stats.size > limit) {
throw new Error(`File exceeds the ${Math.floor(limit / (1024 * 1024))}MB size limit.`);
}
}
async function imageConvert(data) {
try {
const sharp = loadSharp();
validateInput(data);
const { inputPath, outputPath, format } = data;
if (!RASTER_FORMATS.includes(format)) {
throw new Error(`Unsupported output format: ${format}`);
}
await sharp(inputPath).toFormat(format).toFile(outputPath);
return { success: true, outputPath };
} catch (error) {
throw new Error(`Image conversion failed: ${error.message}`);
}
}
async function imageResize(data) {
try {
const sharp = loadSharp();
validateInput(data);
const { inputPath, outputPath, width = null, height = null, fit = 'inside' } = data;
if (width === null && height === null) {
throw new Error('At least one of width or height must be provided');
}
if (!RESIZE_FIT_MODES.includes(fit)) {
throw new Error(`Unsupported fit mode: ${fit}`);
}
await sharp(inputPath).resize({ width, height, fit }).toFile(outputPath);
return { success: true, outputPath };
} catch (error) {
throw new Error(`Image resize failed: ${error.message}`);
}
}
async function imageCompress(data) {
try {
const sharp = loadSharp();
validateInput(data);
const { inputPath, outputPath, quality = 80 } = data;
if (!Number.isInteger(quality) || quality < 1 || quality > 100) {
throw new Error('quality must be an integer between 1 and 100');
}
const ext = path.extname(outputPath).toLowerCase().replace('.', '');
let pipeline = sharp(inputPath);
switch (ext) {
case 'jpg':
case 'jpeg':
pipeline = pipeline.jpeg({ quality });
break;
case 'webp':
pipeline = pipeline.webp({ quality });
break;
case 'avif':
pipeline = pipeline.avif({ quality });
break;
case 'png':
pipeline = pipeline.png({ quality, compressionLevel: 9 });
break;
default:
throw new Error(`Unsupported compression output format: ${ext}`);
}
await pipeline.toFile(outputPath);
return { success: true, outputPath };
} catch (error) {
throw new Error(`Image compression failed: ${error.message}`);
}
}
async function imageRotate(data) {
try {
const sharp = loadSharp();
validateInput(data);
const { inputPath, outputPath, angle } = data;
if (typeof angle !== 'number' || !Number.isFinite(angle)) {
throw new Error('angle must be a number');
}
await sharp(inputPath).rotate(angle).toFile(outputPath);
return { success: true, outputPath };
} catch (error) {
throw new Error(`Image rotation failed: ${error.message}`);
}
}
function executeOperation(operation, data) {
try {
loadSharp();
} catch (error) {
// Honest degradation: the app keeps booting and every image op reports the
// unavailable state as a resolved result instead of throwing at import time.
return Promise.resolve({
success: false,
error: `Image operations unavailable: ${sanitizeMessage(error.message)}`,
});
}
switch (operation) {
case 'convert':
return imageConvert(data);
case 'resize':
return imageResize(data);
case 'compress':
return imageCompress(data);
case 'rotate':
return imageRotate(data);
default:
return Promise.reject(new Error(`Unknown operation: ${operation}`));
}
}
module.exports = {
executeOperation,
imageConvert,
imageResize,
imageCompress,
imageRotate,
};
+56
View File
@@ -0,0 +1,56 @@
'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 };
+177
View File
@@ -0,0 +1,177 @@
/**
* PDFBatchOperations
*
* Applies one PDFOperations.executeOperation() operation (watermark, compress,
* rotate, split, ...) to every .pdf file in an input folder — the PDF sibling of
* runMediaBatchOperation() in main.js (Task 12's image/audio/video batch mode):
* collect matching files via collectFilesByExtension (which generalizes the
* inline collectFiles() of the 'universal-convert-batch' handler), loop the
* operation over them, and report per-file progress plus a final
* completed/failed summary.
*
* Pulled out as its own Electron-free module (same precedent as
* collectFilesByExtension) so the batch loop is unit-testable against real
* pdf-lib fixtures; main.js injects the IPC-facing callbacks:
* onProgress -> mainWindow.webContents.send('batch-progress', ...)
* onComplete -> mainWindow.webContents.send('pdf-batch-complete', ...) + dialog
*
* Not every executeOperation op fits the "apply the same operation to every
* file" batch model. Excluded (enforced by absence from PDF_BATCH_OUTPUT_SPEC,
* which doubles as the defensive backstop for renderer-supplied op names):
* - merge / reorder / fillForm — consume per-file knowledge the batch flow
* cannot supply (merge takes many inputs in one op; reorder needs each
* file's full page order; fillForm's field values differ per file).
* - formFields — a read-only query returning data, not a transform.
* - encrypt / decrypt / permissions — pdf-lib 1.17.1 (bundled) lacks
* encryption support, so since Task 27 these ops fail honestly with an
* "unavailable" result instead of silently writing unprotected files;
* a batch run would deterministically fail every file.
*
* @module PDFBatchOperations
*/
const fs = require('fs');
const path = require('path');
const PDFOperations = require('./PDFOperations');
const { collectFilesByExtension } = require('./collectFilesByExtension');
// How to derive each output file's path (or directory) from the source file,
// mirroring BATCH_OUTPUT_SPEC in main.js:
// { ext: 'original' } -> <outputFolder>/<relativeDir>/<baseName>.pdf via outputPath
// { ext: 'txt' } -> <outputFolder>/<relativeDir>/<baseName>.txt via outputPath
// { folder: true } -> split writes its `<baseName>_part_N.pdf` files into
// the mirrored output folder via outputFolder
// { dir: true } -> extractImages writes images into a per-PDF
// <outputFolder>/<relativeDir>/<baseName>/ via outputDir
const PDF_BATCH_OUTPUT_SPEC = {
split: { folder: true },
compress: { ext: 'original' },
rotate: { ext: 'original' },
delete: { ext: 'original' },
watermark: { ext: 'original' },
extractText: { ext: 'txt' },
pageNumbers: { ext: 'original' },
crop: { ext: 'original' },
extractImages: { dir: true },
};
/**
* Runs a single PDFOperations operation over every .pdf under `inputFolder`.
*
* @param {object} args
* @param {string} args.operation - executeOperation op name (must be batchable).
* @param {string} args.inputFolder - Folder to scan for .pdf files.
* @param {string} args.outputFolder - Destination folder (created if missing);
* the input folder's relative structure is mirrored beneath it.
* @param {boolean} [args.includeSubfolders=true] - Recurse into subdirectories.
* @param {object} [args.data={}] - Shared operation options forwarded to
* executeOperation for every file (same option shapes as the single-file PDF
* editor dialog; inputPath/outputPath are added per file here).
* @param {number} [args.maxFileSize] - Skip (count as failed) files larger than
* this many bytes, mirroring the batch-convert handler's file-size guard.
* @param {Function} [args.onProgress] - Called with { completed, failed, total,
* currentFile } before each file and once (currentFile: null) at the end —
* the existing 'batch-progress' payload shape.
* @param {Function} args.onComplete - Called exactly once with the outcome:
* { success: false, error } for early failures, otherwise
* { success: true, completed, failed, total, outputFolder }.
* @param {Function} [args.sanitizeError] - Sanitizer for error messages that
* could leak absolute paths (main.js passes sanitizeErrorMessage).
* @returns {Promise<void>}
*/
async function runPDFBatchOperation({
operation,
inputFolder,
outputFolder,
includeSubfolders,
data = {},
maxFileSize,
onProgress = () => {},
onComplete,
sanitizeError = (message) => message,
}) {
const spec = PDF_BATCH_OUTPUT_SPEC[operation];
if (!spec) {
onComplete({
success: false,
error: `Batch mode is not supported for the "${operation}" operation.`,
});
return;
}
if (!inputFolder || !fs.existsSync(inputFolder)) {
onComplete({ success: false, error: 'Input folder does not exist.' });
return;
}
try {
fs.mkdirSync(outputFolder, { recursive: true });
} catch (error) {
onComplete({
success: false,
error: sanitizeError(`Failed to create output folder: ${error.message}`),
});
return;
}
const files = collectFilesByExtension(inputFolder, ['.pdf'], includeSubfolders !== false);
if (files.length === 0) {
onComplete({ success: false, error: 'No matching files found in the selected folder.' });
return;
}
const total = files.length;
let completed = 0;
let failed = 0;
for (const filePath of files) {
onProgress({
completed,
failed,
total,
currentFile: path.basename(filePath),
});
try {
if (maxFileSize && fs.statSync(filePath).size > maxFileSize) {
failed++;
continue;
}
const baseName = path.basename(filePath, path.extname(filePath));
const relativeDir = path.dirname(path.relative(inputFolder, filePath));
const targetDir = relativeDir === '.' ? outputFolder : path.join(outputFolder, relativeDir);
fs.mkdirSync(targetDir, { recursive: true });
const fileData = { ...data, inputPath: filePath };
if (spec.dir) {
fileData.outputDir = path.join(targetDir, baseName);
} else if (spec.folder) {
fileData.outputFolder = targetDir;
} else {
const ext = spec.ext === 'original' ? 'pdf' : spec.ext;
fileData.outputPath = path.join(targetDir, `${baseName}.${ext}`);
}
// PDFOperations ops report failures via { success: false } rather than by
// throwing (each op catches internally), so the result flag — not just
// the promise — decides the per-file outcome.
const result = await PDFOperations.executeOperation(operation, fileData);
if (result && result.success) {
completed++;
} else {
failed++;
}
} catch {
// stat/mkdir can throw (file vanished mid-scan, output path became a
// file, ...): count the file as failed and keep the batch going, matching
// how executeOperation's own failures are handled.
failed++;
}
}
onProgress({ completed, failed, total, currentFile: null });
onComplete({ success: true, completed, failed, total, outputFolder });
}
module.exports = { runPDFBatchOperation, PDF_BATCH_OUTPUT_SPEC };
+760
View File
@@ -0,0 +1,760 @@
const fs = require('fs');
const path = require('path');
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
// pdf-lib 1.17.1 cannot encrypt: SaveOptions has no userPassword/ownerPassword/
// permissions fields, so save() silently ignores them and writes an unprotected
// file, and PDFDocument.load() cannot open password-protected input (verified
// empirically in Task 22's review). Rather than trusting a pinned version
// string, probe the installed library once at module load: save a tiny
// in-memory document with a userPassword and check the raw bytes for an
// /Encrypt dictionary (which an unencrypted document never contains). A library
// that supports encryption passes the probe and the password ops re-enable
// automatically. Probe errors fail closed (treated as unsupported).
const pdfEncryptionSupported = (async () => {
try {
const probeDoc = await PDFDocument.create();
const probeBytes = await probeDoc.save({ userPassword: 'encryption-capability-probe' });
return Buffer.from(probeBytes).includes('/Encrypt');
} catch {
return false;
}
})();
// Returned by the password ops when the probe reports no encryption support
// (Task 27): fail honestly instead of silently writing an unprotected file.
const PDF_ENCRYPTION_UNAVAILABLE_MESSAGE =
'Password protection is not available in this build (pdf-lib lacks encryption support).';
function parsePageRanges(rangeString, totalPages) {
const pages = [];
const ranges = rangeString.split(',').map((r) => r.trim());
for (const range of ranges) {
if (range.includes('-')) {
const [start, end] = range.split('-').map((n) => parseInt(n.trim()));
for (let i = start; i <= end && i <= totalPages; i++) {
if (i > 0 && !pages.includes(i - 1)) {
pages.push(i - 1);
}
}
} else {
const page = parseInt(range);
if (page > 0 && page <= totalPages && !pages.includes(page - 1)) {
pages.push(page - 1);
}
}
}
return pages.sort((a, b) => a - b);
}
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16) / 255,
g: parseInt(result[2], 16) / 255,
b: parseInt(result[3], 16) / 255,
}
: { r: 0, g: 0, b: 0 };
}
async function pdfMerge(data) {
try {
const mergedPdf = await PDFDocument.create();
for (const filePath of data.inputFiles) {
const pdfBytes = fs.readFileSync(filePath);
const pdf = await PDFDocument.load(pdfBytes);
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
copiedPages.forEach((page) => mergedPdf.addPage(page));
}
const pdfBytes = await mergedPdf.save();
fs.writeFileSync(data.outputPath, pdfBytes);
return { success: true, message: `Successfully merged ${data.inputFiles.length} PDFs` };
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfSplit(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
const splits = [];
if (data.splitMode === 'pages') {
const ranges = data.pageRanges.split(',').map((r) => r.trim());
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
const pages = [];
if (range.includes('-')) {
const [start, end] = range.split('-').map((n) => parseInt(n.trim()));
for (let p = start; p <= end && p <= totalPages; p++) {
pages.push(p - 1);
}
} else {
const page = parseInt(range);
if (page > 0 && page <= totalPages) {
pages.push(page - 1);
}
}
if (pages.length > 0) {
splits.push({ pages, name: `part_${i + 1}` });
}
}
} else if (data.splitMode === 'interval') {
const interval = data.interval;
if (!Number.isInteger(interval) || interval <= 0) {
return { success: false, message: 'Split interval must be a positive integer.' };
}
for (let i = 0; i < totalPages; i += interval) {
const pages = [];
for (let j = i; j < i + interval && j < totalPages; j++) {
pages.push(j);
}
splits.push({ pages, name: `part_${Math.floor(i / interval) + 1}` });
}
} else if (data.splitMode === 'size') {
const chunkSize = Math.max(1, Math.floor(totalPages / 5));
for (let i = 0; i < totalPages; i += chunkSize) {
const pages = [];
for (let j = i; j < i + chunkSize && j < totalPages; j++) {
pages.push(j);
}
splits.push({ pages, name: `part_${Math.floor(i / chunkSize) + 1}` });
}
}
const baseName = path.basename(data.inputPath, '.pdf');
for (const split of splits) {
const newPdf = await PDFDocument.create();
const copiedPages = await newPdf.copyPages(pdf, split.pages);
copiedPages.forEach((page) => newPdf.addPage(page));
const outputPath = path.join(data.outputFolder, `${baseName}_${split.name}.pdf`);
const newPdfBytes = await newPdf.save();
fs.writeFileSync(outputPath, newPdfBytes);
}
return { success: true, message: `Successfully split PDF into ${splits.length} files` };
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfCompress(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const compressedPdfBytes = await pdf.save({
useObjectStreams: true,
addDefaultPage: false,
objectsPerTick: 50,
});
fs.writeFileSync(data.outputPath, compressedPdfBytes);
const originalSize = fs.statSync(data.inputPath).size;
const compressedSize = fs.statSync(data.outputPath).size;
const savings = (((originalSize - compressedSize) / originalSize) * 100).toFixed(1);
return {
success: true,
message: `PDF compressed. Size reduced by ${savings}% (${(originalSize / 1024).toFixed(1)}KB → ${(compressedSize / 1024).toFixed(1)}KB)`,
};
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfRotate(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
let pagesToRotate = [];
if (data.pages && data.pages.trim()) {
pagesToRotate = parsePageRanges(data.pages, totalPages);
} else {
pagesToRotate = Array.from({ length: totalPages }, (_, i) => i);
}
pagesToRotate.forEach((pageIndex) => {
const page = pdf.getPage(pageIndex);
page.setRotation(degrees(data.angle));
});
const rotatedPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, rotatedPdfBytes);
return {
success: true,
message: `Successfully rotated ${pagesToRotate.length} page(s) by ${data.angle}\u00B0`,
};
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfDeletePages(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
const pagesToDelete = parsePageRanges(data.pages, totalPages);
pagesToDelete
.sort((a, b) => b - a)
.forEach((pageIndex) => {
pdf.removePage(pageIndex);
});
const newPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, newPdfBytes);
return {
success: true,
message: `Successfully deleted ${pagesToDelete.length} page(s). New PDF has ${totalPages - pagesToDelete.length} pages`,
};
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfReorder(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
const newOrder = data.newOrder.split(',').map((n) => parseInt(n.trim()) - 1);
if (newOrder.length !== totalPages) {
return { success: false, error: `New order must include all ${totalPages} pages` };
}
const newPdf = await PDFDocument.create();
const copiedPages = await newPdf.copyPages(pdf, newOrder);
copiedPages.forEach((page) => newPdf.addPage(page));
const reorderedPdfBytes = await newPdf.save();
fs.writeFileSync(data.outputPath, reorderedPdfBytes);
return { success: true, message: 'Successfully reordered PDF pages' };
} catch (error) {
return { success: false, error: error.message };
}
}
// Shared corner/center coordinate mapping used by pdfWatermark and pdfAddPageNumbers.
function resolvePosition(position, width, height, margin = 50) {
switch (position) {
case 'center':
return { x: width / 2, y: height / 2 };
case 'diagonal':
return { x: width / 2, y: height / 2 };
case 'top-left':
return { x: margin, y: height - margin };
case 'top-center':
return { x: width / 2, y: height - margin };
case 'top-right':
return { x: width - margin, y: height - margin };
case 'bottom-left':
return { x: margin, y: margin };
case 'bottom-center':
return { x: width / 2, y: margin };
case 'bottom-right':
return { x: width - margin, y: margin };
default:
return { x: width / 2, y: height / 2 };
}
}
async function pdfWatermark(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
let pagesToWatermark = [];
if (data.pages === 'all') {
pagesToWatermark = Array.from({ length: totalPages }, (_, i) => i);
} else if (data.pages === 'custom' && data.customPages) {
pagesToWatermark = parsePageRanges(data.customPages, totalPages);
}
const font = await pdf.embedFont(StandardFonts.Helvetica);
const color = hexToRgb(data.color);
for (const pageIndex of pagesToWatermark) {
const page = pdf.getPage(pageIndex);
const { width, height } = page.getSize();
const { x, y } = resolvePosition(data.position, width, height, 50);
const rotation = data.position === 'diagonal' ? 45 : 0;
page.drawText(data.text, {
x,
y,
size: data.fontSize,
font,
color: rgb(color.r, color.g, color.b),
opacity: data.opacity,
rotate: degrees(rotation),
});
}
const watermarkedPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, watermarkedPdfBytes);
return {
success: true,
message: `Successfully added watermark to ${pagesToWatermark.length} page(s)`,
};
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfEncrypt(data) {
if (!(await pdfEncryptionSupported)) {
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
}
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const encryptedPdfBytes = await pdf.save({
userPassword: data.userPassword,
ownerPassword: data.ownerPassword || data.userPassword,
permissions: {
printing: data.permissions.printing ? 'highResolution' : 'lowResolution',
modifying: data.permissions.modifying,
copying: data.permissions.copying,
annotating: data.permissions.annotating,
fillingForms: data.permissions.fillingForms,
contentAccessibility: data.permissions.contentAccessibility,
documentAssembly: data.permissions.documentAssembly,
},
});
fs.writeFileSync(data.outputPath, encryptedPdfBytes);
return { success: true, message: 'Successfully added password protection to PDF' };
} catch (error) {
if (error.message.includes('encrypt') || error.message.includes('password')) {
return {
success: false,
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 };
}
}
async function pdfDecrypt(data) {
if (!(await pdfEncryptionSupported)) {
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
}
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes, { password: data.password });
const decryptedPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, decryptedPdfBytes);
return { success: true, message: 'Successfully removed password protection from PDF' };
} catch (error) {
if (error.message.includes('password') || error.message.includes('encrypted')) {
return { success: false, error: 'Incorrect password or PDF is not encrypted' };
}
return { success: false, error: error.message };
}
}
async function pdfSetPermissions(data) {
if (!(await pdfEncryptionSupported)) {
return { success: false, message: PDF_ENCRYPTION_UNAVAILABLE_MESSAGE };
}
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const loadOptions = data.currentPassword ? { password: data.currentPassword } : {};
const pdf = await PDFDocument.load(pdfBytes, loadOptions);
const newPdfBytes = await pdf.save({
ownerPassword: data.ownerPassword,
permissions: {
printing: data.permissions.printing ? 'highResolution' : 'lowResolution',
modifying: data.permissions.modifying,
copying: data.permissions.copying,
annotating: data.permissions.annotating,
fillingForms: data.permissions.fillingForms,
contentAccessibility: data.permissions.contentAccessibility,
documentAssembly: data.permissions.documentAssembly,
},
});
fs.writeFileSync(data.outputPath, newPdfBytes);
return { success: true, message: 'Successfully updated PDF permissions' };
} catch (error) {
if (error.message.includes('encrypt') || error.message.includes('permission')) {
return {
success: false,
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 };
}
}
// pdf-lib has no text-extraction API, so this loads pdfjs-dist's Node-friendly
// "legacy" build (the standard build assumes DOM globals like DOMMatrix).
// pdfjs-dist v5.x ships ESM-only, so it must be loaded via dynamic import()
// even from this CommonJS module.
async function loadPdfjs() {
return import('pdfjs-dist/legacy/build/pdf.mjs');
}
// Points pdfjs-dist at its bundled standard font metrics so it doesn't warn
// (and degrade text-extraction fidelity) when a PDF uses a standard font.
function getStandardFontDataUrl() {
return (
path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts') + path.sep
);
}
async function pdfExtractText(data) {
try {
const pdfjsLib = await loadPdfjs();
const fileData = new Uint8Array(fs.readFileSync(data.inputPath));
const pdf = await pdfjsLib.getDocument({
data: fileData,
standardFontDataUrl: getStandardFontDataUrl(),
}).promise;
let text = '';
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
const content = await page.getTextContent();
const pageText = content.items.map((item) => item.str).join(' ');
text += pageText + '\n';
}
const trimmedText = text.trim();
const result = { success: true, text: trimmedText };
// outputPath is optional: when provided (e.g. from the PDF editor UI),
// also save the extracted text to disk and report where it went.
if (data.outputPath) {
fs.writeFileSync(data.outputPath, trimmedText, 'utf8');
result.message = `Successfully extracted text to ${data.outputPath}`;
}
return result;
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfAddPageNumbers(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
const font = await pdf.embedFont(StandardFonts.Helvetica);
const position = data.position || 'bottom-center';
const fontSize = data.fontSize || 12;
const startNumber = data.startNumber && data.startNumber > 0 ? data.startNumber : 1;
for (let i = 0; i < totalPages; i++) {
const page = pdf.getPage(i);
const { width, height } = page.getSize();
const { x, y } = resolvePosition(position, width, height, 30);
const label = String(startNumber + i);
const textWidth = font.widthOfTextAtSize(label, fontSize);
let drawX = x;
if (position.includes('center')) {
drawX = x - textWidth / 2;
} else if (position.includes('right')) {
drawX = x - textWidth;
}
page.drawText(label, {
x: drawX,
y,
size: fontSize,
font,
color: rgb(0, 0, 0),
});
}
const newPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, newPdfBytes);
return { success: true, message: `Successfully added page numbers to ${totalPages} page(s)` };
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfCrop(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const totalPages = pdf.getPageCount();
const margins = data.margins || {};
const top = margins.top || 0;
const bottom = margins.bottom || 0;
const left = margins.left || 0;
const right = margins.right || 0;
for (let i = 0; i < totalPages; i++) {
const page = pdf.getPage(i);
const mediaBox = page.getMediaBox();
const newWidth = mediaBox.width - left - right;
const newHeight = mediaBox.height - top - bottom;
if (newWidth <= 0 || newHeight <= 0) {
return { success: false, error: `Crop margins are too large for page ${i + 1}` };
}
page.setCropBox(mediaBox.x + left, mediaBox.y + bottom, newWidth, newHeight);
}
const croppedPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, croppedPdfBytes);
return { success: true, message: `Successfully cropped ${totalPages} page(s)` };
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfExtractImages(data) {
try {
const pdfjsLib = await loadPdfjs();
// sharp is only needed here; require lazily to match the module's existing
// pattern of not pulling heavy optional deps in until an operation runs.
const sharp = require('sharp');
const fileData = new Uint8Array(fs.readFileSync(data.inputPath));
const pdf = await pdfjsLib.getDocument({
data: fileData,
standardFontDataUrl: getStandardFontDataUrl(),
}).promise;
if (!fs.existsSync(data.outputDir)) {
fs.mkdirSync(data.outputDir, { recursive: true });
}
const baseName = path.basename(data.inputPath, path.extname(data.inputPath));
const files = [];
let imageIndex = 0;
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
const opList = await page.getOperatorList();
for (let i = 0; i < opList.fnArray.length; i++) {
if (opList.fnArray[i] !== pdfjsLib.OPS.paintImageXObject) {
continue;
}
const objId = opList.argsArray[i][0];
try {
const imgObj = await new Promise((resolve) => page.objs.get(objId, resolve));
if (!imgObj || !imgObj.data || !imgObj.width || !imgObj.height) {
continue;
}
const channels =
imgObj.kind === pdfjsLib.ImageKind.RGBA_32BPP
? 4
: imgObj.kind === pdfjsLib.ImageKind.GRAYSCALE_1BPP
? 1
: 3;
imageIndex++;
const outputFile = path.join(
data.outputDir,
`${baseName}_page${pageNum}_img${imageIndex}.png`
);
await sharp(Buffer.from(imgObj.data), {
raw: { width: imgObj.width, height: imgObj.height, channels },
})
.png()
.toFile(outputFile);
files.push(outputFile);
} catch {
// Skip images pdfjs/sharp can't decode (e.g. unsupported color spaces).
continue;
}
}
}
return {
success: true,
count: files.length,
files,
message: `Successfully extracted ${files.length} image(s)`,
};
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfGetFormFields(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const form = pdf.getForm();
const fields = form.getFields().map((field) => {
let value;
try {
if (typeof field.getText === 'function') {
value = field.getText();
} else if (typeof field.isChecked === 'function') {
value = field.isChecked();
} else if (typeof field.getSelected === 'function') {
value = field.getSelected();
}
} catch {
// Some field types throw when read in an unexpected state; leave value undefined.
value = undefined;
}
return { name: field.getName(), type: field.constructor.name, value };
});
return { success: true, fields };
} catch (error) {
return { success: false, error: error.message };
}
}
async function pdfFillForm(data) {
try {
const pdfBytes = fs.readFileSync(data.inputPath);
const pdf = await PDFDocument.load(pdfBytes);
const form = pdf.getForm();
const values = data.values || {};
let filledCount = 0;
for (const [name, value] of Object.entries(values)) {
try {
const field = form.getTextField(name);
field.setText(value !== null && value !== undefined ? String(value) : '');
filledCount++;
} catch (fieldError) {
// Batch-of-independent-fields: a field that doesn't exist or isn't a text
// field shouldn't fail the whole fill — skip it and keep going (same
// partial-success precedent as pdfExtractImages).
console.warn(`pdfFillForm: skipping field "${name}": ${fieldError.message}`);
}
}
if (data.flatten) {
form.flatten();
}
const filledPdfBytes = await pdf.save();
fs.writeFileSync(data.outputPath, filledPdfBytes);
return { success: true, message: `Successfully filled ${filledCount} form field(s)` };
} catch (error) {
return { success: false, error: error.message };
}
}
function executeOperation(operation, data) {
switch (operation) {
case 'merge':
return pdfMerge(data);
case 'split':
return pdfSplit(data);
case 'compress':
return pdfCompress(data);
case 'rotate':
return pdfRotate(data);
case 'delete':
return pdfDeletePages(data);
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);
case 'extractText':
return pdfExtractText(data);
case 'pageNumbers':
return pdfAddPageNumbers(data);
case 'crop':
return pdfCrop(data);
case 'extractImages':
return pdfExtractImages(data);
case 'formFields':
return pdfGetFormFields(data);
case 'fillForm':
return pdfFillForm(data);
default:
return Promise.resolve({ success: false, error: `Unknown operation: ${operation}` });
}
}
async function getPageCount(filePath) {
const pdfBytes = fs.readFileSync(filePath);
const pdf = await PDFDocument.load(pdfBytes);
return pdf.getPageCount();
}
module.exports = {
parsePageRanges,
hexToRgb,
pdfEncryptionSupported,
PDF_ENCRYPTION_UNAVAILABLE_MESSAGE,
pdfMerge,
pdfSplit,
pdfCompress,
pdfRotate,
pdfDeletePages,
pdfReorder,
pdfWatermark,
pdfEncrypt,
pdfDecrypt,
pdfSetPermissions,
pdfExtractText,
pdfAddPageNumbers,
pdfCrop,
pdfExtractImages,
pdfGetFormFields,
pdfFillForm,
executeOperation,
getPageCount,
};
+135
View File
@@ -0,0 +1,135 @@
/**
* Pure builders for Pandoc execFile argument arrays.
*
* Every Pandoc invocation in the main process must call
* execFile(pandocPath, args) with an argument array built here or with plain
* Array.push calls — never a command string that is later re-tokenized.
* Values that come from the user (file paths, template names, metadata values)
* are pushed verbatim as single argv elements, so a crafted value such as
* `/tmp/x.bib" --lua-filter=/tmp/evil.lua` can never break out of its argument
* and inject additional Pandoc flags (security finding SEC-1).
*/
/**
* Formats exported through a plain `-t <target>` conversion. The export dialog
* replaces the whole command for these formats (dialog options like template or
* metadata are not applied) — this map preserves that pre-existing behavior.
*/
const SIMPLE_TARGET_FORMATS = {
json: 'json',
beamer: 'beamer',
confluence: 'jira',
jira: 'jira',
asciidoc: 'asciidoc',
rst: 'rst',
mediawiki: 'mediawiki',
org: 'org',
textile: 'textile',
man: 'man',
ipynb: 'ipynb',
};
/**
* Append the export-dialog options shared by the export, batch-conversion and
* fallback paths. Each value lands in argv exactly once, unquoted and
* unescaped — execFile passes array elements as literal arguments.
* @param {string[]} args - Argument array to append to (mutated)
* @param {Object} options - Export options ({ template, metadata, variables,
* toc, tocDepth, numberSections, citeproc, bibliography, csl })
*/
function appendCommonOptions(args, options) {
if (!options) return;
if (options.template && options.template !== 'default') {
args.push(`--template=${options.template}`);
}
if (options.metadata) {
for (const [key, value] of Object.entries(options.metadata)) {
if (value.trim()) {
args.push('-M', `${key}=${value}`);
}
}
}
if (options.variables) {
for (const [key, value] of Object.entries(options.variables)) {
if (value.trim()) {
args.push('-V', `${key}=${value}`);
}
}
}
if (options.toc) args.push('--toc');
if (options.tocDepth) args.push(`--toc-depth=${options.tocDepth}`);
if (options.numberSections) args.push('--number-sections');
if (options.citeproc) args.push('--citeproc');
if (options.bibliography) args.push(`--bibliography=${options.bibliography}`);
if (options.csl) args.push(`--csl=${options.csl}`);
}
/**
* Append the shared prefix of every PDF invocation: the pdf engine flag and,
* when set, the page geometry variable.
* @param {string[]} args - Argument array to append to (mutated)
* @param {Object} params
* @param {string} [params.pdfEngine] - Falls back to xelatex when omitted
* @param {string} [params.geometry] - LaTeX geometry string (e.g. margin=1in)
*/
function appendPdfEngineOptions(args, { pdfEngine, geometry } = {}) {
args.push(`--pdf-engine=${pdfEngine || 'xelatex'}`);
if (geometry) args.push('-V', `geometry:${geometry}`);
}
/**
* Append the PowerPoint footer variable (used when header/footer is enabled).
* @param {string[]} args - Argument array to append to (mutated)
* @param {string} footerText - Processed footer text
*/
function appendFooterVariable(args, footerText) {
if (footerText) args.push('--variable', `footer=${footerText}`);
}
/**
* Build the base argument array for the export dialog and batch conversion:
* input, -o output, the shared export options, and the `-t docx` tail for
* Word exports. Format-specific extras (PDF engine flags, EPUB fonts, HTML
* css, reveal.js themes) are appended by the call site.
* @param {Object} params
* @param {string} params.inputFile - Path passed to pandoc verbatim
* @param {string} params.outputFile - Path passed to pandoc verbatim
* @param {string} [params.format] - Export format name
* @param {Object} [params.options] - Export dialog options
* @returns {string[]}
*/
function buildPandocArgs({ inputFile, outputFile, format, options = {} }) {
const args = [inputFile, '-o', outputFile];
appendCommonOptions(args, options);
if (format === 'docx') {
args.push('-t', 'docx');
}
return args;
}
/**
* Build args for the simple `-t <target>` formats (see SIMPLE_TARGET_FORMATS).
* @param {string} inputFile - Input path
* @param {string} outputFile - Output path
* @param {string} format - Export format name
* @returns {string[]|null} Argument array, or null when format is not one of
* the simple target formats
*/
function buildSimpleTargetArgs(inputFile, outputFile, format) {
const target = SIMPLE_TARGET_FORMATS[format];
if (!target) return null;
return [inputFile, '-t', target, '-o', outputFile];
}
module.exports = {
SIMPLE_TARGET_FORMATS,
appendCommonOptions,
appendPdfEngineOptions,
appendFooterVariable,
buildPandocArgs,
buildSimpleTargetArgs,
};
+47
View File
@@ -0,0 +1,47 @@
'use strict';
// fontspec accepts forward-slash paths on all platforms (TeX normalizes).
// Normalize Windows backslashes so we can reliably build Path/filename.
function toPosix(p) {
return String(p).replace(/\\/g, '/');
}
function escape(s) {
// fontspec values: braces are the only TeX-significant chars we might emit
// from a basename. Backslashes are converted to '/' upstream by toPosix().
return String(s).replace(/[{}]/g, '\\$&');
}
function dirOf(p) {
return toPosix(p).replace(/\/[^/]+$/, '') + '/';
}
function baseName(p) {
return toPosix(p).split('/').pop();
}
// Strip a weight-style suffix from a TTF filename to get the family prefix
// (e.g. JetBrainsMono-Regular.ttf -> JetBrainsMono). Used as the `\setmonofont`
// argument so `*-Regular` / `*-Bold` globs resolve to the right files.
function weightPrefix(p) {
return baseName(p).replace(/-(Regular|Bold|Light|Medium|SemiBold|Italic)\.ttf$/i, '');
}
function build({ fontTtfPath, boldTtfPath, ligatures }) {
if (!fontTtfPath) {
return '% Monospace font path unavailable; TeX will use its default monospace.\n';
}
// `boldTtfPath` is accepted for API symmetry with future formats; the glob
// below resolves the bold file from the regular file's family prefix.
void boldTtfPath;
const ligValue = ligatures ? 'Ligatures=TeX' : 'Ligatures=NoCommon';
const prefix = escape(weightPrefix(fontTtfPath));
return `\\usepackage{fontspec}
\\setmonofont[Path=${escape(dirOf(fontTtfPath))},Extension=.ttf,UprightFont=*-Regular,BoldFont=*-Bold,${ligValue}]{${prefix}}
`;
}
module.exports = { build };
+145
View File
@@ -0,0 +1,145 @@
/**
* Video Operations Module
*
* Handles video manipulation via `ffmpeg`: format conversion, compression, trim,
* frame extraction, and GIF conversion. Because ffmpeg is an external binary, this
* module is split into pure/testable argument-builder functions and a single
* `executeOperation` that is the only piece which actually spawns ffmpeg — the
* ffmpeg binary path and the `execFile` implementation are both injected so tests
* can replace them with fakes, without invoking a real binary.
*
* @module VideoOperations
*/
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
/**
* Build args for a straight format conversion. ffmpeg infers the output format
* from outputPath's extension.
*/
function buildConvertArgs({ inputPath, outputPath }) {
return ['-i', inputPath, '-y', outputPath];
}
/**
* Build args to re-encode inputPath with libx264 at the given CRF (Constant Rate
* Factor). Lower CRF = higher quality/larger file, per libx264 convention. crf
* must be an integer in [0, 51].
*/
function buildCompressArgs({ inputPath, outputPath, crf = 28 }) {
if (!Number.isInteger(crf) || crf < 0 || crf > 51) {
throw new Error('Invalid crf: must be an integer between 0 and 51');
}
return ['-i', inputPath, '-vcodec', 'libx264', '-crf', String(crf), '-y', outputPath];
}
/**
* Build args to trim inputPath to [startTime, startTime + duration) seconds.
* startTime/duration must be finite, non-negative numbers — they become argv
* elements passed straight to execFile with no shell involved, so there's no
* injection risk, but malformed values should still fail fast rather than reach
* ffmpeg with garbage.
*/
function buildTrimArgs({ inputPath, outputPath, startTime, duration }) {
const isValid = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
if (!isValid(startTime) || !isValid(duration)) {
throw new Error('Invalid trim range');
}
return ['-i', inputPath, '-ss', String(startTime), '-t', String(duration), '-y', outputPath];
}
/**
* Build args to extract frames from inputPath at fps frames-per-second, written
* as sequentially numbered PNGs into outputDir. fps must be a positive finite
* number.
*/
function buildFramesArgs({ inputPath, outputDir, fps = 1 }) {
if (typeof fps !== 'number' || !Number.isFinite(fps) || fps <= 0) {
throw new Error('Invalid fps: must be a positive finite number');
}
return ['-i', inputPath, '-vf', `fps=${fps}`, path.join(outputDir, 'frame-%04d.png')];
}
/**
* Build args to convert inputPath to an animated GIF at the given fps and width
* (height scales automatically via -1), using the lanczos scaling filter.
*/
function buildGifArgs({ inputPath, outputPath, fps = 10, width = 480 }) {
return ['-i', inputPath, '-vf', `fps=${fps},scale=${width}:-1:flags=lanczos`, '-y', outputPath];
}
/**
* Run ffmpeg with the given args via the injected execFileFn, wrapped in a Promise.
*/
function runFfmpeg(ffmpegPath, args, execFileFn) {
return new Promise((resolve, reject) => {
execFileFn(ffmpegPath, args, { maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr || error.message));
return;
}
resolve();
});
});
}
async function executeOperation(operation, data, { ffmpegPath, execFileFn } = {}) {
const resolvedFfmpegPath = ffmpegPath || 'ffmpeg';
const resolvedExecFileFn = execFileFn || execFile;
switch (operation) {
case 'convert': {
const { inputPath, outputPath } = data || {};
const args = buildConvertArgs({ inputPath, outputPath });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
case 'compress': {
const { inputPath, outputPath, crf } = data || {};
const args = buildCompressArgs({ inputPath, outputPath, crf });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
case 'trim': {
const { inputPath, outputPath, startTime, duration } = data || {};
const args = buildTrimArgs({ inputPath, outputPath, startTime, duration });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
case 'frames': {
const { inputPath, outputDir, fps } = data || {};
const args = buildFramesArgs({ inputPath, outputDir, fps });
fs.mkdirSync(outputDir, { recursive: true });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputDir };
}
case 'gif': {
const { inputPath, outputPath, fps, width } = data || {};
const args = buildGifArgs({ inputPath, outputPath, fps, width });
await runFfmpeg(resolvedFfmpegPath, args, resolvedExecFileFn);
return { success: true, outputPath };
}
default:
throw new Error(`Unknown operation: ${operation}`);
}
}
module.exports = {
executeOperation,
buildConvertArgs,
buildCompressArgs,
buildTrimArgs,
buildFramesArgs,
buildGifArgs,
};
+52
View File
@@ -0,0 +1,52 @@
/**
* collectFilesByExtension
*
* Recursively (optionally) collects files under a directory whose extension matches
* one of a given set of extensions. Generalizes the `collectFiles()` closure defined
* inside `ipcMain.on('universal-convert-batch', ...)` in main.js (which matches a
* single `.${fromFormat}` extension) to match against an arbitrary extension list —
* used by the batch-image/audio/video-operation handlers, which need to match several
* possible input extensions per media kind (e.g. .jpg/.jpeg/.png/... for images).
*
* Pulled out as its own module (rather than an inline closure like the original) so it
* can be unit tested without Electron.
*
* @module collectFilesByExtension
*/
const fs = require('fs');
const path = require('path');
/**
* @param {string} dir - Directory to scan.
* @param {string[]} extensions - Extensions to match, each including the leading dot
* (e.g. ['.jpg', '.png']). Matching is case-insensitive.
* @param {boolean} [includeSubfolders=true] - Recurse into subdirectories.
* @returns {string[]} Absolute paths of matching files, in directory-walk order.
*/
function collectFilesByExtension(dir, extensions, includeSubfolders = true) {
const normalizedExts = (extensions || []).map((ext) => ext.toLowerCase());
const results = [];
function walk(currentDir) {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
if (includeSubfolders) {
walk(fullPath);
}
} else if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if (normalizedExts.includes(ext)) {
results.push(fullPath);
}
}
}
}
walk(dir);
return results;
}
module.exports = { collectFilesByExtension };
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const FAMILY_BY_KEY = {
'jetbrains-mono': 'JetBrains Mono',
'fira-code': 'Fira Code',
};
function getDefaults() {
return Object.freeze({ monospaceFont: 'jetbrains-mono', monospaceLigatures: false });
}
function getActiveMonoFont(settings) {
const key = settings && settings.monospaceFont;
return FAMILY_BY_KEY[key] || 'JetBrains Mono';
}
function isLigaturesEnabled(settings) {
return Boolean(settings && settings.monospaceLigatures === true);
}
module.exports = { getDefaults, getActiveMonoFont, isLigaturesEnabled, FAMILY_BY_KEY };
+12
View File
@@ -0,0 +1,12 @@
const { PluginAPI } = require('../../plugin-api');
class SamplePlugin extends PluginAPI {
init(context) {
this.context = context;
context.commands.register('hello', 'Sample: Hello World', () => {
console.log('[SamplePlugin] Hello from the plugin system!');
});
}
}
module.exports = { Plugin: SamplePlugin };
@@ -0,0 +1,11 @@
{
"id": "_sample",
"name": "Sample Plugin",
"version": "1.0.0",
"description": "Demonstrates the plugin system. Safe to delete.",
"icon": "puzzle",
"extensionPoints": {
"commands": [{ "id": "hello", "label": "Sample: Hello World", "shortcut": "" }]
},
"settings": []
}
@@ -0,0 +1,87 @@
const HISTORY_KEY = 'plugins.writing-studio.history';
class GoalTracker {
/**
* @param {object} store - { get(key), set(key, value) } settings backend
*/
constructor(store) {
this.store = store;
}
_getHistory() {
const raw = this.store.get(HISTORY_KEY);
return raw ? JSON.parse(raw) : {};
}
_setHistory(history) {
this.store.set(HISTORY_KEY, JSON.stringify(history));
}
_setHistoryDay(dateStr, data) {
const history = this._getHistory();
history[dateStr] = data;
this._setHistory(history);
}
addWords(count) {
const today = new Date().toISOString().split('T')[0];
const history = this._getHistory();
if (!history[today]) {
history[today] = { words: 0, sessions: 0 };
}
history[today].words += count;
history[today].sessions += 1;
this._setHistory(history);
}
getDailyProgress(goal) {
const today = new Date().toISOString().split('T')[0];
const history = this._getHistory();
const written = history[today]?.words || 0;
return { written, goal, pct: goal > 0 ? Math.min(100, Math.round((written / goal) * 100)) : 0 };
}
getStreak(goal) {
const history = this._getHistory();
let streak = 0;
const d = new Date();
for (let i = 0; i < 365; i++) {
const key = d.toISOString().split('T')[0];
const day = history[key];
if (day && day.words >= goal) {
streak++;
d.setDate(d.getDate() - 1);
} else {
break;
}
}
return streak;
}
getLast30Days() {
const history = this._getHistory();
const days = [];
const d = new Date();
for (let i = 0; i < 30; i++) {
const key = d.toISOString().split('T')[0];
const day = history[key];
days.push({ date: key, words: day?.words || 0 });
d.setDate(d.getDate() - 1);
}
return days.reverse();
}
getWeeklyTotal() {
const history = this._getHistory();
let total = 0;
const d = new Date();
for (let i = 0; i < 7; i++) {
const key = d.toISOString().split('T')[0];
if (history[key]) total += history[key].words || 0;
d.setDate(d.getDate() - 1);
}
return total;
}
}
module.exports = { GoalTracker };
@@ -0,0 +1,169 @@
const { PluginAPI } = require('../../../plugins/plugin-api');
const { SprintEngine } = require('./sprint-engine');
const { GoalTracker } = require('./goal-tracker');
const { SnapshotManager } = require('./snapshot-manager');
const { ProjectManager } = require('./project-manager');
class WritingStudioPlugin extends PluginAPI {
init(context) {
this.context = context;
this.sprintEngine = new SprintEngine({
onEvent: (name, data) => context.events.emit(name, data),
});
this.goalTracker = new GoalTracker(context.settings);
this.snapshotManager = new SnapshotManager(context.settings);
this.projectManager = new ProjectManager({
readFile: (p) => context.ipc.invoke('read-file', p),
writeFile: (p, c) => context.ipc.invoke('write-file', p, c),
fileExists: (p) => context.ipc.invoke('path-exists', p),
listDir: (p) => context.ipc.invoke('list-directory', p),
});
this._engines = {
sprint: this.sprintEngine,
goals: this.goalTracker,
snapshots: this.snapshotManager,
projects: this.projectManager,
};
this._registerCommands(context);
this._registerStatusBar(context);
this._registerExportFormats(context);
}
_registerCommands(context) {
const { sprintEngine, snapshotManager, goalTracker } = this;
context.commands.register(
'start-sprint',
'Studio: Start Sprint',
() => {
const duration = context.settings.get('sprintDuration') || 25;
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',
() => {
if (!sprintEngine.isActive()) return;
const content = context.editor.getContent() || '';
const words = content.split(/\s+/).filter(Boolean).length;
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',
() => {
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',
() => {
const snaps = snapshotManager.list();
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.events.emit('studio:new-project', {});
});
context.commands.register(
'compile-manuscript',
'Studio: Compile Manuscript',
() => {
context.events.emit('studio:compile', {});
},
'Ctrl+Alt+E'
);
context.commands.register(
'proofread-document',
'Studio: Proofread Document',
() => {
if (context.events.hasHandler('ai:analyze')) {
const content = context.editor.getContent() || '';
context.events.emit('ai:analyze', { text: content, type: 'grammar' });
}
},
'Ctrl+Alt+G'
);
}
_registerStatusBar(context) {
context.statusBar.registerIndicator('word-goal', {
text: '0/1000',
tooltip: 'Daily word goal progress',
});
context.statusBar.registerIndicator('sprint-timer', {
text: '',
tooltip: 'Writing sprint timer',
});
}
// Example usage of context.formats.registerExportFormat (Task 17): adds
// a "Writing Studio Summary" entry to the Export menu that writes a
// plain-text snapshot of today's sprint/goal progress instead of going
// through Pandoc. Doubles as documentation for how a plugin can offer
// its own export target.
_registerExportFormats(context) {
const { sprintEngine, goalTracker } = this;
context.formats.registerExportFormat('sprint-summary', {
label: 'Writing Studio Summary (.txt)',
extension: 'txt',
handler: async (markdownContent, outputPath) => {
const fs = require('fs');
const goal = context.settings.get('dailyGoal') || 1000;
const progress = goalTracker.getDailyProgress(goal);
const streak = goalTracker.getStreak(goal);
const wordCount = (markdownContent || '').split(/\s+/).filter(Boolean).length;
const lines = [
'Writing Studio Summary',
'=======================',
`Generated: ${new Date().toISOString()}`,
'',
`Document word count: ${wordCount}`,
`Daily goal: ${goal}`,
`Words written today: ${progress.written} (${progress.pct}%)`,
`Current streak: ${streak} day(s)`,
`Sprint active: ${sprintEngine.isActive() ? 'yes' : 'no'}`,
'',
];
fs.writeFileSync(outputPath, lines.join('\n'), 'utf-8');
},
});
}
deactivate() {
if (this._sprintInterval) clearInterval(this._sprintInterval);
}
getEngines() {
return this._engines;
}
}
module.exports = { Plugin: WritingStudioPlugin };
@@ -0,0 +1,55 @@
{
"id": "writing-studio",
"name": "Writing Studio",
"version": "1.0.0",
"description": "Manuscript management, writing sprints, goal tracking, snapshots, and smart proofreading",
"icon": "pen-tool",
"extensionPoints": {
"sidebar": [
{ "id": "manuscript", "title": "Manuscript", "order": 30 },
{ "id": "goals", "title": "Goals", "order": 31 },
{ "id": "snapshots", "title": "Snapshots", "order": 32 },
{ "id": "proofread", "title": "Proofread", "order": 33 }
],
"commands": [
{ "id": "start-sprint", "label": "Studio: Start Sprint", "shortcut": "Ctrl+Alt+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": "restore-last-snapshot",
"label": "Studio: Restore Last Snapshot",
"shortcut": "Ctrl+Alt+Z"
},
{ "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"
}
],
"statusBar": { "indicators": ["sprint-timer", "word-goal"] },
"exportFormats": [
{
"id": "sprint-summary",
"label": "Writing Studio Summary (.txt)",
"extension": "txt"
}
]
},
"settings": [
{ "key": "dailyGoal", "type": "number", "default": 1000, "label": "Daily word goal" },
{ "key": "sprintDuration", "type": "number", "default": 25, "label": "Sprint duration (min)" },
{
"key": "autoSnapshotInterval",
"type": "number",
"default": 0,
"label": "Auto-snapshot interval (min, 0=off)"
},
{ "key": "maxSnapshots", "type": "number", "default": 50, "label": "Max snapshots to keep" }
]
}
@@ -0,0 +1,100 @@
function renderGoalsPanel(container, { engines, settings }) {
const dailyGoal = settings.get('dailyGoal') || 1000;
const progress = engines.goals.getDailyProgress(dailyGoal);
const streak = engines.goals.getStreak(dailyGoal);
const weekly = engines.goals.getWeeklyTotal();
const last30 = engines.goals.getLast30Days();
container.replaceChildren();
const panel = document.createElement('div');
panel.className = 'ws-panel';
// Daily progress section
const section1 = document.createElement('div');
section1.className = 'ws-section';
const heading1 = document.createElement('h3');
heading1.className = 'ws-heading';
heading1.textContent = 'Daily Progress';
section1.appendChild(heading1);
const bar = document.createElement('div');
bar.className = 'ws-progress-bar';
const fill = document.createElement('div');
fill.className = 'ws-progress-fill';
fill.style.width = progress.pct + '%';
bar.appendChild(fill);
section1.appendChild(bar);
const row = document.createElement('div');
row.className = 'ws-stat-row';
const label = document.createElement('span');
label.textContent =
progress.written.toLocaleString() + ' / ' + dailyGoal.toLocaleString() + ' words';
const pct = document.createElement('span');
pct.className = 'ws-pct';
pct.textContent = progress.pct + '%';
row.appendChild(label);
row.appendChild(pct);
section1.appendChild(row);
panel.appendChild(section1);
// Stats cards
const section2 = document.createElement('div');
section2.className = 'ws-section';
const grid = document.createElement('div');
grid.className = 'ws-stat-grid';
const streakCard = document.createElement('div');
streakCard.className = 'ws-stat-card';
const streakVal = document.createElement('span');
streakVal.className = 'ws-stat-value';
streakVal.textContent = String(streak);
const streakLbl = document.createElement('span');
streakLbl.className = 'ws-stat-label';
streakLbl.textContent = 'Day Streak';
streakCard.appendChild(streakVal);
streakCard.appendChild(streakLbl);
const weekCard = document.createElement('div');
weekCard.className = 'ws-stat-card';
const weekVal = document.createElement('span');
weekVal.className = 'ws-stat-value';
weekVal.textContent = weekly.toLocaleString();
const weekLbl = document.createElement('span');
weekLbl.className = 'ws-stat-label';
weekLbl.textContent = 'This Week';
weekCard.appendChild(weekVal);
weekCard.appendChild(weekLbl);
grid.appendChild(streakCard);
grid.appendChild(weekCard);
section2.appendChild(grid);
panel.appendChild(section2);
// 30-day chart
const section3 = document.createElement('div');
section3.className = 'ws-section';
const heading3 = document.createElement('h3');
heading3.className = 'ws-heading';
heading3.textContent = 'Last 30 Days';
section3.appendChild(heading3);
const chart = document.createElement('div');
chart.className = 'ws-chart';
const maxWords = Math.max(...last30.map((d) => d.words), 1);
for (const day of last30) {
const barEl = document.createElement('div');
const height = Math.max(2, (day.words / maxWords) * 60);
barEl.className = 'ws-bar' + (day.words >= dailyGoal ? ' ws-bar-met' : '');
barEl.style.height = height + 'px';
barEl.title = day.date + ': ' + day.words + ' words';
chart.appendChild(barEl);
}
section3.appendChild(chart);
panel.appendChild(section3);
container.appendChild(panel);
}
module.exports = { renderGoalsPanel };
@@ -0,0 +1,125 @@
function renderManuscriptPanel(container, { engines, editor, settings }) {
const projectDir = settings.get('projectDir');
container.replaceChildren();
const panel = document.createElement('div');
panel.className = 'ws-panel';
if (!projectDir) {
const empty = document.createElement('div');
empty.className = 'ws-empty';
const p = document.createElement('p');
p.textContent = 'No manuscript project open';
empty.appendChild(p);
const btn = document.createElement('button');
btn.className = 'ws-btn ws-btn-primary';
btn.id = 'ws-new-project';
btn.textContent = 'New Project';
btn.addEventListener('click', () => {
const name = prompt('Project name:');
if (!name) return;
settings.set('projectDir', name);
renderManuscriptPanel(container, { engines, editor, settings });
});
empty.appendChild(btn);
panel.appendChild(empty);
container.appendChild(panel);
return;
}
const project = engines.projects.loadProject(projectDir);
if (!project) {
const empty = document.createElement('div');
empty.className = 'ws-empty';
const p = document.createElement('p');
p.textContent = 'Project not found at ' + projectDir;
empty.appendChild(p);
const btn = document.createElement('button');
btn.className = 'ws-btn';
btn.id = 'ws-clear-project';
btn.textContent = 'Clear Project';
btn.addEventListener('click', () => {
settings.set('projectDir', null);
renderManuscriptPanel(container, { engines, editor, settings });
});
empty.appendChild(btn);
panel.appendChild(empty);
container.appendChild(panel);
return;
}
const stats = engines.projects.getStats(projectDir);
// Project title + progress
const section1 = document.createElement('div');
section1.className = 'ws-section';
const heading = document.createElement('h3');
heading.className = 'ws-heading';
heading.textContent = project.title;
section1.appendChild(heading);
const bar = document.createElement('div');
bar.className = 'ws-progress-bar';
const fill = document.createElement('div');
fill.className = 'ws-progress-fill';
fill.style.width = stats.pctComplete + '%';
bar.appendChild(fill);
section1.appendChild(bar);
const row = document.createElement('div');
row.className = 'ws-stat-row';
const label = document.createElement('span');
label.textContent =
stats.totalWords.toLocaleString() + ' / ' + stats.targetWords.toLocaleString() + ' words';
const pct = document.createElement('span');
pct.className = 'ws-pct';
pct.textContent = stats.pctComplete + '%';
row.appendChild(label);
row.appendChild(pct);
section1.appendChild(row);
panel.appendChild(section1);
// Chapters list
const section2 = document.createElement('div');
section2.className = 'ws-section';
const heading2 = document.createElement('h3');
heading2.className = 'ws-heading';
heading2.textContent = 'Chapters (' + project.chapters.length + ')';
section2.appendChild(heading2);
const chList = document.createElement('div');
chList.className = 'ws-chapter-list';
for (const ch of project.chapters) {
const item = document.createElement('div');
item.className = 'ws-chapter-item';
const title = document.createElement('span');
title.className = 'ws-chapter-title';
title.textContent = ch.title || ch.file;
const status = document.createElement('span');
status.className = 'ws-chapter-status ws-status-' + (ch.status || 'draft');
status.textContent = ch.status || 'draft';
item.appendChild(title);
item.appendChild(status);
chList.appendChild(item);
}
section2.appendChild(chList);
panel.appendChild(section2);
// Compile button
const section3 = document.createElement('div');
section3.className = 'ws-section';
const compileBtn = document.createElement('button');
compileBtn.className = 'ws-btn ws-btn-primary';
compileBtn.id = 'ws-compile';
compileBtn.textContent = 'Compile Manuscript';
compileBtn.addEventListener('click', () => {
const compiled = engines.projects.compileManuscript(projectDir);
editor.insertAtCursor(compiled);
});
section3.appendChild(compileBtn);
panel.appendChild(section3);
container.appendChild(panel);
}
module.exports = { renderManuscriptPanel };
@@ -0,0 +1,100 @@
function renderProofreadPanel(container, { events, editor }) {
const hasAI = events.hasHandler('ai:analyze');
container.replaceChildren();
const panel = document.createElement('div');
panel.className = 'ws-panel';
const section = document.createElement('div');
section.className = 'ws-section';
const btn = document.createElement('button');
btn.className = 'ws-btn ws-btn-primary';
btn.id = 'ws-proofread';
btn.textContent = hasAI ? 'Check Document' : 'AI Plugin Required';
btn.disabled = !hasAI;
section.appendChild(btn);
if (!hasAI) {
const note = document.createElement('p');
note.className = 'ws-muted';
note.textContent = 'Install the AI Assistant plugin to enable proofreading.';
section.appendChild(note);
}
panel.appendChild(section);
const issuesList = document.createElement('div');
issuesList.className = 'ws-issues-list';
issuesList.id = 'ws-issues';
panel.appendChild(issuesList);
container.appendChild(panel);
if (!hasAI) return;
container.querySelector('#ws-proofread').addEventListener('click', () => {
const content = editor.getContent() || '';
events.emit('ai:analyze', {
text: content,
type: 'grammar',
callback: (result) => {
if (result && result.issues) {
renderIssues(issuesList, result.issues);
}
},
});
});
}
function renderIssues(container, issues) {
container.replaceChildren();
if (!issues || issues.length === 0) {
const p = document.createElement('p');
p.className = 'ws-muted';
p.textContent = 'No issues found.';
container.appendChild(p);
return;
}
for (let i = 0; i < issues.length; i++) {
const issue = issues[i];
const item = document.createElement('div');
item.className = 'ws-issue-item';
const type = document.createElement('div');
type.className = 'ws-issue-type';
type.textContent = (issue.type || 'grammar').toUpperCase();
item.appendChild(type);
const text = document.createElement('div');
text.className = 'ws-issue-text';
text.textContent = issue.message || issue.text || '';
item.appendChild(text);
if (issue.suggestion) {
const sug = document.createElement('div');
sug.className = 'ws-issue-suggestion';
sug.textContent = 'Suggestion: ' + issue.suggestion;
item.appendChild(sug);
}
const actions = document.createElement('div');
actions.className = 'ws-issue-actions';
for (const [, label] of [
['accept', 'Accept'],
['dismiss', 'Dismiss'],
]) {
const actionBtn = document.createElement('button');
actionBtn.className = 'ws-btn ws-btn-sm';
actionBtn.textContent = label;
actionBtn.addEventListener('click', () => {
item.remove();
});
actions.appendChild(actionBtn);
}
item.appendChild(actions);
container.appendChild(item);
}
}
module.exports = { renderProofreadPanel };
@@ -0,0 +1,85 @@
function renderSnapshotsPanel(container, { engines, editor }) {
const snapshots = engines.snapshots.list();
container.replaceChildren();
const panel = document.createElement('div');
panel.className = 'ws-panel';
// Header with take snapshot button
const section = document.createElement('div');
section.className = 'ws-section';
const btn = document.createElement('button');
btn.className = 'ws-btn ws-btn-primary';
btn.id = 'ws-take-snapshot';
btn.textContent = 'Take Snapshot';
section.appendChild(btn);
const count = document.createElement('span');
count.className = 'ws-muted';
count.textContent = snapshots.length + ' snapshots';
section.appendChild(count);
panel.appendChild(section);
// Snapshot list
const list = document.createElement('div');
list.className = 'ws-snapshot-list';
for (const s of snapshots) {
const item = document.createElement('div');
item.className = 'ws-snapshot-item';
const header = document.createElement('div');
header.className = 'ws-snapshot-header';
const sLabel = document.createElement('span');
sLabel.className = 'ws-snapshot-label';
sLabel.textContent = s.label;
const sWords = document.createElement('span');
sWords.textContent = s.wordCount + ' words';
header.appendChild(sLabel);
header.appendChild(sWords);
item.appendChild(header);
const time = document.createElement('div');
time.className = 'ws-snapshot-time';
time.textContent = new Date(s.timestamp).toLocaleString();
item.appendChild(time);
const actions = document.createElement('div');
actions.className = 'ws-snapshot-actions';
for (const [action, text, cls] of [
['restore', 'Restore', ''],
['diff', 'Diff', ''],
['delete', 'Delete', 'ws-btn-danger'],
]) {
const actionBtn = document.createElement('button');
actionBtn.className = 'ws-btn ws-btn-sm' + (cls ? ' ' + cls : '');
actionBtn.textContent = text;
actionBtn.addEventListener('click', () => {
if (action === 'restore') {
const content = engines.snapshots.restore(s.id);
editor.insertAtCursor(content);
} else if (action === 'delete') {
engines.snapshots.delete(s.id);
renderSnapshotsPanel(container, { engines, editor });
} else if (action === 'diff') {
const current = editor.getContent() || '';
const result = engines.snapshots.diff(s.id, current);
alert('+' + result.added + ' lines added, -' + result.removed + ' lines removed');
}
});
actions.appendChild(actionBtn);
}
item.appendChild(actions);
list.appendChild(item);
}
panel.appendChild(list);
container.appendChild(panel);
// Take snapshot button handler
container.querySelector('#ws-take-snapshot').addEventListener('click', () => {
const content = editor.getContent() || '';
engines.snapshots.create(content, 'manual');
renderSnapshotsPanel(container, { engines, editor });
});
}
module.exports = { renderSnapshotsPanel };
@@ -0,0 +1,74 @@
class ProjectManager {
/**
* @param {object} fs - { readFile(path), writeFile(path, content), fileExists(path), listDir(path) }
*/
constructor(fs) {
this.fs = fs;
}
createProject(dir, opts) {
const project = {
title: opts.title,
type: opts.type || 'manuscript',
target: { words: opts.targetWords || 0, deadline: opts.deadline || null },
chapters: [],
metadata: opts.metadata || {},
};
this.fs.writeFile(dir + '/.project.json', JSON.stringify(project, null, 2));
return project;
}
loadProject(dir) {
const raw = this.fs.readFile(dir + '/.project.json');
if (!raw) return null;
return JSON.parse(raw);
}
_saveProject(dir, project) {
this.fs.writeFile(dir + '/.project.json', JSON.stringify(project, null, 2));
}
addChapter(dir, chapter) {
const project = this.loadProject(dir);
if (!project) throw new Error('Project not found');
project.chapters.push(chapter);
this._saveProject(dir, project);
}
updateChapter(dir, index, updates) {
const project = this.loadProject(dir);
if (!project) throw new Error('Project not found');
Object.assign(project.chapters[index], updates);
this._saveProject(dir, project);
}
compileManuscript(dir) {
const project = this.loadProject(dir);
if (!project) throw new Error('Project not found');
const parts = [];
for (const ch of project.chapters) {
const content = this.fs.readFile(dir + '/' + ch.file);
if (content) parts.push(content);
}
return parts.join('\n\n---\n\n');
}
getStats(dir) {
const project = this.loadProject(dir);
if (!project) throw new Error('Project not found');
let totalWords = 0;
for (const ch of project.chapters) {
const content = this.fs.readFile(dir + '/' + ch.file);
if (content) totalWords += content.split(/\s+/).filter(Boolean).length;
}
const target = project.target.words || 0;
return {
totalWords,
chapterCount: project.chapters.length,
targetWords: target,
pctComplete: target > 0 ? Math.min(100, Math.round((totalWords / target) * 100)) : 0,
};
}
}
module.exports = { ProjectManager };
@@ -0,0 +1,77 @@
class SnapshotManager {
/**
* @param {object} store - { get(key), set(key, value) }
* @param {string} storeKey - settings key for snapshots
*/
constructor(store, storeKey = 'plugins.writing-studio.snapshots') {
this.store = store;
this.storeKey = storeKey;
}
_getAll() {
const raw = this.store.get(this.storeKey);
return raw ? JSON.parse(raw) : [];
}
_saveAll(snaps) {
this.store.set(this.storeKey, JSON.stringify(snaps));
}
create(content, label = 'manual') {
const snaps = this._getAll();
const snap = {
id: 'snap-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8),
timestamp: new Date().toISOString(),
content,
wordCount: content.split(/\s+/).filter(Boolean).length,
label,
};
snaps.unshift(snap);
this._saveAll(snaps);
return snap;
}
list() {
return this._getAll();
}
getById(id) {
return this._getAll().find((s) => s.id === id) || null;
}
restore(id) {
const snap = this.getById(id);
if (!snap) throw new Error('Snapshot not found');
return snap.content;
}
delete(id) {
const snaps = this._getAll().filter((s) => s.id !== id);
this._saveAll(snaps);
}
diff(id, currentContent) {
const snap = this.getById(id);
if (!snap) throw new Error('Snapshot not found');
const oldLines = snap.content.split('\n');
const newLines = currentContent.split('\n');
const oldSet = new Set(oldLines);
const newSet = new Set(newLines);
let added = 0;
let removed = 0;
for (const line of newLines) {
if (!oldSet.has(line)) added++;
}
for (const line of oldLines) {
if (!newSet.has(line)) removed++;
}
return { added, removed };
}
prune(keepCount) {
const snaps = this._getAll();
this._saveAll(snaps.slice(0, keepCount));
}
}
module.exports = { SnapshotManager };
@@ -0,0 +1,53 @@
class SprintEngine {
/**
* @param {object} opts
* @param {function} opts.onEvent - callback(event_name, data)
*/
constructor(opts = {}) {
this.onEvent = opts.onEvent || (() => {});
this._active = false;
this._startTime = null;
this._duration = 0;
this._initialWords = 0;
}
start(durationMinutes, currentWordCount) {
if (this._active) throw new Error('Sprint already active');
this._active = true;
this._startTime = Date.now();
this._duration = durationMinutes * 60 * 1000;
this._initialWords = currentWordCount;
}
stop(currentWordCount) {
if (!this._active) throw new Error('No active sprint');
const elapsed = Date.now() - this._startTime;
const wordDelta = Math.max(0, currentWordCount - this._initialWords);
const elapsedMinutes = elapsed / 60000;
const wpm = elapsedMinutes > 0 ? Math.round(wordDelta / elapsedMinutes) : 0;
this._active = false;
this._startTime = null;
return { wordDelta, elapsed, wpm };
}
tick(elapsedMs) {
if (!this._active) return;
const remaining = Math.max(0, this._duration - elapsedMs);
this.onEvent('sprint:tick', { remaining, elapsed: elapsedMs });
if (remaining <= 0) {
this._active = false;
this.onEvent('sprint:complete', { expired: true });
}
}
isActive() {
return this._active;
}
getRemaining() {
if (!this._active) return 0;
return Math.max(0, this._duration - (Date.now() - this._startTime));
}
}
module.exports = { SprintEngine };
+43
View File
@@ -0,0 +1,43 @@
class EventBus {
constructor() {
this.listeners = new Map();
}
on(event, handler) {
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event).push(handler);
}
off(event, handler) {
if (!handler) {
this.listeners.delete(event);
return;
}
const handlers = this.listeners.get(event);
if (handlers) {
const idx = handlers.indexOf(handler);
if (idx !== -1) handlers.splice(idx, 1);
}
}
emit(event, payload) {
const handlers = this.listeners.get(event);
if (!handlers) return;
for (const handler of handlers) {
try {
handler(payload);
} catch (err) {
console.error(`[EventBus] Error in handler for "${event}":`, err);
}
}
}
hasHandler(event) {
const handlers = this.listeners.get(event);
return handlers !== undefined && handlers !== null && handlers.length > 0;
}
}
module.exports = { EventBus };
+40
View File
@@ -0,0 +1,40 @@
/**
* FormatRegistry — tracks export formats registered by plugins via
* `context.formats.registerExportFormat(id, opts)`.
*
* Mirrors the simple Map-backed storage pattern used by PluginRegistry
* (see plugin-registry.js), scoped to a single concern: export format
* metadata + handler functions rather than whole plugin instances.
*/
class FormatRegistry {
constructor() {
this.formats = new Map();
}
/**
* Register (or overwrite) an export format entry.
* @param {string} id - Fully-namespaced format id, e.g. "writing-studio:sprint-summary"
* @param {object} opts - { label, extension, handler: async (markdownContent, outputPath, options) => void }
*/
register(id, opts) {
this.formats.set(id, opts);
}
/**
* Look up a single registered format entry by its namespaced id.
* @param {string} id
* @returns {object|undefined}
*/
get(id) {
return this.formats.get(id);
}
/**
* Return all registered formats as an array of { id, ...opts }.
*/
getAll() {
return Array.from(this.formats.entries()).map(([id, opts]) => ({ id, ...opts }));
}
}
module.exports = { FormatRegistry };
+23
View File
@@ -0,0 +1,23 @@
class PluginAPI {
/**
* Called when the plugin is discovered and loaded.
* Receives a scoped context object with APIs.
* @param {object} context - Plugin context (sidebar, commands, settings, etc.)
*/
init(context) {
this.context = context;
}
/** Called when the plugin is activated (e.g., sidebar panel clicked). */
activate() {}
/** Called when the plugin is deactivated. */
deactivate() {}
/** Returns the parsed manifest.json for this plugin. */
getManifest() {
return this._manifest || null;
}
}
module.exports = { PluginAPI };
+99
View File
@@ -0,0 +1,99 @@
class PluginContext {
/**
* @param {object} deps - Injected dependencies
* @param {string} deps.pluginId - Plugin unique ID (for namespacing)
* @param {object} deps.sidebar - SidebarManager.registerPanel
* @param {object} deps.commands - CommandPalette.register
* @param {object} deps.statusBar - StatusBar.registerIndicator
* @param {object} deps.eventBus - EventBus instance
* @param {object} deps.settings - { get, set, onChanged }
* @param {object} deps.editor - { getContent, getSelection, insertAtCursor, onContentChanged }
* @param {object} deps.ipc - { invoke, on }
* @param {object} deps.exportHooks - { preHooks: [], postHooks: [] }
* @param {object} deps.formatRegistry - FormatRegistry instance ({ register, get, getAll })
*/
constructor(deps) {
const {
pluginId,
sidebar,
commands,
statusBar,
eventBus,
settings,
editor,
ipc,
exportHooks,
formatRegistry,
} = deps;
this.sidebar = {
registerPanel: (id, opts) => sidebar.registerPanel(`${pluginId}:${id}`, opts),
};
this.commands = {
register: (id, label, handler, shortcut) => {
const safeHandler = (...args) => {
try {
handler(...args);
} catch (err) {
console.error(`[Plugin:${pluginId}] Command "${id}" error:`, err);
}
};
commands.register(`${pluginId}:${id}`, label, safeHandler, shortcut);
},
};
this.statusBar = {
registerIndicator: (id, opts) => statusBar.registerIndicator(`${pluginId}:${id}`, opts),
};
this.settings = {
get: (key) => settings.get(`plugins.${pluginId}.${key}`),
set: (key, value) => settings.set(`plugins.${pluginId}.${key}`, value),
onChanged: (key, cb) => settings.onChanged(`plugins.${pluginId}.${key}`, cb),
};
this.editor = {
getContent: () => editor.getContent(),
getSelection: () => editor.getSelection(),
insertAtCursor: (text) => editor.insertAtCursor(text),
onContentChanged: (cb) => editor.onContentChanged(cb),
};
this.events = {
on: (event, handler) => eventBus.on(event, handler),
off: (event, handler) => eventBus.off(event, handler),
emit: (event, payload) => eventBus.emit(event, payload),
hasHandler: (event) => eventBus.hasHandler(event),
};
this.ipc = {
invoke: (channel, ...args) => ipc.invoke(channel, ...args),
on: (channel, handler) => ipc.on(channel, handler),
};
this.exports = {
registerPreHook: (handler) => {
if (exportHooks) exportHooks.preHooks.push(handler);
},
registerPostHook: (handler) => {
if (exportHooks) exportHooks.postHooks.push(handler);
},
};
this.formats = {
/**
* Register a plugin-provided export format. It is namespaced as
* `${pluginId}:${id}` so plugins can't collide with each other or
* with the built-in Pandoc-backed formats.
* @param {string} id - Format id, unique within this plugin.
* @param {object} opts - { label, extension, handler: async (markdownContent, outputPath, options) => void }
*/
registerExportFormat: (id, opts) => {
if (formatRegistry) formatRegistry.register(`${pluginId}:${id}`, opts);
},
};
}
}
module.exports = { PluginContext };
+78
View File
@@ -0,0 +1,78 @@
const fs = require('fs');
const path = require('path');
class PluginLoader {
/**
* @param {string[]} searchDirs - Directories to scan for plugin folders
*/
constructor(searchDirs = []) {
this.searchDirs = searchDirs;
this.loadedIds = new Set();
}
/**
* Discover plugins by scanning searchDirs for manifest.json files.
* Returns array of { id, name, version, description, manifest, PluginClass, dir }
*/
discoverPlugins() {
const plugins = [];
for (const dir of this.searchDirs) {
if (!fs.existsSync(dir)) continue;
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const pluginDir = path.join(dir, entry.name);
const manifestPath = path.join(pluginDir, 'manifest.json');
if (!fs.existsSync(manifestPath)) continue;
try {
const raw = fs.readFileSync(manifestPath, 'utf-8');
const manifest = JSON.parse(raw);
this.validateManifest(manifest);
let PluginClass = null;
const indexPath = path.join(pluginDir, 'index.js');
if (fs.existsSync(indexPath)) {
try {
const loaded = require(indexPath);
PluginClass = loaded.Plugin || loaded.default || null;
} catch (err) {
console.error(
`[PluginLoader] Failed to load index.js for "${manifest.id}":`,
err.message
);
continue;
}
}
plugins.push({
id: manifest.id,
name: manifest.name,
version: manifest.version,
description: manifest.description,
manifest,
PluginClass,
dir: pluginDir,
});
this.loadedIds.add(manifest.id);
} catch (err) {
console.error(`[PluginLoader] Skipping plugin in ${pluginDir}:`, err.message);
}
}
}
return plugins;
}
/**
* Validate a manifest object. Throws on invalid.
*/
validateManifest(manifest) {
if (!manifest.id) throw new Error('Manifest missing required field: id');
if (!manifest.name) throw new Error('Manifest missing required field: name');
if (!manifest.version) throw new Error('Manifest missing required field: version');
if (!manifest.description) throw new Error('Manifest missing required field: description');
if (this.loadedIds.has(manifest.id)) {
throw new Error(`Duplicate plugin id: "${manifest.id}"`);
}
return true;
}
}
module.exports = { PluginLoader };
+81
View File
@@ -0,0 +1,81 @@
const { PluginContext } = require('./plugin-context');
const { PluginAPI } = require('./plugin-api');
class PluginRegistry {
constructor(deps) {
this.deps = deps;
this.plugins = new Map();
this.exportHooks = { preHooks: [], postHooks: [] };
}
/**
* Register a discovered plugin. Creates instance, builds context, calls init.
* If init throws, plugin is NOT registered.
*/
register(pluginInfo) {
const { id, name, version, description, manifest, PluginClass, dir } = pluginInfo;
let instance;
if (PluginClass) {
instance = new PluginClass();
} else {
instance = new PluginAPI();
}
instance._manifest = manifest;
const context = new PluginContext({
pluginId: id,
sidebar: this.deps.sidebar,
commands: this.deps.commands,
statusBar: this.deps.statusBar,
eventBus: this.deps.eventBus,
settings: this.deps.settings,
editor: this.deps.editor,
ipc: this.deps.ipc,
exportHooks: this.exportHooks,
formatRegistry: this.deps.formatRegistry,
});
try {
instance.init(context);
} catch (err) {
console.error(`[PluginRegistry] Plugin "${id}" init failed:`, err.message);
return;
}
this.plugins.set(id, { id, name, version, description, manifest, instance, dir, context });
console.log(`[PluginRegistry] Registered plugin: ${name} v${version}`);
}
getPlugin(id) {
return this.plugins.get(id);
}
getAll() {
return Array.from(this.plugins.values());
}
activate(id) {
const plugin = this.plugins.get(id);
if (plugin?.instance) {
try {
plugin.instance.activate();
} catch (err) {
console.error(`[PluginRegistry] Plugin "${id}" activate error:`, err.message);
}
}
}
deactivate(id) {
const plugin = this.plugins.get(id);
if (plugin?.instance) {
try {
plugin.instance.deactivate();
} catch (err) {
console.error(`[PluginRegistry] Plugin "${id}" deactivate error:`, err.message);
}
}
}
}
module.exports = { PluginRegistry };
+23
View File
@@ -0,0 +1,23 @@
class SettingsStore {
/**
* @param {object} backend - { get(key), set(key, value) } backed by main process store
*/
constructor(backend) {
this.backend = backend;
}
get(key) {
return this.backend.get(key);
}
set(key, value) {
this.backend.set(key, value);
}
onChanged(_key, _callback) {
// Deferred: plugins read settings on init/activate for MVP.
// Full change notification requires IPC watcher in main process.
}
}
module.exports = { SettingsStore };
+159 -64
View File
@@ -9,10 +9,10 @@
* - All IPC channels are explicitly whitelisted
* - Prevents XSS from escalating to full system access
*
* @version 2.2.0
* @version 4.4.1
*/
const { contextBridge, ipcRenderer } = require('electron');
const { contextBridge, ipcRenderer, webUtils } = require('electron');
// Define allowed IPC channels for security
const ALLOWED_SEND_CHANNELS = [
@@ -23,17 +23,23 @@ const ALLOWED_SEND_CHANNELS = [
'save-recent-files',
'clear-recent-files',
'renderer-ready',
'select-custom-css',
// Theme
'get-theme',
// Print
'do-print',
'do-print-with-options',
// Export
'export-with-options',
'export-spreadsheet',
// Plugin export formats
'plugin-export-formats-registered',
'plugin-export-format-result',
// Batch conversion
'batch-convert',
'select-folder',
@@ -43,26 +49,17 @@ const ALLOWED_SEND_CHANNELS = [
'universal-convert-batch',
// Image converter
'image-convert',
'image-batch-convert',
'image-resize',
'image-compress',
'image-rotate',
'process-image-operation',
'select-image-folder',
'batch-image-operation',
// Audio converter
'audio-convert',
'audio-batch-convert',
'audio-extract',
'audio-trim',
'audio-merge',
'process-audio-operation',
'batch-audio-operation',
// Video converter
'video-convert',
'video-batch-convert',
'video-compress',
'video-trim',
'video-frames',
'video-gif',
'process-video-operation',
'batch-video-operation',
// Header/Footer
'get-header-footer-settings',
@@ -71,17 +68,28 @@ const ALLOWED_SEND_CHANNELS = [
'save-header-footer-logo',
'clear-header-footer-logo',
// Word template settings
'get-word-template-settings',
'save-word-template-settings',
'browse-word-template',
'clear-word-template',
// Export presets (invoke channels — gated by this same array)
'get-export-presets',
'save-export-preset',
'delete-export-preset',
// Page settings
'get-page-settings',
'update-page-settings',
// Template settings
'set-custom-start-page',
// PDF operations
'process-pdf-operation',
'get-pdf-page-count',
'get-pdf-form-fields',
'get-pdf-capabilities',
'select-pdf-folder',
'batch-pdf-operation',
// ASCII generator (separate window)
'open-ascii-generator',
@@ -90,7 +98,63 @@ const ALLOWED_SEND_CHANNELS = [
'open-table-generator',
// Insert generated content
'insert-generated-content'
'insert-generated-content',
// Image paste/drop
'save-pasted-image',
// Templates
'load-template',
// File Explorer
'list-directory',
'read-file',
'write-file',
'delete-file',
'ensure-directory',
'path-exists',
'is-directory',
'copy-path',
'move-path',
// Git
'git-status',
'git-stage',
'git-commit',
'git-log',
'git-branches',
'git-checkout',
'git-push',
'git-pull',
// Snippets
'get-snippets',
'save-snippet',
'delete-snippet',
// Code execution (REPL)
'execute-code',
// File open by path
'open-file-path',
// PDF editor from toolbar
'show-pdf-editor-from-toolbar',
// Menu triggers
'menu-open',
'export',
// Git diff
'git-diff',
// Plugin settings
'plugin-settings:get',
'plugin-settings:set',
// Monospace font settings
'get-monospace-settings',
'set-monospace-settings',
];
const ALLOWED_RECEIVE_CHANNELS = [
@@ -101,6 +165,8 @@ const ALLOWED_RECEIVE_CHANNELS = [
'get-content-for-save',
'get-content-for-spreadsheet',
'recent-files-cleared',
'load-custom-css',
'clear-custom-css',
// UI toggles
'toggle-preview',
@@ -116,6 +182,7 @@ const ALLOWED_RECEIVE_CHANNELS = [
// Font
'adjust-font-size',
'monospace-setting-change',
// Print
'print-preview',
@@ -127,6 +194,7 @@ const ALLOWED_RECEIVE_CHANNELS = [
'show-universal-converter-dialog',
'show-table-generator',
'show-pdf-editor-dialog',
'show-document-compare',
// Converter dialogs
'show-image-converter',
@@ -144,22 +212,34 @@ const ALLOWED_RECEIVE_CHANNELS = [
'audio-conversion-complete',
'video-conversion-complete',
// Batch media operations (Image/Audio/Video Tools dialog batch mode)
'media-batch-progress',
'media-batch-complete',
// Folder selection
'folder-selected',
'pdf-folder-selected',
'image-folder-selected',
// Header/Footer
'header-footer-settings-data',
'header-footer-logo-selected',
'header-footer-logo-saved',
// Word template settings
'word-template-settings-data',
'word-template-browsed',
'open-word-template-dialog',
// Page settings
'page-settings-data',
// PDF operations
'pdf-page-count',
'pdf-form-fields',
'pdf-operation-complete',
'pdf-operation-error',
'pdf-batch-complete',
// ASCII Art Generator
'show-ascii-generator-window',
@@ -176,7 +256,19 @@ const ALLOWED_RECEIVE_CHANNELS = [
'pdf-operation-progress',
// Insert content from generator windows
'insert-content'
'insert-content',
// Batch converter
'show-batch-converter',
// v4 menu-triggered events
'load-template-menu',
'toggle-command-palette',
'toggle-sidebar-panel',
'toggle-bottom-panel',
// Plugin export formats
'run-plugin-export-format',
];
/**
@@ -275,23 +367,31 @@ contextBridge.exposeInMainWorld('electronAPI', {
setCurrent: (filePath) => ipcRenderer.send('set-current-file', filePath),
saveRecent: (recentFiles) => ipcRenderer.send('save-recent-files', recentFiles),
clearRecent: () => ipcRenderer.send('clear-recent-files'),
rendererReady: () => ipcRenderer.send('renderer-ready')
rendererReady: () => ipcRenderer.send('renderer-ready'),
read: (filePath) => ipcRenderer.invoke('read-file', filePath),
write: (filePath, content) => ipcRenderer.invoke('write-file', { path: filePath, content }),
delete: (filePath) => ipcRenderer.invoke('delete-file', filePath),
ensureDir: (dirPath) => ipcRenderer.invoke('ensure-directory', dirPath),
exists: (filePath) => ipcRenderer.invoke('path-exists', filePath),
isDirectory: (filePath) => ipcRenderer.invoke('is-directory', filePath),
copy: (source, destination) => ipcRenderer.invoke('copy-path', { source, destination }),
move: (source, destination) => ipcRenderer.invoke('move-path', { source, destination }),
},
// Theme Operations
theme: {
get: () => ipcRenderer.send('get-theme')
get: () => ipcRenderer.send('get-theme'),
},
// Print Operations
print: {
doPrint: (options) => ipcRenderer.send('do-print', options)
doPrint: (options) => ipcRenderer.send('do-print', options),
},
// Export Operations
export: {
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
@@ -299,7 +399,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
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
@@ -308,8 +408,14 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath });
},
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
@@ -317,57 +423,46 @@ contextBridge.exposeInMainWorld('electronAPI', {
getSettings: () => ipcRenderer.send('get-header-footer-settings'),
saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings),
browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position),
saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }),
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position)
saveLogo: (position, filePath) =>
ipcRenderer.send('save-header-footer-logo', { position, filePath }),
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position),
},
// Page Settings
page: {
getSettings: () => ipcRenderer.send('get-page-settings'),
updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings),
setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber)
},
/**
* Resolve a File object chosen via `<input type="file">` to its absolute
* path. `File.path` was removed in Electron 32; `webUtils.getPathForFile`
* is its replacement. Falls back to `file.path` on older Electron where
* webUtils is unavailable.
* @param {File} file - File object from a file input's files list
* @returns {string | undefined} Absolute filesystem path when resolvable
*/
getFilePath: (file) => {
if (webUtils && typeof webUtils.getPathForFile === 'function') {
return webUtils.getPathForFile(file);
}
return file && file.path;
},
// PDF Operations
pdf: {
processOperation: (data) => ipcRenderer.send('process-pdf-operation', data),
getPageCount: (filePath) => ipcRenderer.send('get-pdf-page-count', filePath),
selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId)
},
// Image Converter Operations
image: {
convert: (data) => ipcRenderer.send('image-convert', data),
batchConvert: (data) => ipcRenderer.send('image-batch-convert', data),
resize: (data) => ipcRenderer.send('image-resize', data),
compress: (data) => ipcRenderer.send('image-compress', data),
rotate: (data) => ipcRenderer.send('image-rotate', data)
},
// Audio Converter Operations
audio: {
convert: (data) => ipcRenderer.send('audio-convert', data),
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
extract: (data) => ipcRenderer.send('audio-extract', data),
trim: (data) => ipcRenderer.send('audio-trim', data),
merge: (data) => ipcRenderer.send('audio-merge', data)
},
// Video Converter Operations
video: {
convert: (data) => ipcRenderer.send('video-convert', data),
batchConvert: (data) => ipcRenderer.send('video-batch-convert', data),
compress: (data) => ipcRenderer.send('video-compress', data),
trim: (data) => ipcRenderer.send('video-trim', data),
extractFrames: (data) => ipcRenderer.send('video-frames', data),
toGif: (data) => ipcRenderer.send('video-gif', data)
selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId),
},
// Generator Windows
generators: {
openAscii: () => ipcRenderer.send('open-ascii-generator'),
openTable: () => ipcRenderer.send('open-table-generator')
}
openTable: () => ipcRenderer.send('open-table-generator'),
},
getAppVersion: () => ipcRenderer.invoke('get-app-version'),
});
// Log successful preload initialization
+203
View File
@@ -0,0 +1,203 @@
const fs = require('fs');
const path = require('path');
function getBundledFontWoff2Path(familyKey, weight) {
// Renderer can read directly from disk because nodeIntegration is on.
// Try repo-relative first, then packaged app.asar mirror.
const familyDir = familyKey === 'fira-code' ? 'FiraCode' : 'JetBrainsMono';
const weightName = weight >= 700 ? 'Bold' : 'Regular';
const filename = `${familyDir}-${weightName}.woff2`;
const repoPath = path.resolve(__dirname, '..', 'assets', 'fonts', filename);
if (fs.existsSync(repoPath)) return repoPath;
// Packaged: under <resourcesPath>/assets/fonts/
if (process.resourcesPath) {
const packaged = path.join(process.resourcesPath, 'assets', 'fonts', filename);
if (fs.existsSync(packaged)) return packaged;
}
return null;
}
function buildFontFaceBlock(familyKey) {
const family = familyKey === 'fira-code' ? 'Fira Code' : 'JetBrains Mono';
const fontPath = getBundledFontWoff2Path(familyKey, 400);
if (!fontPath) return '';
try {
const data = fs.readFileSync(fontPath);
const dataUri = `data:font/woff2;base64,${data.toString('base64')}`;
return `@font-face { font-family: '${family}'; font-weight: 400; font-style: normal; src: url('${dataUri}') format('woff2'); }`;
} catch (err) {
// Non-fatal: fall back to the system monospace stack declared in styles-modern.css.
if (typeof console !== 'undefined')
console.warn('[print-preview] font embed failed:', err.message);
return '';
}
}
class PrintPreview {
constructor(monospaceSettings = {}) {
this.overlay = document.getElementById('print-preview-overlay');
this.modal = window.modals?.printPreviewModal;
this._lastContent = '';
this._monospaceSettings = {
monospaceFont: monospaceSettings.monospaceFont || 'jetbrains-mono',
monospaceLigatures: monospaceSettings.monospaceLigatures === true,
};
this.setupEventListeners();
}
setMonospaceSettings(settings) {
this._monospaceSettings = {
monospaceFont: (settings && settings.monospaceFont) || 'jetbrains-mono',
monospaceLigatures: !!(settings && settings.monospaceLigatures === true),
};
this.refreshPreview();
}
open(htmlContent) {
this._lastContent = htmlContent;
if (this.modal) {
this.modal.open();
} else {
this.overlay.classList.remove('hidden');
}
this.updatePreview(htmlContent);
this.updateScaleLabel();
}
close() {
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 family =
this._monospaceSettings.monospaceFont === 'fira-code' ? 'Fira Code' : 'JetBrains Mono';
const ligaturesOn = this._monospaceSettings.monospaceLigatures === true;
const featureSettings = ligaturesOn ? 'normal' : "'liga' 0, 'calt' 0, 'dlig' 0";
const fontFaceBlock = buildFontFaceBlock(this._monospaceSettings.monospaceFont);
const previewHtml = `
<!DOCTYPE html>
<html>
<head>
<style>
${fontFaceBlock}
body {
margin: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 14px;
line-height: 1.6;
}
@page { size: ${width} ${height}; }
pre, code, kbd, samp {
font-family: '${family}', monospace;
font-feature-settings: ${featureSettings};
}
pre {
background: #f5f5f5;
padding: 12px;
border-radius: 6px;
overflow-x: auto;
white-space: pre;
tab-size: 4;
}
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
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 };
+3705 -1639
View File
File diff suppressed because it is too large Load Diff
+343
View File
@@ -0,0 +1,343 @@
/**
* Document Compare Dialog
*
* Two-pane line diff opened from Tools > Document Compare (main.js sends
* `show-document-compare`; renderer.js registers the listener).
*
* Construction mirrors src/renderer/media-operations-dialog.js: a modal built from
* `.modal` / `.modal-content` / `.modal-header` / `.modal-body` / `.modal-footer`
* markup appended to document.body on first use, driven by ModalManager, with a
* status line reusing the `info-message` / `warning-message` classes. File
* selection reuses the app's existing convention: a plain `<input type="file">`
* whose chosen File is resolved to a path via `window.electronAPI.getFilePath`
* (webUtils.getPathForFile `File.path` was removed in Electron 32)
* no new IPC channel for picking files. File *contents* are read through the
* existing `read-file` invoke channel (the same one the renderer's electronAPI
* adapters use), not through a new privileged renderer-side file path.
*
* Two modes:
* - Local: File A (prefilled with the current tab's file, changeable) vs File B,
* diffed locally by the pure LCS function in src/utils/line-diff.js.
* - Git HEAD: the current file against its last commit, via the existing
* `git-diff` invoke channel with `againstHead: true` (GitOperations.diff).
* Git's own raw diff text is rendered verbatim, one row per line, colored by
* leading character it is already a diff and is never re-diffed through
* line-diff. When the current file is not inside a git repository (or no file
* is open), the option is disabled with a hint instead of erroring.
*
* @module document-compare-dialog
*/
const { ipcRenderer } = require('electron');
const { getFilePath } = require('../utils/file-path');
const { computeLineDiff } = require('../utils/line-diff');
const COMPARE_ACCEPT = '.md,.markdown,.txt,.text,.log,.json,.xml,.yml,.yaml,.csv';
const GIT_DIFF_ROW_CLASS = [
{ prefix: '@@', className: 'diff-hunk' },
{ prefix: '+++', className: 'diff-context' },
{ prefix: '---', className: 'diff-context' },
{ prefix: '+', className: 'diff-added' },
{ prefix: '-', className: 'diff-removed' },
];
let modalEl = null;
let modalManager = null;
let els = null;
let currentFilePath = null;
function buildDialogDom() {
modalEl = document.createElement('div');
modalEl.id = 'document-compare-dialog';
modalEl.className = 'modal hidden';
modalEl.setAttribute('role', 'dialog');
modalEl.setAttribute('aria-modal', 'true');
modalEl.setAttribute('aria-labelledby', 'document-compare-title');
modalEl.innerHTML = `
<div class="modal-backdrop" data-close></div>
<div class="modal-content large">
<div class="modal-header">
<h3 id="document-compare-title">Document Compare</h3>
<button class="modal-close" id="document-compare-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
<div class="export-section">
<label for="compare-mode-select">Mode:</label>
<select id="compare-mode-select">
<option value="local">Compare Two Files</option>
<option value="git">Compare Current File with Git HEAD</option>
</select>
<small id="compare-git-hint" class="hidden"></small>
</div>
<div id="compare-local-section">
<div class="export-section">
<label for="compare-file-a-input">File A (original):</label>
<div class="folder-input-group">
<input type="text" id="compare-file-a-input" readonly>
<button type="button" id="compare-file-a-browse">Choose File A</button>
</div>
</div>
<div class="export-section">
<label for="compare-file-b-input">File B (revised):</label>
<div class="folder-input-group">
<input type="text" id="compare-file-b-input" readonly>
<button type="button" id="compare-file-b-browse">Choose File B</button>
</div>
</div>
</div>
<div id="compare-git-section" class="hidden">
<div class="export-section">
<label>Current file:</label>
<code id="compare-git-file"></code>
</div>
</div>
<div id="compare-status-message" class="info-message hidden" aria-live="polite"></div>
<div id="compare-result" class="diff-view hidden"></div>
</div>
<div class="modal-footer">
<button id="document-compare-cancel" class="btn btn-secondary" data-close>Close</button>
<button id="document-compare-run" class="btn btn-primary">Compare</button>
</div>
</div>
`;
document.body.appendChild(modalEl);
els = {
modeSelect: modalEl.querySelector('#compare-mode-select'),
gitHint: modalEl.querySelector('#compare-git-hint'),
localSection: modalEl.querySelector('#compare-local-section'),
fileAInput: modalEl.querySelector('#compare-file-a-input'),
fileABrowse: modalEl.querySelector('#compare-file-a-browse'),
fileBInput: modalEl.querySelector('#compare-file-b-input'),
fileBBrowse: modalEl.querySelector('#compare-file-b-browse'),
gitSection: modalEl.querySelector('#compare-git-section'),
gitFile: modalEl.querySelector('#compare-git-file'),
status: modalEl.querySelector('#compare-status-message'),
result: modalEl.querySelector('#compare-result'),
runBtn: modalEl.querySelector('#document-compare-run'),
cancelBtn: modalEl.querySelector('#document-compare-cancel'),
};
els.modeSelect.addEventListener('change', updateModeSections);
els.fileABrowse.addEventListener('click', () => chooseFile(els.fileAInput));
els.fileBBrowse.addEventListener('click', () => chooseFile(els.fileBInput));
els.runBtn.addEventListener('click', handleCompare);
els.cancelBtn.addEventListener('click', hideDialog);
modalManager = new window.ModalManager(modalEl);
}
function ensureDialog() {
if (!modalEl) {
buildDialogDom();
}
}
// Same renderer-side picker the Media Operations and PDF Editor dialogs use.
function chooseFile(input) {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = COMPARE_ACCEPT;
fileInput.onchange = (e) => {
const file = e.target.files[0];
if (file) {
input.value = getFilePath(file);
clearResult();
}
};
fileInput.click();
}
function clearStatus() {
if (!els.status) return;
els.status.textContent = '';
els.status.classList.remove('info-message', 'warning-message', 'success-message');
els.status.classList.add('hidden');
}
function showStatus(message, type = 'info') {
if (!els.status) return;
els.status.textContent = message;
els.status.classList.remove('hidden', 'info-message', 'warning-message', 'success-message');
els.status.classList.add(`${type}-message`);
}
function clearResult() {
if (!els.result) return;
els.result.innerHTML = '';
els.result.classList.add('hidden');
}
function updateModeSections() {
const isGit = els.modeSelect.value === 'git';
els.localSection.classList.toggle('hidden', isGit);
els.gitSection.classList.toggle('hidden', !isGit);
clearStatus();
clearResult();
}
function appendDiffRow(className, text, marker) {
const row = document.createElement('div');
row.className = `diff-row ${className}`;
const markerSpan = document.createElement('span');
markerSpan.className = 'diff-marker';
markerSpan.textContent = marker;
const textSpan = document.createElement('span');
textSpan.className = 'diff-text';
// Non-breaking space keeps empty lines one row tall under pre-wrap.
textSpan.textContent = text === '' ? ' ' : text;
row.appendChild(markerSpan);
row.appendChild(textSpan);
els.result.appendChild(row);
}
// Mode 1: local two-file diff through the pure LCS line-diff function.
function renderLocalDiff(entries) {
clearResult();
entries.forEach((entry) => {
const marker = entry.type === 'added' ? '+' : entry.type === 'removed' ? '-' : '';
const rowClass = entry.type === 'unchanged' ? 'diff-context' : `diff-${entry.type}`;
appendDiffRow(rowClass, entry.text, marker);
});
els.result.classList.remove('hidden');
}
// Mode 2: git's own diff text, rendered verbatim (one row per line), colored by
// leading character. This is presentation only — the text is never re-diffed.
function renderGitDiff(rawDiff) {
clearResult();
rawDiff.split('\n').forEach((line) => {
const match = GIT_DIFF_ROW_CLASS.find(({ prefix }) => line.startsWith(prefix));
const className = match ? match.className : 'diff-context';
appendDiffRow(className, line, '');
});
els.result.classList.remove('hidden');
}
async function compareLocalFiles() {
const pathA = els.fileAInput.value.trim();
const pathB = els.fileBInput.value.trim();
if (!pathA || !pathB) {
showStatus('Choose both files to compare.', 'warning');
return;
}
clearStatus();
clearResult();
let contentA;
let contentB;
try {
contentA = await ipcRenderer.invoke('read-file', pathA);
contentB = await ipcRenderer.invoke('read-file', pathB);
} catch (err) {
showStatus(`Error reading file: ${err.message}`, 'warning');
return;
}
const entries = computeLineDiff(contentA, contentB);
const added = entries.filter((entry) => entry.type === 'added').length;
const removed = entries.filter((entry) => entry.type === 'removed').length;
if (added === 0 && removed === 0) {
showStatus('Files are identical.', 'info');
return;
}
renderLocalDiff(entries);
showStatus(`${added} line(s) added, ${removed} line(s) removed.`, 'success');
}
async function compareWithGitHead() {
if (!currentFilePath) {
showStatus('No file is open — save the current document first.', 'warning');
return;
}
clearStatus();
clearResult();
let rawDiff;
try {
rawDiff = await ipcRenderer.invoke('git-diff', { file: currentFilePath, againstHead: true });
} catch (err) {
showStatus(`Error: ${err.message}`, 'warning');
return;
}
if (rawDiff && typeof rawDiff === 'object' && rawDiff.error) {
showStatus(`Git diff unavailable: ${rawDiff.error}`, 'warning');
return;
}
if (!rawDiff || rawDiff.trim() === '') {
showStatus('No differences against HEAD.', 'info');
return;
}
renderGitDiff(rawDiff);
}
async function handleCompare() {
if (els.modeSelect.value === 'git') {
await compareWithGitHead();
} else {
await compareLocalFiles();
}
}
// The Git HEAD option must degrade gracefully (disabled + hint), never error:
// no file open, or the file's directory is not a git repository.
async function refreshGitModeAvailability() {
const gitOption = els.modeSelect.querySelector('option[value="git"]');
if (!gitOption) return;
const disableGitOption = (hint) => {
gitOption.disabled = true;
els.gitHint.textContent = hint;
els.gitHint.classList.remove('hidden');
if (els.modeSelect.value === 'git') {
els.modeSelect.value = 'local';
updateModeSections();
}
};
if (!currentFilePath) {
disableGitOption('Open (or save) a file to compare it with its git history.');
return;
}
try {
const status = await ipcRenderer.invoke('git-status');
if (status && typeof status === 'object' && status.error) {
disableGitOption('Current file is not inside a git repository.');
return;
}
} catch (err) {
disableGitOption(`Git check failed: ${err.message}`);
return;
}
gitOption.disabled = false;
els.gitHint.textContent = '';
els.gitHint.classList.add('hidden');
}
function hideDialog() {
if (modalManager) modalManager.close();
clearStatus();
clearResult();
}
/**
* Open the Document Compare dialog.
* @param {object} [context] - Current editor context from renderer.js.
* @param {string|null} [context.filePath] - Active tab's file path, used to
* prefill File A and to resolve the Git HEAD mode.
*/
function showDocumentCompareDialog({ filePath = null } = {}) {
ensureDialog();
currentFilePath = filePath;
els.fileAInput.value = filePath || '';
els.fileBInput.value = '';
els.gitFile.textContent = filePath || '(unsaved document)';
els.modeSelect.value = 'local';
updateModeSections();
refreshGitModeAvailability();
modalManager.open();
}
module.exports = { showDocumentCompareDialog };
+524
View File
@@ -0,0 +1,524 @@
/**
* Export Presets UI
*
* Preset dropdown + "Save as preset" for the export-options dialog
* (#export-dialog in src/index.html). Replaces the earlier localStorage-only
* "export profiles": presets are now owned by the main process and persisted
* in settings.json (`exportPresets` key) through three invoke channels
* get-export-presets / save-export-preset / delete-export-preset so they
* behave like every other app setting instead of living and dying with the
* renderer's localStorage.
*
* Construction mirrors src/renderer/document-compare-dialog.js: a dialog
* module in src/renderer/ using the raw `ipcRenderer` invoke surface
* (nodeIntegration is enabled for this renderer). DOM is hand-rolled a
* button + row list instead of a native <select> so each preset row can carry
* its own delete icon.
*
* The dialog markup lives in src/index.html; renderer.js calls
* initExportPresets() once at startup and refreshExportPresets() whenever the
* export dialog opens.
*/
const { ipcRenderer } = require('electron');
// localStorage key of the pre-4.x renderer-only "export profiles" that the
// preset system replaced; consumed once by importLegacyProfiles().
const LEGACY_PROFILES_KEY = 'exportProfiles';
let currentPresets = [];
let selectedPresetId = null;
let notify = (message, type) => console.warn(`Export presets (${type}): ${message}`);
// ============================================
// DOM helpers (all element access is guarded —
// this module may outlive a dialog re-render)
// ============================================
function elementById(id) {
return document.getElementById(id);
}
function valueOf(id) {
const el = elementById(id);
return el ? el.value : '';
}
function setValue(id, value) {
const el = elementById(id);
if (el) el.value = value;
}
function isChecked(id) {
const el = elementById(id);
return !!(el && el.checked);
}
function setChecked(id, checked) {
const el = elementById(id);
if (el) el.checked = checked;
}
function setVisible(id, visible) {
const el = elementById(id);
if (el) el.style.display = visible ? 'block' : 'none';
}
function getDialogFormat() {
const dialogEl = elementById('export-dialog');
return dialogEl ? dialogEl.getAttribute('data-format') : null;
}
// ============================================
// Capture / restore of the dialog's option values
// ============================================
/**
* Snapshot every option field of the export dialog into a plain object.
* Side-effect free (unlike collectExportOptions in renderer.js, which also
* pushes page settings to the main process) the snapshot is stored as the
* preset's `options` and replayed by applyPresetToDialog().
* @returns {Object} options snapshot
*/
function captureDialogOptions() {
const format = getDialogFormat();
const advancedMode = isChecked('advanced-export-toggle');
const options = {
advancedMode,
pageSize: valueOf('page-size'),
pageOrientation: valueOf('page-orientation'),
customWidth: valueOf('custom-width').trim() || null,
customHeight: valueOf('custom-height').trim() || null,
};
if (!advancedMode) {
options.toc = isChecked('basic-toc');
options.numberSections = isChecked('basic-number-sections');
return options;
}
const template = valueOf('export-template');
options.template = template === 'custom' ? valueOf('custom-template-path').trim() : template;
options.metadata = {};
document.querySelectorAll('.metadata-field').forEach((field) => {
const key = field.querySelector('.metadata-key').value.trim();
const value = field.querySelector('.metadata-value').value.trim();
if (key && value) options.metadata[key] = value;
});
options.toc = isChecked('export-toc');
options.tocDepth = valueOf('export-toc-depth') || '3';
options.numberSections = isChecked('export-number-sections');
options.citeproc = isChecked('export-citeproc');
if (format === 'pdf') {
options.pdfEngine = valueOf('pdf-engine');
const geometrySelect = valueOf('pdf-geometry');
options.geometry =
geometrySelect === 'custom'
? valueOf('custom-geometry').trim() || 'margin=1in'
: geometrySelect;
}
if (format === 'revealjs') {
options.revealTheme = valueOf('reveal-theme');
options.revealTransition = valueOf('reveal-transition');
options.revealTransitionSpeed = valueOf('reveal-speed');
options.revealSlideNumber = isChecked('reveal-slide-number');
options.revealControls = isChecked('reveal-controls');
options.revealProgress = isChecked('reveal-progress');
options.revealHistory = isChecked('reveal-history');
options.revealCenter = isChecked('reveal-center');
}
const bibliography = valueOf('bibliography-file').trim();
const csl = valueOf('csl-file').trim();
if (bibliography) options.bibliography = bibliography;
if (csl) options.csl = csl;
return options;
}
/**
* Restore a preset's option snapshot onto the dialog. Every field is written
* explicitly (preset value or the dialog default), so switching from a rich
* preset to a plain one clears whatever the rich one had set.
* @param {{options?: Object}} preset preset to apply
*/
function applyPresetToDialog(preset) {
const options = (preset && preset.options) || {};
const advancedMode = options.advancedMode === true;
setChecked('advanced-export-toggle', advancedMode);
const advancedSection = elementById('advanced-export-options');
if (advancedSection) advancedSection.classList.toggle('hidden', !advancedMode);
// Page setup (applies to both modes)
setValue('page-size', options.pageSize || 'a4');
setValue('page-orientation', options.pageOrientation || 'portrait');
setValue('custom-width', options.customWidth || '');
setValue('custom-height', options.customHeight || '');
setVisible('custom-page-size', valueOf('page-size') === 'custom');
setChecked('basic-toc', !advancedMode && options.toc === true);
setChecked('basic-number-sections', !advancedMode && options.numberSections === true);
// In basic mode the advanced-only fields are reset to their defaults so no
// stale values from a previously applied rich preset survive the switch.
const advancedOptions = advancedMode ? options : {};
// Template: anything other than the literal default is a custom path
const template =
advancedOptions.template && advancedOptions.template !== 'default'
? advancedOptions.template
: null;
if (template) {
setValue('export-template', 'custom');
setValue('custom-template-path', template);
setVisible('custom-template-path', true);
setVisible('template-file-input', true);
} else {
setValue('export-template', 'default');
setValue('custom-template-path', '');
setVisible('custom-template-path', false);
setVisible('template-file-input', false);
}
rebuildMetadataRows(advancedOptions.metadata || {});
setChecked('export-toc', advancedOptions.toc === true);
setValue('export-toc-depth', advancedOptions.tocDepth || '3');
setChecked('export-number-sections', advancedOptions.numberSections === true);
setChecked('export-citeproc', advancedOptions.citeproc === true);
// PDF options
setValue('pdf-engine', advancedOptions.pdfEngine || 'xelatex');
const geometry = advancedOptions.geometry || 'margin=1in';
const geometrySelect = elementById('pdf-geometry');
const hasGeometryOption =
geometrySelect && Array.from(geometrySelect.options).some((opt) => opt.value === geometry);
if (hasGeometryOption) {
setValue('pdf-geometry', geometry);
setValue('custom-geometry', '');
setVisible('custom-geometry', false);
} else {
setValue('pdf-geometry', 'custom');
setValue('custom-geometry', geometry);
setVisible('custom-geometry', true);
}
// Reveal.js options
setValue('reveal-theme', advancedOptions.revealTheme || 'black');
setValue('reveal-transition', advancedOptions.revealTransition || 'slide');
setValue('reveal-speed', advancedOptions.revealTransitionSpeed || 'default');
setChecked('reveal-slide-number', advancedOptions.revealSlideNumber === true);
setChecked('reveal-controls', advancedOptions.revealControls !== false);
setChecked('reveal-progress', advancedOptions.revealProgress !== false);
setChecked('reveal-history', advancedOptions.revealHistory !== false);
setChecked('reveal-center', advancedOptions.revealCenter !== false);
setValue('bibliography-file', advancedOptions.bibliography || '');
setValue('csl-file', advancedOptions.csl || '');
}
function rebuildMetadataRows(metadata) {
const container = document.querySelector('.metadata-container');
if (!container) return;
const entries = Object.keys(metadata).map((key) => [key, metadata[key]]);
if (entries.length === 0) {
['title', 'author', 'date', 'subject'].forEach((key) => entries.push([key, '']));
}
container.innerHTML = '';
entries.forEach(([key, value]) => {
const field = document.createElement('div');
field.className = 'metadata-field';
const keyInput = document.createElement('input');
keyInput.type = 'text';
keyInput.className = 'metadata-key';
keyInput.value = key;
const valueInput = document.createElement('input');
valueInput.type = 'text';
valueInput.className = 'metadata-value';
valueInput.value = value;
field.append(keyInput, valueInput);
container.appendChild(field);
});
}
// ============================================
// Preset dropdown rendering + interaction
// ============================================
function createPresetRow(preset) {
const selected = preset.id === selectedPresetId;
const row = document.createElement('div');
row.className = selected ? 'preset-row selected' : 'preset-row';
row.dataset.id = preset.id;
row.setAttribute('role', 'option');
row.setAttribute('aria-selected', selected ? 'true' : 'false');
const selectButton = document.createElement('button');
selectButton.type = 'button';
selectButton.className = 'preset-row-select';
selectButton.textContent = preset.name;
row.appendChild(selectButton);
if (preset.format) {
const badge = document.createElement('span');
badge.className = 'preset-format';
badge.textContent = preset.format;
row.appendChild(badge);
}
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'preset-delete';
deleteButton.textContent = '×';
deleteButton.title = `Delete preset ${preset.name}`;
deleteButton.setAttribute('aria-label', `Delete preset ${preset.name}`);
row.appendChild(deleteButton);
return row;
}
function renderPresets() {
const list = elementById('preset-dropdown-list');
const toggle = elementById('preset-dropdown-toggle');
if (!list || !toggle) return;
list.innerHTML = '';
if (currentPresets.length === 0) {
const empty = document.createElement('div');
empty.className = 'preset-empty';
empty.textContent = 'No saved presets';
list.appendChild(empty);
} else {
currentPresets.forEach((preset) => list.appendChild(createPresetRow(preset)));
}
const selected = currentPresets.find((preset) => preset.id === selectedPresetId);
toggle.textContent = selected ? selected.name : 'Custom Settings';
closeDropdown();
}
function toggleDropdown() {
const list = elementById('preset-dropdown-list');
if (!list) return;
const opened = !list.classList.contains('hidden');
list.classList.toggle('hidden');
const toggle = elementById('preset-dropdown-toggle');
if (toggle) toggle.setAttribute('aria-expanded', String(!opened));
}
function closeDropdown() {
const list = elementById('preset-dropdown-list');
if (list) list.classList.add('hidden');
const toggle = elementById('preset-dropdown-toggle');
if (toggle) toggle.setAttribute('aria-expanded', 'false');
}
function handleListClick(event) {
const deleteButton = event.target.closest('.preset-delete');
const row = event.target.closest('.preset-row');
if (deleteButton && row) {
deleteExportPreset(row.dataset.id);
return;
}
if (row) selectPreset(row.dataset.id);
}
function selectPreset(presetId) {
const preset = currentPresets.find((candidate) => candidate.id === presetId);
if (!preset) return;
selectedPresetId = presetId;
applyPresetToDialog(preset);
renderPresets();
}
// ============================================
// IPC-backed preset operations
// ============================================
/**
* Fetch presets from the main process and re-render the dropdown.
* Called whenever the export dialog opens.
*/
async function refreshExportPresets() {
try {
const presets = await ipcRenderer.invoke('get-export-presets');
currentPresets = Array.isArray(presets) ? presets : [];
} catch (error) {
console.error('Failed to load export presets:', error);
currentPresets = [];
}
if (!currentPresets.some((preset) => preset.id === selectedPresetId)) {
selectedPresetId = null;
}
renderPresets();
}
async function saveCurrentAsPreset() {
const selected = currentPresets.find((preset) => preset.id === selectedPresetId);
const defaultName = selected ? selected.name : 'My Preset';
const answer = window.prompt('Enter a name for this export preset:', defaultName);
if (answer === null) return; // user cancelled the prompt
const name = answer.trim();
if (!name) {
notify('Preset name cannot be empty.', 'warning');
return;
}
// A selected preset is overwritten (same id); otherwise a new id is minted.
// The main process re-validates and remains the source of truth.
const preset = {
id: selected ? selected.id : createPresetId(),
name,
format: getDialogFormat(),
options: captureDialogOptions(),
};
try {
const presets = await ipcRenderer.invoke('save-export-preset', preset);
currentPresets = Array.isArray(presets) ? presets : currentPresets;
// Normally the saved preset keeps the id we sent; fall back to the last
// entry with the same name should the main process have normalized it.
selectedPresetId = preset.id;
if (!currentPresets.some((candidate) => candidate.id === selectedPresetId)) {
const byName = currentPresets.filter((candidate) => candidate.name === name).pop();
selectedPresetId = byName ? byName.id : null;
}
renderPresets();
notify(`Preset "${name}" saved.`, 'success');
} catch (error) {
console.error('Failed to save export preset:', error);
notify('Failed to save preset. Please try again.', 'warning');
}
}
async function deleteExportPreset(presetId) {
const preset = currentPresets.find((candidate) => candidate.id === presetId);
const label = preset ? preset.name : 'this preset';
if (!window.confirm(`Are you sure you want to delete the preset "${label}"?`)) return;
try {
const presets = await ipcRenderer.invoke('delete-export-preset', presetId);
currentPresets = Array.isArray(presets) ? presets : currentPresets;
if (selectedPresetId === presetId) selectedPresetId = null;
renderPresets();
notify(`Preset "${label}" deleted.`, 'success');
} catch (error) {
console.error('Failed to delete export preset:', error);
notify('Failed to delete preset. Please try again.', 'warning');
}
}
function createPresetId() {
return `preset-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
// ============================================
// One-time import of legacy localStorage profiles
// ============================================
/**
* Map one legacy export profile onto the preset options shape captured by
* captureDialogOptions(). Legacy shape (saveCurrentProfile at git 52ef5b4):
* { format, advancedMode, pageSize, pageOrientation, basicToc,
* basicNumberSections } plus, in advanced mode, { template, toc, tocDepth,
* numberSections, citeproc, pdfEngine, pdfGeometry } all raw select/input
* values. Two fidelity limits of the legacy format itself: the custom
* template PATH and the custom geometry TEXT were never persisted (only the
* literal select value 'custom'), so those map back to the dialog defaults.
* @param {Object} profile legacy profile value
* @returns {Object} preset options snapshot
*/
function mapLegacyProfileOptions(profile) {
const advancedMode = profile.advancedMode === true;
const options = {
advancedMode,
pageSize: typeof profile.pageSize === 'string' ? profile.pageSize : 'a4',
pageOrientation:
typeof profile.pageOrientation === 'string' ? profile.pageOrientation : 'portrait',
};
if (!advancedMode) {
// Basic mode maps like collectExportOptions: basicToc -> toc,
// basicNumberSections -> numberSections.
options.toc = profile.basicToc === true;
options.numberSections = profile.basicNumberSections === true;
return options;
}
options.template = 'default';
options.metadata = {};
options.toc = profile.toc === true;
options.tocDepth =
typeof profile.tocDepth === 'string' && profile.tocDepth ? profile.tocDepth : '3';
options.numberSections = profile.numberSections === true;
options.citeproc = profile.citeproc === true;
options.pdfEngine = typeof profile.pdfEngine === 'string' ? profile.pdfEngine : 'xelatex';
options.geometry =
typeof profile.pdfGeometry === 'string' && profile.pdfGeometry !== 'custom'
? profile.pdfGeometry
: 'margin=1in';
return options;
}
/**
* Import the legacy localStorage export profiles into the main-process preset
* store via save-export-preset, then remove the legacy key so the import runs
* only once. Ids are deterministic (`preset-legacy-<name>`), so an import
* interrupted midway retries as an upsert on the next launch instead of
* duplicating presets. Malformed or unexpected data degrades to "skip import"
* it must never break dialog init.
* @returns {Promise<boolean>} true when at least one preset was imported
*/
async function importLegacyProfiles() {
try {
const raw = localStorage.getItem(LEGACY_PROFILES_KEY);
if (!raw) return false;
const legacy = JSON.parse(raw);
if (!legacy || typeof legacy !== 'object' || Array.isArray(legacy)) return false;
let imported = false;
for (const name of Object.keys(legacy)) {
const profile = legacy[name];
if (!name.trim() || !profile || typeof profile !== 'object') continue;
await ipcRenderer.invoke('save-export-preset', {
id: `preset-legacy-${name}`,
name,
format: typeof profile.format === 'string' ? profile.format : null,
options: mapLegacyProfileOptions(profile),
});
imported = true;
}
localStorage.removeItem(LEGACY_PROFILES_KEY);
return imported;
} catch (error) {
console.error('Skipping legacy export profile import:', error);
return false;
}
}
/**
* Wire the preset section of the export dialog. Call once after DOM ready.
* @param {{notify?: Function}} options hooks from renderer.js
*/
function initExportPresets(options = {}) {
if (typeof options.notify === 'function') notify = options.notify;
selectedPresetId = null;
const saveButton = elementById('save-preset-btn');
if (saveButton) saveButton.addEventListener('click', saveCurrentAsPreset);
const toggle = elementById('preset-dropdown-toggle');
if (toggle) toggle.addEventListener('click', toggleDropdown);
const list = elementById('preset-dropdown-list');
if (list) list.addEventListener('click', handleListClick);
// One-time legacy import; refresh afterwards so imported presets are
// visible even if the dialog is already open.
importLegacyProfiles().then((imported) => {
if (imported) refreshExportPresets();
});
}
module.exports = {
initExportPresets,
refreshExportPresets,
captureDialogOptions,
applyPresetToDialog,
};
+922
View File
@@ -0,0 +1,922 @@
/**
* Media Operations Dialog
*
* Single dialog for image/audio/video operation-specific tasks (resize, compress,
* rotate, trim, extract, merge, frames, gif, ...). Mirrors the construction pattern
* used by the PDF Editor dialog in renderer.js (a modal built from `.modal` /
* `.modal-content` / `.modal-header` / `.modal-body` / `.modal-footer` markup, driven
* by ModalManager, with a readonly text input + "Browse" button for file/folder
* selection, and a status line reusing the `info-message` / `success-message` /
* `warning-message` classes) except the operation-specific fields are generated
* dynamically instead of being hand-authored per-operation in index.html, since the
* three media kinds together cover 13 distinct operations.
*
* File selection reuses the app's existing convention: a plain `<input type="file">`
* whose chosen File is resolved to a path via `window.electronAPI.getFilePath`
* (webUtils.getPathForFile `File.path` was removed in Electron 32), the same
* approach already used throughout the PDF Editor and Universal Converter
* dialogs. No new IPC channel is needed for single-file or save-file pickers. Output
* *folder* selection (used by the video "Extract Frames" operation, and by batch
* mode below) reuses the existing generic `select-folder` / `folder-selected` IPC
* channels already wired up in main.js for the batch converter filtered here by a
* unique `type` string per picker so this dialog only reacts to requests it made.
*
* A "Mode: Single File / Batch Folder" dropdown (disabled for audio "Merge", which
* doesn't fit a per-file batch model) swaps the input/output file fields for an
* Input Folder + "Include subfolders" + Output Folder trio while keeping every other
* parameter field as-is; Process then fires `batch-image-operation` /
* `batch-audio-operation` / `batch-video-operation` (fire-and-forget, like
* `universal-convert-batch`) and progress/completion arrive via the
* `media-batch-progress` / `media-batch-complete` events sent by
* `runMediaBatchOperation()` in main.js.
*
* @module media-operations-dialog
*/
const { ipcRenderer } = require('electron');
const { getFilePath } = require('../utils/file-path');
const IMAGE_ACCEPT = '.jpg,.jpeg,.png,.webp,.avif,.tiff,.tif,.gif';
const AUDIO_ACCEPT = '.mp3,.wav,.ogg,.flac,.aac,.m4a,.wma';
const VIDEO_ACCEPT = '.mp4,.mov,.avi,.mkv,.webm,.flv,.wmv';
// Field names below are chosen to exactly match the `data` shape each backend
// operation destructures — see src/main/ImageOperations.js, AudioOperations.js,
// VideoOperations.js.
const MEDIA_KIND_CONFIG = {
image: {
title: 'Image Tools',
channel: 'process-image-operation',
batchChannel: 'batch-image-operation',
operations: {
convert: {
label: 'Convert Format',
fields: [
{ name: 'inputPath', label: 'Input Image', type: 'file', accept: IMAGE_ACCEPT },
{
name: 'format',
label: 'Output Format',
type: 'select',
options: ['jpeg', 'png', 'webp', 'avif', 'tiff', 'gif'],
default: 'png',
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
resize: {
label: 'Resize',
help: 'Provide at least one of Width or Height; the other scales proportionally.',
fields: [
{ name: 'inputPath', label: 'Input Image', type: 'file', accept: IMAGE_ACCEPT },
{ name: 'width', label: 'Width (px)', type: 'number', min: 1, optional: true },
{ name: 'height', label: 'Height (px)', type: 'number', min: 1, optional: true },
{
name: 'fit',
label: 'Fit Mode',
type: 'select',
options: ['cover', 'contain', 'fill', 'inside', 'outside'],
default: 'inside',
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
compress: {
label: 'Compress',
fields: [
{ name: 'inputPath', label: 'Input Image', type: 'file', accept: IMAGE_ACCEPT },
{
name: 'quality',
label: 'Quality (1-100)',
type: 'number',
min: 1,
max: 100,
default: 80,
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
rotate: {
label: 'Rotate',
fields: [
{ name: 'inputPath', label: 'Input Image', type: 'file', accept: IMAGE_ACCEPT },
{ name: 'angle', label: 'Angle (degrees)', type: 'number', default: 90, step: 1 },
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
},
},
audio: {
title: 'Audio Tools',
channel: 'process-audio-operation',
batchChannel: 'batch-audio-operation',
operations: {
convert: {
label: 'Convert Format',
fields: [
{ name: 'inputPath', label: 'Input Audio', type: 'file', accept: AUDIO_ACCEPT },
{
name: 'format',
label: 'Output Format',
type: 'select',
options: ['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'],
default: 'mp3',
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
trim: {
label: 'Trim',
fields: [
{ name: 'inputPath', label: 'Input Audio', type: 'file', accept: AUDIO_ACCEPT },
{
name: 'startTime',
label: 'Start Time (seconds)',
type: 'number',
min: 0,
default: 0,
},
{ name: 'duration', label: 'Duration (seconds)', type: 'number', min: 0, default: 10 },
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
extract: {
label: 'Extract Audio Track',
help: 'Extracts the audio track from a video or audio file.',
fields: [
{
name: 'inputPath',
label: 'Input File (video or audio)',
type: 'file',
accept: `${VIDEO_ACCEPT},${AUDIO_ACCEPT}`,
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
merge: {
label: 'Merge',
help: 'Select at least 2 audio files to merge, in order.',
// Merge combines several input files into a single output — it does not
// fit the "apply the same operation to every file in a folder" batch model
// (there is no single "one operation per file" mapping), so batch mode is
// unavailable for it. Enforced both here (hides the Batch option in the UI)
// and defensively in main.js's BATCH_OUTPUT_SPEC (no 'merge' entry).
batchable: false,
fields: [
{
name: 'inputPaths',
label: 'Input Audio Files',
type: 'files',
accept: AUDIO_ACCEPT,
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
},
},
video: {
title: 'Video Tools',
channel: 'process-video-operation',
batchChannel: 'batch-video-operation',
operations: {
convert: {
label: 'Convert Format',
help: 'Output format is inferred from the output file extension (e.g. .mp4, .webm).',
fields: [
{ name: 'inputPath', label: 'Input Video', type: 'file', accept: VIDEO_ACCEPT },
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
compress: {
label: 'Compress',
fields: [
{ name: 'inputPath', label: 'Input Video', type: 'file', accept: VIDEO_ACCEPT },
{
name: 'crf',
label: 'CRF (0-51, lower = higher quality)',
type: 'number',
min: 0,
max: 51,
default: 28,
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
trim: {
label: 'Trim',
fields: [
{ name: 'inputPath', label: 'Input Video', type: 'file', accept: VIDEO_ACCEPT },
{
name: 'startTime',
label: 'Start Time (seconds)',
type: 'number',
min: 0,
default: 0,
},
{ name: 'duration', label: 'Duration (seconds)', type: 'number', min: 0, default: 10 },
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
frames: {
label: 'Extract Frames',
fields: [
{ name: 'inputPath', label: 'Input Video', type: 'file', accept: VIDEO_ACCEPT },
{
name: 'fps',
label: 'Frames per Second',
type: 'number',
min: 0.1,
step: 0.1,
default: 1,
},
{ name: 'outputDir', label: 'Output Folder', type: 'folder' },
],
},
gif: {
label: 'Convert to GIF',
fields: [
{ name: 'inputPath', label: 'Input Video', type: 'file', accept: VIDEO_ACCEPT },
{ name: 'fps', label: 'Frames per Second', type: 'number', min: 1, default: 10 },
{
name: 'width',
label: 'Width (px, height auto-scales)',
type: 'number',
min: 1,
default: 480,
},
{ name: 'outputPath', label: 'Output File', type: 'save' },
],
},
},
},
};
const FOLDER_PICK_TYPE = 'media-operations-output-dir';
const BATCH_INPUT_FOLDER_PICK_TYPE = 'media-operations-batch-input-dir';
const BATCH_OUTPUT_FOLDER_PICK_TYPE = 'media-operations-batch-output-dir';
const BATCH_INPUT_FIELD_NAME = 'batchInputFolder';
const BATCH_OUTPUT_FIELD_NAME = 'batchOutputFolder';
const BATCH_SUBFOLDERS_FIELD_NAME = 'batchIncludeSubfolders';
let modalEl = null;
let modalManager = null;
let els = null;
let currentKind = null;
let currentMode = 'single';
let mergeFilePaths = [];
function fieldElId(name) {
return `media-field-${name}`;
}
function buildDialogDom() {
modalEl = document.createElement('div');
modalEl.id = 'media-operations-dialog';
modalEl.className = 'modal hidden';
modalEl.setAttribute('role', 'dialog');
modalEl.setAttribute('aria-modal', 'true');
modalEl.setAttribute('aria-labelledby', 'media-operations-title');
modalEl.innerHTML = `
<div class="modal-backdrop" data-close></div>
<div class="modal-content large">
<div class="modal-header">
<h3 id="media-operations-title">Media Tools</h3>
<button class="modal-close" id="media-operations-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
<div class="export-section">
<label for="media-operation-select">Operation:</label>
<select id="media-operation-select"></select>
</div>
<div class="export-section">
<label for="media-mode-select">Mode:</label>
<select id="media-mode-select">
<option value="single">Single File</option>
<option value="batch">Batch Folder (apply to every matching file)</option>
</select>
</div>
<small id="media-operation-help" class="hidden"></small>
<div id="media-operation-fields"></div>
<div id="media-status-message" class="info-message hidden" aria-live="polite"></div>
<div id="media-progress" class="batch-progress hidden">
<div class="progress-bar">
<div class="progress-fill" id="media-progress-fill"></div>
</div>
<div class="progress-text">
<span id="media-progress-text">Processing...</span>
</div>
</div>
</div>
<div class="modal-footer">
<button id="media-operations-cancel" class="btn btn-secondary" data-close>Cancel</button>
<button id="media-operations-process" class="btn btn-primary">Process</button>
</div>
</div>
`;
document.body.appendChild(modalEl);
els = {
title: modalEl.querySelector('#media-operations-title'),
operationSelect: modalEl.querySelector('#media-operation-select'),
modeSelect: modalEl.querySelector('#media-mode-select'),
help: modalEl.querySelector('#media-operation-help'),
fieldsContainer: modalEl.querySelector('#media-operation-fields'),
status: modalEl.querySelector('#media-status-message'),
progress: modalEl.querySelector('#media-progress'),
progressFill: modalEl.querySelector('#media-progress-fill'),
progressText: modalEl.querySelector('#media-progress-text'),
processBtn: modalEl.querySelector('#media-operations-process'),
cancelBtn: modalEl.querySelector('#media-operations-cancel'),
};
els.operationSelect.addEventListener('change', () => {
currentMode = 'single';
updateModeOptions();
renderFields();
});
els.modeSelect.addEventListener('change', () => {
currentMode = els.modeSelect.value;
renderFields();
});
els.processBtn.addEventListener('click', handleProcess);
els.cancelBtn.addEventListener('click', hideDialog);
modalManager = new window.ModalManager(modalEl);
// Generic output-folder picker reply (shared with the batch converter's
// input/output folder pickers) — filter by our own `type` so we only react
// to requests this dialog made.
ipcRenderer.on('folder-selected', (event, { type, path: folderPath }) => {
if (!folderPath) return;
let targetFieldName = null;
if (type === FOLDER_PICK_TYPE) targetFieldName = 'outputDir';
else if (type === BATCH_INPUT_FOLDER_PICK_TYPE) targetFieldName = BATCH_INPUT_FIELD_NAME;
else if (type === BATCH_OUTPUT_FOLDER_PICK_TYPE) targetFieldName = BATCH_OUTPUT_FIELD_NAME;
if (!targetFieldName) return;
const input = document.getElementById(fieldElId(targetFieldName));
if (input) input.value = folderPath;
});
// Batch operation progress/completion (main.js: runMediaBatchOperation()).
ipcRenderer.on('media-batch-progress', (event, { completed, failed, total, currentFile }) => {
if (!els.progress || els.progress.classList.contains('hidden')) return;
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
els.progressFill.style.width = `${pct}%`;
els.progressText.textContent = currentFile
? `Processing ${completed + 1}/${total}: ${currentFile}${failed ? ` (${failed} failed so far)` : ''}`
: `Processed ${completed}/${total}${failed ? ` (${failed} failed)` : ''}`;
});
ipcRenderer.on('media-batch-complete', (event, { success, completed, failed, total, error }) => {
hideProgress();
if (success) {
showStatus(
`Batch complete: ${completed}/${total} file(s) processed${failed ? ` (${failed} failed)` : ''}.`,
failed > 0 ? 'warning' : 'success'
);
} else {
showStatus(`Error: ${error || 'Batch operation failed.'}`, 'warning');
}
});
}
function ensureDialog() {
if (!modalEl) {
buildDialogDom();
}
}
function clearStatus() {
if (!els.status) return;
els.status.textContent = '';
els.status.classList.remove('info-message', 'warning-message', 'success-message');
els.status.classList.add('hidden');
}
function showStatus(message, type = 'info') {
if (!els.status) return;
els.status.textContent = message;
els.status.classList.remove('hidden', 'info-message', 'warning-message', 'success-message');
els.status.classList.add(`${type}-message`);
}
function showProgress() {
els.progress.classList.remove('hidden');
els.progressText.textContent = 'Processing...';
els.progressFill.style.width = '50%';
els.processBtn.disabled = true;
}
function hideProgress() {
els.progress.classList.add('hidden');
els.progressFill.style.width = '0%';
els.processBtn.disabled = false;
}
function createFolderInputGroup(field, { onBrowse }) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
label.textContent = `${field.label}:`;
wrapper.appendChild(label);
const group = document.createElement('div');
group.className = 'folder-input-group';
const input = document.createElement('input');
input.type = 'text';
input.id = fieldElId(field.name);
input.placeholder = field.placeholder || 'Choose...';
input.readOnly = true;
group.appendChild(input);
const browseBtn = document.createElement('button');
browseBtn.type = 'button';
browseBtn.textContent = field.type === 'folder' ? 'Browse Folder' : 'Browse';
browseBtn.addEventListener('click', () => onBrowse(input));
group.appendChild(browseBtn);
wrapper.appendChild(group);
return wrapper;
}
function renderFileField(field) {
return createFolderInputGroup(field, {
onBrowse: (input) => {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = field.accept || '*';
fileInput.onchange = (e) => {
const file = e.target.files[0];
if (file) input.value = getFilePath(file);
};
fileInput.click();
},
});
}
function renderSaveField(field) {
return createFolderInputGroup(field, {
onBrowse: (input) => {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.nwsaveas = true;
fileInput.onchange = (e) => {
const file = e.target.files[0];
if (file) input.value = getFilePath(file);
};
fileInput.click();
},
});
}
function renderFolderField(field, pickType = FOLDER_PICK_TYPE) {
return createFolderInputGroup(field, {
onBrowse: () => {
ipcRenderer.send('select-folder', pickType);
},
});
}
function renderCheckboxField(field) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
const input = document.createElement('input');
input.type = 'checkbox';
input.id = fieldElId(field.name);
input.checked = field.default !== false;
input.style.marginRight = '0.5em';
label.appendChild(input);
label.appendChild(document.createTextNode(field.label));
wrapper.appendChild(label);
return wrapper;
}
function renderNumberField(field) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
label.textContent = `${field.label}:`;
wrapper.appendChild(label);
const input = document.createElement('input');
input.type = 'number';
input.id = fieldElId(field.name);
if (field.min !== undefined) input.min = field.min;
if (field.max !== undefined) input.max = field.max;
if (field.step !== undefined) input.step = field.step;
if (field.default !== undefined) input.value = field.default;
wrapper.appendChild(input);
return wrapper;
}
function renderSelectField(field) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
label.textContent = `${field.label}:`;
wrapper.appendChild(label);
const select = document.createElement('select');
select.id = fieldElId(field.name);
field.options.forEach((opt) => {
const option = document.createElement('option');
option.value = opt;
option.textContent = opt;
if (opt === field.default) option.selected = true;
select.appendChild(option);
});
wrapper.appendChild(select);
return wrapper;
}
function updateMergeFilesList(listContainer) {
listContainer.innerHTML = '';
mergeFilePaths.forEach((filePath, index) => {
const fileEntry = document.createElement('div');
fileEntry.className = 'file-entry';
const name = document.createElement('span');
name.className = 'file-name';
name.textContent = filePath.split(/[\\/]/).pop();
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-file';
removeBtn.type = 'button';
removeBtn.textContent = 'Remove';
removeBtn.addEventListener('click', () => {
mergeFilePaths.splice(index, 1);
updateMergeFilesList(listContainer);
});
fileEntry.appendChild(name);
fileEntry.appendChild(removeBtn);
listContainer.appendChild(fileEntry);
});
}
function renderFilesField(field) {
mergeFilePaths = [];
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
const label = document.createElement('label');
label.textContent = `${field.label}:`;
wrapper.appendChild(label);
const listContainer = document.createElement('div');
listContainer.className = 'file-list';
listContainer.id = fieldElId(field.name);
wrapper.appendChild(listContainer);
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.textContent = '+ Add File';
addBtn.addEventListener('click', () => {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = field.accept || '*';
fileInput.multiple = true;
fileInput.onchange = (e) => {
Array.from(e.target.files).forEach((file) => {
const filePath = getFilePath(file);
if (!mergeFilePaths.includes(filePath)) {
mergeFilePaths.push(filePath);
}
});
updateMergeFilesList(listContainer);
};
fileInput.click();
});
wrapper.appendChild(addBtn);
return wrapper;
}
// The field carrying the input-file picker for a batchable operation is always a
// 'file' field (single input) — 'files' (merge) operations are excluded from batch
// mode via `batchable: false` before this is ever consulted.
function getInputFileField(opConfig) {
return opConfig.fields.find((field) => field.type === 'file');
}
function isBatchable(opConfig) {
return opConfig.batchable !== false;
}
// Keep the Mode dropdown in sync with whether the currently selected operation
// supports batch mode (everything except audio "Merge").
function updateModeOptions() {
const kindConfig = MEDIA_KIND_CONFIG[currentKind];
const opConfig = kindConfig.operations[els.operationSelect.value];
const batchOption = els.modeSelect.querySelector('option[value="batch"]');
if (batchOption) {
batchOption.disabled = !isBatchable(opConfig);
}
if (!isBatchable(opConfig)) {
currentMode = 'single';
}
els.modeSelect.value = currentMode;
}
function renderSingleFields(opConfig) {
opConfig.fields.forEach((field) => {
let fieldEl;
switch (field.type) {
case 'file':
fieldEl = renderFileField(field);
break;
case 'save':
fieldEl = renderSaveField(field);
break;
case 'folder':
fieldEl = renderFolderField(field);
break;
case 'number':
fieldEl = renderNumberField(field);
break;
case 'select':
fieldEl = renderSelectField(field);
break;
case 'files':
fieldEl = renderFilesField(field);
break;
default:
return;
}
els.fieldsContainer.appendChild(fieldEl);
});
}
// Batch mode swaps the single input/output file (or folder) fields for one
// "Input Folder" + "Include Subfolders" + "Output Folder" trio, while keeping every
// other parameter field (width/height/quality/angle/startTime/duration/crf/fps/
// format/fit/...) exactly as in single mode — those values apply to every matching
// file. The actual per-file output path/dir is computed by main.js's
// runMediaBatchOperation()/BATCH_OUTPUT_SPEC.
function renderBatchFields(opConfig) {
els.fieldsContainer.appendChild(
renderFolderField(
{ name: BATCH_INPUT_FIELD_NAME, label: 'Input Folder', type: 'folder' },
BATCH_INPUT_FOLDER_PICK_TYPE
)
);
els.fieldsContainer.appendChild(
renderCheckboxField({
name: BATCH_SUBFOLDERS_FIELD_NAME,
label: 'Include subfolders',
default: true,
})
);
opConfig.fields.forEach((field) => {
if (field.type === 'number') {
els.fieldsContainer.appendChild(renderNumberField(field));
} else if (field.type === 'select') {
els.fieldsContainer.appendChild(renderSelectField(field));
}
// 'file' / 'save' / 'folder' single-file fields are intentionally skipped —
// replaced by the Input/Output Folder fields below/above.
});
els.fieldsContainer.appendChild(
renderFolderField(
{ name: BATCH_OUTPUT_FIELD_NAME, label: 'Output Folder', type: 'folder' },
BATCH_OUTPUT_FOLDER_PICK_TYPE
)
);
}
function renderFields() {
const kindConfig = MEDIA_KIND_CONFIG[currentKind];
const opKey = els.operationSelect.value;
const opConfig = kindConfig.operations[opKey];
updateModeOptions();
els.fieldsContainer.innerHTML = '';
if (opConfig.help) {
els.help.textContent = opConfig.help;
els.help.classList.remove('hidden');
} else {
els.help.textContent = '';
els.help.classList.add('hidden');
}
if (currentMode === 'batch') {
renderBatchFields(opConfig);
} else {
renderSingleFields(opConfig);
}
}
function collectOperationData(opConfig) {
const data = {};
for (const field of opConfig.fields) {
if (field.type === 'files') {
data[field.name] = [...mergeFilePaths];
continue;
}
const input = document.getElementById(fieldElId(field.name));
if (!input) continue;
if (field.type === 'number') {
const raw = String(input.value).trim();
if (raw === '') {
if (field.optional) {
data[field.name] = null;
continue;
}
return { error: `${field.label} is required.` };
}
const num = Number(raw);
if (!Number.isFinite(num)) {
return { error: `${field.label} must be a valid number.` };
}
data[field.name] = num;
} else {
data[field.name] = input.value;
}
}
if ('inputPath' in data && !data.inputPath) {
return { error: 'Select an input file.' };
}
if ('inputPaths' in data && (!data.inputPaths || data.inputPaths.length < 2)) {
return { error: 'Select at least 2 input files.' };
}
if ('outputPath' in data && !data.outputPath) {
return { error: 'Select an output file.' };
}
if ('outputDir' in data && !data.outputDir) {
return { error: 'Select an output folder.' };
}
if ('width' in data && 'height' in data && data.width === null && data.height === null) {
return { error: 'Provide at least one of Width or Height.' };
}
return { data };
}
async function handleSingleProcess(kindConfig, opKey, opConfig) {
const { data, error } = collectOperationData(opConfig);
if (error) {
showStatus(error, 'warning');
return;
}
clearStatus();
showProgress();
try {
const result = await ipcRenderer.invoke(kindConfig.channel, { operation: opKey, data });
hideProgress();
if (result && result.success) {
showStatus(
`Success: ${result.outputPath || result.outputDir || 'Operation completed.'}`,
'success'
);
} else {
showStatus(`Error: ${(result && result.error) || 'Operation failed.'}`, 'warning');
}
} catch (err) {
hideProgress();
showStatus(`Error: ${err.message}`, 'warning');
}
}
// Collects the shared parameter fields (number/select only — no file/folder/files
// fields) that apply identically to every file in a batch run.
function collectBatchParamData(opConfig) {
const data = {};
for (const field of opConfig.fields) {
if (field.type !== 'number' && field.type !== 'select') continue;
const input = document.getElementById(fieldElId(field.name));
if (!input) continue;
if (field.type === 'number') {
const raw = String(input.value).trim();
if (raw === '') {
if (field.optional) {
data[field.name] = null;
continue;
}
return { error: `${field.label} is required.` };
}
const num = Number(raw);
if (!Number.isFinite(num)) {
return { error: `${field.label} must be a valid number.` };
}
data[field.name] = num;
} else {
data[field.name] = input.value;
}
}
if ('width' in data && 'height' in data && data.width === null && data.height === null) {
return { error: 'Provide at least one of Width or Height.' };
}
return { data };
}
function handleBatchProcess(kindConfig, opKey, opConfig) {
const inputFolder = document.getElementById(fieldElId(BATCH_INPUT_FIELD_NAME))?.value;
const outputFolder = document.getElementById(fieldElId(BATCH_OUTPUT_FIELD_NAME))?.value;
const includeSubfolders =
document.getElementById(fieldElId(BATCH_SUBFOLDERS_FIELD_NAME))?.checked !== false;
if (!inputFolder) {
showStatus('Select an input folder.', 'warning');
return;
}
if (!outputFolder) {
showStatus('Select an output folder.', 'warning');
return;
}
const { data, error } = collectBatchParamData(opConfig);
if (error) {
showStatus(error, 'warning');
return;
}
const inputField = getInputFileField(opConfig);
const extensions = (inputField?.accept || '').split(',').filter(Boolean);
if (extensions.length === 0) {
showStatus('This operation does not support batch mode.', 'warning');
return;
}
clearStatus();
showProgress();
els.progressText.textContent = 'Scanning folder...';
ipcRenderer.send(kindConfig.batchChannel, {
operation: opKey,
inputFolder,
outputFolder,
includeSubfolders,
extensions,
data,
});
}
async function handleProcess() {
const kindConfig = MEDIA_KIND_CONFIG[currentKind];
const opKey = els.operationSelect.value;
const opConfig = kindConfig.operations[opKey];
if (currentMode === 'batch' && isBatchable(opConfig)) {
handleBatchProcess(kindConfig, opKey, opConfig);
} else {
await handleSingleProcess(kindConfig, opKey, opConfig);
}
}
function hideDialog() {
if (modalManager) modalManager.close();
clearStatus();
hideProgress();
}
function showMediaOperationsDialog(kind) {
if (!MEDIA_KIND_CONFIG[kind]) {
throw new Error(`Unknown media kind: ${kind}`);
}
ensureDialog();
currentKind = kind;
currentMode = 'single';
const kindConfig = MEDIA_KIND_CONFIG[kind];
els.title.textContent = kindConfig.title;
els.operationSelect.innerHTML = '';
Object.entries(kindConfig.operations).forEach(([key, op]) => {
const option = document.createElement('option');
option.value = key;
option.textContent = op.label;
els.operationSelect.appendChild(option);
});
clearStatus();
hideProgress();
renderFields();
modalManager.open();
}
module.exports = { showMediaOperationsDialog };
+715
View File
@@ -0,0 +1,715 @@
/**
* PDF Batch Dialog
*
* Batch wrapper for the single-file PDF operations (Tasks 15-16 backend via
* PDFOperations.executeOperation): pick one operation (watermark, compress,
* rotate, split, ...) plus that operation's shared option fields the same
* fields and option shapes the single-file PDF editor dialog in
* renderer.js/index.html already sends and apply it to every .pdf in an
* input folder. Mirrors the batch-folder construction pattern of the Image/
* Audio/Video Tools dialog (src/renderer/media-operations-dialog.js, Task 12):
* a `.modal`-based dialog driven by ModalManager, folder pickers via the
* existing generic `select-folder` / `folder-selected` IPC channels filtered by
* a unique `type` per picker, and Process firing a fire-and-forget
* `batch-pdf-operation` whose progress/completion arrive via `batch-progress`
* / `pdf-batch-complete` events sent by the `batch-pdf-operation` handler in
* main.js (which delegates to src/main/PDFBatchOperations.js).
*
* The dialog is reached from the Tools > Batch PDF Conversion... menu item
* (`show-batch-converter` with type 'pdf'). Its top selector keeps that menu
* item's existing behavior as the default: "Convert Format" delegates to the
* pre-existing universal-converter batch flow via the `onConvertFormat`
* callback renderer.js passes in; "Bulk PDF Operation" reveals this dialog's
* per-file operation controls.
*
* Only per-file, non-interactive operations are offered (see
* PDF_BATCH_OUTPUT_SPEC in src/main/PDFBatchOperations.js for the exclusions
* the renderer list and that spec intentionally agree).
*
* @module pdf-batch-dialog
*/
const { ipcRenderer } = require('electron');
// Field names are chosen to exactly match the `data` shape each backend
// operation destructures — see src/main/PDFOperations.js — mirroring the
// single-file PDF editor dialog's collection code in renderer.js. Defaults and
// option lists mirror the corresponding index.html sections.
const BATCH_OPERATIONS = {
watermark: {
label: 'Add Watermark',
fields: [
{ name: 'text', label: 'Watermark Text', type: 'text' },
{
name: 'pages',
label: 'Apply to',
type: 'select',
options: [
{ value: 'all', label: 'All Pages' },
{ value: 'custom', label: 'Custom Pages' },
],
default: 'all',
},
{
name: 'customPages',
label: 'Custom Pages (e.g. 1-5, 7)',
type: 'text',
showIf: { field: 'pages', equals: 'custom' },
},
{
name: 'position',
label: 'Position',
type: 'select',
options: [
'center',
'diagonal',
'top-left',
'top-center',
'top-right',
'bottom-left',
'bottom-center',
'bottom-right',
],
default: 'center',
},
{ name: 'fontSize', label: 'Font Size', type: 'number', min: 8, max: 144, default: 48 },
// 0-100 in the UI; divided by 100 before sending, like the single-file dialog.
{ name: 'opacity', label: 'Opacity (0-100)', type: 'number', min: 0, max: 100, default: 30 },
{ name: 'color', label: 'Color', type: 'color', default: '#000000' },
],
},
split: {
label: 'Split',
fields: [
{
name: 'splitMode',
label: 'Split Mode',
type: 'select',
options: [
{ value: 'pages', label: 'By Page Range' },
{ value: 'interval', label: 'Every N Pages' },
{ value: 'size', label: 'By File Size' },
],
default: 'pages',
},
{
name: 'pageRanges',
label: 'Page Ranges (e.g. 1-5, 6-10)',
type: 'text',
showIf: { field: 'splitMode', equals: 'pages' },
},
{
name: 'interval',
label: 'Pages per Split File',
type: 'number',
min: 1,
default: 5,
showIf: { field: 'splitMode', equals: 'interval' },
},
],
},
compress: { label: 'Compress', fields: [] },
rotate: {
label: 'Rotate',
fields: [
{
name: 'angle',
label: 'Rotation Angle',
type: 'select',
options: [
{ value: '90', label: '90° Clockwise' },
{ value: '180', label: '180°' },
{ value: '270', label: '270° Clockwise (90° Counter-clockwise)' },
],
default: '90',
},
{ name: 'pages', label: 'Pages (e.g. 1-3, 5; empty = all)', type: 'text', optional: true },
],
},
delete: {
label: 'Delete Pages',
fields: [{ name: 'pages', label: 'Pages to Delete (e.g. 1-3, 5)', type: 'text' }],
},
extractText: { label: 'Extract Text', fields: [] },
pageNumbers: {
label: 'Add Page Numbers',
fields: [
{
name: 'position',
label: 'Position',
type: 'select',
options: [
'bottom-center',
'bottom-left',
'bottom-right',
'top-center',
'top-left',
'top-right',
],
default: 'bottom-center',
},
{ name: 'startNumber', label: 'Start Number', type: 'number', min: 1, default: 1 },
],
},
crop: {
label: 'Crop Margins',
fields: [
{ name: 'margins.top', label: 'Top Margin', type: 'number', min: 0, default: 0, float: true },
{
name: 'margins.bottom',
label: 'Bottom Margin',
type: 'number',
min: 0,
default: 0,
float: true,
},
{
name: 'margins.left',
label: 'Left Margin',
type: 'number',
min: 0,
default: 0,
float: true,
},
{
name: 'margins.right',
label: 'Right Margin',
type: 'number',
min: 0,
default: 0,
float: true,
},
],
},
extractImages: { label: 'Extract Images', fields: [] },
};
const INPUT_FOLDER_FIELD = { name: 'inputFolder', label: 'Input Folder' };
const OUTPUT_FOLDER_FIELD = { name: 'outputFolder', label: 'Output Folder' };
const SUBFOLDERS_FIELD = { name: 'includeSubfolders', label: 'Include subfolders' };
const INPUT_FOLDER_PICK_TYPE = 'pdf-batch-input-dir';
const OUTPUT_FOLDER_PICK_TYPE = 'pdf-batch-output-dir';
let modalEl = null;
let modalManager = null;
let els = null;
let onConvertFormatCallback = null;
// True between sending a batch-pdf-operation and its pdf-batch-complete; guards
// against firing a second overlapping run (the Process button is also disabled,
// but the batch-type switch re-labels it, so the flag is the real guard).
let runInFlight = false;
function fieldElId(name) {
return `pdf-batch-field-${name}`;
}
function buildDialogDom() {
modalEl = document.createElement('div');
modalEl.id = 'pdf-batch-dialog';
modalEl.className = 'modal hidden';
modalEl.setAttribute('role', 'dialog');
modalEl.setAttribute('aria-modal', 'true');
modalEl.setAttribute('aria-labelledby', 'pdf-batch-title');
modalEl.innerHTML = `
<div class="modal-backdrop" data-close></div>
<div class="modal-content large">
<div class="modal-header">
<h3 id="pdf-batch-title">Batch PDF Tools</h3>
<button class="modal-close" id="pdf-batch-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
<div class="export-section">
<label for="pdf-batch-type">Batch Type:</label>
<select id="pdf-batch-type">
<option value="convert">Convert Format (existing batch converter)</option>
<option value="operation">Bulk PDF Operation</option>
</select>
</div>
<small id="pdf-batch-convert-hint">
Format conversion (PDF to DOCX/HTML/...) uses the existing batch converter.
Choose "Bulk PDF Operation" to watermark, compress, or otherwise process many PDFs at once.
</small>
<div id="pdf-batch-operation-panel" class="hidden">
<div class="export-section">
<label for="pdf-batch-operation">Operation:</label>
<select id="pdf-batch-operation"></select>
</div>
<div id="pdf-batch-operation-fields"></div>
</div>
<div id="pdf-batch-status" class="info-message hidden" aria-live="polite"></div>
<div id="pdf-batch-progress" class="batch-progress hidden">
<div class="progress-bar">
<div class="progress-fill" id="pdf-batch-progress-fill"></div>
</div>
<div class="progress-text">
<span id="pdf-batch-progress-text">Processing...</span>
</div>
</div>
</div>
<div class="modal-footer">
<button id="pdf-batch-cancel" class="btn btn-secondary" data-close>Cancel</button>
<button id="pdf-batch-process" class="btn btn-primary">Open Batch Converter...</button>
</div>
</div>
`;
document.body.appendChild(modalEl);
els = {
typeSelect: modalEl.querySelector('#pdf-batch-type'),
convertHint: modalEl.querySelector('#pdf-batch-convert-hint'),
operationPanel: modalEl.querySelector('#pdf-batch-operation-panel'),
operationSelect: modalEl.querySelector('#pdf-batch-operation'),
fieldsContainer: modalEl.querySelector('#pdf-batch-operation-fields'),
status: modalEl.querySelector('#pdf-batch-status'),
progress: modalEl.querySelector('#pdf-batch-progress'),
progressFill: modalEl.querySelector('#pdf-batch-progress-fill'),
progressText: modalEl.querySelector('#pdf-batch-progress-text'),
processBtn: modalEl.querySelector('#pdf-batch-process'),
};
els.typeSelect.addEventListener('change', updateBatchTypeUI);
els.operationSelect.addEventListener('change', renderOperationFields);
els.processBtn.addEventListener('click', handleProcess);
modalEl.querySelector('#pdf-batch-cancel').addEventListener('click', hideDialog);
modalManager = new window.ModalManager(modalEl);
// Generic output-folder picker reply (shared with the batch converter's
// input/output folder pickers) — filter by our own `type` so we only react
// to requests this dialog made.
ipcRenderer.on('folder-selected', (event, { type, path: folderPath }) => {
if (!folderPath) return;
const fieldName =
type === INPUT_FOLDER_PICK_TYPE
? INPUT_FOLDER_FIELD.name
: type === OUTPUT_FOLDER_PICK_TYPE
? OUTPUT_FOLDER_FIELD.name
: null;
if (!fieldName) return;
const input = document.getElementById(fieldElId(fieldName));
if (input) input.value = folderPath;
});
// Batch operation progress/completion (main.js: batch-pdf-operation handler,
// delegating to runPDFBatchOperation() in src/main/PDFBatchOperations.js).
ipcRenderer.on('batch-progress', (event, { completed, failed, total, currentFile }) => {
if (!els.progress || els.progress.classList.contains('hidden')) return;
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
els.progressFill.style.width = `${pct}%`;
els.progressText.textContent = currentFile
? `Processing ${completed + 1}/${total}: ${currentFile}${failed ? ` (${failed} failed so far)` : ''}`
: `Processed ${completed}/${total}${failed ? ` (${failed} failed)` : ''}`;
});
ipcRenderer.on('pdf-batch-complete', (event, { success, completed, failed, total, error }) => {
runInFlight = false;
hideProgress();
if (success) {
showStatus(
`Batch complete: ${completed}/${total} file(s) processed${failed ? ` (${failed} failed)` : ''}.`,
failed > 0 ? 'warning' : 'success'
);
} else {
showStatus(`Error: ${error || 'Batch operation failed.'}`, 'warning');
}
});
}
function ensureDialog() {
if (!modalEl) {
buildDialogDom();
}
}
function clearStatus() {
els.status.textContent = '';
els.status.classList.remove('info-message', 'warning-message', 'success-message');
els.status.classList.add('hidden');
}
function showStatus(message, type = 'info') {
els.status.textContent = message;
els.status.classList.remove('hidden', 'info-message', 'warning-message', 'success-message');
els.status.classList.add(`${type}-message`);
}
function showProgress() {
els.progress.classList.remove('hidden');
els.progressText.textContent = 'Scanning folder...';
els.progressFill.style.width = '0%';
els.processBtn.disabled = true;
}
function hideProgress() {
els.progress.classList.add('hidden');
els.progressFill.style.width = '0%';
els.processBtn.disabled = false;
}
function optionValue(option) {
return typeof option === 'string' ? option : option.value;
}
function optionLabel(option) {
return typeof option === 'string' ? option : option.label;
}
function createLabeledWrapper(field) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
wrapper.id = `${fieldElId(field.name)}-wrapper`;
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
label.textContent = `${field.label}:`;
wrapper.appendChild(label);
return wrapper;
}
function renderTextField(field) {
const wrapper = createLabeledWrapper(field);
const input = document.createElement('input');
input.type = 'text';
input.id = fieldElId(field.name);
input.placeholder = field.placeholder || '';
wrapper.appendChild(input);
return wrapper;
}
function renderNumberField(field) {
const wrapper = createLabeledWrapper(field);
const input = document.createElement('input');
input.type = 'number';
input.id = fieldElId(field.name);
if (field.min !== undefined) input.min = field.min;
if (field.max !== undefined) input.max = field.max;
if (field.default !== undefined) input.value = field.default;
wrapper.appendChild(input);
return wrapper;
}
function renderSelectField(field) {
const wrapper = createLabeledWrapper(field);
const select = document.createElement('select');
select.id = fieldElId(field.name);
field.options.forEach((opt) => {
const option = document.createElement('option');
option.value = optionValue(opt);
option.textContent = optionLabel(opt);
if (optionValue(opt) === field.default) option.selected = true;
select.appendChild(option);
});
// Attached to the select itself (not via a bubbling container listener) so
// conditional fields update regardless of how the change event was fired.
select.addEventListener('change', updateConditionalFields);
wrapper.appendChild(select);
return wrapper;
}
function renderColorField(field) {
const wrapper = createLabeledWrapper(field);
const input = document.createElement('input');
input.type = 'color';
input.id = fieldElId(field.name);
input.value = field.default || '#000000';
wrapper.appendChild(input);
return wrapper;
}
function createFolderPickerField(field, pickType) {
const wrapper = createLabeledWrapper(field);
const group = document.createElement('div');
group.className = 'folder-input-group';
const input = document.createElement('input');
input.type = 'text';
input.id = fieldElId(field.name);
input.placeholder = 'Choose...';
input.readOnly = true;
group.appendChild(input);
const browseBtn = document.createElement('button');
browseBtn.type = 'button';
browseBtn.textContent = 'Browse Folder';
browseBtn.addEventListener('click', () => {
ipcRenderer.send('select-folder', pickType);
});
group.appendChild(browseBtn);
wrapper.appendChild(group);
return wrapper;
}
function renderCheckboxField(field) {
const wrapper = document.createElement('div');
wrapper.className = 'export-section';
wrapper.id = `${fieldElId(field.name)}-wrapper`;
const label = document.createElement('label');
label.setAttribute('for', fieldElId(field.name));
const input = document.createElement('input');
input.type = 'checkbox';
input.id = fieldElId(field.name);
input.checked = true;
input.style.marginRight = '0.5em';
label.appendChild(input);
label.appendChild(document.createTextNode(field.label));
wrapper.appendChild(label);
return wrapper;
}
function fieldIsVisible(field, values) {
if (!field.showIf) return true;
return values[field.showIf.field] === field.showIf.equals;
}
// Toggles the hidden class of conditionally-shown fields (watermark custom
// pages, split ranges/interval) based on the current select values.
function updateConditionalFields() {
const opConfig = BATCH_OPERATIONS[els.operationSelect.value];
if (!opConfig) return;
const values = {};
opConfig.fields.forEach((field) => {
const input = document.getElementById(fieldElId(field.name));
if (input) values[field.name] = input.value;
});
opConfig.fields.forEach((field) => {
if (!field.showIf) return;
const wrapper = document.getElementById(`${fieldElId(field.name)}-wrapper`);
if (wrapper) wrapper.classList.toggle('hidden', !fieldIsVisible(field, values));
});
}
function renderOperationFields() {
const opConfig = BATCH_OPERATIONS[els.operationSelect.value];
els.fieldsContainer.innerHTML = '';
els.fieldsContainer.appendChild(
createFolderPickerField(INPUT_FOLDER_FIELD, INPUT_FOLDER_PICK_TYPE)
);
els.fieldsContainer.appendChild(renderCheckboxField(SUBFOLDERS_FIELD));
opConfig.fields.forEach((field) => {
let fieldEl;
switch (field.type) {
case 'text':
fieldEl = renderTextField(field);
break;
case 'number':
fieldEl = renderNumberField(field);
break;
case 'select':
fieldEl = renderSelectField(field);
break;
case 'color':
fieldEl = renderColorField(field);
break;
default:
return;
}
els.fieldsContainer.appendChild(fieldEl);
});
els.fieldsContainer.appendChild(
createFolderPickerField(OUTPUT_FOLDER_FIELD, OUTPUT_FOLDER_PICK_TYPE)
);
updateConditionalFields();
}
function updateBatchTypeUI() {
const isConvert = els.typeSelect.value === 'convert';
els.convertHint.classList.toggle('hidden', !isConvert);
els.operationPanel.classList.toggle('hidden', isConvert);
els.processBtn.textContent = isConvert ? 'Open Batch Converter...' : 'Process';
// Progress state is left alone here: clearing it mid-run would re-enable the
// Process button while a batch is still in flight (runInFlight guards that).
clearStatus();
}
// Reads the shared option fields into the exact `data` shape the backend
// operation destructures, dropping conditionally-hidden fields and applying
// per-op conversions (opacity /100, margins grouping) exactly like the
// single-file PDF editor dialog does.
function collectOperationData(opKey) {
const opConfig = BATCH_OPERATIONS[opKey];
const raw = {};
for (const field of opConfig.fields) {
const input = document.getElementById(fieldElId(field.name));
if (!input) continue;
if (field.type === 'number') {
const num = field.float ? parseFloat(input.value) : parseInt(input.value, 10);
raw[field.name] = Number.isFinite(num) ? num : null;
} else {
raw[field.name] = input.value.trim();
}
}
const visible = (name) =>
fieldIsVisible(
opConfig.fields.find((f) => f.name === name),
raw
);
let data;
switch (opKey) {
case 'watermark':
data = {
text: raw.text,
fontSize: raw.fontSize,
opacity: raw.opacity !== null ? raw.opacity / 100 : null,
position: raw.position,
color: raw.color,
pages: raw.pages,
};
if (raw.pages === 'custom' && visible('customPages')) {
data.customPages = raw.customPages;
}
break;
case 'split':
data = { splitMode: raw.splitMode };
if (raw.splitMode === 'pages' && visible('pageRanges')) data.pageRanges = raw.pageRanges;
if (raw.splitMode === 'interval' && visible('interval')) data.interval = raw.interval;
break;
case 'rotate':
data = { angle: parseInt(raw.angle, 10), pages: raw.pages };
break;
case 'delete':
data = { pages: raw.pages };
break;
case 'pageNumbers':
data = { position: raw.position, startNumber: raw.startNumber };
break;
case 'crop':
data = {
margins: {
top: raw['margins.top'],
bottom: raw['margins.bottom'],
left: raw['margins.left'],
right: raw['margins.right'],
},
};
break;
default:
data = {};
}
return { data };
}
// Per-operation required-field checks, mirroring the single-file dialog's
// validation messages.
function validateOperationData(opKey, data) {
switch (opKey) {
case 'watermark':
if (!data.text) return 'Enter watermark text.';
if (!data.fontSize) return 'Enter a font size.';
if (data.pages === 'custom' && !data.customPages) {
return 'Enter the custom pages to watermark.';
}
return null;
case 'split':
if (data.splitMode === 'pages' && !data.pageRanges) {
return 'Enter page ranges (e.g. 1-5, 6-10).';
}
if (data.splitMode === 'interval' && !data.interval) {
return 'Enter the number of pages per split file.';
}
return null;
case 'delete':
if (!data.pages) return 'Enter the pages to delete (e.g. 1-3, 5).';
return null;
default:
return null;
}
}
function handleConvertProcess() {
hideDialog();
if (typeof onConvertFormatCallback === 'function') {
onConvertFormatCallback();
}
}
function handleBulkProcess() {
if (runInFlight) return;
const inputFolder = document.getElementById(fieldElId(INPUT_FOLDER_FIELD.name))?.value;
const outputFolder = document.getElementById(fieldElId(OUTPUT_FOLDER_FIELD.name))?.value;
const includeSubfolders =
document.getElementById(fieldElId(SUBFOLDERS_FIELD.name))?.checked !== false;
if (!inputFolder) {
showStatus('Select an input folder.', 'warning');
return;
}
if (!outputFolder) {
showStatus('Select an output folder.', 'warning');
return;
}
const opKey = els.operationSelect.value;
const { data } = collectOperationData(opKey);
const error = validateOperationData(opKey, data);
if (error) {
showStatus(error, 'warning');
return;
}
clearStatus();
showProgress();
runInFlight = true;
ipcRenderer.send('batch-pdf-operation', {
operation: opKey,
inputFolder,
outputFolder,
includeSubfolders,
data,
});
}
function handleProcess() {
if (els.typeSelect.value === 'convert') {
handleConvertProcess();
} else {
handleBulkProcess();
}
}
function hideDialog() {
if (modalManager) modalManager.close();
clearStatus();
hideProgress();
}
/**
* Opens the Batch PDF Tools dialog.
*
* @param {object} [options]
* @param {Function} [options.onConvertFormat] - Invoked when the user keeps the
* default "Convert Format" batch type; renderer.js passes the pre-existing
* universal-converter batch flow that the Tools > Batch PDF Conversion...
* menu item used to open directly.
*/
function showPdfBatchDialog(options = {}) {
ensureDialog();
onConvertFormatCallback = options.onConvertFormat || null;
els.operationSelect.innerHTML = '';
Object.entries(BATCH_OPERATIONS).forEach(([key, op]) => {
const option = document.createElement('option');
option.value = key;
option.textContent = op.label;
els.operationSelect.appendChild(option);
});
els.typeSelect.value = 'convert';
runInFlight = false;
clearStatus();
hideProgress();
updateBatchTypeUI();
renderOperationFields();
modalManager.open();
}
module.exports = { showPdfBatchDialog, BATCH_OPERATIONS };
+49
View File
@@ -0,0 +1,49 @@
class ReplPanel {
constructor() {
this.panel = document.getElementById('bottom-panel');
this.output = document.getElementById('repl-output');
this.setupEventListeners();
}
setupEventListeners() {
document.getElementById('bottom-panel-toggle')?.addEventListener('click', () => this.toggle());
document.getElementById('repl-clear')?.addEventListener('click', () => this.clear());
}
toggle() {
this.panel.classList.toggle('collapsed');
const btn = document.getElementById('bottom-panel-toggle');
if (btn) btn.textContent = this.panel.classList.contains('collapsed') ? '\u25BC' : '\u25B2';
}
show() {
this.panel.classList.remove('collapsed');
const btn = document.getElementById('bottom-panel-toggle');
if (btn) btn.textContent = '\u25B2';
}
clear() {
if (this.output) this.output.innerHTML = '';
}
appendOutput(command, result) {
const entry = document.createElement('div');
entry.className = 'repl-entry';
entry.innerHTML = `
<div class="repl-command">\u25B6 ${command}</div>
${result.stdout ? `<div class="repl-stdout">${this.escapeHtml(result.stdout)}</div>` : ''}
${result.stderr ? `<div class="repl-stderr">${this.escapeHtml(result.stderr)}</div>` : ''}
${result.error ? `<div class="repl-error">Error: ${this.escapeHtml(result.error)}</div>` : ''}
`;
this.output?.appendChild(entry);
this.output?.scrollTo(0, this.output.scrollHeight);
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
module.exports = { ReplPanel };
+94
View File
@@ -0,0 +1,94 @@
function renderExplorerPanel(container, { listDirectory, onFileOpen, currentDir }) {
container.innerHTML = `
<div class="explorer-panel">
<div class="explorer-toolbar">
<input type="text" class="explorer-path" id="explorer-path" value="${currentDir || ''}" placeholder="Open a folder..." readonly>
<button class="explorer-browse-btn" id="explorer-browse" title="Browse folder">&#x1F4C2;</button>
</div>
<div class="explorer-tree" id="explorer-tree"></div>
</div>
`;
document.getElementById('explorer-browse')?.addEventListener('click', async () => {
const dir = await listDirectory(null); // null means open folder dialog
if (dir) {
document.getElementById('explorer-path').value = dir.path;
renderTree(
document.getElementById('explorer-tree'),
dir.entries,
listDirectory,
onFileOpen,
dir.path
);
}
});
if (currentDir) {
listDirectory(currentDir).then((dir) => {
if (dir)
renderTree(
document.getElementById('explorer-tree'),
dir.entries,
listDirectory,
onFileOpen,
currentDir
);
});
}
}
function renderTree(container, entries, listDirectory, onFileOpen, _basePath) {
container.innerHTML = entries
.map((entry) => {
if (entry.isDirectory) {
return `<div class="tree-item tree-folder collapsed" data-path="${entry.path}">
<span class="tree-icon">&#x25B6;</span>
<span class="tree-name">${entry.name}</span>
<div class="tree-children"></div>
</div>`;
}
return `<div class="tree-item tree-file" data-path="${entry.path}">
<span class="tree-icon">${getFileIcon(entry.name)}</span>
<span class="tree-name">${entry.name}</span>
</div>`;
})
.join('');
container.querySelectorAll('.tree-folder').forEach((el) => {
el.querySelector('.tree-name').addEventListener('click', async () => {
const isCollapsed = el.classList.contains('collapsed');
if (isCollapsed) {
const dir = await listDirectory(el.dataset.path);
if (dir) {
const childContainer = el.querySelector('.tree-children');
renderTree(childContainer, dir.entries, listDirectory, onFileOpen, el.dataset.path);
}
}
el.classList.toggle('collapsed');
el.querySelector('.tree-icon').textContent = el.classList.contains('collapsed')
? '\u25B6'
: '\u25BC';
});
});
container.querySelectorAll('.tree-file').forEach((el) => {
el.addEventListener('click', () => onFileOpen(el.dataset.path));
});
}
function getFileIcon(filename) {
const ext = filename.split('.').pop().toLowerCase();
const icons = {
md: '\u{1F4DD}',
js: '\u{1F4DC}',
json: '{}',
html: '\u{1F310}',
css: '\u{1F3A8}',
py: '\u{1F40D}',
pdf: '\u{1F4D5}',
txt: '\u{1F4C4}',
};
return icons[ext] || '\u{1F4C4}';
}
module.exports = { renderExplorerPanel };
+226
View File
@@ -0,0 +1,226 @@
// Escape repo-derived strings (branch/file names, commit messages, git stderr) before
// interpolating them into innerHTML. Quotes are included so attribute contexts
// (data-file, data-branch) cannot be broken out of.
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function renderGitPanel(
container,
{ gitStatus, gitDiff, gitStage, gitCommit, gitLog, gitBranches, gitCheckout, gitPush, gitPull }
) {
container.innerHTML = `
<div class="git-panel">
<div class="git-section">
<h4 class="git-section-title">Branches</h4>
<div class="git-branches" id="git-branches">
<p class="git-loading">Loading...</p>
</div>
<div class="git-branch-new">
<input type="text" class="git-branch-input" id="git-branch-input" placeholder="New branch name..." />
<button class="git-branch-create-btn" id="git-branch-create-btn">Create</button>
</div>
<div class="git-remote-actions">
<button class="git-push-btn" id="git-push-btn">Push</button>
<button class="git-pull-btn" id="git-pull-btn">Pull</button>
</div>
<p class="git-remote-status" id="git-remote-status"></p>
</div>
<div class="git-section">
<h4 class="git-section-title">Changes</h4>
<div class="git-changes" id="git-changes">
<p class="git-loading">Loading...</p>
</div>
<pre class="git-diff-view" id="git-diff-view" style="display:none;"></pre>
</div>
<div class="git-section">
<h4 class="git-section-title">Commit</h4>
<textarea class="git-commit-input" id="git-commit-msg" placeholder="Commit message..." rows="3"></textarea>
<button class="git-commit-btn" id="git-commit-btn">Commit</button>
</div>
<div class="git-section">
<h4 class="git-section-title">Recent Commits</h4>
<div class="git-log" id="git-log"></div>
</div>
</div>
`;
loadGitStatus();
loadGitBranches();
async function loadGitStatus() {
const status = await gitStatus();
const changesEl = document.getElementById('git-changes');
if (!status || !changesEl) return;
if (status.error) {
changesEl.innerHTML = `<p class="git-info">${escapeHtml(status.error)}</p>`;
return;
}
const files = [
...status.modified.map((f) => ({ file: f, status: 'M', color: '#f59e0b' })),
...status.not_added.map((f) => ({ file: f, status: '?', color: '#6b7280' })),
...status.created.map((f) => ({ file: f, status: 'A', color: '#10b981' })),
...status.deleted.map((f) => ({ file: f, status: 'D', color: '#ef4444' })),
...status.staged.map((f) => ({ file: f, status: 'S', color: '#3b82f6' })),
];
if (files.length === 0) {
changesEl.innerHTML = '<p class="git-info">No changes</p>';
} else {
changesEl.innerHTML = files
.map(
(f) => `
<div class="git-file" data-file="${escapeHtml(f.file)}">
<span class="git-file-status" style="color:${f.color}">${f.status}</span>
<span class="git-file-name">${escapeHtml(f.file)}</span>
<button class="git-diff-btn" data-file="${escapeHtml(f.file)}" title="View diff">diff</button>
<button class="git-stage-btn" data-file="${escapeHtml(f.file)}" title="Stage file">+</button>
</div>
`
)
.join('');
changesEl.querySelectorAll('.git-stage-btn').forEach((btn) => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
await gitStage([btn.dataset.file]);
loadGitStatus();
});
});
changesEl.querySelectorAll('.git-diff-btn').forEach((btn) => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
await showDiff(btn.dataset.file);
});
});
}
// Load log
const log = await gitLog();
const logEl = document.getElementById('git-log');
if (log && logEl) {
logEl.innerHTML =
(log.all || [])
.slice(0, 10)
.map(
(entry) => `
<div class="git-log-entry">
<div class="git-log-msg">${escapeHtml(entry.message)}</div>
<div class="git-log-meta">${entry.date?.substring(0, 10) || ''} &middot; ${escapeHtml(entry.author_name || '')}</div>
</div>
`
)
.join('') || '<p class="git-info">No commits</p>';
}
}
async function showDiff(file) {
const diffView = document.getElementById('git-diff-view');
if (!diffView || !gitDiff) return;
const result = await gitDiff(file);
diffView.textContent =
result && result.error ? result.error : result && result.length ? result : 'No changes';
diffView.style.display = 'block';
}
async function loadGitBranches() {
const branchesEl = document.getElementById('git-branches');
if (!gitBranches || !branchesEl) return;
const result = await gitBranches();
if (!result) return;
if (result.error) {
branchesEl.innerHTML = `<p class="git-info">${escapeHtml(result.error)}</p>`;
return;
}
const names = result.all || [];
const current = result.current;
if (names.length === 0) {
branchesEl.innerHTML = '<p class="git-info">No branches</p>';
return;
}
branchesEl.innerHTML = names
.map(
(name) => `
<div class="git-branch-item${name === current ? ' git-branch-current' : ''}" data-branch="${escapeHtml(name)}">
<span class="git-branch-name">${name === current ? '&#9679; ' : ''}${escapeHtml(name)}</span>
${name === current ? '' : `<button class="git-checkout-btn" data-branch="${escapeHtml(name)}" title="Checkout branch">checkout</button>`}
</div>
`
)
.join('');
branchesEl.querySelectorAll('.git-checkout-btn').forEach((btn) => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
const result = await gitCheckout(btn.dataset.branch, false);
if (result && result.error) {
const statusEl = document.getElementById('git-remote-status');
if (statusEl) statusEl.textContent = `Checkout failed: ${result.error}`;
}
loadGitBranches();
loadGitStatus();
});
});
}
document.getElementById('git-commit-btn')?.addEventListener('click', async () => {
const msg = document.getElementById('git-commit-msg')?.value?.trim();
if (!msg) return;
await gitCommit(msg);
document.getElementById('git-commit-msg').value = '';
loadGitStatus();
});
document.getElementById('git-branch-create-btn')?.addEventListener('click', async () => {
const input = document.getElementById('git-branch-input');
const name = input?.value?.trim();
if (!name || !gitCheckout) return;
const result = await gitCheckout(name, true);
const statusEl = document.getElementById('git-remote-status');
if (result && result.error) {
if (statusEl) statusEl.textContent = `Create branch failed: ${result.error}`;
} else {
input.value = '';
if (statusEl) statusEl.textContent = '';
}
loadGitBranches();
loadGitStatus();
});
document.getElementById('git-push-btn')?.addEventListener('click', async () => {
const statusEl = document.getElementById('git-remote-status');
if (!gitPush) return;
const result = await gitPush();
if (statusEl) {
statusEl.textContent =
result && result.error ? `Push failed: ${result.error}` : 'Push complete';
}
});
document.getElementById('git-pull-btn')?.addEventListener('click', async () => {
const statusEl = document.getElementById('git-remote-status');
if (!gitPull) return;
const result = await gitPull();
if (statusEl) {
statusEl.textContent =
result && result.error ? `Pull failed: ${result.error}` : 'Pull complete';
}
loadGitStatus();
loadGitBranches();
});
}
module.exports = { renderGitPanel };
+120
View File
@@ -0,0 +1,120 @@
/**
* Document Outline Panel
* Parses markdown headings and renders a navigable tree in the sidebar.
*/
function renderOutlinePanel(container, { getEditorContent, getActiveLine, onHeadingClick }) {
container.innerHTML = `
<div class="outline-panel">
<div class="outline-list" id="outline-list"></div>
</div>
`;
const listEl = document.getElementById('outline-list');
let headings = [];
let activeLine = 1;
let debounceTimer = null;
function parseHeadings(content) {
const result = [];
if (!content) return result;
const lines = content.split('\n');
const regex = /^(#{1,6})\s+(.+)$/;
for (let i = 0; i < lines.length; i++) {
const match = regex.exec(lines[i]);
if (match) {
result.push({
level: match[1].length,
text: match[2].trim(),
line: i + 1,
});
}
}
return result;
}
function findActiveHeading(currentLine) {
let active = null;
for (const h of headings) {
if (h.line <= currentLine) {
active = h;
} else {
break;
}
}
return active;
}
function renderHeadings() {
const content = getEditorContent();
headings = parseHeadings(content);
activeLine = getActiveLine();
if (headings.length === 0) {
listEl.innerHTML = `
<div class="outline-empty">
<p>No headings found</p>
<p class="outline-hint"># Heading 1</p>
<p class="outline-hint">## Heading 2</p>
<p class="outline-hint">### Heading 3</p>
</div>
`;
return;
}
const activeHeading = findActiveHeading(activeLine);
listEl.innerHTML =
headings
.map(
(h, idx) => `
<div class="outline-item outline-level-${h.level}${activeHeading && h.line === activeHeading.line ? ' active' : ''}"
data-line="${h.line}" data-index="${idx}">
<span class="outline-text">${escapeHtml(h.text)}</span>
<span class="outline-badge">H${h.level}</span>
</div>
`
)
.join('') +
`<div class="outline-footer">${headings.length} heading${headings.length !== 1 ? 's' : ''}</div>`;
listEl.querySelectorAll('.outline-item').forEach((item) => {
item.addEventListener('click', () => {
const line = parseInt(item.dataset.line, 10);
onHeadingClick(line);
});
});
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function refresh() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(renderHeadings, 300);
}
function setActiveHeading(line) {
activeLine = line;
const activeHeading = findActiveHeading(line);
listEl.querySelectorAll('.outline-item').forEach((item) => {
const itemLine = parseInt(item.dataset.line, 10);
if (activeHeading && itemLine === activeHeading.line) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
container._refreshOutline = refresh;
container._setActiveHeading = setActiveHeading;
renderHeadings();
}
module.exports = { renderOutlinePanel };
+52
View File
@@ -0,0 +1,52 @@
class SidebarManager {
constructor() {
this.sidebar = document.getElementById('sidebar');
this.panelContent = document.getElementById('sidebar-panel-content');
this.panelTitle = document.querySelector('.sidebar-panel-title');
this.activePanel = null;
this.panels = new Map();
this.setupEventListeners();
}
setupEventListeners() {
document.querySelectorAll('.sidebar-icon').forEach((btn) => {
btn.addEventListener('click', () => this.togglePanel(btn.dataset.panel));
});
document
.querySelector('.sidebar-panel-close')
?.addEventListener('click', () => this.collapse());
}
registerPanel(name, { title, render }) {
this.panels.set(name, { title, render });
}
togglePanel(name) {
if (this.activePanel === name) {
this.collapse();
} else {
this.expand(name);
}
}
expand(name) {
const panel = this.panels.get(name);
if (!panel) return;
this.sidebar.classList.remove('collapsed');
this.panelTitle.textContent = panel.title;
this.panelContent.innerHTML = '';
panel.render(this.panelContent);
this.activePanel = name;
document.querySelectorAll('.sidebar-icon').forEach((btn) => {
btn.classList.toggle('active', btn.dataset.panel === name);
});
}
collapse() {
this.sidebar.classList.add('collapsed');
this.activePanel = null;
document.querySelectorAll('.sidebar-icon').forEach((btn) => btn.classList.remove('active'));
}
}
module.exports = { SidebarManager };
+83
View File
@@ -0,0 +1,83 @@
function renderSnippetsPanel(container, { getSnippets, saveSnippet, deleteSnippet, onInsert }) {
container.innerHTML = `
<div class="snippets-panel">
<div class="snippets-toolbar">
<input type="text" class="snippets-search" id="snippets-search" placeholder="Search snippets...">
<button class="snippets-add-btn" id="snippets-add" title="Add snippet">+</button>
</div>
<div class="snippets-list" id="snippets-list"></div>
</div>
`;
let snippets = [];
async function loadSnippets() {
snippets = (await getSnippets()) || [];
renderList(document.getElementById('snippets-search')?.value || '');
}
function renderList(query) {
const list = document.getElementById('snippets-list');
if (!list) return;
const filtered = query
? snippets.filter(
(s) =>
s.name.toLowerCase().includes(query.toLowerCase()) ||
(s.language || '').toLowerCase().includes(query.toLowerCase())
)
: snippets;
list.innerHTML = filtered.length
? filtered
.map(
(s) => `
<div class="snippet-item" data-id="${s.id}">
<div class="snippet-header">
<span class="snippet-name">${s.name}</span>
<span class="snippet-lang">${s.language || 'text'}</span>
</div>
<pre class="snippet-preview"><code>${(s.code || '').substring(0, 100)}${(s.code || '').length > 100 ? '...' : ''}</code></pre>
<div class="snippet-actions">
<button class="snippet-insert" data-id="${s.id}" title="Insert">Insert</button>
<button class="snippet-delete" data-id="${s.id}" title="Delete">&times;</button>
</div>
</div>
`
)
.join('')
: '<p class="git-info">No snippets yet. Click + to add one.</p>';
list.querySelectorAll('.snippet-insert').forEach((btn) => {
btn.addEventListener('click', () => {
const s = snippets.find((sn) => sn.id === btn.dataset.id);
if (s) onInsert(s.code);
});
});
list.querySelectorAll('.snippet-delete').forEach((btn) => {
btn.addEventListener('click', async () => {
await deleteSnippet(btn.dataset.id);
loadSnippets();
});
});
}
document
.getElementById('snippets-search')
?.addEventListener('input', (e) => renderList(e.target.value));
document.getElementById('snippets-add')?.addEventListener('click', () => {
const name = prompt('Snippet name:');
if (!name) return;
const language = prompt('Language (e.g., javascript, python, html):') || 'text';
const code = prompt('Paste your code snippet:');
if (!code) return;
saveSnippet({ id: Date.now().toString(), name, language, code }).then(() => loadSnippets());
});
loadSnippets();
}
module.exports = { renderSnippetsPanel };

Some files were not shown because too many files have changed in this diff Show More