Compare commits

..
1 Commits
Author SHA1 Message Date
amitwhandClaude Opus 4.5 16c0e00201 Normalize line endings and remove rpm from Linux build targets
- Normalize line endings across all files
- Remove rpm target from Linux build (requires rpmbuild)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 17:58:55 +05:30
69 changed files with 23253 additions and 26501 deletions
+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.mdcoverage/ agents.md
+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"
} }
+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
+166 -217
View File
@@ -1,217 +1,166 @@
# PanConverter - Updates & Changelog # PanConverter - Updates & Changelog
## Version 4.0.0 (2026-03-04) ## Version 2.1.0 (December 14, 2025)
### Major Changes ### 🎨 UI/UX Improvements
- **CodeMirror 6 Editor** — Replaced textarea with CodeMirror 6 featuring syntax highlighting, code folding, bracket matching, multiple cursors, and auto-indent
- **Sidebar Panel System** — Collapsible sidebar with File Explorer, Git, Snippets, and Templates panels #### Subtle & Small Preview Popout Button
- **Command Palette** — Ctrl+Shift+P to search and execute all app actions - Redesigned popout button with minimalist aesthetic
- **Code Execution (REPL)** — Run JavaScript, Python, and Bash code blocks directly from the preview - Removed border for cleaner appearance
- Reduced size: 11px font, 2px×6px padding (previously 14px font, 4px×8px padding)
### New Features - Added opacity transition: 50% when idle, 100% on hover
- Print Preview dialog with paper size, orientation, margins, scale, and page range controls - Subtle background effect on hover instead of heavy border styling
- Image paste from clipboard and drag-drop support with auto-save to assets folder - **File**: `src/styles.css:195-211`
- Document templates library (10 templates: blog post, meeting notes, tech spec, changelog, README, project plan, API docs, tutorial, release notes, comparison)
- Markdown extensions: footnotes, admonitions (note/warning/tip/danger/info), and [[toc]] table of contents #### Simplified Table Headers in Preview
- PlantUML diagram rendering alongside Mermaid - Removed gradient background from table headers in modern theme
- Welcome tab with onboarding and "What's New" feature showcase - Changed from `var(--primary-gradient)` (purple gradient) to simple light gray (#f0f0f0)
- System spell checking with context menu suggestions and dictionary support - Updated text color to dark (#333333) for better readability
- Enhanced status bar with word count, character count, line/column, encoding, and language mode - Clean, professional appearance matching standard themes
- Grouped toolbar with visual section separators - **File**: `src/styles-modern.css:445-449`
- Breadcrumb bar showing current file path
### 📥 Enhanced Import Capabilities
### New Export/Import Formats
- Reveal.js slides (.html) #### Comprehensive Format-to-Markdown Conversion
- Beamer slides (.pdf) Dramatically expanded the "Import Document" feature to support 30+ file formats:
- Confluence/Jira wiki markup (.txt)
- MOBI e-books (via Calibre) **Supported Formats:**
- Developer formats: JSON, YAML, XML, TOML - **Documents**: DOCX, ODT, RTF, HTML, HTM, TEX, EPUB, PDF, TXT
- **Presentations**: PPTX, ODP
### Security - **Markup Languages**: RST, Textile, MediaWiki, Org-mode, AsciiDoc, TWiki, OPML
- Content Security Policy (CSP) meta tag - **E-book Formats**: EPUB, FB2
- File size validation (50MB limit) - **LaTeX Formats**: TEX, LATEX, LTX
- Error message sanitization (stripped file paths) - **Web Formats**: HTML, HTM, XHTML
- Conversion rate limiting (2-second debounce) - **Wiki Formats**: MediaWiki, DokuWiki, TikiWiki, TWiki
- **Data Formats**: CSV, TSV, JSON
### Dependencies Updated
- marked: 16.x to 17.x (with marked-highlight extension) **Format-Specific Optimizations:**
- pdfjs-dist: 3.x to 5.x (new worker model) - PDF text extraction with XeLaTeX engine
- html2pdf.js: 0.10 to 0.14 - CSV/TSV automatic table conversion
- pdfkit: 0.14 to 0.17 - JSON structure handling
- dompurify, docx, and others updated to latest - Improved error messages with format hints
### Testing **Access**: File → Import Document (Ctrl+I)
- 80 tests across 7 test suites **File**: `src/main.js:1933-1994`
- New tests for sidebar manager, command palette, print preview, markdown extensions, and utility functions
### 🎨 Exhaustive ASCII Art Generator
### Breaking Changes
- Editor is now CodeMirror 6 (replaces textarea) #### 5 New Text Banner Styles
- marked API changed to use marked.use() instead of marked.setOptions() Complete alphabet (A-Z) and numbers (0-9) support for all styles:
- 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 (█ ╔ ╗ ═ ║)
## Version 2.1.0 (December 14, 2025) 4. **Bubble** - Circular bubble letters (Ⓐ Ⓑ Ⓒ)
5. **Digital** - Digital display style (▄ ▀ ▐ ▌)
### 🎨 UI/UX Improvements
**File**: `src/renderer.js:3397-3537`
#### Subtle & Small Preview Popout Button
- Redesigned popout button with minimalist aesthetic #### 19 Professional ASCII Templates
- Removed border for cleaner appearance Organized into 4 categories with expanded options:
- Reduced size: 11px font, 2px×6px padding (previously 14px font, 4px×8px padding)
- Added opacity transition: 50% when idle, 100% on hover **Arrows & Flow (4 templates):**
- Subtle background effect on hover instead of heavy border styling - Arrow Right - Horizontal flow indicators
- **File**: `src/styles.css:195-211` - Arrow Down - Vertical flow indicators
- Decision - Binary decision diagrams
#### Simplified Table Headers in Preview - Process Flow - Multi-step process visualization
- Removed gradient background from table headers in modern theme
- Changed from `var(--primary-gradient)` (purple gradient) to simple light gray (#f0f0f0) **Diagrams & Charts (6 templates):**
- Updated text color to dark (#333333) for better readability - Flowchart - Advanced flowchart with decision branches and loops
- Clean, professional appearance matching standard themes - Sequence - Sequence diagrams for User-System-Database interactions
- **File**: `src/styles-modern.css:445-449` - Network - Server-client network topology
- Hierarchy - Organizational tree structures
### 📥 Enhanced Import Capabilities - Timeline - Milestone visualization with dates
- Table Simple - Basic table template with borders
#### Comprehensive Format-to-Markdown Conversion
Dramatically expanded the "Import Document" feature to support 30+ file formats: **Boxes & Containers (4 templates):**
- Header - Section header with decorative borders
**Supported Formats:** - Note Box - Important notes with rounded corners (┏━━┓)
- **Documents**: DOCX, ODT, RTF, HTML, HTM, TEX, EPUB, PDF, TXT - Warning Box - Warning messages with bold borders (╔═══╗)
- **Presentations**: PPTX, ODP - Info Box - Information boxes with subtle styling (╭───╮)
- **Markup Languages**: RST, Textile, MediaWiki, Org-mode, AsciiDoc, TWiki, OPML
- **E-book Formats**: EPUB, FB2 **Decorative Elements (6 templates):**
- **LaTeX Formats**: TEX, LATEX, LTX - Divider - Horizontal section separator (═══)
- **Web Formats**: HTML, HTM, XHTML - Separator Fancy - Elegant rounded divider
- **Wiki Formats**: MediaWiki, DokuWiki, TikiWiki, TWiki - Brackets - Japanese-style brackets 【 】
- **Data Formats**: CSV, TSV, JSON - Banner Stars - Star-bordered banners
- Checklist - Task lists with ✓ checkmarks
**Format-Specific Optimizations:** - Progress Bar - Visual progress indicators
- PDF text extraction with XeLaTeX engine
- CSV/TSV automatic table conversion **Features:**
- JSON structure handling - All ASCII art automatically wrapped in code blocks for proper rendering
- Improved error messages with format hints - Preserved formatting in markdown preview and all export formats
- Categorized template selection interface
**Access**: File → Import Document (Ctrl+I) - Real-time preview generation
**File**: `src/main.js:1933-1994`
**Access**: Tools → ASCII Art Generator
### 🎨 Exhaustive ASCII Art Generator **Files**: `src/renderer.js:3513-3671`, `src/index.html:427-466`
#### 5 New Text Banner Styles ### 📝 Technical Improvements
Complete alphabet (A-Z) and numbers (0-9) support for all styles:
- Enhanced ASCII art detection in Word template exporter
1. **Standard** - Classic ASCII art with slashes and underscores - Improved monospace font rendering across all export formats
2. **Banner** - Large format using # characters (7-line height) - Better code block preservation in PDF and Word exports
3. **Block** - Modern Unicode block characters (█ ╔ ╗ ═ ║) - Optimized template categorization and organization
4. **Bubble** - Circular bubble letters (Ⓐ Ⓑ Ⓒ)
5. **Digital** - Digital display style (▄ ▀ ▐ ▌) ### 🔧 Files Modified
**File**: `src/renderer.js:3397-3537` - `src/styles.css` - Preview popout button styling
- `src/styles-modern.css` - Table header simplification
#### 19 Professional ASCII Templates - `src/main.js` - Enhanced import function, version update
Organized into 4 categories with expanded options: - `src/renderer.js` - ASCII art generator enhancements
- `src/index.html` - ASCII template UI organization
**Arrows & Flow (4 templates):** - `package.json` - Version bump to 2.1.0
- Arrow Right - Horizontal flow indicators
- Arrow Down - Vertical flow indicators ---
- Decision - Binary decision diagrams
- Process Flow - Multi-step process visualization ## Version 2.0.0 (Previous Release)
**Diagrams & Charts (6 templates):** ### Major Features
- Flowchart - Advanced flowchart with decision branches and loops - Export Profiles - Save and reuse export configurations
- Sequence - Sequence diagrams for User-System-Database interactions - Mermaid.js diagram support
- Network - Server-client network topology - Command Palette (Ctrl+Shift+P)
- Hierarchy - Organizational tree structures - GitHub Light/Dark preview themes
- Timeline - Milestone visualization with dates - Table Generator
- Table Simple - Basic table template with borders - ASCII Art Generator (basic)
- Resizable Preview Pane
**Boxes & Containers (4 templates):** - Pop-out Preview Window
- Header - Section header with decorative borders - Configurable page sizes (A3-A5, B4-B5, Letter, Legal, Tabloid, Custom)
- Note Box - Important notes with rounded corners (┏━━┓) - Custom Headers & Footers for exports
- Warning Box - Warning messages with bold borders (╔═══╗) - Enhanced PDF and Word export with templates
- Info Box - Information boxes with subtle styling (╭───╮) - 22 beautiful themes
**Decorative Elements (6 templates):** ### Core Capabilities
- Divider - Horizontal section separator (═══) - Cross-platform markdown editor with live preview
- Separator Fancy - Elegant rounded divider - Universal document conversion (30+ formats)
- Brackets - Japanese-style brackets 【 】 - PDF Editor (merge, split, compress, rotate, watermark, encrypt)
- Banner Stars - Star-bordered banners - Batch file conversion
- Checklist - Task lists with ✓ checkmarks - File association support
- Progress Bar - Visual progress indicators - Advanced export options
- Multi-tab interface
**Features:**
- All ASCII art automatically wrapped in code blocks for proper rendering ---
- Preserved formatting in markdown preview and all export formats
- Categorized template selection interface ## Installation & Usage
- Real-time preview generation
### Prerequisites
**Access**: Tools → ASCII Art Generator - **Pandoc** - Required for document conversion
**Files**: `src/renderer.js:3513-3671`, `src/index.html:427-466` - **Optional**: LibreOffice, ImageMagick, FFmpeg for universal converter
### 📝 Technical Improvements ### Download
Get the latest release from: https://github.com/amitwh/pan-converter/releases
- Enhanced ASCII art detection in Word template exporter
- Improved monospace font rendering across all export formats ### Supported Platforms
- Better code block preservation in PDF and Word exports - Windows (x64)
- Optimized template categorization and organization - Linux (AppImage, .deb, .snap)
- macOS (planned)
### 🔧 Files Modified
---
- `src/styles.css` - Preview popout button styling
- `src/styles-modern.css` - Table header simplification ## Contributing
- `src/main.js` - Enhanced import function, version update
- `src/renderer.js` - ASCII art generator enhancements Contributions are welcome! Please see [CLAUDE.md](CLAUDE.md) for development guidelines.
- `src/index.html` - ASCII template UI organization
- `package.json` - Version bump to 2.1.0 **Author**: Amit Haridas (amit.wh@gmail.com)
**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
+89 -111
View File
@@ -1,111 +1,89 @@
/** /**
* 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',
prompt: 'readonly', Event: 'readonly',
confirm: 'readonly', CustomEvent: 'readonly',
Event: 'readonly', HTMLElement: 'readonly',
CustomEvent: 'readonly', MutationObserver: 'readonly',
HTMLElement: 'readonly', // Electron
MutationObserver: 'readonly', electronAPI: 'readonly',
TextEncoder: 'readonly', // Libraries
FileReader: 'readonly', marked: 'readonly',
requestAnimationFrame: 'readonly', DOMPurify: 'readonly',
cancelAnimationFrame: 'readonly', hljs: 'readonly',
navigator: 'readonly', mermaid: 'readonly',
location: 'readonly', // Jest
fetch: 'readonly', jest: 'readonly',
URL: 'readonly', describe: 'readonly',
Blob: 'readonly', test: 'readonly',
Image: 'readonly', expect: 'readonly',
DragEvent: 'readonly', beforeEach: 'readonly',
ClipboardEvent: 'readonly', afterEach: 'readonly',
KeyboardEvent: 'readonly', beforeAll: 'readonly',
MouseEvent: 'readonly', afterAll: 'readonly'
NodeList: 'readonly', }
HTMLInputElement: 'readonly', },
HTMLTextAreaElement: 'readonly', rules: {
getComputedStyle: 'readonly', // Error prevention
// Electron 'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
electronAPI: 'readonly', 'no-undef': 'error',
// Libraries 'no-console': 'off', // Allow console for Electron apps
marked: 'readonly',
DOMPurify: 'readonly', // Code quality
hljs: 'readonly', 'eqeqeq': ['warn', 'always'],
mermaid: 'readonly', 'no-var': 'warn',
// Node.js global object 'prefer-const': 'warn',
global: 'writable',
// Jest // Style (handled by Prettier)
jest: 'readonly', 'semi': 'off',
describe: 'readonly', 'quotes': 'off',
test: 'readonly', 'indent': 'off',
expect: 'readonly',
beforeEach: 'readonly', // Async handling
afterEach: 'readonly', 'no-async-promise-executor': 'warn',
beforeAll: 'readonly', 'require-await': 'off',
afterAll: 'readonly'
} // Security
}, 'no-eval': 'error',
rules: { 'no-implied-eval': 'error',
// Error prevention 'no-new-func': 'error'
'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'
}
}
];
+59 -61
View File
@@ -1,61 +1,59 @@
/** /**
* 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
'!src/renderer.js', // Large renderer file with duplicate declarations '!**/node_modules/**'
'!src/preload.js', // Electron preload requires contextBridge ],
'!**/node_modules/**'
], // Coverage thresholds (start low, increase over time)
coverageThreshold: {
// Coverage thresholds (raised with expanded test suite) global: {
coverageThreshold: { branches: 10,
global: { functions: 10,
branches: 10, lines: 10,
functions: 15, statements: 10
lines: 15, }
statements: 15 },
}
}, // Transform settings (no transpilation needed for vanilla JS)
transform: {},
// Transform settings (no transpilation needed for vanilla JS)
transform: {}, // Module paths
moduleDirectories: ['node_modules', 'src'],
// Module paths
moduleDirectories: ['node_modules', 'src'], // Setup files
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'],
// Setup files
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'], // Ignore patterns
testPathIgnorePatterns: [
// Ignore patterns '/node_modules/',
testPathIgnorePatterns: [ '/dist/'
'/node_modules/', ],
'/dist/'
], // Verbose output
verbose: true,
// Verbose output
verbose: true, // Clear mocks between tests
clearMocks: true,
// Clear mocks between tests
clearMocks: true, // Reset modules between tests
resetModules: true
// Reset modules between tests };
resetModules: true
};
+181 -200
View File
@@ -1,200 +1,181 @@
{ {
"name": "markdown-converter", "name": "markdown-converter",
"version": "4.0.0", "version": "3.0.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", "dist": "electron-builder --publish=never",
"dist:all": "electron-builder -mwl", "dist:all": "electron-builder -mwl",
"generate-icons": "node scripts/generate-icons.js" "generate-icons": "node scripts/generate-icons.js"
}, },
"keywords": [ "keywords": [
"markdown", "markdown",
"pandoc", "pandoc",
"converter", "converter",
"editor", "editor",
"pdf", "pdf",
"audio", "audio",
"video", "video",
"image" "image"
], ],
"author": "ConcreteInfo <amit.wh@gmail.com>", "author": "ConcreteInfo <amit.wh@gmail.com>",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/amitwh/markdown-converter" "url": "https://github.com/amitwh/markdown-converter"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.1",
"cross-env": "^10.0.0", "cross-env": "^10.0.0",
"electron": "^37.4.0", "electron": "^37.4.0",
"electron-builder": "^26.0.12", "electron-builder": "^26.0.12",
"eslint": "^9.39.2", "eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4", "eslint-plugin-prettier": "^5.5.4",
"jest": "^30.2.0", "jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0", "jest-environment-jsdom": "^30.2.0",
"prettier": "^3.7.4", "prettier": "^3.7.4",
"sharp": "^0.34.3" "sharp": "^0.34.3"
}, },
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.20.1", "codemirror": "^6.0.2",
"@codemirror/commands": "^6.10.2", "core-util-is": "^1.0.3",
"@codemirror/lang-css": "^6.3.1", "docx": "^9.5.1",
"@codemirror/lang-html": "^6.4.11", "docx4js": "^3.3.0",
"@codemirror/lang-javascript": "^6.2.5", "dompurify": "^3.2.6",
"@codemirror/lang-json": "^6.0.2", "electron-store": "^10.1.0",
"@codemirror/lang-markdown": "^6.5.0", "highlight.js": "^11.11.1",
"@codemirror/lang-python": "^6.2.1", "html2pdf.js": "^0.10.1",
"@codemirror/language": "^6.12.2", "marked": "^16.2.1",
"@codemirror/lint": "^6.9.5", "pdf-lib": "^1.17.1",
"@codemirror/search": "^6.6.0", "pdfjs-dist": "^3.11.174",
"@codemirror/state": "^6.5.4", "pdfkit": "^0.14.0",
"@codemirror/theme-one-dark": "^6.1.3", "pizzip": "^3.2.0",
"@codemirror/view": "^6.39.16", "tslib": "^2.8.1",
"codemirror": "^6.0.2", "xlsx": "^0.18.5"
"core-util-is": "^1.0.3", },
"docx": "^9.6.0", "build": {
"docx4js": "^3.3.0", "appId": "com.concreteinfo.markdownconverter",
"dompurify": "^3.3.1", "productName": "MarkdownConverter",
"electron-store": "^10.1.0", "directories": {
"highlight.js": "^11.11.1", "output": "dist"
"html2pdf.js": "^0.14.0", },
"marked": "^17.0.3", "icon": "assets/icon",
"marked-footnote": "^1.4.0", "files": [
"marked-highlight": "^2.2.3", "src/**/*",
"mermaid": "^11.12.3", "assets/**/*",
"pdf-lib": "^1.17.1", "scripts/**/*",
"pdfjs-dist": "^5.5.207", "node_modules/**/*",
"pdfkit": "^0.17.2", "package.json"
"pizzip": "^3.2.0", ],
"simple-git": "^3.32.3", "fileAssociations": [
"tslib": "^2.8.1", {
"xlsx": "^0.18.5" "ext": "md",
}, "name": "Markdown Document",
"build": { "description": "Markdown Document",
"appId": "com.concreteinfo.markdownconverter", "mimeType": "text/markdown",
"productName": "MarkdownConverter", "role": "Editor"
"directories": { },
"output": "dist" {
}, "ext": "markdown",
"icon": "assets/icon", "name": "Markdown Document",
"files": [ "description": "Markdown Document",
"src/**/*", "mimeType": "text/markdown",
"assets/**/*", "role": "Editor"
"scripts/**/*", },
"node_modules/**/*", {
"package.json" "ext": "pdf",
], "name": "PDF Document",
"fileAssociations": [ "description": "PDF Document",
{ "mimeType": "application/pdf",
"ext": "md", "role": "Editor"
"name": "Markdown Document", }
"description": "Markdown Document", ],
"mimeType": "text/markdown", "mac": {
"role": "Editor" "category": "public.app-category.productivity",
}, "identity": null
{ },
"ext": "markdown", "win": {
"name": "Markdown Document", "target": [
"description": "Markdown Document", {
"mimeType": "text/markdown", "target": "nsis",
"role": "Editor" "arch": [
}, "x64"
{ ]
"ext": "pdf", },
"name": "PDF Document", {
"description": "PDF Document", "target": "portable",
"mimeType": "application/pdf", "arch": [
"role": "Editor" "x64"
} ]
], },
"mac": { {
"category": "public.app-category.productivity", "target": "zip",
"identity": null "arch": [
}, "x64"
"win": { ]
"target": [ }
{ ],
"target": "nsis", "artifactName": "${productName}-${version}-${arch}.${ext}",
"arch": [ "requestedExecutionLevel": "asInvoker",
"x64" "signAndEditExecutable": false
] },
}, "nsis": {
{ "oneClick": false,
"target": "portable", "perMachine": false,
"arch": [ "allowToChangeInstallationDirectory": true,
"x64" "displayLanguageSelector": true,
] "createDesktopShortcut": true,
}, "createStartMenuShortcut": true,
{ "shortcutName": "MarkdownConverter",
"target": "zip", "runAfterFinish": true,
"arch": [ "menuCategory": "Productivity",
"x64" "license": "LICENSE",
] "warningsAsErrors": false,
} "artifactName": "${productName}-Setup-${version}.${ext}",
], "deleteAppDataOnUninstall": false,
"artifactName": "${productName}-${version}-${arch}.${ext}", "differentialPackage": true
"requestedExecutionLevel": "asInvoker", },
"signAndEditExecutable": false "linux": {
}, "target": [
"nsis": { "deb",
"oneClick": false, "AppImage",
"perMachine": false, "snap"
"allowToChangeInstallationDirectory": true, ],
"displayLanguageSelector": true, "category": "Utility",
"createDesktopShortcut": true, "maintainer": "ConcreteInfo <amit.wh@gmail.com>"
"createStartMenuShortcut": true, },
"shortcutName": "MarkdownConverter", "deb": {
"runAfterFinish": true, "depends": [
"menuCategory": "Productivity", "pandoc",
"license": "LICENSE", "ffmpeg",
"warningsAsErrors": false, "imagemagick",
"artifactName": "${productName}-Setup-${version}.${ext}", "libreoffice-common"
"deleteAppDataOnUninstall": false, ],
"differentialPackage": true "description": "Professional Markdown editor and universal file converter",
}, "maintainer": "ConcreteInfo <amit.wh@gmail.com>"
"linux": { },
"target": [ "rpm": {
"deb", "depends": [
"AppImage", "pandoc",
"snap", "ffmpeg",
"rpm" "ImageMagick",
], "libreoffice-core"
"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)"
+601 -601
View File
File diff suppressed because it is too large Load Diff
-109
View File
@@ -1,109 +0,0 @@
class CommandPalette {
constructor() {
this.overlay = document.getElementById('command-palette-overlay');
this.input = document.getElementById('command-palette-input');
this.results = document.getElementById('command-palette-results');
this.commands = [];
this.selectedIndex = 0;
this.filteredCommands = [];
this.setupEventListeners();
}
register(label, shortcut, action) {
this.commands.push({ label, shortcut, action });
}
open() {
this.overlay.classList.remove('hidden');
this.input.value = '';
this.input.focus();
this.selectedIndex = 0;
this.renderResults('');
}
close() {
this.overlay.classList.add('hidden');
}
isOpen() {
return !this.overlay.classList.contains('hidden');
}
setupEventListeners() {
this.input.addEventListener('input', () => {
this.selectedIndex = 0;
this.renderResults(this.input.value);
});
this.overlay.addEventListener('click', (e) => {
if (e.target === this.overlay) this.close();
});
this.input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
this.close();
} else if (e.key === 'Enter') {
e.preventDefault();
this.executeSelected();
} else if (e.key === 'ArrowDown') {
e.preventDefault();
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCommands.length - 1);
this.updateSelection();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
this.updateSelection();
}
});
}
renderResults(query) {
this.filteredCommands = query
? this.commands.filter(cmd => cmd.label.toLowerCase().includes(query.toLowerCase()))
: [...this.commands];
this.results.innerHTML = this.filteredCommands.map((cmd, i) => `
<div class="command-item ${i === this.selectedIndex ? 'selected' : ''}" data-index="${i}">
<span class="command-label">${this.highlightMatch(cmd.label, query)}</span>
${cmd.shortcut ? `<span class="command-shortcut">${cmd.shortcut}</span>` : ''}
</div>
`).join('');
this.results.querySelectorAll('.command-item').forEach((el) => {
el.addEventListener('click', () => {
const idx = parseInt(el.dataset.index);
this.filteredCommands[idx].action();
this.close();
});
el.addEventListener('mouseenter', () => {
this.selectedIndex = parseInt(el.dataset.index);
this.updateSelection();
});
});
}
highlightMatch(text, query) {
if (!query) return text;
const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
return text.replace(regex, '<strong>$1</strong>');
}
updateSelection() {
this.results.querySelectorAll('.command-item').forEach((el, i) => {
el.classList.toggle('selected', i === this.selectedIndex);
});
// Scroll selected into view
const selected = this.results.querySelector('.command-item.selected');
if (selected) selected.scrollIntoView({ block: 'nearest' });
}
executeSelected() {
if (this.filteredCommands[this.selectedIndex]) {
this.filteredCommands[this.selectedIndex].action();
this.close();
}
}
}
module.exports = { CommandPalette };
-123
View File
@@ -1,123 +0,0 @@
// 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');
/**
* 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(),
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');
} }
+1413 -1568
View File
File diff suppressed because it is too large Load Diff
+3794 -4395
View File
File diff suppressed because it is too large Load Diff
+376 -422
View File
@@ -1,422 +1,376 @@
/** /**
* 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 4.0.0 * @version 2.2.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 'export-with-options',
'export-with-options', 'export-spreadsheet',
'export-spreadsheet',
// Batch conversion
// Batch conversion 'batch-convert',
'batch-convert', 'select-folder',
'select-folder',
// Universal converter
// Universal converter 'universal-convert',
'universal-convert', 'universal-convert-batch',
'universal-convert-batch',
// Image converter
// Image converter 'image-convert',
'image-convert', 'image-batch-convert',
'image-batch-convert', 'image-resize',
'image-resize', 'image-compress',
'image-compress', 'image-rotate',
'image-rotate',
// Audio converter
// Audio converter 'audio-convert',
'audio-convert', 'audio-batch-convert',
'audio-batch-convert', 'audio-extract',
'audio-extract', 'audio-trim',
'audio-trim', 'audio-merge',
'audio-merge',
// Video converter
// Video converter 'video-convert',
'video-convert', 'video-batch-convert',
'video-batch-convert', 'video-compress',
'video-compress', 'video-trim',
'video-trim', 'video-frames',
'video-frames', 'video-gif',
'video-gif',
// Header/Footer
// Header/Footer 'get-header-footer-settings',
'get-header-footer-settings', 'save-header-footer-settings',
'save-header-footer-settings', 'browse-header-footer-logo',
'browse-header-footer-logo', 'save-header-footer-logo',
'save-header-footer-logo', 'clear-header-footer-logo',
'clear-header-footer-logo',
// Page settings
// Page settings 'get-page-settings',
'get-page-settings', 'update-page-settings',
'update-page-settings',
// Template settings
// Template settings 'set-custom-start-page',
'set-custom-start-page',
// PDF operations
// PDF operations 'process-pdf-operation',
'process-pdf-operation', 'get-pdf-page-count',
'get-pdf-page-count', 'select-pdf-folder',
'select-pdf-folder',
// ASCII generator (separate window)
// ASCII generator (separate window) 'open-ascii-generator',
'open-ascii-generator',
// Table generator (separate window)
// Table generator (separate window) 'open-table-generator',
'open-table-generator',
// Insert generated content
// Insert generated content 'insert-generated-content'
'insert-generated-content', ];
// Image paste/drop const ALLOWED_RECEIVE_CHANNELS = [
'save-pasted-image', // File operations
'file-new',
// Templates 'file-opened',
'load-template', 'file-save',
'get-content-for-save',
// File Explorer 'get-content-for-spreadsheet',
'list-directory', 'recent-files-cleared',
// Git // UI toggles
'git-status', 'toggle-preview',
'git-stage', 'toggle-find',
'git-commit',
'git-log', // Theme
'theme-changed',
// Snippets 'theme-data',
'get-snippets',
'save-snippet', // Edit operations
'delete-snippet', 'undo',
'redo',
// Code execution (REPL)
'execute-code', // Font
'adjust-font-size',
// File open by path
'open-file-path', // Print
'print-preview',
// PDF editor from toolbar 'print-preview-styled',
'show-pdf-editor-from-toolbar',
// Export dialogs
// Menu triggers 'show-export-dialog',
'menu-open', 'show-batch-dialog',
'export', 'show-universal-converter-dialog',
'show-table-generator',
// Git diff 'show-pdf-editor-dialog',
'git-diff'
]; // Converter dialogs
'show-image-converter',
const ALLOWED_RECEIVE_CHANNELS = [ 'show-audio-converter',
// File operations 'show-video-converter',
'file-new',
'file-opened', // PDF viewer
'file-save', 'open-pdf-viewer',
'get-content-for-save',
'get-content-for-spreadsheet', // Conversion status
'recent-files-cleared', 'conversion-status',
'conversion-complete',
// UI toggles 'batch-progress',
'toggle-preview', 'image-conversion-complete',
'toggle-find', 'audio-conversion-complete',
'video-conversion-complete',
// Theme
'theme-changed', // Folder selection
'theme-data', 'folder-selected',
'pdf-folder-selected',
// Edit operations
'undo', // Header/Footer
'redo', 'header-footer-settings-data',
'header-footer-logo-selected',
// Font 'header-footer-logo-saved',
'adjust-font-size',
// Page settings
// Print 'page-settings-data',
'print-preview',
'print-preview-styled', // PDF operations
'pdf-page-count',
// Export dialogs 'pdf-operation-complete',
'show-export-dialog', 'pdf-operation-error',
'show-batch-dialog',
'show-universal-converter-dialog', // ASCII Art Generator
'show-table-generator', 'show-ascii-generator-window',
'show-pdf-editor-dialog', 'show-ascii-generator',
// Converter dialogs // Table Generator
'show-image-converter', 'show-table-generator-window',
'show-audio-converter',
'show-video-converter', // Header/Footer dialog
'open-header-footer-dialog',
// PDF viewer 'header-footer-logo-cleared',
'open-pdf-viewer',
// PDF operation progress
// Conversion status 'pdf-operation-progress',
'conversion-status',
'conversion-complete', // Insert content from generator windows
'batch-progress', 'insert-content'
'image-conversion-complete', ];
'audio-conversion-complete',
'video-conversion-complete', /**
* Secure API exposed to renderer process
// Folder selection * Access via window.electronAPI in renderer
'folder-selected', */
'pdf-folder-selected', contextBridge.exposeInMainWorld('electronAPI', {
// ============================================
// Header/Footer // SEND METHODS (Renderer -> Main)
'header-footer-settings-data', // ============================================
'header-footer-logo-selected',
'header-footer-logo-saved', /**
* Send a message to the main process
// Page settings * @param {string} channel - IPC channel name
'page-settings-data', * @param {any} data - Data to send
*/
// PDF operations send: (channel, data) => {
'pdf-page-count', if (ALLOWED_SEND_CHANNELS.includes(channel)) {
'pdf-operation-complete', ipcRenderer.send(channel, data);
'pdf-operation-error', } else {
console.warn(`[Preload] Blocked send to unauthorized channel: ${channel}`);
// ASCII Art Generator }
'show-ascii-generator-window', },
'show-ascii-generator',
/**
// Table Generator * Invoke a main process handler and get a response
'show-table-generator-window', * @param {string} channel - IPC channel name
* @param {any} data - Data to send
// Header/Footer dialog * @returns {Promise<any>} Response from main process
'open-header-footer-dialog', */
'header-footer-logo-cleared', invoke: async (channel, data) => {
if (ALLOWED_SEND_CHANNELS.includes(channel)) {
// PDF operation progress return await ipcRenderer.invoke(channel, data);
'pdf-operation-progress', } else {
console.warn(`[Preload] Blocked invoke to unauthorized channel: ${channel}`);
// Insert content from generator windows return null;
'insert-content', }
},
// Batch converter
'show-batch-converter', // ============================================
// RECEIVE METHODS (Main -> Renderer)
// v4 menu-triggered events // ============================================
'load-template-menu',
'toggle-command-palette', /**
'toggle-sidebar-panel', * Register a listener for messages from main process
'toggle-bottom-panel' * @param {string} channel - IPC channel name
]; * @param {Function} callback - Function to call with received data
* @returns {Function} Cleanup function to remove listener
/** */
* Secure API exposed to renderer process on: (channel, callback) => {
* Access via window.electronAPI in renderer if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
*/ const subscription = (event, ...args) => callback(...args);
contextBridge.exposeInMainWorld('electronAPI', { ipcRenderer.on(channel, subscription);
// ============================================
// SEND METHODS (Renderer -> Main) // Return cleanup function
// ============================================ return () => {
ipcRenderer.removeListener(channel, subscription);
/** };
* Send a message to the main process } else {
* @param {string} channel - IPC channel name console.warn(`[Preload] Blocked listener for unauthorized channel: ${channel}`);
* @param {any} data - Data to send return () => {}; // No-op cleanup
*/ }
send: (channel, data) => { },
if (ALLOWED_SEND_CHANNELS.includes(channel)) {
ipcRenderer.send(channel, data); /**
} else { * Register a one-time listener for messages from main process
console.warn(`[Preload] Blocked send to unauthorized channel: ${channel}`); * @param {string} channel - IPC channel name
} * @param {Function} callback - Function to call with received data
}, */
once: (channel, callback) => {
/** if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
* Invoke a main process handler and get a response ipcRenderer.once(channel, (event, ...args) => callback(...args));
* @param {string} channel - IPC channel name } else {
* @param {any} data - Data to send console.warn(`[Preload] Blocked once listener for unauthorized channel: ${channel}`);
* @returns {Promise<any>} Response from main process }
*/ },
invoke: async (channel, data) => {
if (ALLOWED_SEND_CHANNELS.includes(channel)) { /**
return await ipcRenderer.invoke(channel, data); * Remove all listeners for a channel
} else { * @param {string} channel - IPC channel name
console.warn(`[Preload] Blocked invoke to unauthorized channel: ${channel}`); */
return null; removeAllListeners: (channel) => {
} if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
}, ipcRenderer.removeAllListeners(channel);
}
// ============================================ },
// RECEIVE METHODS (Main -> Renderer)
// ============================================ // ============================================
// CONVENIENCE METHODS
/** // ============================================
* Register a listener for messages from main process
* @param {string} channel - IPC channel name // File Operations
* @param {Function} callback - Function to call with received data file: {
* @returns {Function} Cleanup function to remove listener save: (filePath, content) => ipcRenderer.send('save-file', { path: filePath, content }),
*/ saveCurrent: (content) => ipcRenderer.send('save-current-file', content),
on: (channel, callback) => { setCurrent: (filePath) => ipcRenderer.send('set-current-file', filePath),
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) { saveRecent: (recentFiles) => ipcRenderer.send('save-recent-files', recentFiles),
const subscription = (event, ...args) => callback(...args); clearRecent: () => ipcRenderer.send('clear-recent-files'),
ipcRenderer.on(channel, subscription); rendererReady: () => ipcRenderer.send('renderer-ready')
},
// Return cleanup function
return () => { // Theme Operations
ipcRenderer.removeListener(channel, subscription); theme: {
}; get: () => ipcRenderer.send('get-theme')
} else { },
console.warn(`[Preload] Blocked listener for unauthorized channel: ${channel}`);
return () => {}; // No-op cleanup // Print Operations
} print: {
}, doPrint: (options) => ipcRenderer.send('do-print', options)
},
/**
* Register a one-time listener for messages from main process // Export Operations
* @param {string} channel - IPC channel name export: {
* @param {Function} callback - Function to call with received data withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }),
*/ spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format })
once: (channel, callback) => { },
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) {
ipcRenderer.once(channel, (event, ...args) => callback(...args)); // Batch Conversion
} else { batch: {
console.warn(`[Preload] Blocked once listener for unauthorized channel: ${channel}`); convert: (inputFolder, outputFolder, format, options) => {
} ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options });
}, },
selectFolder: (type) => ipcRenderer.send('select-folder', type)
/** },
* Remove all listeners for a channel
* @param {string} channel - IPC channel name // Universal Converter
*/ converter: {
removeAllListeners: (channel) => { convert: (tool, fromFormat, toFormat, filePath) => {
if (ALLOWED_RECEIVE_CHANNELS.includes(channel)) { ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath });
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: {
// File Operations getSettings: () => ipcRenderer.send('get-header-footer-settings'),
file: { saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings),
save: (filePath, content) => ipcRenderer.send('save-file', { path: filePath, content }), browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position),
saveCurrent: (content) => ipcRenderer.send('save-current-file', content), saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }),
setCurrent: (filePath) => ipcRenderer.send('set-current-file', filePath), clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position)
saveRecent: (recentFiles) => ipcRenderer.send('save-recent-files', recentFiles), },
clearRecent: () => ipcRenderer.send('clear-recent-files'),
rendererReady: () => ipcRenderer.send('renderer-ready') // Page Settings
}, page: {
getSettings: () => ipcRenderer.send('get-page-settings'),
// Theme Operations updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings),
theme: { setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber)
get: () => ipcRenderer.send('get-theme') },
},
// PDF Operations
// Print Operations pdf: {
print: { processOperation: (data) => ipcRenderer.send('process-pdf-operation', data),
doPrint: (options) => ipcRenderer.send('do-print', options) getPageCount: (filePath) => ipcRenderer.send('get-pdf-page-count', filePath),
}, selectFolder: (inputId) => ipcRenderer.send('select-pdf-folder', inputId)
},
// Export Operations
export: { // Image Converter Operations
withOptions: (format, options) => ipcRenderer.send('export-with-options', { format, options }), image: {
spreadsheet: (content, format) => ipcRenderer.send('export-spreadsheet', { content, format }) convert: (data) => ipcRenderer.send('image-convert', data),
}, batchConvert: (data) => ipcRenderer.send('image-batch-convert', data),
resize: (data) => ipcRenderer.send('image-resize', data),
// Batch Conversion compress: (data) => ipcRenderer.send('image-compress', data),
batch: { rotate: (data) => ipcRenderer.send('image-rotate', data)
convert: (inputFolder, outputFolder, format, options) => { },
ipcRenderer.send('batch-convert', { inputFolder, outputFolder, format, options });
}, // Audio Converter Operations
selectFolder: (type) => ipcRenderer.send('select-folder', type) audio: {
}, convert: (data) => ipcRenderer.send('audio-convert', data),
batchConvert: (data) => ipcRenderer.send('audio-batch-convert', data),
// Universal Converter extract: (data) => ipcRenderer.send('audio-extract', data),
converter: { trim: (data) => ipcRenderer.send('audio-trim', data),
convert: (tool, fromFormat, toFormat, filePath) => { merge: (data) => ipcRenderer.send('audio-merge', data)
ipcRenderer.send('universal-convert', { tool, fromFormat, toFormat, filePath }); },
},
convertBatch: (tool, fromFormat, toFormat, inputFolder, outputFolder) => { // Video Converter Operations
ipcRenderer.send('universal-convert-batch', { tool, fromFormat, toFormat, inputFolder, outputFolder }); video: {
} convert: (data) => ipcRenderer.send('video-convert', data),
}, batchConvert: (data) => ipcRenderer.send('video-batch-convert', data),
compress: (data) => ipcRenderer.send('video-compress', data),
// Header/Footer Operations trim: (data) => ipcRenderer.send('video-trim', data),
headerFooter: { extractFrames: (data) => ipcRenderer.send('video-frames', data),
getSettings: () => ipcRenderer.send('get-header-footer-settings'), toGif: (data) => ipcRenderer.send('video-gif', data)
saveSettings: (settings) => ipcRenderer.send('save-header-footer-settings', settings), },
browseLogo: (position) => ipcRenderer.send('browse-header-footer-logo', position),
saveLogo: (position, filePath) => ipcRenderer.send('save-header-footer-logo', { position, filePath }), // Generator Windows
clearLogo: (position) => ipcRenderer.send('clear-header-footer-logo', position) generators: {
}, openAscii: () => ipcRenderer.send('open-ascii-generator'),
openTable: () => ipcRenderer.send('open-table-generator')
// Page Settings }
page: { });
getSettings: () => ipcRenderer.send('get-page-settings'),
updateSettings: (settings) => ipcRenderer.send('update-page-settings', settings), // Log successful preload initialization
setCustomStartPage: (pageNumber) => ipcRenderer.send('set-custom-start-page', pageNumber) 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);
// 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);
-139
View File
@@ -1,139 +0,0 @@
class PrintPreview {
constructor() {
this.overlay = document.getElementById('print-preview-overlay');
this._lastContent = '';
this.setupEventListeners();
}
open(htmlContent) {
this._lastContent = htmlContent;
this.overlay.classList.remove('hidden');
this.updatePreview(htmlContent);
this.updateScaleLabel();
}
close() {
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');
}
});
// Close on overlay click
this.overlay?.addEventListener('click', (e) => {
if (e.target === this.overlay) this.close();
});
// Close on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !this.overlay.classList.contains('hidden')) {
this.close();
}
});
}
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 };
+4514 -4445
View File
File diff suppressed because it is too large Load Diff
-49
View File
@@ -1,49 +0,0 @@
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
@@ -1,70 +0,0 @@
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
@@ -1,84 +0,0 @@
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
@@ -1,50 +0,0 @@
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
@@ -1,71 +0,0 @@
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
@@ -1,34 +0,0 @@
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
+2113 -2335
View File
File diff suppressed because it is too large Load Diff
-268
View File
@@ -1,268 +0,0 @@
/* 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-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-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
@@ -1,24 +0,0 @@
.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; }
+4080 -4060
View File
File diff suppressed because it is too large Load Diff
+545 -545
View File
File diff suppressed because it is too large Load Diff
-90
View File
@@ -1,90 +0,0 @@
# 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
@@ -1,20 +0,0 @@
---
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
@@ -1,20 +0,0 @@
# Changelog
## [Unreleased]
### Added
- New feature
### Changed
- Updated feature
### Fixed
- Bug fix
### Removed
- Removed feature
## [1.0.0] - {{DATE}}
### Added
- Initial release
-59
View File
@@ -1,59 +0,0 @@
# 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
@@ -1,26 +0,0 @@
# 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
@@ -1,54 +0,0 @@
# 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
@@ -1,38 +0,0 @@
# 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
@@ -1,42 +0,0 @@
# 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
@@ -1,42 +0,0 @@
# 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
@@ -1,71 +0,0 @@
# 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)
-78
View File
@@ -1,78 +0,0 @@
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
@@ -1,144 +0,0 @@
/**
* @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
@@ -1,100 +0,0 @@
/**
* 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
@@ -1,130 +0,0 @@
/**
* 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');
});
});
});
+121 -175
View File
@@ -1,175 +1,121 @@
/** /**
* 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',
'do-print-with-options', 'export-with-options',
'export-with-options', 'export-spreadsheet',
'export-spreadsheet', 'batch-convert',
'batch-convert', 'select-folder',
'select-folder', 'universal-convert',
'universal-convert', 'universal-convert-batch',
'universal-convert-batch', 'get-header-footer-settings',
'image-convert', 'save-header-footer-settings',
'image-batch-convert', 'browse-header-footer-logo',
'image-resize', 'save-header-footer-logo',
'image-compress', 'clear-header-footer-logo',
'image-rotate', 'get-page-settings',
'audio-convert', 'update-page-settings',
'audio-batch-convert', 'set-custom-start-page',
'audio-extract', 'process-pdf-operation',
'audio-trim', 'get-pdf-page-count',
'audio-merge', 'select-pdf-folder'
'video-convert', ];
'video-batch-convert',
'video-compress', const EXPECTED_RECEIVE_CHANNELS = [
'video-trim', 'file-new',
'video-frames', 'file-opened',
'video-gif', 'file-save',
'get-header-footer-settings', 'get-content-for-save',
'save-header-footer-settings', 'get-content-for-spreadsheet',
'browse-header-footer-logo', 'recent-files-cleared',
'save-header-footer-logo', 'toggle-preview',
'clear-header-footer-logo', 'toggle-find',
'get-page-settings', 'theme-changed',
'update-page-settings', 'theme-data',
'set-custom-start-page', 'undo',
'process-pdf-operation', 'redo',
'get-pdf-page-count', 'adjust-font-size',
'select-pdf-folder', 'print-preview',
'open-ascii-generator', 'print-preview-styled',
'open-table-generator', 'show-export-dialog',
'insert-generated-content', 'show-batch-dialog',
'save-pasted-image', 'show-universal-converter-dialog',
'load-template', 'show-table-generator',
'list-directory', 'show-pdf-editor-dialog',
'open-file-path', 'conversion-status',
'git-status', 'conversion-complete',
'git-stage', 'batch-progress',
'git-commit', 'folder-selected',
'git-log', 'pdf-folder-selected',
'git-diff', 'header-footer-settings-data',
'get-snippets', 'header-footer-logo-selected',
'save-snippet', 'header-footer-logo-saved',
'delete-snippet', 'page-settings-data',
'execute-code', 'pdf-page-count',
'show-pdf-editor-from-toolbar', 'pdf-operation-complete',
'menu-open', 'pdf-operation-error'
'export' ];
];
test('should define all expected send channels', () => {
const EXPECTED_RECEIVE_CHANNELS = [ // This test documents expected channels
'file-new', expect(EXPECTED_SEND_CHANNELS.length).toBeGreaterThan(0);
'file-opened', });
'file-save',
'get-content-for-save', test('should define all expected receive channels', () => {
'get-content-for-spreadsheet', // This test documents expected channels
'recent-files-cleared', expect(EXPECTED_RECEIVE_CHANNELS.length).toBeGreaterThan(0);
'toggle-preview', });
'toggle-find', });
'theme-changed',
'theme-data', describe('electronAPI Interface', () => {
'undo', test('should expose send method', () => {
'redo', expect(window.electronAPI.send).toBeDefined();
'adjust-font-size', expect(typeof window.electronAPI.send).toBe('function');
'print-preview', });
'print-preview-styled',
'show-export-dialog', test('should expose on method', () => {
'show-batch-dialog', expect(window.electronAPI.on).toBeDefined();
'show-universal-converter-dialog', expect(typeof window.electronAPI.on).toBe('function');
'show-table-generator', });
'show-pdf-editor-dialog',
'show-image-converter', test('should expose once method', () => {
'show-audio-converter', expect(window.electronAPI.once).toBeDefined();
'show-video-converter', expect(typeof window.electronAPI.once).toBe('function');
'open-pdf-viewer', });
'conversion-status',
'conversion-complete', test('should expose invoke method', () => {
'batch-progress', expect(window.electronAPI.invoke).toBeDefined();
'image-conversion-complete', expect(typeof window.electronAPI.invoke).toBe('function');
'audio-conversion-complete', });
'video-conversion-complete',
'folder-selected', test('should expose file convenience methods', () => {
'pdf-folder-selected', expect(window.electronAPI.file).toBeDefined();
'header-footer-settings-data', expect(window.electronAPI.file.save).toBeDefined();
'header-footer-logo-selected', expect(window.electronAPI.file.saveCurrent).toBeDefined();
'header-footer-logo-saved', expect(window.electronAPI.file.setCurrent).toBeDefined();
'header-footer-logo-cleared', });
'page-settings-data',
'pdf-page-count', test('should expose theme convenience methods', () => {
'pdf-operation-complete', expect(window.electronAPI.theme).toBeDefined();
'pdf-operation-error', expect(window.electronAPI.theme.get).toBeDefined();
'pdf-operation-progress', });
'show-ascii-generator-window',
'show-ascii-generator', test('should expose pdf convenience methods', () => {
'show-table-generator-window', expect(window.electronAPI.pdf).toBeDefined();
'open-header-footer-dialog', expect(window.electronAPI.pdf.processOperation).toBeDefined();
'insert-content', expect(window.electronAPI.pdf.getPageCount).toBeDefined();
'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
@@ -1,109 +0,0 @@
/**
* @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>`),
use: jest.fn() setOptions: 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
@@ -1,121 +0,0 @@
/**
* @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');
}); });
}); });
}); });