Compare commits

..
60 Commits
Author SHA1 Message Date
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
91 changed files with 34057 additions and 23253 deletions
+25
View File
@@ -0,0 +1,25 @@
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
+99
View File
@@ -0,0 +1,99 @@
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 rpmbuild
run: sudo apt-get update && sudo apt-get install -y rpm
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build Linux packages
run: npm run build:linux
- 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: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- name: Install Wine and NSIS
run: |
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install -y wine64 wine32 nsis
- name: Install dependencies
run: npm ci
- name: Build Windows packages
run: npm run build:win
- name: Upload Windows artifacts
uses: actions/upload-artifact@v4
with:
name: windows-artifacts
path: |
dist/*.exe
dist/*-win.zip
retention-days: 5
release:
needs: [build-linux, build-windows]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download Linux artifacts
uses: actions/download-artifact@v4
with:
name: linux-artifacts
path: dist
- name: Download Windows artifacts
uses: actions/download-artifact@v4
with:
name: windows-artifacts
path: dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
files: dist/*
+36 -36
View File
@@ -1,36 +1,36 @@
node_modules/ node_modules/
dist/ dist/
*.log *.log
.DS_Store .DS_Store
Thumbs.db Thumbs.db
.env .env
.env.local .env.local
*.swp *.swp
*.swo *.swo
*~ *~
.vscode/ .vscode/
.idea/ .idea/
*.iml *.iml
out/ out/
.cache/ .cache/
.npm/ .npm/
.electron/ .electron/
package-lock.json package-lock.json
# Screenshots and temp files # Screenshots and temp files
*.png.bak *.png.bak
Screen.png Screen.png
dark.png dark.png
light.png light.png
pdf.png pdf.png
uvmodal.png uvmodal.png
nul nul
*.tmp *.tmp
# Development screenshots # Development screenshots
pdf\ modal.png pdf\ modal.png
# Claude/AI development files # Claude/AI development files
.claude/ .claude/
CLAUDE.md CLAUDE.md
agents.md agents.mdcoverage/
+11 -11
View File
@@ -1,11 +1,11 @@
{ {
"semi": true, "semi": true,
"singleQuote": true, "singleQuote": true,
"tabWidth": 2, "tabWidth": 2,
"useTabs": false, "useTabs": false,
"trailingComma": "es5", "trailingComma": "es5",
"bracketSpacing": true, "bracketSpacing": true,
"arrowParens": "always", "arrowParens": "always",
"printWidth": 100, "printWidth": 100,
"endOfLine": "auto" "endOfLine": "auto"
} }
@@ -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
}
}
+102 -102
View File
@@ -1,103 +1,103 @@
# Export Functionality Fix - Summary # Export Functionality Fix - Summary
## Issues Found and Fixed ## Issues Found and Fixed
### 1. **Primary Issue: Pandoc Installation Problem** ### 1. **Primary Issue: Pandoc Installation Problem**
- **Problem**: Pandoc is installed but has a system error (paging file too small) - **Problem**: Pandoc is installed but has a system error (paging file too small)
- **Impact**: All pandoc-dependent exports (DOCX, LaTeX, etc.) were failing - **Impact**: All pandoc-dependent exports (DOCX, LaTeX, etc.) were failing
- **Solution**: Added robust fallback mechanisms - **Solution**: Added robust fallback mechanisms
### 2. **Export Function Improvements** ### 2. **Export Function Improvements**
#### Before (Issues): #### Before (Issues):
- ❌ No pandoc availability checking - ❌ No pandoc availability checking
- ❌ Poor error messages - ❌ Poor error messages
- ❌ No fallback for missing pandoc - ❌ No fallback for missing pandoc
- ❌ Limited debugging information - ❌ Limited debugging information
#### After (Fixed): #### After (Fixed):
-**Pandoc Detection**: Automatically checks if pandoc is available -**Pandoc Detection**: Automatically checks if pandoc is available
-**Built-in HTML Export**: Works without pandoc using marked library -**Built-in HTML Export**: Works without pandoc using marked library
-**Built-in PDF Export**: Works without pandoc using Electron's printToPDF -**Built-in PDF Export**: Works without pandoc using Electron's printToPDF
-**Better Error Messages**: Clear instructions for users -**Better Error Messages**: Clear instructions for users
-**Comprehensive Logging**: Debug information in console -**Comprehensive Logging**: Debug information in console
-**Graceful Fallbacks**: Falls back to built-in converters when pandoc fails -**Graceful Fallbacks**: Falls back to built-in converters when pandoc fails
## How It Works Now ## How It Works Now
### Export Process Flow: ### Export Process Flow:
1. **User clicks export** → Check if file is saved 1. **User clicks export** → Check if file is saved
2. **Select output location** → Show save dialog 2. **Select output location** → Show save dialog
3. **Check pandoc availability** → Async pandoc detection 3. **Check pandoc availability** → Async pandoc detection
4. **Choose export method**: 4. **Choose export method**:
- **If pandoc available**: Use pandoc with format-specific options - **If pandoc available**: Use pandoc with format-specific options
- **If pandoc not available**: - **If pandoc not available**:
- HTML → Use built-in marked converter - HTML → Use built-in marked converter
- PDF → Use Electron's printToPDF - PDF → Use Electron's printToPDF
- Other formats → Show helpful error with installation guide - Other formats → Show helpful error with installation guide
### Supported Export Formats: ### Supported Export Formats:
#### ✅ **Always Work** (no pandoc required): #### ✅ **Always Work** (no pandoc required):
- **HTML**: Built-in converter using marked library - **HTML**: Built-in converter using marked library
- **PDF**: Built-in converter using Electron - **PDF**: Built-in converter using Electron
#### ✅ **Work with Pandoc** (better quality): #### ✅ **Work with Pandoc** (better quality):
- **DOCX**: Microsoft Word format - **DOCX**: Microsoft Word format
- **LaTeX**: LaTeX document - **LaTeX**: LaTeX document
- **RTF**: Rich Text Format - **RTF**: Rich Text Format
- **ODT**: OpenDocument Text - **ODT**: OpenDocument Text
- **EPUB**: E-book format - **EPUB**: E-book format
- **PPTX**: PowerPoint presentations - **PPTX**: PowerPoint presentations
- **ODP**: OpenDocument Presentations - **ODP**: OpenDocument Presentations
## Testing the Fixes ## Testing the Fixes
### Manual Test Procedure: ### Manual Test Procedure:
1. **Start the application**: `npm start` 1. **Start the application**: `npm start`
2. **Open test file**: Load `test-export.md` 2. **Open test file**: Load `test-export.md`
3. **Test HTML export**: File → Export → HTML (should work) 3. **Test HTML export**: File → Export → HTML (should work)
4. **Test PDF export**: File → Export → PDF (should work) 4. **Test PDF export**: File → Export → PDF (should work)
5. **Test DOCX export**: File → Export → DOCX (will show pandoc error) 5. **Test DOCX export**: File → Export → DOCX (will show pandoc error)
### Expected Behavior: ### Expected Behavior:
- **HTML/PDF exports**: Should work immediately and create files - **HTML/PDF exports**: Should work immediately and create files
- **Other format exports**: Should show informative error about pandoc - **Other format exports**: Should show informative error about pandoc
- **Console logs**: Should show debug information about export process - **Console logs**: Should show debug information about export process
## Fix Summary ## Fix Summary
### Code Changes Made: ### Code Changes Made:
1. **Added `checkPandocAvailability()` function** - Detects pandoc 1. **Added `checkPandocAvailability()` function** - Detects pandoc
2. **Added `exportToHTML()` function** - Built-in HTML export 2. **Added `exportToHTML()` function** - Built-in HTML export
3. **Added `exportToPDFElectron()` function** - Built-in PDF export 3. **Added `exportToPDFElectron()` function** - Built-in PDF export
4. **Added `exportWithPandoc()` helper** - Generic pandoc export 4. **Added `exportWithPandoc()` helper** - Generic pandoc export
5. **Added `exportWithPandocPDF()` helper** - PDF with fallbacks 5. **Added `exportWithPandocPDF()` helper** - PDF with fallbacks
6. **Improved `exportFile()` function** - Main export logic with detection 6. **Improved `exportFile()` function** - Main export logic with detection
7. **Enhanced error handling** - Better user messages 7. **Enhanced error handling** - Better user messages
8. **Added comprehensive logging** - Debug information 8. **Added comprehensive logging** - Debug information
### Files Modified: ### Files Modified:
- `src/main.js` - Enhanced export functionality - `src/main.js` - Enhanced export functionality
- `test-export.md` - Created test file - `test-export.md` - Created test file
- `test-export-functionality.js` - Created test script - `test-export-functionality.js` - Created test script
## User Instructions ## User Instructions
### For Users Without Pandoc: ### For Users Without Pandoc:
-**HTML and PDF exports work perfectly** -**HTML and PDF exports work perfectly**
-**No additional software needed** -**No additional software needed**
-**Professional-looking output with proper styling** -**Professional-looking output with proper styling**
### For Users Who Want All Formats: ### For Users Who Want All Formats:
1. **Install Pandoc**: Visit https://pandoc.org/installing.html 1. **Install Pandoc**: Visit https://pandoc.org/installing.html
2. **For PDF with LaTeX**: Also install MiKTeX or TeX Live 2. **For PDF with LaTeX**: Also install MiKTeX or TeX Live
3. **Restart the application** after installation 3. **Restart the application** after installation
4. **All export formats will then be available** 4. **All export formats will then be available**
## Result ## Result
🎉 **Export functionality is now working reliably!** 🎉 **Export functionality is now working reliably!**
- Built-in exports (HTML, PDF) work without any dependencies - Built-in exports (HTML, PDF) work without any dependencies
- Clear error messages guide users for advanced formats - Clear error messages guide users for advanced formats
- Robust error handling prevents crashes - Robust error handling prevents crashes
- Better user experience with informative dialogs - Better user experience with informative dialogs
+82 -82
View File
@@ -1,82 +1,82 @@
# GEMINI.md # GEMINI.md
## Project Overview ## Project Overview
This project is a cross-platform Markdown editor and converter named **PanConverter**. It is built using the Electron framework, allowing it to run on Windows, macOS, and Linux. The application provides a rich text editor for writing Markdown, a live preview pane, and robust export capabilities powered by Pandoc. This project is a cross-platform Markdown editor and converter named **PanConverter**. It is built using the Electron framework, allowing it to run on Windows, macOS, and Linux. The application provides a rich text editor for writing Markdown, a live preview pane, and robust export capabilities powered by Pandoc.
The core technologies used are: The core technologies used are:
- **Electron:** For creating the desktop application. - **Electron:** For creating the desktop application.
- **JavaScript:** The primary programming language. - **JavaScript:** The primary programming language.
- **Pandoc:** For converting Markdown to various formats like PDF, DOCX, HTML, etc. - **Pandoc:** For converting Markdown to various formats like PDF, DOCX, HTML, etc.
- **Marked:** For parsing and rendering the Markdown preview in real-time. - **Marked:** For parsing and rendering the Markdown preview in real-time.
- **CodeMirror:** As the underlying text editor component. - **CodeMirror:** As the underlying text editor component.
- **highlight.js:** For syntax highlighting in the editor. - **highlight.js:** For syntax highlighting in the editor.
- **DOMPurify:** To sanitize the HTML output in the preview pane for security. - **DOMPurify:** To sanitize the HTML output in the preview pane for security.
The application features a tabbed interface for working with multiple files, various themes, find and replace functionality, and detailed document statistics. The application features a tabbed interface for working with multiple files, various themes, find and replace functionality, and detailed document statistics.
## Building and Running ## Building and Running
To build and run this project locally, you will need to have Node.js and npm installed. To build and run this project locally, you will need to have Node.js and npm installed.
### Installation ### Installation
1. **Clone the repository:** 1. **Clone the repository:**
```bash ```bash
git clone https://github.com/amitwh/pan-converter.git git clone https://github.com/amitwh/pan-converter.git
cd pan-converter cd pan-converter
``` ```
2. **Install dependencies:** 2. **Install dependencies:**
```bash ```bash
npm install npm install
``` ```
### Running the Application ### Running the Application
To run the application in development mode, use the following command: To run the application in development mode, use the following command:
```bash ```bash
npm start npm start
``` ```
### Building the Application ### Building the Application
You can build the application for different platforms using the scripts defined in `package.json`. You can build the application for different platforms using the scripts defined in `package.json`.
- **Build for the current platform:** - **Build for the current platform:**
```bash ```bash
npm run build npm run build
``` ```
- **Build for a specific platform:** - **Build for a specific platform:**
```bash ```bash
npm run build:win # For Windows npm run build:win # For Windows
npm run build:mac # For macOS npm run build:mac # For macOS
npm run build:linux # For Linux npm run build:linux # For Linux
``` ```
- **Build for all platforms at once:** - **Build for all platforms at once:**
```bash ```bash
npm run dist:all npm run dist:all
``` ```
The distributable files will be located in the `dist/` directory. The distributable files will be located in the `dist/` directory.
### Testing ### Testing
The project does not have a dedicated test suite configured. The `test` script in `package.json` currently returns an error. The project does not have a dedicated test suite configured. The `test` script in `package.json` currently returns an error.
```bash ```bash
npm test npm test
``` ```
## Development Conventions ## Development Conventions
- **Code Style:** The codebase is written in JavaScript (ES6+). There is no linter or formatter configured, but the code generally follows standard JavaScript conventions. - **Code Style:** The codebase is written in JavaScript (ES6+). There is no linter or formatter configured, but the code generally follows standard JavaScript conventions.
- **Main vs. Renderer Process:** The application logic is split between the Electron main process (`src/main.js`) and the renderer process (`src/renderer.js`). - **Main vs. Renderer Process:** The application logic is split between the Electron main process (`src/main.js`) and the renderer process (`src/renderer.js`).
- `src/main.js` handles window management, application menus, file system operations, and communication with the operating system. - `src/main.js` handles window management, application menus, file system operations, and communication with the operating system.
- `src/renderer.js` manages the user interface, editor functionality, and the Markdown preview. - `src/renderer.js` manages the user interface, editor functionality, and the Markdown preview.
- **Dependencies:** Project dependencies are managed through `package.json`. `devDependencies` are used for the build process, while `dependencies` are required for the application to run. - **Dependencies:** Project dependencies are managed through `package.json`. `devDependencies` are used for the build process, while `dependencies` are required for the application to run.
- **User Data:** The application stores settings and recent files in the user's application data directory. - **User Data:** The application stores settings and recent files in the user's application data directory.
- **Pandoc Integration:** The application relies on a system-installed version of Pandoc for its export functionality. It does not bundle Pandoc. - **Pandoc Integration:** The application relies on a system-installed version of Pandoc for its export functionality. It does not bundle Pandoc.
+1478 -1478
View File
File diff suppressed because it is too large Load Diff
+20 -20
View File
@@ -1,21 +1,21 @@
MIT License MIT License
Copyright (c) 2024 Amit Haridas Copyright (c) 2024 Amit Haridas
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
+12 -12
View File
@@ -1,12 +1,12 @@
# Test Double-Click File Opening # Test Double-Click File Opening
This is a test file to verify double-click functionality. This is a test file to verify double-click functionality.
## Features to Test ## Features to Test
- File should load automatically - File should load automatically
- Content should display in editor - Content should display in editor
- Tab should show filename - Tab should show filename
- Preview should render markdown - Preview should render markdown
**This text should be bold** **This text should be bold**
*This text should be italic* *This text should be italic*
+378 -378
View File
@@ -1,378 +1,378 @@
\hypertarget{panconverter}{% \hypertarget{panconverter}{%
\section{PanConverter}\label{panconverter}} \section{PanConverter}\label{panconverter}}
A cross-platform Markdown editor and converter powered by Pandoc. A cross-platform Markdown editor and converter powered by Pandoc.
\begin{figure} \begin{figure}
\centering \centering
\includegraphics{assets/icon.png} \includegraphics{assets/icon.png}
\caption{PanConverter} \caption{PanConverter}
\end{figure} \end{figure}
\hypertarget{features}{% \hypertarget{features}{%
\subsection{Features}\label{features}} \subsection{Features}\label{features}}
\hypertarget{advanced-markdown-editor}{% \hypertarget{advanced-markdown-editor}{%
\subsubsection{✨ Advanced Markdown \subsubsection{✨ Advanced Markdown
Editor}\label{advanced-markdown-editor}} Editor}\label{advanced-markdown-editor}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
🗂️ \textbf{Tabbed Interface} - Work with multiple files simultaneously 🗂️ \textbf{Tabbed Interface} - Work with multiple files simultaneously
in separate tabs in separate tabs
\item \item
📝 \textbf{Rich Text Editor} - Full-featured editor with syntax 📝 \textbf{Rich Text Editor} - Full-featured editor with syntax
highlighting and comprehensive toolbar highlighting and comprehensive toolbar
\item \item
🔍 \textbf{Find \& Replace} - Powerful search and replace with match 🔍 \textbf{Find \& Replace} - Powerful search and replace with match
highlighting and navigation highlighting and navigation
\item \item
🔢 \textbf{Line Numbers} - Toggle line numbers for easier code editing 🔢 \textbf{Line Numbers} - Toggle line numbers for easier code editing
and navigation and navigation
\item \item
↩️ \textbf{Smart Auto-Indentation} - Automatic list continuation and ↩️ \textbf{Smart Auto-Indentation} - Automatic list continuation and
intelligent indentation intelligent indentation
\item \item
⏪ \textbf{Undo/Redo} - Full undo/redo support with keyboard shortcuts ⏪ \textbf{Undo/Redo} - Full undo/redo support with keyboard shortcuts
\item \item
⌨️ \textbf{Advanced Shortcuts} - Tab indentation, line selection, and ⌨️ \textbf{Advanced Shortcuts} - Tab indentation, line selection, and
smart text formatting smart text formatting
\item \item
📂 \textbf{File Association Support} - Open markdown files directly 📂 \textbf{File Association Support} - Open markdown files directly
from file manager from file manager
\end{itemize} \end{itemize}
\hypertarget{themes-interface}{% \hypertarget{themes-interface}{%
\subsubsection{🎨 Themes \& Interface}\label{themes-interface}} \subsubsection{🎨 Themes \& Interface}\label{themes-interface}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
👁️ \textbf{Live Preview} - See your markdown rendered in real-time 👁️ \textbf{Live Preview} - See your markdown rendered in real-time
with synchronized scrolling with synchronized scrolling
\item \item
🎨 \textbf{Multiple Themes} - Choose from Light, Dark, Solarized, 🎨 \textbf{Multiple Themes} - Choose from Light, Dark, Solarized,
Monokai, or GitHub themes Monokai, or GitHub themes
\item \item
💾 \textbf{Auto-Save} - Never lose your work with automatic saving 💾 \textbf{Auto-Save} - Never lose your work with automatic saving
every 30 seconds every 30 seconds
\end{itemize} \end{itemize}
\hypertarget{export-conversion}{% \hypertarget{export-conversion}{%
\subsubsection{📤 Export \& Conversion}\label{export-conversion}} \subsubsection{📤 Export \& Conversion}\label{export-conversion}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
📄 \textbf{Enhanced PDF Export} - Robust PDF generation with multiple 📄 \textbf{Enhanced PDF Export} - Robust PDF generation with multiple
LaTeX engine fallbacks (XeLaTeX, PDFLaTeX, wkhtmltopdf) LaTeX engine fallbacks (XeLaTeX, PDFLaTeX, wkhtmltopdf)
\item \item
📄 \textbf{Document Export} - Convert to HTML, DOCX, LaTeX, RTF, ODT, 📄 \textbf{Document Export} - Convert to HTML, DOCX, LaTeX, RTF, ODT,
EPUB, PowerPoint (PPTX), and OpenDocument Presentation (ODP) EPUB, PowerPoint (PPTX), and OpenDocument Presentation (ODP)
\item \item
📊 \textbf{Spreadsheet Export} - Export markdown tables to Excel 📊 \textbf{Spreadsheet Export} - Export markdown tables to Excel
(XLSX/XLS) and OpenDocument Spreadsheet (ODS) formats (XLSX/XLS) and OpenDocument Spreadsheet (ODS) formats
\item \item
📥 \textbf{Document Import} - Import DOCX, ODT, RTF, HTML, PDF, and 📥 \textbf{Document Import} - Import DOCX, ODT, RTF, HTML, PDF, and
presentation files to markdown presentation files to markdown
\item \item
📋 \textbf{Table Creation Helper} - Built-in table generator for easy 📋 \textbf{Table Creation Helper} - Built-in table generator for easy
markdown table creation markdown table creation
\end{itemize} \end{itemize}
\hypertarget{platform-support}{% \hypertarget{platform-support}{%
\subsubsection{🖥️ Platform Support}\label{platform-support}} \subsubsection{🖥️ Platform Support}\label{platform-support}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{Cross-Platform} - Works seamlessly on Windows, macOS, and \textbf{Cross-Platform} - Works seamlessly on Windows, macOS, and
Linux Linux
\end{itemize} \end{itemize}
\hypertarget{installation}{% \hypertarget{installation}{%
\subsection{Installation}\label{installation}} \subsection{Installation}\label{installation}}
\hypertarget{prerequisites}{% \hypertarget{prerequisites}{%
\subsubsection{Prerequisites}\label{prerequisites}} \subsubsection{Prerequisites}\label{prerequisites}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\href{https://pandoc.org/installing.html}{Pandoc} must be installed \href{https://pandoc.org/installing.html}{Pandoc} must be installed
for export functionality for export functionality
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{Ubuntu/Debian}: \texttt{sudo\ apt-get\ install\ pandoc} \textbf{Ubuntu/Debian}: \texttt{sudo\ apt-get\ install\ pandoc}
\item \item
\textbf{macOS}: \texttt{brew\ install\ pandoc} \textbf{macOS}: \texttt{brew\ install\ pandoc}
\item \item
\textbf{Windows}: Download installer from Pandoc website \textbf{Windows}: Download installer from Pandoc website
\end{itemize} \end{itemize}
\end{itemize} \end{itemize}
\hypertarget{pdf-export-requirements}{% \hypertarget{pdf-export-requirements}{%
\subsubsection{PDF Export Requirements}\label{pdf-export-requirements}} \subsubsection{PDF Export Requirements}\label{pdf-export-requirements}}
For optimal PDF export, install a LaTeX engine (recommended): - For optimal PDF export, install a LaTeX engine (recommended): -
\textbf{Ubuntu/Debian}: \textbf{Ubuntu/Debian}:
\texttt{sudo\ apt-get\ install\ texlive-xetex\ texlive-latex-base} - \texttt{sudo\ apt-get\ install\ texlive-xetex\ texlive-latex-base} -
\textbf{macOS}: \texttt{brew\ install\ -\/-cask\ mactex} - \textbf{macOS}: \texttt{brew\ install\ -\/-cask\ mactex} -
\textbf{Windows}: Install MiKTeX or TeX Live - \textbf{Alternative}: \textbf{Windows}: Install MiKTeX or TeX Live - \textbf{Alternative}:
\texttt{sudo\ apt-get\ install\ wkhtmltopdf} (fallback option) \texttt{sudo\ apt-get\ install\ wkhtmltopdf} (fallback option)
\hypertarget{download}{% \hypertarget{download}{%
\subsubsection{Download}\label{download}} \subsubsection{Download}\label{download}}
Download the latest release for your platform from the Download the latest release for your platform from the
\href{https://github.com/amitwh/pan-converter/releases}{Releases} page. \href{https://github.com/amitwh/pan-converter/releases}{Releases} page.
\hypertarget{linux}{% \hypertarget{linux}{%
\paragraph{Linux}\label{linux}} \paragraph{Linux}\label{linux}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{AppImage}: \texttt{PanConverter-1.3.1.AppImage} (universal, \textbf{AppImage}: \texttt{PanConverter-1.3.1.AppImage} (universal,
may require \texttt{-\/-no-sandbox} flag) may require \texttt{-\/-no-sandbox} flag)
\item \item
\textbf{Debian Package}: \texttt{pan-converter\_1.3.1\_amd64.deb} \textbf{Debian Package}: \texttt{pan-converter\_1.3.1\_amd64.deb}
\item \item
\textbf{Snap Package}: \texttt{pan-converter\_1.3.1\_amd64.snap} \textbf{Snap Package}: \texttt{pan-converter\_1.3.1\_amd64.snap}
\end{itemize} \end{itemize}
\hypertarget{install-from-source}{% \hypertarget{install-from-source}{%
\subsubsection{Install from Source}\label{install-from-source}} \subsubsection{Install from Source}\label{install-from-source}}
\begin{Shaded} \begin{Shaded}
\begin{Highlighting}[] \begin{Highlighting}[]
\FunctionTok{git}\NormalTok{ clone https://github.com/amitwh/pan{-}converter.git} \FunctionTok{git}\NormalTok{ clone https://github.com/amitwh/pan{-}converter.git}
\BuiltInTok{cd}\NormalTok{ pan{-}converter} \BuiltInTok{cd}\NormalTok{ pan{-}converter}
\ExtensionTok{npm}\NormalTok{ install} \ExtensionTok{npm}\NormalTok{ install}
\ExtensionTok{npm}\NormalTok{ start} \ExtensionTok{npm}\NormalTok{ start}
\end{Highlighting} \end{Highlighting}
\end{Shaded} \end{Shaded}
\hypertarget{usage}{% \hypertarget{usage}{%
\subsection{Usage}\label{usage}} \subsection{Usage}\label{usage}}
\hypertarget{basic-workflow}{% \hypertarget{basic-workflow}{%
\subsubsection{Basic Workflow}\label{basic-workflow}} \subsubsection{Basic Workflow}\label{basic-workflow}}
\begin{enumerate} \begin{enumerate}
\def\labelenumi{\arabic{enumi}.} \def\labelenumi{\arabic{enumi}.}
\tightlist \tightlist
\item \item
\textbf{Write} - Use the editor to write your Markdown content \textbf{Write} - Use the editor to write your Markdown content
\item \item
\textbf{Preview} - Toggle the preview pane to see rendered output \textbf{Preview} - Toggle the preview pane to see rendered output
\item \item
\textbf{Theme} - Choose your preferred theme from the View menu \textbf{Theme} - Choose your preferred theme from the View menu
\item \item
\textbf{Export} - Export your document to various formats \textbf{Export} - Export your document to various formats
\end{enumerate} \end{enumerate}
\hypertarget{export-options}{% \hypertarget{export-options}{%
\subsubsection{Export Options}\label{export-options}} \subsubsection{Export Options}\label{export-options}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{Documents}: HTML, PDF, DOCX, LaTeX, RTF, ODT, EPUB \textbf{Documents}: HTML, PDF, DOCX, LaTeX, RTF, ODT, EPUB
\item \item
\textbf{Presentations}: PowerPoint (PPTX), OpenDocument Presentation \textbf{Presentations}: PowerPoint (PPTX), OpenDocument Presentation
(ODP) (ODP)
\item \item
\textbf{Spreadsheets}: Excel (XLSX/XLS), OpenDocument Spreadsheet \textbf{Spreadsheets}: Excel (XLSX/XLS), OpenDocument Spreadsheet
(ODS) (ODS)
\end{itemize} \end{itemize}
\hypertarget{import-conversion}{% \hypertarget{import-conversion}{%
\subsubsection{Import \& Conversion}\label{import-conversion}} \subsubsection{Import \& Conversion}\label{import-conversion}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{Import Documents}: Convert DOCX, ODT, RTF, HTML, PDF, and \textbf{Import Documents}: Convert DOCX, ODT, RTF, HTML, PDF, and
presentation files to Markdown presentation files to Markdown
\item \item
\textbf{Cross-Format Conversion}: Convert current file between \textbf{Cross-Format Conversion}: Convert current file between
multiple formats multiple formats
\item \item
\textbf{Smart Presentation Handling}: Automatic slide-level formatting \textbf{Smart Presentation Handling}: Automatic slide-level formatting
for PPTX/ODP exports for PPTX/ODP exports
\end{itemize} \end{itemize}
\hypertarget{table-creation}{% \hypertarget{table-creation}{%
\subsubsection{Table Creation}\label{table-creation}} \subsubsection{Table Creation}\label{table-creation}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
Click the table button in the toolbar Click the table button in the toolbar
\item \item
Specify number of rows and columns Specify number of rows and columns
\item \item
Automatically generates properly formatted Markdown tables Automatically generates properly formatted Markdown tables
\end{itemize} \end{itemize}
\hypertarget{keyboard-shortcuts}{% \hypertarget{keyboard-shortcuts}{%
\subsection{Keyboard Shortcuts}\label{keyboard-shortcuts}} \subsection{Keyboard Shortcuts}\label{keyboard-shortcuts}}
\hypertarget{file-operations}{% \hypertarget{file-operations}{%
\subsubsection{File Operations}\label{file-operations}} \subsubsection{File Operations}\label{file-operations}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\texttt{Ctrl/Cmd\ +\ N} - New file/tab \texttt{Ctrl/Cmd\ +\ N} - New file/tab
\item \item
\texttt{Ctrl/Cmd\ +\ T} - New tab \texttt{Ctrl/Cmd\ +\ T} - New tab
\item \item
\texttt{Ctrl/Cmd\ +\ W} - Close current tab \texttt{Ctrl/Cmd\ +\ W} - Close current tab
\item \item
\texttt{Ctrl/Cmd\ +\ Tab} - Switch to next tab \texttt{Ctrl/Cmd\ +\ Tab} - Switch to next tab
\item \item
\texttt{Ctrl/Cmd\ +\ O} - Open file \texttt{Ctrl/Cmd\ +\ O} - Open file
\item \item
\texttt{Ctrl/Cmd\ +\ S} - Save file \texttt{Ctrl/Cmd\ +\ S} - Save file
\item \item
\texttt{Ctrl/Cmd\ +\ Shift\ +\ S} - Save as \texttt{Ctrl/Cmd\ +\ Shift\ +\ S} - Save as
\item \item
\texttt{Ctrl/Cmd\ +\ I} - Import document \texttt{Ctrl/Cmd\ +\ I} - Import document
\end{itemize} \end{itemize}
\hypertarget{editor-features}{% \hypertarget{editor-features}{%
\subsubsection{Editor Features}\label{editor-features}} \subsubsection{Editor Features}\label{editor-features}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\texttt{Ctrl/Cmd\ +\ F} - Find \& Replace \texttt{Ctrl/Cmd\ +\ F} - Find \& Replace
\item \item
\texttt{Ctrl/Cmd\ +\ Z} - Undo \texttt{Ctrl/Cmd\ +\ Z} - Undo
\item \item
\texttt{Ctrl/Cmd\ +\ Shift\ +\ Z} - Redo \texttt{Ctrl/Cmd\ +\ Shift\ +\ Z} - Redo
\item \item
\texttt{Tab} - Indent lines or insert 4 spaces \texttt{Tab} - Indent lines or insert 4 spaces
\item \item
\texttt{Shift\ +\ Tab} - Outdent selected lines \texttt{Shift\ +\ Tab} - Outdent selected lines
\item \item
\texttt{Enter} - Auto-continue lists with proper indentation \texttt{Enter} - Auto-continue lists with proper indentation
\end{itemize} \end{itemize}
\hypertarget{view-navigation}{% \hypertarget{view-navigation}{%
\subsubsection{View \& Navigation}\label{view-navigation}} \subsubsection{View \& Navigation}\label{view-navigation}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\texttt{Ctrl/Cmd\ +\ P} - Toggle preview \texttt{Ctrl/Cmd\ +\ P} - Toggle preview
\item \item
\texttt{Ctrl/Cmd\ +\ Enter} - Toggle preview (alternative) \texttt{Ctrl/Cmd\ +\ Enter} - Toggle preview (alternative)
\item \item
\texttt{Escape} - Close find dialog \texttt{Escape} - Close find dialog
\end{itemize} \end{itemize}
\hypertarget{building}{% \hypertarget{building}{%
\subsection{Building}\label{building}} \subsection{Building}\label{building}}
\begin{Shaded} \begin{Shaded}
\begin{Highlighting}[] \begin{Highlighting}[]
\CommentTok{\# Install dependencies} \CommentTok{\# Install dependencies}
\ExtensionTok{npm}\NormalTok{ install} \ExtensionTok{npm}\NormalTok{ install}
\CommentTok{\# Generate icons} \CommentTok{\# Generate icons}
\ExtensionTok{npm}\NormalTok{ run generate{-}icons} \ExtensionTok{npm}\NormalTok{ run generate{-}icons}
\CommentTok{\# Build for current platform} \CommentTok{\# Build for current platform}
\ExtensionTok{npm}\NormalTok{ run build} \ExtensionTok{npm}\NormalTok{ run build}
\CommentTok{\# Build for specific platform} \CommentTok{\# Build for specific platform}
\ExtensionTok{npm}\NormalTok{ run build:win }\CommentTok{\# Windows} \ExtensionTok{npm}\NormalTok{ run build:win }\CommentTok{\# Windows}
\ExtensionTok{npm}\NormalTok{ run build:mac }\CommentTok{\# macOS } \ExtensionTok{npm}\NormalTok{ run build:mac }\CommentTok{\# macOS }
\ExtensionTok{npm}\NormalTok{ run build:linux }\CommentTok{\# Linux (generates .deb, .AppImage, and .snap)} \ExtensionTok{npm}\NormalTok{ run build:linux }\CommentTok{\# Linux (generates .deb, .AppImage, and .snap)}
\CommentTok{\# Build for all platforms} \CommentTok{\# Build for all platforms}
\ExtensionTok{npm}\NormalTok{ run dist:all} \ExtensionTok{npm}\NormalTok{ run dist:all}
\end{Highlighting} \end{Highlighting}
\end{Shaded} \end{Shaded}
\hypertarget{version-history}{% \hypertarget{version-history}{%
\subsection{Version History}\label{version-history}} \subsection{Version History}\label{version-history}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
\textbf{v1.3.1} - Bug fixes: Fixed file associations for \textbf{v1.3.1} - Bug fixes: Fixed file associations for
double-clicking .md files, corrected 50/50 layout alignment for double-clicking .md files, corrected 50/50 layout alignment for
editor/preview panes editor/preview panes
\item \item
\textbf{v1.3.0} - Major update: Tabbed interface for multiple files, \textbf{v1.3.0} - Major update: Tabbed interface for multiple files,
enhanced PDF export with LaTeX engines, fixed file associations, enhanced PDF export with LaTeX engines, fixed file associations,
removed redundant converter menu, improved UI architecture removed redundant converter menu, improved UI architecture
\item \item
\textbf{v1.2.1} - Comprehensive editor enhancements: Find \& Replace, \textbf{v1.2.1} - Comprehensive editor enhancements: Find \& Replace,
Line Numbers, Undo/Redo, Auto-indentation, PowerPoint export, document Line Numbers, Undo/Redo, Auto-indentation, PowerPoint export, document
conversion menu, table creation helper, spreadsheet export conversion menu, table creation helper, spreadsheet export
\item \item
\textbf{v1.1.0} - Added Excel/ODS spreadsheet export, updated author \textbf{v1.1.0} - Added Excel/ODS spreadsheet export, updated author
information, renamed to PanConverter information, renamed to PanConverter
\item \item
\textbf{v1.0.0} - Initial release with basic markdown editing, themes, \textbf{v1.0.0} - Initial release with basic markdown editing, themes,
and Pandoc export and Pandoc export
\end{itemize} \end{itemize}
\hypertarget{known-issues}{% \hypertarget{known-issues}{%
\subsection{Known Issues}\label{known-issues}} \subsection{Known Issues}\label{known-issues}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
AppImage may require \texttt{-\/-no-sandbox} flag on some Linux AppImage may require \texttt{-\/-no-sandbox} flag on some Linux
systems systems
\item \item
Windows/Mac builds require platform-specific build environments Windows/Mac builds require platform-specific build environments
\item \item
Large files may cause performance issues Large files may cause performance issues
\end{itemize} \end{itemize}
\hypertarget{contributing}{% \hypertarget{contributing}{%
\subsection{Contributing}\label{contributing}} \subsection{Contributing}\label{contributing}}
Contributions are welcome! Please feel free to submit a Pull Request to Contributions are welcome! Please feel free to submit a Pull Request to
the \href{https://github.com/amitwh/pan-converter}{GitHub repository}. the \href{https://github.com/amitwh/pan-converter}{GitHub repository}.
\hypertarget{license}{% \hypertarget{license}{%
\subsection{License}\label{license}} \subsection{License}\label{license}}
MIT License - see LICENSE file for details. MIT License - see LICENSE file for details.
\hypertarget{author}{% \hypertarget{author}{%
\subsection{Author}\label{author}} \subsection{Author}\label{author}}
\textbf{Amit Haridas} - \textbf{Amit Haridas} -
\href{mailto:amit.wh@gmail.com}{\nolinkurl{amit.wh@gmail.com}} \href{mailto:amit.wh@gmail.com}{\nolinkurl{amit.wh@gmail.com}}
\hypertarget{acknowledgments}{% \hypertarget{acknowledgments}{%
\subsection{Acknowledgments}\label{acknowledgments}} \subsection{Acknowledgments}\label{acknowledgments}}
\begin{itemize} \begin{itemize}
\tightlist \tightlist
\item \item
Built with \href{https://www.electronjs.org/}{Electron} Built with \href{https://www.electronjs.org/}{Electron}
\item \item
Markdown parsing by \href{https://marked.js.org/}{marked} Markdown parsing by \href{https://marked.js.org/}{marked}
\item \item
Export functionality powered by \href{https://pandoc.org/}{Pandoc} Export functionality powered by \href{https://pandoc.org/}{Pandoc}
\item \item
Syntax highlighting by \href{https://highlightjs.org/}{highlight.js} Syntax highlighting by \href{https://highlightjs.org/}{highlight.js}
\item \item
Spreadsheet export by \href{https://www.npmjs.com/package/xlsx}{XLSX} Spreadsheet export by \href{https://www.npmjs.com/package/xlsx}{XLSX}
\item \item
HTML sanitization by HTML sanitization by
\href{https://www.npmjs.com/package/dompurify}{DOMPurify} \href{https://www.npmjs.com/package/dompurify}{DOMPurify}
\end{itemize} \end{itemize}
+165 -165
View File
@@ -1,165 +1,165 @@
# MarkdownConverter # MarkdownConverter
A powerful cross-platform Markdown editor and document converter powered by Pandoc, built with Electron. 100% open-source with no proprietary dependencies. A powerful cross-platform Markdown editor and document converter powered by Pandoc, built with Electron. 100% open-source with no proprietary dependencies.
## Features ## Features
### Markdown Editor ### Markdown Editor
<img width="1920" height="1032" alt="image" src="https://github.com/user-attachments/assets/5f53ba94-7663-47c3-b12b-b7b8bd2645aa" /> <img width="1920" height="1032" alt="image" src="https://github.com/user-attachments/assets/5f53ba94-7663-47c3-b12b-b7b8bd2645aa" />
- **Multi-tab editing** - Work on multiple files simultaneously - **Multi-tab editing** - Work on multiple files simultaneously
- **Live preview** - Real-time markdown rendering with syntax highlighting - **Live preview** - Real-time markdown rendering with syntax highlighting
- **Dynamic splitter** - Drag to resize editor and preview panes - **Dynamic splitter** - Drag to resize editor and preview panes
- **25+ themes** - Light and dark themes including Atom One Light, Dracula, Nord, Sepia, and more - **25+ themes** - Light and dark themes including Atom One Light, Dracula, Nord, Sepia, and more
- **Find & Replace** - Search and replace with regex support - **Find & Replace** - Search and replace with regex support
- **Line numbers** - Toggle line numbers in the editor - **Line numbers** - Toggle line numbers in the editor
- **Auto-save** - Automatic saving every 30 seconds - **Auto-save** - Automatic saving every 30 seconds
- **Math support** - KaTeX integration for mathematical expressions - **Math support** - KaTeX integration for mathematical expressions
### PDF Viewer & Editor ### PDF Viewer & Editor
<img width="1920" height="1032" alt="image" src="https://github.com/user-attachments/assets/f10f62be-af3d-496e-81df-37ab4f91abfd" /> <img width="1920" height="1032" alt="image" src="https://github.com/user-attachments/assets/f10f62be-af3d-496e-81df-37ab4f91abfd" />
- **Built-in PDF viewer** - Open and view PDF files directly in the app - **Built-in PDF viewer** - Open and view PDF files directly in the app
- **Page navigation** - Navigate pages with keyboard or buttons - **Page navigation** - Navigate pages with keyboard or buttons
- **Zoom controls** - Zoom in/out, fit to width, fit to page - **Zoom controls** - Zoom in/out, fit to width, fit to page
- **Rotation** - Rotate pages left or right - **Rotation** - Rotate pages left or right
- **PDF Editor tools**: - **PDF Editor tools**:
- Merge multiple PDFs - Merge multiple PDFs
- Split PDFs by page range - Split PDFs by page range
- Compress PDFs - Compress PDFs
- Rotate pages - Rotate pages
- Delete pages - Delete pages
- Reorder pages - Reorder pages
- Add watermarks - Add watermarks
- Password protection - Password protection
- Remove passwords - Remove passwords
- Set permissions - Set permissions
### Export Options ### Export Options
- **PDF** - Export to PDF with customizable page sizes and orientation - **PDF** - Export to PDF with customizable page sizes and orientation
- **DOCX** - Standard and Enhanced (template-based) Word export - **DOCX** - Standard and Enhanced (template-based) Word export
- **ODT** - OpenDocument format - **ODT** - OpenDocument format
- **HTML** - Web-ready HTML export - **HTML** - Web-ready HTML export
- **PowerPoint** - PPTX presentation export - **PowerPoint** - PPTX presentation export
- **EPUB** - E-book format - **EPUB** - E-book format
- **LaTeX** - Academic document format - **LaTeX** - Academic document format
- **RTF** - Rich Text Format - **RTF** - Rich Text Format
### Advanced Features ### Advanced Features
- **Custom headers & footers** - Add headers/footers to exports with dynamic fields - **Custom headers & footers** - Add headers/footers to exports with dynamic fields
- **Page size configuration** - A3, A4, A5, B4, B5, Letter, Legal, Tabloid, or custom sizes - **Page size configuration** - A3, A4, A5, B4, B5, Letter, Legal, Tabloid, or custom sizes
- **Batch conversion** - Convert entire folders of markdown files - **Batch conversion** - Convert entire folders of markdown files
- **ASCII Art Generator** - Create text banners and diagrams - **ASCII Art Generator** - Create text banners and diagrams
- **Word templates** - Use custom Word templates for enhanced exports - **Word templates** - Use custom Word templates for enhanced exports
- **Import documents** - Import from 30+ formats (DOCX, PDF, HTML, etc.) - **Import documents** - Import from 30+ formats (DOCX, PDF, HTML, etc.)
## Installation ## Installation
### Prerequisites ### Prerequisites
- [Node.js](https://nodejs.org/) (v16 or later) - [Node.js](https://nodejs.org/) (v16 or later)
- [Pandoc](https://pandoc.org/installing.html) (required for export functionality) - [Pandoc](https://pandoc.org/installing.html) (required for export functionality)
### Install Dependencies ### Install Dependencies
```bash ```bash
npm install npm install
``` ```
### Run the Application ### Run the Application
```bash ```bash
npm start npm start
``` ```
### Build for Distribution ### Build for Distribution
```bash ```bash
# Windows # Windows
npm run build:win npm run build:win
# macOS # macOS
npm run build:mac npm run build:mac
# Linux # Linux
npm run build:linux npm run build:linux
``` ```
## Keyboard Shortcuts ## Keyboard Shortcuts
| Action | Shortcut | | Action | Shortcut |
|--------|----------| |--------|----------|
| New File | Ctrl+N | | New File | Ctrl+N |
| Open File | Ctrl+O | | Open File | Ctrl+O |
| Open PDF | Ctrl+Shift+O | | Open PDF | Ctrl+Shift+O |
| Save | Ctrl+S | | Save | Ctrl+S |
| Save As | Ctrl+Shift+S | | Save As | Ctrl+Shift+S |
| Export | Ctrl+E | | Export | Ctrl+E |
| Print | Ctrl+P | | Print | Ctrl+P |
| Find | Ctrl+F | | Find | Ctrl+F |
| Undo | Ctrl+Z | | Undo | Ctrl+Z |
| Redo | Ctrl+Shift+Z | | Redo | Ctrl+Shift+Z |
| New Tab | Ctrl+T | | New Tab | Ctrl+T |
| Close Tab | Ctrl+W | | Close Tab | Ctrl+W |
| Toggle Preview | Ctrl+Shift+P | | Toggle Preview | Ctrl+Shift+P |
| Zoom In | Ctrl+Shift++ | | Zoom In | Ctrl+Shift++ |
| Zoom Out | Ctrl+Shift+- | | Zoom Out | Ctrl+Shift+- |
## Themes ## Themes
### Light Themes ### Light Themes
- Atom One Light (Default) - Atom One Light (Default)
- GitHub Light - GitHub Light
- Light - Light
- Solarized Light - Solarized Light
- Gruvbox Light - Gruvbox Light
- Ayu Light - Ayu Light
- Sepia - Sepia
- Paper - Paper
- Rose Pine Dawn - Rose Pine Dawn
- Concrete Light - Concrete Light
### Dark Themes ### Dark Themes
- Dark - Dark
- One Dark - One Dark
- Dracula - Dracula
- Nord - Nord
- Monokai - Monokai
- Material - Material
- Gruvbox Dark - Gruvbox Dark
- Tokyo Night - Tokyo Night
- Palenight - Palenight
- Ayu Dark - Ayu Dark
- Ayu Mirage - Ayu Mirage
- Oceanic Next - Oceanic Next
- Cobalt2 - Cobalt2
- Concrete Dark - Concrete Dark
- Concrete Warm - Concrete Warm
## PDF Viewer ## PDF Viewer
Open PDF files directly in MarkdownConverter: Open PDF files directly in MarkdownConverter:
- **File > Open PDF** or **Ctrl+Shift+O** - **File > Open PDF** or **Ctrl+Shift+O**
- Navigate pages with arrow buttons or page input - Navigate pages with arrow buttons or page input
- Zoom controls: +/- buttons, Fit Width, Fit Page - Zoom controls: +/- buttons, Fit Width, Fit Page
- Rotate pages left or right - Rotate pages left or right
- Close PDF to return to editor - Close PDF to return to editor
## Open Source ## Open Source
MarkdownConverter is 100% open-source. All dependencies are permissively licensed: MarkdownConverter is 100% open-source. All dependencies are permissively licensed:
- **Electron** - MIT License - **Electron** - MIT License
- **pdf-lib** - MIT License - **pdf-lib** - MIT License
- **pdfjs-dist** - Apache 2.0 License - **pdfjs-dist** - Apache 2.0 License
- **marked** - MIT License - **marked** - MIT License
- **highlight.js** - BSD 3-Clause License - **highlight.js** - BSD 3-Clause License
- **dompurify** - Apache 2.0/MIT License - **dompurify** - Apache 2.0/MIT License
- **docx** - MIT License - **docx** - MIT License
- **xlsx** - Apache 2.0 License (SheetJS Community Edition) - **xlsx** - Apache 2.0 License (SheetJS Community Edition)
## License ## License
MIT License - see LICENSE file for details. MIT License - see LICENSE file for details.
## Author ## Author
Amit Haridas (amit.wh@gmail.com) Amit Haridas (amit.wh@gmail.com)
## Version ## Version
v3.0.0 v3.0.0
+217 -166
View File
@@ -1,166 +1,217 @@
# PanConverter - Updates & Changelog # PanConverter - Updates & Changelog
## Version 2.1.0 (December 14, 2025) ## Version 4.0.0 (2026-03-04)
### 🎨 UI/UX Improvements ### Major Changes
- **CodeMirror 6 Editor** — Replaced textarea with CodeMirror 6 featuring syntax highlighting, code folding, bracket matching, multiple cursors, and auto-indent
#### Subtle & Small Preview Popout Button - **Sidebar Panel System** — Collapsible sidebar with File Explorer, Git, Snippets, and Templates panels
- Redesigned popout button with minimalist aesthetic - **Command Palette** — Ctrl+Shift+P to search and execute all app actions
- Removed border for cleaner appearance - **Code Execution (REPL)** — Run JavaScript, Python, and Bash code blocks directly from the preview
- Reduced size: 11px font, 2px×6px padding (previously 14px font, 4px×8px padding)
- Added opacity transition: 50% when idle, 100% on hover ### New Features
- Subtle background effect on hover instead of heavy border styling - Print Preview dialog with paper size, orientation, margins, scale, and page range controls
- **File**: `src/styles.css:195-211` - 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)
#### Simplified Table Headers in Preview - Markdown extensions: footnotes, admonitions (note/warning/tip/danger/info), and [[toc]] table of contents
- Removed gradient background from table headers in modern theme - PlantUML diagram rendering alongside Mermaid
- Changed from `var(--primary-gradient)` (purple gradient) to simple light gray (#f0f0f0) - Welcome tab with onboarding and "What's New" feature showcase
- Updated text color to dark (#333333) for better readability - System spell checking with context menu suggestions and dictionary support
- Clean, professional appearance matching standard themes - Enhanced status bar with word count, character count, line/column, encoding, and language mode
- **File**: `src/styles-modern.css:445-449` - Grouped toolbar with visual section separators
- Breadcrumb bar showing current file path
### 📥 Enhanced Import Capabilities
### New Export/Import Formats
#### Comprehensive Format-to-Markdown Conversion - Reveal.js slides (.html)
Dramatically expanded the "Import Document" feature to support 30+ file formats: - Beamer slides (.pdf)
- Confluence/Jira wiki markup (.txt)
**Supported Formats:** - MOBI e-books (via Calibre)
- **Documents**: DOCX, ODT, RTF, HTML, HTM, TEX, EPUB, PDF, TXT - Developer formats: JSON, YAML, XML, TOML
- **Presentations**: PPTX, ODP
- **Markup Languages**: RST, Textile, MediaWiki, Org-mode, AsciiDoc, TWiki, OPML ### Security
- **E-book Formats**: EPUB, FB2 - Content Security Policy (CSP) meta tag
- **LaTeX Formats**: TEX, LATEX, LTX - File size validation (50MB limit)
- **Web Formats**: HTML, HTM, XHTML - Error message sanitization (stripped file paths)
- **Wiki Formats**: MediaWiki, DokuWiki, TikiWiki, TWiki - Conversion rate limiting (2-second debounce)
- **Data Formats**: CSV, TSV, JSON
### Dependencies Updated
**Format-Specific Optimizations:** - marked: 16.x to 17.x (with marked-highlight extension)
- PDF text extraction with XeLaTeX engine - pdfjs-dist: 3.x to 5.x (new worker model)
- CSV/TSV automatic table conversion - html2pdf.js: 0.10 to 0.14
- JSON structure handling - pdfkit: 0.14 to 0.17
- Improved error messages with format hints - dompurify, docx, and others updated to latest
**Access**: File → Import Document (Ctrl+I) ### Testing
**File**: `src/main.js:1933-1994` - 80 tests across 7 test suites
- New tests for sidebar manager, command palette, print preview, markdown extensions, and utility functions
### 🎨 Exhaustive ASCII Art Generator
### Breaking Changes
#### 5 New Text Banner Styles - Editor is now CodeMirror 6 (replaces textarea)
Complete alphabet (A-Z) and numbers (0-9) support for all styles: - marked API changed to use marked.use() instead of marked.setOptions()
- pdfjs-dist upgraded to v5 with new worker model
1. **Standard** - Classic ASCII art with slashes and underscores
2. **Banner** - Large format using # characters (7-line height) ---
3. **Block** - Modern Unicode block characters (█ ╔ ╗ ═ ║)
4. **Bubble** - Circular bubble letters (Ⓐ Ⓑ Ⓒ) ## Version 2.1.0 (December 14, 2025)
5. **Digital** - Digital display style (▄ ▀ ▐ ▌)
### 🎨 UI/UX Improvements
**File**: `src/renderer.js:3397-3537`
#### Subtle & Small Preview Popout Button
#### 19 Professional ASCII Templates - Redesigned popout button with minimalist aesthetic
Organized into 4 categories with expanded options: - Removed border for cleaner appearance
- Reduced size: 11px font, 2px×6px padding (previously 14px font, 4px×8px padding)
**Arrows & Flow (4 templates):** - Added opacity transition: 50% when idle, 100% on hover
- Arrow Right - Horizontal flow indicators - Subtle background effect on hover instead of heavy border styling
- Arrow Down - Vertical flow indicators - **File**: `src/styles.css:195-211`
- Decision - Binary decision diagrams
- Process Flow - Multi-step process visualization #### Simplified Table Headers in Preview
- Removed gradient background from table headers in modern theme
**Diagrams & Charts (6 templates):** - Changed from `var(--primary-gradient)` (purple gradient) to simple light gray (#f0f0f0)
- Flowchart - Advanced flowchart with decision branches and loops - Updated text color to dark (#333333) for better readability
- Sequence - Sequence diagrams for User-System-Database interactions - Clean, professional appearance matching standard themes
- Network - Server-client network topology - **File**: `src/styles-modern.css:445-449`
- Hierarchy - Organizational tree structures
- Timeline - Milestone visualization with dates ### 📥 Enhanced Import Capabilities
- Table Simple - Basic table template with borders
#### Comprehensive Format-to-Markdown Conversion
**Boxes & Containers (4 templates):** Dramatically expanded the "Import Document" feature to support 30+ file formats:
- Header - Section header with decorative borders
- Note Box - Important notes with rounded corners (┏━━┓) **Supported Formats:**
- Warning Box - Warning messages with bold borders (╔═══╗) - **Documents**: DOCX, ODT, RTF, HTML, HTM, TEX, EPUB, PDF, TXT
- Info Box - Information boxes with subtle styling (╭───╮) - **Presentations**: PPTX, ODP
- **Markup Languages**: RST, Textile, MediaWiki, Org-mode, AsciiDoc, TWiki, OPML
**Decorative Elements (6 templates):** - **E-book Formats**: EPUB, FB2
- Divider - Horizontal section separator (═══) - **LaTeX Formats**: TEX, LATEX, LTX
- Separator Fancy - Elegant rounded divider - **Web Formats**: HTML, HTM, XHTML
- Brackets - Japanese-style brackets 【 】 - **Wiki Formats**: MediaWiki, DokuWiki, TikiWiki, TWiki
- Banner Stars - Star-bordered banners - **Data Formats**: CSV, TSV, JSON
- Checklist - Task lists with ✓ checkmarks
- Progress Bar - Visual progress indicators **Format-Specific Optimizations:**
- PDF text extraction with XeLaTeX engine
**Features:** - CSV/TSV automatic table conversion
- All ASCII art automatically wrapped in code blocks for proper rendering - JSON structure handling
- Preserved formatting in markdown preview and all export formats - Improved error messages with format hints
- Categorized template selection interface
- Real-time preview generation **Access**: File → Import Document (Ctrl+I)
**File**: `src/main.js:1933-1994`
**Access**: Tools → ASCII Art Generator
**Files**: `src/renderer.js:3513-3671`, `src/index.html:427-466` ### 🎨 Exhaustive ASCII Art Generator
### 📝 Technical Improvements #### 5 New Text Banner Styles
Complete alphabet (A-Z) and numbers (0-9) support for all styles:
- Enhanced ASCII art detection in Word template exporter
- Improved monospace font rendering across all export formats 1. **Standard** - Classic ASCII art with slashes and underscores
- Better code block preservation in PDF and Word exports 2. **Banner** - Large format using # characters (7-line height)
- Optimized template categorization and organization 3. **Block** - Modern Unicode block characters (█ ╔ ╗ ═ ║)
4. **Bubble** - Circular bubble letters (Ⓐ Ⓑ Ⓒ)
### 🔧 Files Modified 5. **Digital** - Digital display style (▄ ▀ ▐ ▌)
- `src/styles.css` - Preview popout button styling **File**: `src/renderer.js:3397-3537`
- `src/styles-modern.css` - Table header simplification
- `src/main.js` - Enhanced import function, version update #### 19 Professional ASCII Templates
- `src/renderer.js` - ASCII art generator enhancements Organized into 4 categories with expanded options:
- `src/index.html` - ASCII template UI organization
- `package.json` - Version bump to 2.1.0 **Arrows & Flow (4 templates):**
- Arrow Right - Horizontal flow indicators
--- - Arrow Down - Vertical flow indicators
- Decision - Binary decision diagrams
## Version 2.0.0 (Previous Release) - Process Flow - Multi-step process visualization
### Major Features **Diagrams & Charts (6 templates):**
- Export Profiles - Save and reuse export configurations - Flowchart - Advanced flowchart with decision branches and loops
- Mermaid.js diagram support - Sequence - Sequence diagrams for User-System-Database interactions
- Command Palette (Ctrl+Shift+P) - Network - Server-client network topology
- GitHub Light/Dark preview themes - Hierarchy - Organizational tree structures
- Table Generator - Timeline - Milestone visualization with dates
- ASCII Art Generator (basic) - Table Simple - Basic table template with borders
- Resizable Preview Pane
- Pop-out Preview Window **Boxes & Containers (4 templates):**
- Configurable page sizes (A3-A5, B4-B5, Letter, Legal, Tabloid, Custom) - Header - Section header with decorative borders
- Custom Headers & Footers for exports - Note Box - Important notes with rounded corners (┏━━┓)
- Enhanced PDF and Word export with templates - Warning Box - Warning messages with bold borders (╔═══╗)
- 22 beautiful themes - Info Box - Information boxes with subtle styling (╭───╮)
### Core Capabilities **Decorative Elements (6 templates):**
- Cross-platform markdown editor with live preview - Divider - Horizontal section separator (═══)
- Universal document conversion (30+ formats) - Separator Fancy - Elegant rounded divider
- PDF Editor (merge, split, compress, rotate, watermark, encrypt) - Brackets - Japanese-style brackets 【 】
- Batch file conversion - Banner Stars - Star-bordered banners
- File association support - Checklist - Task lists with ✓ checkmarks
- Advanced export options - Progress Bar - Visual progress indicators
- Multi-tab interface
**Features:**
--- - All ASCII art automatically wrapped in code blocks for proper rendering
- Preserved formatting in markdown preview and all export formats
## Installation & Usage - Categorized template selection interface
- Real-time preview generation
### Prerequisites
- **Pandoc** - Required for document conversion **Access**: Tools → ASCII Art Generator
- **Optional**: LibreOffice, ImageMagick, FFmpeg for universal converter **Files**: `src/renderer.js:3513-3671`, `src/index.html:427-466`
### Download ### 📝 Technical Improvements
Get the latest release from: https://github.com/amitwh/pan-converter/releases
- Enhanced ASCII art detection in Word template exporter
### Supported Platforms - Improved monospace font rendering across all export formats
- Windows (x64) - Better code block preservation in PDF and Word exports
- Linux (AppImage, .deb, .snap) - Optimized template categorization and organization
- macOS (planned)
### 🔧 Files Modified
---
- `src/styles.css` - Preview popout button styling
## Contributing - `src/styles-modern.css` - Table header simplification
- `src/main.js` - Enhanced import function, version update
Contributions are welcome! Please see [CLAUDE.md](CLAUDE.md) for development guidelines. - `src/renderer.js` - ASCII art generator enhancements
- `src/index.html` - ASCII template UI organization
**Author**: Amit Haridas (amit.wh@gmail.com) - `package.json` - Version bump to 2.1.0
**License**: MIT
**Repository**: https://github.com/amitwh/pan-converter ---
## Version 2.0.0 (Previous Release)
### Major Features
- Export Profiles - Save and reuse export configurations
- Mermaid.js diagram support
- Command Palette (Ctrl+Shift+P)
- GitHub Light/Dark preview themes
- Table Generator
- ASCII Art Generator (basic)
- Resizable Preview Pane
- Pop-out Preview Window
- Configurable page sizes (A3-A5, B4-B5, Letter, Legal, Tabloid, Custom)
- Custom Headers & Footers for exports
- Enhanced PDF and Word export with templates
- 22 beautiful themes
### Core Capabilities
- Cross-platform markdown editor with live preview
- Universal document conversion (30+ formats)
- PDF Editor (merge, split, compress, rotate, watermark, encrypt)
- Batch file conversion
- File association support
- Advanced export options
- Multi-tab interface
---
## Installation & Usage
### Prerequisites
- **Pandoc** - Required for document conversion
- **Optional**: LibreOffice, ImageMagick, FFmpeg for universal converter
### Download
Get the latest release from: https://github.com/amitwh/pan-converter/releases
### Supported Platforms
- Windows (x64)
- Linux (AppImage, .deb, .snap)
- macOS (planned)
---
## Contributing
Contributions are welcome! Please see [CLAUDE.md](CLAUDE.md) for development guidelines.
**Author**: Amit Haridas (amit.wh@gmail.com)
**License**: MIT
**Repository**: https://github.com/amitwh/pan-converter
+866
View File
@@ -0,0 +1,866 @@
# MarkdownConverter - STRIDE Threat Model Analysis
**Version:** 4.0.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*
+111 -89
View File
@@ -1,89 +1,111 @@
/** /**
* ESLint Configuration for PanConverter * ESLint Configuration for PanConverter
* Uses flat config format (ESLint 9+) * Uses flat config format (ESLint 9+)
*/ */
module.exports = [ module.exports = [
{ {
// Global ignores // Global ignores
ignores: [ ignores: [
'node_modules/**', 'node_modules/**',
'dist/**', 'dist/**',
'coverage/**', 'coverage/**',
'*.min.js' '*.min.js'
] ]
}, },
{ {
// JavaScript files // JavaScript files
files: ['**/*.js'], files: ['**/*.js'],
languageOptions: { languageOptions: {
ecmaVersion: 2022, ecmaVersion: 2022,
sourceType: 'module', sourceType: 'module',
globals: { globals: {
// Node.js // Node.js
require: 'readonly', require: 'readonly',
module: 'readonly', module: 'readonly',
exports: 'readonly', exports: 'readonly',
__dirname: 'readonly', __dirname: 'readonly',
__filename: 'readonly', __filename: 'readonly',
process: 'readonly', process: 'readonly',
Buffer: 'readonly', Buffer: 'readonly',
console: 'readonly', console: 'readonly',
setTimeout: 'readonly', setTimeout: 'readonly',
setInterval: 'readonly', setInterval: 'readonly',
clearTimeout: 'readonly', clearTimeout: 'readonly',
clearInterval: 'readonly', clearInterval: 'readonly',
// Browser // Browser
window: 'readonly', window: 'readonly',
document: 'readonly', document: 'readonly',
localStorage: 'readonly', localStorage: 'readonly',
alert: 'readonly', alert: 'readonly',
Event: 'readonly', prompt: 'readonly',
CustomEvent: 'readonly', confirm: 'readonly',
HTMLElement: 'readonly', Event: 'readonly',
MutationObserver: 'readonly', CustomEvent: 'readonly',
// Electron HTMLElement: 'readonly',
electronAPI: 'readonly', MutationObserver: 'readonly',
// Libraries TextEncoder: 'readonly',
marked: 'readonly', FileReader: 'readonly',
DOMPurify: 'readonly', requestAnimationFrame: 'readonly',
hljs: 'readonly', cancelAnimationFrame: 'readonly',
mermaid: 'readonly', navigator: 'readonly',
// Jest location: 'readonly',
jest: 'readonly', fetch: 'readonly',
describe: 'readonly', URL: 'readonly',
test: 'readonly', Blob: 'readonly',
expect: 'readonly', Image: 'readonly',
beforeEach: 'readonly', DragEvent: 'readonly',
afterEach: 'readonly', ClipboardEvent: 'readonly',
beforeAll: 'readonly', KeyboardEvent: 'readonly',
afterAll: 'readonly' MouseEvent: 'readonly',
} NodeList: 'readonly',
}, HTMLInputElement: 'readonly',
rules: { HTMLTextAreaElement: 'readonly',
// Error prevention getComputedStyle: 'readonly',
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }], // Electron
'no-undef': 'error', electronAPI: 'readonly',
'no-console': 'off', // Allow console for Electron apps // Libraries
marked: 'readonly',
// Code quality DOMPurify: 'readonly',
'eqeqeq': ['warn', 'always'], hljs: 'readonly',
'no-var': 'warn', mermaid: 'readonly',
'prefer-const': 'warn', // Node.js global object
global: 'writable',
// Style (handled by Prettier) // Jest
'semi': 'off', jest: 'readonly',
'quotes': 'off', describe: 'readonly',
'indent': 'off', test: 'readonly',
expect: 'readonly',
// Async handling beforeEach: 'readonly',
'no-async-promise-executor': 'warn', afterEach: 'readonly',
'require-await': 'off', beforeAll: 'readonly',
afterAll: 'readonly'
// Security }
'no-eval': 'error', },
'no-implied-eval': 'error', rules: {
'no-new-func': 'error' // Error prevention
} 'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
} 'no-undef': 'error',
]; 'no-console': 'off', // Allow console for Electron apps
// Code quality
'eqeqeq': ['warn', 'always'],
'no-var': 'warn',
'prefer-const': 'warn',
// Style (handled by Prettier)
'semi': 'off',
'quotes': 'off',
'indent': 'off',
// Async handling
'no-async-promise-executor': 'warn',
'require-await': 'off',
// Security
'no-eval': 'error',
'no-implied-eval': 'error',
'no-new-func': 'error'
}
}
];
+61 -59
View File
@@ -1,59 +1,61 @@
/** /**
* Jest Configuration for PanConverter * Jest Configuration for PanConverter
* @version 2.2.0 * @version 2.2.0
*/ */
module.exports = { module.exports = {
// Test environment // Test environment
testEnvironment: 'jsdom', testEnvironment: 'jsdom',
// Root directory // Root directory
rootDir: '.', rootDir: '.',
// Test file patterns // Test file patterns
testMatch: [ testMatch: [
'**/tests/**/*.test.js', '**/tests/**/*.test.js',
'**/tests/**/*.spec.js' '**/tests/**/*.spec.js'
], ],
// Coverage configuration // Coverage configuration
collectCoverageFrom: [ collectCoverageFrom: [
'src/**/*.js', 'src/**/*.js',
'!src/main.js', // Main process needs electron-mock '!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) ],
coverageThreshold: {
global: { // Coverage thresholds (raised with expanded test suite)
branches: 10, coverageThreshold: {
functions: 10, global: {
lines: 10, branches: 10,
statements: 10 functions: 15,
} lines: 15,
}, statements: 15
}
// Transform settings (no transpilation needed for vanilla JS) },
transform: {},
// Transform settings (no transpilation needed for vanilla JS)
// Module paths transform: {},
moduleDirectories: ['node_modules', 'src'],
// Module paths
// Setup files moduleDirectories: ['node_modules', 'src'],
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
// Setup files
// Ignore patterns setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
testPathIgnorePatterns: [
'/node_modules/', // Ignore patterns
'/dist/' testPathIgnorePatterns: [
], '/node_modules/',
'/dist/'
// Verbose output ],
verbose: true,
// Verbose output
// Clear mocks between tests verbose: true,
clearMocks: true,
// Clear mocks between tests
// Reset modules between tests clearMocks: true,
resetModules: true
}; // Reset modules between tests
resetModules: true
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+205 -181
View File
@@ -1,181 +1,205 @@
{ {
"name": "markdown-converter", "name": "markdown-converter",
"version": "3.0.0", "version": "4.1.0",
"description": "Professional Markdown editor and universal file converter with PDF editing, batch processing, and syntax highlighting", "description": "Professional Markdown editor and universal file converter with PDF editing, batch processing, and syntax highlighting",
"main": "src/main.js", "main": "src/main.js",
"scripts": { "scripts": {
"start": "electron .", "start": "electron .",
"test": "jest", "test": "jest",
"test:watch": "jest --watch", "test:watch": "jest --watch",
"test:coverage": "jest --coverage", "test:coverage": "jest --coverage",
"lint": "eslint src tests", "lint": "eslint src tests",
"lint:fix": "eslint src tests --fix", "lint:fix": "eslint src tests --fix",
"format": "prettier --write src tests", "format": "prettier --write src tests",
"format:check": "prettier --check src tests", "format:check": "prettier --check src tests",
"build": "electron-builder", "build": "electron-builder",
"build:win": "electron-builder --win", "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 CSC_KEY_PASSWORD=%CSC_KEY_PASSWORD% electron-builder --win",
"build:win-unsigned": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win", "build:win-unsigned": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win",
"build:mac": "electron-builder --mac", "build:mac": "electron-builder --mac",
"build:linux": "electron-builder --linux", "build:linux": "electron-builder --linux",
"dist": "electron-builder --publish=never", "build:local": "electron-builder --linux --win",
"dist:all": "electron-builder -mwl", "dist": "electron-builder --publish=never",
"generate-icons": "node scripts/generate-icons.js" "dist:all": "electron-builder -mwl",
}, "generate-icons": "node scripts/generate-icons.js"
"keywords": [ },
"markdown", "keywords": [
"pandoc", "markdown",
"converter", "pandoc",
"editor", "converter",
"pdf", "editor",
"audio", "pdf",
"video", "audio",
"image" "video",
], "image"
"author": "ConcreteInfo <amit.wh@gmail.com>", ],
"license": "MIT", "author": "ConcreteInfo <amit.wh@gmail.com>",
"repository": { "license": "MIT",
"type": "git", "repository": {
"url": "https://github.com/amitwh/markdown-converter" "type": "git",
}, "url": "https://github.com/amitwh/markdown-converter"
"devDependencies": { },
"@testing-library/dom": "^10.4.1", "devDependencies": {
"cross-env": "^10.0.0", "@testing-library/dom": "^10.4.1",
"electron": "^37.4.0", "cross-env": "^10.0.0",
"electron-builder": "^26.0.12", "electron": "^37.4.0",
"eslint": "^9.39.2", "electron-builder": "^26.0.12",
"eslint-config-prettier": "^10.1.8", "eslint": "^9.39.2",
"eslint-plugin-prettier": "^5.5.4", "eslint-config-prettier": "^10.1.8",
"jest": "^30.2.0", "eslint-plugin-prettier": "^5.5.4",
"jest-environment-jsdom": "^30.2.0", "jest": "^30.2.0",
"prettier": "^3.7.4", "jest-environment-jsdom": "^30.2.0",
"sharp": "^0.34.3" "prettier": "^3.7.4",
}, "sharp": "^0.34.3"
"dependencies": { },
"codemirror": "^6.0.2", "dependencies": {
"core-util-is": "^1.0.3", "@codemirror/autocomplete": "^6.20.1",
"docx": "^9.5.1", "@codemirror/commands": "^6.10.2",
"docx4js": "^3.3.0", "@codemirror/lang-css": "^6.3.1",
"dompurify": "^3.2.6", "@codemirror/lang-html": "^6.4.11",
"electron-store": "^10.1.0", "@codemirror/lang-javascript": "^6.2.5",
"highlight.js": "^11.11.1", "@codemirror/lang-json": "^6.0.2",
"html2pdf.js": "^0.10.1", "@codemirror/lang-markdown": "^6.5.0",
"marked": "^16.2.1", "@codemirror/lang-python": "^6.2.1",
"pdf-lib": "^1.17.1", "@codemirror/language": "^6.12.2",
"pdfjs-dist": "^3.11.174", "@codemirror/lint": "^6.9.5",
"pdfkit": "^0.14.0", "@codemirror/search": "^6.6.0",
"pizzip": "^3.2.0", "@codemirror/state": "^6.5.4",
"tslib": "^2.8.1", "@codemirror/theme-one-dark": "^6.1.3",
"xlsx": "^0.18.5" "@codemirror/view": "^6.39.16",
}, "codemirror": "^6.0.2",
"build": { "core-util-is": "^1.0.3",
"appId": "com.concreteinfo.markdownconverter", "docx": "^9.6.0",
"productName": "MarkdownConverter", "docx4js": "^3.3.0",
"directories": { "dompurify": "^3.3.1",
"output": "dist" "electron-store": "^10.1.0",
}, "highlight.js": "^11.11.1",
"icon": "assets/icon", "html2pdf.js": "^0.14.0",
"files": [ "marked": "^17.0.3",
"src/**/*", "marked-footnote": "^1.4.0",
"assets/**/*", "marked-highlight": "^2.2.3",
"scripts/**/*", "mermaid": "^11.12.3",
"node_modules/**/*", "pdf-lib": "^1.17.1",
"package.json" "pdfjs-dist": "^5.5.207",
], "pdfkit": "^0.17.2",
"fileAssociations": [ "pizzip": "^3.2.0",
{ "simple-git": "^3.32.3",
"ext": "md", "tslib": "^2.8.1"
"name": "Markdown Document", },
"description": "Markdown Document", "overrides": {
"mimeType": "text/markdown", "jszip": "^3.10.1",
"role": "Editor" "nth-check": "^2.1.1",
}, "lodash.pick": "npm:lodash@^4.17.21"
{ },
"ext": "markdown", "build": {
"name": "Markdown Document", "appId": "com.concreteinfo.markdownconverter",
"description": "Markdown Document", "productName": "MarkdownConverter",
"mimeType": "text/markdown", "directories": {
"role": "Editor" "output": "dist"
}, },
{ "icon": "assets/icon",
"ext": "pdf", "files": [
"name": "PDF Document", "src/**/*",
"description": "PDF Document", "assets/**/*",
"mimeType": "application/pdf", "scripts/**/*",
"role": "Editor" "node_modules/**/*",
} "package.json"
], ],
"mac": { "fileAssociations": [
"category": "public.app-category.productivity", {
"identity": null "ext": "md",
}, "name": "Markdown Document",
"win": { "description": "Markdown Document",
"target": [ "mimeType": "text/markdown",
{ "role": "Editor"
"target": "nsis", },
"arch": [ {
"x64" "ext": "markdown",
] "name": "Markdown Document",
}, "description": "Markdown Document",
{ "mimeType": "text/markdown",
"target": "portable", "role": "Editor"
"arch": [ },
"x64" {
] "ext": "pdf",
}, "name": "PDF Document",
{ "description": "PDF Document",
"target": "zip", "mimeType": "application/pdf",
"arch": [ "role": "Editor"
"x64" }
] ],
} "mac": {
], "category": "public.app-category.productivity",
"artifactName": "${productName}-${version}-${arch}.${ext}", "identity": null
"requestedExecutionLevel": "asInvoker", },
"signAndEditExecutable": false "win": {
}, "target": [
"nsis": { {
"oneClick": false, "target": "nsis",
"perMachine": false, "arch": [
"allowToChangeInstallationDirectory": true, "x64"
"displayLanguageSelector": true, ]
"createDesktopShortcut": true, },
"createStartMenuShortcut": true, {
"shortcutName": "MarkdownConverter", "target": "portable",
"runAfterFinish": true, "arch": [
"menuCategory": "Productivity", "x64"
"license": "LICENSE", ]
"warningsAsErrors": false, },
"artifactName": "${productName}-Setup-${version}.${ext}", {
"deleteAppDataOnUninstall": false, "target": "zip",
"differentialPackage": true "arch": [
}, "x64"
"linux": { ]
"target": [ }
"deb", ],
"AppImage", "artifactName": "${productName}-${version}-${arch}.${ext}",
"snap" "requestedExecutionLevel": "asInvoker",
], "signAndEditExecutable": false
"category": "Utility", },
"maintainer": "ConcreteInfo <amit.wh@gmail.com>" "nsis": {
}, "oneClick": false,
"deb": { "perMachine": false,
"depends": [ "allowToChangeInstallationDirectory": true,
"pandoc", "displayLanguageSelector": true,
"ffmpeg", "createDesktopShortcut": true,
"imagemagick", "createStartMenuShortcut": true,
"libreoffice-common" "shortcutName": "MarkdownConverter",
], "runAfterFinish": true,
"description": "Professional Markdown editor and universal file converter", "menuCategory": "Productivity",
"maintainer": "ConcreteInfo <amit.wh@gmail.com>" "license": "LICENSE",
}, "warningsAsErrors": false,
"rpm": { "artifactName": "${productName}-Setup-${version}.${ext}",
"depends": [ "deleteAppDataOnUninstall": false,
"pandoc", "differentialPackage": true
"ffmpeg", },
"ImageMagick", "linux": {
"libreoffice-core" "target": [
] "deb",
} "AppImage",
} "snap",
} "rpm"
],
"category": "Utility",
"maintainer": "ConcreteInfo <amit.wh@gmail.com>"
},
"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"
]
}
}
}
+82 -82
View File
@@ -1,83 +1,83 @@
#!/bin/bash #!/bin/bash
echo "==========================================" echo "=========================================="
echo "Pan Converter - GitHub Push Helper" echo "Pan Converter - GitHub Push Helper"
echo "==========================================" echo "=========================================="
echo "" echo ""
echo "Before running this script, please ensure:" echo "Before running this script, please ensure:"
echo "1. You have created a repository named 'pan-converter' on GitHub" echo "1. You have created a repository named 'pan-converter' on GitHub"
echo "2. The repository is empty (no README, .gitignore, or license)" echo "2. The repository is empty (no README, .gitignore, or license)"
echo "3. You have set up authentication (SSH key or Personal Access Token)" echo "3. You have set up authentication (SSH key or Personal Access Token)"
echo "" echo ""
read -p "Have you completed the above steps? (y/n): " -n 1 -r read -p "Have you completed the above steps? (y/n): " -n 1 -r
echo "" echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Please complete the setup first:" echo "Please complete the setup first:"
echo "1. Go to https://github.com/new" echo "1. Go to https://github.com/new"
echo "2. Create a new repository named 'pan-converter'" echo "2. Create a new repository named 'pan-converter'"
echo "3. DO NOT initialize with README, .gitignore, or license" echo "3. DO NOT initialize with README, .gitignore, or license"
echo "4. Set up SSH key or Personal Access Token for authentication" echo "4. Set up SSH key or Personal Access Token for authentication"
exit 1 exit 1
fi fi
echo "" echo ""
echo "Choose authentication method:" echo "Choose authentication method:"
echo "1. SSH (Recommended if you have SSH keys set up)" echo "1. SSH (Recommended if you have SSH keys set up)"
echo "2. HTTPS (Requires Personal Access Token)" echo "2. HTTPS (Requires Personal Access Token)"
read -p "Enter your choice (1 or 2): " AUTH_CHOICE read -p "Enter your choice (1 or 2): " AUTH_CHOICE
if [ "$AUTH_CHOICE" = "1" ]; then if [ "$AUTH_CHOICE" = "1" ]; then
echo "Using SSH authentication..." echo "Using SSH authentication..."
git remote set-url origin git@github.com:amitwh/pan-converter.git git remote set-url origin git@github.com:amitwh/pan-converter.git
elif [ "$AUTH_CHOICE" = "2" ]; then elif [ "$AUTH_CHOICE" = "2" ]; then
echo "Using HTTPS authentication..." echo "Using HTTPS authentication..."
echo "You'll need to enter your GitHub username and Personal Access Token" echo "You'll need to enter your GitHub username and Personal Access Token"
git remote set-url origin https://github.com/amitwh/pan-converter.git git remote set-url origin https://github.com/amitwh/pan-converter.git
else else
echo "Invalid choice. Exiting." echo "Invalid choice. Exiting."
exit 1 exit 1
fi fi
echo "" echo ""
echo "Pushing branches to GitHub..." echo "Pushing branches to GitHub..."
echo "==============================" echo "=============================="
# Push master branch with upstream tracking # Push master branch with upstream tracking
echo "Pushing master branch..." echo "Pushing master branch..."
if git push -u origin master; then if git push -u origin master; then
echo "✓ Master branch pushed successfully" echo "✓ Master branch pushed successfully"
else else
echo "✗ Failed to push master branch" echo "✗ Failed to push master branch"
echo "Please check your authentication and try again" echo "Please check your authentication and try again"
exit 1 exit 1
fi fi
# Push other branches # Push other branches
echo "Pushing linux branch..." echo "Pushing linux branch..."
if git push origin linux; then if git push origin linux; then
echo "✓ Linux branch pushed successfully" echo "✓ Linux branch pushed successfully"
else else
echo "✗ Failed to push linux branch" echo "✗ Failed to push linux branch"
fi fi
echo "Pushing macos branch..." echo "Pushing macos branch..."
if git push origin macos; then if git push origin macos; then
echo "✓ macOS branch pushed successfully" echo "✓ macOS branch pushed successfully"
else else
echo "✗ Failed to push macos branch" echo "✗ Failed to push macos branch"
fi fi
echo "Pushing windows branch..." echo "Pushing windows branch..."
if git push origin windows; then if git push origin windows; then
echo "✓ Windows branch pushed successfully" echo "✓ Windows branch pushed successfully"
else else
echo "✗ Failed to push windows branch" echo "✗ Failed to push windows branch"
fi fi
echo "" echo ""
echo "==========================================" echo "=========================================="
echo "Push complete!" echo "Push complete!"
echo "Your repository is available at:" echo "Your repository is available at:"
echo "https://github.com/amitwh/pan-converter" echo "https://github.com/amitwh/pan-converter"
echo "==========================================" echo "=========================================="
+115 -115
View File
@@ -1,116 +1,116 @@
# PanConverter Windows Explorer Context Menu Integration # PanConverter Windows Explorer Context Menu Integration
This directory contains scripts to add PanConverter to the Windows Explorer context menu, allowing you to right-click on files and convert them directly without opening the full application. This directory contains scripts to add PanConverter to the Windows Explorer context menu, allowing you to right-click on files and convert them directly without opening the full application.
## Features ## Features
### Context Menu Options ### Context Menu Options
- **Convert with PanConverter**: Shows a format selection dialog for any supported file - **Convert with PanConverter**: Shows a format selection dialog for any supported file
- **PanConverter > Convert to...**: Direct conversion options (for Markdown files) - **PanConverter > Convert to...**: Direct conversion options (for Markdown files)
- PDF - PDF
- HTML - HTML
- DOCX - DOCX
- LaTeX - LaTeX
- PowerPoint - PowerPoint
### Supported File Types ### Supported File Types
- **Markdown**: `.md`, `.markdown` - **Markdown**: `.md`, `.markdown`
- **HTML**: `.html`, `.htm` - **HTML**: `.html`, `.htm`
- **Documents**: `.docx`, `.odt`, `.rtf` - **Documents**: `.docx`, `.odt`, `.rtf`
- **LaTeX**: `.tex` - **LaTeX**: `.tex`
- **PDF**: `.pdf` - **PDF**: `.pdf`
- **Presentations**: `.pptx`, `.ppt`, `.odp` - **Presentations**: `.pptx`, `.ppt`, `.odp`
## Installation Methods ## Installation Methods
### Method 1: Automatic (During PanConverter Installation) ### Method 1: Automatic (During PanConverter Installation)
When installing PanConverter using the Windows installer, you'll be prompted to install context menu integration automatically. When installing PanConverter using the Windows installer, you'll be prompted to install context menu integration automatically.
### Method 2: Manual Installation ### Method 2: Manual Installation
#### Using PowerShell (Recommended) #### Using PowerShell (Recommended)
1. Right-click on `install-context-menu.ps1` 1. Right-click on `install-context-menu.ps1`
2. Select "Run with PowerShell" 2. Select "Run with PowerShell"
3. Follow the prompts (will request administrator privileges) 3. Follow the prompts (will request administrator privileges)
#### Using Batch File #### Using Batch File
1. Right-click on `install-context-menu.bat` 1. Right-click on `install-context-menu.bat`
2. Select "Run as administrator" 2. Select "Run as administrator"
3. Follow the prompts 3. Follow the prompts
#### Using Registry File Directly #### Using Registry File Directly
1. Right-click on `install-context-menu.reg` 1. Right-click on `install-context-menu.reg`
2. Select "Merge" 2. Select "Merge"
3. Confirm the registry modification 3. Confirm the registry modification
## Uninstallation ## Uninstallation
### Using PowerShell ### Using PowerShell
```powershell ```powershell
.\install-context-menu.ps1 -Uninstall .\install-context-menu.ps1 -Uninstall
``` ```
### Using Batch File ### Using Batch File
Run `uninstall-context-menu.bat` as administrator Run `uninstall-context-menu.bat` as administrator
### Using Registry File ### Using Registry File
Run `uninstall-context-menu.reg` Run `uninstall-context-menu.reg`
## How It Works ## How It Works
### Command Line Interface ### Command Line Interface
The context menu integration works by passing command line arguments to PanConverter: The context menu integration works by passing command line arguments to PanConverter:
- `--convert <file>`: Shows conversion dialog for the specified file - `--convert <file>`: Shows conversion dialog for the specified file
- `--convert-to <format> <file>`: Directly converts to the specified format - `--convert-to <format> <file>`: Directly converts to the specified format
### Examples ### Examples
```batch ```batch
# Show conversion dialog # Show conversion dialog
PanConverter.exe --convert "document.md" PanConverter.exe --convert "document.md"
# Direct conversion to PDF # Direct conversion to PDF
PanConverter.exe --convert-to pdf "document.md" PanConverter.exe --convert-to pdf "document.md"
``` ```
### Conversion Process ### Conversion Process
1. PanConverter reads the input file 1. PanConverter reads the input file
2. Creates a temporary file if needed 2. Creates a temporary file if needed
3. Uses Pandoc to convert to the target format 3. Uses Pandoc to convert to the target format
4. Saves the output in the same directory as the input file 4. Saves the output in the same directory as the input file
5. Shows a Windows notification when complete 5. Shows a Windows notification when complete
## Requirements ## Requirements
- PanConverter must be installed in the default location: `%LOCALAPPDATA%\Programs\PanConverter\` - PanConverter must be installed in the default location: `%LOCALAPPDATA%\Programs\PanConverter\`
- Pandoc must be installed and accessible from the command line - Pandoc must be installed and accessible from the command line
- Administrator privileges required for registry modifications - Administrator privileges required for registry modifications
## Troubleshooting ## Troubleshooting
### Context Menu Not Appearing ### Context Menu Not Appearing
1. Ensure you ran the installation script as administrator 1. Ensure you ran the installation script as administrator
2. Try logging out and back in, or restart Windows Explorer 2. Try logging out and back in, or restart Windows Explorer
3. Check if PanConverter is installed in the expected location 3. Check if PanConverter is installed in the expected location
### Conversion Failures ### Conversion Failures
1. Verify Pandoc is installed: `pandoc --version` 1. Verify Pandoc is installed: `pandoc --version`
2. Check if the input file is not corrupted or locked 2. Check if the input file is not corrupted or locked
3. Ensure you have write permissions in the output directory 3. Ensure you have write permissions in the output directory
### Permission Errors ### Permission Errors
- The installation scripts require administrator privileges to modify the registry - The installation scripts require administrator privileges to modify the registry
- If you get permission errors, right-click and "Run as administrator" - If you get permission errors, right-click and "Run as administrator"
## File Descriptions ## File Descriptions
- `install-context-menu.reg`: Registry entries for context menu - `install-context-menu.reg`: Registry entries for context menu
- `uninstall-context-menu.reg`: Registry entries removal - `uninstall-context-menu.reg`: Registry entries removal
- `install-context-menu.ps1`: PowerShell installation script - `install-context-menu.ps1`: PowerShell installation script
- `install-context-menu.bat`: Batch installation script - `install-context-menu.bat`: Batch installation script
- `uninstall-context-menu.bat`: Batch uninstallation script - `uninstall-context-menu.bat`: Batch uninstallation script
- `nsis-installer.nsh`: NSIS installer integration script - `nsis-installer.nsh`: NSIS installer integration script
## Security Note ## Security Note
The scripts modify the Windows registry to add context menu entries. Only run these scripts if you trust the source and understand the changes being made to your system. The scripts modify the Windows registry to add context menu entries. Only run these scripts if you trust the source and understand the changes being made to your system.
+82 -82
View File
@@ -1,82 +1,82 @@
/** /**
* Icon Generator for MarkdownConverter * Icon Generator for MarkdownConverter
* Generates all required icon sizes from NewIcon.jpg * Generates all required icon sizes from NewIcon.jpg
*/ */
const sharp = require('sharp'); const sharp = require('sharp');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
// Source image // Source image
const sourceImage = path.join(__dirname, '..', 'assets', 'docico1.png'); const sourceImage = path.join(__dirname, '..', 'assets', 'docico1.png');
const assetsDir = path.join(__dirname, '..', 'assets'); const assetsDir = path.join(__dirname, '..', 'assets');
// Icon sizes needed for different platforms // Icon sizes needed for different platforms
const iconSizes = [16, 24, 32, 48, 64, 128, 256, 512, 1024]; const iconSizes = [16, 24, 32, 48, 64, 128, 256, 512, 1024];
async function generateIcons() { async function generateIcons() {
console.log('Generating icons from docico1.png...'); console.log('Generating icons from docico1.png...');
// Check if source exists // Check if source exists
if (!fs.existsSync(sourceImage)) { if (!fs.existsSync(sourceImage)) {
console.error('Source image not found:', sourceImage); console.error('Source image not found:', sourceImage);
process.exit(1); process.exit(1);
} }
try { try {
// Generate main icon.png (512x512) // Generate main icon.png (512x512)
await sharp(sourceImage) await sharp(sourceImage)
.resize(512, 512, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) .resize(512, 512, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } })
.png() .png()
.toFile(path.join(assetsDir, 'icon.png')); .toFile(path.join(assetsDir, 'icon.png'));
console.log('Generated icon.png (512x512)'); console.log('Generated icon.png (512x512)');
// Generate icon@2x.png (1024x1024) // Generate icon@2x.png (1024x1024)
await sharp(sourceImage) await sharp(sourceImage)
.resize(1024, 1024, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) .resize(1024, 1024, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } })
.png() .png()
.toFile(path.join(assetsDir, 'icon@2x.png')); .toFile(path.join(assetsDir, 'icon@2x.png'));
console.log('Generated icon@2x.png (1024x1024)'); console.log('Generated icon@2x.png (1024x1024)');
// Create icons directory for multi-size icons // Create icons directory for multi-size icons
const iconsDir = path.join(assetsDir, 'icons'); const iconsDir = path.join(assetsDir, 'icons');
if (!fs.existsSync(iconsDir)) { if (!fs.existsSync(iconsDir)) {
fs.mkdirSync(iconsDir, { recursive: true }); fs.mkdirSync(iconsDir, { recursive: true });
} }
// Generate all sizes // Generate all sizes
for (const size of iconSizes) { for (const size of iconSizes) {
await sharp(sourceImage) await sharp(sourceImage)
.resize(size, size, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) .resize(size, size, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } })
.png() .png()
.toFile(path.join(iconsDir, `${size}x${size}.png`)); .toFile(path.join(iconsDir, `${size}x${size}.png`));
console.log(`Generated icons/${size}x${size}.png`); console.log(`Generated icons/${size}x${size}.png`);
} }
// Generate favicon // Generate favicon
await sharp(sourceImage) await sharp(sourceImage)
.resize(32, 32, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) .resize(32, 32, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } })
.png() .png()
.toFile(path.join(assetsDir, 'favicon.png')); .toFile(path.join(assetsDir, 'favicon.png'));
console.log('Generated favicon.png (32x32)'); console.log('Generated favicon.png (32x32)');
// Generate tray icon (smaller, for system tray) // Generate tray icon (smaller, for system tray)
await sharp(sourceImage) await sharp(sourceImage)
.resize(24, 24, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) .resize(24, 24, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } })
.png() .png()
.toFile(path.join(assetsDir, 'tray-icon.png')); .toFile(path.join(assetsDir, 'tray-icon.png'));
console.log('Generated tray-icon.png (24x24)'); console.log('Generated tray-icon.png (24x24)');
console.log('\nIcon generation complete!'); console.log('\nIcon generation complete!');
console.log('\nFor Windows .ico file, use an online converter or:'); console.log('\nFor Windows .ico file, use an online converter or:');
console.log(' magick convert assets/icons/*.png assets/icon.ico'); console.log(' magick convert assets/icons/*.png assets/icon.ico');
console.log('\nFor macOS .icns file, use:'); console.log('\nFor macOS .icns file, use:');
console.log(' iconutil -c icns assets/icon.iconset -o assets/icon.icns'); console.log(' iconutil -c icns assets/icon.iconset -o assets/icon.icns');
} catch (error) { } catch (error) {
console.error('Error generating icons:', error); console.error('Error generating icons:', error);
process.exit(1); process.exit(1);
} }
} }
generateIcons(); generateIcons();
+47 -47
View File
@@ -1,48 +1,48 @@
@echo off @echo off
echo PanConverter Context Menu Installation echo PanConverter Context Menu Installation
echo ===================================== echo =====================================
echo. echo.
REM Check for administrator privileges REM Check for administrator privileges
net session >nul 2>&1 net session >nul 2>&1
if %errorLevel% == 0 ( if %errorLevel% == 0 (
echo Running with administrator privileges... echo Running with administrator privileges...
) else ( ) else (
echo This script requires administrator privileges. echo This script requires administrator privileges.
echo Please right-click and select "Run as administrator" echo Please right-click and select "Run as administrator"
echo. echo.
pause pause
exit /b 1 exit /b 1
) )
REM Check if PanConverter is installed REM Check if PanConverter is installed
if not exist "%LOCALAPPDATA%\Programs\PanConverter\PanConverter.exe" ( if not exist "%LOCALAPPDATA%\Programs\PanConverter\PanConverter.exe" (
echo Warning: PanConverter not found at the expected location. echo Warning: PanConverter not found at the expected location.
echo Please ensure PanConverter is installed before continuing. echo Please ensure PanConverter is installed before continuing.
echo Expected location: %LOCALAPPDATA%\Programs\PanConverter\PanConverter.exe echo Expected location: %LOCALAPPDATA%\Programs\PanConverter\PanConverter.exe
echo. echo.
set /p continue="Continue anyway? (y/N): " set /p continue="Continue anyway? (y/N): "
if /i not "%continue%"=="y" exit /b 1 if /i not "%continue%"=="y" exit /b 1
) )
echo Installing context menu entries... echo Installing context menu entries...
reg import "%~dp0install-context-menu.reg" reg import "%~dp0install-context-menu.reg"
if %errorLevel% == 0 ( if %errorLevel% == 0 (
echo. echo.
echo Context menu integration installed successfully! echo Context menu integration installed successfully!
echo. echo.
echo You can now right-click on supported files and select: echo You can now right-click on supported files and select:
echo"Convert with PanConverter" - Shows conversion dialog echo"Convert with PanConverter" - Shows conversion dialog
echo"PanConverter > Convert to..." - Direct conversion ^(for Markdown^) echo"PanConverter > Convert to..." - Direct conversion ^(for Markdown^)
echo. echo.
echo Supported file types: echo Supported file types:
echo .md .markdown .html .htm .docx .odt .rtf .tex .pdf .pptx .ppt .odp echo .md .markdown .html .htm .docx .odt .rtf .tex .pdf .pptx .ppt .odp
) else ( ) else (
echo. echo.
echo Failed to install context menu entries. echo Failed to install context menu entries.
echo Please check that the registry file exists and try again. echo Please check that the registry file exists and try again.
) )
echo. echo.
pause pause
+66 -66
View File
@@ -1,67 +1,67 @@
# PanConverter Context Menu Installation Script # PanConverter Context Menu Installation Script
# This script installs PanConverter context menu integration for Windows Explorer # This script installs PanConverter context menu integration for Windows Explorer
param( param(
[switch]$Uninstall = $false [switch]$Uninstall = $false
) )
# Check if running as administrator # Check if running as administrator
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "This script requires Administrator privileges. Restarting with elevated permissions..." -ForegroundColor Yellow Write-Host "This script requires Administrator privileges. Restarting with elevated permissions..." -ForegroundColor Yellow
Start-Process PowerShell -Verb RunAs "-File `"$PSCommandPath`" $(if ($Uninstall) { '-Uninstall' })" Start-Process PowerShell -Verb RunAs "-File `"$PSCommandPath`" $(if ($Uninstall) { '-Uninstall' })"
exit exit
} }
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$appPath = "${env:LOCALAPPDATA}\Programs\PanConverter\PanConverter.exe" $appPath = "${env:LOCALAPPDATA}\Programs\PanConverter\PanConverter.exe"
if ($Uninstall) { if ($Uninstall) {
Write-Host "Uninstalling PanConverter context menu integration..." -ForegroundColor Yellow Write-Host "Uninstalling PanConverter context menu integration..." -ForegroundColor Yellow
$regFile = Join-Path $scriptDir "uninstall-context-menu.reg" $regFile = Join-Path $scriptDir "uninstall-context-menu.reg"
if (Test-Path $regFile) { if (Test-Path $regFile) {
reg import $regFile reg import $regFile
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) {
Write-Host "PanConverter context menu has been successfully removed!" -ForegroundColor Green Write-Host "PanConverter context menu has been successfully removed!" -ForegroundColor Green
} else { } else {
Write-Host "Failed to remove context menu entries." -ForegroundColor Red Write-Host "Failed to remove context menu entries." -ForegroundColor Red
} }
} else { } else {
Write-Host "Uninstall registry file not found: $regFile" -ForegroundColor Red Write-Host "Uninstall registry file not found: $regFile" -ForegroundColor Red
} }
} else { } else {
Write-Host "Installing PanConverter context menu integration..." -ForegroundColor Yellow Write-Host "Installing PanConverter context menu integration..." -ForegroundColor Yellow
# Check if PanConverter is installed # Check if PanConverter is installed
if (-not (Test-Path $appPath)) { if (-not (Test-Path $appPath)) {
Write-Host "Warning: PanConverter executable not found at: $appPath" -ForegroundColor Yellow Write-Host "Warning: PanConverter executable not found at: $appPath" -ForegroundColor Yellow
Write-Host "Please make sure PanConverter is installed before running this script." -ForegroundColor Yellow Write-Host "Please make sure PanConverter is installed before running this script." -ForegroundColor Yellow
$continue = Read-Host "Continue anyway? (y/N)" $continue = Read-Host "Continue anyway? (y/N)"
if ($continue -ne 'y' -and $continue -ne 'Y') { if ($continue -ne 'y' -and $continue -ne 'Y') {
exit exit
} }
} }
$regFile = Join-Path $scriptDir "install-context-menu.reg" $regFile = Join-Path $scriptDir "install-context-menu.reg"
if (Test-Path $regFile) { if (Test-Path $regFile) {
reg import $regFile reg import $regFile
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) {
Write-Host "PanConverter context menu has been successfully installed!" -ForegroundColor Green Write-Host "PanConverter context menu has been successfully installed!" -ForegroundColor Green
Write-Host "" Write-Host ""
Write-Host "You can now right-click on supported files (MD, HTML, DOCX, PDF, etc.) and select:" -ForegroundColor Cyan Write-Host "You can now right-click on supported files (MD, HTML, DOCX, PDF, etc.) and select:" -ForegroundColor Cyan
Write-Host "• 'Convert with PanConverter' - Shows conversion dialog" -ForegroundColor Cyan Write-Host "• 'Convert with PanConverter' - Shows conversion dialog" -ForegroundColor Cyan
Write-Host "• 'PanConverter > Convert to...' - Direct conversion options (for Markdown files)" -ForegroundColor Cyan Write-Host "• 'PanConverter > Convert to...' - Direct conversion options (for Markdown files)" -ForegroundColor Cyan
Write-Host "" Write-Host ""
Write-Host "Supported file types: .md, .markdown, .html, .htm, .docx, .odt, .rtf, .tex, .pdf, .pptx, .ppt, .odp" -ForegroundColor Gray Write-Host "Supported file types: .md, .markdown, .html, .htm, .docx, .odt, .rtf, .tex, .pdf, .pptx, .ppt, .odp" -ForegroundColor Gray
} else { } else {
Write-Host "Failed to install context menu entries." -ForegroundColor Red Write-Host "Failed to install context menu entries." -ForegroundColor Red
} }
} else { } else {
Write-Host "Install registry file not found: $regFile" -ForegroundColor Red Write-Host "Install registry file not found: $regFile" -ForegroundColor Red
} }
} }
Write-Host "" Write-Host ""
Write-Host "Press any key to exit..." Write-Host "Press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
+133 -133
View File
@@ -1,134 +1,134 @@
Windows Registry Editor Version 5.00 Windows Registry Editor Version 5.00
; PanConverter Context Menu Integration ; PanConverter Context Menu Integration
; This registry file adds context menu options for converting files using PanConverter ; This registry file adds context menu options for converting files using PanConverter
; Add context menu for Markdown files (.md, .markdown) ; Add context menu for Markdown files (.md, .markdown)
[HKEY_CLASSES_ROOT\.md\shell\PanConverter] [HKEY_CLASSES_ROOT\.md\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.md\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
[HKEY_CLASSES_ROOT\.markdown\shell\PanConverter] [HKEY_CLASSES_ROOT\.markdown\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.markdown\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.markdown\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for HTML files ; Add context menu for HTML files
[HKEY_CLASSES_ROOT\.html\shell\PanConverter] [HKEY_CLASSES_ROOT\.html\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.html\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.html\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
[HKEY_CLASSES_ROOT\.htm\shell\PanConverter] [HKEY_CLASSES_ROOT\.htm\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.htm\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.htm\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for DOCX files ; Add context menu for DOCX files
[HKEY_CLASSES_ROOT\.docx\shell\PanConverter] [HKEY_CLASSES_ROOT\.docx\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.docx\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.docx\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for ODT files ; Add context menu for ODT files
[HKEY_CLASSES_ROOT\.odt\shell\PanConverter] [HKEY_CLASSES_ROOT\.odt\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.odt\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.odt\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for RTF files ; Add context menu for RTF files
[HKEY_CLASSES_ROOT\.rtf\shell\PanConverter] [HKEY_CLASSES_ROOT\.rtf\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.rtf\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.rtf\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for LaTeX files ; Add context menu for LaTeX files
[HKEY_CLASSES_ROOT\.tex\shell\PanConverter] [HKEY_CLASSES_ROOT\.tex\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.tex\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.tex\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for PDF files ; Add context menu for PDF files
[HKEY_CLASSES_ROOT\.pdf\shell\PanConverter] [HKEY_CLASSES_ROOT\.pdf\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.pdf\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.pdf\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for PowerPoint files ; Add context menu for PowerPoint files
[HKEY_CLASSES_ROOT\.pptx\shell\PanConverter] [HKEY_CLASSES_ROOT\.pptx\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.pptx\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.pptx\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
[HKEY_CLASSES_ROOT\.ppt\shell\PanConverter] [HKEY_CLASSES_ROOT\.ppt\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.ppt\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.ppt\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add context menu for OpenDocument Presentation files ; Add context menu for OpenDocument Presentation files
[HKEY_CLASSES_ROOT\.odp\shell\PanConverter] [HKEY_CLASSES_ROOT\.odp\shell\PanConverter]
@="Convert with PanConverter" @="Convert with PanConverter"
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
[HKEY_CLASSES_ROOT\.odp\shell\PanConverter\command] [HKEY_CLASSES_ROOT\.odp\shell\PanConverter\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert \"%1\""
; Add submenu with specific conversion options for Markdown files ; Add submenu with specific conversion options for Markdown files
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu]
@="PanConverter" @="PanConverter"
"MUIVerb"="Convert to..." "MUIVerb"="Convert to..."
"Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\"" "Icon"="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\""
"SubCommands"="" "SubCommands"=""
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PDF] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PDF]
@="PDF" @="PDF"
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PDF\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PDF\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to pdf \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to pdf \"%1\""
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\HTML] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\HTML]
@="HTML" @="HTML"
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\HTML\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\HTML\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to html \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to html \"%1\""
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\DOCX] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\DOCX]
@="DOCX" @="DOCX"
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\DOCX\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\DOCX\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to docx \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to docx \"%1\""
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\LaTeX] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\LaTeX]
@="LaTeX" @="LaTeX"
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\LaTeX\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\LaTeX\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to latex \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to latex \"%1\""
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PPTX] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PPTX]
@="PowerPoint" @="PowerPoint"
[HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PPTX\command] [HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu\shell\PPTX\command]
@="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to pptx \"%1\"" @="\"%LOCALAPPDATA%\\Programs\\PanConverter\\PanConverter.exe\" --convert-to pptx \"%1\""
+144 -144
View File
@@ -1,145 +1,145 @@
; PanConverter NSIS Installer Include File ; PanConverter NSIS Installer Include File
; Handles context menu installation and uninstallation ; Handles context menu installation and uninstallation
!include "LogicLib.nsh" !include "LogicLib.nsh"
!include "MUI2.nsh" !include "MUI2.nsh"
; Custom installation page for context menu option ; Custom installation page for context menu option
Var ContextMenuCheckbox Var ContextMenuCheckbox
Var ContextMenuState Var ContextMenuState
Function ContextMenuPage Function ContextMenuPage
!insertmacro MUI_HEADER_TEXT "Additional Options" "Choose additional installation options" !insertmacro MUI_HEADER_TEXT "Additional Options" "Choose additional installation options"
nsDialogs::Create 1018 nsDialogs::Create 1018
Pop $0 Pop $0
${If} $0 == error ${If} $0 == error
Abort Abort
${EndIf} ${EndIf}
${NSD_CreateLabel} 0 0 100% 20u "Select additional features to install:" ${NSD_CreateLabel} 0 0 100% 20u "Select additional features to install:"
Pop $0 Pop $0
${NSD_CreateCheckbox} 20u 30u 280u 15u "Add PanConverter to Windows Explorer context menu" ${NSD_CreateCheckbox} 20u 30u 280u 15u "Add PanConverter to Windows Explorer context menu"
Pop $ContextMenuCheckbox Pop $ContextMenuCheckbox
${NSD_SetState} $ContextMenuCheckbox ${BST_CHECKED} ${NSD_SetState} $ContextMenuCheckbox ${BST_CHECKED}
${NSD_CreateLabel} 20u 50u 280u 30u "This will allow you to right-click on supported files and convert them directly using PanConverter." ${NSD_CreateLabel} 20u 50u 280u 30u "This will allow you to right-click on supported files and convert them directly using PanConverter."
Pop $0 Pop $0
nsDialogs::Show nsDialogs::Show
FunctionEnd FunctionEnd
Function ContextMenuPageLeave Function ContextMenuPageLeave
${NSD_GetState} $ContextMenuCheckbox $ContextMenuState ${NSD_GetState} $ContextMenuCheckbox $ContextMenuState
FunctionEnd FunctionEnd
; Install context menu entries ; Install context menu entries
Function InstallContextMenu Function InstallContextMenu
${If} $ContextMenuState == ${BST_CHECKED} ${If} $ContextMenuState == ${BST_CHECKED}
DetailPrint "Installing context menu integration..." DetailPrint "Installing context menu integration..."
; Create registry entries for context menu ; Create registry entries for context menu
WriteRegStr HKCR ".md\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".md\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".md\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".md\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".md\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".md\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
WriteRegStr HKCR ".markdown\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".markdown\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".markdown\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".markdown\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".markdown\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".markdown\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for HTML files ; Context menu for HTML files
WriteRegStr HKCR ".html\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".html\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".html\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".html\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".html\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".html\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
WriteRegStr HKCR ".htm\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".htm\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".htm\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".htm\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".htm\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".htm\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for DOCX files ; Context menu for DOCX files
WriteRegStr HKCR ".docx\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".docx\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".docx\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".docx\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".docx\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".docx\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for ODT files ; Context menu for ODT files
WriteRegStr HKCR ".odt\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".odt\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".odt\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".odt\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".odt\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".odt\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for RTF files ; Context menu for RTF files
WriteRegStr HKCR ".rtf\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".rtf\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".rtf\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".rtf\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".rtf\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".rtf\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for LaTeX files ; Context menu for LaTeX files
WriteRegStr HKCR ".tex\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".tex\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".tex\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".tex\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".tex\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".tex\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for PDF files ; Context menu for PDF files
WriteRegStr HKCR ".pdf\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".pdf\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".pdf\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".pdf\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".pdf\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".pdf\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for PowerPoint files ; Context menu for PowerPoint files
WriteRegStr HKCR ".pptx\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".pptx\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".pptx\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".pptx\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".pptx\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".pptx\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
WriteRegStr HKCR ".ppt\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".ppt\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".ppt\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".ppt\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".ppt\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".ppt\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Context menu for ODP files ; Context menu for ODP files
WriteRegStr HKCR ".odp\shell\PanConverter" "" "Convert with PanConverter" WriteRegStr HKCR ".odp\shell\PanConverter" "" "Convert with PanConverter"
WriteRegStr HKCR ".odp\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".odp\shell\PanConverter" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".odp\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"' WriteRegStr HKCR ".odp\shell\PanConverter\command" "" '"$INSTDIR\PanConverter.exe" --convert "%1"'
; Submenu for Markdown files with direct conversion options ; Submenu for Markdown files with direct conversion options
WriteRegStr HKCR ".md\shell\PanConverterMenu" "" "PanConverter" WriteRegStr HKCR ".md\shell\PanConverterMenu" "" "PanConverter"
WriteRegStr HKCR ".md\shell\PanConverterMenu" "MUIVerb" "Convert to..." WriteRegStr HKCR ".md\shell\PanConverterMenu" "MUIVerb" "Convert to..."
WriteRegStr HKCR ".md\shell\PanConverterMenu" "Icon" "$INSTDIR\PanConverter.exe" WriteRegStr HKCR ".md\shell\PanConverterMenu" "Icon" "$INSTDIR\PanConverter.exe"
WriteRegStr HKCR ".md\shell\PanConverterMenu" "SubCommands" "" WriteRegStr HKCR ".md\shell\PanConverterMenu" "SubCommands" ""
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PDF" "" "PDF" WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PDF" "" "PDF"
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PDF\command" "" '"$INSTDIR\PanConverter.exe" --convert-to pdf "%1"' WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PDF\command" "" '"$INSTDIR\PanConverter.exe" --convert-to pdf "%1"'
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\HTML" "" "HTML" WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\HTML" "" "HTML"
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\HTML\command" "" '"$INSTDIR\PanConverter.exe" --convert-to html "%1"' WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\HTML\command" "" '"$INSTDIR\PanConverter.exe" --convert-to html "%1"'
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\DOCX" "" "DOCX" WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\DOCX" "" "DOCX"
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\DOCX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to docx "%1"' WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\DOCX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to docx "%1"'
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\LaTeX" "" "LaTeX" WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\LaTeX" "" "LaTeX"
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\LaTeX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to latex "%1"' WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\LaTeX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to latex "%1"'
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PPTX" "" "PowerPoint" WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PPTX" "" "PowerPoint"
WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PPTX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to pptx "%1"' WriteRegStr HKCR ".md\shell\PanConverterMenu\shell\PPTX\command" "" '"$INSTDIR\PanConverter.exe" --convert-to pptx "%1"'
DetailPrint "Context menu integration installed successfully!" DetailPrint "Context menu integration installed successfully!"
${EndIf} ${EndIf}
FunctionEnd FunctionEnd
; Uninstall context menu entries ; Uninstall context menu entries
Function un.RemoveContextMenu Function un.RemoveContextMenu
DetailPrint "Removing context menu integration..." DetailPrint "Removing context menu integration..."
; Remove context menu entries for all file types ; Remove context menu entries for all file types
DeleteRegKey HKCR ".md\shell\PanConverter" DeleteRegKey HKCR ".md\shell\PanConverter"
DeleteRegKey HKCR ".md\shell\PanConverterMenu" DeleteRegKey HKCR ".md\shell\PanConverterMenu"
DeleteRegKey HKCR ".markdown\shell\PanConverter" DeleteRegKey HKCR ".markdown\shell\PanConverter"
DeleteRegKey HKCR ".html\shell\PanConverter" DeleteRegKey HKCR ".html\shell\PanConverter"
DeleteRegKey HKCR ".htm\shell\PanConverter" DeleteRegKey HKCR ".htm\shell\PanConverter"
DeleteRegKey HKCR ".docx\shell\PanConverter" DeleteRegKey HKCR ".docx\shell\PanConverter"
DeleteRegKey HKCR ".odt\shell\PanConverter" DeleteRegKey HKCR ".odt\shell\PanConverter"
DeleteRegKey HKCR ".rtf\shell\PanConverter" DeleteRegKey HKCR ".rtf\shell\PanConverter"
DeleteRegKey HKCR ".tex\shell\PanConverter" DeleteRegKey HKCR ".tex\shell\PanConverter"
DeleteRegKey HKCR ".pdf\shell\PanConverter" DeleteRegKey HKCR ".pdf\shell\PanConverter"
DeleteRegKey HKCR ".pptx\shell\PanConverter" DeleteRegKey HKCR ".pptx\shell\PanConverter"
DeleteRegKey HKCR ".ppt\shell\PanConverter" DeleteRegKey HKCR ".ppt\shell\PanConverter"
DeleteRegKey HKCR ".odp\shell\PanConverter" DeleteRegKey HKCR ".odp\shell\PanConverter"
DetailPrint "Context menu integration removed successfully!" DetailPrint "Context menu integration removed successfully!"
FunctionEnd FunctionEnd
+31 -31
View File
@@ -1,32 +1,32 @@
@echo off @echo off
echo PanConverter Context Menu Uninstallation echo PanConverter Context Menu Uninstallation
echo ======================================== echo ========================================
echo. echo.
REM Check for administrator privileges REM Check for administrator privileges
net session >nul 2>&1 net session >nul 2>&1
if %errorLevel% == 0 ( if %errorLevel% == 0 (
echo Running with administrator privileges... echo Running with administrator privileges...
) else ( ) else (
echo This script requires administrator privileges. echo This script requires administrator privileges.
echo Please right-click and select "Run as administrator" echo Please right-click and select "Run as administrator"
echo. echo.
pause pause
exit /b 1 exit /b 1
) )
echo Removing context menu entries... echo Removing context menu entries...
reg import "%~dp0uninstall-context-menu.reg" reg import "%~dp0uninstall-context-menu.reg"
if %errorLevel% == 0 ( if %errorLevel% == 0 (
echo. echo.
echo Context menu integration removed successfully! echo Context menu integration removed successfully!
echo PanConverter entries have been removed from the Windows Explorer context menu. echo PanConverter entries have been removed from the Windows Explorer context menu.
) else ( ) else (
echo. echo.
echo Failed to remove context menu entries. echo Failed to remove context menu entries.
echo Please check that the registry file exists and try again. echo Please check that the registry file exists and try again.
) )
echo. echo.
pause pause
+35 -35
View File
@@ -1,36 +1,36 @@
Windows Registry Editor Version 5.00 Windows Registry Editor Version 5.00
; PanConverter Context Menu Uninstall Script ; PanConverter Context Menu Uninstall Script
; This registry file removes PanConverter context menu entries ; This registry file removes PanConverter context menu entries
; Remove context menu for Markdown files (.md, .markdown) ; Remove context menu for Markdown files (.md, .markdown)
[-HKEY_CLASSES_ROOT\.md\shell\PanConverter] [-HKEY_CLASSES_ROOT\.md\shell\PanConverter]
[-HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu] [-HKEY_CLASSES_ROOT\.md\shell\PanConverterMenu]
[-HKEY_CLASSES_ROOT\.markdown\shell\PanConverter] [-HKEY_CLASSES_ROOT\.markdown\shell\PanConverter]
; Remove context menu for HTML files ; Remove context menu for HTML files
[-HKEY_CLASSES_ROOT\.html\shell\PanConverter] [-HKEY_CLASSES_ROOT\.html\shell\PanConverter]
[-HKEY_CLASSES_ROOT\.htm\shell\PanConverter] [-HKEY_CLASSES_ROOT\.htm\shell\PanConverter]
; Remove context menu for DOCX files ; Remove context menu for DOCX files
[-HKEY_CLASSES_ROOT\.docx\shell\PanConverter] [-HKEY_CLASSES_ROOT\.docx\shell\PanConverter]
; Remove context menu for ODT files ; Remove context menu for ODT files
[-HKEY_CLASSES_ROOT\.odt\shell\PanConverter] [-HKEY_CLASSES_ROOT\.odt\shell\PanConverter]
; Remove context menu for RTF files ; Remove context menu for RTF files
[-HKEY_CLASSES_ROOT\.rtf\shell\PanConverter] [-HKEY_CLASSES_ROOT\.rtf\shell\PanConverter]
; Remove context menu for LaTeX files ; Remove context menu for LaTeX files
[-HKEY_CLASSES_ROOT\.tex\shell\PanConverter] [-HKEY_CLASSES_ROOT\.tex\shell\PanConverter]
; Remove context menu for PDF files ; Remove context menu for PDF files
[-HKEY_CLASSES_ROOT\.pdf\shell\PanConverter] [-HKEY_CLASSES_ROOT\.pdf\shell\PanConverter]
; Remove context menu for PowerPoint files ; Remove context menu for PowerPoint files
[-HKEY_CLASSES_ROOT\.pptx\shell\PanConverter] [-HKEY_CLASSES_ROOT\.pptx\shell\PanConverter]
[-HKEY_CLASSES_ROOT\.ppt\shell\PanConverter] [-HKEY_CLASSES_ROOT\.ppt\shell\PanConverter]
; Remove context menu for OpenDocument Presentation files ; Remove context menu for OpenDocument Presentation files
[-HKEY_CLASSES_ROOT\.odp\shell\PanConverter] [-HKEY_CLASSES_ROOT\.odp\shell\PanConverter]
+37 -37
View File
@@ -1,37 +1,37 @@
#!/bin/bash #!/bin/bash
# Pan Converter - Git Remote Setup Script # Pan Converter - Git Remote Setup Script
# #
# Instructions: # Instructions:
# 1. Create a new repository on GitHub named "pan-converter" # 1. Create a new repository on GitHub named "pan-converter"
# 2. Replace YOUR_GITHUB_USERNAME with your actual GitHub username # 2. Replace YOUR_GITHUB_USERNAME with your actual GitHub username
# 3. Run this script: bash setup-upstream.sh # 3. Run this script: bash setup-upstream.sh
GITHUB_USERNAME="amitwh" GITHUB_USERNAME="amitwh"
REPO_NAME="pan-converter" REPO_NAME="pan-converter"
echo "Setting up remote repository..." echo "Setting up remote repository..."
# Add remote origin # Add remote origin
git remote add origin "https://github.com/$GITHUB_USERNAME/$REPO_NAME.git" git remote add origin "https://github.com/$GITHUB_USERNAME/$REPO_NAME.git"
echo "Pushing all branches to remote..." echo "Pushing all branches to remote..."
# Push master branch # Push master branch
git push -u origin master git push -u origin master
# Push platform-specific branches # Push platform-specific branches
git push origin linux git push origin linux
git push origin macos git push origin macos
git push origin windows git push origin windows
echo "Repository setup complete!" echo "Repository setup complete!"
echo "" echo ""
echo "Your repository is now available at:" echo "Your repository is now available at:"
echo "https://github.com/$GITHUB_USERNAME/$REPO_NAME" echo "https://github.com/$GITHUB_USERNAME/$REPO_NAME"
echo "" echo ""
echo "Branch structure:" echo "Branch structure:"
echo " - master (main development)" echo " - master (main development)"
echo " - linux (Linux-specific)" echo " - linux (Linux-specific)"
echo " - macos (macOS-specific)" echo " - macos (macOS-specific)"
echo " - windows (Windows-specific)" echo " - windows (Windows-specific)"
+107
View File
@@ -0,0 +1,107 @@
/**
* Electron File System Adapter
*
* Implements file system operations for Electron using IPC.
* This abstracts file operations to enable easier testing and migration.
*
* @version 4.1.0
*/
/**
* 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.readFile(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.writeFile(path, content);
},
/**
* Delete file
* @param {string} path - File path
* @returns {Promise<void>}
*/
async deleteFile(path) {
// TODO: Add IPC channel for delete
throw new Error('deleteFile not implemented');
},
/**
* Ensure directory exists
* @param {string} path - Directory path
* @returns {Promise<void>}
*/
async ensureDir(path) {
// TODO: Add IPC channel for ensureDir
throw new Error('ensureDir not implemented');
},
/**
* List directory contents
* @param {string} path - Directory path
* @returns {Promise<Array<import('../types').FileInfo>>}
*/
async listDirectory(path) {
// TODO: Add IPC channel for listDirectory
throw new Error('listDirectory not implemented');
},
/**
* Check if path exists
* @param {string} path - Path to check
* @returns {Promise<boolean>}
*/
async exists(path) {
// TODO: Add IPC channel for exists
throw new Error('exists not implemented');
},
/**
* Check if path is a directory
* @param {string} path - Path to check
* @returns {Promise<boolean>}
*/
async isDirectory(path) {
// TODO: Add IPC channel for isDirectory
throw new Error('isDirectory not implemented');
},
/**
* Copy file or directory
* @param {string} source - Source path
* @param {string} dest - Destination path
* @returns {Promise<void>}
*/
async copy(source, dest) {
// TODO: Add IPC channel for copy
throw new Error('copy not implemented');
},
/**
* Move file or directory
* @param {string} source - Source path
* @param {string} dest - Destination path
* @returns {Promise<void>}
*/
async move(source, dest) {
// TODO: Add IPC channel for move
throw new Error('move not implemented');
}
};
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.1.0
*/
/**
* @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
};
+601 -601
View File
File diff suppressed because it is too large Load Diff
+109
View File
@@ -0,0 +1,109 @@
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 };
+137
View File
@@ -0,0 +1,137 @@
// 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 = {}) {
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 };
+75 -75
View File
@@ -1,75 +1,75 @@
/* Local Font Definitions for MarkdownConverter */ /* Local Font Definitions for MarkdownConverter */
/* Inter Font Family */ /* Inter Font Family */
@font-face { @font-face {
font-family: 'Inter'; font-family: 'Inter';
font-style: normal; font-style: normal;
font-weight: 300; font-weight: 300;
font-display: swap; font-display: swap;
src: url('../assets/fonts/Inter-Light.woff2') format('woff2'); src: url('../assets/fonts/Inter-Light.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'Inter'; font-family: 'Inter';
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
font-display: swap; font-display: swap;
src: url('../assets/fonts/Inter-Regular.woff2') format('woff2'); src: url('../assets/fonts/Inter-Regular.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'Inter'; font-family: 'Inter';
font-style: normal; font-style: normal;
font-weight: 500; font-weight: 500;
font-display: swap; font-display: swap;
src: url('../assets/fonts/Inter-Medium.woff2') format('woff2'); src: url('../assets/fonts/Inter-Medium.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'Inter'; font-family: 'Inter';
font-style: normal; font-style: normal;
font-weight: 600; font-weight: 600;
font-display: swap; font-display: swap;
src: url('../assets/fonts/Inter-SemiBold.woff2') format('woff2'); src: url('../assets/fonts/Inter-SemiBold.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'Inter'; font-family: 'Inter';
font-style: normal; font-style: normal;
font-weight: 700; font-weight: 700;
font-display: swap; font-display: swap;
src: url('../assets/fonts/Inter-Bold.woff2') format('woff2'); src: url('../assets/fonts/Inter-Bold.woff2') format('woff2');
} }
/* JetBrains Mono Font Family - For code, markdown editor, and ASCII art */ /* JetBrains Mono Font Family - For code, markdown editor, and ASCII art */
@font-face { @font-face {
font-family: 'JetBrains Mono'; font-family: 'JetBrains Mono';
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
font-display: swap; font-display: swap;
src: url('../assets/fonts/JetBrainsMono-Regular.woff2') format('woff2'); src: url('../assets/fonts/JetBrainsMono-Regular.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'JetBrains Mono'; font-family: 'JetBrains Mono';
font-style: normal; font-style: normal;
font-weight: 500; font-weight: 500;
font-display: swap; font-display: swap;
src: url('../assets/fonts/JetBrainsMono-Medium.woff2') format('woff2'); src: url('../assets/fonts/JetBrainsMono-Medium.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'JetBrains Mono'; font-family: 'JetBrains Mono';
font-style: normal; font-style: normal;
font-weight: 600; font-weight: 600;
font-display: swap; font-display: swap;
src: url('../assets/fonts/JetBrainsMono-SemiBold.woff2') format('woff2'); src: url('../assets/fonts/JetBrainsMono-SemiBold.woff2') format('woff2');
} }
@font-face { @font-face {
font-family: 'JetBrains Mono'; font-family: 'JetBrains Mono';
font-style: normal; font-style: normal;
font-weight: 700; font-weight: 700;
font-display: swap; font-display: swap;
src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2'); src: url('../assets/fonts/JetBrainsMono-Bold.woff2') format('woff2');
} }
+1595 -1413
View File
File diff suppressed because it is too large Load Diff
+4492 -3794
View File
File diff suppressed because it is too large Load Diff
+422 -376
View File
@@ -1,376 +1,422 @@
/** /**
* Preload Script for PanConverter * Preload Script for PanConverter
* *
* This script creates a secure bridge between the main process and renderer process. * This script creates a secure bridge between the main process and renderer process.
* It exposes only specific IPC channels, preventing direct Node.js access in the renderer. * It exposes only specific IPC channels, preventing direct Node.js access in the renderer.
* *
* Security Benefits: * Security Benefits:
* - No direct access to Node.js APIs (fs, path, child_process, etc.) * - No direct access to Node.js APIs (fs, path, child_process, etc.)
* - All IPC channels are explicitly whitelisted * - All IPC channels are explicitly whitelisted
* - Prevents XSS from escalating to full system access * - Prevents XSS from escalating to full system access
* *
* @version 2.2.0 * @version 4.0.0
*/ */
const { contextBridge, ipcRenderer } = require('electron'); const { contextBridge, ipcRenderer } = require('electron');
// Define allowed IPC channels for security // Define allowed IPC channels for security
const ALLOWED_SEND_CHANNELS = [ const ALLOWED_SEND_CHANNELS = [
// File operations // File operations
'save-file', 'save-file',
'save-current-file', 'save-current-file',
'set-current-file', 'set-current-file',
'save-recent-files', 'save-recent-files',
'clear-recent-files', 'clear-recent-files',
'renderer-ready', 'renderer-ready',
// Theme // Theme
'get-theme', 'get-theme',
// Print // Print
'do-print', 'do-print',
'do-print-with-options',
// Export
'export-with-options', // Export
'export-spreadsheet', 'export-with-options',
'export-spreadsheet',
// Batch conversion
'batch-convert', // Batch conversion
'select-folder', 'batch-convert',
'select-folder',
// Universal converter
'universal-convert', // Universal converter
'universal-convert-batch', 'universal-convert',
'universal-convert-batch',
// Image converter
'image-convert', // Image converter
'image-batch-convert', 'image-convert',
'image-resize', 'image-batch-convert',
'image-compress', 'image-resize',
'image-rotate', 'image-compress',
'image-rotate',
// Audio converter
'audio-convert', // Audio converter
'audio-batch-convert', 'audio-convert',
'audio-extract', 'audio-batch-convert',
'audio-trim', 'audio-extract',
'audio-merge', 'audio-trim',
'audio-merge',
// Video converter
'video-convert', // Video converter
'video-batch-convert', 'video-convert',
'video-compress', 'video-batch-convert',
'video-trim', 'video-compress',
'video-frames', 'video-trim',
'video-gif', 'video-frames',
'video-gif',
// Header/Footer
'get-header-footer-settings', // Header/Footer
'save-header-footer-settings', 'get-header-footer-settings',
'browse-header-footer-logo', 'save-header-footer-settings',
'save-header-footer-logo', 'browse-header-footer-logo',
'clear-header-footer-logo', 'save-header-footer-logo',
'clear-header-footer-logo',
// Page settings
'get-page-settings', // Page settings
'update-page-settings', 'get-page-settings',
'update-page-settings',
// Template settings
'set-custom-start-page', // Template settings
'set-custom-start-page',
// PDF operations
'process-pdf-operation', // PDF operations
'get-pdf-page-count', 'process-pdf-operation',
'select-pdf-folder', 'get-pdf-page-count',
'select-pdf-folder',
// ASCII generator (separate window)
'open-ascii-generator', // ASCII generator (separate window)
'open-ascii-generator',
// Table generator (separate window)
'open-table-generator', // Table generator (separate window)
'open-table-generator',
// Insert generated content
'insert-generated-content' // Insert generated content
]; 'insert-generated-content',
const ALLOWED_RECEIVE_CHANNELS = [ // Image paste/drop
// File operations 'save-pasted-image',
'file-new',
'file-opened', // Templates
'file-save', 'load-template',
'get-content-for-save',
'get-content-for-spreadsheet', // File Explorer
'recent-files-cleared', 'list-directory',
// UI toggles // Git
'toggle-preview', 'git-status',
'toggle-find', 'git-stage',
'git-commit',
// Theme 'git-log',
'theme-changed',
'theme-data', // Snippets
'get-snippets',
// Edit operations 'save-snippet',
'undo', 'delete-snippet',
'redo',
// Code execution (REPL)
// Font 'execute-code',
'adjust-font-size',
// File open by path
// Print 'open-file-path',
'print-preview',
'print-preview-styled', // PDF editor from toolbar
'show-pdf-editor-from-toolbar',
// Export dialogs
'show-export-dialog', // Menu triggers
'show-batch-dialog', 'menu-open',
'show-universal-converter-dialog', 'export',
'show-table-generator',
'show-pdf-editor-dialog', // Git diff
'git-diff'
// Converter dialogs ];
'show-image-converter',
'show-audio-converter', const ALLOWED_RECEIVE_CHANNELS = [
'show-video-converter', // File operations
'file-new',
// PDF viewer 'file-opened',
'open-pdf-viewer', 'file-save',
'get-content-for-save',
// Conversion status 'get-content-for-spreadsheet',
'conversion-status', 'recent-files-cleared',
'conversion-complete',
'batch-progress', // UI toggles
'image-conversion-complete', 'toggle-preview',
'audio-conversion-complete', 'toggle-find',
'video-conversion-complete',
// Theme
// Folder selection 'theme-changed',
'folder-selected', 'theme-data',
'pdf-folder-selected',
// Edit operations
// Header/Footer 'undo',
'header-footer-settings-data', 'redo',
'header-footer-logo-selected',
'header-footer-logo-saved', // Font
'adjust-font-size',
// Page settings
'page-settings-data', // Print
'print-preview',
// PDF operations 'print-preview-styled',
'pdf-page-count',
'pdf-operation-complete', // Export dialogs
'pdf-operation-error', 'show-export-dialog',
'show-batch-dialog',
// ASCII Art Generator 'show-universal-converter-dialog',
'show-ascii-generator-window', 'show-table-generator',
'show-ascii-generator', 'show-pdf-editor-dialog',
// Table Generator // Converter dialogs
'show-table-generator-window', 'show-image-converter',
'show-audio-converter',
// Header/Footer dialog 'show-video-converter',
'open-header-footer-dialog',
'header-footer-logo-cleared', // PDF viewer
'open-pdf-viewer',
// PDF operation progress
'pdf-operation-progress', // Conversion status
'conversion-status',
// Insert content from generator windows 'conversion-complete',
'insert-content' 'batch-progress',
]; 'image-conversion-complete',
'audio-conversion-complete',
/** 'video-conversion-complete',
* Secure API exposed to renderer process
* Access via window.electronAPI in renderer // Folder selection
*/ 'folder-selected',
contextBridge.exposeInMainWorld('electronAPI', { 'pdf-folder-selected',
// ============================================
// SEND METHODS (Renderer -> Main) // Header/Footer
// ============================================ 'header-footer-settings-data',
'header-footer-logo-selected',
/** 'header-footer-logo-saved',
* Send a message to the main process
* @param {string} channel - IPC channel name // Page settings
* @param {any} data - Data to send 'page-settings-data',
*/
send: (channel, data) => { // PDF operations
if (ALLOWED_SEND_CHANNELS.includes(channel)) { 'pdf-page-count',
ipcRenderer.send(channel, data); 'pdf-operation-complete',
} else { 'pdf-operation-error',
console.warn(`[Preload] Blocked send to unauthorized channel: ${channel}`);
} // ASCII Art Generator
}, 'show-ascii-generator-window',
'show-ascii-generator',
/**
* Invoke a main process handler and get a response // Table Generator
* @param {string} channel - IPC channel name 'show-table-generator-window',
* @param {any} data - Data to send
* @returns {Promise<any>} Response from main process // Header/Footer dialog
*/ 'open-header-footer-dialog',
invoke: async (channel, data) => { 'header-footer-logo-cleared',
if (ALLOWED_SEND_CHANNELS.includes(channel)) {
return await ipcRenderer.invoke(channel, data); // PDF operation progress
} else { 'pdf-operation-progress',
console.warn(`[Preload] Blocked invoke to unauthorized channel: ${channel}`);
return null; // Insert content from generator windows
} 'insert-content',
},
// Batch converter
// ============================================ 'show-batch-converter',
// RECEIVE METHODS (Main -> Renderer)
// ============================================ // v4 menu-triggered events
'load-template-menu',
/** 'toggle-command-palette',
* Register a listener for messages from main process 'toggle-sidebar-panel',
* @param {string} channel - IPC channel name 'toggle-bottom-panel'
* @param {Function} callback - Function to call with received data ];
* @returns {Function} Cleanup function to remove listener
*/ /**
on: (channel, callback) => { * Secure API exposed to renderer process
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) { * Access via window.electronAPI in renderer
const subscription = (event, ...args) => callback(...args); */
ipcRenderer.on(channel, subscription); contextBridge.exposeInMainWorld('electronAPI', {
// ============================================
// Return cleanup function // SEND METHODS (Renderer -> Main)
return () => { // ============================================
ipcRenderer.removeListener(channel, subscription);
}; /**
} else { * Send a message to the main process
console.warn(`[Preload] Blocked listener for unauthorized channel: ${channel}`); * @param {string} channel - IPC channel name
return () => {}; // No-op cleanup * @param {any} data - Data to send
} */
}, send: (channel, data) => {
if (ALLOWED_SEND_CHANNELS.includes(channel)) {
/** ipcRenderer.send(channel, data);
* Register a one-time listener for messages from main process } else {
* @param {string} channel - IPC channel name console.warn(`[Preload] Blocked send to unauthorized channel: ${channel}`);
* @param {Function} callback - Function to call with received data }
*/ },
once: (channel, callback) => {
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) { /**
ipcRenderer.once(channel, (event, ...args) => callback(...args)); * Invoke a main process handler and get a response
} else { * @param {string} channel - IPC channel name
console.warn(`[Preload] Blocked once listener for unauthorized channel: ${channel}`); * @param {any} data - Data to send
} * @returns {Promise<any>} Response from main process
}, */
invoke: async (channel, data) => {
/** if (ALLOWED_SEND_CHANNELS.includes(channel)) {
* Remove all listeners for a channel return await ipcRenderer.invoke(channel, data);
* @param {string} channel - IPC channel name } else {
*/ console.warn(`[Preload] Blocked invoke to unauthorized channel: ${channel}`);
removeAllListeners: (channel) => { return null;
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) { }
ipcRenderer.removeAllListeners(channel); },
}
}, // ============================================
// RECEIVE METHODS (Main -> Renderer)
// ============================================ // ============================================
// CONVENIENCE METHODS
// ============================================ /**
* Register a listener for messages from main process
// File Operations * @param {string} channel - IPC channel name
file: { * @param {Function} callback - Function to call with received data
save: (filePath, content) => ipcRenderer.send('save-file', { path: filePath, content }), * @returns {Function} Cleanup function to remove listener
saveCurrent: (content) => ipcRenderer.send('save-current-file', content), */
setCurrent: (filePath) => ipcRenderer.send('set-current-file', filePath), on: (channel, callback) => {
saveRecent: (recentFiles) => ipcRenderer.send('save-recent-files', recentFiles), if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
clearRecent: () => ipcRenderer.send('clear-recent-files'), const subscription = (event, ...args) => callback(...args);
rendererReady: () => ipcRenderer.send('renderer-ready') ipcRenderer.on(channel, subscription);
},
// Return cleanup function
// Theme Operations return () => {
theme: { ipcRenderer.removeListener(channel, subscription);
get: () => ipcRenderer.send('get-theme') };
}, } else {
console.warn(`[Preload] Blocked listener for unauthorized channel: ${channel}`);
// Print Operations return () => {}; // No-op cleanup
print: { }
doPrint: (options) => ipcRenderer.send('do-print', options) },
},
/**
// Export Operations * Register a one-time listener for messages from main process
export: { * @param {string} channel - IPC channel name
withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }), * @param {Function} callback - Function to call with received data
spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format }) */
}, once: (channel, callback) => {
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
// Batch Conversion ipcRenderer.once(channel, (event, ...args) => callback(...args));
batch: { } else {
convert: (inputFolder, outputFolder, format, options) => { console.warn(`[Preload] Blocked once listener for unauthorized channel: ${channel}`);
ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options }); }
}, },
selectFolder: (type) => ipcRenderer.send('select-folder', type)
}, /**
* Remove all listeners for a channel
// Universal Converter * @param {string} channel - IPC channel name
converter: { */
convert: (tool, fromFormat, toFormat, filePath) => { removeAllListeners: (channel) => {
ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath }); if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
}, ipcRenderer.removeAllListeners(channel);
convertBatch: (tool, fromFormat, toFormat, inputFolder, outputFolder) => { }
ipcRenderer.send('universal-convert-batch', { tool, fromFormat, toFormat, inputFolder, outputFolder }); },
}
}, // ============================================
// CONVENIENCE METHODS
// Header/Footer Operations // ============================================
headerFooter: {
getSettings: () => ipcRenderer.send('get-header-footer-settings'), // File Operations
saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings), file: {
browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position), save: (filePath, content) => ipcRenderer.send('save-file', { path: filePath, content }),
saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }), saveCurrent: (content) => ipcRenderer.send('save-current-file', content),
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position) setCurrent: (filePath) => ipcRenderer.send('set-current-file', filePath),
}, saveRecent: (recentFiles) => ipcRenderer.send('save-recent-files', recentFiles),
clearRecent: () => ipcRenderer.send('clear-recent-files'),
// Page Settings rendererReady: () => ipcRenderer.send('renderer-ready')
page: { },
getSettings: () => ipcRenderer.send('get-page-settings'),
updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings), // Theme Operations
setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber) theme: {
}, get: () => ipcRenderer.send('get-theme')
},
// PDF Operations
pdf: { // Print Operations
processOperation: (data) => ipcRenderer.send('process-pdf-operation', data), print: {
getPageCount: (filePath) => ipcRenderer.send('get-pdf-page-count', filePath), doPrint: (options) => ipcRenderer.send('do-print', options)
selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId) },
},
// Export Operations
// Image Converter Operations export: {
image: { withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }),
convert: (data) => ipcRenderer.send('image-convert', data), spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format })
batchConvert: (data) => ipcRenderer.send('image-batch-convert', data), },
resize: (data) => ipcRenderer.send('image-resize', data),
compress: (data) => ipcRenderer.send('image-compress', data), // Batch Conversion
rotate: (data) => ipcRenderer.send('image-rotate', data) batch: {
}, convert: (inputFolder, outputFolder, format, options) => {
ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options });
// Audio Converter Operations },
audio: { selectFolder: (type) => ipcRenderer.send('select-folder', type)
convert: (data) => ipcRenderer.send('audio-convert', data), },
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
extract: (data) => ipcRenderer.send('audio-extract', data), // Universal Converter
trim: (data) => ipcRenderer.send('audio-trim', data), converter: {
merge: (data) => ipcRenderer.send('audio-merge', data) convert: (tool, fromFormat, toFormat, filePath) => {
}, ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath });
},
// Video Converter Operations convertBatch: (tool, fromFormat, toFormat, inputFolder, outputFolder) => {
video: { ipcRenderer.send('universal-convert-batch', { tool, fromFormat, toFormat, inputFolder, outputFolder });
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), // Header/Footer Operations
extractFrames: (data) => ipcRenderer.send('video-frames', data), headerFooter: {
toGif: (data) => ipcRenderer.send('video-gif', data) 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),
// Generator Windows saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }),
generators: { clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position)
openAscii: () => ipcRenderer.send('open-ascii-generator'), },
openTable: () => ipcRenderer.send('open-table-generator')
} // Page Settings
}); page: {
getSettings: () => ipcRenderer.send('get-page-settings'),
// Log successful preload initialization updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings),
console.log('[Preload] Secure IPC bridge initialized'); setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber)
console.log('[Preload] Allowed send channels:', ALLOWED_SEND_CHANNELS.length); },
console.log('[Preload] Allowed receive channels:', ALLOWED_RECEIVE_CHANNELS.length);
// 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)
},
// Generator Windows
generators: {
openAscii: () => ipcRenderer.send('open-ascii-generator'),
openTable: () => ipcRenderer.send('open-table-generator')
}
});
// Log successful preload initialization
console.log('[Preload] Secure IPC bridge initialized');
console.log('[Preload] Allowed send channels:', ALLOWED_SEND_CHANNELS.length);
console.log('[Preload] Allowed receive channels:', ALLOWED_RECEIVE_CHANNELS.length);
+138
View File
@@ -0,0 +1,138 @@
class PrintPreview {
constructor() {
this.overlay = document.getElementById('print-preview-overlay');
this.modal = window.modals?.printPreviewModal;
this._lastContent = '';
this.setupEventListeners();
}
open(htmlContent) {
this._lastContent = htmlContent;
if (this.modal) {
this.modal.open();
} else {
this.overlay.classList.remove('hidden');
}
this.updatePreview(htmlContent);
this.updateScaleLabel();
}
close() {
if (this.modal) {
this.modal.close();
} else {
this.overlay.classList.add('hidden');
}
}
setupEventListeners() {
document.getElementById('print-preview-close')?.addEventListener('click', () => this.close());
document.getElementById('print-cancel')?.addEventListener('click', () => this.close());
document.getElementById('print-execute')?.addEventListener('click', () => this.executePrint());
// Update preview on option changes
['print-paper-size', 'print-orientation', 'print-margins'].forEach(id => {
document.getElementById(id)?.addEventListener('change', () => this.refreshPreview());
});
// Scale slider
const scaleSlider = document.getElementById('print-scale');
scaleSlider?.addEventListener('input', () => this.updateScaleLabel());
// Page range toggle
document.getElementById('print-pages')?.addEventListener('change', (e) => {
const rangeInput = document.getElementById('print-page-range');
if (rangeInput) {
rangeInput.classList.toggle('hidden', e.target.value !== 'custom');
}
});
// Note: Backdrop click and Escape key are now handled by ModalManager
}
updateScaleLabel() {
const scale = document.getElementById('print-scale')?.value || 100;
const label = document.getElementById('print-scale-value');
if (label) label.textContent = `${scale}%`;
}
updatePreview(htmlContent) {
const frame = document.getElementById('print-preview-frame');
if (!frame) return;
this._lastContent = htmlContent;
const orientation = document.getElementById('print-orientation')?.value || 'portrait';
const paperSize = document.getElementById('print-paper-size')?.value || 'A4';
// Get dimensions for paper size
const sizes = {
'A3': { width: '297mm', height: '420mm' },
'A4': { width: '210mm', height: '297mm' },
'A5': { width: '148mm', height: '210mm' },
'Letter': { width: '8.5in', height: '11in' },
'Legal': { width: '8.5in', height: '14in' },
'Tabloid': { width: '11in', height: '17in' },
};
const size = sizes[paperSize] || sizes['A4'];
const width = orientation === 'landscape' ? size.height : size.width;
const height = orientation === 'landscape' ? size.width : size.height;
const previewHtml = `
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 14px;
line-height: 1.6;
}
@page { size: ${width} ${height}; }
pre { background: #f5f5f5; padding: 12px; border-radius: 6px; overflow-x: auto; }
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
pre code { background: none; padding: 0; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; }
blockquote { border-left: 4px solid #ddd; margin-left: 0; padding-left: 16px; color: #666; }
img { max-width: 100%; }
h1, h2, h3 { margin-top: 1.5em; }
</style>
</head>
<body>${htmlContent || ''}</body>
</html>
`;
frame.srcdoc = previewHtml;
}
refreshPreview() {
if (this._lastContent) {
this.updatePreview(this._lastContent);
}
}
getOptions() {
return {
paperSize: document.getElementById('print-paper-size')?.value || 'A4',
orientation: document.getElementById('print-orientation')?.value || 'portrait',
margins: document.getElementById('print-margins')?.value || 'default',
scale: parseInt(document.getElementById('print-scale')?.value || '100'),
headers: document.getElementById('print-headers')?.checked ?? true,
background: document.getElementById('print-background')?.checked ?? true,
pages: document.getElementById('print-pages')?.value || 'all',
pageRange: document.getElementById('print-page-range')?.value || '',
};
}
executePrint() {
const options = this.getOptions();
const { ipcRenderer } = require('electron');
ipcRenderer.send('do-print-with-options', options);
this.close();
}
}
module.exports = { PrintPreview };
+4631 -4514
View File
File diff suppressed because it is too large Load Diff
+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 };
+70
View File
@@ -0,0 +1,70 @@
const path = require('path');
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 };
+84
View File
@@ -0,0 +1,84 @@
function renderGitPanel(container, { gitStatus, gitDiff, gitStage, gitCommit, gitLog }) {
container.innerHTML = `
<div class="git-panel">
<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>
</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();
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">${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="${f.file}">
<span class="git-file-status" style="color:${f.color}">${f.status}</span>
<span class="git-file-name">${f.file}</span>
<button class="git-stage-btn" data-file="${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();
});
});
}
// 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">${entry.message}</div>
<div class="git-log-meta">${entry.date?.substring(0, 10) || ''} &middot; ${entry.author_name || ''}</div>
</div>
`).join('') || '<p class="git-info">No commits</p>';
}
}
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();
});
}
module.exports = { renderGitPanel };
+50
View File
@@ -0,0 +1,50 @@
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 };
+71
View File
@@ -0,0 +1,71 @@
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 };
+34
View File
@@ -0,0 +1,34 @@
const fs = require('fs');
const path = require('path');
const templates = [
{ name: 'Blog Post', file: 'blog-post.md', description: 'Article with frontmatter' },
{ name: 'Meeting Notes', file: 'meeting-notes.md', description: 'Agenda, notes, action items' },
{ name: 'Technical Spec', file: 'technical-spec.md', description: 'Requirements and architecture' },
{ name: 'Changelog', file: 'changelog.md', description: 'Keep a Changelog format' },
{ name: 'README', file: 'readme.md', description: 'Project documentation' },
{ name: 'Project Plan', file: 'project-plan.md', description: 'Goals, milestones, timeline' },
{ name: 'API Docs', file: 'api-docs.md', description: 'API endpoint documentation' },
{ name: 'Tutorial', file: 'tutorial.md', description: 'Step-by-step guide' },
{ name: 'Release Notes', file: 'release-notes.md', description: 'Version release summary' },
{ name: 'Comparison', file: 'comparison.md', description: 'Feature comparison table' },
];
function renderTemplatesPanel(container, onSelect) {
container.innerHTML = `
<div class="panel-list">
${templates.map(t => `
<div class="panel-list-item template-item" data-file="${t.file}">
<div class="panel-list-item-title">${t.name}</div>
<div class="panel-list-item-desc">${t.description}</div>
</div>
`).join('')}
</div>
`;
container.querySelectorAll('.template-item').forEach(el => {
el.addEventListener('click', () => onSelect(el.dataset.file));
});
}
module.exports = { renderTemplatesPanel, templates };
File diff suppressed because it is too large Load Diff
+2348 -2113
View File
File diff suppressed because it is too large Load Diff
+278
View File
@@ -0,0 +1,278 @@
/* Sidebar */
.main-content {
display: flex;
flex: 1;
overflow: hidden;
min-height: 0;
}
.sidebar {
display: flex;
flex-shrink: 0;
height: 100%;
transition: width 0.2s ease;
}
.sidebar.collapsed {
width: 48px;
}
.sidebar:not(.collapsed) {
width: 328px; /* 48px icons + 280px panel */
}
.sidebar-icons {
display: flex;
flex-direction: column;
width: 48px;
background: var(--gray-100, #f3f4f6);
border-right: 1px solid var(--gray-200, #e5e7eb);
padding: 8px 0;
gap: 4px;
align-items: center;
}
.sidebar-icon {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border: none;
background: transparent;
border-radius: 8px;
cursor: pointer;
color: var(--gray-500, #6b7280);
transition: all 0.15s ease;
}
.sidebar-icon:hover {
background: var(--gray-200, #e5e7eb);
color: var(--gray-700, #374151);
}
.sidebar-icon.active {
background: var(--gray-200, #e5e7eb);
color: var(--primary-dark, #5661b3);
box-shadow: inset 3px 0 0 var(--primary-dark, #5661b3);
}
.sidebar-icon:focus-visible {
outline: 2px solid var(--primary-dark, #5661b3);
outline-offset: 2px;
}
.sidebar-panel {
width: 280px;
background: var(--gray-50, #f9fafb);
border-right: 1px solid var(--gray-200, #e5e7eb);
display: flex;
flex-direction: column;
overflow: hidden;
}
.sidebar.collapsed .sidebar-panel {
display: none;
}
.sidebar-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--gray-200, #e5e7eb);
font-weight: 600;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--gray-600, #4b5563);
}
.sidebar-panel-close {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
color: var(--gray-400, #9ca3af);
padding: 0 4px;
border-radius: 4px;
}
.sidebar-panel-close:hover {
background: var(--gray-200, #e5e7eb);
color: var(--gray-600, #4b5563);
}
.sidebar-panel-close:focus-visible {
outline: 2px solid var(--primary-dark, #5661b3);
outline-offset: 2px;
}
.sidebar-panel-content {
flex: 1;
overflow-y: auto;
padding: 12px;
}
/* Dark theme support */
body[class*="dark"] .sidebar-icons,
body[class*="dark"] .sidebar-panel {
background: #1e1e1e;
border-color: #333;
}
body[class*="dark"] .sidebar-icon {
color: #888;
}
body[class*="dark"] .sidebar-icon:hover {
background: #333;
color: #ccc;
}
body[class*="dark"] .sidebar-icon.active {
background: #333;
color: #8b9aff;
box-shadow: inset 3px 0 0 #8b9aff;
}
body[class*="dark"] .sidebar-panel-header {
border-color: #333;
color: #ccc;
}
/* Panel list items (templates, etc.) */
.panel-list-item {
padding: 10px 12px;
border-radius: 6px;
cursor: pointer;
margin-bottom: 4px;
}
.panel-list-item:hover {
background: var(--gray-200, #e5e7eb);
}
.panel-list-item-title {
font-size: 13px;
font-weight: 500;
color: var(--gray-800, #1f2937);
}
.panel-list-item-desc {
font-size: 11px;
color: var(--gray-500, #6b7280);
margin-top: 2px;
}
body[class*="dark"] .panel-list-item:hover {
background: #333;
}
body[class*="dark"] .panel-list-item-title {
color: #ddd;
}
body[class*="dark"] .panel-list-item-desc {
color: #888;
}
/* Explorer Panel */
.explorer-toolbar {
display: flex;
gap: 4px;
margin-bottom: 8px;
}
.explorer-path {
flex: 1;
padding: 6px 8px;
border: 1px solid var(--gray-300, #d1d5db);
border-radius: 6px;
font-size: 12px;
background: white;
overflow: hidden;
text-overflow: ellipsis;
}
.explorer-browse-btn {
border: 1px solid var(--gray-300, #d1d5db);
border-radius: 6px;
background: white;
cursor: pointer;
padding: 4px 8px;
}
.tree-item {
padding: 3px 0;
cursor: pointer;
font-size: 13px;
user-select: none;
}
.tree-item:hover {
background: var(--gray-100, #f3f4f6);
border-radius: 4px;
}
.tree-icon {
margin-right: 4px;
font-size: 12px;
}
.tree-children {
padding-left: 16px;
}
.tree-folder.collapsed .tree-children {
display: none;
}
.tree-name {
font-size: 13px;
}
/* Git Panel */
.git-section { margin-bottom: 16px; }
.git-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gray-500); margin-bottom: 8px; }
.git-file { display: flex; align-items: center; padding: 4px 6px; border-radius: 4px; font-size: 13px; gap: 6px; }
.git-file:hover { background: var(--gray-100, #f3f4f6); }
.git-file-status { font-weight: 700; font-family: monospace; width: 16px; text-align: center; }
.git-file-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.git-stage-btn { border: none; background: var(--gray-200); border-radius: 4px; cursor: pointer; font-size: 14px; width: 22px; height: 22px; }
.git-commit-input { width: 100%; padding: 8px; border: 1px solid var(--gray-300); border-radius: 6px; font-size: 13px; font-family: inherit; resize: vertical; box-sizing: border-box; }
.git-commit-btn { width: 100%; margin-top: 8px; padding: 8px; background: var(--primary-dark, #5661b3); color: white; border: none; border-radius: 6px; font-size: 13px; cursor: pointer; }
.git-commit-btn:hover { opacity: 0.9; }
.git-log-entry { padding: 6px 0; border-bottom: 1px solid var(--gray-100); }
.git-log-msg { font-size: 13px; }
.git-log-meta { font-size: 11px; color: var(--gray-500); margin-top: 2px; }
.git-info { font-size: 13px; color: var(--gray-500); padding: 8px 0; }
.git-loading { font-size: 13px; color: var(--gray-400); }
/* Snippets Panel */
.snippets-toolbar { display: flex; gap: 4px; margin-bottom: 8px; }
.snippets-search { flex: 1; padding: 6px 10px; border: 1px solid var(--gray-300); border-radius: 6px; font-size: 13px; }
.snippets-add-btn { width: 32px; border: 1px solid var(--gray-300); border-radius: 6px; background: white; font-size: 18px; cursor: pointer; }
.snippet-item { padding: 8px; border: 1px solid var(--gray-200); border-radius: 6px; margin-bottom: 6px; }
.snippet-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
.snippet-name { font-size: 13px; font-weight: 500; }
.snippet-lang { font-size: 11px; background: var(--gray-100); padding: 2px 6px; border-radius: 4px; color: var(--gray-500); }
.snippet-preview { font-size: 12px; background: var(--gray-50); padding: 6px; border-radius: 4px; margin: 4px 0; overflow: hidden; max-height: 60px; }
.snippet-preview code { font-family: 'JetBrains Mono', monospace; }
.snippet-actions { display: flex; gap: 4px; }
.snippet-insert { font-size: 12px; padding: 4px 8px; border: 1px solid var(--gray-300); border-radius: 4px; background: white; cursor: pointer; }
.snippet-delete { font-size: 14px; padding: 4px 8px; border: 1px solid var(--gray-300); border-radius: 4px; background: white; cursor: pointer; color: #ef4444; }
/* Dark theme for sidebar panels */
body[class*="dark"] .explorer-path,
body[class*="dark"] .explorer-browse-btn,
body[class*="dark"] .snippets-search,
body[class*="dark"] .snippets-add-btn,
body[class*="dark"] .snippet-insert,
body[class*="dark"] .snippet-delete {
background: #2d2d2d;
border-color: #444;
color: #ccc;
}
body[class*="dark"] .git-commit-input {
background: #2d2d2d;
border-color: #444;
color: #ccc;
}
body[class*="dark"] .snippet-item {
border-color: #444;
}
body[class*="dark"] .snippet-preview {
background: #2d2d2d;
}
body[class*="dark"] .tree-item:hover,
body[class*="dark"] .git-file:hover {
background: #333;
}
+24
View File
@@ -0,0 +1,24 @@
.welcome-container { padding: 40px; max-width: 900px; margin: 0 auto; }
.welcome-hero { text-align: center; margin-bottom: 40px; }
.welcome-title { font-size: 32px; font-weight: 700; color: var(--gray-800, #1f2937); }
.welcome-version { font-size: 14px; color: var(--primary-dark, #5661b3); margin-top: 4px; font-weight: 500; }
.welcome-subtitle { font-size: 16px; color: var(--gray-500, #6b7280); margin-top: 8px; }
.welcome-grid { display: grid; gap: 32px; }
.welcome-section h2 { font-size: 18px; margin-bottom: 16px; color: var(--gray-700, #374151); }
.welcome-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
.welcome-card { padding: 20px; border: 1px solid var(--gray-200, #e5e7eb); border-radius: 12px; cursor: pointer; text-align: center; transition: all 0.2s; }
.welcome-card:hover { border-color: var(--primary-dark, #5661b3); box-shadow: 0 4px 12px rgba(0,0,0,0.08); transform: translateY(-2px); }
.welcome-card-icon { font-size: 28px; margin-bottom: 8px; }
.welcome-card h3 { font-size: 15px; margin-bottom: 4px; }
.welcome-card p { font-size: 13px; color: var(--gray-500); }
.welcome-card kbd { display: inline-block; margin-top: 8px; padding: 2px 8px; background: var(--gray-100); border: 1px solid var(--gray-300); border-radius: 4px; font-size: 12px; font-family: 'JetBrains Mono', monospace; }
.welcome-features { list-style: none; padding: 0; }
.welcome-features li { padding: 6px 0; font-size: 14px; border-bottom: 1px solid var(--gray-100, #f3f4f6); }
.welcome-features strong { color: var(--primary-dark, #5661b3); }
.welcome-recent-item { padding: 8px 12px; border-radius: 6px; cursor: pointer; margin-bottom: 4px; }
.welcome-recent-item:hover { background: var(--gray-100); }
.welcome-recent-name { font-size: 14px; font-weight: 500; display: block; }
.welcome-recent-path { font-size: 12px; color: var(--gray-500); display: block; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; }
.welcome-muted { color: var(--gray-400); font-size: 14px; }
.welcome-footer { margin-top: 32px; text-align: center; }
.welcome-checkbox { font-size: 13px; color: var(--gray-500); cursor: pointer; }
+3675 -4080
View File
File diff suppressed because it is too large Load Diff
+265
View File
@@ -0,0 +1,265 @@
/**
* Modal System Styles
* Unified modal components with glassmorphism backdrop
* @version 4.0.0
*/
/* ============================================
* Modal Backdrop - Glassmorphism
* ============================================ */
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
z-index: 0;
cursor: pointer;
}
/* ============================================
* Modal Container
* ============================================ */
.modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
z-index: calc(var(--z-modal, 200) + 1);
opacity: 0;
visibility: hidden;
transition: opacity var(--transition-normal, 200ms cubic-bezier(0.4, 0, 0.2, 1)),
visibility var(--transition-normal, 200ms cubic-bezier(0.4, 0, 0.2, 1));
padding: var(--spacing-4, 1rem);
}
.modal.open {
opacity: 1;
visibility: visible;
}
/* ============================================
* Modal Content - With Animation
* ============================================ */
.modal-content {
position: relative;
z-index: 1;
width: 100%;
background: hsl(var(--background, 0 0% 100%));
border-radius: var(--radius-lg, 0.5rem);
box-shadow: var(--shadow-xl, 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1));
max-width: 90vw;
max-height: 90vh;
overflow: hidden;
display: flex;
flex-direction: column;
transform: scale(0.95);
transition: transform var(--transition-normal, 200ms cubic-bezier(0.4, 0, 0.2, 1));
}
.modal.open .modal-content {
transform: scale(1);
}
/* ============================================
* Modal Header
* ============================================ */
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--spacing-4, 1rem) var(--spacing-6, 1.5rem);
border-bottom: 1px solid hsl(var(--border, 214.3 31.8% 91.4%));
background: hsl(var(--muted, 210 40% 96.1%));
}
.modal-header h3 {
margin: 0;
font-size: var(--text-lg, 1.125rem);
font-weight: var(--font-semibold, 600);
color: hsl(var(--foreground, 222.2 84% 4.9%));
}
/* ============================================
* Modal Close Button
* ============================================ */
.modal-close {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border: none;
border-radius: var(--radius, 0.5rem);
background: transparent;
color: hsl(var(--muted-foreground, 215.4 16.3% 46.9%));
font-size: 24px;
line-height: 1;
cursor: pointer;
transition: background-color var(--transition-fast, 150ms),
color var(--transition-fast, 150ms);
}
.modal-close:hover {
background: hsl(var(--accent, 210 40% 96.1%));
color: hsl(var(--foreground, 222.2 84% 4.9%));
}
.modal-close:focus-visible {
outline: 2px solid hsl(var(--ring, 227 44% 52%));
outline-offset: 2px;
}
/* ============================================
* Modal Body
* ============================================ */
.modal-body {
padding: var(--spacing-6, 1.5rem);
overflow-y: auto;
flex: 1;
}
/* ============================================
* Modal Footer
* ============================================ */
.modal-footer {
display: flex;
justify-content: flex-end;
gap: var(--spacing-3, 0.75rem);
padding: var(--spacing-4, 1rem) var(--spacing-6, 1.5rem);
border-top: 1px solid hsl(var(--border, 214.3 31.8% 91.4%));
background: hsl(var(--muted, 210 40% 96.1%));
}
.modal-footer .btn {
min-width: 80px;
/* styles-modern.css sets flex:1 on .btn-primary/.btn-secondary globally
* which causes footer buttons to stretch to full width. Override here. */
flex: none;
}
/* ============================================
* Form Elements within Modal
* ============================================ */
.modal-body .form-row {
display: flex;
align-items: center;
gap: var(--spacing-3, 0.75rem);
margin-bottom: var(--spacing-3, 0.75rem);
}
.modal-body .form-row label {
min-width: 100px;
font-size: var(--text-sm, 0.875rem);
color: hsl(var(--foreground, 222.2 84% 4.9%));
}
.modal-body .form-row input,
.modal-body .form-row select {
flex: 1;
padding: var(--spacing-2, 0.5rem) var(--spacing-3, 0.75rem);
border: 1px solid hsl(var(--input, 214.3 31.8% 91.4%));
border-radius: var(--radius, 0.5rem);
font-size: var(--text-sm, 0.875rem);
background: hsl(var(--background, 0 0% 100%));
color: hsl(var(--foreground, 222.2 84% 4.9%));
}
.modal-body .form-row input:focus,
.modal-body .form-row select:focus {
outline: 2px solid hsl(var(--ring, 227 44% 52%));
outline-offset: 1px;
}
.modal-body .export-section {
margin-bottom: var(--spacing-4, 1rem);
padding-bottom: var(--spacing-4, 1rem);
border-bottom: 1px solid hsl(var(--border, 214.3 31.8% 91.4%));
}
.modal-body .export-section:last-child {
border-bottom: none;
margin-bottom: 0;
}
.modal-body .export-section label {
display: block;
font-weight: var(--font-medium, 500);
margin-bottom: var(--spacing-2, 0.5rem);
color: hsl(var(--foreground, 222.2 84% 4.9%));
}
.modal-body .checkbox-group label {
display: flex;
align-items: center;
gap: var(--spacing-2, 0.5rem);
margin-bottom: var(--spacing-2, 0.5rem);
font-weight: var(--font-normal, 400);
cursor: pointer;
}
/* ============================================
* Size Variants
* ============================================ */
.modal-content.small {
max-width: 400px;
min-width: 320px;
}
.modal-content.large {
max-width: 800px;
min-width: 560px;
}
.modal-content.full {
max-width: 95vw;
max-height: 95vh;
min-width: min(95vw, 700px);
}
/* ============================================
* Dark Mode Support
* ============================================ */
.dark .modal-content,
[data-theme="dark"] .modal-content {
background: hsl(var(--background));
box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.4), 0 8px 10px -6px rgb(0 0 0 / 0.3);
}
.dark .modal-header,
.dark .modal-footer,
[data-theme="dark"] .modal-header,
[data-theme="dark"] .modal-footer {
background: hsl(var(--muted));
}
/* ============================================
* Accessibility - Reduced Motion
* ============================================ */
@media (prefers-reduced-motion: reduce) {
.modal,
.modal-content {
transition: none;
}
}
/* ============================================
* Legacy Support - Hidden class
* ============================================ */
.modal.hidden {
display: none;
}
+347
View File
@@ -0,0 +1,347 @@
/**
* Design Tokens - Shadcn/ui Compatible
*
* This file provides CSS custom properties (design tokens) following
* the Shadcn/ui convention. These tokens enable consistent theming
* and easy theme switching between light and dark modes.
*
* Usage:
* color: hsl(var(--primary));
* background: hsl(var(--background));
*
* @version 4.1.0
*/
:root {
/* ============================================
* Base Colors - Light Mode
* ============================================ */
/* Background and foreground */
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
/* Card */
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
/* Popover/Dropdown */
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
/* Primary - Brand color (ConcreteInfo blue-purple) */
--primary: 227 44% 52%;
--primary-foreground: 210 40% 98%;
/* Secondary */
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
/* Muted - Subtle backgrounds */
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
/* Accent - Highlight color */
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
/* Destructive - Error/danger states */
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
/* Success - Positive states */
--success: 142 76% 36%;
--success-foreground: 210 40% 98%;
/* Warning - Caution states */
--warning: 38 92% 50%;
--warning-foreground: 0 0% 0%;
/* Info - Informational states */
--info: 199 89% 48%;
--info-foreground: 210 40% 98%;
/* Border and input */
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
/* Focus ring */
--ring: 227 44% 52%;
/* ============================================
* Spacing & Sizing
* ============================================ */
--radius: 0.5rem;
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
/* Spacing unit (4px base) */
--spacing-1: 0.25rem;
--spacing-2: 0.5rem;
--spacing-3: 0.75rem;
--spacing-4: 1rem;
--spacing-5: 1.25rem;
--spacing-6: 1.5rem;
--spacing-8: 2rem;
--spacing-10: 2.5rem;
--spacing-12: 3rem;
/* ============================================
* Typography
* ============================================ */
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, 'Courier New', monospace;
--text-xs: 0.75rem;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.125rem;
--text-xl: 1.25rem;
--text-2xl: 1.5rem;
--text-3xl: 1.875rem;
--font-normal: 400;
--font-medium: 500;
--font-semibold: 600;
--font-bold: 700;
--leading-tight: 1.25;
--leading-normal: 1.5;
--leading-relaxed: 1.625;
/* ============================================
* Shadows
* ============================================ */
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
--shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
/* ============================================
* Transitions
* ============================================ */
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-normal: 200ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-slow: 300ms cubic-bezier(0.4, 0, 0.2, 1);
/* ============================================
* Z-Index Scale
* ============================================ */
--z-dropdown: 50;
--z-sticky: 100;
--z-modal: 200;
--z-popover: 300;
--z-tooltip: 400;
--z-toast: 500;
}
/* ============================================
* Dark Mode
* ============================================ */
.dark,
[data-theme="dark"] {
/* Background and foreground */
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
/* Card */
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
/* Popover/Dropdown */
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
/* Primary */
--primary: 227 44% 52%;
--primary-foreground: 222.2 47.4% 11.2%;
/* Secondary */
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
/* Muted */
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
/* Accent */
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
/* Destructive */
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
/* Success */
--success: 142 76% 26%;
--success-foreground: 210 40% 98%;
/* Warning */
--warning: 38 92% 40%;
--warning-foreground: 0 0% 100%;
/* Info */
--info: 199 89% 38%;
--info-foreground: 210 40% 98%;
/* Border and input */
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
/* Focus ring */
--ring: 227 44% 52%;
}
/* ============================================
* Semantic Color Classes
* ============================================ */
.bg-background { background-color: hsl(var(--background)); }
.bg-foreground { background-color: hsl(var(--foreground)); }
.bg-card { background-color: hsl(var(--card)); }
.bg-primary { background-color: hsl(var(--primary)); }
.bg-secondary { background-color: hsl(var(--secondary)); }
.bg-muted { background-color: hsl(var(--muted)); }
.bg-accent { background-color: hsl(var(--accent)); }
.bg-destructive { background-color: hsl(var(--destructive)); }
.text-foreground { color: hsl(var(--foreground)); }
.text-primary { color: hsl(var(--primary)); }
.text-secondary { color: hsl(var(--secondary-foreground)); }
.text-muted-foreground { color: hsl(var(--muted-foreground)); }
.text-destructive { color: hsl(var(--destructive)); }
.border-border { border-color: hsl(var(--border)); }
.border-primary { border-color: hsl(var(--primary)); }
.border-input { border-color: hsl(var(--input)); }
/* ============================================
* Utility Classes
* ============================================ */
/* Focus ring */
.focus-ring:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
/* Button base styles */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--spacing-2) var(--spacing-4);
font-size: var(--text-sm);
font-weight: var(--font-medium);
border-radius: var(--radius);
transition: all var(--transition-fast);
cursor: pointer;
}
.btn:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
.btn-primary {
background-color: hsl(var(--primary));
color: hsl(var(--primary-foreground));
}
.btn-primary:hover {
background-color: hsl(var(--primary) / 0.9);
}
.btn-secondary {
background-color: hsl(var(--secondary));
color: hsl(var(--secondary-foreground));
}
.btn-secondary:hover {
background-color: hsl(var(--secondary) / 0.8);
}
.btn-destructive {
background-color: hsl(var(--destructive));
color: hsl(var(--destructive-foreground));
}
.btn-destructive:hover {
background-color: hsl(var(--destructive) / 0.9);
}
.btn-ghost {
background-color: transparent;
color: hsl(var(--foreground));
}
.btn-ghost:hover {
background-color: hsl(var(--accent));
}
.btn-outline {
background-color: transparent;
border: 1px solid hsl(var(--border));
color: hsl(var(--foreground));
}
.btn-outline:hover {
background-color: hsl(var(--accent));
color: hsl(var(--accent-foreground));
}
/* Badge styles */
.badge {
display: inline-flex;
align-items: center;
padding: var(--spacing-1) var(--spacing-2);
font-size: var(--text-xs);
font-weight: var(--font-medium);
border-radius: 9999px;
}
.badge-primary {
background-color: hsl(var(--primary));
color: hsl(var(--primary-foreground));
}
.badge-secondary {
background-color: hsl(var(--secondary));
color: hsl(var(--secondary-foreground));
}
.badge-destructive {
background-color: hsl(var(--destructive));
color: hsl(var(--destructive-foreground));
}
/* Input styles */
.input {
display: flex;
width: 100%;
padding: var(--spacing-2) var(--spacing-3);
font-size: var(--text-sm);
border: 1px solid hsl(var(--input));
border-radius: var(--radius);
background-color: hsl(var(--background));
color: hsl(var(--foreground));
transition: border-color var(--transition-fast);
}
.input:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
.input::placeholder {
color: hsl(var(--muted-foreground));
}
+545 -545
View File
File diff suppressed because it is too large Load Diff
+90
View File
@@ -0,0 +1,90 @@
# API Documentation
**Base URL:** `https://api.example.com/v1`
**Version:** 1.0
**Date:** {{DATE}}
## Authentication
All requests require an API key in the header:
```
Authorization: Bearer YOUR_API_KEY
```
## Endpoints
### Get All Resources
```
GET /resources
```
**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| page | integer | No | Page number (default: 1) |
| limit | integer | No | Items per page (default: 20) |
**Response:**
```json
{
"data": [],
"total": 0,
"page": 1
}
```
### Get Resource by ID
```
GET /resources/:id
```
**Response:**
```json
{
"id": "1",
"name": "Resource name",
"created_at": "2024-01-01T00:00:00Z"
}
```
### Create Resource
```
POST /resources
```
**Request Body:**
```json
{
"name": "New resource",
"description": "Description"
}
```
### Update Resource
```
PUT /resources/:id
```
### Delete Resource
```
DELETE /resources/:id
```
## Error Codes
| Code | Description |
|------|-------------|
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Internal Server Error |
+20
View File
@@ -0,0 +1,20 @@
---
title: Blog Post Title
date: {{DATE}}
author: Your Name
tags: []
---
# Blog Post Title
## Introduction
Write your introduction here.
## Main Content
Your main content goes here.
## Conclusion
Wrap up your thoughts.
+20
View File
@@ -0,0 +1,20 @@
# Changelog
## [Unreleased]
### Added
- New feature
### Changed
- Updated feature
### Fixed
- Bug fix
### Removed
- Removed feature
## [1.0.0] - {{DATE}}
### Added
- Initial release
+59
View File
@@ -0,0 +1,59 @@
# Comparison: [Option A] vs [Option B]
**Date:** {{DATE}}
**Author:** Your Name
## Overview
Brief description of what is being compared and why.
## Feature Comparison
| Feature | Option A | Option B |
|---------|----------|----------|
| Feature 1 | Yes | Yes |
| Feature 2 | Yes | No |
| Feature 3 | No | Yes |
| Feature 4 | Partial | Yes |
## Pricing
| Plan | Option A | Option B |
|------|----------|----------|
| Free | Limited | Limited |
| Pro | $10/mo | $15/mo |
| Enterprise | Custom | Custom |
## Pros and Cons
### Option A
**Pros:**
- Pro 1
- Pro 2
**Cons:**
- Con 1
- Con 2
### Option B
**Pros:**
- Pro 1
- Pro 2
**Cons:**
- Con 1
- Con 2
## Performance
| Metric | Option A | Option B |
|--------|----------|----------|
| Speed | Fast | Moderate |
| Memory | Low | Medium |
| Scalability | Good | Excellent |
## Recommendation
Based on the analysis above, [Option A/B] is recommended for [use case] because [reason].
+26
View File
@@ -0,0 +1,26 @@
# Meeting Notes
**Date:** {{DATE}}
**Attendees:**
- Name 1
- Name 2
## Agenda
1. Topic 1
2. Topic 2
## Discussion
### Topic 1
Notes here.
## Action Items
- [ ] Action item 1 — Owner — Due date
- [ ] Action item 2 — Owner — Due date
## Next Meeting
Date: TBD
+54
View File
@@ -0,0 +1,54 @@
# Project Plan: [Project Name]
**Date:** {{DATE}}
**Project Lead:** Your Name
**Status:** Planning
## Goals
1. Primary goal
2. Secondary goal
## Scope
### In Scope
- Item 1
- Item 2
### Out of Scope
- Item 1
## Milestones
| Milestone | Target Date | Status |
|-----------|-------------|--------|
| Kickoff | {{DATE}} | Not Started |
| MVP | TBD | Not Started |
| Launch | TBD | Not Started |
## Resources
| Role | Person | Allocation |
|------|--------|------------|
| Lead | Name | 100% |
| Developer | Name | 50% |
## Risks
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Risk 1 | High | Medium | Plan |
## Timeline
### Phase 1: Planning
- [ ] Define requirements
- [ ] Create design documents
### Phase 2: Development
- [ ] Implement core features
- [ ] Write tests
### Phase 3: Launch
- [ ] Deploy to production
- [ ] Monitor and iterate
+38
View File
@@ -0,0 +1,38 @@
# Project Name
Brief description of the project.
## Features
- Feature 1
- Feature 2
## Installation
```bash
npm install project-name
```
## Usage
```javascript
const project = require('project-name');
```
## Configuration
| Option | Default | Description |
|--------|---------|-------------|
| option1 | true | Description |
## Contributing
1. Fork the repository
2. Create your feature branch
3. Commit your changes
4. Push to the branch
5. Open a Pull Request
## License
MIT
+42
View File
@@ -0,0 +1,42 @@
# Release Notes - v1.0.0
**Release Date:** {{DATE}}
## Highlights
Brief summary of the most important changes in this release.
## New Features
- **Feature 1:** Description of the new feature
- **Feature 2:** Description of the new feature
## Improvements
- Improved performance of feature X
- Updated dependency Y to version Z
## Bug Fixes
- Fixed issue where X would cause Y (#123)
- Resolved crash when performing Z (#456)
## Breaking Changes
- Changed API endpoint from `/old` to `/new`
- Removed deprecated method `oldMethod()`
## Migration Guide
### From v0.9.x to v1.0.0
1. Update configuration file format
2. Replace deprecated API calls
## Known Issues
- Issue description (#789)
## Contributors
Thanks to everyone who contributed to this release.
+42
View File
@@ -0,0 +1,42 @@
# Technical Specification: [Feature Name]
**Version:** 1.0
**Date:** {{DATE}}
**Author:** Your Name
**Status:** Draft
## Overview
Brief description of what this feature does.
## Requirements
### Functional Requirements
1. Requirement 1
2. Requirement 2
### Non-Functional Requirements
1. Performance requirement
2. Security requirement
## Architecture
Describe the technical approach.
## API Design
### Endpoints
| Method | Path | Description |
|--------|------|-------------|
| GET | /api/resource | Get resource |
## Testing Strategy
Describe how this will be tested.
## Timeline
| Phase | Duration | Deliverables |
|-------|----------|-------------|
| Phase 1 | 1 week | Core implementation |
+71
View File
@@ -0,0 +1,71 @@
# Tutorial: [Topic Name]
**Date:** {{DATE}}
**Difficulty:** Beginner / Intermediate / Advanced
**Time:** ~30 minutes
## Prerequisites
- Prerequisite 1
- Prerequisite 2
## What You Will Learn
- Learning objective 1
- Learning objective 2
## Step 1: Getting Started
Description of the first step.
```bash
# Example command
echo "Hello, World!"
```
## Step 2: Core Concepts
Explain the main concepts here.
### Key Concept A
Details about concept A.
### Key Concept B
Details about concept B.
## Step 3: Building the Feature
Walk through the implementation.
```javascript
// Example code
function example() {
return 'Hello';
}
```
## Step 4: Testing
How to verify everything works.
## Common Issues
### Issue 1
**Problem:** Description of the problem.
**Solution:** How to fix it.
### Issue 2
**Problem:** Description of the problem.
**Solution:** How to fix it.
## Next Steps
- Suggested follow-up 1
- Suggested follow-up 2
## Resources
- [Resource 1](https://example.com)
- [Resource 2](https://example.com)
+246
View File
@@ -0,0 +1,246 @@
/**
* ModalManager - Unified modal system with accessibility support
* @version 4.0.0
*/
class ModalManager {
#modal;
#backdrop;
#options;
#lastFocusedElement;
#focusableElements;
#eventListeners;
#isOpen;
static #openModals = [];
constructor(element, options = {}) {
this.#modal = typeof element === 'string' ? document.querySelector(element) : element;
this.#options = {
closeOnBackdrop: true,
closeOnEscape: true,
focusFirst: true,
onOpen: null,
onClose: null,
...options
};
this.#isOpen = false;
this.#eventListeners = [];
this.#init();
}
#init() {
// Ensure modal has required attributes
if (!this.#modal.hasAttribute('role')) {
this.#modal.setAttribute('role', 'dialog');
}
if (!this.#modal.hasAttribute('aria-modal')) {
this.#modal.setAttribute('aria-modal', 'true');
}
// Find or create backdrop
this.#backdrop = this.#modal.querySelector('.modal-backdrop');
// Setup close triggers
this.#setupCloseTriggers();
}
#setupCloseTriggers() {
// Close button
const closeBtn = this.#modal.querySelector('.modal-close');
if (closeBtn) {
const handler = (e) => {
e.preventDefault();
this.close();
};
closeBtn.addEventListener('click', handler);
this.#eventListeners.push({ el: closeBtn, type: 'click', handler });
}
// Elements with data-close attribute
const closeTriggers = this.#modal.querySelectorAll('[data-close]');
closeTriggers.forEach(el => {
if (el.classList.contains('modal-backdrop') && !this.#options.closeOnBackdrop) {
return;
}
const handler = (e) => {
e.preventDefault();
this.close();
};
el.addEventListener('click', handler);
this.#eventListeners.push({ el, type: 'click', handler });
});
}
#getFocusableElements() {
const selector = [
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'a[href]',
'[tabindex]:not([tabindex="-1"])'
].join(', ');
return Array.from(this.#modal.querySelectorAll(selector))
.filter(el => el.offsetParent !== null && !el.classList.contains('modal-backdrop'));
}
#trapFocus(e) {
if (e.key !== 'Tab') return;
const focusable = this.#getFocusableElements();
if (focusable.length === 0) return;
const firstEl = focusable[0];
const lastEl = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === firstEl) {
e.preventDefault();
lastEl.focus();
}
} else {
if (document.activeElement === lastEl) {
e.preventDefault();
firstEl.focus();
}
}
}
#handleKeydown(e) {
if (e.key === 'Escape' && this.#options.closeOnEscape) {
e.preventDefault();
this.close();
}
this.#trapFocus(e);
}
open() {
if (this.#isOpen) return;
// Store last focused element
this.#lastFocusedElement = document.activeElement;
// Track open modals
ModalManager.#openModals.push(this);
// Show modal: remove hidden first, force a reflow so the browser
// records opacity:0 as the start state, then add 'open' to trigger
// the CSS transition. Without the reflow, both class changes are
// batched into one style recalculation and the transition is skipped.
this.#modal.classList.remove('hidden');
void this.#modal.offsetHeight; // Force reflow — do not remove
this.#modal.classList.add('open');
this.#isOpen = true;
// Prevent body scroll
document.body.style.overflow = 'hidden';
// Add keyboard listener
const keydownHandler = (e) => this.#handleKeydown(e);
document.addEventListener('keydown', keydownHandler);
this.#eventListeners.push({ el: document, type: 'keydown', handler: keydownHandler });
// Focus first element
if (this.#options.focusFirst) {
requestAnimationFrame(() => {
const focusable = this.#getFocusableElements();
if (focusable.length > 0) {
focusable[0].focus();
}
});
}
// Callback
if (this.#options.onOpen) {
this.#options.onOpen(this);
}
// Dispatch custom event
this.#modal.dispatchEvent(new CustomEvent('modal:open'));
}
close() {
if (!this.#isOpen) return;
// Remove from open modals
const index = ModalManager.#openModals.indexOf(this);
if (index > -1) {
ModalManager.#openModals.splice(index, 1);
}
// Start hide transition
this.#modal.classList.remove('open');
this.#isOpen = false;
// Re-add 'hidden' after the CSS transition completes so the modal
// is fully removed from rendering (display:none), not just invisible.
// We use both transitionend and a setTimeout fallback because
// transitionend never fires when prefers-reduced-motion disables transitions.
let hidden = false;
const addHidden = () => {
if (hidden || this.#isOpen) return;
hidden = true;
this.#modal.removeEventListener('transitionend', onTransitionEnd);
this.#modal.classList.add('hidden');
};
const onTransitionEnd = (e) => {
if (e.target !== this.#modal) return;
addHidden();
};
this.#modal.addEventListener('transitionend', onTransitionEnd);
setTimeout(addHidden, 250); // fallback: slightly longer than 200ms transition
// Restore body scroll if no modals open
if (ModalManager.#openModals.length === 0) {
document.body.style.overflow = '';
}
// Remove keyboard listener
const keydownListener = this.#eventListeners.find(
l => l.el === document && l.type === 'keydown'
);
if (keydownListener) {
document.removeEventListener('keydown', keydownListener.handler);
this.#eventListeners = this.#eventListeners.filter(l => l !== keydownListener);
}
// Restore focus
if (this.#lastFocusedElement && typeof this.#lastFocusedElement.focus === 'function') {
this.#lastFocusedElement.focus();
}
// Callback
if (this.#options.onClose) {
this.#options.onClose(this);
}
// Dispatch custom event
this.#modal.dispatchEvent(new CustomEvent('modal:close'));
}
isOpen() {
return this.#isOpen;
}
destroy() {
// Close if open
if (this.#isOpen) {
this.close();
}
// Remove all event listeners
this.#eventListeners.forEach(({ el, type, handler }) => {
el.removeEventListener(type, handler);
});
this.#eventListeners = [];
}
}
// Export for use in renderer
if (typeof window !== 'undefined') {
window.ModalManager = ModalManager;
}
// CommonJS export
module.exports = { ModalManager };
+78
View File
@@ -0,0 +1,78 @@
function createWelcomeContent(recentFiles = []) {
const recentHtml = recentFiles.length
? recentFiles.map(f => {
const name = f.split(/[/\\]/).pop();
return `<div class="welcome-recent-item" data-path="${f}"><span class="welcome-recent-name">${name}</span><span class="welcome-recent-path">${f}</span></div>`;
}).join('')
: '<p class="welcome-muted">No recent files</p>';
return `
<div class="welcome-container">
<div class="welcome-hero">
<h1 class="welcome-title">MarkdownConverter</h1>
<p class="welcome-version">Version 4.0.0</p>
<p class="welcome-subtitle">Professional Markdown Editor & Universal Document Converter</p>
</div>
<div class="welcome-grid">
<div class="welcome-section">
<h2>Quick Start</h2>
<div class="welcome-cards">
<div class="welcome-card" data-action="new-file">
<div class="welcome-card-icon">+</div>
<h3>New Document</h3>
<p>Create a blank document</p>
<kbd>Ctrl+N</kbd>
</div>
<div class="welcome-card" data-action="open-file">
<div class="welcome-card-icon">&#128194;</div>
<h3>Open File</h3>
<p>Open an existing file</p>
<kbd>Ctrl+O</kbd>
</div>
<div class="welcome-card" data-action="open-template">
<div class="welcome-card-icon">&#128203;</div>
<h3>From Template</h3>
<p>Start from a template</p>
</div>
<div class="welcome-card" data-action="command-palette">
<div class="welcome-card-icon">&#8984;</div>
<h3>Command Palette</h3>
<p>Search all actions</p>
<kbd>Ctrl+Shift+P</kbd>
</div>
</div>
</div>
<div class="welcome-section">
<h2>What's New in v4.0.0</h2>
<ul class="welcome-features">
<li><strong>CodeMirror Editor</strong> Syntax highlighting, code folding, multiple cursors</li>
<li><strong>Sidebar Panels</strong> File Explorer, Git, Snippets, Templates</li>
<li><strong>Command Palette</strong> Quick access to all actions</li>
<li><strong>Code Execution</strong> Run JS, Python, Bash from code blocks</li>
<li><strong>Print Preview</strong> Full print customization dialog</li>
<li><strong>New Formats</strong> Reveal.js, YAML, JSON, Confluence, and more</li>
<li><strong>Spell Checking</strong> System dictionary with suggestions</li>
<li><strong>Markdown Extensions</strong> Footnotes, admonitions, TOC</li>
<li><strong>Image Handling</strong> Paste and drag-drop images</li>
<li><strong>PlantUML</strong> Diagram rendering in preview</li>
</ul>
</div>
<div class="welcome-section">
<h2>Recent Files</h2>
<div class="welcome-recent">${recentHtml}</div>
</div>
</div>
<div class="welcome-footer">
<label class="welcome-checkbox">
<input type="checkbox" id="show-welcome-startup" checked>
Show this tab on startup
</label>
</div>
</div>`;
}
module.exports = { createWelcomeContent };
File diff suppressed because it is too large Load Diff
+12 -12
View File
@@ -1,12 +1,12 @@
# Test Double-Click File Opening # Test Double-Click File Opening
This is a test file to verify double-click functionality. This is a test file to verify double-click functionality.
## Features to Test ## Features to Test
- File should load automatically - File should load automatically
- Content should display in editor - Content should display in editor
- Tab should show filename - Tab should show filename
- Preview should render markdown - Preview should render markdown
**This text should be bold** **This text should be bold**
*This text should be italic* *This text should be italic*
+48 -48
View File
@@ -1,49 +1,49 @@
// Test script to verify export functionality // Test script to verify export functionality
const { exec } = require('child_process'); const { exec } = require('child_process');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
console.log('Testing export functionality...'); console.log('Testing export functionality...');
// Test 1: Check if pandoc is available // Test 1: Check if pandoc is available
console.log('\n1. Checking Pandoc availability...'); console.log('\n1. Checking Pandoc availability...');
exec('pandoc --version', (error, stdout, stderr) => { exec('pandoc --version', (error, stdout, stderr) => {
if (error) { if (error) {
console.log('❌ Pandoc not available:', error.message); console.log('❌ Pandoc not available:', error.message);
console.log('✅ Built-in HTML and PDF export should work'); console.log('✅ Built-in HTML and PDF export should work');
} else { } else {
console.log('✅ Pandoc is available'); console.log('✅ Pandoc is available');
console.log(' Version info:', stdout.split('\n')[0]); console.log(' Version info:', stdout.split('\n')[0]);
} }
}); });
// Test 2: Check if test markdown file exists // Test 2: Check if test markdown file exists
console.log('\n2. Checking test file...'); console.log('\n2. Checking test file...');
const testFile = path.join(__dirname, 'test-export.md'); const testFile = path.join(__dirname, 'test-export.md');
if (fs.existsSync(testFile)) { if (fs.existsSync(testFile)) {
console.log('✅ Test markdown file exists:', testFile); console.log('✅ Test markdown file exists:', testFile);
const content = fs.readFileSync(testFile, 'utf8'); const content = fs.readFileSync(testFile, 'utf8');
console.log(' File size:', content.length, 'characters'); console.log(' File size:', content.length, 'characters');
} else { } else {
console.log('❌ Test markdown file not found'); console.log('❌ Test markdown file not found');
} }
// Test 3: Check marked library // Test 3: Check marked library
console.log('\n3. Testing marked library...'); console.log('\n3. Testing marked library...');
try { try {
const marked = require('marked'); const marked = require('marked');
const testMarkdown = '# Test\nThis is a **test** markdown.'; const testMarkdown = '# Test\nThis is a **test** markdown.';
const html = marked.parse(testMarkdown); const html = marked.parse(testMarkdown);
console.log('✅ Marked library working'); console.log('✅ Marked library working');
console.log(' Sample output:', html.substring(0, 50) + '...'); console.log(' Sample output:', html.substring(0, 50) + '...');
} catch (error) { } catch (error) {
console.log('❌ Marked library error:', error.message); console.log('❌ Marked library error:', error.message);
} }
console.log('\n✅ Export functionality test completed!'); console.log('\n✅ Export functionality test completed!');
console.log('\nHow to test exports:'); console.log('\nHow to test exports:');
console.log('1. Open the application'); console.log('1. Open the application');
console.log('2. Open test-export.md file'); console.log('2. Open test-export.md file');
console.log('3. Try exporting to HTML (should work without Pandoc)'); console.log('3. Try exporting to HTML (should work without Pandoc)');
console.log('4. Try exporting to PDF (should work without Pandoc)'); console.log('4. Try exporting to PDF (should work without Pandoc)');
console.log('5. Try exporting to DOCX (requires Pandoc)'); console.log('5. Try exporting to DOCX (requires Pandoc)');
+25 -25
View File
@@ -1,26 +1,26 @@
# Test Document # Test Document
This is a test markdown document for export testing. This is a test markdown document for export testing.
## Features ## Features
- **Bold text** - **Bold text**
- *Italic text* - *Italic text*
- [Links](https://example.com) - [Links](https://example.com)
## Code Example ## Code Example
```javascript ```javascript
function hello() { function hello() {
console.log("Hello World!"); console.log("Hello World!");
} }
``` ```
## Table ## Table
| Column 1 | Column 2 | Column 3 | | Column 1 | Column 2 | Column 3 |
|----------|----------|----------| |----------|----------|----------|
| Value 1 | Value 2 | Value 3 | | Value 1 | Value 2 | Value 3 |
| Value 4 | Value 5 | Value 6 | | Value 4 | Value 5 | Value 6 |
This is a test document to verify export functionality. This is a test document to verify export functionality.
+14 -14
View File
@@ -1,14 +1,14 @@
# Test File Opening # Test File Opening
This is a test file to verify that double-click file opening works correctly. This is a test file to verify that double-click file opening works correctly.
## Features ## Features
- **Bold text** - **Bold text**
- *Italic text* - *Italic text*
- `Code` - `Code`
```javascript ```javascript
console.log("Hello World"); console.log("Hello World");
``` ```
This should appear when you double-click to open the file! This should appear when you double-click to open the file!
+22 -22
View File
@@ -1,23 +1,23 @@
# Test Document # Test Document
This is a **test** markdown document. This is a **test** markdown document.
## Features ## Features
- Item 1 - Item 1
- Item 2 - Item 2
- Item 3 - Item 3
### Code Example ### Code Example
```javascript ```javascript
console.log("Hello World"); console.log("Hello World");
``` ```
> Tqweqweqweqweqweqweqeweqweqweqwe > Tqweqweqweqweqweqweqeweqweqweqwe
dfe dfe
qwe qwe
qwe qwe
qwe qwe
qwe qwe
+144
View File
@@ -0,0 +1,144 @@
/**
* @jest-environment jsdom
*/
/**
* Tests for CommandPalette
* Tests command registration, filtering, execution, and keyboard navigation
*/
describe('CommandPalette', () => {
let CommandPalette;
beforeEach(() => {
document.body.innerHTML = `
<div class="command-palette-overlay hidden" id="command-palette-overlay">
<div class="command-palette">
<input type="text" id="command-palette-input">
<div id="command-palette-results"></div>
</div>
</div>
`;
CommandPalette = require('../src/command-palette').CommandPalette;
});
test('starts hidden', () => {
const palette = new CommandPalette();
expect(palette.isOpen()).toBe(false);
});
test('opens and focuses input', () => {
const palette = new CommandPalette();
palette.open();
expect(palette.isOpen()).toBe(true);
});
test('closes', () => {
const palette = new CommandPalette();
palette.open();
palette.close();
expect(palette.isOpen()).toBe(false);
});
test('registers and renders commands', () => {
const palette = new CommandPalette();
palette.register('Test Command', 'Ctrl+T', () => {});
palette.register('Another Command', '', () => {});
palette.open();
const items = document.querySelectorAll('.command-item');
expect(items.length).toBe(2);
});
test('filters commands by search', () => {
const palette = new CommandPalette();
palette.register('Save File', 'Ctrl+S', () => {});
palette.register('Open File', 'Ctrl+O', () => {});
palette.register('Bold Text', 'Ctrl+B', () => {});
palette.renderResults('file');
const items = document.querySelectorAll('.command-item');
expect(items.length).toBe(2);
});
test('executes command', () => {
const palette = new CommandPalette();
const action = jest.fn();
palette.register('Test', '', action);
palette.open();
palette.executeSelected();
expect(action).toHaveBeenCalled();
});
test('highlights matching text', () => {
const palette = new CommandPalette();
const result = palette.highlightMatch('Save File', 'save');
expect(result).toContain('<strong>');
expect(result).toContain('Save');
});
test('highlightMatch returns original text when no query', () => {
const palette = new CommandPalette();
const result = palette.highlightMatch('Save File', '');
expect(result).toBe('Save File');
});
test('filters case-insensitively', () => {
const palette = new CommandPalette();
palette.register('Save File', '', () => {});
palette.register('Open File', '', () => {});
palette.renderResults('SAVE');
const items = document.querySelectorAll('.command-item');
expect(items.length).toBe(1);
});
test('shows all commands when query is empty', () => {
const palette = new CommandPalette();
palette.register('Cmd1', '', () => {});
palette.register('Cmd2', '', () => {});
palette.register('Cmd3', '', () => {});
palette.renderResults('');
const items = document.querySelectorAll('.command-item');
expect(items.length).toBe(3);
});
test('displays shortcut when provided', () => {
const palette = new CommandPalette();
palette.register('Save File', 'Ctrl+S', () => {});
palette.open();
const shortcut = document.querySelector('.command-shortcut');
expect(shortcut).not.toBeNull();
expect(shortcut.textContent).toBe('Ctrl+S');
});
test('does not display shortcut when empty', () => {
const palette = new CommandPalette();
palette.register('Test Command', '', () => {});
palette.open();
const shortcut = document.querySelector('.command-shortcut');
expect(shortcut).toBeNull();
});
test('closes on overlay click', () => {
const palette = new CommandPalette();
palette.open();
// Simulate click on the overlay itself
const event = new Event('click', { bubbles: true });
Object.defineProperty(event, 'target', { value: palette.overlay });
palette.overlay.dispatchEvent(event);
expect(palette.isOpen()).toBe(false);
});
test('executeSelected does nothing when no commands', () => {
const palette = new CommandPalette();
palette.open();
// Should not throw
expect(() => palette.executeSelected()).not.toThrow();
});
test('closes after executing command', () => {
const palette = new CommandPalette();
palette.register('Test', '', jest.fn());
palette.open();
palette.executeSelected();
expect(palette.isOpen()).toBe(false);
});
});
+100
View File
@@ -0,0 +1,100 @@
/**
* Tests for Main Process Utilities
* Tests sanitization, rate limiting, and other main process helpers
*/
describe('sanitizeErrorMessage', () => {
const sanitizeErrorMessage = (message) => {
if (typeof message !== 'string') return String(message);
return message
.replace(/[A-Z]:\\[^\s"']+\\([^\s"'\\]+)/gi, '$1')
.replace(/\/[^\s"']+\/([^\s"'/]+)/g, '$1');
};
test('strips Windows absolute paths', () => {
expect(sanitizeErrorMessage('Error in C:\\Users\\test\\file.js'))
.toBe('Error in file.js');
});
test('strips Unix absolute paths', () => {
expect(sanitizeErrorMessage('Error in /home/user/project/file.js'))
.toBe('Error in file.js');
});
test('handles non-string input', () => {
expect(sanitizeErrorMessage(42)).toBe('42');
expect(sanitizeErrorMessage(null)).toBe('null');
});
test('preserves messages without paths', () => {
expect(sanitizeErrorMessage('Something went wrong'))
.toBe('Something went wrong');
});
test('strips nested Windows paths', () => {
expect(sanitizeErrorMessage('Cannot read C:\\Users\\admin\\AppData\\Local\\config.json'))
.toBe('Cannot read config.json');
});
test('strips nested Unix paths', () => {
expect(sanitizeErrorMessage('File not found: /var/log/app/error.log'))
.toBe('File not found: error.log');
});
test('handles undefined input', () => {
expect(sanitizeErrorMessage(undefined)).toBe('undefined');
});
});
describe('createRateLimiter', () => {
const createRateLimiter = (minIntervalMs = 2000) => {
let lastCall = 0;
return function canProceed() {
const now = Date.now();
if (now - lastCall < minIntervalMs) return false;
lastCall = now;
return true;
};
};
test('allows first call', () => {
const limiter = createRateLimiter(1000);
expect(limiter()).toBe(true);
});
test('blocks rapid calls', () => {
const limiter = createRateLimiter(1000);
limiter(); // first call
expect(limiter()).toBe(false); // too soon
});
test('allows call after interval', () => {
jest.useFakeTimers();
const limiter = createRateLimiter(1000);
limiter();
jest.advanceTimersByTime(1001);
expect(limiter()).toBe(true);
jest.useRealTimers();
});
test('uses default interval of 2000ms', () => {
jest.useFakeTimers();
const limiter = createRateLimiter();
limiter();
jest.advanceTimersByTime(1999);
expect(limiter()).toBe(false);
jest.advanceTimersByTime(2);
expect(limiter()).toBe(true);
jest.useRealTimers();
});
test('resets after successful call', () => {
jest.useFakeTimers();
const limiter = createRateLimiter(500);
limiter();
jest.advanceTimersByTime(501);
limiter(); // resets the timer
expect(limiter()).toBe(false); // too soon after second call
jest.useRealTimers();
});
});
+130
View File
@@ -0,0 +1,130 @@
/**
* Tests for Markdown Extensions
* Tests TOC generation, admonition parsing, and PlantUML encoding
*/
describe('Markdown Extensions', () => {
describe('TOC generation from headings', () => {
test('extracts all heading levels', () => {
const html = '<h1>Title</h1><h2>Section 1</h2><h2>Section 2</h2><h3>Subsection</h3>';
const headingRegex = /<h([1-6])[^>]*>(.*?)<\/h[1-6]>/gi;
const toc = [];
let match;
while ((match = headingRegex.exec(html)) !== null) {
toc.push({ level: parseInt(match[1]), text: match[2] });
}
expect(toc).toHaveLength(4);
expect(toc[0]).toEqual({ level: 1, text: 'Title' });
expect(toc[3]).toEqual({ level: 3, text: 'Subsection' });
});
test('handles empty HTML', () => {
const html = '<p>No headings here</p>';
const headingRegex = /<h([1-6])[^>]*>(.*?)<\/h[1-6]>/gi;
const toc = [];
let match;
while ((match = headingRegex.exec(html)) !== null) {
toc.push({ level: parseInt(match[1]), text: match[2] });
}
expect(toc).toHaveLength(0);
});
test('handles headings with attributes', () => {
const html = '<h1 id="title" class="main">Title</h1><h2 id="sec">Section</h2>';
const headingRegex = /<h([1-6])[^>]*>(.*?)<\/h[1-6]>/gi;
const toc = [];
let match;
while ((match = headingRegex.exec(html)) !== null) {
toc.push({ level: parseInt(match[1]), text: match[2] });
}
expect(toc).toHaveLength(2);
expect(toc[0].text).toBe('Title');
});
});
describe('Admonition regex matching', () => {
test('matches note admonition', () => {
const src = ':::note\nThis is a note.\n:::\n';
const match = src.match(/^:::(note|warning|tip|danger|info)\s*\n([\s\S]*?)^:::\s*$/m);
expect(match).not.toBeNull();
expect(match[1]).toBe('note');
expect(match[2].trim()).toBe('This is a note.');
});
test('matches all admonition types', () => {
const types = ['note', 'warning', 'tip', 'danger', 'info'];
types.forEach(type => {
const src = `:::${type}\nContent\n:::\n`;
const match = src.match(/^:::(note|warning|tip|danger|info)\s*\n([\s\S]*?)^:::\s*$/m);
expect(match).not.toBeNull();
expect(match[1]).toBe(type);
});
});
test('does not match invalid admonition type', () => {
const src = ':::custom\nContent\n:::\n';
const match = src.match(/^:::(note|warning|tip|danger|info)\s*\n([\s\S]*?)^:::\s*$/m);
expect(match).toBeNull();
});
test('captures multiline content', () => {
const src = ':::warning\nLine 1\nLine 2\nLine 3\n:::\n';
const match = src.match(/^:::(note|warning|tip|danger|info)\s*\n([\s\S]*?)^:::\s*$/m);
expect(match).not.toBeNull();
expect(match[2]).toContain('Line 1');
expect(match[2]).toContain('Line 3');
});
});
describe('PlantUML hex encoding', () => {
const plantumlEncode = (text) => {
const hex = Array.from(Buffer.from(text, 'utf-8'))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
return '~h' + hex;
};
test('encodes simple text', () => {
const encoded = plantumlEncode('A -> B');
expect(encoded).toBe('~h41202d3e2042');
});
test('encodes empty string', () => {
expect(plantumlEncode('')).toBe('~h');
});
test('encodes special characters', () => {
const encoded = plantumlEncode('@startuml');
expect(encoded).toMatch(/^~h[0-9a-f]+$/);
// '@' is 0x40, 's' is 0x73
expect(encoded.startsWith('~h40')).toBe(true);
});
});
describe('Slug generation for TOC anchors', () => {
const slugify = (text) => {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
};
test('converts heading to slug', () => {
expect(slugify('Hello World')).toBe('hello-world');
});
test('removes special characters', () => {
expect(slugify('What is C++?')).toBe('what-is-c');
});
test('collapses multiple dashes', () => {
expect(slugify('Hello World')).toBe('hello-world');
});
test('handles already lowercase text', () => {
expect(slugify('simple')).toBe('simple');
});
});
});
+280
View File
@@ -0,0 +1,280 @@
/**
* Tests for ModalManager
* Covers the three bugs fixed in modal refactor:
* 1. open() animation: reflow between hidden removal and open class add
* 2. close() cleanup: 'hidden' class restored after transition
* 3. State management: isOpen() accuracy
*/
const { ModalManager } = require('../src/utils/ModalManager');
function createModalElement(id = 'test-modal') {
const modal = document.createElement('div');
modal.id = id;
modal.className = 'modal hidden';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
backdrop.setAttribute('data-close', '');
const content = document.createElement('div');
content.className = 'modal-content';
const header = document.createElement('div');
header.className = 'modal-header';
const closeBtn = document.createElement('button');
closeBtn.className = 'modal-close';
closeBtn.setAttribute('aria-label', 'Close');
const body = document.createElement('div');
body.className = 'modal-body';
const input = document.createElement('input');
input.type = 'text';
body.appendChild(input);
header.appendChild(closeBtn);
content.appendChild(header);
content.appendChild(body);
modal.appendChild(backdrop);
modal.appendChild(content);
document.body.appendChild(modal);
return modal;
}
describe('ModalManager', () => {
let modal;
let manager;
beforeEach(() => {
modal = createModalElement();
manager = new ModalManager(modal);
});
afterEach(() => {
manager.destroy();
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.style.overflow = '';
});
// =========================================================
// open()
// =========================================================
describe('open()', () => {
test('removes hidden class and adds open class', () => {
expect(modal.classList.contains('hidden')).toBe(true);
expect(modal.classList.contains('open')).toBe(false);
manager.open();
expect(modal.classList.contains('hidden')).toBe(false);
expect(modal.classList.contains('open')).toBe(true);
});
test('sets isOpen to true', () => {
expect(manager.isOpen()).toBe(false);
manager.open();
expect(manager.isOpen()).toBe(true);
});
test('prevents body scroll', () => {
manager.open();
expect(document.body.style.overflow).toBe('hidden');
});
test('does not open again if already open', () => {
manager.open();
manager.open(); // second call should be no-op
expect(manager.isOpen()).toBe(true);
});
test('calls onOpen callback', () => {
const onOpen = jest.fn();
manager.destroy();
manager = new ModalManager(modal, { onOpen });
manager.open();
expect(onOpen).toHaveBeenCalledTimes(1);
});
test('dispatches modal:open custom event', () => {
const handler = jest.fn();
modal.addEventListener('modal:open', handler);
manager.open();
expect(handler).toHaveBeenCalledTimes(1);
});
});
// =========================================================
// close()
// =========================================================
describe('close()', () => {
beforeEach(() => {
manager.open();
});
test('removes open class', () => {
expect(modal.classList.contains('open')).toBe(true);
manager.close();
expect(modal.classList.contains('open')).toBe(false);
});
test('sets isOpen to false immediately', () => {
manager.close();
expect(manager.isOpen()).toBe(false);
});
test('restores body scroll when no modals remain open', () => {
manager.close();
expect(document.body.style.overflow).toBe('');
});
test('adds hidden class after transitionend event fires', () => {
manager.close();
// Immediately after close(): hidden should NOT yet be added —
// the close animation is still in progress.
// (This is the bug that existed before the fix.)
expect(modal.classList.contains('hidden')).toBe(false);
// Simulate the CSS transition completing
const event = new Event('transitionend');
Object.defineProperty(event, 'target', { value: modal, writable: false });
modal.dispatchEvent(event);
expect(modal.classList.contains('hidden')).toBe(true);
});
test('adds hidden class via 250ms timeout fallback when transitionend never fires', () => {
jest.useFakeTimers();
manager.close();
expect(modal.classList.contains('hidden')).toBe(false);
// Advance past the fallback timeout (250ms)
jest.advanceTimersByTime(300);
expect(modal.classList.contains('hidden')).toBe(true);
jest.useRealTimers();
});
test('does not add hidden class if modal is reopened before timeout fires', () => {
jest.useFakeTimers();
manager.close();
jest.advanceTimersByTime(100); // halfway through timeout
// Re-open the modal before the timeout fires
manager.open();
jest.advanceTimersByTime(200); // past original timeout expiry
// Modal was reopened, so hidden must NOT have been added
expect(modal.classList.contains('hidden')).toBe(false);
expect(modal.classList.contains('open')).toBe(true);
jest.useRealTimers();
});
test('calls onClose callback', () => {
const onClose = jest.fn();
manager.destroy();
manager = new ModalManager(modal, { onClose });
manager.open();
manager.close();
expect(onClose).toHaveBeenCalledTimes(1);
});
test('dispatches modal:close custom event', () => {
const handler = jest.fn();
modal.addEventListener('modal:close', handler);
manager.close();
expect(handler).toHaveBeenCalledTimes(1);
});
test('is a no-op when modal is already closed', () => {
manager.close(); // close from open
const onClose = jest.fn();
manager.destroy();
manager = new ModalManager(modal, { onClose });
manager.close(); // call close on an already-closed modal
expect(onClose).not.toHaveBeenCalled();
});
});
// =========================================================
// Keyboard interaction
// =========================================================
describe('keyboard shortcuts', () => {
test('Escape key closes an open modal', () => {
manager.open();
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
expect(manager.isOpen()).toBe(false);
});
test('Escape key does nothing when modal is already closed', () => {
expect(() => {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
}).not.toThrow();
});
test('closeOnEscape: false prevents Escape from closing', () => {
manager.destroy();
manager = new ModalManager(modal, { closeOnEscape: false });
manager.open();
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
expect(manager.isOpen()).toBe(true);
});
});
// =========================================================
// Close triggers
// =========================================================
describe('close triggers', () => {
test('clicking the × close button closes the modal', () => {
manager.open();
modal.querySelector('.modal-close').click();
expect(manager.isOpen()).toBe(false);
});
test('clicking backdrop (data-close) closes the modal', () => {
manager.open();
modal.querySelector('.modal-backdrop').click();
expect(manager.isOpen()).toBe(false);
});
test('closeOnBackdrop: false prevents backdrop from closing', () => {
manager.destroy();
manager = new ModalManager(modal, { closeOnBackdrop: false });
manager.open();
modal.querySelector('.modal-backdrop').click();
expect(manager.isOpen()).toBe(true);
});
});
// =========================================================
// destroy()
// =========================================================
describe('destroy()', () => {
test('closes modal if open', () => {
manager.open();
manager.destroy();
expect(manager.isOpen()).toBe(false);
});
test('does not throw when destroying a closed modal', () => {
expect(() => manager.destroy()).not.toThrow();
});
});
});
+175 -121
View File
@@ -1,121 +1,175 @@
/** /**
* Tests for Preload Script Security * Tests for Preload Script Security
* Verifies that the IPC bridge is properly configured * Verifies that the IPC bridge is properly configured
*/ */
describe('Preload Security', () => { describe('Preload Security', () => {
describe('Allowed Channels', () => { describe('Allowed Channels', () => {
const EXPECTED_SEND_CHANNELS = [ const EXPECTED_SEND_CHANNELS = [
'save-file', 'save-file',
'save-current-file', 'save-current-file',
'set-current-file', 'set-current-file',
'save-recent-files', 'save-recent-files',
'clear-recent-files', 'clear-recent-files',
'renderer-ready', 'renderer-ready',
'get-theme', 'get-theme',
'do-print', 'do-print',
'export-with-options', 'do-print-with-options',
'export-spreadsheet', 'export-with-options',
'batch-convert', 'export-spreadsheet',
'select-folder', 'batch-convert',
'universal-convert', 'select-folder',
'universal-convert-batch', 'universal-convert',
'get-header-footer-settings', 'universal-convert-batch',
'save-header-footer-settings', 'image-convert',
'browse-header-footer-logo', 'image-batch-convert',
'save-header-footer-logo', 'image-resize',
'clear-header-footer-logo', 'image-compress',
'get-page-settings', 'image-rotate',
'update-page-settings', 'audio-convert',
'set-custom-start-page', 'audio-batch-convert',
'process-pdf-operation', 'audio-extract',
'get-pdf-page-count', 'audio-trim',
'select-pdf-folder' 'audio-merge',
]; 'video-convert',
'video-batch-convert',
const EXPECTED_RECEIVE_CHANNELS = [ 'video-compress',
'file-new', 'video-trim',
'file-opened', 'video-frames',
'file-save', 'video-gif',
'get-content-for-save', 'get-header-footer-settings',
'get-content-for-spreadsheet', 'save-header-footer-settings',
'recent-files-cleared', 'browse-header-footer-logo',
'toggle-preview', 'save-header-footer-logo',
'toggle-find', 'clear-header-footer-logo',
'theme-changed', 'get-page-settings',
'theme-data', 'update-page-settings',
'undo', 'set-custom-start-page',
'redo', 'process-pdf-operation',
'adjust-font-size', 'get-pdf-page-count',
'print-preview', 'select-pdf-folder',
'print-preview-styled', 'open-ascii-generator',
'show-export-dialog', 'open-table-generator',
'show-batch-dialog', 'insert-generated-content',
'show-universal-converter-dialog', 'save-pasted-image',
'show-table-generator', 'load-template',
'show-pdf-editor-dialog', 'list-directory',
'conversion-status', 'open-file-path',
'conversion-complete', 'git-status',
'batch-progress', 'git-stage',
'folder-selected', 'git-commit',
'pdf-folder-selected', 'git-log',
'header-footer-settings-data', 'git-diff',
'header-footer-logo-selected', 'get-snippets',
'header-footer-logo-saved', 'save-snippet',
'page-settings-data', 'delete-snippet',
'pdf-page-count', 'execute-code',
'pdf-operation-complete', 'show-pdf-editor-from-toolbar',
'pdf-operation-error' 'menu-open',
]; 'export'
];
test('should define all expected send channels', () => {
// This test documents expected channels const EXPECTED_RECEIVE_CHANNELS = [
expect(EXPECTED_SEND_CHANNELS.length).toBeGreaterThan(0); 'file-new',
}); 'file-opened',
'file-save',
test('should define all expected receive channels', () => { 'get-content-for-save',
// This test documents expected channels 'get-content-for-spreadsheet',
expect(EXPECTED_RECEIVE_CHANNELS.length).toBeGreaterThan(0); 'recent-files-cleared',
}); 'toggle-preview',
}); 'toggle-find',
'theme-changed',
describe('electronAPI Interface', () => { 'theme-data',
test('should expose send method', () => { 'undo',
expect(window.electronAPI.send).toBeDefined(); 'redo',
expect(typeof window.electronAPI.send).toBe('function'); 'adjust-font-size',
}); 'print-preview',
'print-preview-styled',
test('should expose on method', () => { 'show-export-dialog',
expect(window.electronAPI.on).toBeDefined(); 'show-batch-dialog',
expect(typeof window.electronAPI.on).toBe('function'); 'show-universal-converter-dialog',
}); 'show-table-generator',
'show-pdf-editor-dialog',
test('should expose once method', () => { 'show-image-converter',
expect(window.electronAPI.once).toBeDefined(); 'show-audio-converter',
expect(typeof window.electronAPI.once).toBe('function'); 'show-video-converter',
}); 'open-pdf-viewer',
'conversion-status',
test('should expose invoke method', () => { 'conversion-complete',
expect(window.electronAPI.invoke).toBeDefined(); 'batch-progress',
expect(typeof window.electronAPI.invoke).toBe('function'); 'image-conversion-complete',
}); 'audio-conversion-complete',
'video-conversion-complete',
test('should expose file convenience methods', () => { 'folder-selected',
expect(window.electronAPI.file).toBeDefined(); 'pdf-folder-selected',
expect(window.electronAPI.file.save).toBeDefined(); 'header-footer-settings-data',
expect(window.electronAPI.file.saveCurrent).toBeDefined(); 'header-footer-logo-selected',
expect(window.electronAPI.file.setCurrent).toBeDefined(); 'header-footer-logo-saved',
}); 'header-footer-logo-cleared',
'page-settings-data',
test('should expose theme convenience methods', () => { 'pdf-page-count',
expect(window.electronAPI.theme).toBeDefined(); 'pdf-operation-complete',
expect(window.electronAPI.theme.get).toBeDefined(); 'pdf-operation-error',
}); 'pdf-operation-progress',
'show-ascii-generator-window',
test('should expose pdf convenience methods', () => { 'show-ascii-generator',
expect(window.electronAPI.pdf).toBeDefined(); 'show-table-generator-window',
expect(window.electronAPI.pdf.processOperation).toBeDefined(); 'open-header-footer-dialog',
expect(window.electronAPI.pdf.getPageCount).toBeDefined(); 'insert-content',
}); 'load-template-menu',
}); 'toggle-command-palette',
}); 'toggle-sidebar-panel',
'toggle-bottom-panel'
];
test('should define all expected send channels', () => {
// This test documents expected channels
expect(EXPECTED_SEND_CHANNELS.length).toBeGreaterThan(0);
});
test('should define all expected receive channels', () => {
// This test documents expected channels
expect(EXPECTED_RECEIVE_CHANNELS.length).toBeGreaterThan(0);
});
});
describe('electronAPI Interface', () => {
test('should expose send method', () => {
expect(window.electronAPI.send).toBeDefined();
expect(typeof window.electronAPI.send).toBe('function');
});
test('should expose on method', () => {
expect(window.electronAPI.on).toBeDefined();
expect(typeof window.electronAPI.on).toBe('function');
});
test('should expose once method', () => {
expect(window.electronAPI.once).toBeDefined();
expect(typeof window.electronAPI.once).toBe('function');
});
test('should expose invoke method', () => {
expect(window.electronAPI.invoke).toBeDefined();
expect(typeof window.electronAPI.invoke).toBe('function');
});
test('should expose file convenience methods', () => {
expect(window.electronAPI.file).toBeDefined();
expect(window.electronAPI.file.save).toBeDefined();
expect(window.electronAPI.file.saveCurrent).toBeDefined();
expect(window.electronAPI.file.setCurrent).toBeDefined();
});
test('should expose theme convenience methods', () => {
expect(window.electronAPI.theme).toBeDefined();
expect(window.electronAPI.theme.get).toBeDefined();
});
test('should expose pdf convenience methods', () => {
expect(window.electronAPI.pdf).toBeDefined();
expect(window.electronAPI.pdf.processOperation).toBeDefined();
expect(window.electronAPI.pdf.getPageCount).toBeDefined();
});
});
});
+109
View File
@@ -0,0 +1,109 @@
/**
* @jest-environment jsdom
*/
/**
* Tests for PrintPreview
* Tests print dialog options, open/close, and preview rendering
*/
describe('PrintPreview', () => {
beforeEach(() => {
// Mock electron require for executePrint
jest.mock('electron', () => ({
ipcRenderer: { send: jest.fn(), invoke: jest.fn() }
}), { virtual: true });
document.body.innerHTML = `
<div class="dialog-overlay hidden" id="print-preview-overlay">
<button id="print-preview-close"></button>
<button id="print-cancel"></button>
<button id="print-execute"></button>
<select id="print-paper-size"><option value="A4">A4</option><option value="Letter">Letter</option></select>
<select id="print-orientation"><option value="portrait">Portrait</option><option value="landscape">Landscape</option></select>
<select id="print-margins"><option value="default">Default</option></select>
<input type="range" id="print-scale" value="100">
<span id="print-scale-value">100%</span>
<input type="checkbox" id="print-headers" checked>
<input type="checkbox" id="print-background" checked>
<select id="print-pages"><option value="all">All</option><option value="custom">Custom</option></select>
<input type="text" id="print-page-range" class="hidden">
<iframe id="print-preview-frame"></iframe>
</div>
`;
});
test('getOptions returns default values', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
const options = preview.getOptions();
expect(options.paperSize).toBe('A4');
expect(options.orientation).toBe('portrait');
expect(options.scale).toBe(100);
expect(options.headers).toBe(true);
expect(options.background).toBe(true);
expect(options.pages).toBe('all');
expect(options.margins).toBe('default');
expect(options.pageRange).toBe('');
});
test('opens and closes', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
preview.open('<p>Test</p>');
expect(document.getElementById('print-preview-overlay').classList.contains('hidden')).toBe(false);
preview.close();
expect(document.getElementById('print-preview-overlay').classList.contains('hidden')).toBe(true);
});
test('updateScaleLabel reflects slider value', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
document.getElementById('print-scale').value = '75';
preview.updateScaleLabel();
expect(document.getElementById('print-scale-value').textContent).toBe('75%');
});
test('close button closes preview', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
preview.open('<p>Test</p>');
document.getElementById('print-preview-close').click();
expect(document.getElementById('print-preview-overlay').classList.contains('hidden')).toBe(true);
});
test('cancel button closes preview', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
preview.open('<p>Test</p>');
document.getElementById('print-cancel').click();
expect(document.getElementById('print-preview-overlay').classList.contains('hidden')).toBe(true);
});
test('getOptions reflects changed values', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
// Change paper size to Letter
const paperSelect = document.getElementById('print-paper-size');
paperSelect.value = 'Letter';
// Change scale
document.getElementById('print-scale').value = '50';
// Uncheck headers
document.getElementById('print-headers').checked = false;
const options = preview.getOptions();
expect(options.paperSize).toBe('Letter');
expect(options.scale).toBe(50);
expect(options.headers).toBe(false);
});
test('stores last content for refresh', () => {
const { PrintPreview } = require('../src/print-preview');
const preview = new PrintPreview();
preview.open('<p>Hello World</p>');
expect(preview._lastContent).toBe('<p>Hello World</p>');
});
});
+100 -100
View File
@@ -1,100 +1,100 @@
/** /**
* Jest Test Setup * Jest Test Setup
* Provides mocks and utilities for PanConverter tests * Provides mocks and utilities for PanConverter tests
*/ */
// Mock window.electronAPI for renderer tests // Mock window.electronAPI for renderer tests
global.window = global.window || {}; global.window = global.window || {};
global.window.electronAPI = { global.window.electronAPI = {
send: jest.fn(), send: jest.fn(),
on: jest.fn(() => jest.fn()), // Returns cleanup function on: jest.fn(() => jest.fn()), // Returns cleanup function
once: jest.fn(), once: jest.fn(),
invoke: jest.fn(() => Promise.resolve(null)), invoke: jest.fn(() => Promise.resolve(null)),
removeAllListeners: jest.fn(), removeAllListeners: jest.fn(),
file: { file: {
save: jest.fn(), save: jest.fn(),
saveCurrent: jest.fn(), saveCurrent: jest.fn(),
setCurrent: jest.fn(), setCurrent: jest.fn(),
saveRecent: jest.fn(), saveRecent: jest.fn(),
clearRecent: jest.fn(), clearRecent: jest.fn(),
rendererReady: jest.fn() rendererReady: jest.fn()
}, },
theme: { theme: {
get: jest.fn() get: jest.fn()
}, },
print: { print: {
doPrint: jest.fn() doPrint: jest.fn()
}, },
export: { export: {
withOptions: jest.fn(), withOptions: jest.fn(),
spreadsheet: jest.fn() spreadsheet: jest.fn()
}, },
batch: { batch: {
convert: jest.fn(), convert: jest.fn(),
selectFolder: jest.fn() selectFolder: jest.fn()
}, },
converter: { converter: {
convert: jest.fn(), convert: jest.fn(),
convertBatch: jest.fn() convertBatch: jest.fn()
}, },
headerFooter: { headerFooter: {
getSettings: jest.fn(), getSettings: jest.fn(),
saveSettings: jest.fn(), saveSettings: jest.fn(),
browseLogo: jest.fn(), browseLogo: jest.fn(),
saveLogo: jest.fn(), saveLogo: jest.fn(),
clearLogo: jest.fn() clearLogo: jest.fn()
}, },
page: { page: {
getSettings: jest.fn(), getSettings: jest.fn(),
updateSettings: jest.fn(), updateSettings: jest.fn(),
setCustomStartPage: jest.fn() setCustomStartPage: jest.fn()
}, },
pdf: { pdf: {
processOperation: jest.fn(), processOperation: jest.fn(),
getPageCount: jest.fn(), getPageCount: jest.fn(),
selectFolder: jest.fn() selectFolder: jest.fn()
} }
}; };
// Mock marked library // Mock marked library
global.window.marked = { global.window.marked = {
parse: jest.fn((text) => `<p>${text}</p>`), parse: jest.fn((text) => `<p>${text}</p>`),
setOptions: jest.fn() use: jest.fn()
}; };
// Mock DOMPurify // Mock DOMPurify
global.window.DOMPurify = { global.window.DOMPurify = {
sanitize: jest.fn((html) => html) sanitize: jest.fn((html) => html)
}; };
// Mock highlight.js // Mock highlight.js
global.window.hljs = { global.window.hljs = {
highlight: jest.fn((code, options) => ({ value: code })), highlight: jest.fn((code, options) => ({ value: code })),
highlightAuto: jest.fn((code) => ({ value: code })), highlightAuto: jest.fn((code) => ({ value: code })),
getLanguage: jest.fn(() => true) getLanguage: jest.fn(() => true)
}; };
// Mock localStorage // Mock localStorage
const localStorageMock = { const localStorageMock = {
getItem: jest.fn(), getItem: jest.fn(),
setItem: jest.fn(), setItem: jest.fn(),
removeItem: jest.fn(), removeItem: jest.fn(),
clear: jest.fn() clear: jest.fn()
}; };
global.localStorage = localStorageMock; global.localStorage = localStorageMock;
// Console spy to catch unintended console logs in tests // Console spy to catch unintended console logs in tests
const originalConsoleError = console.error; const originalConsoleError = console.error;
console.error = (...args) => { console.error = (...args) => {
// Allow certain expected errors // Allow certain expected errors
const message = args[0]?.toString() || ''; const message = args[0]?.toString() || '';
if (message.includes('Warning:') || message.includes('React')) { if (message.includes('Warning:') || message.includes('React')) {
return; return;
} }
originalConsoleError.apply(console, args); originalConsoleError.apply(console, args);
}; };
// Cleanup after each test // Cleanup after each test
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
+121
View File
@@ -0,0 +1,121 @@
/**
* @jest-environment jsdom
*/
/**
* Tests for SidebarManager
* Tests panel registration, toggling, expand/collapse behavior
*/
describe('SidebarManager', () => {
let SidebarManager;
beforeEach(() => {
document.body.innerHTML = `
<div class="sidebar collapsed" id="sidebar">
<div class="sidebar-icons">
<button class="sidebar-icon" data-panel="test1"></button>
<button class="sidebar-icon" data-panel="test2"></button>
</div>
<div class="sidebar-panel" id="sidebar-panel">
<div class="sidebar-panel-header">
<span class="sidebar-panel-title"></span>
<button class="sidebar-panel-close"></button>
</div>
<div class="sidebar-panel-content" id="sidebar-panel-content"></div>
</div>
</div>
`;
SidebarManager = require('../src/sidebar/sidebar-manager').SidebarManager;
});
test('starts collapsed', () => {
const mgr = new SidebarManager();
expect(document.getElementById('sidebar').classList.contains('collapsed')).toBe(true);
});
test('expands on panel toggle', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: (c) => { c.innerHTML = 'hello'; } });
mgr.togglePanel('test1');
expect(document.getElementById('sidebar').classList.contains('collapsed')).toBe(false);
expect(document.querySelector('.sidebar-panel-title').textContent).toBe('Test 1');
});
test('collapses on second toggle', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: () => {} });
mgr.togglePanel('test1');
mgr.togglePanel('test1');
expect(document.getElementById('sidebar').classList.contains('collapsed')).toBe(true);
});
test('switches panels', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Panel 1', render: (c) => { c.innerHTML = 'one'; } });
mgr.registerPanel('test2', { title: 'Panel 2', render: (c) => { c.innerHTML = 'two'; } });
mgr.togglePanel('test1');
mgr.togglePanel('test2');
expect(document.querySelector('.sidebar-panel-title').textContent).toBe('Panel 2');
expect(document.getElementById('sidebar-panel-content').innerHTML).toBe('two');
});
test('collapse resets active panel', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test', render: () => {} });
mgr.expand('test1');
mgr.collapse();
expect(mgr.activePanel).toBe(null);
});
test('expand sets active icon', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: () => {} });
mgr.expand('test1');
const btn = document.querySelector('[data-panel="test1"]');
expect(btn.classList.contains('active')).toBe(true);
});
test('collapse removes active icon', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: () => {} });
mgr.expand('test1');
mgr.collapse();
const btn = document.querySelector('[data-panel="test1"]');
expect(btn.classList.contains('active')).toBe(false);
});
test('expand with unregistered panel does nothing', () => {
const mgr = new SidebarManager();
mgr.expand('nonexistent');
expect(document.getElementById('sidebar').classList.contains('collapsed')).toBe(true);
expect(mgr.activePanel).toBe(null);
});
test('render function receives panel content element', () => {
const mgr = new SidebarManager();
const renderFn = jest.fn();
mgr.registerPanel('test1', { title: 'Test 1', render: renderFn });
mgr.expand('test1');
expect(renderFn).toHaveBeenCalledWith(document.getElementById('sidebar-panel-content'));
});
test('clicking sidebar icon toggles panel', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: () => {} });
const btn = document.querySelector('[data-panel="test1"]');
btn.click();
expect(mgr.activePanel).toBe('test1');
btn.click();
expect(mgr.activePanel).toBe(null);
});
test('clicking close button collapses sidebar', () => {
const mgr = new SidebarManager();
mgr.registerPanel('test1', { title: 'Test 1', render: () => {} });
mgr.expand('test1');
document.querySelector('.sidebar-panel-close').click();
expect(mgr.activePanel).toBe(null);
expect(document.getElementById('sidebar').classList.contains('collapsed')).toBe(true);
});
});
+137 -137
View File
@@ -1,137 +1,137 @@
/** /**
* Tests for Utility Functions * Tests for Utility Functions
* Tests helper functions that can be extracted and tested * Tests helper functions that can be extracted and tested
*/ */
describe('Utility Functions', () => { describe('Utility Functions', () => {
describe('parseCommand', () => { describe('parseCommand', () => {
// This function parses command strings into command and args // This function parses command strings into command and args
function parseCommand(cmdString) { function parseCommand(cmdString) {
const parts = []; const parts = [];
let current = ''; let current = '';
let inQuotes = false; let inQuotes = false;
let quoteChar = ''; let quoteChar = '';
for (let i = 0; i < cmdString.length; i++) { for (let i = 0; i < cmdString.length; i++) {
const char = cmdString[i]; const char = cmdString[i];
if ((char === '"' || char === "'") && !inQuotes) { if ((char === '"' || char === "'") && !inQuotes) {
inQuotes = true; inQuotes = true;
quoteChar = char; quoteChar = char;
} else if (char === quoteChar && inQuotes) { } else if (char === quoteChar && inQuotes) {
inQuotes = false; inQuotes = false;
quoteChar = ''; quoteChar = '';
} else if (char === ' ' && !inQuotes) { } else if (char === ' ' && !inQuotes) {
if (current) { if (current) {
parts.push(current); parts.push(current);
current = ''; current = '';
} }
} else { } else {
current += char; current += char;
} }
} }
if (current) { if (current) {
parts.push(current); parts.push(current);
} }
return { return {
command: parts[0], command: parts[0],
args: parts.slice(1) args: parts.slice(1)
}; };
} }
test('should parse simple command', () => { test('should parse simple command', () => {
const result = parseCommand('pandoc input.md -o output.pdf'); const result = parseCommand('pandoc input.md -o output.pdf');
expect(result.command).toBe('pandoc'); expect(result.command).toBe('pandoc');
expect(result.args).toEqual(['input.md', '-o', 'output.pdf']); expect(result.args).toEqual(['input.md', '-o', 'output.pdf']);
}); });
test('should handle double-quoted paths', () => { test('should handle double-quoted paths', () => {
const result = parseCommand('pandoc "C:/path with spaces/file.md" -o output.pdf'); const result = parseCommand('pandoc "C:/path with spaces/file.md" -o output.pdf');
expect(result.command).toBe('pandoc'); expect(result.command).toBe('pandoc');
expect(result.args).toEqual(['C:/path with spaces/file.md', '-o', 'output.pdf']); expect(result.args).toEqual(['C:/path with spaces/file.md', '-o', 'output.pdf']);
}); });
test('should handle single-quoted paths', () => { test('should handle single-quoted paths', () => {
const result = parseCommand("pandoc 'file name.md' -o output.pdf"); const result = parseCommand("pandoc 'file name.md' -o output.pdf");
expect(result.command).toBe('pandoc'); expect(result.command).toBe('pandoc');
expect(result.args).toEqual(['file name.md', '-o', 'output.pdf']); expect(result.args).toEqual(['file name.md', '-o', 'output.pdf']);
}); });
test('should handle multiple options', () => { test('should handle multiple options', () => {
const result = parseCommand('pandoc input.md --pdf-engine=xelatex -V geometry:margin=1in -o output.pdf'); const result = parseCommand('pandoc input.md --pdf-engine=xelatex -V geometry:margin=1in -o output.pdf');
expect(result.command).toBe('pandoc'); expect(result.command).toBe('pandoc');
expect(result.args).toContain('--pdf-engine=xelatex'); expect(result.args).toContain('--pdf-engine=xelatex');
expect(result.args).toContain('-V'); expect(result.args).toContain('-V');
}); });
test('should handle empty command', () => { test('should handle empty command', () => {
const result = parseCommand(''); const result = parseCommand('');
expect(result.command).toBeUndefined(); expect(result.command).toBeUndefined();
expect(result.args).toEqual([]); expect(result.args).toEqual([]);
}); });
}); });
describe('hexToRgb', () => { describe('hexToRgb', () => {
// This function converts hex colors to RGB // This function converts hex colors to RGB
function hexToRgb(hex) { function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? { return result ? {
r: parseInt(result[1], 16) / 255, r: parseInt(result[1], 16) / 255,
g: parseInt(result[2], 16) / 255, g: parseInt(result[2], 16) / 255,
b: parseInt(result[3], 16) / 255 b: parseInt(result[3], 16) / 255
} : null; } : null;
} }
test('should convert black hex to RGB', () => { test('should convert black hex to RGB', () => {
const result = hexToRgb('#000000'); const result = hexToRgb('#000000');
expect(result).toEqual({ r: 0, g: 0, b: 0 }); expect(result).toEqual({ r: 0, g: 0, b: 0 });
}); });
test('should convert white hex to RGB', () => { test('should convert white hex to RGB', () => {
const result = hexToRgb('#ffffff'); const result = hexToRgb('#ffffff');
expect(result).toEqual({ r: 1, g: 1, b: 1 }); expect(result).toEqual({ r: 1, g: 1, b: 1 });
}); });
test('should convert red hex to RGB', () => { test('should convert red hex to RGB', () => {
const result = hexToRgb('#ff0000'); const result = hexToRgb('#ff0000');
expect(result.r).toBeCloseTo(1); expect(result.r).toBeCloseTo(1);
expect(result.g).toBeCloseTo(0); expect(result.g).toBeCloseTo(0);
expect(result.b).toBeCloseTo(0); expect(result.b).toBeCloseTo(0);
}); });
test('should handle hex without hash', () => { test('should handle hex without hash', () => {
const result = hexToRgb('00ff00'); const result = hexToRgb('00ff00');
expect(result.r).toBeCloseTo(0); expect(result.r).toBeCloseTo(0);
expect(result.g).toBeCloseTo(1); expect(result.g).toBeCloseTo(1);
expect(result.b).toBeCloseTo(0); expect(result.b).toBeCloseTo(0);
}); });
test('should return null for invalid hex', () => { test('should return null for invalid hex', () => {
expect(hexToRgb('invalid')).toBeNull(); expect(hexToRgb('invalid')).toBeNull();
expect(hexToRgb('#xyz')).toBeNull(); expect(hexToRgb('#xyz')).toBeNull();
}); });
}); });
describe('File Path Utilities', () => { describe('File Path Utilities', () => {
test('should extract file extension', () => { test('should extract file extension', () => {
const getExtension = (filepath) => { const getExtension = (filepath) => {
const match = filepath.match(/\.([^/.]+)$/); const match = filepath.match(/\.([^/.]+)$/);
return match ? match[1].toLowerCase() : ''; return match ? match[1].toLowerCase() : '';
}; };
expect(getExtension('file.md')).toBe('md'); expect(getExtension('file.md')).toBe('md');
expect(getExtension('document.PDF')).toBe('pdf'); expect(getExtension('document.PDF')).toBe('pdf');
expect(getExtension('path/to/file.docx')).toBe('docx'); expect(getExtension('path/to/file.docx')).toBe('docx');
expect(getExtension('noextension')).toBe(''); expect(getExtension('noextension')).toBe('');
}); });
test('should replace file extension', () => { test('should replace file extension', () => {
const replaceExtension = (filepath, newExt) => { const replaceExtension = (filepath, newExt) => {
return filepath.replace(/\.[^/.]+$/, `.${newExt}`); return filepath.replace(/\.[^/.]+$/, `.${newExt}`);
}; };
expect(replaceExtension('file.md', 'pdf')).toBe('file.pdf'); expect(replaceExtension('file.md', 'pdf')).toBe('file.pdf');
expect(replaceExtension('path/to/doc.docx', 'html')).toBe('path/to/doc.html'); expect(replaceExtension('path/to/doc.docx', 'html')).toBe('path/to/doc.html');
}); });
}); });
}); });
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB