25 Commits

Author SHA1 Message Date
lashman 8b55855c81 Update README.md 2026-03-09 15:17:38 +02:00
TypoGenie 63cfed02d9 docs: add WCAG 2.2 AAA accessibility section to README 2026-02-19 00:12:20 +02:00
TypoGenie 87dd578e92 a11y: add error boundary, reduced motion, remaining fixes 2026-02-18 23:52:06 +02:00
TypoGenie 2ca1439680 a11y: add runtime contrast validation, justify override, line-height floor 2026-02-18 23:49:03 +02:00
TypoGenie bd842b87a2 a11y: add DOCX metadata, image placeholders, table headers 2026-02-18 23:46:32 +02:00
TypoGenie 1458210d88 a11y: add landmarks, semantic structure, skip nav, iframe lang 2026-02-18 23:43:48 +02:00
TypoGenie e460f4df68 a11y: add ARIA live regions for status announcements and errors 2026-02-18 23:35:52 +02:00
TypoGenie d0f88625b5 a11y: fix keyboard access, listbox pattern, ARIA labels, target sizes 2026-02-18 23:32:21 +02:00
TypoGenie 242e16f75d a11y: convert all modals to native dialog with focus management 2026-02-18 23:27:55 +02:00
TypoGenie 7d5af9e39c a11y: fix CSS foundation - contrast, overflow, focus ring, reduced motion 2026-02-18 23:22:04 +02:00
TypoGenie 3b8e80c3a3 docs: add WCAG 2.2 AAA implementation plan 2026-02-18 23:17:00 +02:00
TypoGenie 3ab4432fcf docs: add WCAG 2.2 AAA accessibility remediation design
Covers 147 issues across 8 sections: CSS foundation, modal system,
keyboard access, ARIA live regions, semantic structure, DOCX output,
template contrast validation, and miscellaneous fixes.
2026-02-18 23:11:05 +02:00
TypoGenie 32c9ab9e92 docs: standardize style count to 165+ across README 2026-02-09 23:00:24 +02:00
TypoGenie 592ded54fe chore: normalize dashes across project files 2026-02-09 22:59:03 +02:00
TypoGenie f34aa9e9a8 chore: switch license from MIT to CC0-1.0 2026-02-09 22:55:59 +02:00
lashman a1f3a86022 Update README.md 2026-02-09 18:10:57 +00:00
TypoGenie 285b9e835d docs: release 1.0.0
- Updated README to reflect Windows Portable focus
- Removed references to Mac/Linux builds
- Updated tech stack and project structure documentation
- Updated Contributing section
2026-02-01 19:17:10 +02:00
TypoGenie 3265ea899b fix: resolve lingering TypeScript errors found during cleanup
- Fixed unused import in useTemplates.ts
- Fixed argument mismatch in templateLoader.ts
2026-02-01 19:05:00 +02:00
TypoGenie 4a8ca94348 chore: cleanup unused files and scripts
- Removed legacy TypeScript templates (replaced by JSON)
- Removed unused PowerShell and CJS maintenance scripts
- Removed debug logs and unused components
- Files moved to local _TRASH/ directory (excluded from git)
2026-02-01 19:03:37 +02:00
TypoGenie 30cff63353 chore: sanitize template names and descriptions
- Renamed 'Artificial Intelligence' to 'Neural Network'
- Renamed 'Blockchain Protocol' to 'Secure Protocol'
- Renamed 'Crypto Futurism' to 'Digital Futurism'
- Renamed 'Startup SaaS' to 'Product Launch'
- Renamed 'Tech Startup' to 'Tech Venture'
- Removed references to AI, crypto, blockchain, and startups from template descriptions
- Updated README.md to remove specific startup/SaaS references
2026-02-01 18:57:57 +02:00
TypoGenie 60f39ed961 feat: port all template categories to JSON format
- Ported Minimalist templates to JSON (Swiss Grid, Brutalist, etc.)
- Ported Tech templates to JSON (SaaS, Terminal, Cyberpunk, etc.)
- Ported Creative templates to JSON (Art Gallery, Zine, Pop Art, etc.)
- Ported Industrial templates to JSON (Blueprint, Factory, Schematic, etc.)
- Ported Nature templates to JSON (Botanical, Ocean, Mountain, etc.)
- Ported Lifestyle templates to JSON (Cookbook, Travel, Coffee House, etc.)
- Ported Vintage templates to JSON (Art Deco, Medieval, Retro 80s, etc.)
- Updated README.md to reflect the new JSON-based style system (example configuration and contribution workflow)
- Completed migration of over 150 styles to the new architecture
2026-02-01 18:51:43 +02:00
TypoGenie a2631ac473 feat: Make app fully portable
- Add tauri-plugin-store for portable data storage
- Implement portable data directory (TypoGenie-Data/ next to EXE)
- Configure Rust backend to use EXE-relative paths
- Add store permissions for persistent settings
- Update README with portable badges and documentation
- Document how to build and use the portable EXE
- Zero registry, zero AppData, fully self-contained
2026-01-29 18:36:48 +02:00
TypoGenie 2c22b0fce6 feat: Transform to Tauri desktop app
- Initialize Tauri v2 project with Rust backend
- Restructure project: move source files to src/ directory
- Add Tauri configuration for Windows, macOS, and Linux builds
- Update Vite config for Tauri development workflow
- Add file system and dialog permissions for native features
- Update package.json with desktop build scripts
- Update tsconfig.json paths for new src structure
- Add Tauri and desktop badges to README
- Document desktop build process and architecture
2026-01-29 18:28:35 +02:00
TypoGenie ae5ce9d243 docs: Rewrite README with comprehensive documentation
- Added extensive project documentation covering all features
- Beautiful visual design with badges, shields, and banners
- Included architecture diagrams and style system deep-dive
- Added contribution guidelines and philosophy section
- Wove in themes of collective benefit, commons, and mutual aid throughout
- Celebrated open-source as a model of voluntary cooperation
2026-01-29 18:14:41 +02:00
TypoGenie f179e79f35 Initial commit: TypoGenie - Markdown to Word document converter 2026-01-29 18:10:07 +02:00
23 changed files with 1716 additions and 784 deletions
+8 -11
View File
@@ -79,7 +79,7 @@ In a world where document formatting tools are increasingly locked behind paywal
### 🎯 Core Capabilities
- **📄 Universal Input Support** - Drop in any `.md`, `.html`, `.txt`, or `.markdown` file - HTML content is auto-detected and converted
- **📄 Universal Markdown Support** - Drop in any `.md`, `.txt`, or `.markdown` file
- **🎨 165+ Typography Styles** - Curated across 8 aesthetic categories
- **📐 Multiple Paper Sizes** - A4 and Letter formats supported
- **💾 Local Processing** - Your documents never leave your machine
@@ -167,7 +167,7 @@ The `.docx` files TypoGenie generates are also built with accessibility in mind:
| **Document Metadata** | Every exported DOCX includes `title`, `description`, and `creator` properties for assistive technology |
| **Heading Structure** | Semantic `HeadingLevel` preserved in both rendering modes (semantic and high-fidelity table layout) |
| **Table Headers** | Rows containing `<th>` elements are marked with `tableHeader: true` so screen readers can announce column/row headers |
| **Image Embedding** | Images linked via URL are fetched and embedded in the exported DOCX, scaled to fit the page width. Falls back to italic `[Image: alt text]` placeholders if the image can't be fetched |
| **Image Placeholders** | `<img>` elements in Markdown are converted to italic `[Image: alt text]` placeholders rather than silently dropped |
| **Contrast-Safe Colors** | All template text colors are validated and auto-corrected against their backgrounds before being applied to the document |
### Runtime Contrast Validation
@@ -228,7 +228,7 @@ This means all 165+ styles automatically meet WCAG AAA contrast requirements reg
**TypoGenie is fully portable** - no installation, no registry entries, no files scattered across your system.
Just download and run:
- 🪟 **Windows**: [`TypoGenie-v1.2.1-Portable.zip`](https://git.lashman.live/lashman/typogenie/releases) - Extract and run, nothing else needed
- 🪟 **Windows**: `TypoGenie.exe` - Single executable, runs immediately
**How it works:**
```
@@ -294,7 +294,7 @@ npm run desktop:build
### Usage
1. **📤 Upload** - Drag and drop your Markdown, HTML, or text file (or click to browse)
1. **📤 Upload** - Drag and drop your Markdown file (or click to browse)
2. **🎨 Select Style** - Browse the gallery and click any style for live preview
3. **📐 Choose Paper Size** - A4 or Letter, depending on your needs
4. **✨ Generate** - Watch the magic happen (with a satisfying loading animation)
@@ -327,7 +327,7 @@ npm run desktop:build
│ ▼ ▼ ▼ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ PROCESSING PIPELINE │ │
│ │ Input → detect/convert → Markdown → marked → HTML → .docx │ │
│ │ Markdown → marked parser → HTML → docx library → .docx │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
@@ -428,10 +428,8 @@ typogenie/
│ │ ├── templateLoader.ts # Loads JSON templates via Rust
│ │ └── templateRenderer.ts # Generates CSS/DOCX with contrast validation
│ ├── 📁 utils/ # Utilities
│ │ ├── contentDetector.ts # Auto-detects HTML vs Markdown vs plain text
│ │ ├── contrastUtils.ts # WCAG contrast ratio validation
│ │ ── docxConverter.ts # Accessible DOCX generation with image embedding
│ │ └── htmlToMarkdown.ts # HTML-to-Markdown conversion via Turndown
│ │ ── docxConverter.ts # Accessible DOCX generation
│ └── 📄 App.tsx # Main application component
├── 📁 src-tauri/ # Tauri desktop app
│ ├── 📁 src/ # Rust backend code (filesystem access)
@@ -455,7 +453,6 @@ typogenie/
| **Animation** | Framer Motion (motion/react) | Transitions with reduced-motion support |
| **Icons** | Lucide React | Beautiful, consistent iconography |
| **Markdown** | marked 12.0.0 | Local Markdown parsing |
| **HTML Import** | turndown 7.2.0 | HTML-to-Markdown conversion with content type detection |
| **Documents** | docx 8.5.0 | Client-side DOCX generation |
| **Desktop** | Tauri 2.0 | Native desktop apps (Rust + WebView) |
| **Backend** | Rust 1.77+ | Systems programming for desktop shell |
@@ -563,6 +560,8 @@ If TypoGenie brings value to your life, consider:
<p>
<i>"The master's tools will never dismantle the master's house. But they might help you format a really nice document while we build something better together."</i>
This project is developed with the help of a locally-run LLM via opencode for scaffolding, planning, and routine code tasks. Architecture and design decisions are my own.
</p>
<p>
@@ -574,5 +573,3 @@ If TypoGenie brings value to your life, consider:
<img src="https://capsule-render.vercel.app/api?type=waving&color=0:a855f7,50:8b5cf6,100:6366f1&height=100&section=footer" alt="Footer" />
</div>
<sub><i>This project is developed with the help of a locally-run LLM via opencode for scaffolding, planning, and routine code tasks. Architecture and design decisions are my own.</i></sub>
@@ -0,0 +1,212 @@
# WCAG 2.2 AAA Accessibility Remediation Design
**Date:** 2026-02-18
**Status:** Approved
**Scope:** 147 accessibility issues across 17 existing files, 3 new files
## Decisions
| Decision | Choice |
|----------|--------|
| Visual approach | Balance accessibility with dark aesthetic |
| Modals | Native `<dialog>` element |
| Style cards | Listbox pattern with existing `useFocusableList` hook |
| Template colors | Runtime contrast validation only, no JSON template edits |
| Justified text | Override to `left` at render time |
| Contrast enforcement | Auto-correct via `ensureContrast()` utility at render time |
## Section 1: CSS Foundation (~25 issues)
### Root font size
Change `:root { font-size: 16px }` to `font-size: 100%` in `index.css` so user browser preferences are respected.
### Overflow
Remove `overflow: hidden` from `body` and `#root`. Replace with `overflow-x: hidden` to prevent horizontal scroll but allow vertical content access when zoomed to 200%.
### Focus indicators
Replace `rgba(99, 102, 241, 0.3)` focus ring with `rgba(99, 102, 241, 0.8)` at 2px. Meets 3:1 contrast on dark backgrounds while fitting indigo theme.
### Reduced motion
Add global CSS rule:
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
```
### Forced colors
Add `@media (forced-colors: active)` rules for Windows High Contrast Mode compatibility.
### Color replacements
Across all components: `text-zinc-600` -> `text-zinc-400`, `text-zinc-500` -> `text-zinc-400`. All text hits 7:1+ contrast on zinc-950. Keeps dark aesthetic.
## Section 2: Modal System (~20 issues)
### New `src/hooks/useDialog.ts`
Reusable hook wrapping native `<dialog>`:
- Manages `dialogRef`, `showModal()`/`close()`
- Restores focus to trigger element on close
- Wires `aria-labelledby`
- Framer Motion animations on inner content div
### KeyboardShortcutsHelp (App.tsx)
Convert from `motion.div` overlay to `<dialog>`. Add `aria-labelledby` to heading. Close button gets `aria-label="Close shortcuts"`. Escape/focus trap handled natively.
### ExportOptionsModal
Same `<dialog>` conversion. Radio buttons wrapped in `<fieldset><legend>`. Close button labeled.
### StylePreviewModal
Same `<dialog>` conversion. Close button labeled. Iframe HTML gets `lang="en"`.
### Animation approach
`dialog[open]` CSS selector for entrance. `::backdrop` gets fade-in. Framer Motion on inner content for exit.
## Section 3: Keyboard Access & Interactive Elements (~20 issues)
### Logo button
Replace `<motion.div onClick>` with `<motion.button aria-label="TypoGenie - Reset to home">`.
### Single-character shortcut
Scope `?`/`/` listener to only fire when `document.activeElement` is body or non-input element. Prevents intercepting typing in search.
### Style cards as listbox
Container: `role="listbox"` + `aria-label="Typography styles"`. Each card: `role="option"` + `tabIndex` + `aria-selected` + `onKeyDown`. Wire `useFocusableList` for arrow keys. Add `:focus-visible` indigo ring.
### Favorite button
Add `aria-label` (dynamic: "Add to favorites"/"Remove from favorites") + `aria-pressed`.
### Category filters
Wrap in `<div role="group" aria-label="Filter by category">`. Active button: `aria-pressed="true"`.
### Paper size buttons
Wrap in `<div role="group" aria-label="Paper size">`. Active button: `aria-pressed="true"`.
### Search input
Add `aria-label="Search templates"` + `aria-describedby` pointing to live result count region.
### Icon-only buttons
Add `aria-label` to all: zoom buttons, external link (Preview), close buttons. Decorative icons next to text: `aria-hidden="true"`.
### Target sizes
Increase padding on small buttons to hit 44x44px minimum. Use `min-w-[44px] min-h-[44px]` with centered content where inline growth not possible.
## Section 4: ARIA Live Regions & Status Announcements (~15 issues)
### Root status region
Persistent `<div role="status" aria-live="polite" className="sr-only">` in App.tsx root. Updated on `appState` changes.
### Generating state
Add `aria-busy="true"` + `role="status"` to container.
### Preview loading
Wrap "Loading..." in `role="status"`.
### Success message
`aria-live="polite"` on button text area for "Saved!" announcement.
### Search results
Visually-hidden `role="status"` announcing "{N} templates found". Debounced 300ms.
### Error fixes
- Remove `aria-live="polite"` where `role="alert"` already set (implies assertive)
- Remove 5-second auto-dismiss from FileUpload error
- Add `aria-describedby` linking FileUpload error to dropzone
- Template loading: `role="status"`. Template error: `role="alert"`
### Loading state
Replace `return null` with minimal `<div role="status">Loading TypoGenie</div>`.
## Section 5: Semantic Structure & Landmarks (~15 issues)
### Skip navigation
`<a href="#main-content" class="sr-only focus:not-sr-only">Skip to main content</a>` in index.html.
### Page title
`<title>TypoGenie - Markdown to Word Converter</title>`
### Noscript
`<noscript><p>TypoGenie requires JavaScript to run.</p></noscript>`
### Landmarks
- `id="main-content"` on `<main>` in both app states
- `<nav aria-label="Style filters">` around category buttons
- `<section aria-label="Style list">` and `<section aria-label="Style preview">` in StyleSelector
### Progress stepper
Wrap in `<nav aria-label="Progress"><ol>`. Active step: `aria-current="step"`.
### Shortcuts list
Convert to `<dl>` with `<dt>`/`<dd>`.
### Decorative elements
`aria-hidden="true"` on blob backgrounds, window-chrome dots, visual dividers.
### Iframe lang
Both Preview.tsx and StylePreviewModal.tsx: inject `<html lang="en">`.
## Section 6: DOCX Output Accessibility (~8 issues)
### Document metadata
Add `title` (from filename/first h1), `description`, `language` to Document constructor.
### Image handling
New `<img>` handler producing `[Image: {alt text}]` placeholder paragraph in italic.
### Table headers
Set `tableHeader: true` on `TableRow` containing `<th>` elements.
### Heading preservation in table mode
Add `HeadingLevel` to paragraph inside `processHeaderAsTable` table cells.
### Code block style
Add custom "Code" paragraph style to DOCX styles. Apply to code blocks.
## Section 7: Template Contrast Validation (~20 issues)
### New `src/utils/contrastUtils.ts`
- `hexToRgb(hex)` - parse hex to RGB
- `relativeLuminance(rgb)` - WCAG luminance formula
- `contrastRatio(color1, color2)` - ratio calculation
- `ensureContrast(fg, bg, minRatio)` - auto-correct foreground color until ratio met
### Integration in templateRenderer.ts
Run `ensureContrast()` on every text/background pair at CSS generation time. Body text: 7:1. Large text (18pt+ or 14pt+ bold): 4.5:1.
### `del` element fix
When resolving `del` color, if `border` palette color fails contrast, fall back to `textSecondary`.
### Justified text
Override `justify` to `left` at render time (1.4.8 AAA prohibits justified text).
### Line-height floor
Enforce minimum 1.5 for body text, 1.0 for headings. Clamp upward if template specifies lower.
## Section 8: Remaining Miscellaneous (~10 issues)
### Iframe keyboard
`tabIndex={-1}` on preview iframe in StyleSelector (passive preview, not interactive).
### Error boundary
New `src/components/ErrorBoundary.tsx` wrapping `<App />`. Renders accessible error with `role="alert"` on crash.
### Framer Motion reduced motion
Import `useReducedMotion` from `motion/react` in App.tsx. When true, disable infinite blob/gradient animations via conditional animate props.
### Hidden buttons on small screens
Add always-visible `<kbd>?</kbd>` hint regardless of breakpoint.
### Truncation
Add `title` attribute with full description on `line-clamp-2` elements.
## Files Modified (17)
`index.html`, `src/index.css`, `src/App.tsx`, `src/main.tsx`, `src/components/StyleSelector.tsx`, `src/components/Preview.tsx`, `src/components/ExportOptionsModal.tsx`, `src/components/StylePreviewModal.tsx`, `src/components/FileUpload.tsx`, `src/hooks/useSettings.ts`, `src/hooks/useTemplates.ts`, `src/services/templateRenderer.ts`, `src/utils/docxConverter.ts`, `src/utils/fontUtils.ts`
## Files Created (3)
`src/utils/contrastUtils.ts`, `src/hooks/useDialog.ts`, `src/components/ErrorBoundary.tsx`
File diff suppressed because it is too large Load Diff
+3 -34
View File
@@ -1,12 +1,12 @@
{
"name": "typogenie",
"version": "1.2.0",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "typogenie",
"version": "1.2.0",
"version": "1.0.0",
"dependencies": {
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-dialog": "^2.0.0",
@@ -21,15 +21,12 @@
"marked": "12.0.0",
"motion": "^12.29.2",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"turndown": "^7.2.2",
"turndown-plugin-gfm": "^1.0.2"
"react-dom": "^19.2.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.18",
"@tauri-apps/cli": "^2.9.6",
"@types/node": "^22.14.0",
"@types/turndown": "^5.0.6",
"@vitejs/plugin-react": "^5.0.0",
"autoprefixer": "^10.4.23",
"postcss": "^8.5.6",
@@ -825,12 +822,6 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@mixmark-io/domino": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz",
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
"license": "BSD-2-Clause"
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.53",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz",
@@ -1811,13 +1802,6 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/turndown": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.6.tgz",
"integrity": "sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg==",
"dev": true,
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.2.tgz",
@@ -2906,21 +2890,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/turndown": {
"version": "7.2.2",
"resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.2.tgz",
"integrity": "sha512-1F7db8BiExOKxjSMU2b7if62D/XOyQyZbPKq/nUwopfgnHlqXHqQ0lvfUTeUIr1lZJzOPFn43dODyMSIfvWRKQ==",
"license": "MIT",
"dependencies": {
"@mixmark-io/domino": "^2.2.0"
}
},
"node_modules/turndown-plugin-gfm": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/turndown-plugin-gfm/-/turndown-plugin-gfm-1.0.2.tgz",
"integrity": "sha512-vwz9tfvF7XN/jE0dGoBei3FXWuvll78ohzCZQuOb+ZjWrs3a0XhQVomJEb2Qh4VHTPNRO4GPZh0V7VRbiWwkRg==",
"license": "MIT"
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
+3 -6
View File
@@ -1,7 +1,7 @@
{
"name": "typogenie",
"private": true,
"version": "1.2.1",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,24 +18,21 @@
"@tauri-apps/plugin-dialog": "^2.0.0",
"@tauri-apps/plugin-fs": "^2.0.0",
"@tauri-apps/plugin-http": "^2.5.6",
"@tauri-apps/plugin-opener": "^2.2.6",
"@tauri-apps/plugin-shell": "^2.3.4",
"@tauri-apps/plugin-store": "^2.4.2",
"@tauri-apps/plugin-window-state": "^2.4.1",
"@tauri-apps/plugin-opener": "^2.2.6",
"docx": "^8.5.0",
"lucide-react": "^0.563.0",
"marked": "12.0.0",
"motion": "^12.29.2",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"turndown": "^7.2.2",
"turndown-plugin-gfm": "^1.0.2"
"react-dom": "^19.2.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.18",
"@tauri-apps/cli": "^2.9.6",
"@types/node": "^22.14.0",
"@types/turndown": "^5.0.6",
"@vitejs/plugin-react": "^5.0.0",
"autoprefixer": "^10.4.23",
"postcss": "^8.5.6",
+1 -1
View File
@@ -4918,7 +4918,7 @@ checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]]
name = "typogenie"
version = "1.2.1"
version = "1.0.0"
dependencies = [
"log",
"opener",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "typogenie"
version = "1.2.1"
version = "1.0.0"
description = "TypoGenie - Portable Markdown to Word document converter"
authors = ["TypoGenie Contributors"]
license = "CC0-1.0"
+7 -5
View File
@@ -27,23 +27,25 @@
"fs:allow-exe-write",
"store:default",
"window-state:default",
"http:default",
"http:allow-fetch",
"shell:default",
"shell:allow-open",
"opener:default",
{
"identifier": "http:default",
"identifier": "http:allow-fetch",
"allow": [
{
"url": "https://*"
"url": "https://fonts.google.com/*"
},
{
"url": "http://*"
"url": "https://github.com/*"
},
{
"url": "https://*:*"
"url": "https://*.githubusercontent.com/*"
},
{
"url": "http://*:*"
"url": "https://fonts.googleapis.com/*"
}
]
},
+2 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "TypoGenie",
"version": "1.2.1",
"version": "1.0.0",
"identifier": "live.lashman.typogenie",
"build": {
"frontendDist": "../dist",
@@ -28,7 +28,7 @@
}
],
"security": {
"csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost https: http:; font-src 'self' https://fonts.gstatic.com data:; style-src 'self' 'unsafe-inline' data: blob: https://fonts.googleapis.com; img-src 'self' data: blob: https: http:; script-src 'self' 'unsafe-inline'; frame-src 'self' blob: about:;",
"csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost https://fonts.googleapis.com https://fonts.gstatic.com https://github.com https://raw.githubusercontent.com https://fonts.google.com; font-src 'self' https://fonts.gstatic.com data:; style-src 'self' 'unsafe-inline' data: blob: https://fonts.googleapis.com; img-src 'self' data: blob:; script-src 'self' 'unsafe-inline'; frame-src 'self' blob: about:;",
"dangerousDisableAssetCspModification": true
}
},
@@ -2,7 +2,7 @@
"id": "creative-portfolio",
"name": "Creative Portfolio",
"category": "creative",
"description": "Minimalist gallery style for presenting visual work. Focuses on images and clean typography.",
"description": "Minimalist gallery style for showcasing visual work. Focuses on images and clean typography.",
"vibe": "Minimalist, Visual, Gallery",
"googleFontsImport": "https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,300..900;1,300..900&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap",
"typography": {
@@ -2,7 +2,7 @@
"id": "rococo-romance",
"name": "Rococo Romance",
"category": "editorial",
"description": "Inspired by 18th-century Rococo. Light, playful, and delicate with pastel tones and swirling elegance.",
"description": "Inspired by 18th-century Rococo. Light, playful, and intricate with pastel tones and swirling elegance.",
"vibe": "Romantic, Ornate, Pastel",
"googleFontsImport": "https://fonts.googleapis.com/css2?family=Pinyon+Script&family=Playfair+Display+SC:ital,wght@0,400;0,700;1,400;1,700&family=Lora:ital,wght@0,400..700;1,400..700&display=swap",
"typography": {
@@ -1,5 +1,5 @@
{
"id": "neural-network",
"id": "artificial-intelligence",
"name": "Neural Network",
"category": "tech",
"description": "Cutting-edge design for advanced computing and data science. Neural network inspired with gradient accents.",
+1 -1
View File
@@ -2,7 +2,7 @@
"id": "tech-startup",
"name": "Tech Venture",
"category": "tech",
"description": "Modern, energetic design for technology companies and ventures. Bold gradients, punchy colors, and confident typography.",
"description": "Modern, energetic design for technology companies and ventures. Bold gradients, vibrant colors, and confident typography.",
"vibe": "Innovative, Dynamic, Bold",
"googleFontsImport": "https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;700&display=swap",
"typography": {
@@ -2,7 +2,7 @@
"id": "memphis-pattern",
"name": "Memphis Pattern",
"category": "retro",
"description": "The chaotic 80s aesthetic. Clashing patterns, zig-zags, and loud pastel-neons.",
"description": "The chaotic 80s aesthetic. Clashing patterns, zig-zags, and vibrant pastel-neons.",
"vibe": "Playful, Chaotic, 80s",
"googleFontsImport": "https://fonts.googleapis.com/css2?family=Righteous&family=Comfortaa:wght@400;700&display=swap",
"typography": {
@@ -2,7 +2,7 @@
"id": "mid-century-modern",
"name": "Mid-Century Modern",
"category": "retro",
"description": "Optimistic and playful design from the 1950s-60s. Geometric sans-serifs, bold atomic-age colors, and approachable warmth.",
"description": "Optimistic and playful design from the 1950s-60s. Geometric sans-serifs, vibrant atomic-age colors, and approachable warmth.",
"vibe": "Playful, Nostalgic, Friendly",
"googleFontsImport": "https://fonts.googleapis.com/css2?family=Quicksand:wght@400;600;700&display=swap",
"typography": {
+4 -42
View File
@@ -10,9 +10,7 @@ import { useTemplates } from './hooks/useTemplates';
import { useDialog } from './hooks/useDialog';
// @ts-ignore
import { parse } from 'marked';
import { Sparkles, Loader2, FileType, Keyboard, X, RefreshCw, AlertCircle } from 'lucide-react';
import { detectContentType } from './utils/contentDetector';
import { htmlToMarkdown } from './utils/htmlToMarkdown';
import { Sparkles, Loader2, FileType, Keyboard, X, RefreshCw } from 'lucide-react';
import { useKeyboardNavigation } from './hooks/useKeyboardNavigation';
@@ -94,7 +92,6 @@ const App: React.FC = () => {
const [error, setError] = useState<string | null>(null);
const [showShortcuts, setShowShortcuts] = useState(false);
const [statusMessage, setStatusMessage] = useState('');
const [uploadError, setUploadError] = useState<string | null>(null);
const { uiZoom, setUiZoom, isLoaded } = useSettings();
const { templates, categories, isLoading: templatesLoading, error: templatesError, refresh, openFolder } = useTemplates();
@@ -138,32 +135,9 @@ const App: React.FC = () => {
const handleFileLoaded = (text: string, fullFileName: string = '') => {
setUploadError(null);
const ext = fullFileName.includes('.')
? fullFileName.split('.').pop()?.toLowerCase() || ''
: '';
const displayName = fullFileName.replace(/\.[^/.]+$/, '') || fullFileName;
const detection = detectContentType(text, ext);
if (detection.error) {
setUploadError(detection.error);
return;
}
let processedContent = text;
if (detection.type === 'html') {
try {
processedContent = htmlToMarkdown(text, true);
} catch (err) {
console.error('HTML conversion failed:', err);
}
}
setContent(processedContent);
setInputFileName(displayName);
const handleFileLoaded = (text: string, fileName: string = '') => {
setContent(text);
setInputFileName(fileName);
setAppState(AppState.CONFIG);
};
@@ -200,7 +174,6 @@ const App: React.FC = () => {
setGeneratedHtml('');
setSelectedStyle(null);
setInputFileName('');
setUploadError(null);
};
const handleBackToConfig = () => {
@@ -398,17 +371,6 @@ const App: React.FC = () => {
</motion.p>
</motion.div>
<FileUpload onFileLoaded={handleFileLoaded} />
{uploadError && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="mt-4 max-w-xl mx-auto p-4 bg-red-900/20 border border-red-800 rounded-lg flex items-center gap-3 text-red-200"
role="alert"
>
<AlertCircle size={20} className="flex-shrink-0" aria-hidden="true" />
<span>{uploadError}</span>
</motion.div>
)}
</motion.div>
)}
+1 -1
View File
@@ -23,7 +23,7 @@ export default function ExportOptionsModal({ isOpen, onClose, onExport }: Export
ref={dialogRef}
onClick={handleBackdropClick}
aria-labelledby="export-title"
className="fixed inset-0 z-50 p-4 m-0 w-full h-full border-none bg-black/50 flex items-center justify-center"
className="fixed inset-0 z-50 p-4"
>
<div
className="relative w-full max-w-2xl bg-zinc-900 rounded-2xl shadow-2xl overflow-hidden border border-zinc-700"
+7 -6
View File
@@ -17,9 +17,8 @@ export const FileUpload: React.FC<FileUploadProps> = ({ onFileLoaded }) => {
const handleFile = (file: File) => {
setError(null);
const ext = file.name.split('.').pop()?.toLowerCase() || '';
if (!['md', 'txt', 'markdown', 'html', 'htm'].includes(ext)) {
setError('Please upload a Markdown (.md), HTML (.html), or Text (.txt) file.');
if (!file.name.endsWith('.md') && !file.name.endsWith('.txt') && !file.name.endsWith('.markdown')) {
setError('Please upload a Markdown (.md) or Text (.txt) file.');
return;
}
@@ -27,7 +26,9 @@ export const FileUpload: React.FC<FileUploadProps> = ({ onFileLoaded }) => {
reader.onload = (e) => {
const text = e.target?.result;
if (typeof text === 'string') {
onFileLoaded(text, file.name);
// Extract filename without extension
const fileName = file.name.replace(/\.[^/.]+$/, '');
onFileLoaded(text, fileName);
}
};
reader.onerror = () => setError('Error reading file.');
@@ -131,7 +132,7 @@ export const FileUpload: React.FC<FileUploadProps> = ({ onFileLoaded }) => {
type="file"
className="hidden"
onChange={handleChange}
accept=".md,.txt,.markdown,.html,.htm"
accept=".md,.txt,.markdown"
aria-label="Select file"
/>
@@ -171,7 +172,7 @@ export const FileUpload: React.FC<FileUploadProps> = ({ onFileLoaded }) => {
animate={{ opacity: 1 }}
transition={{ delay: 0.7 }}
>
Markdown, HTML, or Plain Text files
Markdown or Plain Text files
</motion.p>
<motion.p
className="text-xs text-zinc-400 mt-2"
+5 -67
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { ArrowLeft, Download, FileText, CheckCircle2, ExternalLink, Loader2, ZoomIn, ZoomOut, AlertTriangle } from 'lucide-react';
import { ArrowLeft, Download, FileText, CheckCircle2, ExternalLink, Loader2, ZoomIn, ZoomOut } from 'lucide-react';
import { PaperSize } from '../types';
import { StyleOption } from '../types';
import { getPreviewCss } from '../services/templateRenderer';
@@ -142,17 +142,14 @@ export const Preview: React.FC<PreviewProps> = ({
const [showExportModal, setShowExportModal] = useState(false);
const [focusedElement, setFocusedElement] = useState<'back' | 'fonts' | 'save'>('save');
const [exportError, setExportError] = useState<string | null>(null);
const [missingFonts, setMissingFonts] = useState<string[]>([]);
const [showFontWarning, setShowFontWarning] = useState(false);
// Get current style from templates
const style = templates.find(s => s.id === selectedStyleId) || templates[0] || null;
// Extract used fonts for display (heading, body, and code)
// Extract used fonts for display
const usedFonts = style ? Array.from(new Set([
style.typography?.fonts?.heading || style.wordConfig?.heading1?.font || 'Arial',
style.typography?.fonts?.body || style.wordConfig?.body?.font || 'Arial',
style.typography?.fonts?.code || 'JetBrains Mono'
style.typography?.fonts?.body || style.wordConfig?.body?.font || 'Arial'
])).filter(Boolean) : [];
useKeyboardNavigation({
@@ -168,24 +165,6 @@ export const Preview: React.FC<PreviewProps> = ({
}, []);
const handleSave = async () => {
// Check if required fonts are installed using Local Font Access API
let missing: string[] = [];
try {
if ('queryLocalFonts' in window) {
const localFonts = await (window as any).queryLocalFonts();
const installed = new Set(localFonts.map((f: any) => f.family));
missing = usedFonts.filter(font => !installed.has(font));
}
} catch {
// Permission denied or API unavailable - skip check
}
if (missing.length > 0) {
setMissingFonts(missing);
setShowFontWarning(true);
return;
}
setShowExportModal(true);
};
@@ -273,6 +252,7 @@ export const Preview: React.FC<PreviewProps> = ({
// Track blob URL for cleanup
const blobUrlRef = useRef<string | null>(null);
// Render preview whenever dependencies change
useEffect(() => {
if (!iframeRef.current || !style) return;
@@ -321,7 +301,7 @@ export const Preview: React.FC<PreviewProps> = ({
`.page {`,
` width: ${paperSize === 'A4' ? '210mm' : '8.5in'};`,
` min-height: ${paperSize === 'A4' ? '297mm' : '11in'};`,
` padding: ${style.page?.margins ? `${style.page.margins.top}pt ${style.page.margins.right}pt ${style.page.margins.bottom}pt ${style.page.margins.left}pt` : '25mm'};`,
` padding: 25mm;`,
` box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.4);`,
` box-sizing: border-box;`,
` margin: 0 auto;`,
@@ -460,48 +440,6 @@ export const Preview: React.FC<PreviewProps> = ({
<button onClick={() => setExportError(null)} className="ml-3 text-red-400 hover:text-white" aria-label="Dismiss error">&#10005;</button>
</div>
)}
{showFontWarning && (
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 backdrop-blur-sm">
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="bg-zinc-900 border border-zinc-700 rounded-2xl p-6 max-w-md w-full shadow-2xl mx-4"
>
<div className="flex items-center gap-3 mb-4">
<div className="p-2 bg-amber-500/10 rounded-lg text-amber-400">
<AlertTriangle size={20} />
</div>
<h3 className="text-lg font-bold text-white">Missing Fonts</h3>
</div>
<p className="text-zinc-300 text-sm mb-3">
The following fonts are not installed on your system:
</p>
<ul className="space-y-1 mb-4">
{missingFonts.map(font => (
<li key={font} className="text-amber-300 text-sm font-medium">- {font}</li>
))}
</ul>
<p className="text-zinc-400 text-xs mb-6">
Download and install them using the font buttons at the top of the page before opening the exported document.
</p>
<div className="flex gap-3">
<button
onClick={() => { setShowFontWarning(false); setShowExportModal(true); }}
className="flex-1 px-4 py-2.5 text-sm font-medium text-zinc-300 bg-zinc-800 border border-zinc-700 rounded-lg hover:bg-zinc-700 transition-colors"
>
Export Anyway
</button>
<button
onClick={() => setShowFontWarning(false)}
className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-500 transition-colors"
>
Cancel
</button>
</div>
</motion.div>
</div>
)}
</motion.div>
);
};
-17
View File
@@ -229,22 +229,6 @@ export const StyleSelector: React.FC<StyleSelectorProps> = ({
<div class="page">
${SAMPLE_CONTENT}
</div>
<script>
function fitPage() {
var page = document.querySelector('.page');
if (!page) return;
var available = window.innerWidth;
var needed = page.offsetWidth + 80;
if (needed > available) {
document.body.style.zoom = (available / needed).toFixed(3);
} else {
document.body.style.zoom = '1';
}
}
window.addEventListener('load', fitPage);
window.addEventListener('resize', fitPage);
setTimeout(fitPage, 100);
</script>
</body>
</html>
`;
@@ -400,7 +384,6 @@ export const StyleSelector: React.FC<StyleSelectorProps> = ({
role="listbox"
aria-label="Typography styles"
aria-activedescendant={selectedStyle ? `style-${selectedStyle}` : undefined}
className="space-y-2"
>
{filteredStyles.length === 0 ? (
<div className="text-center py-8 text-zinc-400">
-136
View File
@@ -1,136 +0,0 @@
export type ContentType = 'html' | 'markdown' | 'text';
export interface DetectionResult {
type: ContentType;
error?: string;
detectedFormat?: string;
}
const BINARY_SIGNATURES: [string, string][] = [
['%PDF', 'PDF document'],
['PK', 'Word document or ZIP archive'],
['\x89PNG', 'PNG image'],
['\xFF\xD8', 'JPEG image'],
['GIF8', 'GIF image'],
['RIFF', 'media file'],
['Rar!', 'RAR archive'],
];
function detectBinaryFormat(content: string): string | null {
if (content.includes('\0')) {
for (const [sig, name] of BINARY_SIGNATURES) {
if (content.startsWith(sig)) return name;
}
return 'binary file';
}
let nonPrintable = 0;
const len = Math.min(content.length, 512);
for (let i = 0; i < len; i++) {
const code = content.charCodeAt(i);
if (code < 32 && code !== 9 && code !== 10 && code !== 13) {
nonPrintable++;
}
}
return nonPrintable / len > 0.1 ? 'binary file' : null;
}
function stripCodeBlocks(content: string): string {
return content.replace(/```[\s\S]*?```/g, '');
}
const STRUCTURAL_TAG_RE = /<(div|p|table|tr|td|th|thead|tbody|tfoot|ul|ol|li|h[1-6]|section|article|header|footer|nav|main|aside|form|blockquote|pre|dl|dt|dd|figure|figcaption|hr)\b[^>]*>/gi;
const INLINE_TAG_RE = /<(span|b|i|u|strong|em|a|img|br|code|sub|sup|small|mark|del|ins|s|abbr)\b[^>]*>/gi;
function countStructuralTags(content: string): number {
return (content.match(STRUCTURAL_TAG_RE) || []).length;
}
function countInlineTags(content: string): number {
return (content.match(INLINE_TAG_RE) || []).length;
}
function countMarkdownSyntax(content: string): number {
let score = 0;
const lines = content.split('\n');
for (const line of lines) {
const t = line.trim();
if (/^#{1,6}\s/.test(t)) score += 3;
if (/^[-*+]\s/.test(t)) score += 2;
if (/^\d+\.\s/.test(t)) score += 2;
if (/^>\s/.test(t)) score += 2;
if (/^(---|\*\*\*|___)$/.test(t)) score += 2;
if (/^```/.test(t)) score += 3;
}
const sample = content.substring(0, 5000);
score += (sample.match(/\*\*[^*]+\*\*/g) || []).length;
score += (sample.match(/\[([^\]]+)\]\(([^)]+)\)/g) || []).length * 2;
score += (sample.match(/!\[([^\]]*)\]\(([^)]+)\)/g) || []).length * 2;
return score;
}
export function detectContentType(content: string, extension: string): DetectionResult {
if (!content || !content.trim()) {
return { type: 'text' };
}
const binaryFormat = detectBinaryFormat(content);
if (binaryFormat) {
return {
type: 'text',
error: `This appears to be a ${binaryFormat}. TypoGenie accepts Markdown, HTML, and plain text files.`,
detectedFormat: binaryFormat,
};
}
// Full HTML document detection
const trimmed = content.trimStart().toLowerCase();
if (trimmed.startsWith('<!doctype') || trimmed.startsWith('<html')) {
return { type: 'html' };
}
const mdScore = countMarkdownSyntax(content);
// Count HTML tags on content with code blocks stripped to avoid false positives
const stripped = stripCodeBlocks(content);
const structural = countStructuralTags(stripped);
const inline = countInlineTags(stripped);
// Both signals strong - likely markdown with HTML examples
if (structural >= 3 && mdScore >= 5) {
return { type: 'markdown' };
}
// Strong HTML signal
if (structural >= 3) {
return { type: 'html' };
}
// Moderate HTML: few structural tags but heavy inline tags (Blogger/Google Docs style)
if (structural >= 1 && inline >= 10) {
return { type: 'html' };
}
// Strong markdown signal
if (mdScore >= 3) {
return { type: 'markdown' };
}
// Weak HTML with no markdown at all
if (structural >= 1 && mdScore === 0) {
return { type: 'html' };
}
// Extension as tiebreaker
if (extension === 'html' || extension === 'htm') {
return { type: 'html' };
}
if (extension === 'md' || extension === 'markdown') {
return { type: 'markdown' };
}
return { type: 'text' };
}
+78 -360
View File
@@ -3,11 +3,10 @@ import {
Document, Paragraph, TextRun, AlignmentType, HeadingLevel, BorderStyle,
UnderlineType, ShadingType, LevelFormat,
Packer, Table, TableCell, TableRow, WidthType, VerticalAlign,
ExternalHyperlink, TableBorders, ImageRun
ExternalHyperlink, TableBorders
} from 'docx';
import { DocxStyleConfig, PaperSize, TemplateElementStyle } from '../types';
import { resolveColor, resolveFont } from '../services/templateRenderer';
import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
const pt = (points: number) => points * 2;
const inchesToTwips = (inches: number) => Math.round(inches * 1440);
@@ -186,72 +185,6 @@ export const generateDocxDocument = async (
const parser = new DOMParser();
const doc = parser.parseFromString(htmlContent, 'text/html');
// Pre-fetch all images for embedding
const imageCache = new Map<string, { data: Uint8Array; width: number; height: number }>();
const imgElements = doc.querySelectorAll('img');
for (const img of Array.from(imgElements)) {
const src = img.getAttribute('src');
if (!src || src.startsWith('data:')) continue;
// Get display dimensions from HTML attributes (prefer width/height over data-original-*)
const htmlW = parseInt(img.getAttribute('width') || '0');
const htmlH = parseInt(img.getAttribute('height') || '0');
try {
// Step 1: Fetch the image bytes
let data: Uint8Array | null = null;
// Try Tauri HTTP plugin
try {
const resp = await tauriFetch(src, { method: 'GET' });
if (resp.ok) {
data = new Uint8Array(await resp.arrayBuffer());
}
} catch (e1) {
console.warn('tauriFetch failed, trying standard fetch:', e1);
}
// Fallback to standard fetch
if (!data) {
try {
const resp = await globalThis.fetch(src, { mode: 'no-cors' });
// no-cors gives opaque response, try cors mode
const resp2 = await globalThis.fetch(src);
if (resp2.ok) {
data = new Uint8Array(await resp2.arrayBuffer());
}
} catch (e2) {
console.warn('Standard fetch also failed:', e2);
}
}
if (!data || data.length === 0) {
console.warn('No image data received for:', src);
continue;
}
// Step 2: Determine dimensions
let width = htmlW;
let height = htmlH;
if (!width || !height) {
try {
const bitmap = await createImageBitmap(new Blob([data]));
width = bitmap.width;
height = bitmap.height;
bitmap.close();
} catch {
width = width || 600;
height = height || 400;
}
}
imageCache.set(src, { data, width, height });
console.log('Image cached:', src.substring(0, 60), width, 'x', height, data.length, 'bytes');
} catch (err) {
console.warn('Image embed failed for:', src, err);
}
}
const children: (Paragraph | Table)[] = [];
// Track separate ordered lists for independent numbering
@@ -351,26 +284,6 @@ export const generateDocxDocument = async (
return elementConfig?.allCaps || false;
};
// Create an ImageRun from a cached image, scaled to fit the page
// Note: docx library transformation uses PIXELS (it converts to EMU internally)
const createInlineImageRun = (src: string): ImageRun | null => {
const cached = imageCache.get(src);
if (!cached) return null;
let width = cached.width;
let height = cached.height;
// Max width in pixels at 96 DPI
const pageWidthTwips = paperSize === 'A4' ? mmToTwips(210) : inchesToTwips(8.5);
const leftMargin = (options.page?.margins?.left || 72) * 20;
const rightMargin = (options.page?.margins?.right || 72) * 20;
const maxWidthPx = ((pageWidthTwips - leftMargin - rightMargin) / 1440) * 96;
if (width > maxWidthPx) {
const scale = maxWidthPx / width;
width = Math.round(maxWidthPx);
height = Math.round(height * scale);
}
return new ImageRun({ data: cached.data, transformation: { width, height } });
};
// Process text runs with support for links and formatting
const processTextRuns = (element: HTMLElement, baseFormatting: any = {}, elementType?: string): (TextRun | ExternalHyperlink)[] => {
const runs: (TextRun | ExternalHyperlink)[] = [];
@@ -447,18 +360,6 @@ export const generateDocxDocument = async (
} else if (node.nodeType === Node.ELEMENT_NODE) {
const childEl = node as HTMLElement;
const childTag = childEl.tagName.toLowerCase();
if (childTag === 'br') {
linkRuns.push(new TextRun({ break: 1 }) as any);
return;
}
if (childTag === 'img') {
const imgSrc = childEl.getAttribute('src');
if (imgSrc) {
const imgRun = createInlineImageRun(imgSrc);
if (imgRun) linkRuns.push(imgRun as any);
}
return;
}
const childFmt = { ...fmt };
if (childTag === 'strong' || childTag === 'b') childFmt.bold = true;
if (childTag === 'em' || childTag === 'i') childFmt.italics = true;
@@ -570,15 +471,9 @@ export const generateDocxDocument = async (
if (tag === 's' || tag === 'strike') fmt.strike = true;
if (tag === 'sub') fmt.subScript = true;
if (tag === 'sup') fmt.superScript = true;
if (tag === 'br') {
runs.push(new TextRun({ break: 1 }) as any);
return;
}
if (tag === 'code') {
fmt.font = codeFontResolved;
fmt.color = codeTextColor;
if (elements?.code?.size) fmt.size = pt(elements.code.size);
if (codeBgColor) fmt.shading = { fill: codeBgColor, type: ShadingType.CLEAR };
}
// Handle links
@@ -603,18 +498,6 @@ export const generateDocxDocument = async (
} else if (node.nodeType === Node.ELEMENT_NODE) {
const childEl = node as HTMLElement;
const childTag = childEl.tagName.toLowerCase();
if (childTag === 'br') {
linkRuns.push(new TextRun({ break: 1 }) as any);
return;
}
if (childTag === 'img') {
const imgSrc = childEl.getAttribute('src');
if (imgSrc) {
const imgRun = createInlineImageRun(imgSrc);
if (imgRun) linkRuns.push(imgRun as any);
}
return;
}
const childFmt = { ...fmt };
if (childTag === 'strong' || childTag === 'b') childFmt.bold = true;
if (childTag === 'em' || childTag === 'i') childFmt.italics = true;
@@ -639,16 +522,6 @@ export const generateDocxDocument = async (
}
}
// Handle standalone images in text runs
if (tag === 'img') {
const imgSrc = el.getAttribute('src');
if (imgSrc) {
const imgRun = createInlineImageRun(imgSrc);
if (imgRun) runs.push(imgRun as any);
}
return;
}
const style = el.getAttribute('style') || '';
const colorMatch = style.match(/color:\s*#?([a-fA-F0-9]{6})/);
if (colorMatch) fmt.color = colorMatch[1];
@@ -683,16 +556,11 @@ export const generateDocxDocument = async (
spacing: {
before: 0,
after: 0,
line: Math.round(Math.max(cfg?.spacing?.line || 1.2, 1.5) * 240),
line: Math.round((cfg?.spacing?.line || 1.2) * 240),
}
}));
const cellBorders: any = {
top: { style: BorderStyle.NIL, size: 0, color: '000000' },
bottom: { style: BorderStyle.NIL, size: 0, color: '000000' },
left: { style: BorderStyle.NIL, size: 0, color: '000000' },
right: { style: BorderStyle.NIL, size: 0, color: '000000' }
};
const cellBorders: any = {};
if (cfg?.border) {
const b = { color: resolveColorToHex(cfg.border.color) || '000000', style: mapBorderStyle(cfg.border.style), size: cfg.border.width * 8 };
cellBorders.top = b;
@@ -828,27 +696,20 @@ export const generateDocxDocument = async (
console.log('TABLE DOCX: Processing table');
// Get table-level border config - check both generic and per-side borders
const tblCfg = elements?.table;
const defaultBorderColor = isDark ? '444444' : 'CCCCCC';
const makeBorder = (cfg: any, fallbackColor: string) => ({
color: resolveColorToHex(cfg?.color) || fallbackColor,
size: (cfg?.width || 1) * 8,
style: mapBorderStyle(cfg?.style || 'single')
});
// Get table-level border config
const tableBorderConfig = elements?.table?.border;
const tableBorderColor = resolveColorToHex(tableBorderConfig?.color) || (isDark ? '444444' : 'CCCCCC');
const tableBorderWidth = tableBorderConfig?.width || 1;
const tableBorderStyle = mapBorderStyle(tableBorderConfig?.style || 'single');
const noBorder = { style: BorderStyle.NONE, size: 0, color: 'auto' };
const htmlBorderAttr = tableEl.getAttribute('border');
const hasHtmlBorder = htmlBorderAttr && parseInt(htmlBorderAttr) > 0;
const genericBorder = tblCfg?.border ? makeBorder(tblCfg.border, defaultBorderColor) : null;
// Create table-level borders (outer border only by default)
const tableBorders = {
top: tblCfg?.borderTop ? makeBorder(tblCfg.borderTop, defaultBorderColor) : (genericBorder || (hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder)),
bottom: tblCfg?.borderBottom ? makeBorder(tblCfg.borderBottom, defaultBorderColor) : (genericBorder || (hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder)),
left: tblCfg?.borderLeft ? makeBorder(tblCfg.borderLeft, defaultBorderColor) : (genericBorder || (hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder)),
right: tblCfg?.borderRight ? makeBorder(tblCfg.borderRight, defaultBorderColor) : (genericBorder || (hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder)),
insideHorizontal: elements?.th?.borderBottom ? makeBorder(elements.th.borderBottom, defaultBorderColor) :
(hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder),
insideVertical: hasHtmlBorder ? { color: defaultBorderColor, size: 4, style: BorderStyle.SINGLE } : noBorder
top: { color: tableBorderColor, size: tableBorderWidth * 8, style: tableBorderStyle },
bottom: { color: tableBorderColor, size: tableBorderWidth * 8, style: tableBorderStyle },
left: { color: tableBorderColor, size: tableBorderWidth * 8, style: tableBorderStyle },
right: { color: tableBorderColor, size: tableBorderWidth * 8, style: tableBorderStyle },
insideHorizontal: { style: BorderStyle.NIL, size: 0 },
insideVertical: { style: BorderStyle.NIL, size: 0 }
};
for (const rowEl of Array.from(tableEl.querySelectorAll('tr'))) {
@@ -876,11 +737,8 @@ export const generateDocxDocument = async (
bold: isHeader || undefined
});
// Get background: HTML bgcolor attribute takes priority, then template config
const htmlBgColor = cell.getAttribute('bgcolor');
const cellBg = htmlBgColor
? formatColor(htmlBgColor.replace('#', ''))
: resolveColorToHex(cellConfig?.background);
// Get background from config
const cellBg = resolveColorToHex(cellConfig?.background);
console.log(`TABLE CELL DOCX [${isHeader ? 'TH' : 'TD'}]:`, {
text: cell.textContent?.substring(0, 30) + (cell.textContent && cell.textContent.length > 30 ? '...' : ''),
@@ -891,8 +749,7 @@ export const generateDocxDocument = async (
bold: isHeader || undefined
});
// Resolve cell-specific borders from template config only
// (HTML border is handled at table level via insideH/insideV to avoid overriding thick outer borders)
// Resolve cell-specific borders from template
const cellBorders: any = {};
if (cellConfig?.border) {
const b = { color: resolveColorToHex(cellConfig.border.color) || '000000', style: mapBorderStyle(cellConfig.border.style), size: (cellConfig.border.width || 1) * 8 };
@@ -909,10 +766,10 @@ export const generateDocxDocument = async (
cells.push(new TableCell({
children: [new Paragraph({
children: cellRuns.length > 0 ? cellRuns : [new TextRun({ text: cell.textContent || '' })],
alignment: mapAlignment(cellConfig?.align || cell.getAttribute('align') || (cell.getAttribute('style')?.match(/text-align:\s*(\w+)/)?.[1]) || undefined),
alignment: isHeader ? AlignmentType.CENTER : mapAlignment(cellConfig?.align),
spacing: {
after: 0,
line: Math.round(Math.max(elements?.table?.spacing?.line || body.spacing?.line || 1.2, 1.5) * 240)
line: Math.round((body.spacing?.line || 1.2) * 240)
}
})],
shading: cellBg ? { fill: cellBg, type: ShadingType.CLEAR } : undefined,
@@ -1054,8 +911,8 @@ export const generateDocxDocument = async (
}
}
const liSpacingBefore = (elements?.li?.spacing?.before ?? 4) * 20;
const liSpacingAfter = (elements?.li?.spacing?.after ?? 4) * 20;
const liSpacingBefore = (elements?.li?.spacing?.before || 4) * 20;
const liSpacingAfter = (elements?.li?.spacing?.after || 4) * 20;
const liLineHeight = (elements?.li?.spacing?.line || body.spacing?.line || 1.2) * 240;
// Log the actual text runs and their styling
@@ -1258,12 +1115,9 @@ export const generateDocxDocument = async (
return results;
}
// Tables - with spacing paragraphs before/after
// Tables
if (tag === 'table') {
const tblSpacing = elements?.table?.spacing;
results.push(new Paragraph({ spacing: { before: (tblSpacing?.before || 18) * 20, after: 0 }, children: [] }));
results.push(processTable(el));
results.push(new Paragraph({ spacing: { before: 0, after: (tblSpacing?.after || 18) * 20 }, children: [] }));
return results;
}
@@ -1291,144 +1145,78 @@ export const generateDocxDocument = async (
});
}
// Center paragraphs that only contain an image
const isImageOnly = el.querySelector('img') !== null && !el.textContent?.trim();
const pSpacing = elements?.p?.spacing || body.spacing;
// When template spacing is 0, CSS generator skips the margin, so browser default 1em applies
const pAfter = (pSpacing?.after || body.size) * 20;
results.push(new Paragraph({
children: runs.length > 0 ? runs : [new TextRun({ text: el.textContent || '' })],
alignment: isImageOnly ? AlignmentType.CENTER : mapAlignment(elements?.p?.align || body.align),
indent: isImageOnly ? undefined : (elements?.p?.indent ? { firstLine: elements.p.indent * 20 } : undefined),
alignment: mapAlignment(body.align),
spacing: {
before: (pSpacing?.before || 0) * 20,
after: pAfter,
line: Math.round((pSpacing?.line || 1.2) * 240)
before: (body.spacing?.before || 0) * 20,
after: (body.spacing?.after || 0) * 20,
line: Math.round((body.spacing?.line || 1.2) * 240)
},
shading: bgMatch ? { fill: formatColor(resolveColorToHex(bgMatch[1])), type: ShadingType.CLEAR } : undefined
}));
return results;
}
// Blockquotes - process each inner <p> as a separate paragraph with blockquote styling
// Word groups adjacent paragraphs with identical borders, showing top/bottom only on outer edges
// Blockquotes
if (tag === 'blockquote') {
const bqConfig = elements?.blockquote;
const bqFont = bqConfig?.font ? resolveFont(bqConfig.font, fonts || {}) : body.font;
const bqSize = pt(bqConfig?.size || body.size);
const bqColor = formatColor(resolveColorToHex(bqConfig?.color || body.color));
const bqFmt = { font: bqFont, size: bqSize, color: bqColor, italics: bqConfig?.italic !== false };
console.log('DOCX BLOCKQUOTE:', {
font: bqFont, size: bqSize, color: bqColor, childCount: el.children.length
const runs = processTextRuns(el, {
font: bqConfig?.font ? resolveFont(bqConfig.font, fonts || {}) : body.font,
size: pt(bqConfig?.size || body.size),
color: formatColor(resolveColorToHex(bqConfig?.color || body.color)),
italics: true
});
const bqBorder: any = {};
if (bqConfig?.border) {
const b = { color: resolveColorToHex(bqConfig.border.color) || accentColor, space: 6, style: mapBorderStyle(bqConfig.border.style), size: (bqConfig.border.width || 1) * 8 };
bqBorder.top = b; bqBorder.bottom = b; bqBorder.left = b; bqBorder.right = b;
}
if (bqConfig?.borderTop) bqBorder.top = { color: resolveColorToHex(bqConfig.borderTop.color) || accentColor, space: 6, style: mapBorderStyle(bqConfig.borderTop.style), size: (bqConfig.borderTop.width || 1) * 8 };
if (bqConfig?.borderBottom) bqBorder.bottom = { color: resolveColorToHex(bqConfig.borderBottom.color) || accentColor, space: 6, style: mapBorderStyle(bqConfig.borderBottom.style), size: (bqConfig.borderBottom.width || 1) * 8 };
if (bqConfig?.borderLeft) bqBorder.left = { color: resolveColorToHex(bqConfig.borderLeft.color) || accentColor, space: 10, style: mapBorderStyle(bqConfig.borderLeft.style), size: (bqConfig.borderLeft.width || 1) * 8 };
if (bqConfig?.borderRight) bqBorder.right = { color: resolveColorToHex(bqConfig.borderRight.color) || accentColor, space: 6, style: mapBorderStyle(bqConfig.borderRight.style), size: (bqConfig.borderRight.width || 1) * 8 };
const borderColor = resolveColorToHex(bqConfig?.borderLeft?.color) || accentColor;
const borderWidth = bqConfig?.borderLeft?.width || 3;
const bqLine = Math.max(bqConfig?.spacing?.line || body.spacing?.line || 1.2, 1.5);
const bqBorderObj = Object.keys(bqBorder).length > 0 ? bqBorder : undefined;
const bqShading = bqConfig?.background ? { fill: resolveColorToHex(bqConfig.background), type: ShadingType.CLEAR } : undefined;
const bqSpacing = {
before: 0,
after: body.size * 20, // 1em gap between inner paragraphs (matches browser default)
line: Math.round(bqLine * 240)
};
// Process children - each <p> becomes its own paragraph with blockquote styling
const childEls = Array.from(el.children);
const makeBqParagraph = (runs: any[], isFirst: boolean, isLast: boolean, align?: any) => new Paragraph({
children: runs,
alignment: align || mapAlignment(bqConfig?.align),
indent: bqConfig?.indent ? { left: bqConfig.indent * 20 } : undefined,
border: bqBorderObj,
shading: bqShading,
spacing: {
...bqSpacing,
before: isFirst ? (bqConfig?.spacing?.before || 12) * 20 : bqSpacing.before,
after: isLast ? (bqConfig?.spacing?.after || 12) * 20 : bqSpacing.after,
}
});
if (childEls.length === 0) {
// No child elements - process as single paragraph with full blockquote styling
const runs = processTextRuns(el, bqFmt);
results.push(makeBqParagraph(runs, true, true, mapAlignment(bqConfig?.align)));
} else {
childEls.forEach((child, i) => {
const childEl = child as HTMLElement;
const childTagName = childEl.tagName.toLowerCase();
// Nested blockquotes - recurse
if (childTagName === 'blockquote') {
results.push(...processNode(childEl));
return;
}
const isP = childTagName === 'p';
// CSS specificity: <p> rules override inherited blockquote styles
// Only italic inherits since .page p doesn't set font-style
const childFmt = isP ? {
font: body.font,
size: pt(body.size),
color: formatColor(resolveColorToHex(body.color)),
italics: bqConfig?.italic !== false
} : bqFmt;
const childAlign = isP ? mapAlignment(elements?.p?.align || body.align) : mapAlignment(bqConfig?.align);
const runs = processTextRuns(childEl, childFmt);
if (runs.length > 0) {
results.push(makeBqParagraph(runs, i === 0, i === childEls.length - 1, childAlign));
}
const debugKey = 'blockquote-debug';
if (!visitedTags.has(debugKey)) {
visitedTags.add(debugKey);
console.log('DOCX BLOCKQUOTE CONFIG:', {
font: bqConfig?.font,
size: bqConfig?.size,
color: formatColor(resolveColorToHex(bqConfig?.color)),
border: { color: borderColor, width: borderWidth },
background: bqConfig?.background
});
}
return results;
}
// Lists - with spacing before/after the list container
if (tag === 'ul' || tag === 'ol') {
const listCfg = tag === 'ul' ? elements?.ul : elements?.ol;
const listBefore = (listCfg?.spacing?.before ?? 12) * 20;
const listAfter = (listCfg?.spacing?.after ?? 12) * 20;
if (listBefore) results.push(new Paragraph({ spacing: { before: listBefore, after: 0 }, children: [] }));
results.push(...processList(el, tag === 'ol', 0));
if (listAfter) results.push(new Paragraph({ spacing: { before: 0, after: listAfter }, children: [] }));
return results;
}
// Images - embed if fetched, otherwise placeholder
if (tag === 'img') {
const src = el.getAttribute('src');
const cached = src ? imageCache.get(src) : null;
if (cached) {
const imgRun = createInlineImageRun(src);
if (imgRun) {
results.push(new Paragraph({
children: [imgRun],
alignment: AlignmentType.CENTER,
spacing: { before: (elements?.img?.spacing?.before ?? 18) * 20, after: (elements?.img?.spacing?.after ?? 18) * 20 },
}));
results.push(new Paragraph({
children: runs,
indent: { left: 720 },
border: { left: { color: borderColor, space: 10, style: BorderStyle.SINGLE, size: borderWidth * 8 } },
shading: bqConfig?.background ? { fill: resolveColorToHex(bqConfig.background), type: ShadingType.CLEAR } : (isDark ? undefined : { fill: 'F8F8F8', type: ShadingType.CLEAR }),
spacing: {
before: (bqConfig?.spacing?.before || 12) * 20,
after: (bqConfig?.spacing?.after || 12) * 20,
line: Math.round((bqConfig?.spacing?.line || body.spacing?.line || 1.2) * 240)
}
} else {
const alt = el.getAttribute('alt') || '';
const placeholderText = alt ? `[Image: ${alt}]` : '[Image]';
results.push(new Paragraph({
children: [new TextRun({
text: placeholderText,
font: body.font,
size: pt(body.size),
color: formatColor(resolveColorToHex(body.color) || '666666'),
italics: true,
})],
spacing: { before: 120, after: 120 },
}));
}
}));
return results;
}
// Lists
if (tag === 'ul' || tag === 'ol') {
results.push(...processList(el, tag === 'ol', 0));
return results;
}
// Images - produce accessible placeholder text
if (tag === 'img') {
const alt = el.getAttribute('alt') || '';
const placeholderText = alt ? `[Image: ${alt}]` : '[Image]';
results.push(new Paragraph({
children: [new TextRun({
text: placeholderText,
font: body.font,
size: pt(body.size),
color: formatColor(resolveColorToHex(body.color) || '666666'),
italics: true,
})],
spacing: { before: 120, after: 120 },
}));
return results;
}
@@ -1446,82 +1234,12 @@ export const generateDocxDocument = async (
},
spacing: {
before: (hrConfig?.spacing?.before || 12) * 20,
after: 0
after: (hrConfig?.spacing?.after || 12) * 20
}
}));
return results;
}
// Divs - split into paragraphs for text/inline content, recurse for nested block elements
if (tag === 'div') {
const style = el.getAttribute('style') || '';
const alignMatch = style.match(/text-align:\s*(left|center|right|justify)/i);
const divAlign = alignMatch ? alignMatch[1].toLowerCase() : undefined;
const divSpacing = elements?.p?.spacing || body.spacing;
const blockTags = new Set(['div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'ul', 'ol', 'table', 'pre', 'hr']);
// Check if div has nested block elements
const hasBlockChildren = Array.from(el.children).some(c => blockTags.has(c.tagName.toLowerCase()));
if (hasBlockChildren) {
// Split: group consecutive inline/text nodes into paragraphs, recurse block elements
let inlineNodes: Node[] = [];
const flushInline = () => {
if (inlineNodes.length === 0) return;
// Create a temp container in the parsed document to process inline nodes
const temp = doc.createElement('span');
inlineNodes.forEach(n => temp.appendChild(n.cloneNode(true)));
const text = temp.textContent?.trim();
if (text) {
const runs = processTextRuns(temp as any, {
font: body.font, size: pt(body.size), color: formatColor(resolveColorToHex(body.color))
});
if (runs.length > 0) {
results.push(new Paragraph({
children: runs,
alignment: divAlign ? mapAlignment(divAlign === 'justify' ? 'both' : divAlign) : mapAlignment(body.align),
spacing: { before: 0, after: (divSpacing?.after || body.size) * 20, line: Math.round((divSpacing?.line || 1.2) * 240) }
}));
}
}
inlineNodes = [];
};
for (const child of Array.from(el.childNodes)) {
if (child.nodeType === Node.ELEMENT_NODE && blockTags.has((child as HTMLElement).tagName.toLowerCase())) {
flushInline();
results.push(...processNode(child));
} else {
inlineNodes.push(child);
}
}
flushInline();
} else {
// No nested blocks - treat entire div as one paragraph
const hasContent = el.textContent?.trim();
if (hasContent) {
const runs = processTextRuns(el, {
font: body.font, size: pt(body.size), color: formatColor(resolveColorToHex(body.color))
});
if (runs.length > 0) {
const isImgOnly = el.querySelector('img') !== null && !hasContent;
results.push(new Paragraph({
children: runs,
alignment: isImgOnly ? AlignmentType.CENTER : (divAlign ? mapAlignment(divAlign === 'justify' ? 'both' : divAlign) : mapAlignment(body.align)),
spacing: { before: 0, after: (divSpacing?.after || body.size) * 20, line: Math.round((divSpacing?.line || 1.2) * 240) }
}));
return results;
}
}
// No text - process children for images etc.
for (const child of Array.from(el.childNodes)) {
results.push(...processNode(child));
}
}
return results;
}
// Default: process children
for (const child of Array.from(el.childNodes)) {
results.push(...processNode(child));
-89
View File
@@ -1,89 +0,0 @@
import TurndownService from 'turndown';
// @ts-ignore
import { gfm } from 'turndown-plugin-gfm';
export function htmlToMarkdown(html: string, preserveAlignment = false): string {
const turndown = new TurndownService({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
emDelimiter: '*',
strongDelimiter: '**',
});
// Enable GFM tables
turndown.use(gfm);
// Convert Blogger caption tables (image + caption) to image + italic caption
// These are layout tables, not data tables - without this rule, GFM converts them
// to markdown tables which then get data table borders in the export
turndown.addRule('bloggerCaptionTable', {
filter: (node) => {
return node.nodeName === 'TABLE' &&
(node as HTMLElement).classList.contains('tr-caption-container');
},
replacement: (_content, node) => {
const el = node as HTMLElement;
const img = el.querySelector('img');
const caption = el.querySelector('.tr-caption');
let result = '\n\n';
if (img) {
const src = img.getAttribute('src') || '';
const alt = img.getAttribute('alt') || '';
const link = img.closest('a');
if (link) {
result += `[![${alt}](${src})](${link.getAttribute('href')})\n`;
} else {
result += `![${alt}](${src})\n`;
}
}
if (caption && caption.textContent?.trim()) {
result += `\n*${caption.textContent.trim()}*\n`;
}
return result + '\n';
},
});
// Strip meaningless wrapper spans (Blogger, Google Docs, Word paste, etc.)
turndown.addRule('stripDecorativeSpans', {
filter: (node) => {
if (node.nodeName !== 'SPAN') return false;
const style = node.getAttribute('style') || '';
if (!style) return true;
const meaningless = /font-family:\s*inherit|font-size:\s*(medium|inherit)|font-weight:\s*normal|color:\s*(black|inherit)/i;
const props = style.split(';').map(p => p.trim()).filter(Boolean);
return props.length > 0 && props.every(p => meaningless.test(p));
},
replacement: (content) => content,
});
// For HTML content: preserve divs with text-align as raw HTML pass-through
if (preserveAlignment) {
turndown.addRule('preserveAlignment', {
filter: (node) => {
if (node.nodeName !== 'DIV') return false;
const style = node.getAttribute('style') || '';
return /text-align:\s*(right|center)/i.test(style);
},
replacement: (_content, node) => {
const el = node as HTMLElement;
return '\n\n' + el.outerHTML + '\n\n';
},
});
}
let markdown = turndown.turndown(html);
// Clean up excessive blank lines
markdown = markdown.replace(/\n{3,}/g, '\n\n');
// Convert non-breaking spaces to &nbsp; entities (NOT regular spaces)
// Regular spaces would trigger markdown code block detection at 4+ indent
// &nbsp; entities pass through Marked.js as HTML and render as visible spaces
markdown = markdown.replace(/\u00A0/g, '&nbsp;');
// Clean up whitespace-only lines but DON'T strip trailing spaces on content lines
// Turndown uses two trailing spaces for <br> line breaks - stripping them breaks line breaks
markdown = markdown.replace(/^[ \t]+$/gm, '');
return markdown.trim();
}