Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f138f0b4b | ||
|
|
f1d545553b | ||
|
|
ff8e9f9ea3 | ||
|
|
21ed9e122f | ||
|
|
731a76eaf2 | ||
|
|
0cd6b53687 | ||
|
|
e084ff38cb | ||
|
|
97b356a912 | ||
|
|
c4062d66b0 | ||
|
|
4e3ef6ce9c | ||
|
|
d54ac148c0 | ||
|
|
a1293808af | ||
|
|
2cdc9c3976 | ||
|
|
0a409076c3 | ||
|
|
a22bd06b7b | ||
|
|
0cc96e9345 | ||
|
|
24a169d490 | ||
|
|
d20e8cf0ae | ||
|
|
b47571dccd | ||
|
|
3782f0a7fb | ||
|
|
c971c920ce | ||
|
|
37015c8ed6 | ||
|
|
0ff5b4a1b8 | ||
|
|
b6f64d1cf7 | ||
|
|
497407e288 | ||
|
|
ee79ed3f74 | ||
|
|
f8142f995a | ||
|
|
948ec77ae6 | ||
|
|
121fc0a75c | ||
|
|
c9304405ee | ||
|
|
86e59c5421 | ||
|
|
610a87d788 | ||
|
|
da904e6ddd | ||
|
|
c6a5e1f346 | ||
|
|
4498281b7d | ||
|
|
d4d5401293 | ||
|
|
180155b4e0 | ||
|
|
5598e0e538 | ||
|
|
e320238a79 | ||
|
|
09dff9f1fb | ||
|
|
bd2a54bb50 | ||
|
|
0a2a324d77 | ||
|
|
18c0e1736c | ||
|
|
4892b4a6c4 | ||
|
|
9124531c58 | ||
|
|
730e4997eb | ||
|
|
7aae2ce63a | ||
|
|
dafa9c2caa | ||
|
|
1d0c6c2541 | ||
|
|
a1d633772b | ||
|
|
75d6f3d002 | ||
|
|
9f1670a224 | ||
|
|
034d4ffba4 | ||
|
|
7f54320e4c | ||
|
|
473f8e80a6 | ||
|
|
c13e48a615 | ||
|
|
80fecbfab2 | ||
|
|
9345198337 | ||
|
|
c40f5af1fb | ||
|
|
8f75352b15 | ||
|
|
2a23bef0f9 | ||
|
|
61ebc10de9 | ||
|
|
b542c95baa | ||
|
|
66d3210f1a | ||
|
|
2bd384fbd1 | ||
|
|
bc689a6768 | ||
|
|
2ed18d2415 | ||
|
|
3787703aab | ||
|
|
fa44c50dc6 | ||
|
|
70ebb6a767 | ||
|
|
53dd1b5903 | ||
|
|
41e70e389e | ||
|
|
3b926fce12 | ||
|
|
1fc47fe9ae | ||
|
|
84bd5fb674 | ||
|
|
3e49d4ade6 | ||
|
|
57555fa859 | ||
|
|
09365e2d75 | ||
|
|
a6b35d336a | ||
|
|
86a339197f | ||
|
|
9960f63650 | ||
|
|
989d839de8 | ||
|
|
3843788351 | ||
|
|
b7f87e4b7f | ||
|
|
676d634d0b | ||
|
|
3c384f1f1b | ||
|
|
9427444015 | ||
|
|
94dfa0da95 | ||
|
|
bf2028dc0d | ||
|
|
0793893228 | ||
|
|
35c351d55c | ||
|
|
7c6a244976 | ||
|
|
d1d322fa17 | ||
|
|
651671da2d | ||
|
|
991a9ae0ec | ||
|
|
ebdfea0a33 |
No files matched your search
@@ -125,7 +125,7 @@ jobs:
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Automatic Installation (Community Plugins)
|
### Automatic Installation (Community Plugins) - Plugin still waiting for approval
|
||||||
Search for "Typst PDF Export" in Obsidian's Community Plugins tab.
|
Search for "Typst PDF Export" in Obsidian's Community Plugins tab.
|
||||||
|
|
||||||
### Manual Installation
|
### Manual Installation
|
||||||
@@ -138,7 +138,7 @@ jobs:
|
|||||||
### Requirements
|
### Requirements
|
||||||
- [Pandoc](https://pandoc.org/installing.html)
|
- [Pandoc](https://pandoc.org/installing.html)
|
||||||
- [Typst](https://typst.app/docs/installation/)
|
- [Typst](https://typst.app/docs/installation/)
|
||||||
- ImageMagick (optional, for enhanced image processing)
|
- [ImageMagick](https://imagemagick.org) (for enhanced image processing)
|
||||||
|
|
||||||
## Files in this release
|
## Files in this release
|
||||||
- `main.js` - Plugin code with embedded templates
|
- `main.js` - Plugin code with embedded templates
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# Obsidian community plugin
|
||||||
|
|
||||||
|
## Project overview
|
||||||
|
|
||||||
|
- Target: Obsidian Community Plugin (TypeScript → bundled JavaScript).
|
||||||
|
- Entry point: `main.ts` compiled to `main.js` and loaded by Obsidian.
|
||||||
|
- Required release artifacts: `main.js`, `manifest.json`, and optional `styles.css`.
|
||||||
|
|
||||||
|
## Environment & tooling
|
||||||
|
|
||||||
|
- Node.js: use current LTS (Node 18+ recommended).
|
||||||
|
- **Package manager: npm** (required for this sample - `package.json` defines npm scripts and dependencies).
|
||||||
|
- **Bundler: esbuild** (required for this sample - `esbuild.config.mjs` and build scripts depend on it). Alternative bundlers like Rollup or webpack are acceptable for other projects if they bundle all external dependencies into `main.js`.
|
||||||
|
- Types: `obsidian` type definitions.
|
||||||
|
|
||||||
|
**Note**: This sample project has specific technical dependencies on npm and esbuild. If you're creating a plugin from scratch, you can choose different tools, but you'll need to replace the build configuration accordingly.
|
||||||
|
|
||||||
|
### Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dev (watch)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Linting
|
||||||
|
|
||||||
|
- To use eslint install eslint from terminal: `npm install -g eslint`
|
||||||
|
- To use eslint to analyze this project use this command: `eslint main.ts`
|
||||||
|
- eslint will then create a report with suggestions for code improvement by file and line number.
|
||||||
|
- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder: `eslint ./src/`
|
||||||
|
|
||||||
|
## File & folder conventions
|
||||||
|
|
||||||
|
- **Organize code into multiple files**: Split functionality across separate modules rather than putting everything in `main.ts`.
|
||||||
|
- Source lives in `src/`. Keep `main.ts` small and focused on plugin lifecycle (loading, unloading, registering commands).
|
||||||
|
- **Example file structure**:
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.ts # Plugin entry point, lifecycle management
|
||||||
|
settings.ts # Settings interface and defaults
|
||||||
|
commands/ # Command implementations
|
||||||
|
command1.ts
|
||||||
|
command2.ts
|
||||||
|
ui/ # UI components, modals, views
|
||||||
|
modal.ts
|
||||||
|
view.ts
|
||||||
|
utils/ # Utility functions, helpers
|
||||||
|
helpers.ts
|
||||||
|
constants.ts
|
||||||
|
types.ts # TypeScript interfaces and types
|
||||||
|
```
|
||||||
|
- **Do not commit build artifacts**: Never commit `node_modules/`, `main.js`, or other generated files to version control.
|
||||||
|
- Keep the plugin small. Avoid large dependencies. Prefer browser-compatible packages.
|
||||||
|
- Generated output should be placed at the plugin root or `dist/` depending on your build setup. Release artifacts must end up at the top level of the plugin folder in the vault (`main.js`, `manifest.json`, `styles.css`).
|
||||||
|
|
||||||
|
## Manifest rules (`manifest.json`)
|
||||||
|
|
||||||
|
- Must include (non-exhaustive):
|
||||||
|
- `id` (plugin ID; for local dev it should match the folder name)
|
||||||
|
- `name`
|
||||||
|
- `version` (Semantic Versioning `x.y.z`)
|
||||||
|
- `minAppVersion`
|
||||||
|
- `description`
|
||||||
|
- `isDesktopOnly` (boolean)
|
||||||
|
- Optional: `author`, `authorUrl`, `fundingUrl` (string or map)
|
||||||
|
- Never change `id` after release. Treat it as stable API.
|
||||||
|
- Keep `minAppVersion` accurate when using newer APIs.
|
||||||
|
- Canonical requirements are coded here: https://github.com/obsidianmd/obsidian-releases/blob/master/.github/workflows/validate-plugin-entry.yml
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- Manual install for testing: copy `main.js`, `manifest.json`, `styles.css` (if any) to:
|
||||||
|
```
|
||||||
|
<Vault>/.obsidian/plugins/<plugin-id>/
|
||||||
|
```
|
||||||
|
- Reload Obsidian and enable the plugin in **Settings → Community plugins**.
|
||||||
|
|
||||||
|
## Commands & settings
|
||||||
|
|
||||||
|
- Any user-facing commands should be added via `this.addCommand(...)`.
|
||||||
|
- If the plugin has configuration, provide a settings tab and sensible defaults.
|
||||||
|
- Persist settings using `this.loadData()` / `this.saveData()`.
|
||||||
|
- Use stable command IDs; avoid renaming once released.
|
||||||
|
|
||||||
|
## Versioning & releases
|
||||||
|
|
||||||
|
- Bump `version` in `manifest.json` (SemVer) and update `versions.json` to map plugin version → minimum app version.
|
||||||
|
- Create a GitHub release whose tag exactly matches `manifest.json`'s `version`. Do not use a leading `v`.
|
||||||
|
- Attach `manifest.json`, `main.js`, and `styles.css` (if present) to the release as individual assets.
|
||||||
|
- After the initial release, follow the process to add/update your plugin in the community catalog as required.
|
||||||
|
|
||||||
|
## Security, privacy, and compliance
|
||||||
|
|
||||||
|
Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particular:
|
||||||
|
|
||||||
|
- Default to local/offline operation. Only make network requests when essential to the feature.
|
||||||
|
- No hidden telemetry. If you collect optional analytics or call third-party services, require explicit opt-in and document clearly in `README.md` and in settings.
|
||||||
|
- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside of normal releases.
|
||||||
|
- Minimize scope: read/write only what's necessary inside the vault. Do not access files outside the vault.
|
||||||
|
- Clearly disclose any external services used, data sent, and risks.
|
||||||
|
- Respect user privacy. Do not collect vault contents, filenames, or personal information unless absolutely necessary and explicitly consented.
|
||||||
|
- Avoid deceptive patterns, ads, or spammy notifications.
|
||||||
|
- Register and clean up all DOM, app, and interval listeners using the provided `register*` helpers so the plugin unloads safely.
|
||||||
|
|
||||||
|
## UX & copy guidelines (for UI text, commands, settings)
|
||||||
|
|
||||||
|
- Prefer sentence case for headings, buttons, and titles.
|
||||||
|
- Use clear, action-oriented imperatives in step-by-step copy.
|
||||||
|
- Use **bold** to indicate literal UI labels. Prefer "select" for interactions.
|
||||||
|
- Use arrow notation for navigation: **Settings → Community plugins**.
|
||||||
|
- Keep in-app strings short, consistent, and free of jargon.
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- Keep startup light. Defer heavy work until needed.
|
||||||
|
- Avoid long-running tasks during `onload`; use lazy initialization.
|
||||||
|
- Batch disk access and avoid excessive vault scans.
|
||||||
|
- Debounce/throttle expensive operations in response to file system events.
|
||||||
|
|
||||||
|
## Coding conventions
|
||||||
|
|
||||||
|
- TypeScript with `"strict": true` preferred.
|
||||||
|
- **Keep `main.ts` minimal**: Focus only on plugin lifecycle (onload, onunload, addCommand calls). Delegate all feature logic to separate modules.
|
||||||
|
- **Split large files**: If any file exceeds ~200-300 lines, consider breaking it into smaller, focused modules.
|
||||||
|
- **Use clear module boundaries**: Each file should have a single, well-defined responsibility.
|
||||||
|
- Bundle everything into `main.js` (no unbundled runtime deps).
|
||||||
|
- Avoid Node/Electron APIs if you want mobile compatibility; set `isDesktopOnly` accordingly.
|
||||||
|
- Prefer `async/await` over promise chains; handle errors gracefully.
|
||||||
|
|
||||||
|
## Mobile
|
||||||
|
|
||||||
|
- Where feasible, test on iOS and Android.
|
||||||
|
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
|
||||||
|
- Avoid large in-memory structures; be mindful of memory and storage constraints.
|
||||||
|
|
||||||
|
## Agent do/don't
|
||||||
|
|
||||||
|
**Do**
|
||||||
|
- Add commands with stable IDs (don't rename once released).
|
||||||
|
- Provide defaults and validation in settings.
|
||||||
|
- Write idempotent code paths so reload/unload doesn't leak listeners or intervals.
|
||||||
|
- Use `this.register*` helpers for everything that needs cleanup.
|
||||||
|
|
||||||
|
**Don't**
|
||||||
|
- Introduce network calls without an obvious user-facing reason and documentation.
|
||||||
|
- Ship features that require cloud services without clear disclosure and explicit opt-in.
|
||||||
|
- Store or transmit vault contents unless essential and consented.
|
||||||
|
|
||||||
|
## Common tasks
|
||||||
|
|
||||||
|
### Organize code across multiple files
|
||||||
|
|
||||||
|
**main.ts** (minimal, lifecycle only):
|
||||||
|
```ts
|
||||||
|
import { Plugin } from "obsidian";
|
||||||
|
import { MySettings, DEFAULT_SETTINGS } from "./settings";
|
||||||
|
import { registerCommands } from "./commands";
|
||||||
|
|
||||||
|
export default class MyPlugin extends Plugin {
|
||||||
|
settings: MySettings;
|
||||||
|
|
||||||
|
async onload() {
|
||||||
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||||
|
registerCommands(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**settings.ts**:
|
||||||
|
```ts
|
||||||
|
export interface MySettings {
|
||||||
|
enabled: boolean;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_SETTINGS: MySettings = {
|
||||||
|
enabled: true,
|
||||||
|
apiKey: "",
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**commands/index.ts**:
|
||||||
|
```ts
|
||||||
|
import { Plugin } from "obsidian";
|
||||||
|
import { doSomething } from "./my-command";
|
||||||
|
|
||||||
|
export function registerCommands(plugin: Plugin) {
|
||||||
|
plugin.addCommand({
|
||||||
|
id: "do-something",
|
||||||
|
name: "Do something",
|
||||||
|
callback: () => doSomething(plugin),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Add a command
|
||||||
|
|
||||||
|
```ts
|
||||||
|
this.addCommand({
|
||||||
|
id: "your-command-id",
|
||||||
|
name: "Do the thing",
|
||||||
|
callback: () => this.doTheThing(),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Persist settings
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface MySettings { enabled: boolean }
|
||||||
|
const DEFAULT_SETTINGS: MySettings = { enabled: true };
|
||||||
|
|
||||||
|
async onload() {
|
||||||
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||||
|
await this.saveData(this.settings);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Register listeners safely
|
||||||
|
|
||||||
|
```ts
|
||||||
|
this.registerEvent(this.app.workspace.on("file-open", f => { /* ... */ }));
|
||||||
|
this.registerDomEvent(window, "resize", () => { /* ... */ });
|
||||||
|
this.registerInterval(window.setInterval(() => { /* ... */ }, 1000));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- Plugin doesn't load after build: ensure `main.js` and `manifest.json` are at the top level of the plugin folder under `<Vault>/.obsidian/plugins/<plugin-id>/`.
|
||||||
|
- Build issues: if `main.js` is missing, run `npm run build` or `npm run dev` to compile your TypeScript source code.
|
||||||
|
- Commands not appearing: verify `addCommand` runs after `onload` and IDs are unique.
|
||||||
|
- Settings not persisting: ensure `loadData`/`saveData` are awaited and you re-render the UI after changes.
|
||||||
|
- Mobile-only issues: confirm you're not using desktop-only APIs; check `isDesktopOnly` and adjust.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Obsidian sample plugin: https://github.com/obsidianmd/obsidian-sample-plugin
|
||||||
|
- API documentation: https://docs.obsidian.md
|
||||||
|
- Developer policies: https://docs.obsidian.md/Developer+policies
|
||||||
|
- Plugin guidelines: https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines
|
||||||
|
- Style guide: https://help.obsidian.md/style-guide
|
||||||
@@ -5,6 +5,89 @@ All notable changes to the Obsidian Typst PDF Export plugin will be documented i
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [1.3.1] - 2025-01-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Windows Compatibility**: Comprehensive Windows executable detection with platform-specific extensions (.cmd, .bat, .ps1, .exe)
|
||||||
|
- **Dynamic Image Format Support**: FileDiscovery now supports multiple image formats (.png, .jpg, .jpeg, .webp, .gif, .bmp, .tiff)
|
||||||
|
- **Enhanced Pattern Matching**: Five-strategy file discovery system for robust PDF-to-image conversion output detection
|
||||||
|
- **Cross-Platform Font Discovery**: Platform-specific PATH building for improved Typst executable and font detection
|
||||||
|
- **Improved Plugin Isolation**: TempDirectoryManager now uses proper plugin namespacing to prevent conflicts
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Cross-Platform Binary Discovery**: BinaryLocator now includes comprehensive fallback paths for different installation methods
|
||||||
|
- **Vault-Relative Path Consistency**: Fixed all vault.adapter operations to use proper vault-relative paths instead of absolute paths
|
||||||
|
- **Resource Path Resolution**: Removed extra quotes from Pandoc arguments that could break spawn commands on Windows
|
||||||
|
- **Font Cache Corruption Recovery**: Enhanced error handling with automatic cache regeneration and validation
|
||||||
|
- **Template Path Resolution**: Fixed resource path handling in PandocCommandBuilder for better cross-platform compatibility
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Enhanced Error Recovery**: Improved fallback mechanisms and graceful degradation throughout font and file discovery systems
|
||||||
|
- **Platform Detection**: Added platform awareness to caching systems for better cross-platform consistency
|
||||||
|
- **Code Quality**: Improved type safety, error handling, and validation across all affected modules
|
||||||
|
- **Performance**: Optimized file discovery with progressive pattern matching strategies
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- **Path Validation**: Enhanced path sanitization and validation for all file system operations
|
||||||
|
- **Process Spawning**: Improved security in font discovery and binary execution with proper argument handling
|
||||||
|
|
||||||
|
## [1.3.0] - 2024-12-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- PathUtils helper class for centralized path operations and safe Obsidian API usage
|
||||||
|
- Improved Typst error reporting in Pandoc conversion with enhanced diagnostic output
|
||||||
|
- New Typst templates for varied document styles (modern, article, report)
|
||||||
|
- Enhanced README with plugin motivation, development philosophy, and updated badges
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Critical**: Embedded file path resolution issue that caused "File not found" errors for PDFs, images, and documents
|
||||||
|
- Proper vault.adapter integration replacing unsafe type casts throughout codebase
|
||||||
|
- Path handling reliability with comprehensive migration from Node.js fs/path to Obsidian APIs
|
||||||
|
- File existence checks now handle both vault-relative and absolute filesystem paths
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Major Refactoring**: Complete migration from Node.js fs/path to Obsidian vault.adapter APIs
|
||||||
|
- Centralized path utilities replacing unsafe `(app.vault.adapter as unknown as { basePath: string }).basePath` patterns
|
||||||
|
- Improved file system operations security and cross-platform compatibility
|
||||||
|
- Enhanced error handling and path validation across all modules
|
||||||
|
- Updated all 16 core files with consistent, safe path handling practices
|
||||||
|
|
||||||
|
## [1.2.1] - 2025-01-10
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Horizontal Rule Processing**: Resolved YAML parsing conflicts when documents contain horizontal rules (`---`)
|
||||||
|
- Added HorizontalRuleProcessor to transform horizontal rules to asterisks (`***`) before Pandoc processing
|
||||||
|
- Preserved YAML frontmatter by detecting and skipping frontmatter sections during transformation
|
||||||
|
- Added horizontalrule definition to all Typst templates for Pandoc compatibility
|
||||||
|
- **TypeScript Build Errors**: Fixed 23 TypeScript errors in 8 files
|
||||||
|
- Resolved DataAdapter casting issues with proper type assertions
|
||||||
|
- Fixed template variable type issues by adding undefined to union types
|
||||||
|
- Ensured type safety while maintaining full functionality
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Code Quality**: Replaced explicit any types for Obsidian plugin review compliance
|
||||||
|
- Improved type safety throughout the codebase
|
||||||
|
- Enhanced code maintainability with proper type assertions
|
||||||
|
|
||||||
|
## [1.2.0] - 2025-01-10
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Major Refactoring**: Complete modularization of codebase for improved maintainability
|
||||||
|
- Restructured main.ts into focused modules (PluginLifecycle, CommandRegistry, EventHandlers, ExportOrchestrator, FontManager, PathResolver, etc.)
|
||||||
|
- Modularized MarkdownPreprocessor into specialized processors (FrontmatterProcessor, WikilinkProcessor, EmbedProcessor, CalloutProcessor, MetadataExtractor)
|
||||||
|
- Split PandocTypstConverter into PandocCommandBuilder, TypstVariableMapper, and ResourcePathResolver
|
||||||
|
- Separated ExportConfigModal into ModalRenderer and ModalValidator components
|
||||||
|
- Extracted PDF processing utilities (ImageOptimizer, PdfProcessor) from PdfToImageConverter
|
||||||
|
- Improved TypeScript type safety throughout the codebase
|
||||||
|
- Enhanced separation of concerns with ExecutableChecker extraction from DependencyChecker
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Used Obsidian API for more robust file path resolution
|
||||||
|
- Simplified file type classification to properly handle DOCX embedding
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- Unused metadata extraction code (tags/wordCount) for cleaner processing pipeline
|
||||||
|
|
||||||
## [1.1.0]
|
## [1.1.0]
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
# Obsidian Typst PDF Export
|
# Obsidian Typst PDF Export
|
||||||
|
|
||||||
[](https://github.com/akucera/obsidian-typst-pdf-export/releases)
|
[](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://obsidian.md/plugins?id=obsidian-typst-pdf-export)
|
[](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
|
||||||
|
[](https://coderabbit.ai/)
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
@@ -34,7 +35,20 @@ Export Obsidian notes to PDF using the Typst typesetting system. Supports custom
|
|||||||
- **🔍 Font Discovery**: Automatic system font detection and caching
|
- **🔍 Font Discovery**: Automatic system font detection and caching
|
||||||
- **🛡️ Security First**: Path validation and sanitization for safe operations
|
- **🛡️ Security First**: Path validation and sanitization for safe operations
|
||||||
- **📐 Professional Layout**: Paper sizes, margins, typography controls, and more
|
- **📐 Professional Layout**: Paper sizes, margins, typography controls, and more
|
||||||
- **📧 Email Block SUpport**: Supports the YAML Email Block format introduced by the [Email Block plugin](https://github.com/joleaf/obsidian-email-block-plugin)
|
- **📧 Email Block Support**: Supports the YAML Email Block format introduced by the [Email Block plugin](https://github.com/joleaf/obsidian-email-block-plugin)
|
||||||
|
|
||||||
|
## Why This Plugin?
|
||||||
|
|
||||||
|
This plugin was born from frustration with Obsidian's native PDF export, which simply renders notes using the current Obsidian theme. While functional, this approach lacks the professional typesetting quality needed for serious documents.
|
||||||
|
|
||||||
|
The immediate catalyst came from a practical need: my wife required single-page PDFs – documents where the page grows to accommodate all content without pagination breaks. This format is ideal for digital preservation and viewing, keeping everything in one continuous, scrollable document. The native export couldn't provide this. By leveraging Typst's powerful typesetting engine, this plugin delivers:
|
||||||
|
|
||||||
|
- **Professional Quality**: Properly typeset documents that look publication-ready, not just screenshots of notes
|
||||||
|
- **Flexible Page Sizing**: Create single-page PDFs that expand to fit all content – perfect for digital preservation and continuous reading
|
||||||
|
- **True Separation of Concerns**: Content and styling are properly separated, following best practices in document preparation
|
||||||
|
- **Consistent Output**: Documents that look good by default, without requiring theme tweaking
|
||||||
|
|
||||||
|
This transforms Obsidian from a note-taking tool into a complete document preparation system, bridging the gap between quick notes and professional output.
|
||||||
|
|
||||||
## Why Typst?
|
## Why Typst?
|
||||||
|
|
||||||
@@ -48,7 +62,7 @@ Typst offers several advantages over standard PDF export:
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Method 1: Community Plugin Store (Recommended)
|
### Method 1: Community Plugin Store (Recommended) - Still waiting on plugin approval
|
||||||
|
|
||||||
1. Open **Settings** → **Community Plugins**
|
1. Open **Settings** → **Community Plugins**
|
||||||
2. **Disable Safe Mode** if needed
|
2. **Disable Safe Mode** if needed
|
||||||
@@ -310,6 +324,26 @@ The plugin follows a modular architecture with:
|
|||||||
- **Security Layer**: Path validation and sanitization
|
- **Security Layer**: Path validation and sanitization
|
||||||
- **Progress Tracking**: Real-time feedback with cancellation support
|
- **Progress Tracking**: Real-time feedback with cancellation support
|
||||||
|
|
||||||
|
## Development Philosophy
|
||||||
|
|
||||||
|
This plugin was developed using [vibe coding](https://en.wikipedia.org/wiki/Vibe_coding) techniques with AI assistance, but with crucial safeguards to prevent [AI slop](https://en.wikipedia.org/wiki/AI_slop). Unlike typical vibe coding where code is generated without detailed review, this project employed strict quality control measures:
|
||||||
|
|
||||||
|
### AI-Assisted Development with Human Oversight
|
||||||
|
|
||||||
|
- **Controlled Generation**: While large portions of code were AI-generated, every function was reviewed and validated
|
||||||
|
- **Slop Prevention Tools**: Used specialized tools like `slopwatch` and `vibe-check` to catch and prevent low-quality patterns
|
||||||
|
- **Systematic Review**: All AI suggestions were filtered through domain expertise and architectural consistency checks
|
||||||
|
- **Test-Driven Validation**: Comprehensive testing ensured generated code met production standards
|
||||||
|
|
||||||
|
### Quality Control Measures
|
||||||
|
|
||||||
|
- **Pattern Enforcement**: AI was guided by strict architectural patterns and coding standards
|
||||||
|
- **Memory Management**: Used persistent context tools to maintain consistency across development sessions
|
||||||
|
- **Iterative Refinement**: Code went through multiple review-refactor cycles to eliminate "code smell"
|
||||||
|
- **Human Decision Making**: Critical design decisions and architecture remained under human control
|
||||||
|
|
||||||
|
This approach allowed rapid development while maintaining the code quality expected of a production Obsidian plugin. The result is clean, maintainable code that leverages AI's productivity benefits without sacrificing quality or introducing the technical debt typically associated with pure vibe coding.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
Contributions are welcome.
|
Contributions are welcome.
|
||||||
|
|||||||
@@ -86,7 +86,6 @@ const context = await esbuild.context({
|
|||||||
"@lezer/common",
|
"@lezer/common",
|
||||||
"@lezer/highlight",
|
"@lezer/highlight",
|
||||||
"@lezer/lr",
|
"@lezer/lr",
|
||||||
"sharp",
|
|
||||||
...builtins],
|
...builtins],
|
||||||
format: "cjs",
|
format: "cjs",
|
||||||
target: "es2018",
|
target: "es2018",
|
||||||
|
|||||||
+60
-42
@@ -1,50 +1,68 @@
|
|||||||
import { defineConfig, globalIgnores } from "eslint/config";
|
// @ts-check
|
||||||
import typescriptEslint from "@typescript-eslint/eslint-plugin";
|
|
||||||
import globals from "globals";
|
|
||||||
import tsParser from "@typescript-eslint/parser";
|
|
||||||
import path from "node:path";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import js from "@eslint/js";
|
|
||||||
import { FlatCompat } from "@eslint/eslintrc";
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
import eslint from '@eslint/js';
|
||||||
const __dirname = path.dirname(__filename);
|
import globals from 'globals';
|
||||||
const compat = new FlatCompat({
|
import tseslint from 'typescript-eslint';
|
||||||
baseDirectory: __dirname,
|
|
||||||
recommendedConfig: js.configs.recommended,
|
|
||||||
allConfig: js.configs.all
|
|
||||||
});
|
|
||||||
|
|
||||||
export default defineConfig([globalIgnores(["**/node_modules/", "**/main.js"]), {
|
export default tseslint.config(
|
||||||
extends: compat.extends(
|
// Apply ESLint recommended rules
|
||||||
"eslint:recommended",
|
eslint.configs.recommended,
|
||||||
"plugin:@typescript-eslint/eslint-recommended",
|
// Apply TypeScript-ESLint recommended rules
|
||||||
"plugin:@typescript-eslint/recommended",
|
...tseslint.configs.recommended,
|
||||||
),
|
{
|
||||||
|
// Configure language options
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.es2022,
|
||||||
|
},
|
||||||
|
parserOptions: {
|
||||||
|
sourceType: 'module',
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
plugins: {
|
// Configure files to lint
|
||||||
"@typescript-eslint": typescriptEslint,
|
files: ['**/*.ts', '**/*.js', 'main.ts'],
|
||||||
},
|
|
||||||
|
|
||||||
languageOptions: {
|
// Configure rules - incorporating Obsidian sample plugin settings
|
||||||
globals: {
|
rules: {
|
||||||
...globals.node,
|
// Disable base ESLint no-unused-vars in favor of TypeScript version
|
||||||
},
|
'no-unused-vars': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
|
||||||
|
|
||||||
parser: tsParser,
|
// Allow @ts-ignore comments (useful for Obsidian API quirks)
|
||||||
ecmaVersion: 5,
|
'@typescript-eslint/ban-ts-comment': 'off',
|
||||||
sourceType: "module",
|
|
||||||
},
|
|
||||||
|
|
||||||
rules: {
|
// Allow prototype builtins usage
|
||||||
"no-unused-vars": "off",
|
'no-prototype-builtins': 'off',
|
||||||
|
|
||||||
"@typescript-eslint/no-unused-vars": ["error", {
|
// Allow empty functions (common in plugin architecture)
|
||||||
args: "none",
|
'@typescript-eslint/no-empty-function': 'off',
|
||||||
}],
|
|
||||||
|
|
||||||
"@typescript-eslint/ban-ts-comment": "off",
|
// Allow require() imports (Node.js environment with mixed modules)
|
||||||
"no-prototype-builtins": "off",
|
'@typescript-eslint/no-require-imports': 'off',
|
||||||
"@typescript-eslint/no-empty-function": "off",
|
'@typescript-eslint/no-var-requires': 'off',
|
||||||
},
|
|
||||||
}]);
|
// Obsidian plugins often use 'any' type for API flexibility
|
||||||
|
'@typescript-eslint/no-explicit-any': 'warn',
|
||||||
|
|
||||||
|
// Allow lexical declarations in case blocks
|
||||||
|
'no-case-declarations': 'off',
|
||||||
|
|
||||||
|
// Prefer const is good but not critical for existing code
|
||||||
|
'prefer-const': 'warn',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Global ignores configuration
|
||||||
|
ignores: [
|
||||||
|
'node_modules/**',
|
||||||
|
'main.js',
|
||||||
|
'dist/**',
|
||||||
|
'build/**',
|
||||||
|
'*.min.js',
|
||||||
|
'coverage/**',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
);
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"id": "typst-pdf-export",
|
"id": "typst-pdf-export",
|
||||||
"name": "Typst PDF Export",
|
"name": "Typst PDF Export",
|
||||||
"version": "1.1.0",
|
"version": "1.3.0",
|
||||||
"minAppVersion": "1.9.12",
|
"minAppVersion": "1.9.12",
|
||||||
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
|
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
|
||||||
"author": "Alexander Kucera",
|
"author": "Alexander Kucera",
|
||||||
|
|||||||
Generated
+332
-13
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "obsidian-typst-pdf-export",
|
"name": "obsidian-typst-pdf-export",
|
||||||
"version": "1.1.0",
|
"version": "1.2.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "obsidian-typst-pdf-export",
|
"name": "obsidian-typst-pdf-export",
|
||||||
"version": "1.1.0",
|
"version": "1.2.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"gray-matter": "^4.0.3",
|
"gray-matter": "^4.0.3",
|
||||||
@@ -24,7 +24,8 @@
|
|||||||
"globals": "^16.3.0",
|
"globals": "^16.3.0",
|
||||||
"obsidian": "latest",
|
"obsidian": "latest",
|
||||||
"tslib": "2.4.0",
|
"tslib": "2.4.0",
|
||||||
"typescript": "4.7.4"
|
"typescript": "^5.9.2",
|
||||||
|
"typescript-eslint": "^8.43.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@codemirror/state": {
|
"node_modules/@codemirror/state": {
|
||||||
@@ -432,7 +433,6 @@
|
|||||||
"integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==",
|
"integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"eslint-visitor-keys": "^3.4.3"
|
"eslint-visitor-keys": "^3.4.3"
|
||||||
},
|
},
|
||||||
@@ -452,7 +452,6 @@
|
|||||||
"integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==",
|
"integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
|
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
|
||||||
}
|
}
|
||||||
@@ -832,6 +831,42 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@typescript-eslint/project-service": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-htB/+D/BIGoNTQYffZw4uM4NzzuolCoaA/BusuSIcC8YjmBYQioew5VUZAYdAETPjeed0hqCaW7EHg+Robq8uw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/tsconfig-utils": "^8.43.0",
|
||||||
|
"@typescript-eslint/types": "^8.43.0",
|
||||||
|
"debug": "^4.3.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript-eslint/project-service/node_modules/@typescript-eslint/types": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-vQ2FZaxJpydjSZJKiSW/LJsabFFvV7KgLC5DiLhkBcykhQj8iK9BOaDmQt74nnKdLvceM5xmhaTF+pLekrxEkw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@typescript-eslint/scope-manager": {
|
"node_modules/@typescript-eslint/scope-manager": {
|
||||||
"version": "5.29.0",
|
"version": "5.29.0",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.29.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.29.0.tgz",
|
||||||
@@ -850,6 +885,23 @@
|
|||||||
"url": "https://opencollective.com/typescript-eslint"
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@typescript-eslint/tsconfig-utils": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-ALC2prjZcj2YqqL5X/bwWQmHA2em6/94GcbB/KKu5SX3EBDOsqztmmX1kMkvAJHzxk7TazKzJfFiEIagNV3qEA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@typescript-eslint/type-utils": {
|
"node_modules/@typescript-eslint/type-utils": {
|
||||||
"version": "5.29.0",
|
"version": "5.29.0",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.29.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.29.0.tgz",
|
||||||
@@ -2510,8 +2562,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
|
||||||
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
|
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/gray-matter": {
|
"node_modules/gray-matter": {
|
||||||
"version": "4.0.3",
|
"version": "4.0.3",
|
||||||
@@ -3101,8 +3152,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
|
||||||
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
|
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/node-abi": {
|
"node_modules/node-abi": {
|
||||||
"version": "3.75.0",
|
"version": "3.75.0",
|
||||||
@@ -4057,6 +4107,19 @@
|
|||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true
|
"optional": true
|
||||||
},
|
},
|
||||||
|
"node_modules/ts-api-utils": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.12"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=4.8.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tslib": {
|
"node_modules/tslib": {
|
||||||
"version": "2.4.0",
|
"version": "2.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz",
|
||||||
@@ -4128,9 +4191,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/typescript": {
|
"node_modules/typescript": {
|
||||||
"version": "4.7.4",
|
"version": "5.9.2",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
|
||||||
"integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==",
|
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -4138,7 +4201,263 @@
|
|||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=4.2.0"
|
"node": ">=14.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-FyRGJKUGvcFekRRcBKFBlAhnp4Ng8rhe8tuvvkR9OiU0gfd4vyvTRQHEckO6VDlH57jbeUQem2IpqPq9kLJH+w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/eslint-plugin": "8.43.0",
|
||||||
|
"@typescript-eslint/parser": "8.43.0",
|
||||||
|
"@typescript-eslint/typescript-estree": "8.43.0",
|
||||||
|
"@typescript-eslint/utils": "8.43.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"eslint": "^8.57.0 || ^9.0.0",
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/eslint-plugin": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-8tg+gt7ENL7KewsKMKDHXR1vm8tt9eMxjJBYINf6swonlWgkYn5NwyIgXpbbDxTNU5DgpDFfj95prcTq2clIQQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@eslint-community/regexpp": "^4.10.0",
|
||||||
|
"@typescript-eslint/scope-manager": "8.43.0",
|
||||||
|
"@typescript-eslint/type-utils": "8.43.0",
|
||||||
|
"@typescript-eslint/utils": "8.43.0",
|
||||||
|
"@typescript-eslint/visitor-keys": "8.43.0",
|
||||||
|
"graphemer": "^1.4.0",
|
||||||
|
"ignore": "^7.0.0",
|
||||||
|
"natural-compare": "^1.4.0",
|
||||||
|
"ts-api-utils": "^2.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@typescript-eslint/parser": "^8.43.0",
|
||||||
|
"eslint": "^8.57.0 || ^9.0.0",
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/parser": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-B7RIQiTsCBBmY+yW4+ILd6mF5h1FUwJsVvpqkrgpszYifetQ2Ke+Z4u6aZh0CblkUGIdR59iYVyXqqZGkZ3aBw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/scope-manager": "8.43.0",
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"@typescript-eslint/typescript-estree": "8.43.0",
|
||||||
|
"@typescript-eslint/visitor-keys": "8.43.0",
|
||||||
|
"debug": "^4.3.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"eslint": "^8.57.0 || ^9.0.0",
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/scope-manager": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-daSWlQ87ZhsjrbMLvpuuMAt3y4ba57AuvadcR7f3nl8eS3BjRc8L9VLxFLk92RL5xdXOg6IQ+qKjjqNEimGuAg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"@typescript-eslint/visitor-keys": "8.43.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/type-utils": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-qaH1uLBpBuBBuRf8c1mLJ6swOfzCXryhKND04Igr4pckzSEW9JX5Aw9AgW00kwfjWJF0kk0ps9ExKTfvXfw4Qg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"@typescript-eslint/typescript-estree": "8.43.0",
|
||||||
|
"@typescript-eslint/utils": "8.43.0",
|
||||||
|
"debug": "^4.3.4",
|
||||||
|
"ts-api-utils": "^2.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"eslint": "^8.57.0 || ^9.0.0",
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/types": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-vQ2FZaxJpydjSZJKiSW/LJsabFFvV7KgLC5DiLhkBcykhQj8iK9BOaDmQt74nnKdLvceM5xmhaTF+pLekrxEkw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/typescript-estree": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-7Vv6zlAhPb+cvEpP06WXXy/ZByph9iL6BQRBDj4kmBsW98AqEeQHlj/13X+sZOrKSo9/rNKH4Ul4f6EICREFdw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/project-service": "8.43.0",
|
||||||
|
"@typescript-eslint/tsconfig-utils": "8.43.0",
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"@typescript-eslint/visitor-keys": "8.43.0",
|
||||||
|
"debug": "^4.3.4",
|
||||||
|
"fast-glob": "^3.3.2",
|
||||||
|
"is-glob": "^4.0.3",
|
||||||
|
"minimatch": "^9.0.4",
|
||||||
|
"semver": "^7.6.0",
|
||||||
|
"ts-api-utils": "^2.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/utils": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-S1/tEmkUeeswxd0GGcnwuVQPFWo8NzZTOMxCvw8BX7OMxnNae+i8Tm7REQen/SwUIPoPqfKn7EaZ+YLpiB3k9g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@eslint-community/eslint-utils": "^4.7.0",
|
||||||
|
"@typescript-eslint/scope-manager": "8.43.0",
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"@typescript-eslint/typescript-estree": "8.43.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"eslint": "^8.57.0 || ^9.0.0",
|
||||||
|
"typescript": ">=4.8.4 <6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/@typescript-eslint/visitor-keys": {
|
||||||
|
"version": "8.43.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.43.0.tgz",
|
||||||
|
"integrity": "sha512-T+S1KqRD4sg/bHfLwrpF/K3gQLBM1n7Rp7OjjikjTEssI2YJzQpi5WXoynOaQ93ERIuq3O8RBTOUYDKszUCEHw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@typescript-eslint/types": "8.43.0",
|
||||||
|
"eslint-visitor-keys": "^4.2.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/brace-expansion": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"balanced-match": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/eslint-visitor-keys": {
|
||||||
|
"version": "4.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
|
||||||
|
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/ignore": {
|
||||||
|
"version": "7.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
|
||||||
|
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript-eslint/node_modules/minimatch": {
|
||||||
|
"version": "9.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
|
||||||
|
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"brace-expansion": "^2.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16 || 14 >=14.17"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/uri-js": {
|
"node_modules/uri-js": {
|
||||||
|
|||||||
+7
-4
@@ -1,11 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "obsidian-typst-pdf-export",
|
"name": "obsidian-typst-pdf-export",
|
||||||
"version": "1.1.0",
|
"version": "1.3.0",
|
||||||
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
|
"description": "Exports a note or collection of notes to a pretty Typst PDF.",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node esbuild.config.mjs",
|
"typecheck": "tsc --noEmit",
|
||||||
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
|
"lint": "eslint src/ main.ts",
|
||||||
|
"dev": "npm run typecheck && node esbuild.config.mjs",
|
||||||
|
"build": "npm run typecheck && npm run lint && node esbuild.config.mjs production",
|
||||||
"package": "node scripts/package-plugin.js",
|
"package": "node scripts/package-plugin.js",
|
||||||
"version": "node version-bump.mjs && git add manifest.json versions.json"
|
"version": "node version-bump.mjs && git add manifest.json versions.json"
|
||||||
},
|
},
|
||||||
@@ -30,7 +32,8 @@
|
|||||||
"globals": "^16.3.0",
|
"globals": "^16.3.0",
|
||||||
"obsidian": "latest",
|
"obsidian": "latest",
|
||||||
"tslib": "2.4.0",
|
"tslib": "2.4.0",
|
||||||
"typescript": "4.7.4"
|
"typescript": "^5.9.2",
|
||||||
|
"typescript-eslint": "^8.43.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"gray-matter": "^4.0.3",
|
"gray-matter": "^4.0.3",
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
# CodeRabbit Suggestions Implementation Plan
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
This plan documents the CodeRabbit review suggestions from PR #5 that should be implemented to improve cross-platform compatibility, code quality, and robustness of the Obsidian Typst PDF Export plugin.
|
||||||
|
|
||||||
|
## Implementation Tasks
|
||||||
|
|
||||||
|
### 1. ~~manifest.json - Version Compatibility~~ **SKIPPED**
|
||||||
|
- **Current**: `minAppVersion: "1.9.12"`
|
||||||
|
- **Decision**: Keep as-is - only up-to-date users should use the plugin
|
||||||
|
- **Status**: ✅ Skipped per user preference
|
||||||
|
|
||||||
|
### 2. PandocCommandBuilder.ts - Path Quoting Fix
|
||||||
|
**File**: `src/converters/pandoc/PandocCommandBuilder.ts`
|
||||||
|
**Line**: 113
|
||||||
|
**Issue**: Extra quotes around path can break spawn command
|
||||||
|
**Current Code**:
|
||||||
|
```typescript
|
||||||
|
args.push('--resource-path', `"${templatesDir}"`);
|
||||||
|
```
|
||||||
|
**Fix**:
|
||||||
|
```typescript
|
||||||
|
args.push('--resource-path', templatesDir);
|
||||||
|
```
|
||||||
|
**Reason**: The spawn command handles quoting automatically. Manual quotes can cause issues, especially on Windows.
|
||||||
|
|
||||||
|
### 3. ResourcePathResolver.ts - Vault-Relative Paths
|
||||||
|
**File**: `src/converters/pandoc/ResourcePathResolver.ts`
|
||||||
|
**Issues**:
|
||||||
|
- `adapter.list()` should use vault-relative paths, not absolute
|
||||||
|
- Should return absolute paths for external tools
|
||||||
|
- Need better error handling
|
||||||
|
|
||||||
|
**Changes Needed**:
|
||||||
|
- Ensure all `adapter.list()` calls use vault-relative paths
|
||||||
|
- Convert to absolute paths only when returning for external tool consumption
|
||||||
|
- Add try-catch blocks around path operations
|
||||||
|
- Validate paths before adding to resource list
|
||||||
|
|
||||||
|
### 4. BinaryLocator.ts - Windows Compatibility
|
||||||
|
**File**: `src/converters/pdf/BinaryLocator.ts`
|
||||||
|
**Issues**:
|
||||||
|
- Missing Windows executable extensions (.cmd, .bat, .ps1)
|
||||||
|
- No platform-specific binary detection
|
||||||
|
- Limited fallback mechanisms
|
||||||
|
|
||||||
|
**Changes Needed**:
|
||||||
|
```typescript
|
||||||
|
// Add Windows-specific executable detection
|
||||||
|
const windowsExtensions = process.platform === 'win32'
|
||||||
|
? ['.cmd', '.bat', '.ps1', '.exe']
|
||||||
|
: [''];
|
||||||
|
|
||||||
|
// Check for platform-specific binaries
|
||||||
|
const binaryName = process.platform === 'win32'
|
||||||
|
? 'pdf2img.cmd'
|
||||||
|
: 'pdf2img';
|
||||||
|
|
||||||
|
// Add multiple fallback paths for different installation methods
|
||||||
|
const fallbackPaths = [
|
||||||
|
path.join(pluginDir, 'node_modules', '.bin'),
|
||||||
|
path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'),
|
||||||
|
// Windows-specific paths
|
||||||
|
path.join(process.env.APPDATA || '', 'npm'),
|
||||||
|
path.join(process.env.LOCALAPPDATA || '', 'npm-cache')
|
||||||
|
];
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. FileDiscovery.ts - Dynamic File Extension Support
|
||||||
|
**File**: `src/converters/pdf/FileDiscovery.ts`
|
||||||
|
**Issues**:
|
||||||
|
- Hardcoded to only look for '.png' files
|
||||||
|
- Should support multiple image formats
|
||||||
|
- Pattern matching too restrictive
|
||||||
|
|
||||||
|
**Changes Needed**:
|
||||||
|
```typescript
|
||||||
|
// Dynamic extension support
|
||||||
|
const supportedImageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];
|
||||||
|
|
||||||
|
// Update file filtering
|
||||||
|
const imageFiles = files.filter(f =>
|
||||||
|
supportedImageExtensions.some(ext => f.toLowerCase().endsWith(ext))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Improve pattern matching to handle more filename variations
|
||||||
|
private static matchFilePattern(files: string[], expectedFileName: string): string | null {
|
||||||
|
const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
|
||||||
|
|
||||||
|
// Try multiple matching strategies
|
||||||
|
// 1. Exact match
|
||||||
|
// 2. Base name match with any supported extension
|
||||||
|
// 3. Sanitized pattern match
|
||||||
|
// 4. Fuzzy match for pdf2img output patterns
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. ExportOrchestrator.ts - Plugin Name for Temp Dir
|
||||||
|
**File**: `src/plugin/ExportOrchestrator.ts`
|
||||||
|
**Line**: 147
|
||||||
|
**Issue**: TempDirectoryManager should receive plugin name for proper namespacing
|
||||||
|
|
||||||
|
**Current Code**:
|
||||||
|
```typescript
|
||||||
|
const tempManager = new TempDirectoryManager({
|
||||||
|
vaultPath: vaultPath,
|
||||||
|
configDir: this.plugin.app.vault.configDir,
|
||||||
|
app: this.plugin.app
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fix**:
|
||||||
|
```typescript
|
||||||
|
const tempManager = new TempDirectoryManager({
|
||||||
|
vaultPath: vaultPath,
|
||||||
|
configDir: this.plugin.app.vault.configDir,
|
||||||
|
app: this.plugin.app,
|
||||||
|
pluginName: this.plugin.manifest.id
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. FontManager.ts - Consistent Path Handling
|
||||||
|
**File**: `src/plugin/FontManager.ts`
|
||||||
|
**Issues**:
|
||||||
|
- Mixed use of absolute and vault-relative paths
|
||||||
|
- Potential issues with cross-platform font discovery
|
||||||
|
- Need better validation
|
||||||
|
|
||||||
|
**Changes Needed**:
|
||||||
|
- Ensure all vault.adapter operations use vault-relative paths
|
||||||
|
- Add platform-specific font discovery improvements
|
||||||
|
- Validate font paths before caching
|
||||||
|
- Add error recovery for corrupted cache
|
||||||
|
|
||||||
|
### 8. General Improvements
|
||||||
|
|
||||||
|
#### Error Handling
|
||||||
|
- Add comprehensive try-catch blocks
|
||||||
|
- Provide meaningful error messages to users
|
||||||
|
- Log detailed errors for debugging
|
||||||
|
- Implement graceful degradation
|
||||||
|
|
||||||
|
#### TypeScript Type Safety
|
||||||
|
- Remove any remaining `any` types
|
||||||
|
- Add proper type guards
|
||||||
|
- Use strict null checks
|
||||||
|
- Validate external data
|
||||||
|
|
||||||
|
#### Resource Cleanup
|
||||||
|
- Ensure temp files are always cleaned up
|
||||||
|
- Add finally blocks for cleanup operations
|
||||||
|
- Implement proper abort handling
|
||||||
|
- Clean up on plugin unload
|
||||||
|
|
||||||
|
#### Cross-Platform Testing Matrix
|
||||||
|
- Windows 10/11
|
||||||
|
- macOS (Intel and Apple Silicon)
|
||||||
|
- Linux (Ubuntu/Debian)
|
||||||
|
- Different Obsidian versions
|
||||||
|
|
||||||
|
## Implementation Order
|
||||||
|
|
||||||
|
1. **Critical Path Fixes** (High Priority)
|
||||||
|
- PandocCommandBuilder.ts - Remove path quotes
|
||||||
|
- ResourcePathResolver.ts - Fix path handling
|
||||||
|
- PathUtils.fileExists - Already fixed in previous commit
|
||||||
|
|
||||||
|
2. **Cross-Platform Compatibility** (Medium Priority)
|
||||||
|
- BinaryLocator.ts - Windows support
|
||||||
|
- FileDiscovery.ts - Dynamic extensions
|
||||||
|
- FontManager.ts - Platform-specific paths
|
||||||
|
|
||||||
|
3. **Code Quality** (Lower Priority)
|
||||||
|
- ExportOrchestrator.ts - Plugin namespacing
|
||||||
|
- General error handling improvements
|
||||||
|
- TypeScript type safety enhancements
|
||||||
|
|
||||||
|
## Testing Plan
|
||||||
|
|
||||||
|
### Unit Tests Needed
|
||||||
|
- Path resolution with various input formats
|
||||||
|
- Binary detection on different platforms
|
||||||
|
- File discovery with multiple extensions
|
||||||
|
- Font caching and retrieval
|
||||||
|
|
||||||
|
### Integration Tests
|
||||||
|
- Full export pipeline on Windows/Mac/Linux
|
||||||
|
- Embedded file resolution
|
||||||
|
- Template loading and processing
|
||||||
|
- Temp directory cleanup
|
||||||
|
|
||||||
|
### Manual Testing Checklist
|
||||||
|
- [ ] Export with embedded PDFs
|
||||||
|
- [ ] Export with various image formats
|
||||||
|
- [ ] Export with custom templates
|
||||||
|
- [ ] Export on Windows
|
||||||
|
- [ ] Export on macOS
|
||||||
|
- [ ] Export on Linux
|
||||||
|
- [ ] Verify temp directory cleanup
|
||||||
|
- [ ] Test cancellation during export
|
||||||
|
- [ ] Test with special characters in paths
|
||||||
|
|
||||||
|
## Expected Outcomes
|
||||||
|
|
||||||
|
1. **Improved Reliability**
|
||||||
|
- Fewer "file not found" errors
|
||||||
|
- Better error messages
|
||||||
|
- Graceful degradation
|
||||||
|
|
||||||
|
2. **Better Cross-Platform Support**
|
||||||
|
- Windows users can use the plugin
|
||||||
|
- Consistent behavior across platforms
|
||||||
|
- Platform-specific optimizations
|
||||||
|
|
||||||
|
3. **Cleaner Codebase**
|
||||||
|
- Better TypeScript types
|
||||||
|
- Consistent error handling
|
||||||
|
- Improved maintainability
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- All changes should maintain backward compatibility
|
||||||
|
- Test thoroughly before release
|
||||||
|
- Document any breaking changes
|
||||||
|
- Consider adding automated tests in future
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Original PR: https://github.com/AlexKucera/obsidian-typst-pdf-export/pull/5
|
||||||
|
- CodeRabbit Review Comments: See PR comments
|
||||||
|
- Obsidian API Documentation: https://docs.obsidian.md/
|
||||||
|
- TypeScript Best Practices: https://www.typescriptlang.org/docs/handbook/
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -3,26 +3,20 @@
|
|||||||
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine
|
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { spawn, ChildProcess } from 'child_process';
|
|
||||||
import * as fs from 'fs';
|
|
||||||
import { promises as fsPromises } from 'fs';
|
|
||||||
import * as path from 'path';
|
|
||||||
import * as os from 'os';
|
|
||||||
import { mapToTypstPaperSize } from '../utils/paperSizeMapper';
|
|
||||||
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
|
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
|
||||||
import type { obsidianTypstPDFExportSettings } from '../core/settings';
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
|
||||||
|
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
|
||||||
|
import { PandocExecutor } from './pandoc/PandocExecutor';
|
||||||
|
|
||||||
export class PandocTypstConverter {
|
export class PandocTypstConverter {
|
||||||
private tempDir: string | null = null;
|
private tempDir: string | null = null;
|
||||||
private cleanupHandlers: (() => void)[] = [];
|
private cleanupHandlers: (() => void)[] = [];
|
||||||
private plugin: any; // Will be properly typed when we refactor the main plugin class
|
private plugin: obsidianTypstPDFExport;
|
||||||
|
private commandBuilder: PandocCommandBuilder;
|
||||||
// Cache for directory scanning optimization
|
private pandocExecutor: PandocExecutor;
|
||||||
private resourcePathCache: string[] = [];
|
|
||||||
private resourcePathCacheTimestamp: number = 0;
|
|
||||||
private resourcePathCacheVaultPath: string = '';
|
|
||||||
private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new PandocTypstConverter instance
|
* Create a new PandocTypstConverter instance
|
||||||
@@ -31,11 +25,13 @@ export class PandocTypstConverter {
|
|||||||
* @param typstSettings Settings specific to Typst engine
|
* @param typstSettings Settings specific to Typst engine
|
||||||
*/
|
*/
|
||||||
constructor(
|
constructor(
|
||||||
plugin: any,
|
plugin: obsidianTypstPDFExport,
|
||||||
private pandocOptions: PandocOptions = {},
|
private pandocOptions: PandocOptions = {},
|
||||||
private typstSettings: TypstSettings = {}
|
private typstSettings: TypstSettings = {}
|
||||||
) {
|
) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
this.commandBuilder = new PandocCommandBuilder(plugin);
|
||||||
|
this.pandocExecutor = new PandocExecutor(plugin);
|
||||||
// Set up cleanup handlers for process termination
|
// Set up cleanup handlers for process termination
|
||||||
this.setupCleanup();
|
this.setupCleanup();
|
||||||
}
|
}
|
||||||
@@ -58,13 +54,21 @@ export class PandocTypstConverter {
|
|||||||
// Create temporary directory if needed
|
// Create temporary directory if needed
|
||||||
await this.ensureTempDirectory();
|
await this.ensureTempDirectory();
|
||||||
|
|
||||||
|
// Add temp directory to pandocOptions for command builder
|
||||||
|
const optionsWithTempDir = {
|
||||||
|
...this.pandocOptions,
|
||||||
|
tempDir: this.tempDir || undefined,
|
||||||
|
typstSettings: this.typstSettings,
|
||||||
|
cleanupHandlers: this.cleanupHandlers
|
||||||
|
};
|
||||||
|
|
||||||
// Build pandoc arguments
|
// Build pandoc arguments
|
||||||
const args = await this.buildPandocArgs(inputPath, outputPath);
|
const args = await this.commandBuilder.buildPandocArgs(inputPath, outputPath, optionsWithTempDir);
|
||||||
|
|
||||||
progressCallback?.('Executing Pandoc with Typst engine...', 30);
|
progressCallback?.('Executing Pandoc with Typst engine...', 30);
|
||||||
|
|
||||||
// Execute pandoc process
|
// Execute pandoc process
|
||||||
const result = await this.executePandoc(args, progressCallback);
|
const result = await this.pandocExecutor.executePandoc(args, this.pandocOptions, progressCallback);
|
||||||
|
|
||||||
// Add the output path to the result if successful
|
// Add the output path to the result if successful
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
@@ -88,42 +92,43 @@ export class PandocTypstConverter {
|
|||||||
* Convert markdown content to PDF
|
* Convert markdown content to PDF
|
||||||
*/
|
*/
|
||||||
async convertMarkdownToPDF(
|
async convertMarkdownToPDF(
|
||||||
content: string,
|
content: string,
|
||||||
outputPath: string,
|
outputPath: string,
|
||||||
options: Partial<PandocOptions> = {},
|
options: Partial<PandocOptions> = {},
|
||||||
progressCallback?: ProgressCallback
|
progressCallback?: ProgressCallback
|
||||||
): Promise<ConversionResult> {
|
): Promise<ConversionResult> {
|
||||||
|
try {
|
||||||
|
progressCallback?.('Preparing markdown content...', 10);
|
||||||
|
|
||||||
|
// Create temporary markdown file
|
||||||
|
await this.ensureTempDirectory();
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const tempInputPath = pathUtils.joinPath(this.tempDir!, `temp-${Date.now()}.md`);
|
||||||
|
|
||||||
|
await this.plugin.app.vault.adapter.write(tempInputPath, content);
|
||||||
|
|
||||||
|
// Merge options
|
||||||
|
this.pandocOptions = { ...this.pandocOptions, ...options };
|
||||||
|
|
||||||
|
// Convert using the file-based method
|
||||||
|
const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback);
|
||||||
|
|
||||||
|
// Cleanup temp file
|
||||||
try {
|
try {
|
||||||
progressCallback?.('Preparing markdown content...', 10);
|
await this.plugin.app.vault.adapter.remove(tempInputPath);
|
||||||
|
|
||||||
// Create temporary markdown file
|
|
||||||
await this.ensureTempDirectory();
|
|
||||||
const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`);
|
|
||||||
|
|
||||||
await fsPromises.writeFile(tempInputPath, content, 'utf-8');
|
|
||||||
|
|
||||||
// Merge options
|
|
||||||
this.pandocOptions = { ...this.pandocOptions, ...options };
|
|
||||||
|
|
||||||
// Convert using the file-based method
|
|
||||||
const result = await this.convertToPDF(tempInputPath, outputPath, progressCallback);
|
|
||||||
|
|
||||||
// Cleanup temp file
|
|
||||||
try {
|
|
||||||
await fsPromises.unlink(tempInputPath);
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to cleanup temp file:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
console.warn('Failed to cleanup temp file:', error);
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: `Conversion failed: ${errorMessage}`
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `Conversion failed: ${errorMessage}`
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set up cleanup handlers for temporary files
|
* Set up cleanup handlers for temporary files
|
||||||
@@ -139,85 +144,6 @@ export class PandocTypstConverter {
|
|||||||
process.on('uncaughtException', cleanup);
|
process.on('uncaughtException', cleanup);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Process PDF embeds by converting them to images and creating combined output
|
|
||||||
*/
|
|
||||||
async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, embedPdfFiles: boolean = true): Promise<void> {
|
|
||||||
const { PdfToImageConverter } = require('./PdfToImageConverter');
|
|
||||||
const converter = PdfToImageConverter.getInstance(this.plugin);
|
|
||||||
|
|
||||||
for (const pdfEmbed of processedResult.metadata.pdfEmbeds) {
|
|
||||||
try {
|
|
||||||
|
|
||||||
// Resolve full path to the PDF
|
|
||||||
const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath);
|
|
||||||
|
|
||||||
// Check if PDF file exists
|
|
||||||
const fs = require('fs');
|
|
||||||
if (!fs.existsSync(fullPdfPath)) {
|
|
||||||
console.warn(`Export: PDF file not found: ${fullPdfPath}`);
|
|
||||||
// Replace marker with error message
|
|
||||||
processedResult.content = processedResult.content.replace(
|
|
||||||
pdfEmbed.marker,
|
|
||||||
`[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert PDF to image (always happens regardless of embedPdfFiles setting)
|
|
||||||
const conversionResult = await converter.convertFirstPageToImage(
|
|
||||||
fullPdfPath,
|
|
||||||
tempDir,
|
|
||||||
{
|
|
||||||
scale: 1.5,
|
|
||||||
maxWidth: 600,
|
|
||||||
maxHeight: 400,
|
|
||||||
format: 'png'
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (conversionResult.success) {
|
|
||||||
// Get relative path for the generated image
|
|
||||||
const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath);
|
|
||||||
|
|
||||||
// Create output based on embedPdfFiles setting
|
|
||||||
let combinedOutput: string;
|
|
||||||
if (embedPdfFiles) {
|
|
||||||
// Include both image preview and PDF attachment note
|
|
||||||
combinedOutput = [
|
|
||||||
``,
|
|
||||||
`[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
|
|
||||||
].join('\n\n');
|
|
||||||
} else {
|
|
||||||
// Only show image preview
|
|
||||||
combinedOutput = ``;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Replace marker with output
|
|
||||||
processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput);
|
|
||||||
|
|
||||||
|
|
||||||
} else {
|
|
||||||
console.error(`Export: PDF conversion failed: ${conversionResult.error}`);
|
|
||||||
|
|
||||||
// Replace marker with fallback link
|
|
||||||
processedResult.content = processedResult.content.replace(
|
|
||||||
pdfEmbed.marker,
|
|
||||||
`[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error(`Export: Error processing PDF embed: ${error.message}`);
|
|
||||||
|
|
||||||
// Replace marker with error fallback
|
|
||||||
processedResult.content = processedResult.content.replace(
|
|
||||||
pdfEmbed.marker,
|
|
||||||
`[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up temporary files and directories
|
* Clean up temporary files and directories
|
||||||
@@ -235,7 +161,8 @@ export class PandocTypstConverter {
|
|||||||
|
|
||||||
// Remove temporary directory
|
// Remove temporary directory
|
||||||
if (this.tempDir) {
|
if (this.tempDir) {
|
||||||
await fsPromises.rmdir(this.tempDir, { recursive: true });
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
await pathUtils.cleanupDir(this.tempDir);
|
||||||
this.tempDir = null;
|
this.tempDir = null;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -251,487 +178,20 @@ export class PandocTypstConverter {
|
|||||||
if (this.pandocOptions.vaultBasePath) {
|
if (this.pandocOptions.vaultBasePath) {
|
||||||
// Use TempDirectoryManager for plugin temp directories
|
// Use TempDirectoryManager for plugin temp directories
|
||||||
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
|
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
|
||||||
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir);
|
const tempManager = TempDirectoryManager.create(this.pandocOptions.vaultBasePath, configDir, undefined, this.plugin?.app);
|
||||||
this.tempDir = tempManager.ensureTempDir('pandoc');
|
this.tempDir = await tempManager.ensureTempDir('pandoc');
|
||||||
} else {
|
} else {
|
||||||
// Fallback to system temp if plugin folder not available
|
// Fallback to system temp if plugin folder not available - use TempDirectoryManager fallback
|
||||||
this.tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'obsidian-typst-'));
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const vaultPath = pathUtils.getVaultPath();
|
||||||
|
const configDir = this.plugin?.app?.vault?.configDir || '.obsidian';
|
||||||
|
const tempManager = new TempDirectoryManager({ vaultPath, configDir, app: this.plugin.app });
|
||||||
|
this.tempDir = await tempManager.ensureTempDir('pandoc');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this.tempDir;
|
return this.tempDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Build pandoc command-line arguments
|
|
||||||
*/
|
|
||||||
private async buildPandocArgs(inputPath: string, outputPath: string): Promise<string[]> {
|
|
||||||
const args: string[] = [];
|
|
||||||
|
|
||||||
// Input file
|
|
||||||
args.push(inputPath);
|
|
||||||
|
|
||||||
// Output file
|
|
||||||
args.push('-o', outputPath);
|
|
||||||
|
|
||||||
// Specify input format as markdown with smart extension disabled
|
|
||||||
args.push('--from', 'markdown-smart');
|
|
||||||
|
|
||||||
// Set PDF engine to Typst (use configured path if available)
|
|
||||||
const typstPath = this.resolveExecutablePath(this.pandocOptions.typstPath, 'typst');
|
|
||||||
args.push(`--pdf-engine=${typstPath}`);
|
|
||||||
|
|
||||||
// Enable standalone mode (required for PDF output)
|
|
||||||
args.push('--standalone');
|
|
||||||
|
|
||||||
// Embed resources (images, etc.) directly into the output
|
|
||||||
args.push('--embed-resources');
|
|
||||||
|
|
||||||
// Add resource paths for attachment resolution
|
|
||||||
if (this.pandocOptions.vaultBasePath) {
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
// Add vault root as primary resource path
|
|
||||||
args.push('--resource-path', this.pandocOptions.vaultBasePath);
|
|
||||||
|
|
||||||
// Add common attachment directories as additional resource paths
|
|
||||||
const commonAttachmentPaths = [
|
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'attachments'),
|
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'assets'),
|
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'files'),
|
|
||||||
path.join(this.pandocOptions.vaultBasePath, 'images'),
|
|
||||||
path.join(this.pandocOptions.vaultBasePath, '.attachments')
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check if these directories exist and add them
|
|
||||||
for (const attachPath of commonAttachmentPaths) {
|
|
||||||
if (fs.existsSync(attachPath)) {
|
|
||||||
args.push('--resource-path', attachPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also scan for note-specific attachment folders (Obsidian often creates these)
|
|
||||||
// Use cache to avoid scanning entire vault on every export
|
|
||||||
const now = Date.now();
|
|
||||||
const cacheIsValid = this.resourcePathCacheVaultPath === this.pandocOptions.vaultBasePath &&
|
|
||||||
(now - this.resourcePathCacheTimestamp) < this.CACHE_EXPIRY_MS &&
|
|
||||||
this.resourcePathCache.length > 0;
|
|
||||||
|
|
||||||
if (cacheIsValid) {
|
|
||||||
// Use cached resource paths
|
|
||||||
for (const cachedPath of this.resourcePathCache) {
|
|
||||||
args.push('--resource-path', cachedPath);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Cache is invalid or expired, perform fresh scan
|
|
||||||
const foundResourcePaths: string[] = [];
|
|
||||||
|
|
||||||
try {
|
|
||||||
const vaultContents = fs.readdirSync(this.pandocOptions.vaultBasePath);
|
|
||||||
for (const item of vaultContents) {
|
|
||||||
const itemPath = path.join(this.pandocOptions.vaultBasePath, item);
|
|
||||||
|
|
||||||
let stat;
|
|
||||||
try {
|
|
||||||
stat = await fsPromises.stat(itemPath);
|
|
||||||
} catch (error) {
|
|
||||||
// File might have been deleted between readdirSync and statSync
|
|
||||||
console.warn(`Export: Unable to stat ${itemPath}:`, error.message);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stat.isDirectory() && !item.startsWith('.') && !item.startsWith('_')) {
|
|
||||||
// Check if this directory contains images
|
|
||||||
try {
|
|
||||||
const dirContents = fs.readdirSync(itemPath);
|
|
||||||
const hasImages = dirContents.some((file: string) =>
|
|
||||||
/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
|
|
||||||
);
|
|
||||||
if (hasImages) {
|
|
||||||
foundResourcePaths.push(itemPath);
|
|
||||||
args.push('--resource-path', itemPath);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// Ignore directories we can't read
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update cache with fresh results
|
|
||||||
this.resourcePathCache = foundResourcePaths;
|
|
||||||
this.resourcePathCacheTimestamp = now;
|
|
||||||
this.resourcePathCacheVaultPath = this.pandocOptions.vaultBasePath;
|
|
||||||
} catch (e) {
|
|
||||||
console.warn('Could not scan vault for attachment directories:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use universal wrapper with --template and pass actual template as template_path variable
|
|
||||||
if (this.pandocOptions.template) {
|
|
||||||
// Get absolute path to universal wrapper using plugin directory from pandocOptions
|
|
||||||
const fs = require('fs');
|
|
||||||
const absolutePluginDir = this.pandocOptions.pluginDir || '';
|
|
||||||
const wrapperPath = path.resolve(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ');
|
|
||||||
|
|
||||||
// Verify wrapper exists
|
|
||||||
if (!fs.existsSync(wrapperPath)) {
|
|
||||||
throw new Error(`Universal wrapper template not found at: ${wrapperPath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
args.push('--template', wrapperPath);
|
|
||||||
|
|
||||||
// Add plugin templates directory as a resource path so Typst can find template files
|
|
||||||
const templatesDir = path.resolve(absolutePluginDir, 'templates');
|
|
||||||
// Quote the path to handle spaces and special characters
|
|
||||||
args.push('--resource-path', `"${templatesDir}"`);
|
|
||||||
|
|
||||||
// Pass the actual template path as a variable
|
|
||||||
// Use relative path from vault root for Typst import
|
|
||||||
let templatePathForTypst = this.pandocOptions.template;
|
|
||||||
if (path.isAbsolute(templatePathForTypst) && this.pandocOptions.vaultBasePath) {
|
|
||||||
// Make template path relative to vault for Typst import
|
|
||||||
templatePathForTypst = path.relative(this.pandocOptions.vaultBasePath, templatePathForTypst);
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push('-V', `template_path=${templatePathForTypst}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add variables from the ExportConfig (these take priority)
|
|
||||||
// These come from the modal and include all the new template variables
|
|
||||||
if (this.pandocOptions.variables) {
|
|
||||||
for (const [key, value] of Object.entries(this.pandocOptions.variables)) {
|
|
||||||
if (value !== null && value !== undefined && value.toString().trim() !== '') {
|
|
||||||
// Handle special variable name mappings for Typst compatibility
|
|
||||||
let variableName = key;
|
|
||||||
let processedValue = value;
|
|
||||||
|
|
||||||
switch (key) {
|
|
||||||
case 'bodyFont':
|
|
||||||
variableName = 'font';
|
|
||||||
break;
|
|
||||||
case 'headingFont':
|
|
||||||
variableName = 'heading_font';
|
|
||||||
break;
|
|
||||||
case 'monospaceFont':
|
|
||||||
variableName = 'monospace_font';
|
|
||||||
break;
|
|
||||||
case 'bodyFontSize':
|
|
||||||
variableName = 'fontsize';
|
|
||||||
processedValue = value + 'pt';
|
|
||||||
break;
|
|
||||||
case 'pageSize':
|
|
||||||
variableName = 'paper';
|
|
||||||
// Convert to Typst-compatible paper size
|
|
||||||
processedValue = mapToTypstPaperSize(value.toString());
|
|
||||||
break;
|
|
||||||
case 'marginTop':
|
|
||||||
variableName = 'margin_top';
|
|
||||||
processedValue = value + 'cm';
|
|
||||||
break;
|
|
||||||
case 'marginBottom':
|
|
||||||
variableName = 'margin_bottom';
|
|
||||||
processedValue = value + 'cm';
|
|
||||||
break;
|
|
||||||
case 'marginLeft':
|
|
||||||
variableName = 'margin_left';
|
|
||||||
processedValue = value + 'cm';
|
|
||||||
break;
|
|
||||||
case 'marginRight':
|
|
||||||
variableName = 'margin_right';
|
|
||||||
processedValue = value + 'cm';
|
|
||||||
break;
|
|
||||||
// Keep other variables as-is (orientation, flipped, width, etc.)
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push('-V', `${variableName}=${processedValue}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add fallback typography and page setup from plugin settings
|
|
||||||
// Only add these if not already provided by ExportConfig variables
|
|
||||||
if (this.plugin && this.plugin.settings) {
|
|
||||||
const settings: obsidianTypstPDFExportSettings = this.plugin.settings;
|
|
||||||
const existingVars = this.pandocOptions.variables || {};
|
|
||||||
|
|
||||||
// Add typography variables only if not already present in variables
|
|
||||||
if (settings.typography) {
|
|
||||||
if (settings.typography.fonts) {
|
|
||||||
// Only add if not already in variables from ExportConfig
|
|
||||||
if (!existingVars.bodyFont && !existingVars.font && settings.typography.fonts.body) {
|
|
||||||
args.push('-V', `font=${settings.typography.fonts.body}`);
|
|
||||||
}
|
|
||||||
if (!existingVars.headingFont && !existingVars.heading_font && settings.typography.fonts.heading) {
|
|
||||||
args.push('-V', `heading_font=${settings.typography.fonts.heading}`);
|
|
||||||
}
|
|
||||||
if (!existingVars.monospaceFont && !existingVars.monospace_font && settings.typography.fonts.monospace) {
|
|
||||||
args.push('-V', `monospace_font=${settings.typography.fonts.monospace}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.typography.fontSizes) {
|
|
||||||
if (!existingVars.bodyFontSize && !existingVars.fontsize && settings.typography.fontSizes.body) {
|
|
||||||
args.push('-V', `fontsize=${settings.typography.fontSizes.body}pt`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add page setup variables only if not already present
|
|
||||||
if (settings.pageSetup) {
|
|
||||||
if (!existingVars.pageSize && !existingVars.paper && settings.pageSetup.size) {
|
|
||||||
const typstPaperSize = mapToTypstPaperSize(settings.pageSetup.size);
|
|
||||||
args.push('-V', `paper=${typstPaperSize}`);
|
|
||||||
}
|
|
||||||
if (!existingVars.orientation && settings.pageSetup.orientation) {
|
|
||||||
args.push('-V', `orientation=${settings.pageSetup.orientation}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add margin fallbacks only if not already specified
|
|
||||||
if (settings.pageSetup.margins) {
|
|
||||||
const margins = settings.pageSetup.margins;
|
|
||||||
if (!existingVars.marginTop && !existingVars.margin_top && margins.top !== undefined) {
|
|
||||||
args.push('-V', `margin_top=${margins.top}cm`);
|
|
||||||
}
|
|
||||||
if (!existingVars.marginRight && !existingVars.margin_right && margins.right !== undefined) {
|
|
||||||
args.push('-V', `margin_right=${margins.right}cm`);
|
|
||||||
}
|
|
||||||
if (!existingVars.marginBottom && !existingVars.margin_bottom && margins.bottom !== undefined) {
|
|
||||||
args.push('-V', `margin_bottom=${margins.bottom}cm`);
|
|
||||||
}
|
|
||||||
if (!existingVars.marginLeft && !existingVars.margin_left && margins.left !== undefined) {
|
|
||||||
args.push('-V', `margin_left=${margins.left}cm`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add export format variable - only use settings default if not already provided
|
|
||||||
if (!existingVars.export_format && settings.exportDefaults && settings.exportDefaults.format) {
|
|
||||||
args.push('-V', `export_format=${settings.exportDefaults.format}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add Typst engine options
|
|
||||||
if (this.typstSettings.engineOptions) {
|
|
||||||
for (const option of this.typstSettings.engineOptions) {
|
|
||||||
args.push('--pdf-engine-opt', option);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate intermediate Typst file if requested
|
|
||||||
if (this.pandocOptions.generateIntermediateTypst) {
|
|
||||||
const tempDir = await this.ensureTempDirectory();
|
|
||||||
const typstPath = path.join(tempDir, 'intermediate.typ');
|
|
||||||
args.push('--output', typstPath);
|
|
||||||
|
|
||||||
// Also create a copy to keep for debugging
|
|
||||||
const debugTypstPath = path.join(tempDir, 'debug.typ');
|
|
||||||
this.cleanupHandlers.push(() => {
|
|
||||||
try {
|
|
||||||
const fs = require('fs');
|
|
||||||
if (fs.existsSync(typstPath)) {
|
|
||||||
fs.copyFileSync(typstPath, debugTypstPath);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.warn('Could not create debug Typst file:', e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add working directory for relative paths
|
|
||||||
if (this.pandocOptions.vaultBasePath) {
|
|
||||||
process.chdir(this.pandocOptions.vaultBasePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve an executable path, handling empty settings by falling back to system search
|
|
||||||
*/
|
|
||||||
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
|
|
||||||
// If user provided a path and it's not empty, use it
|
|
||||||
if (userPath && userPath.trim() !== '') {
|
|
||||||
return userPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to find the executable using which command
|
|
||||||
const { spawnSync } = require('child_process');
|
|
||||||
try {
|
|
||||||
const augmentedEnv = {
|
|
||||||
...process.env,
|
|
||||||
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = spawnSync('which', [defaultName], {
|
|
||||||
encoding: 'utf8',
|
|
||||||
env: augmentedEnv
|
|
||||||
});
|
|
||||||
|
|
||||||
if (result.status === 0 && result.stdout) {
|
|
||||||
const foundPath = result.stdout.trim();
|
|
||||||
if (foundPath) {
|
|
||||||
return foundPath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Ignore errors from which command
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fall back to the default name (will be found via PATH if available)
|
|
||||||
return defaultName;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute pandoc process with the given arguments
|
|
||||||
*/
|
|
||||||
private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise<ConversionResult> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const pandocPath = this.resolveExecutablePath(this.pandocOptions.pandocPath, 'pandoc');
|
|
||||||
const timeout = this.pandocOptions.timeout || 60000;
|
|
||||||
|
|
||||||
// Log the exact command being executed for debugging
|
|
||||||
|
|
||||||
progressCallback?.('Starting Pandoc process...', 40);
|
|
||||||
|
|
||||||
// Determine working directory - use vault base path if available, fallback to plugin directory
|
|
||||||
let workingDir: string;
|
|
||||||
|
|
||||||
if (this.pandocOptions.vaultBasePath) {
|
|
||||||
workingDir = this.pandocOptions.vaultBasePath;
|
|
||||||
} else {
|
|
||||||
// Fallback to plugin directory
|
|
||||||
const pluginDir = this.pandocOptions.pluginDir || process.cwd();
|
|
||||||
workingDir = pluginDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Augment PATH to include common binary locations
|
|
||||||
const augmentedEnv = {
|
|
||||||
...process.env,
|
|
||||||
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
|
||||||
};
|
|
||||||
|
|
||||||
// Spawn pandoc process with vault as working directory for attachment resolution
|
|
||||||
const pandocProcess: ChildProcess = spawn(pandocPath, args, {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
cwd: workingDir,
|
|
||||||
env: augmentedEnv, // Use augmented environment
|
|
||||||
});
|
|
||||||
|
|
||||||
let stdout = '';
|
|
||||||
let stderr = '';
|
|
||||||
let hasTimedOut = false;
|
|
||||||
|
|
||||||
// Set up timeout
|
|
||||||
const timeoutHandle = setTimeout(() => {
|
|
||||||
hasTimedOut = true;
|
|
||||||
pandocProcess.kill('SIGTERM');
|
|
||||||
resolve({
|
|
||||||
success: false,
|
|
||||||
error: `Pandoc process timed out after ${timeout}ms`,
|
|
||||||
exitCode: -1
|
|
||||||
});
|
|
||||||
}, timeout);
|
|
||||||
|
|
||||||
// Collect stdout
|
|
||||||
pandocProcess.stdout?.on('data', (data: Buffer) => {
|
|
||||||
stdout += data.toString();
|
|
||||||
progressCallback?.('Processing document...', 60);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Collect stderr and monitor for progress
|
|
||||||
pandocProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
const output = data.toString();
|
|
||||||
stderr += output;
|
|
||||||
|
|
||||||
// Parse progress information from stderr if available
|
|
||||||
this.parseProgressFromOutput(output, progressCallback);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle process completion
|
|
||||||
pandocProcess.on('close', (code: number | null) => {
|
|
||||||
clearTimeout(timeoutHandle);
|
|
||||||
|
|
||||||
if (hasTimedOut) {
|
|
||||||
return; // Already resolved with timeout error
|
|
||||||
}
|
|
||||||
|
|
||||||
const success = code === 0;
|
|
||||||
const result: ConversionResult = {
|
|
||||||
success,
|
|
||||||
stdout,
|
|
||||||
stderr,
|
|
||||||
exitCode: code || -1
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!success) {
|
|
||||||
result.error = this.extractErrorMessage(stderr, stdout);
|
|
||||||
} else {
|
|
||||||
progressCallback?.('PDF generation complete!', 90);
|
|
||||||
}
|
|
||||||
|
|
||||||
resolve(result);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle process errors
|
|
||||||
pandocProcess.on('error', (error: Error) => {
|
|
||||||
clearTimeout(timeoutHandle);
|
|
||||||
resolve({
|
|
||||||
success: false,
|
|
||||||
error: `Failed to start Pandoc process: ${error.message}`,
|
|
||||||
exitCode: -1
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse progress information from pandoc output
|
|
||||||
*/
|
|
||||||
private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
|
|
||||||
// Look for common progress indicators in pandoc/typst output
|
|
||||||
if (output.includes('reading')) {
|
|
||||||
progressCallback?.('Reading input file...', 50);
|
|
||||||
} else if (output.includes('parsing')) {
|
|
||||||
progressCallback?.('Parsing document...', 55);
|
|
||||||
} else if (output.includes('typst')) {
|
|
||||||
progressCallback?.('Generating PDF with Typst...', 70);
|
|
||||||
} else if (output.includes('writing')) {
|
|
||||||
progressCallback?.('Writing output file...', 80);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extract meaningful error messages from pandoc output
|
|
||||||
*/
|
|
||||||
private extractErrorMessage(stderr: string, stdout: string): string {
|
|
||||||
// Look for common error patterns
|
|
||||||
const errorPatterns = [
|
|
||||||
/error:/i,
|
|
||||||
/Error:/,
|
|
||||||
/failed/i,
|
|
||||||
/Fatal/i,
|
|
||||||
/pandoc:/i
|
|
||||||
];
|
|
||||||
|
|
||||||
const allOutput = (stderr + '\n' + stdout).split('\n');
|
|
||||||
|
|
||||||
for (const line of allOutput) {
|
|
||||||
for (const pattern of errorPatterns) {
|
|
||||||
if (pattern.test(line)) {
|
|
||||||
return line.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no specific error found, return first non-empty line from stderr
|
|
||||||
const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0);
|
|
||||||
if (stderrLines.length > 0) {
|
|
||||||
return stderrLines[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'Unknown error occurred during conversion';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dispose of the converter and clean up resources
|
* Dispose of the converter and clean up resources
|
||||||
|
|||||||
@@ -3,8 +3,13 @@
|
|||||||
* Converts PDF files to PNG images for preview in Typst exports
|
* Converts PDF files to PNG images for preview in Typst exports
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import * as fs from 'fs/promises';
|
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
|
import { PdfProcessor } from './pdf/PdfProcessor';
|
||||||
|
import { ImageOptimizer } from './pdf/ImageOptimizer';
|
||||||
|
import { PdfCliExecutor } from './pdf/PdfCliExecutor';
|
||||||
|
import { FileDiscovery } from './pdf/FileDiscovery';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
|
||||||
export interface PdfConversionOptions {
|
export interface PdfConversionOptions {
|
||||||
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
|
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
|
||||||
@@ -40,30 +45,14 @@ export interface PdfConversionResult {
|
|||||||
|
|
||||||
export class PdfToImageConverter {
|
export class PdfToImageConverter {
|
||||||
private static instance: PdfToImageConverter;
|
private static instance: PdfToImageConverter;
|
||||||
private plugin: any; // Plugin instance for accessing settings
|
private plugin: obsidianTypstPDFExport | undefined;
|
||||||
|
|
||||||
private constructor(plugin?: any) {
|
private constructor(plugin?: obsidianTypstPDFExport) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get augmented environment with extended PATH for ImageMagick
|
|
||||||
*/
|
|
||||||
private getAugmentedEnv(): NodeJS.ProcessEnv {
|
|
||||||
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
|
||||||
const commonPaths = [
|
|
||||||
'/opt/homebrew/bin',
|
|
||||||
'/usr/local/bin',
|
|
||||||
'/usr/bin'
|
|
||||||
].map(p => homeDir.includes('Users') ? p : homeDir + p);
|
|
||||||
|
|
||||||
return {
|
public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter {
|
||||||
...process.env,
|
|
||||||
PATH: `${process.env.PATH}:${commonPaths.join(':')}`
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public static getInstance(plugin?: any): PdfToImageConverter {
|
|
||||||
if (!PdfToImageConverter.instance) {
|
if (!PdfToImageConverter.instance) {
|
||||||
PdfToImageConverter.instance = new PdfToImageConverter(plugin);
|
PdfToImageConverter.instance = new PdfToImageConverter(plugin);
|
||||||
} else if (plugin && !PdfToImageConverter.instance.plugin) {
|
} else if (plugin && !PdfToImageConverter.instance.plugin) {
|
||||||
@@ -91,285 +80,85 @@ export class PdfToImageConverter {
|
|||||||
quality: options.quality || 90
|
quality: options.quality || 90
|
||||||
};
|
};
|
||||||
|
|
||||||
// Ensure the PDF file exists
|
// Validate PDF file exists and is valid
|
||||||
try {
|
const pdfValidation = await PdfProcessor.validatePdfFile(pdfPath);
|
||||||
await fs.access(pdfPath);
|
if (!pdfValidation.success) {
|
||||||
} catch (error) {
|
|
||||||
return {
|
return {
|
||||||
imagePath: '',
|
imagePath: '',
|
||||||
originalDimensions: { width: 0, height: 0 },
|
originalDimensions: { width: 0, height: 0 },
|
||||||
imageDimensions: { width: 0, height: 0 },
|
imageDimensions: { width: 0, height: 0 },
|
||||||
success: false,
|
success: false,
|
||||||
error: `PDF file not found: ${pdfPath}`
|
error: pdfValidation.error
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure output directory exists
|
// Ensure output directory exists
|
||||||
await fs.mkdir(outputDir, { recursive: true });
|
if (this.plugin?.app) {
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
await pathUtils.ensureDir(outputDir);
|
||||||
|
}
|
||||||
|
|
||||||
// Calculate relative path from vault to temp directory for pdf2img
|
// Generate expected output file name for the first page
|
||||||
// pdf2img doesn't handle absolute paths correctly, needs relative paths
|
|
||||||
const vaultPath = process.cwd(); // This should be the vault directory
|
|
||||||
const relativeOutputDir = path.relative(vaultPath, outputDir);
|
|
||||||
|
|
||||||
// Generate output file name for the first page
|
|
||||||
const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath));
|
const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath));
|
||||||
// pdf2img uses the pattern: "filename-1.png" for first page
|
const expectedOutputFileName = FileDiscovery.generateExpectedFilename(pdfBaseName, 1, 'png');
|
||||||
const expectedOutputFileName = `${pdfBaseName}-1.png`;
|
|
||||||
const expectedOutputPath = path.join(outputDir, expectedOutputFileName);
|
|
||||||
|
|
||||||
// Use the CLI to convert PDF to images
|
// Execute PDF to image conversion using CLI
|
||||||
const { exec } = require('child_process');
|
const cliResult = await PdfCliExecutor.executePdf2Img(
|
||||||
const { promisify } = require('util');
|
pdfPath,
|
||||||
const execAsync = promisify(exec);
|
{
|
||||||
|
scale: opts.scale,
|
||||||
|
pages: '1', // Only convert the first page
|
||||||
|
outputDir: outputDir
|
||||||
|
},
|
||||||
|
this.plugin
|
||||||
|
);
|
||||||
|
|
||||||
// Get the plugin directory - need to handle Obsidian's environment
|
if (!cliResult.success) {
|
||||||
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
|
|
||||||
let pluginDir: string;
|
|
||||||
|
|
||||||
// Try multiple strategies to find the plugin directory
|
|
||||||
const pluginDirName = this.plugin?.manifest?.dir || 'typst-pdf-export';
|
|
||||||
const configDir = this.plugin?.app.vault.configDir || '.obsidian';
|
|
||||||
const possiblePluginDirs = [
|
|
||||||
// Strategy 1: From process.cwd() if it's in the vault
|
|
||||||
path.join(process.cwd(), configDir, 'plugins', pluginDirName),
|
|
||||||
// Strategy 2: Assuming we're running from vault root
|
|
||||||
path.join(configDir, 'plugins', pluginDirName),
|
|
||||||
// Strategy 3: From vault base path if plugin is available
|
|
||||||
...(this.plugin ? [path.join((this.plugin.app.vault.adapter as any).basePath, this.plugin.manifest.dir!)] : [])
|
|
||||||
];
|
|
||||||
|
|
||||||
// Find the first directory that exists and has node_modules
|
|
||||||
pluginDir = possiblePluginDirs.find(dir => {
|
|
||||||
try {
|
|
||||||
const nodeModulesPath = path.join(dir, 'node_modules');
|
|
||||||
return require('fs').existsSync(nodeModulesPath);
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}) || possiblePluginDirs[0]; // Fallback to first option
|
|
||||||
|
|
||||||
const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img');
|
|
||||||
|
|
||||||
|
|
||||||
// Check if the binary exists
|
|
||||||
const fs2 = require('fs');
|
|
||||||
if (!fs2.existsSync(pdf2imgPath)) {
|
|
||||||
return {
|
return {
|
||||||
imagePath: '',
|
imagePath: '',
|
||||||
originalDimensions: { width: 0, height: 0 },
|
originalDimensions: { width: 0, height: 0 },
|
||||||
imageDimensions: { width: 0, height: 0 },
|
imageDimensions: { width: 0, height: 0 },
|
||||||
success: false,
|
success: false,
|
||||||
error: `PDF2IMG binary not found at: ${pdf2imgPath}`
|
error: cliResult.error
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the CLI command - the pdf2img binary is already executable
|
// Find the generated image file (may have different name than expected)
|
||||||
const cliCommand = [
|
const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName, this.plugin);
|
||||||
`"${pdf2imgPath}"`,
|
if (!fileDiscovery.found) {
|
||||||
`"${pdfPath}"`,
|
|
||||||
'--scale', opts.scale.toString(),
|
|
||||||
'--output', `"${relativeOutputDir}"`,
|
|
||||||
'--pages', '1' // Only convert the first page
|
|
||||||
].join(' ');
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Set environment variables to ensure node can be found
|
|
||||||
// Use configured additional paths or fall back to defaults
|
|
||||||
const additionalPaths = this.plugin?.settings?.executablePaths?.additionalPaths ||
|
|
||||||
['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'];
|
|
||||||
|
|
||||||
// Ensure Node.js paths are included for pdf2img execution
|
|
||||||
const nodePaths = [
|
|
||||||
'/usr/local/bin', // Common Node.js installation
|
|
||||||
'/opt/homebrew/bin', // Homebrew on macOS
|
|
||||||
'/usr/bin', // System Node.js
|
|
||||||
'/usr/local/node/bin' // Alternative Node.js location
|
|
||||||
];
|
|
||||||
|
|
||||||
const env = {
|
|
||||||
...process.env,
|
|
||||||
PATH: [
|
|
||||||
process.env.PATH,
|
|
||||||
...nodePaths,
|
|
||||||
...additionalPaths
|
|
||||||
].filter(Boolean).join(':')
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = await execAsync(cliCommand, {
|
|
||||||
env
|
|
||||||
});
|
|
||||||
if (result.stderr) {
|
|
||||||
console.warn(`PDF conversion stderr: ${result.stderr}`);
|
|
||||||
}
|
|
||||||
} catch (cliError) {
|
|
||||||
console.error(`PDF conversion error: ${cliError.message}`);
|
|
||||||
return {
|
return {
|
||||||
imagePath: '',
|
imagePath: '',
|
||||||
originalDimensions: { width: 0, height: 0 },
|
originalDimensions: { width: 0, height: 0 },
|
||||||
imageDimensions: { width: 0, height: 0 },
|
imageDimensions: { width: 0, height: 0 },
|
||||||
success: false,
|
success: false,
|
||||||
error: `PDF CLI conversion failed: ${cliError.message}`
|
error: fileDiscovery.error
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the expected output file exists
|
// Use ImageOptimizer to handle format conversion and dimension detection
|
||||||
let actualOutputPath = expectedOutputPath;
|
const optimizationResult = await ImageOptimizer.optimizeImage(
|
||||||
try {
|
fileDiscovery.filePath,
|
||||||
await fs.access(expectedOutputPath);
|
outputDir,
|
||||||
} catch (error) {
|
pdfBaseName,
|
||||||
// Debug: List what files are actually in the output directory
|
{
|
||||||
try {
|
format: opts.format,
|
||||||
const files = await fs.readdir(outputDir);
|
quality: opts.quality
|
||||||
|
},
|
||||||
|
this.plugin
|
||||||
|
);
|
||||||
|
|
||||||
// Look for any PNG files that might match
|
if (!optimizationResult.success) {
|
||||||
const pngFiles = files.filter(f => f.endsWith('.png'));
|
return {
|
||||||
if (pngFiles.length > 0) {
|
imagePath: '',
|
||||||
|
originalDimensions: { width: 0, height: 0 },
|
||||||
// Try to find a file that matches the pattern (with or without exact name)
|
imageDimensions: { width: 0, height: 0 },
|
||||||
// pdf2img might sanitize filenames differently
|
success: false,
|
||||||
const matchingFile = pngFiles.find(f => {
|
error: optimizationResult.error
|
||||||
// Try exact match first
|
};
|
||||||
if (f === expectedOutputFileName) return true;
|
|
||||||
// Try partial match by removing special characters
|
|
||||||
const simplifiedExpected = expectedOutputFileName.replace(/[^a-zA-Z0-9.-]/g, '');
|
|
||||||
const simplifiedActual = f.replace(/[^a-zA-Z0-9.-]/g, '');
|
|
||||||
return simplifiedActual === simplifiedExpected;
|
|
||||||
}) || pngFiles[0]; // Fallback to first PNG file
|
|
||||||
|
|
||||||
if (matchingFile) {
|
|
||||||
actualOutputPath = path.join(outputDir, matchingFile);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (listError) {
|
|
||||||
console.error(`Failed to list output directory:`, listError);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Final check if we found an alternative file
|
|
||||||
try {
|
|
||||||
await fs.access(actualOutputPath);
|
|
||||||
} catch (finalError) {
|
|
||||||
return {
|
|
||||||
imagePath: '',
|
|
||||||
originalDimensions: { width: 0, height: 0 },
|
|
||||||
imageDimensions: { width: 0, height: 0 },
|
|
||||||
success: false,
|
|
||||||
error: `Generated image file not found: ${actualOutputPath}. Expected: ${expectedOutputPath}`
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rename to our desired format if needed
|
const finalOutputPath = optimizationResult.imagePath;
|
||||||
const finalOutputFileName = `${pdfBaseName}_preview.${opts.format}`;
|
const imageDimensions = optimizationResult.dimensions;
|
||||||
const finalOutputPath = path.join(outputDir, finalOutputFileName);
|
|
||||||
|
|
||||||
let buffer: Buffer;
|
|
||||||
if (opts.format === 'jpeg') {
|
|
||||||
// Convert PNG to JPEG using ImageMagick
|
|
||||||
try {
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
const { promisify } = require('util');
|
|
||||||
|
|
||||||
// Use ImageMagick to convert PNG to JPEG
|
|
||||||
const convertProcess = spawn('magick', [
|
|
||||||
actualOutputPath,
|
|
||||||
'-quality', opts.quality.toString(),
|
|
||||||
finalOutputPath
|
|
||||||
], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
env: this.getAugmentedEnv()
|
|
||||||
});
|
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
let error = '';
|
|
||||||
convertProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
error += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
convertProcess.on('close', (code: number | null) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
reject(new Error(`ImageMagick conversion failed with code ${code}: ${error}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
convertProcess.on('error', (err: Error) => {
|
|
||||||
reject(new Error(`Failed to spawn ImageMagick: ${err.message}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clean up the original PNG
|
|
||||||
await fs.unlink(actualOutputPath);
|
|
||||||
buffer = await fs.readFile(finalOutputPath);
|
|
||||||
} catch (imagemagickError) {
|
|
||||||
console.warn('ImageMagick not available for JPEG conversion, keeping PNG format');
|
|
||||||
// Just rename the file to PNG format
|
|
||||||
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
|
|
||||||
await fs.rename(actualOutputPath, pngFinalPath);
|
|
||||||
buffer = await fs.readFile(pngFinalPath);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Keep as PNG, just rename
|
|
||||||
await fs.rename(actualOutputPath, finalOutputPath);
|
|
||||||
buffer = await fs.readFile(finalOutputPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get image dimensions using ImageMagick
|
|
||||||
let imageDimensions = { width: opts.maxWidth, height: opts.maxHeight };
|
|
||||||
try {
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
// Use ImageMagick identify to get image dimensions
|
|
||||||
const identifyProcess = spawn('magick', [
|
|
||||||
'identify',
|
|
||||||
'-ping',
|
|
||||||
'-format',
|
|
||||||
'%wx%h',
|
|
||||||
finalOutputPath
|
|
||||||
], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
env: this.getAugmentedEnv()
|
|
||||||
});
|
|
||||||
|
|
||||||
const dimensionsOutput = await new Promise<string>((resolve, reject) => {
|
|
||||||
let output = '';
|
|
||||||
let error = '';
|
|
||||||
|
|
||||||
identifyProcess.stdout?.on('data', (data: Buffer) => {
|
|
||||||
output += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
identifyProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
error += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
identifyProcess.on('close', (code: number | null) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve(output.trim());
|
|
||||||
} else {
|
|
||||||
reject(new Error(`ImageMagick identify failed with code ${code}: ${error}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
identifyProcess.on('error', (err: Error) => {
|
|
||||||
reject(new Error(`Failed to spawn ImageMagick identify: ${err.message}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Parse dimensions from "WIDTHxHEIGHT" format
|
|
||||||
const dimensionMatch = dimensionsOutput.match(/^(\d+)x(\d+)$/);
|
|
||||||
if (dimensionMatch) {
|
|
||||||
imageDimensions = {
|
|
||||||
width: parseInt(dimensionMatch[1], 10),
|
|
||||||
height: parseInt(dimensionMatch[2], 10)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (imagemagickError) {
|
|
||||||
// Fallback to estimated dimensions if ImageMagick is not available
|
|
||||||
console.warn('ImageMagick not available for image metadata, using estimated dimensions');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
imagePath: finalOutputPath,
|
imagePath: finalOutputPath,
|
||||||
@@ -378,13 +167,14 @@ export class PdfToImageConverter {
|
|||||||
success: true
|
success: true
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
return {
|
return {
|
||||||
imagePath: '',
|
imagePath: '',
|
||||||
originalDimensions: { width: 0, height: 0 },
|
originalDimensions: { width: 0, height: 0 },
|
||||||
imageDimensions: { width: 0, height: 0 },
|
imageDimensions: { width: 0, height: 0 },
|
||||||
success: false,
|
success: false,
|
||||||
error: `PDF conversion failed: ${error.message}`
|
error: `PDF conversion failed: ${errorMessage}`
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -393,15 +183,7 @@ export class PdfToImageConverter {
|
|||||||
* Check if a file is a valid PDF
|
* Check if a file is a valid PDF
|
||||||
*/
|
*/
|
||||||
public async isValidPdf(filePath: string): Promise<boolean> {
|
public async isValidPdf(filePath: string): Promise<boolean> {
|
||||||
try {
|
return await PdfProcessor.isValidPdf(filePath);
|
||||||
const buffer = await fs.readFile(filePath);
|
|
||||||
|
|
||||||
// Check PDF signature
|
|
||||||
const signature = buffer.subarray(0, 4).toString();
|
|
||||||
return signature === '%PDF';
|
|
||||||
} catch (error) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -413,33 +195,6 @@ export class PdfToImageConverter {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
error?: string;
|
error?: string;
|
||||||
}> {
|
}> {
|
||||||
try {
|
return await PdfProcessor.getPdfInfo(filePath);
|
||||||
// pdf-to-img doesn't provide metadata directly
|
|
||||||
// We'll use a basic approach with the PDF signature check
|
|
||||||
const isValid = await this.isValidPdf(filePath);
|
|
||||||
if (!isValid) {
|
|
||||||
return {
|
|
||||||
pageCount: 0,
|
|
||||||
dimensions: { width: 0, height: 0 },
|
|
||||||
success: false,
|
|
||||||
error: 'Invalid PDF file'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// For now, return basic info since pdf-to-img focuses on conversion
|
|
||||||
// In a real implementation, you might want to use pdf-parse or similar for metadata
|
|
||||||
return {
|
|
||||||
pageCount: 1, // We only handle first page anyway
|
|
||||||
dimensions: { width: 612, height: 792 }, // Standard letter size estimate
|
|
||||||
success: true
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
pageCount: 0,
|
|
||||||
dimensions: { width: 0, height: 0 },
|
|
||||||
success: false,
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,12 @@ export interface PandocOptions {
|
|||||||
vaultBasePath?: string;
|
vaultBasePath?: string;
|
||||||
/** Plugin directory path for resolving plugin-relative paths */
|
/** Plugin directory path for resolving plugin-relative paths */
|
||||||
pluginDir?: string;
|
pluginDir?: string;
|
||||||
|
/** Temporary directory path for intermediate files */
|
||||||
|
tempDir?: string;
|
||||||
|
/** Cleanup handlers to be executed when process completes */
|
||||||
|
cleanupHandlers?: (() => void)[];
|
||||||
|
/** Typst-specific settings */
|
||||||
|
typstSettings?: TypstSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TypstSettings {
|
export interface TypstSettings {
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
/**
|
||||||
|
* Pandoc Command Builder
|
||||||
|
* Handles construction of Pandoc command-line arguments for Typst PDF conversion
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as path from 'path';
|
||||||
|
import { PandocOptions } from '../converterTypes';
|
||||||
|
import { TypstVariableMapper } from './TypstVariableMapper';
|
||||||
|
import { ResourcePathResolver } from './ResourcePathResolver';
|
||||||
|
import { PathResolver } from '../../plugin/PathResolver';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
import { PathUtils } from '../../core/PathUtils';
|
||||||
|
|
||||||
|
export class PandocCommandBuilder {
|
||||||
|
private plugin: obsidianTypstPDFExport;
|
||||||
|
private variableMapper: TypstVariableMapper;
|
||||||
|
private resourcePathResolver: ResourcePathResolver;
|
||||||
|
private pathResolver: PathResolver;
|
||||||
|
|
||||||
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
this.variableMapper = new TypstVariableMapper(plugin);
|
||||||
|
this.resourcePathResolver = new ResourcePathResolver(plugin);
|
||||||
|
this.pathResolver = new PathResolver(plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build pandoc command-line arguments
|
||||||
|
*/
|
||||||
|
async buildPandocArgs(inputPath: string, outputPath: string, pandocOptions: PandocOptions): Promise<string[]> {
|
||||||
|
const args: string[] = [];
|
||||||
|
|
||||||
|
// Input file
|
||||||
|
args.push(inputPath);
|
||||||
|
|
||||||
|
// Output file
|
||||||
|
args.push('-o', outputPath);
|
||||||
|
|
||||||
|
// Specify input format as markdown with smart extension disabled
|
||||||
|
args.push('--from', 'markdown-smart');
|
||||||
|
|
||||||
|
// Set PDF engine to Typst (use configured path if available)
|
||||||
|
const typstPath = this.pathResolver.resolveExecutablePath(pandocOptions.typstPath, 'typst');
|
||||||
|
args.push(`--pdf-engine=${typstPath}`);
|
||||||
|
|
||||||
|
// Enable standalone mode (required for PDF output)
|
||||||
|
args.push('--standalone');
|
||||||
|
|
||||||
|
// Embed resources (images, etc.) directly into the output
|
||||||
|
args.push('--embed-resources');
|
||||||
|
|
||||||
|
// Add resource paths for attachment resolution
|
||||||
|
await this.addResourcePaths(args, pandocOptions);
|
||||||
|
|
||||||
|
// Handle template configuration
|
||||||
|
await this.addTemplateConfiguration(args, pandocOptions);
|
||||||
|
|
||||||
|
// Add all variables using the variable mapper
|
||||||
|
this.addTypstVariables(args, pandocOptions);
|
||||||
|
|
||||||
|
// Add Typst engine options
|
||||||
|
this.addTypstEngineOptions(args, pandocOptions);
|
||||||
|
|
||||||
|
// Add enhanced Typst diagnostics for better error reporting
|
||||||
|
this.addTypstDiagnostics(args, pandocOptions);
|
||||||
|
|
||||||
|
// Set working directory for relative paths
|
||||||
|
if (pandocOptions.vaultBasePath) {
|
||||||
|
process.chdir(pandocOptions.vaultBasePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add resource paths for attachment resolution
|
||||||
|
*/
|
||||||
|
private async addResourcePaths(args: string[], pandocOptions: PandocOptions): Promise<void> {
|
||||||
|
if (!pandocOptions.vaultBasePath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all resource paths from the resolver
|
||||||
|
const resourcePaths = await this.resourcePathResolver.getResourcePaths(pandocOptions.vaultBasePath);
|
||||||
|
|
||||||
|
// Add each path to the pandoc arguments
|
||||||
|
for (const resourcePath of resourcePaths) {
|
||||||
|
args.push('--resource-path', resourcePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add template configuration to pandoc arguments
|
||||||
|
*/
|
||||||
|
private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise<void> {
|
||||||
|
// Use universal wrapper with --template and pass actual template as template_path variable
|
||||||
|
if (pandocOptions.template) {
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const absolutePluginDir = pandocOptions.pluginDir || '';
|
||||||
|
const wrapperPath = pathUtils.joinPath(absolutePluginDir, 'templates', 'universal-wrapper.pandoc.typ');
|
||||||
|
|
||||||
|
// Verify wrapper exists
|
||||||
|
if (!(await pathUtils.fileExists(wrapperPath))) {
|
||||||
|
throw new Error(`Universal wrapper template not found at: ${wrapperPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push('--template', wrapperPath);
|
||||||
|
|
||||||
|
// Add plugin templates directory as a resource path so Typst can find template files
|
||||||
|
const templatesDir = pathUtils.joinPath(absolutePluginDir, 'templates');
|
||||||
|
// Path quoting handled automatically by spawn
|
||||||
|
args.push('--resource-path', templatesDir);
|
||||||
|
|
||||||
|
// Pass the actual template path as a variable
|
||||||
|
// Use relative path from vault root for Typst import
|
||||||
|
let templatePathForTypst = pandocOptions.template;
|
||||||
|
if (path.isAbsolute(templatePathForTypst) && pandocOptions.vaultBasePath) {
|
||||||
|
// Make template path relative to vault for Typst import
|
||||||
|
templatePathForTypst = path.relative(pandocOptions.vaultBasePath, templatePathForTypst);
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push('-V', `template_path=${templatePathForTypst}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add all Typst variables using the variable mapper
|
||||||
|
*/
|
||||||
|
private addTypstVariables(args: string[], pandocOptions: PandocOptions): void {
|
||||||
|
// Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper
|
||||||
|
const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions);
|
||||||
|
|
||||||
|
// Convert to pandoc arguments and add to args
|
||||||
|
const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables);
|
||||||
|
args.push(...variableArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Typst engine options to pandoc arguments
|
||||||
|
*/
|
||||||
|
private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void {
|
||||||
|
if (pandocOptions.typstSettings?.engineOptions) {
|
||||||
|
for (const option of pandocOptions.typstSettings.engineOptions) {
|
||||||
|
args.push('--pdf-engine-opt', option);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add enhanced Typst diagnostics for better error reporting
|
||||||
|
*/
|
||||||
|
private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void {
|
||||||
|
// Add Typst diagnostic options for better error reporting
|
||||||
|
args.push('--pdf-engine-opt', '--diagnostic-format=short');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { spawn, ChildProcess } from 'child_process';
|
||||||
|
import { ConversionResult, ProgressCallback, PandocOptions } from '../converterTypes';
|
||||||
|
import { PathResolver } from '../../plugin/PathResolver';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles pandoc process execution, monitoring, and error parsing.
|
||||||
|
* Manages the spawning and lifecycle of pandoc processes for document conversion.
|
||||||
|
*/
|
||||||
|
export class PandocExecutor {
|
||||||
|
private pathResolver: PathResolver;
|
||||||
|
|
||||||
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathResolver = new PathResolver(plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute pandoc process with the given arguments
|
||||||
|
* @param args Command line arguments for pandoc
|
||||||
|
* @param pandocOptions Configuration options including paths and timeout
|
||||||
|
* @param progressCallback Optional callback for progress updates
|
||||||
|
* @returns Promise resolving to conversion result
|
||||||
|
*/
|
||||||
|
async executePandoc(
|
||||||
|
args: string[],
|
||||||
|
pandocOptions: PandocOptions,
|
||||||
|
progressCallback?: ProgressCallback
|
||||||
|
): Promise<ConversionResult> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const pandocPath = this.pathResolver.resolveExecutablePath(pandocOptions.pandocPath, 'pandoc');
|
||||||
|
const timeout = pandocOptions.timeout || 60000;
|
||||||
|
|
||||||
|
// Determine working directory - use vault base path if available, fallback to plugin directory
|
||||||
|
let workingDir: string;
|
||||||
|
|
||||||
|
if (pandocOptions.vaultBasePath) {
|
||||||
|
workingDir = pandocOptions.vaultBasePath;
|
||||||
|
} else {
|
||||||
|
// Fallback to plugin directory
|
||||||
|
const pluginDir = pandocOptions.pluginDir || process.cwd();
|
||||||
|
workingDir = pluginDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Augment PATH to include common binary locations
|
||||||
|
const augmentedEnv = {
|
||||||
|
...process.env,
|
||||||
|
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
||||||
|
};
|
||||||
|
|
||||||
|
// Spawn pandoc process with vault as working directory for attachment resolution
|
||||||
|
const pandocProcess: ChildProcess = spawn(pandocPath, args, {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
cwd: workingDir,
|
||||||
|
env: augmentedEnv, // Use augmented environment
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
let hasTimedOut = false;
|
||||||
|
|
||||||
|
// Set up timeout
|
||||||
|
const timeoutHandle = setTimeout(() => {
|
||||||
|
hasTimedOut = true;
|
||||||
|
pandocProcess.kill('SIGTERM');
|
||||||
|
resolve({
|
||||||
|
success: false,
|
||||||
|
error: `Pandoc process timed out after ${timeout}ms`,
|
||||||
|
exitCode: -1
|
||||||
|
});
|
||||||
|
}, timeout);
|
||||||
|
|
||||||
|
// Collect stdout
|
||||||
|
pandocProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
stdout += data.toString();
|
||||||
|
progressCallback?.('Processing document...', 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Collect stderr and monitor for progress
|
||||||
|
pandocProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
const output = data.toString();
|
||||||
|
stderr += output;
|
||||||
|
|
||||||
|
// Parse progress information from stderr if available
|
||||||
|
this.parseProgressFromOutput(output, progressCallback);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle process completion
|
||||||
|
pandocProcess.on('close', (code: number | null) => {
|
||||||
|
clearTimeout(timeoutHandle);
|
||||||
|
|
||||||
|
if (hasTimedOut) {
|
||||||
|
return; // Already resolved with timeout error
|
||||||
|
}
|
||||||
|
|
||||||
|
const success = code === 0;
|
||||||
|
const result: ConversionResult = {
|
||||||
|
success,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
exitCode: code || -1
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
result.error = this.extractErrorMessage(stderr, stdout);
|
||||||
|
} else {
|
||||||
|
progressCallback?.('PDF generation complete!', 90);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle process errors
|
||||||
|
pandocProcess.on('error', (error: Error) => {
|
||||||
|
clearTimeout(timeoutHandle);
|
||||||
|
resolve({
|
||||||
|
success: false,
|
||||||
|
error: `Failed to start Pandoc process: ${error.message}`,
|
||||||
|
exitCode: -1
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse progress information from pandoc output and update progress callback
|
||||||
|
* @param output Raw output from pandoc stderr
|
||||||
|
* @param progressCallback Optional callback to update progress
|
||||||
|
*/
|
||||||
|
private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
|
||||||
|
// Basic progress parsing - could be enhanced based on pandoc output patterns
|
||||||
|
if (output.includes('parsing') || output.includes('reading')) {
|
||||||
|
progressCallback?.('Reading input...', 45);
|
||||||
|
} else if (output.includes('writing') || output.includes('generating')) {
|
||||||
|
progressCallback?.('Generating output...', 75);
|
||||||
|
} else if (output.includes('typst')) {
|
||||||
|
progressCallback?.('Running Typst engine...', 85);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract meaningful error messages from pandoc output
|
||||||
|
* @param stderr Standard error output from pandoc
|
||||||
|
* @param stdout Standard output from pandoc
|
||||||
|
* @returns Formatted error message
|
||||||
|
*/
|
||||||
|
private extractErrorMessage(stderr: string, stdout: string): string {
|
||||||
|
// Look for common error patterns
|
||||||
|
const errorPatterns = [
|
||||||
|
/error:/i,
|
||||||
|
/Error:/,
|
||||||
|
/failed/i,
|
||||||
|
/Fatal/i,
|
||||||
|
/pandoc:/i
|
||||||
|
];
|
||||||
|
|
||||||
|
const allOutput = (stderr + '\n' + stdout).split('\n');
|
||||||
|
|
||||||
|
for (const line of allOutput) {
|
||||||
|
for (const pattern of errorPatterns) {
|
||||||
|
if (pattern.test(line)) {
|
||||||
|
return line.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no specific error found, return first non-empty line from stderr
|
||||||
|
const stderrLines = stderr.split('\n').filter(line => line.trim().length > 0);
|
||||||
|
if (stderrLines.length > 0) {
|
||||||
|
return stderrLines[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Unknown error occurred during conversion';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { PathUtils } from '../../core/PathUtils';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles resource path resolution and caching for Pandoc conversions.
|
||||||
|
* Discovers and caches attachment directories to help Pandoc find embedded resources.
|
||||||
|
*/
|
||||||
|
export class ResourcePathResolver {
|
||||||
|
private plugin: obsidianTypstPDFExport | undefined;
|
||||||
|
private resourcePathCache: string[] = [];
|
||||||
|
private resourcePathCacheTimestamp: number = 0;
|
||||||
|
private resourcePathCacheVaultPath: string = '';
|
||||||
|
private readonly CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
|
||||||
|
|
||||||
|
constructor(plugin?: obsidianTypstPDFExport) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all resource paths for the given vault, using cache when possible
|
||||||
|
* @param vaultBasePath The base path of the vault
|
||||||
|
* @returns Array of resource paths for Pandoc to search
|
||||||
|
*/
|
||||||
|
async getResourcePaths(vaultBasePath: string): Promise<string[]> {
|
||||||
|
if (!vaultBasePath || !this.plugin?.app) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const resourcePaths: string[] = [];
|
||||||
|
|
||||||
|
// Add vault root as primary resource path
|
||||||
|
resourcePaths.push(vaultBasePath);
|
||||||
|
|
||||||
|
// Add common attachment directories
|
||||||
|
const commonPaths = this.getCommonAttachmentPaths(vaultBasePath, pathUtils);
|
||||||
|
for (const attachPath of commonPaths) {
|
||||||
|
if (await pathUtils.fileExists(attachPath)) {
|
||||||
|
resourcePaths.push(attachPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add cached or freshly scanned resource paths
|
||||||
|
const now = Date.now();
|
||||||
|
if (this.isCacheValid(vaultBasePath, now)) {
|
||||||
|
// Use cached resource paths
|
||||||
|
resourcePaths.push(...this.resourcePathCache);
|
||||||
|
} else {
|
||||||
|
// Cache is invalid or expired, perform fresh scan
|
||||||
|
const scannedPaths = await this.scanForResourcePaths(vaultBasePath, pathUtils, now);
|
||||||
|
resourcePaths.push(...scannedPaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resourcePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get common attachment directory paths that Obsidian users typically use
|
||||||
|
* @param vaultBasePath The base path of the vault
|
||||||
|
* @param pathUtils PathUtils instance for path operations
|
||||||
|
* @returns Array of common attachment directory paths
|
||||||
|
*/
|
||||||
|
private getCommonAttachmentPaths(vaultBasePath: string, pathUtils: PathUtils): string[] {
|
||||||
|
return [
|
||||||
|
pathUtils.joinPath(vaultBasePath, 'attachments'),
|
||||||
|
pathUtils.joinPath(vaultBasePath, 'assets'),
|
||||||
|
pathUtils.joinPath(vaultBasePath, 'files'),
|
||||||
|
pathUtils.joinPath(vaultBasePath, 'images'),
|
||||||
|
pathUtils.joinPath(vaultBasePath, '.attachments')
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the resource path cache is still valid
|
||||||
|
* @param vaultBasePath The vault path to check against
|
||||||
|
* @param now Current timestamp
|
||||||
|
* @returns True if cache is valid and can be used
|
||||||
|
*/
|
||||||
|
private isCacheValid(vaultBasePath: string, now: number): boolean {
|
||||||
|
return this.resourcePathCacheVaultPath === vaultBasePath &&
|
||||||
|
(now - this.resourcePathCacheTimestamp) < this.CACHE_EXPIRY_MS &&
|
||||||
|
this.resourcePathCache.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan the vault for directories containing images and cache the results
|
||||||
|
* @param vaultBasePath The base path of the vault
|
||||||
|
* @param pathUtils PathUtils instance for path operations
|
||||||
|
* @param now Current timestamp
|
||||||
|
* @returns Array of resource paths found during scan
|
||||||
|
*/
|
||||||
|
private async scanForResourcePaths(vaultBasePath: string, pathUtils: PathUtils, now: number): Promise<string[]> {
|
||||||
|
const foundResourcePaths: string[] = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!this.plugin?.app) {
|
||||||
|
return foundResourcePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use vault root (empty string) for adapter.list() to get vault-relative paths
|
||||||
|
const vaultContents = await this.plugin.app.vault.adapter.list('');
|
||||||
|
for (const item of vaultContents.folders) {
|
||||||
|
const itemName = item.split('/').pop() || item;
|
||||||
|
|
||||||
|
if (!itemName.startsWith('.') && !itemName.startsWith('_')) {
|
||||||
|
// Check if this directory contains images
|
||||||
|
try {
|
||||||
|
const dirContents = await this.plugin.app.vault.adapter.list(item);
|
||||||
|
const hasImages = dirContents.files.some((file: string) =>
|
||||||
|
/\.(png|jpg|jpeg|gif|svg|webp|bmp|ico|tiff)$/i.test(file)
|
||||||
|
);
|
||||||
|
if (hasImages) {
|
||||||
|
// Convert vault-relative path to absolute path for external tools
|
||||||
|
const absolutePath = pathUtils.joinPath(vaultBasePath, item);
|
||||||
|
foundResourcePaths.push(absolutePath);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore directories we can't read
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update cache with fresh results
|
||||||
|
this.resourcePathCache = foundResourcePaths;
|
||||||
|
this.resourcePathCacheTimestamp = now;
|
||||||
|
this.resourcePathCacheVaultPath = vaultBasePath;
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Could not scan vault for attachment directories:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return foundResourcePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the resource path cache
|
||||||
|
*/
|
||||||
|
clearCache(): void {
|
||||||
|
this.resourcePathCache = [];
|
||||||
|
this.resourcePathCacheTimestamp = 0;
|
||||||
|
this.resourcePathCacheVaultPath = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
/**
|
||||||
|
* Typst Variable Mapper
|
||||||
|
* Handles mapping of ExportConfig and plugin settings to Typst template variables
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { mapToTypstPaperSize } from '../../utils/paperSizeMapper';
|
||||||
|
import { PandocOptions } from '../converterTypes';
|
||||||
|
import type { obsidianTypstPDFExportSettings } from '../../core/settings';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
export interface TypstVariable {
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TypstVariableMapper {
|
||||||
|
private plugin: obsidianTypstPDFExport;
|
||||||
|
|
||||||
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map all variables from ExportConfig and plugin settings to Typst variables
|
||||||
|
* ExportConfig variables take priority over plugin settings
|
||||||
|
*/
|
||||||
|
mapAllVariablesToTypst(pandocOptions: PandocOptions): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
// Add variables from ExportConfig (these take priority)
|
||||||
|
const exportConfigVariables = this.mapExportConfigVariables(pandocOptions);
|
||||||
|
variables.push(...exportConfigVariables);
|
||||||
|
|
||||||
|
// Add fallback variables from plugin settings (only if not already present)
|
||||||
|
const pluginSettingsVariables = this.mapPluginSettingsVariables(pandocOptions);
|
||||||
|
variables.push(...pluginSettingsVariables);
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map ExportConfig variables to Typst variables with transformations
|
||||||
|
*/
|
||||||
|
private mapExportConfigVariables(pandocOptions: PandocOptions): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
if (!pandocOptions.variables) {
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(pandocOptions.variables)) {
|
||||||
|
if (value !== null && value !== undefined && value.toString().trim() !== '') {
|
||||||
|
const mappedVariable = this.transformExportConfigVariable(key, value);
|
||||||
|
if (mappedVariable) {
|
||||||
|
variables.push(mappedVariable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform a single ExportConfig variable to Typst variable with name mapping and unit conversion
|
||||||
|
*/
|
||||||
|
private transformExportConfigVariable(key: string, value: string | number | boolean): TypstVariable | null {
|
||||||
|
// Handle special variable name mappings for Typst compatibility
|
||||||
|
let variableName = key;
|
||||||
|
let processedValue = value;
|
||||||
|
|
||||||
|
switch (key) {
|
||||||
|
case 'bodyFont':
|
||||||
|
variableName = 'font';
|
||||||
|
break;
|
||||||
|
case 'headingFont':
|
||||||
|
variableName = 'heading_font';
|
||||||
|
break;
|
||||||
|
case 'monospaceFont':
|
||||||
|
variableName = 'monospace_font';
|
||||||
|
break;
|
||||||
|
case 'bodyFontSize':
|
||||||
|
variableName = 'fontsize';
|
||||||
|
processedValue = value + 'pt';
|
||||||
|
break;
|
||||||
|
case 'pageSize':
|
||||||
|
variableName = 'paper';
|
||||||
|
// Convert to Typst-compatible paper size
|
||||||
|
processedValue = mapToTypstPaperSize(value.toString());
|
||||||
|
break;
|
||||||
|
case 'marginTop':
|
||||||
|
variableName = 'margin_top';
|
||||||
|
processedValue = value + 'cm';
|
||||||
|
break;
|
||||||
|
case 'marginBottom':
|
||||||
|
variableName = 'margin_bottom';
|
||||||
|
processedValue = value + 'cm';
|
||||||
|
break;
|
||||||
|
case 'marginLeft':
|
||||||
|
variableName = 'margin_left';
|
||||||
|
processedValue = value + 'cm';
|
||||||
|
break;
|
||||||
|
case 'marginRight':
|
||||||
|
variableName = 'margin_right';
|
||||||
|
processedValue = value + 'cm';
|
||||||
|
break;
|
||||||
|
// Keep other variables as-is (orientation, flipped, width, etc.)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: variableName,
|
||||||
|
value: processedValue.toString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map plugin settings to Typst variables as fallbacks (only if not already present in ExportConfig)
|
||||||
|
*/
|
||||||
|
private mapPluginSettingsVariables(pandocOptions: PandocOptions): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
if (!this.plugin || !this.plugin.settings) {
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
const settings: obsidianTypstPDFExportSettings = this.plugin.settings;
|
||||||
|
const existingVars = pandocOptions.variables || {};
|
||||||
|
|
||||||
|
// Add typography variables only if not already present in variables
|
||||||
|
variables.push(...this.mapTypographyVariables(settings, existingVars));
|
||||||
|
|
||||||
|
// Add page setup variables only if not already present
|
||||||
|
variables.push(...this.mapPageSetupVariables(settings, existingVars));
|
||||||
|
|
||||||
|
// Add export format variable - only use settings default if not already provided
|
||||||
|
if (!existingVars.export_format && settings.exportDefaults && settings.exportDefaults.format) {
|
||||||
|
variables.push({
|
||||||
|
name: 'export_format',
|
||||||
|
value: settings.exportDefaults.format
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map typography settings to Typst variables
|
||||||
|
*/
|
||||||
|
private mapTypographyVariables(settings: obsidianTypstPDFExportSettings, existingVars: Record<string, string | number | boolean>): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
if (!settings.typography) {
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Font variables
|
||||||
|
if (settings.typography.fonts) {
|
||||||
|
// Only add if not already in variables from ExportConfig
|
||||||
|
if (!existingVars.bodyFont && !existingVars.font && settings.typography.fonts.body) {
|
||||||
|
variables.push({
|
||||||
|
name: 'font',
|
||||||
|
value: settings.typography.fonts.body
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!existingVars.headingFont && !existingVars.heading_font && settings.typography.fonts.heading) {
|
||||||
|
variables.push({
|
||||||
|
name: 'heading_font',
|
||||||
|
value: settings.typography.fonts.heading
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!existingVars.monospaceFont && !existingVars.monospace_font && settings.typography.fonts.monospace) {
|
||||||
|
variables.push({
|
||||||
|
name: 'monospace_font',
|
||||||
|
value: settings.typography.fonts.monospace
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Font size variables
|
||||||
|
if (settings.typography.fontSizes) {
|
||||||
|
if (!existingVars.bodyFontSize && !existingVars.fontsize && settings.typography.fontSizes.body) {
|
||||||
|
variables.push({
|
||||||
|
name: 'fontsize',
|
||||||
|
value: `${settings.typography.fontSizes.body}pt`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map page setup settings to Typst variables
|
||||||
|
*/
|
||||||
|
private mapPageSetupVariables(settings: obsidianTypstPDFExportSettings, existingVars: Record<string, string | number | boolean>): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
if (!settings.pageSetup) {
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paper size variable
|
||||||
|
if (!existingVars.pageSize && !existingVars.paper && settings.pageSetup.size) {
|
||||||
|
const typstPaperSize = mapToTypstPaperSize(settings.pageSetup.size);
|
||||||
|
variables.push({
|
||||||
|
name: 'paper',
|
||||||
|
value: typstPaperSize
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Orientation variable
|
||||||
|
if (!existingVars.orientation && settings.pageSetup.orientation) {
|
||||||
|
variables.push({
|
||||||
|
name: 'orientation',
|
||||||
|
value: settings.pageSetup.orientation
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Margin variables - only add if not already specified
|
||||||
|
if (settings.pageSetup.margins) {
|
||||||
|
variables.push(...this.mapMarginVariables(settings.pageSetup.margins, existingVars));
|
||||||
|
}
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map margin settings to Typst variables
|
||||||
|
*/
|
||||||
|
private mapMarginVariables(margins: {top: number; right: number; bottom: number; left: number;}, existingVars: Record<string, string | number | boolean>): TypstVariable[] {
|
||||||
|
const variables: TypstVariable[] = [];
|
||||||
|
|
||||||
|
if (!existingVars.marginTop && !existingVars.margin_top && margins.top !== undefined) {
|
||||||
|
variables.push({
|
||||||
|
name: 'margin_top',
|
||||||
|
value: `${margins.top}cm`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!existingVars.marginRight && !existingVars.margin_right && margins.right !== undefined) {
|
||||||
|
variables.push({
|
||||||
|
name: 'margin_right',
|
||||||
|
value: `${margins.right}cm`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!existingVars.marginBottom && !existingVars.margin_bottom && margins.bottom !== undefined) {
|
||||||
|
variables.push({
|
||||||
|
name: 'margin_bottom',
|
||||||
|
value: `${margins.bottom}cm`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!existingVars.marginLeft && !existingVars.margin_left && margins.left !== undefined) {
|
||||||
|
variables.push({
|
||||||
|
name: 'margin_left',
|
||||||
|
value: `${margins.left}cm`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return variables;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a set of variable names that are already defined in ExportConfig
|
||||||
|
* Used for priority checking between ExportConfig and plugin settings
|
||||||
|
*/
|
||||||
|
getExportConfigVariableNames(pandocOptions: PandocOptions): Set<string> {
|
||||||
|
const names = new Set<string>();
|
||||||
|
|
||||||
|
if (!pandocOptions.variables) {
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(pandocOptions.variables)) {
|
||||||
|
if (value !== null && value !== undefined && value.toString().trim() !== '') {
|
||||||
|
// Add both original key and mapped name
|
||||||
|
names.add(key);
|
||||||
|
|
||||||
|
// Add mapped names for priority checking
|
||||||
|
switch (key) {
|
||||||
|
case 'bodyFont':
|
||||||
|
names.add('font');
|
||||||
|
break;
|
||||||
|
case 'headingFont':
|
||||||
|
names.add('heading_font');
|
||||||
|
break;
|
||||||
|
case 'monospaceFont':
|
||||||
|
names.add('monospace_font');
|
||||||
|
break;
|
||||||
|
case 'bodyFontSize':
|
||||||
|
names.add('fontsize');
|
||||||
|
break;
|
||||||
|
case 'pageSize':
|
||||||
|
names.add('paper');
|
||||||
|
break;
|
||||||
|
case 'marginTop':
|
||||||
|
names.add('margin_top');
|
||||||
|
break;
|
||||||
|
case 'marginBottom':
|
||||||
|
names.add('margin_bottom');
|
||||||
|
break;
|
||||||
|
case 'marginLeft':
|
||||||
|
names.add('margin_left');
|
||||||
|
break;
|
||||||
|
case 'marginRight':
|
||||||
|
names.add('margin_right');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert TypstVariable array to pandoc argument format
|
||||||
|
*/
|
||||||
|
convertVariablesToPandocArgs(variables: TypstVariable[]): string[] {
|
||||||
|
const args: string[] = [];
|
||||||
|
|
||||||
|
for (const variable of variables) {
|
||||||
|
args.push('-V', `${variable.name}=${variable.value}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
/**
|
||||||
|
* Binary locator utilities for finding external tool binaries.
|
||||||
|
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as path from 'path';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
import { PathUtils } from '../../core/PathUtils';
|
||||||
|
|
||||||
|
export interface BinaryLocation {
|
||||||
|
/** Full path to the binary */
|
||||||
|
binaryPath: string;
|
||||||
|
/** Whether the binary was found and is executable */
|
||||||
|
exists: boolean;
|
||||||
|
/** Error message if binary was not found */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BinaryLocator {
|
||||||
|
/**
|
||||||
|
* Find the pdf2img binary in the plugin's node_modules directory.
|
||||||
|
* Handles the complex Obsidian environment where __dirname points to electron.asar.
|
||||||
|
* Includes Windows-specific executable detection and fallback paths.
|
||||||
|
* @param plugin The plugin instance for accessing manifest and settings
|
||||||
|
* @returns Binary location info
|
||||||
|
*/
|
||||||
|
public static async findPdf2ImgBinary(plugin?: obsidianTypstPDFExport): Promise<BinaryLocation> {
|
||||||
|
try {
|
||||||
|
// Get the plugin directory - need to handle Obsidian's environment
|
||||||
|
// In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path
|
||||||
|
// Try multiple strategies to find the plugin directory
|
||||||
|
const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export';
|
||||||
|
const configDir = plugin?.app.vault.configDir || '.obsidian';
|
||||||
|
const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir);
|
||||||
|
|
||||||
|
// Find the first directory that exists and has node_modules
|
||||||
|
let pluginDir = possiblePluginDirs[0]; // Default fallback
|
||||||
|
for (const dir of possiblePluginDirs) {
|
||||||
|
try {
|
||||||
|
const nodeModulesPath = path.join(dir, 'node_modules');
|
||||||
|
if (plugin?.app) {
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
if (await pathUtils.fileExists(nodeModulesPath)) {
|
||||||
|
pluginDir = dir;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find the binary with platform-specific handling
|
||||||
|
const binaryLocation = await this.findBinaryWithFallbacks(pluginDir, plugin);
|
||||||
|
|
||||||
|
return binaryLocation;
|
||||||
|
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
binaryPath: '',
|
||||||
|
exists: false,
|
||||||
|
error: `Failed to locate pdf2img binary: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the pdf2img binary with platform-specific extensions and multiple fallback paths.
|
||||||
|
* @param pluginDir The plugin directory path
|
||||||
|
* @param plugin The plugin instance for path utilities
|
||||||
|
* @returns Binary location info
|
||||||
|
*/
|
||||||
|
private static async findBinaryWithFallbacks(pluginDir: string, plugin?: obsidianTypstPDFExport): Promise<BinaryLocation> {
|
||||||
|
// Define Windows-specific executable extensions
|
||||||
|
const windowsExtensions = process.platform === 'win32' ? ['.cmd', '.bat', '.ps1', '.exe'] : [''];
|
||||||
|
|
||||||
|
// Get platform-specific binary name
|
||||||
|
const baseBinaryName = 'pdf2img';
|
||||||
|
|
||||||
|
// Define fallback search paths for different installation methods
|
||||||
|
const fallbackPaths = [
|
||||||
|
// Standard npm binary location
|
||||||
|
path.join(pluginDir, 'node_modules', '.bin'),
|
||||||
|
// Direct package binary location
|
||||||
|
path.join(pluginDir, 'node_modules', 'pdf-to-img', 'bin'),
|
||||||
|
// Windows-specific npm locations
|
||||||
|
...(process.platform === 'win32' ? [
|
||||||
|
path.join(process.env.APPDATA || '', 'npm'),
|
||||||
|
path.join(process.env.LOCALAPPDATA || '', 'npm-cache'),
|
||||||
|
// Additional Windows global npm locations
|
||||||
|
path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'nodejs'),
|
||||||
|
path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'nodejs')
|
||||||
|
] : [])
|
||||||
|
];
|
||||||
|
|
||||||
|
// Try each fallback path with platform-specific extensions
|
||||||
|
for (const searchPath of fallbackPaths) {
|
||||||
|
for (const extension of windowsExtensions) {
|
||||||
|
const binaryName = baseBinaryName + extension;
|
||||||
|
const fullBinaryPath = path.join(searchPath, binaryName);
|
||||||
|
|
||||||
|
// Check if this binary exists and is accessible
|
||||||
|
const exists = await this.validateBinaryExists(fullBinaryPath, plugin);
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
return {
|
||||||
|
binaryPath: fullBinaryPath,
|
||||||
|
exists: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no binary found, return the default expected path for error reporting
|
||||||
|
const defaultPath = path.join(pluginDir, 'node_modules', '.bin', baseBinaryName);
|
||||||
|
const finalPath = process.platform === 'win32' ? defaultPath + '.cmd' : defaultPath;
|
||||||
|
|
||||||
|
return {
|
||||||
|
binaryPath: finalPath,
|
||||||
|
exists: false,
|
||||||
|
error: `PDF2IMG binary not found. Searched in ${fallbackPaths.length} locations with platform-specific extensions. Expected at: ${finalPath}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get possible plugin directory locations based on different Obsidian environments.
|
||||||
|
* @param plugin Plugin instance
|
||||||
|
* @param pluginDirName Name of the plugin directory
|
||||||
|
* @param configDir Obsidian config directory (.obsidian)
|
||||||
|
* @returns Array of possible plugin directory paths
|
||||||
|
*/
|
||||||
|
private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] {
|
||||||
|
return [
|
||||||
|
// Strategy 1: From process.cwd() if it's in the vault
|
||||||
|
path.join(process.cwd(), configDir, 'plugins', pluginDirName),
|
||||||
|
// Strategy 2: Assuming we're running from vault root
|
||||||
|
path.join(configDir, 'plugins', pluginDirName),
|
||||||
|
// Strategy 3: From vault base path if plugin is available
|
||||||
|
...(plugin ? [path.join(new PathUtils(plugin.app).getVaultPath(), plugin.manifest.dir!)] : [])
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate that a binary exists and is accessible.
|
||||||
|
* @param binaryPath Full path to the binary
|
||||||
|
* @param plugin Plugin instance for PathUtils
|
||||||
|
* @returns True if binary exists, false otherwise
|
||||||
|
*/
|
||||||
|
private static async validateBinaryExists(binaryPath: string, plugin?: obsidianTypstPDFExport): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
if (!plugin?.app) {
|
||||||
|
// This should not happen in normal plugin operation, but provide fallback
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
await fs.access(binaryPath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
return await pathUtils.fileExists(binaryPath);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
/**
|
||||||
|
* Environment utilities for setting up CLI tool execution environment.
|
||||||
|
* Handles PATH augmentation and environment variable setup for external tools.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { obsidianTypstPDFExportSettings } from '../../core/settings';
|
||||||
|
|
||||||
|
export interface EnvironmentSetupOptions {
|
||||||
|
/** Additional paths to include in PATH */
|
||||||
|
additionalPaths?: string[];
|
||||||
|
/** Base environment to extend */
|
||||||
|
baseEnvironment?: NodeJS.ProcessEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EnvironmentUtils {
|
||||||
|
/**
|
||||||
|
* Get augmented environment with extended PATH for CLI tool execution.
|
||||||
|
* Ensures Node.js and other common tool paths are available.
|
||||||
|
* @param settings Plugin settings containing additional paths
|
||||||
|
* @param options Additional environment setup options
|
||||||
|
* @returns Augmented environment with extended PATH
|
||||||
|
*/
|
||||||
|
public static getAugmentedEnvironment(
|
||||||
|
settings?: obsidianTypstPDFExportSettings,
|
||||||
|
options: EnvironmentSetupOptions = {}
|
||||||
|
): NodeJS.ProcessEnv {
|
||||||
|
// Common tool paths where CLI tools might be installed
|
||||||
|
const commonToolPaths = [
|
||||||
|
'/opt/homebrew/bin', // Homebrew on Apple Silicon
|
||||||
|
'/usr/local/bin', // Homebrew on Intel Mac, standard Unix tools
|
||||||
|
'/usr/bin', // System binaries
|
||||||
|
'/bin', // Core system binaries
|
||||||
|
'/usr/local/texlive/bin', // TeX Live installation
|
||||||
|
'/Library/TeX/texbin', // MacTeX installation
|
||||||
|
...(options.additionalPaths || [])
|
||||||
|
];
|
||||||
|
|
||||||
|
// Get base environment
|
||||||
|
const baseEnv = options.baseEnvironment || process.env;
|
||||||
|
|
||||||
|
// Build augmented PATH
|
||||||
|
const existingPath = baseEnv.PATH || '';
|
||||||
|
const augmentedPath = [
|
||||||
|
...commonToolPaths,
|
||||||
|
existingPath
|
||||||
|
].filter(Boolean).join(':');
|
||||||
|
|
||||||
|
// Create augmented environment
|
||||||
|
const augmentedEnv = {
|
||||||
|
...baseEnv,
|
||||||
|
PATH: augmentedPath,
|
||||||
|
// Ensure locale is set for proper tool operation
|
||||||
|
LC_ALL: baseEnv.LC_ALL || 'en_US.UTF-8',
|
||||||
|
LANG: baseEnv.LANG || 'en_US.UTF-8'
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add any custom environment variables from settings if available
|
||||||
|
if (settings?.customEnvironmentVariables) {
|
||||||
|
Object.assign(augmentedEnv, settings.customEnvironmentVariables);
|
||||||
|
}
|
||||||
|
|
||||||
|
return augmentedEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get common Node.js installation paths.
|
||||||
|
* @returns Array of common Node.js binary paths
|
||||||
|
*/
|
||||||
|
private static getNodePaths(): string[] {
|
||||||
|
return [
|
||||||
|
'/usr/local/bin', // Common Node.js installation
|
||||||
|
'/opt/homebrew/bin', // Homebrew on macOS
|
||||||
|
'/usr/bin', // System Node.js
|
||||||
|
'/usr/local/node/bin' // Alternative Node.js location
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge multiple PATH variables into a single PATH string.
|
||||||
|
* @param paths Array of path strings to merge
|
||||||
|
* @returns Merged PATH string
|
||||||
|
*/
|
||||||
|
private static mergePathVariables(paths: (string | undefined)[]): string {
|
||||||
|
return paths
|
||||||
|
.filter(Boolean) // Remove undefined/empty paths
|
||||||
|
.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create environment for executing CLI commands with timeout.
|
||||||
|
* @param settings Plugin settings
|
||||||
|
* @param timeout Command timeout in milliseconds
|
||||||
|
* @returns Environment configuration object
|
||||||
|
*/
|
||||||
|
public static createCliEnvironment(settings?: obsidianTypstPDFExportSettings, timeout?: number) {
|
||||||
|
const env = this.getAugmentedEnvironment(settings);
|
||||||
|
|
||||||
|
return {
|
||||||
|
env,
|
||||||
|
timeout: timeout || 60000, // Default 60 second timeout
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'] as const,
|
||||||
|
shell: false // Use direct process spawning for better control
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
/**
|
||||||
|
* File discovery utilities for finding generated PDF to image conversion outputs.
|
||||||
|
* Handles filename pattern matching when pdf2img generates files with different names.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as path from 'path';
|
||||||
|
import { PathUtils } from '../../core/PathUtils';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
export interface FileDiscoveryResult {
|
||||||
|
/** Path to the discovered file */
|
||||||
|
filePath: string;
|
||||||
|
/** Whether the file was found successfully */
|
||||||
|
found: boolean;
|
||||||
|
/** Error message if file was not found */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FileDiscovery {
|
||||||
|
/** Supported image extensions for PDF conversion output */
|
||||||
|
private static readonly SUPPORTED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'];
|
||||||
|
/**
|
||||||
|
* Find the generated image file in the output directory.
|
||||||
|
* Handles cases where pdf2img sanitizes filenames differently than expected.
|
||||||
|
* @param outputDir Directory where files were generated
|
||||||
|
* @param expectedFileName Expected output filename
|
||||||
|
* @param plugin Plugin instance for PathUtils
|
||||||
|
* @returns Discovery result with actual file path
|
||||||
|
*/
|
||||||
|
public static async findGeneratedFile(
|
||||||
|
outputDir: string,
|
||||||
|
expectedFileName: string,
|
||||||
|
plugin?: obsidianTypstPDFExport
|
||||||
|
): Promise<FileDiscoveryResult> {
|
||||||
|
if (!plugin?.app) {
|
||||||
|
// Fallback to path for external tool output directories
|
||||||
|
const expectedOutputPath = path.join(outputDir, expectedFileName);
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
try {
|
||||||
|
await fs.access(expectedOutputPath);
|
||||||
|
return {
|
||||||
|
filePath: expectedOutputPath,
|
||||||
|
found: true
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return await this.findAlternativeFileFs(outputDir, expectedFileName, expectedOutputPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
const expectedOutputPath = pathUtils.joinPath(outputDir, expectedFileName);
|
||||||
|
|
||||||
|
// Check if the expected output file exists first
|
||||||
|
try {
|
||||||
|
if (await pathUtils.fileExists(expectedOutputPath)) {
|
||||||
|
return {
|
||||||
|
filePath: expectedOutputPath,
|
||||||
|
found: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Continue to alternative search
|
||||||
|
}
|
||||||
|
|
||||||
|
// File not found with expected name, try to find alternatives
|
||||||
|
return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath, plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find alternative files when the expected filename doesn't match (using vault.adapter).
|
||||||
|
* @param outputDir Output directory to search
|
||||||
|
* @param expectedFileName Expected filename for pattern matching
|
||||||
|
* @param expectedOutputPath Full expected output path
|
||||||
|
* @param plugin Plugin instance for vault access
|
||||||
|
* @returns Discovery result with alternative file if found
|
||||||
|
*/
|
||||||
|
private static async findAlternativeFile(
|
||||||
|
outputDir: string,
|
||||||
|
expectedFileName: string,
|
||||||
|
expectedOutputPath: string,
|
||||||
|
plugin: obsidianTypstPDFExport
|
||||||
|
): Promise<FileDiscoveryResult> {
|
||||||
|
try {
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
|
||||||
|
// Check if outputDir is inside the vault
|
||||||
|
let vaultPath = '';
|
||||||
|
try {
|
||||||
|
vaultPath = pathUtils.getVaultPath();
|
||||||
|
} catch {
|
||||||
|
// If vault path unavailable, treat all paths as external
|
||||||
|
vaultPath = '';
|
||||||
|
}
|
||||||
|
let isVaultRelative = false;
|
||||||
|
let vaultRelativeDir = outputDir;
|
||||||
|
|
||||||
|
if (vaultPath) {
|
||||||
|
// Compute relative path from vault root
|
||||||
|
const relativePath = path.relative(vaultPath, outputDir);
|
||||||
|
// Path is inside vault if it doesn't start with '..' or path separator
|
||||||
|
isVaultRelative = !relativePath.startsWith('..') && !path.isAbsolute(relativePath);
|
||||||
|
if (isVaultRelative) {
|
||||||
|
vaultRelativeDir = relativePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let files: string[];
|
||||||
|
|
||||||
|
if (isVaultRelative) {
|
||||||
|
// Use adapter for vault-relative paths
|
||||||
|
const dirList = await plugin.app.vault.adapter.list(vaultRelativeDir);
|
||||||
|
files = dirList.files.map(f => path.basename(f));
|
||||||
|
} else {
|
||||||
|
// Use filesystem fallback for absolute/external paths
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
files = await fs.readdir(outputDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look for any image files that might match
|
||||||
|
const imageFiles = files.filter(f =>
|
||||||
|
this.SUPPORTED_IMAGE_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))
|
||||||
|
);
|
||||||
|
if (imageFiles.length === 0) {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `No image files found in output directory: ${outputDir}. Supported formats: ${this.SUPPORTED_IMAGE_EXTENSIONS.join(', ')}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find a file that matches the pattern (with or without exact name)
|
||||||
|
// pdf2img might sanitize filenames differently
|
||||||
|
const matchingFile = this.matchFilePattern(imageFiles, expectedFileName);
|
||||||
|
|
||||||
|
if (matchingFile) {
|
||||||
|
const actualOutputPath = pathUtils.joinPath(outputDir, matchingFile);
|
||||||
|
|
||||||
|
// Final check if we found an alternative file
|
||||||
|
if (await pathUtils.fileExists(actualOutputPath)) {
|
||||||
|
return {
|
||||||
|
filePath: actualOutputPath,
|
||||||
|
found: true
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Alternative file not accessible: ${actualOutputPath}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Generated image file not found: ${expectedOutputPath}. Available files: ${imageFiles.join(', ')}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (listError: unknown) {
|
||||||
|
console.error(`Failed to list output directory:`, listError);
|
||||||
|
const errorMessage = listError instanceof Error ? listError.message : String(listError);
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Failed to search output directory: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find alternative files when the expected filename doesn't match (fs fallback).
|
||||||
|
* @param outputDir Output directory to search
|
||||||
|
* @param expectedFileName Expected filename for pattern matching
|
||||||
|
* @param expectedOutputPath Full expected output path
|
||||||
|
* @returns Discovery result with alternative file if found
|
||||||
|
*/
|
||||||
|
private static async findAlternativeFileFs(
|
||||||
|
outputDir: string,
|
||||||
|
expectedFileName: string,
|
||||||
|
expectedOutputPath: string
|
||||||
|
): Promise<FileDiscoveryResult> {
|
||||||
|
try {
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
// Debug: List what files are actually in the output directory
|
||||||
|
const files = await fs.readdir(outputDir);
|
||||||
|
|
||||||
|
// Look for any image files that might match
|
||||||
|
const imageFiles = files.filter((f: string) =>
|
||||||
|
this.SUPPORTED_IMAGE_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))
|
||||||
|
);
|
||||||
|
if (imageFiles.length === 0) {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `No image files found in output directory: ${outputDir}. Supported formats: ${this.SUPPORTED_IMAGE_EXTENSIONS.join(', ')}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find a file that matches the pattern (with or without exact name)
|
||||||
|
// pdf2img might sanitize filenames differently
|
||||||
|
const matchingFile = this.matchFilePattern(imageFiles, expectedFileName);
|
||||||
|
|
||||||
|
if (matchingFile) {
|
||||||
|
const actualOutputPath = path.join(outputDir, matchingFile);
|
||||||
|
|
||||||
|
// Final check if we found an alternative file
|
||||||
|
try {
|
||||||
|
await fs.access(actualOutputPath);
|
||||||
|
return {
|
||||||
|
filePath: actualOutputPath,
|
||||||
|
found: true
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Alternative file not accessible: ${actualOutputPath}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Generated image file not found: ${expectedOutputPath}. Available files: ${imageFiles.join(', ')}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (listError: unknown) {
|
||||||
|
console.error(`Failed to list output directory:`, listError);
|
||||||
|
const errorMessage = listError instanceof Error ? listError.message : String(listError);
|
||||||
|
return {
|
||||||
|
filePath: '',
|
||||||
|
found: false,
|
||||||
|
error: `Failed to search output directory: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Match files against expected filename patterns using multiple strategies.
|
||||||
|
* Handles filename sanitization that pdf2img might apply and supports multiple image formats.
|
||||||
|
* @param files Array of available filenames
|
||||||
|
* @param expectedFileName Expected filename pattern
|
||||||
|
* @returns Matching filename or null if no match found
|
||||||
|
*/
|
||||||
|
private static matchFilePattern(files: string[], expectedFileName: string): string | null {
|
||||||
|
const expectedBase = path.basename(expectedFileName, path.extname(expectedFileName));
|
||||||
|
|
||||||
|
// Strategy 1: Exact match
|
||||||
|
const exactMatch = files.find(f => f === expectedFileName);
|
||||||
|
if (exactMatch) {
|
||||||
|
return exactMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 2: Base name match with any supported extension
|
||||||
|
const baseNameMatch = files.find(f => {
|
||||||
|
const fileBase = path.basename(f, path.extname(f));
|
||||||
|
return fileBase === expectedBase;
|
||||||
|
});
|
||||||
|
if (baseNameMatch) {
|
||||||
|
return baseNameMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 3: Sanitized pattern match (remove special characters)
|
||||||
|
const simplifiedExpected = this.sanitizeFilename(expectedBase);
|
||||||
|
const sanitizedMatch = files.find(f => {
|
||||||
|
const fileBase = path.basename(f, path.extname(f));
|
||||||
|
const simplifiedActual = this.sanitizeFilename(fileBase);
|
||||||
|
return simplifiedActual === simplifiedExpected;
|
||||||
|
});
|
||||||
|
if (sanitizedMatch) {
|
||||||
|
return sanitizedMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 4: Fuzzy match for pdf2img output patterns (filename-1.ext, filename-page1.ext, etc.)
|
||||||
|
const fuzzyMatch = files.find(f => {
|
||||||
|
const fileBase = path.basename(f, path.extname(f));
|
||||||
|
// Remove common pdf2img suffixes like "-1", "-page1", etc.
|
||||||
|
const cleanedFileBase = fileBase.replace(/[-_](page)?\d+$/i, '');
|
||||||
|
const cleanedExpectedBase = expectedBase.replace(/[-_](page)?\d+$/i, '');
|
||||||
|
return cleanedFileBase === cleanedExpectedBase ||
|
||||||
|
this.sanitizeFilename(cleanedFileBase) === this.sanitizeFilename(cleanedExpectedBase);
|
||||||
|
});
|
||||||
|
if (fuzzyMatch) {
|
||||||
|
return fuzzyMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 5: Fallback to first available image file if no pattern matches
|
||||||
|
return files.length > 0 ? files[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize filename by removing special characters for pattern matching.
|
||||||
|
* @param filename Original filename
|
||||||
|
* @returns Sanitized filename for comparison
|
||||||
|
*/
|
||||||
|
private static sanitizeFilename(filename: string): string {
|
||||||
|
return filename.replace(/[^a-zA-Z0-9.-]/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate expected output filename for pdf2img conversion.
|
||||||
|
* pdf2img uses the pattern: "filename-1.ext" for first page.
|
||||||
|
* @param pdfBaseName Base name of the PDF file (without extension)
|
||||||
|
* @param pageNumber Page number (1-based)
|
||||||
|
* @param format Output format (defaults to 'png', supports any image format)
|
||||||
|
* @returns Expected output filename
|
||||||
|
*/
|
||||||
|
public static generateExpectedFilename(
|
||||||
|
pdfBaseName: string,
|
||||||
|
pageNumber: number = 1,
|
||||||
|
format: string = 'png'
|
||||||
|
): string {
|
||||||
|
// Validate format is supported
|
||||||
|
const formatExtension = format.toLowerCase().startsWith('.') ? format.substring(1) : format.toLowerCase();
|
||||||
|
const supportedFormats = this.SUPPORTED_IMAGE_EXTENSIONS.map(ext => ext.substring(1));
|
||||||
|
|
||||||
|
if (!supportedFormats.includes(formatExtension)) {
|
||||||
|
console.warn(`Unsupported image format '${format}', falling back to PNG`);
|
||||||
|
return `${pdfBaseName}-${pageNumber}.png`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${pdfBaseName}-${pageNumber}.${formatExtension}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
/**
|
||||||
|
* Image optimization utilities for PDF to image conversion.
|
||||||
|
* Handles format conversion, quality management, and dimension detection.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as path from 'path';
|
||||||
|
import { PathUtils } from '../../core/PathUtils';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
export interface ImageOptimizationOptions {
|
||||||
|
/** Output format (default: 'png') */
|
||||||
|
format?: 'png' | 'jpeg';
|
||||||
|
/** JPEG quality if using jpeg format (default: 90) */
|
||||||
|
quality?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageDimensions {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageOptimizationResult {
|
||||||
|
/** Path to the optimized image file */
|
||||||
|
imagePath: string;
|
||||||
|
/** Image dimensions after optimization */
|
||||||
|
dimensions: ImageDimensions;
|
||||||
|
/** Success status */
|
||||||
|
success: boolean;
|
||||||
|
/** Error message if optimization failed */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ImageOptimizer {
|
||||||
|
/**
|
||||||
|
* Get augmented environment with extended PATH for ImageMagick
|
||||||
|
*/
|
||||||
|
private static getAugmentedEnv(): NodeJS.ProcessEnv {
|
||||||
|
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
||||||
|
const commonPaths = [
|
||||||
|
'/opt/homebrew/bin',
|
||||||
|
'/usr/local/bin',
|
||||||
|
'/usr/bin'
|
||||||
|
].map(p => homeDir.includes('Users') ? p : homeDir + p);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
PATH: `${process.env.PATH}:${commonPaths.join(':')}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert PNG image to JPEG with quality optimization.
|
||||||
|
* Falls back to keeping PNG format if ImageMagick is not available.
|
||||||
|
*/
|
||||||
|
public static async convertPngToJpeg(
|
||||||
|
inputPngPath: string,
|
||||||
|
outputJpegPath: string,
|
||||||
|
quality: number = 90
|
||||||
|
): Promise<{success: boolean; error?: string}> {
|
||||||
|
try {
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
// Use ImageMagick to convert PNG to JPEG
|
||||||
|
const convertProcess = spawn('magick', [
|
||||||
|
inputPngPath,
|
||||||
|
'-quality', quality.toString(),
|
||||||
|
outputJpegPath
|
||||||
|
], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: this.getAugmentedEnv()
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let error = '';
|
||||||
|
convertProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
convertProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve();
|
||||||
|
} else {
|
||||||
|
reject(new Error(`ImageMagick conversion failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
convertProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn ImageMagick: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `JPEG conversion failed: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get image dimensions using ImageMagick identify command.
|
||||||
|
* Falls back to estimated dimensions if ImageMagick is not available.
|
||||||
|
*/
|
||||||
|
public static async getImageDimensions(
|
||||||
|
imagePath: string,
|
||||||
|
fallbackDimensions: ImageDimensions = { width: 800, height: 600 }
|
||||||
|
): Promise<{dimensions: ImageDimensions; success: boolean; error?: string}> {
|
||||||
|
try {
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
// Use ImageMagick identify to get image dimensions
|
||||||
|
const identifyProcess = spawn('magick', [
|
||||||
|
'identify',
|
||||||
|
'-ping',
|
||||||
|
'-format',
|
||||||
|
'%wx%h',
|
||||||
|
imagePath
|
||||||
|
], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: this.getAugmentedEnv()
|
||||||
|
});
|
||||||
|
|
||||||
|
const dimensionsOutput = await new Promise<string>((resolve, reject) => {
|
||||||
|
let output = '';
|
||||||
|
let error = '';
|
||||||
|
|
||||||
|
identifyProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
identifyProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
identifyProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve(output.trim());
|
||||||
|
} else {
|
||||||
|
reject(new Error(`ImageMagick identify failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
identifyProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn ImageMagick identify: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Parse dimensions from "WIDTHxHEIGHT" format
|
||||||
|
const dimensionMatch = dimensionsOutput.match(/^(\d+)x(\d+)$/);
|
||||||
|
if (dimensionMatch) {
|
||||||
|
const dimensions = {
|
||||||
|
width: parseInt(dimensionMatch[1], 10),
|
||||||
|
height: parseInt(dimensionMatch[2], 10)
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
dimensions,
|
||||||
|
success: true
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
dimensions: fallbackDimensions,
|
||||||
|
success: false,
|
||||||
|
error: 'Could not parse dimensions from ImageMagick output'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
console.warn('ImageMagick not available for image metadata, using fallback dimensions');
|
||||||
|
return {
|
||||||
|
dimensions: fallbackDimensions,
|
||||||
|
success: false,
|
||||||
|
error: `Failed to get image dimensions: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optimize an image by converting format and/or adjusting quality.
|
||||||
|
* Handles both PNG to JPEG conversion and dimension detection.
|
||||||
|
*/
|
||||||
|
public static async optimizeImage(
|
||||||
|
inputImagePath: string,
|
||||||
|
outputDir: string,
|
||||||
|
baseFileName: string,
|
||||||
|
options: ImageOptimizationOptions = {},
|
||||||
|
plugin?: obsidianTypstPDFExport
|
||||||
|
): Promise<ImageOptimizationResult> {
|
||||||
|
try {
|
||||||
|
const opts = {
|
||||||
|
format: options.format || 'png',
|
||||||
|
quality: options.quality || 90
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generate final output path
|
||||||
|
const finalOutputFileName = `${baseFileName}_preview.${opts.format}`;
|
||||||
|
let finalOutputPath: string;
|
||||||
|
if (plugin?.app) {
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
finalOutputPath = pathUtils.joinPath(outputDir, finalOutputFileName);
|
||||||
|
} else {
|
||||||
|
finalOutputPath = path.join(outputDir, finalOutputFileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
let actualImagePath = inputImagePath;
|
||||||
|
|
||||||
|
// Handle format conversion if needed
|
||||||
|
if (opts.format === 'jpeg') {
|
||||||
|
// Convert PNG to JPEG using ImageMagick
|
||||||
|
const conversionResult = await this.convertPngToJpeg(
|
||||||
|
inputImagePath,
|
||||||
|
finalOutputPath,
|
||||||
|
opts.quality
|
||||||
|
);
|
||||||
|
|
||||||
|
if (conversionResult.success) {
|
||||||
|
// Clean up the original PNG if conversion succeeded
|
||||||
|
try {
|
||||||
|
if (plugin?.app) {
|
||||||
|
// Convert absolute path to vault-relative path for adapter.remove()
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
const vaultBasePath = pathUtils.getVaultPath();
|
||||||
|
|
||||||
|
let relativePath = inputImagePath;
|
||||||
|
if (inputImagePath.startsWith(vaultBasePath)) {
|
||||||
|
// Remove vault base path and leading separator
|
||||||
|
relativePath = inputImagePath.substring(vaultBasePath.length);
|
||||||
|
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
|
||||||
|
relativePath = relativePath.substring(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await plugin.app.vault.adapter.remove(relativePath);
|
||||||
|
} else {
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
await fs.unlink(inputImagePath);
|
||||||
|
}
|
||||||
|
} catch (unlinkError) {
|
||||||
|
console.warn(`Could not remove original PNG: ${unlinkError}`);
|
||||||
|
}
|
||||||
|
actualImagePath = finalOutputPath;
|
||||||
|
} else {
|
||||||
|
console.warn(`ImageMagick not available for JPEG conversion, keeping PNG format: ${conversionResult.error}`);
|
||||||
|
// Just rename the file to PNG format
|
||||||
|
const pngFinalPath = finalOutputPath.replace(/\.jpeg?$/, '.png');
|
||||||
|
if (plugin?.app) {
|
||||||
|
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
|
||||||
|
await plugin.app.vault.adapter.writeBinary(pngFinalPath, content);
|
||||||
|
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||||
|
} else {
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
await fs.rename(inputImagePath, pngFinalPath);
|
||||||
|
}
|
||||||
|
actualImagePath = pngFinalPath;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Keep as PNG, just rename to final location
|
||||||
|
if (plugin?.app) {
|
||||||
|
const content = await plugin.app.vault.adapter.readBinary(inputImagePath);
|
||||||
|
await plugin.app.vault.adapter.writeBinary(finalOutputPath, content);
|
||||||
|
await plugin.app.vault.adapter.remove(inputImagePath);
|
||||||
|
} else {
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
await fs.rename(inputImagePath, finalOutputPath);
|
||||||
|
}
|
||||||
|
actualImagePath = finalOutputPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get image dimensions
|
||||||
|
const dimensionResult = await this.getImageDimensions(actualImagePath);
|
||||||
|
|
||||||
|
return {
|
||||||
|
imagePath: actualImagePath,
|
||||||
|
dimensions: dimensionResult.dimensions,
|
||||||
|
success: true
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
imagePath: '',
|
||||||
|
dimensions: { width: 0, height: 0 },
|
||||||
|
success: false,
|
||||||
|
error: `Image optimization failed: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
/**
|
||||||
|
* PDF CLI Executor for handling pdf2img command line operations.
|
||||||
|
* Executes external pdf2img binary to convert PDF pages to images.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as path from 'path';
|
||||||
|
import { BinaryLocator } from './BinaryLocator';
|
||||||
|
import { EnvironmentUtils } from './EnvironmentUtils';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
export interface PdfCliOptions {
|
||||||
|
/** Scale factor for the rendered image */
|
||||||
|
scale: number;
|
||||||
|
/** Page number to convert (1-based) */
|
||||||
|
pages: string;
|
||||||
|
/** Output directory for generated images */
|
||||||
|
outputDir: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PdfCliResult {
|
||||||
|
/** Whether the CLI execution succeeded */
|
||||||
|
success: boolean;
|
||||||
|
/** Standard output from the command */
|
||||||
|
stdout?: string;
|
||||||
|
/** Standard error from the command */
|
||||||
|
stderr?: string;
|
||||||
|
/** Error message if execution failed */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PdfCliExecutor {
|
||||||
|
/**
|
||||||
|
* Execute pdf2img CLI command to convert PDF to images.
|
||||||
|
* @param pdfPath Path to the input PDF file
|
||||||
|
* @param options CLI execution options
|
||||||
|
* @param plugin Plugin instance for accessing settings
|
||||||
|
* @returns CLI execution result
|
||||||
|
*/
|
||||||
|
public static async executePdf2Img(
|
||||||
|
pdfPath: string,
|
||||||
|
options: PdfCliOptions,
|
||||||
|
plugin?: obsidianTypstPDFExport
|
||||||
|
): Promise<PdfCliResult> {
|
||||||
|
try {
|
||||||
|
// Find the pdf2img binary
|
||||||
|
const binaryLocation = await BinaryLocator.findPdf2ImgBinary(plugin);
|
||||||
|
if (!binaryLocation.exists) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: binaryLocation.error
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate relative path from vault to temp directory for pdf2img
|
||||||
|
// pdf2img doesn't handle absolute paths correctly, needs relative paths
|
||||||
|
const vaultPath = process.cwd(); // This should be the vault directory
|
||||||
|
const relativeOutputDir = path.relative(vaultPath, options.outputDir);
|
||||||
|
|
||||||
|
// Build the CLI command
|
||||||
|
const cliCommand = this.buildCommand(
|
||||||
|
binaryLocation.binaryPath,
|
||||||
|
pdfPath,
|
||||||
|
relativeOutputDir,
|
||||||
|
options
|
||||||
|
);
|
||||||
|
|
||||||
|
// Execute the command
|
||||||
|
return await this.executeCommand(cliCommand, plugin);
|
||||||
|
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `PDF CLI execution failed: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the pdf2img CLI command string.
|
||||||
|
* @param binaryPath Full path to pdf2img binary
|
||||||
|
* @param pdfPath Path to input PDF file
|
||||||
|
* @param outputDir Output directory (relative path)
|
||||||
|
* @param options CLI options
|
||||||
|
* @returns Command string ready for execution
|
||||||
|
*/
|
||||||
|
private static buildCommand(
|
||||||
|
binaryPath: string,
|
||||||
|
pdfPath: string,
|
||||||
|
outputDir: string,
|
||||||
|
options: PdfCliOptions
|
||||||
|
): string {
|
||||||
|
// Build the CLI command - the pdf2img binary is already executable
|
||||||
|
return [
|
||||||
|
`"${binaryPath}"`,
|
||||||
|
`"${pdfPath}"`,
|
||||||
|
'--scale', options.scale.toString(),
|
||||||
|
'--output', `"${outputDir}"`,
|
||||||
|
'--pages', options.pages // Only convert the specified page(s)
|
||||||
|
].join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a CLI command with proper environment setup.
|
||||||
|
* @param command Command string to execute
|
||||||
|
* @param plugin Plugin instance for accessing settings
|
||||||
|
* @returns Command execution result
|
||||||
|
*/
|
||||||
|
private static async executeCommand(
|
||||||
|
command: string,
|
||||||
|
plugin?: obsidianTypstPDFExport
|
||||||
|
): Promise<PdfCliResult> {
|
||||||
|
try {
|
||||||
|
const { exec } = require('child_process');
|
||||||
|
const { promisify } = require('util');
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
|
// Get augmented environment for CLI execution
|
||||||
|
const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings);
|
||||||
|
|
||||||
|
const result = await execAsync(command, { env });
|
||||||
|
|
||||||
|
// Log stderr as warning if present, but don't treat as error
|
||||||
|
if (result.stderr) {
|
||||||
|
console.warn(`PDF conversion stderr: ${result.stderr}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
stdout: result.stdout,
|
||||||
|
stderr: result.stderr
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (cliError: unknown) {
|
||||||
|
const errorMessage = cliError instanceof Error ? cliError.message : String(cliError);
|
||||||
|
console.error(`PDF conversion error: ${errorMessage}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `PDF CLI conversion failed: ${errorMessage}`,
|
||||||
|
stderr: (cliError as { stderr?: string })?.stderr || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate that pdf2img binary is available and working.
|
||||||
|
* @param plugin Plugin instance for accessing settings
|
||||||
|
* @returns Validation result
|
||||||
|
*/
|
||||||
|
public static async validatePdf2ImgAvailable(plugin?: obsidianTypstPDFExport): Promise<{
|
||||||
|
available: boolean;
|
||||||
|
error?: string;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const binaryLocation = await BinaryLocator.findPdf2ImgBinary(plugin);
|
||||||
|
return {
|
||||||
|
available: binaryLocation.exists,
|
||||||
|
error: binaryLocation.error
|
||||||
|
};
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
available: false,
|
||||||
|
error: `Failed to validate pdf2img: ${errorMessage}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
/**
|
||||||
|
* PDF Processing utilities for validation and metadata extraction.
|
||||||
|
* Handles PDF-specific operations separate from image conversion.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as fs from 'fs/promises';
|
||||||
|
|
||||||
|
export interface PdfMetadata {
|
||||||
|
/** Number of pages in the PDF */
|
||||||
|
pageCount: number;
|
||||||
|
/** PDF dimensions (width x height) */
|
||||||
|
dimensions: { width: number; height: number };
|
||||||
|
/** Operation success status */
|
||||||
|
success: boolean;
|
||||||
|
/** Error message if operation failed */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PdfProcessor {
|
||||||
|
/**
|
||||||
|
* Check if a file is a valid PDF by examining its signature.
|
||||||
|
* @param filePath Path to the file to validate
|
||||||
|
* @returns True if the file is a valid PDF, false otherwise
|
||||||
|
*/
|
||||||
|
public static async isValidPdf(filePath: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const buffer = await fs.readFile(filePath);
|
||||||
|
|
||||||
|
// Check PDF signature - all valid PDFs must start with %PDF
|
||||||
|
const signature = buffer.subarray(0, 4).toString();
|
||||||
|
return signature === '%PDF';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get PDF metadata including page count and dimensions.
|
||||||
|
* @param filePath Path to the PDF file
|
||||||
|
* @returns PDF metadata with page count, dimensions, and status
|
||||||
|
*/
|
||||||
|
public static async getPdfInfo(filePath: string): Promise<PdfMetadata> {
|
||||||
|
try {
|
||||||
|
// First validate that this is a proper PDF file
|
||||||
|
const isValid = await this.isValidPdf(filePath);
|
||||||
|
if (!isValid) {
|
||||||
|
return {
|
||||||
|
pageCount: 0,
|
||||||
|
dimensions: { width: 0, height: 0 },
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid PDF file'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// For now, return basic info since we use pdf-to-img for conversion
|
||||||
|
// In a real implementation, you might want to use pdf-parse or similar for metadata
|
||||||
|
// We only handle first page anyway in the conversion process
|
||||||
|
return {
|
||||||
|
pageCount: 1, // We only handle first page anyway
|
||||||
|
dimensions: { width: 612, height: 792 }, // Standard letter size estimate
|
||||||
|
success: true
|
||||||
|
};
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
return {
|
||||||
|
pageCount: 0,
|
||||||
|
dimensions: { width: 0, height: 0 },
|
||||||
|
success: false,
|
||||||
|
error: errorMessage
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate that a PDF file exists and is accessible.
|
||||||
|
* @param filePath Path to the PDF file
|
||||||
|
* @returns Object with success status and error message if applicable
|
||||||
|
*/
|
||||||
|
public static async validatePdfFile(filePath: string): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
await fs.access(filePath);
|
||||||
|
return { success: true };
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `PDF file not found: ${filePath}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a file exists and is a valid PDF.
|
||||||
|
* Combines file existence check with PDF validation.
|
||||||
|
* @param filePath Path to the file to check
|
||||||
|
* @returns True if file exists and is a valid PDF, false otherwise
|
||||||
|
*/
|
||||||
|
public static async isValidPdfFile(filePath: string): Promise<boolean> {
|
||||||
|
const validation = await this.validatePdfFile(filePath);
|
||||||
|
if (!validation.success) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.isValidPdf(filePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
import { PreprocessingResult } from '../MarkdownPreprocessor';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles processing of Obsidian callouts and email blocks for Typst conversion
|
||||||
|
*/
|
||||||
|
export class CalloutProcessor {
|
||||||
|
// Patterns for matching different block types
|
||||||
|
private readonly CALLOUT_PATTERN = /^>\s*\[![\w-]+\]/;
|
||||||
|
private readonly MULTI_LINE_CALLOUT_PATTERN = /^>\s*\[![\w-]+\][+-]?\s*.*$/;
|
||||||
|
private readonly EMAIL_BLOCK_PATTERN = /^```email\s*\n([\s\S]*?)^```\s*$/gm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main entry point for processing callouts
|
||||||
|
*/
|
||||||
|
public processCallouts(content: string, result: PreprocessingResult): string {
|
||||||
|
// Process multi-line callouts first
|
||||||
|
const processed = this.processMultiLineCallouts(content, result);
|
||||||
|
return processed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main entry point for processing email blocks
|
||||||
|
*/
|
||||||
|
public processEmailBlocks(content: string, result: PreprocessingResult): string {
|
||||||
|
return content.replace(this.EMAIL_BLOCK_PATTERN, (match, blockContent) => {
|
||||||
|
try {
|
||||||
|
return this.processEmailBlock(blockContent, result);
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Failed to process email block: ${error.message}`);
|
||||||
|
return match; // Return original on error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filters out unnecessary links from content
|
||||||
|
*/
|
||||||
|
public filterUnnecessaryLinks(content: string, result: PreprocessingResult): string {
|
||||||
|
let processed = content;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Remove [[filename|Open: filename]] links
|
||||||
|
processed = processed.replace(/\[\[.*?\|Open:.*?\]\]/g, '');
|
||||||
|
|
||||||
|
// Remove [Open in Mail.app](message://) links
|
||||||
|
processed = processed.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, '');
|
||||||
|
|
||||||
|
// Clean up any resulting multiple newlines
|
||||||
|
processed = processed.replace(/\n{3,}/g, '\n\n');
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Error filtering unnecessary links: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return processed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes multi-line callout blocks
|
||||||
|
*/
|
||||||
|
private processMultiLineCallouts(content: string, result: PreprocessingResult): string {
|
||||||
|
const lines = content.split('\n');
|
||||||
|
const processedLines: string[] = [];
|
||||||
|
let i = 0;
|
||||||
|
|
||||||
|
while (i < lines.length) {
|
||||||
|
const line = lines[i];
|
||||||
|
const calloutMatch = line.match(/^>\s*\[!([\w-]+)\]([+-]?)\s*(.*)$/);
|
||||||
|
|
||||||
|
if (calloutMatch) {
|
||||||
|
const [, calloutType, foldable, title] = calloutMatch;
|
||||||
|
const calloutBlock = this.extractCalloutBlock(lines, i);
|
||||||
|
const processedCallout = this.convertCalloutToTypstFormat(
|
||||||
|
calloutType,
|
||||||
|
title,
|
||||||
|
foldable,
|
||||||
|
calloutBlock.content,
|
||||||
|
result
|
||||||
|
);
|
||||||
|
|
||||||
|
processedLines.push(processedCallout);
|
||||||
|
i = calloutBlock.endIndex;
|
||||||
|
} else {
|
||||||
|
processedLines.push(line);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedLines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts content from a callout block
|
||||||
|
*/
|
||||||
|
private extractCalloutBlock(lines: string[], startIndex: number): { content: string[]; endIndex: number } {
|
||||||
|
const calloutContent: string[] = [];
|
||||||
|
let currentIndex = startIndex + 1;
|
||||||
|
|
||||||
|
// Add the title/first line content if present
|
||||||
|
const firstLineMatch = lines[startIndex].match(/^>\s*\[![\w-]+\]([+-]?)\s*(.*)$/);
|
||||||
|
if (firstLineMatch && firstLineMatch[2].trim()) {
|
||||||
|
calloutContent.push(firstLineMatch[2].trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Continue reading lines that start with '>' or are empty (within callout)
|
||||||
|
while (currentIndex < lines.length) {
|
||||||
|
const line = lines[currentIndex];
|
||||||
|
|
||||||
|
if (line.startsWith('>')) {
|
||||||
|
// Remove the '>' prefix and add to content
|
||||||
|
const contentLine = line.substring(1).trim();
|
||||||
|
calloutContent.push(contentLine);
|
||||||
|
currentIndex++;
|
||||||
|
} else if (line.trim() === '' && currentIndex + 1 < lines.length && lines[currentIndex + 1].startsWith('>')) {
|
||||||
|
// Empty line followed by more callout content
|
||||||
|
calloutContent.push('');
|
||||||
|
currentIndex++;
|
||||||
|
} else {
|
||||||
|
// End of callout block
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: calloutContent,
|
||||||
|
endIndex: currentIndex
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts callout to Typst format with enhanced styling
|
||||||
|
*/
|
||||||
|
private convertCalloutToTypstFormat(
|
||||||
|
calloutType: string,
|
||||||
|
title: string,
|
||||||
|
foldable: string,
|
||||||
|
content: string[],
|
||||||
|
result: PreprocessingResult
|
||||||
|
): string {
|
||||||
|
// Enhanced callout type mapping with icons and styling hints
|
||||||
|
const calloutTypeMap: Record<string, { display: string; icon: string; class: string }> = {
|
||||||
|
'note': { display: 'Note', icon: '📝', class: 'callout-note' },
|
||||||
|
'abstract': { display: 'Abstract', icon: '📋', class: 'callout-abstract' },
|
||||||
|
'info': { display: 'Info', icon: 'ℹ️', class: 'callout-info' },
|
||||||
|
'tip': { display: 'Tip', icon: '💡', class: 'callout-tip' },
|
||||||
|
'success': { display: 'Success', icon: '✅', class: 'callout-success' },
|
||||||
|
'question': { display: 'Question', icon: '❓', class: 'callout-question' },
|
||||||
|
'warning': { display: 'Warning', icon: '⚠️', class: 'callout-warning' },
|
||||||
|
'failure': { display: 'Failure', icon: '❌', class: 'callout-failure' },
|
||||||
|
'danger': { display: 'Danger', icon: '⚡', class: 'callout-danger' },
|
||||||
|
'bug': { display: 'Bug', icon: '🐛', class: 'callout-bug' },
|
||||||
|
'example': { display: 'Example', icon: '📋', class: 'callout-example' },
|
||||||
|
'quote': { display: 'Quote', icon: '💬', class: 'callout-quote' },
|
||||||
|
'cite': { display: 'Citation', icon: '📖', class: 'callout-cite' }
|
||||||
|
};
|
||||||
|
|
||||||
|
const calloutInfo = calloutTypeMap[calloutType.toLowerCase()] || {
|
||||||
|
display: calloutType.charAt(0).toUpperCase() + calloutType.slice(1),
|
||||||
|
icon: '📌',
|
||||||
|
class: 'callout-default'
|
||||||
|
};
|
||||||
|
|
||||||
|
// Build the blockquote with enhanced formatting
|
||||||
|
let blockquote = '';
|
||||||
|
|
||||||
|
// Add Typst comment with class for styling
|
||||||
|
blockquote += `<!-- ${calloutInfo.class} -->\n`;
|
||||||
|
|
||||||
|
// Create the header
|
||||||
|
const headerText = title.trim() || calloutInfo.display;
|
||||||
|
blockquote += `> **${calloutInfo.icon} ${headerText}**`;
|
||||||
|
|
||||||
|
// Add foldable indicator if present
|
||||||
|
if (foldable === '+') {
|
||||||
|
blockquote += ' 🔽'; // Expanded
|
||||||
|
} else if (foldable === '-') {
|
||||||
|
blockquote += ' 🔼'; // Collapsed
|
||||||
|
}
|
||||||
|
|
||||||
|
blockquote += '\n>';
|
||||||
|
|
||||||
|
// Add content with proper blockquote formatting
|
||||||
|
if (content.length > 0) {
|
||||||
|
blockquote += '\n';
|
||||||
|
content.forEach(line => {
|
||||||
|
if (line.trim() === '') {
|
||||||
|
blockquote += '>\n';
|
||||||
|
} else {
|
||||||
|
blockquote += `> ${line}\n`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
blockquote += '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add spacing after callout
|
||||||
|
blockquote += '\n';
|
||||||
|
|
||||||
|
return blockquote.trimEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes individual email block
|
||||||
|
*/
|
||||||
|
private processEmailBlock(blockContent: string, result: PreprocessingResult): string {
|
||||||
|
try {
|
||||||
|
// Split at --- to separate header from body
|
||||||
|
const parts = blockContent.split('---');
|
||||||
|
const yamlHeader = parts[0].trim();
|
||||||
|
let body = parts.length > 1 ? parts.slice(1).join('---').trim() : '';
|
||||||
|
|
||||||
|
// Filter out unnecessary links from the body
|
||||||
|
// Remove [[filename|Open: filename]] links
|
||||||
|
body = body.replace(/\[\[.*?\|Open:.*?\]\]/g, '');
|
||||||
|
// Remove [Open in Mail.app](message://) links
|
||||||
|
body = body.replace(/\[Open in Mail\.app\]\(message:\/\/[^)]+\)/g, '');
|
||||||
|
// Clean up any resulting double newlines
|
||||||
|
body = body.replace(/\n{3,}/g, '\n\n').trim();
|
||||||
|
|
||||||
|
// Parse YAML header
|
||||||
|
const params = this.parseEmailYaml(yamlHeader);
|
||||||
|
|
||||||
|
// Build Typst function call arguments
|
||||||
|
const args: string[] = [];
|
||||||
|
|
||||||
|
// Add parameters in the order expected by the Typst template
|
||||||
|
if (params.from) {
|
||||||
|
args.push(`from: "${this.escapeQuotes(params.from)}"`);
|
||||||
|
}
|
||||||
|
if (params.to) {
|
||||||
|
args.push(`to: "${this.escapeQuotes(params.to)}"`);
|
||||||
|
}
|
||||||
|
if (params.subject) {
|
||||||
|
args.push(`subject: "${this.escapeQuotes(params.subject)}"`);
|
||||||
|
}
|
||||||
|
if (params.date) {
|
||||||
|
args.push(`date: "${this.escapeQuotes(params.date)}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add body as string parameter (always present, even if empty)
|
||||||
|
// Use the escapeQuotes method to preserve paragraphs but keep as string
|
||||||
|
const bodyParam = `"${this.escapeBodyForTypst(body)}"`;
|
||||||
|
|
||||||
|
// Construct the Typst email-block function call with proper line breaks
|
||||||
|
// Wrap in Pandoc raw blocks so it's treated as Typst code, not markdown text
|
||||||
|
const argsString = args.length > 0 ? args.join(', ') + ', ' : '';
|
||||||
|
return `\n\n\`\`\`{=typst}\n#email-block(${argsString}${bodyParam})\n\`\`\`\n\n`;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Error processing email block content: ${error.message}`);
|
||||||
|
// Return as code block to preserve original content
|
||||||
|
return `\`\`\`\n${blockContent}\n\`\`\``;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses YAML header in email blocks
|
||||||
|
*/
|
||||||
|
private parseEmailYaml(yamlString: string): Record<string, string> {
|
||||||
|
try {
|
||||||
|
let processedYaml = yamlString;
|
||||||
|
|
||||||
|
// Handle wikilinks - quote them if not already quoted (from email block plugin logic)
|
||||||
|
if (processedYaml.includes('[[') && !processedYaml.includes('"[[')) {
|
||||||
|
processedYaml = processedYaml.replace(/\[\[/g, '"[[');
|
||||||
|
processedYaml = processedYaml.replace(/\]\]/g, ']]"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle template variables - quote them if not already quoted
|
||||||
|
if (processedYaml.includes('{{') && !processedYaml.includes('"{{')) {
|
||||||
|
processedYaml = processedYaml.replace(/\{\{/g, '"{{');
|
||||||
|
processedYaml = processedYaml.replace(/\}\}/g, '}}"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use Obsidian's YAML parser (from email block plugin approach)
|
||||||
|
// For now, we'll do simple parsing since we don't have access to Obsidian's parseYaml
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
const lines = processedYaml.split('\n');
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
const colonIndex = line.indexOf(':');
|
||||||
|
if (colonIndex > 0) {
|
||||||
|
const key = line.substring(0, colonIndex).trim();
|
||||||
|
let value = line.substring(colonIndex + 1).trim();
|
||||||
|
|
||||||
|
// Remove quotes if present
|
||||||
|
if ((value.startsWith('"') && value.endsWith('"')) ||
|
||||||
|
(value.startsWith("'") && value.endsWith("'"))) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle array values (convert to comma-separated string)
|
||||||
|
if (value.startsWith('[') && value.endsWith(']')) {
|
||||||
|
value = value.slice(1, -1).replace(/"/g, '').replace(/'/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
params[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return params;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`YAML parsing failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escapes quotes in text for safe Typst string usage
|
||||||
|
*/
|
||||||
|
private escapeQuotes(text: string): string {
|
||||||
|
if (!text) return '';
|
||||||
|
return text
|
||||||
|
.replace(/\\/g, '\\\\') // Escape backslashes first
|
||||||
|
.replace(/"/g, '\\"') // Escape double quotes
|
||||||
|
.replace(/'/g, "\\'") // Escape single quotes to prevent smart quote conversion
|
||||||
|
.replace(/\n/g, '\\n') // Convert newlines to literal \n for string parameters
|
||||||
|
.replace(/\r/g, '\\r'); // Convert carriage returns
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escapes email body content for safe Typst usage
|
||||||
|
*/
|
||||||
|
private escapeBodyForTypst(text: string): string {
|
||||||
|
if (!text) return '';
|
||||||
|
|
||||||
|
// First, clean up problematic Unicode characters
|
||||||
|
const cleaned = text
|
||||||
|
// Replace various Unicode spaces with regular spaces
|
||||||
|
.replace(/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g, ' ')
|
||||||
|
// Replace Unicode line separators with regular newlines
|
||||||
|
.replace(/[\u2028\u2029]/g, '\n') // Line Separator and Paragraph Separator
|
||||||
|
// Replace Unicode hyphens/dashes with regular hyphen
|
||||||
|
.replace(/[\u2010-\u2015\u2212]/g, '-')
|
||||||
|
// Remove or replace problematic symbols that can cause layout issues
|
||||||
|
.replace(/[\u2020\u2021]/g, '') // Remove dagger symbols
|
||||||
|
.replace(/[\u2022\u2023\u2043]/g, '• ') // Replace various bullets with standard bullet
|
||||||
|
// Remove zero-width characters
|
||||||
|
.replace(/[\u200B-\u200D\uFEFF]/g, '')
|
||||||
|
// Remove other problematic Unicode characters that can cause spacing issues
|
||||||
|
.replace(/[\u00AD\u061C\u180E\u2066-\u2069]/g, '')
|
||||||
|
// Normalize multiple spaces to single space (but preserve newlines)
|
||||||
|
.replace(/[ \t]+/g, ' ')
|
||||||
|
// Preserve paragraph breaks but clean up excessive newlines
|
||||||
|
.replace(/\n{3,}/g, '\n\n');
|
||||||
|
|
||||||
|
// Then escape for Typst string safety
|
||||||
|
return cleaned
|
||||||
|
.replace(/\\/g, '\\\\') // Escape backslashes first
|
||||||
|
.replace(/"/g, '\\"') // Escape double quotes
|
||||||
|
.replace(/'/g, "\\'"); // Escape single quotes
|
||||||
|
// Note: DO NOT replace newlines - they should be preserved for proper formatting
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
/**
|
||||||
|
* EmbedProcessor - Handles conversion of Obsidian embed syntax to markdown references
|
||||||
|
* Processes images, PDFs, and generic file embeds with appropriate markers for later processing
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { WikilinkProcessor } from './WikilinkProcessor';
|
||||||
|
|
||||||
|
export interface EmbedProcessorConfig {
|
||||||
|
/** WikilinkProcessor instance for path sanitization */
|
||||||
|
wikilinkProcessor: WikilinkProcessor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: PreprocessingResult is imported from the parent MarkdownPreprocessor module
|
||||||
|
export interface PreprocessingResult {
|
||||||
|
/** Processed markdown content */
|
||||||
|
content: string;
|
||||||
|
/** Extracted metadata including tags and frontmatter */
|
||||||
|
metadata: {
|
||||||
|
tags: string[];
|
||||||
|
frontmatter?: Record<string, unknown>;
|
||||||
|
title?: string;
|
||||||
|
pdfEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
imageEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
sizeOrAlt?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
fileEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
fileType: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
/** Processing errors and warnings */
|
||||||
|
errors: string[];
|
||||||
|
/** Processing warnings */
|
||||||
|
warnings: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EmbedProcessor {
|
||||||
|
private wikilinkProcessor: WikilinkProcessor;
|
||||||
|
|
||||||
|
// Regex patterns for embed matching
|
||||||
|
private readonly EMBED_PATTERN = /!\[\[([^|\]]+)(?:\|([^\]]+))?\]\]/g;
|
||||||
|
private readonly EMBED_SIZE_PATTERN = /(\d+)(?:x(\d+))?/;
|
||||||
|
|
||||||
|
constructor(config: EmbedProcessorConfig) {
|
||||||
|
this.wikilinkProcessor = config.wikilinkProcessor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert embed syntax to standard markdown references
|
||||||
|
*/
|
||||||
|
public processEmbeds(content: string, result: PreprocessingResult): string {
|
||||||
|
return content.replace(this.EMBED_PATTERN, (match, embedPath, sizeOrAlt) => {
|
||||||
|
try {
|
||||||
|
const cleanPath = embedPath.trim();
|
||||||
|
|
||||||
|
if (!cleanPath) {
|
||||||
|
result.warnings.push(`Empty embed path found: ${match}`);
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse file extension and path
|
||||||
|
const fileExtension = this.getFileExtension(cleanPath);
|
||||||
|
const fileType = this.determineFileType(fileExtension);
|
||||||
|
|
||||||
|
// Handle different file types
|
||||||
|
switch (fileType) {
|
||||||
|
case 'image':
|
||||||
|
return this.processImageEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
case 'pdf':
|
||||||
|
return this.processPdfEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
case 'file':
|
||||||
|
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
default:
|
||||||
|
// This should never happen with the simplified type system
|
||||||
|
result.warnings.push(`Unexpected file type for embed: ${cleanPath}`);
|
||||||
|
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Failed to process embed: ${match} - ${error.message}`);
|
||||||
|
return match; // Return original on error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get file extension from path
|
||||||
|
*/
|
||||||
|
private getFileExtension(filePath: string): string {
|
||||||
|
const lastDot = filePath.lastIndexOf('.');
|
||||||
|
return lastDot > 0 ? filePath.substring(lastDot).toLowerCase() : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine file type based on extension
|
||||||
|
* Simplified to 3 types: image (displayed), pdf (embedded with preview), file (embedded)
|
||||||
|
*/
|
||||||
|
private determineFileType(extension: string): 'image' | 'pdf' | 'file' {
|
||||||
|
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff'];
|
||||||
|
|
||||||
|
if (imageExtensions.includes(extension)) return 'image';
|
||||||
|
if (extension === '.pdf') return 'pdf';
|
||||||
|
|
||||||
|
// All other file types (including DOCX, videos, audio, etc.) are treated as files to be embedded
|
||||||
|
return 'file';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process image embeds with size parameters
|
||||||
|
*/
|
||||||
|
private processImageEmbed(imagePath: string, sizeOrAlt: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(imagePath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual copying will be handled in the main export process
|
||||||
|
const fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace
|
||||||
|
const marker = `IMAGE_EMBED_MARKER:${imagePath}:${baseName}:${sizeOrAlt || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later copying
|
||||||
|
if (!result.metadata.imageEmbeds) {
|
||||||
|
result.metadata.imageEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.imageEmbeds.push({
|
||||||
|
originalPath: imagePath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
sizeOrAlt: sizeOrAlt,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`Image embed queued for processing: ${imagePath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed
|
||||||
|
*/
|
||||||
|
private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(pdfPath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual conversion will be handled in the main export process
|
||||||
|
const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace with Typst code
|
||||||
|
const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later conversion
|
||||||
|
if (!result.metadata.pdfEmbeds) {
|
||||||
|
result.metadata.pdfEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.pdfEmbeds.push({
|
||||||
|
originalPath: pdfPath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
options: options,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process generic file embeds - Convert to attachment using Typst's pdf.embed
|
||||||
|
* Note: This handles all non-image, non-PDF files including videos, audio, documents, etc.
|
||||||
|
*/
|
||||||
|
private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(filePath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual embedding will be handled in the main export process
|
||||||
|
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
const fileExtension = this.getFileExtension(fileName);
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace with Typst code
|
||||||
|
const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later conversion
|
||||||
|
if (!result.metadata.fileEmbeds) {
|
||||||
|
result.metadata.fileEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.fileEmbeds.push({
|
||||||
|
originalPath: filePath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
fileType: fileExtension,
|
||||||
|
options: options,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update configuration
|
||||||
|
*/
|
||||||
|
public updateConfig(config: Partial<EmbedProcessorConfig>): void {
|
||||||
|
if (config.wikilinkProcessor) {
|
||||||
|
this.wikilinkProcessor = config.wikilinkProcessor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current configuration
|
||||||
|
*/
|
||||||
|
public getConfig(): EmbedProcessorConfig {
|
||||||
|
return {
|
||||||
|
wikilinkProcessor: this.wikilinkProcessor
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
/**
|
||||||
|
* FrontmatterProcessor - Handles YAML frontmatter parsing and processing
|
||||||
|
* Extracted from MarkdownPreprocessor for better code organization
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { PreprocessingResult } from '../MarkdownPreprocessor';
|
||||||
|
|
||||||
|
export interface FrontmatterProcessorConfig {
|
||||||
|
noteTitle?: string;
|
||||||
|
preserveFrontmatter: boolean;
|
||||||
|
printFrontmatter: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FrontmatterProcessor {
|
||||||
|
private readonly FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/;
|
||||||
|
private readonly noteTitle?: string;
|
||||||
|
private readonly preserveFrontmatter: boolean;
|
||||||
|
private readonly printFrontmatter: boolean;
|
||||||
|
|
||||||
|
constructor(config: FrontmatterProcessorConfig) {
|
||||||
|
this.noteTitle = config.noteTitle;
|
||||||
|
this.preserveFrontmatter = config.preserveFrontmatter;
|
||||||
|
this.printFrontmatter = config.printFrontmatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process frontmatter using the gray-matter library approach
|
||||||
|
*/
|
||||||
|
public processFrontmatter(content: string, result: PreprocessingResult): string {
|
||||||
|
try {
|
||||||
|
// Check if content actually has frontmatter before trying to parse
|
||||||
|
if (!this.FRONTMATTER_PATTERN.test(content)) {
|
||||||
|
// No frontmatter found - add title frontmatter if we have a noteTitle
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
result.metadata.title = this.noteTitle;
|
||||||
|
result.metadata.frontmatter = { title: this.noteTitle };
|
||||||
|
return `---\n${titleFrontmatter}---\n${content}`;
|
||||||
|
} else {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use gray-matter for robust frontmatter parsing
|
||||||
|
const matter = require('gray-matter');
|
||||||
|
|
||||||
|
// Add debugging to see what's being parsed
|
||||||
|
console.log('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected');
|
||||||
|
console.log('First 200 chars:', content.substring(0, 200));
|
||||||
|
|
||||||
|
const parsed = matter(content);
|
||||||
|
|
||||||
|
if (parsed.data && Object.keys(parsed.data).length > 0) {
|
||||||
|
// Replace frontmatter title with filename if noteTitle is provided
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const frontmatterCopy = { ...parsed.data };
|
||||||
|
frontmatterCopy.title = this.noteTitle;
|
||||||
|
result.metadata.frontmatter = frontmatterCopy;
|
||||||
|
} else {
|
||||||
|
result.metadata.frontmatter = parsed.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract tags from frontmatter if they exist
|
||||||
|
if (parsed.data.tags) {
|
||||||
|
let frontmatterTags: string[] = [];
|
||||||
|
|
||||||
|
if (Array.isArray(parsed.data.tags)) {
|
||||||
|
// Handle array of tags
|
||||||
|
frontmatterTags = parsed.data.tags
|
||||||
|
.map((tag: unknown) => typeof tag === 'string' ? tag : String(tag))
|
||||||
|
.filter((tag: string) => tag.trim() !== '');
|
||||||
|
} else if (typeof parsed.data.tags === 'string') {
|
||||||
|
// Handle comma-separated string or single tag
|
||||||
|
frontmatterTags = parsed.data.tags
|
||||||
|
.split(/[,\s]+/)
|
||||||
|
.map((tag: string) => tag.trim())
|
||||||
|
.filter((tag: string) => tag !== '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge with existing tags (avoid duplicates)
|
||||||
|
for (const tag of frontmatterTags) {
|
||||||
|
if (!result.metadata.tags.includes(tag)) {
|
||||||
|
result.metadata.tags.push(tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract title - use noteTitle if available, otherwise frontmatter title
|
||||||
|
if (this.noteTitle) {
|
||||||
|
result.metadata.title = this.noteTitle;
|
||||||
|
} else if (parsed.data.title && typeof parsed.data.title === 'string') {
|
||||||
|
result.metadata.title = parsed.data.title.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle frontmatter preservation and display options
|
||||||
|
const finalFrontmatter = this.noteTitle ?
|
||||||
|
{ ...parsed.data, title: this.noteTitle } :
|
||||||
|
parsed.data;
|
||||||
|
|
||||||
|
if (this.preserveFrontmatter) {
|
||||||
|
// Keep the frontmatter in the content, but reconstruct it with the modified title
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const newFrontmatter = yaml.dump(finalFrontmatter);
|
||||||
|
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
|
||||||
|
|
||||||
|
// Add printed frontmatter if requested
|
||||||
|
if (this.printFrontmatter) {
|
||||||
|
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
|
||||||
|
processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedContent;
|
||||||
|
} else {
|
||||||
|
// Return content without frontmatter, but add title as frontmatter for Pandoc
|
||||||
|
let processedContent: string;
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
|
||||||
|
} else {
|
||||||
|
processedContent = parsed.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add printed frontmatter if requested
|
||||||
|
if (this.printFrontmatter) {
|
||||||
|
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
|
||||||
|
// Insert after the title frontmatter but before content
|
||||||
|
const lines = processedContent.split('\n');
|
||||||
|
if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) {
|
||||||
|
const endIndex = lines.findIndex((line, i) => i > 0 && line === '---');
|
||||||
|
lines.splice(endIndex + 1, 0, '', frontmatterDisplay, '');
|
||||||
|
processedContent = lines.join('\n');
|
||||||
|
} else {
|
||||||
|
processedContent = `${frontmatterDisplay}\n\n${processedContent}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedContent;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No frontmatter found - add title frontmatter if we have a noteTitle
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
result.metadata.title = this.noteTitle;
|
||||||
|
result.metadata.frontmatter = { title: this.noteTitle };
|
||||||
|
return `---\n${titleFrontmatter}---\n${content}`;
|
||||||
|
} else {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
console.log('FrontmatterProcessor: gray-matter failed with error:', errorMessage);
|
||||||
|
console.log('Content being parsed (first 500 chars):', content.substring(0, 500));
|
||||||
|
result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`);
|
||||||
|
|
||||||
|
// Fallback to simple regex-based parsing
|
||||||
|
const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN);
|
||||||
|
|
||||||
|
if (frontmatterMatch) {
|
||||||
|
try {
|
||||||
|
const yamlContent = frontmatterMatch[1];
|
||||||
|
const frontmatter: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
const lines = yamlContent.split('\n');
|
||||||
|
for (const line of lines) {
|
||||||
|
const colonIndex = line.indexOf(':');
|
||||||
|
if (colonIndex > 0) {
|
||||||
|
const key = line.substring(0, colonIndex).trim();
|
||||||
|
const value = line.substring(colonIndex + 1).trim();
|
||||||
|
const cleanValue = value.replace(/^["']|["']$/g, '');
|
||||||
|
frontmatter[key] = cleanValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace title with noteTitle if provided
|
||||||
|
if (this.noteTitle) {
|
||||||
|
frontmatter.title = this.noteTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.metadata.frontmatter = frontmatter;
|
||||||
|
|
||||||
|
if (this.preserveFrontmatter) {
|
||||||
|
// Reconstruct frontmatter with modified title
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const newFrontmatter = yaml.dump(frontmatter);
|
||||||
|
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`);
|
||||||
|
|
||||||
|
// Add printed frontmatter if requested
|
||||||
|
if (this.printFrontmatter) {
|
||||||
|
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
|
||||||
|
processedContent = processedContent.replace(
|
||||||
|
this.FRONTMATTER_PATTERN,
|
||||||
|
`---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedContent;
|
||||||
|
} else {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Add title as frontmatter for Pandoc even when not preserving original
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`);
|
||||||
|
|
||||||
|
// Add printed frontmatter if requested
|
||||||
|
if (this.printFrontmatter) {
|
||||||
|
const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter);
|
||||||
|
processedContent = processedContent.replace(
|
||||||
|
this.FRONTMATTER_PATTERN,
|
||||||
|
`---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedContent;
|
||||||
|
} else {
|
||||||
|
return content.replace(this.FRONTMATTER_PATTERN, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (fallbackError: unknown) {
|
||||||
|
const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
|
||||||
|
result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No frontmatter pattern found, but gray-matter failed - treat as file without frontmatter
|
||||||
|
if (this.noteTitle) {
|
||||||
|
const yaml = require('js-yaml');
|
||||||
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
result.metadata.title = this.noteTitle;
|
||||||
|
result.metadata.frontmatter = { title: this.noteTitle };
|
||||||
|
return `---\n${titleFrontmatter}---\n${content}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format frontmatter as a readable display block
|
||||||
|
*/
|
||||||
|
private formatFrontmatterForDisplay(frontmatter: Record<string, unknown>): string {
|
||||||
|
if (!frontmatter || Object.keys(frontmatter).length === 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push('**Document Information**');
|
||||||
|
lines.push('');
|
||||||
|
|
||||||
|
// Format each frontmatter field
|
||||||
|
for (const [key, value] of Object.entries(frontmatter)) {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
// Format the key nicely (capitalize first letter, convert underscores to spaces)
|
||||||
|
const formattedKey = key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' ');
|
||||||
|
|
||||||
|
// Handle different value types
|
||||||
|
let formattedValue: string;
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
// For arrays, put each item on its own line if there are many items
|
||||||
|
if (value.length > 3) {
|
||||||
|
formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n';
|
||||||
|
} else {
|
||||||
|
formattedValue = value.join(', ');
|
||||||
|
}
|
||||||
|
} else if (typeof value === 'object') {
|
||||||
|
formattedValue = JSON.stringify(value);
|
||||||
|
} else {
|
||||||
|
const valueStr = String(value);
|
||||||
|
// If the value is very long (like email lists), break it up
|
||||||
|
if (valueStr.length > 80 && valueStr.includes(',')) {
|
||||||
|
// Split on commas and format as a bulleted list
|
||||||
|
const items = valueStr.split(',').map(item => item.trim());
|
||||||
|
if (items.length > 1) {
|
||||||
|
formattedValue = '\n\n' + items.map(item => `- ${item}`).join('\n') + '\n';
|
||||||
|
} else {
|
||||||
|
formattedValue = valueStr;
|
||||||
|
}
|
||||||
|
} else if (valueStr.length > 100) {
|
||||||
|
// For other very long values, try to break at word boundaries
|
||||||
|
const words = valueStr.split(' ');
|
||||||
|
let currentLine = '';
|
||||||
|
const wrappedLines: string[] = [];
|
||||||
|
|
||||||
|
for (const word of words) {
|
||||||
|
if (currentLine.length + word.length + 1 > 80) {
|
||||||
|
if (currentLine) {
|
||||||
|
wrappedLines.push(currentLine);
|
||||||
|
currentLine = word;
|
||||||
|
} else {
|
||||||
|
wrappedLines.push(word);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentLine += (currentLine ? ' ' : '') + word;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentLine) {
|
||||||
|
wrappedLines.push(currentLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
formattedValue = '\n\n' + wrappedLines.join(' \n') + '\n';
|
||||||
|
} else {
|
||||||
|
formattedValue = valueStr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add line break after the property label, then the value
|
||||||
|
if (formattedValue.startsWith('\n')) {
|
||||||
|
// Value already starts with newline (like lists), so just add the label
|
||||||
|
lines.push(`**${formattedKey}:**${formattedValue}`);
|
||||||
|
} else {
|
||||||
|
// Add a line break after the label for regular values
|
||||||
|
lines.push(`**${formattedKey}:**\n${formattedValue}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join with double newlines to ensure proper spacing between fields
|
||||||
|
const result = lines.join('\n\n');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* Processes horizontal rules to avoid conflicts with YAML frontmatter delimiters
|
||||||
|
*
|
||||||
|
* Transforms markdown horizontal rules that could be mistaken for YAML delimiters
|
||||||
|
* into alternative formats that Pandoc will still recognize as horizontal rules
|
||||||
|
* but won't interpret as YAML frontmatter boundaries.
|
||||||
|
*
|
||||||
|
* Preserves YAML frontmatter sections by detecting and skipping them.
|
||||||
|
*/
|
||||||
|
export class HorizontalRuleProcessor {
|
||||||
|
private readonly FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// No initialization needed
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process horizontal rules to avoid YAML conflicts
|
||||||
|
*
|
||||||
|
* Transforms:
|
||||||
|
* - `---` (3 dashes) -> `***` (3 asterisks)
|
||||||
|
* - `----` (4+ dashes) -> `****` (4+ asterisks)
|
||||||
|
*
|
||||||
|
* Both formats are valid markdown horizontal rules but `***` won't be
|
||||||
|
* mistaken for YAML delimiters by Pandoc.
|
||||||
|
*
|
||||||
|
* Skips YAML frontmatter sections to preserve them.
|
||||||
|
*/
|
||||||
|
process(content: string): string {
|
||||||
|
// Check if content has frontmatter at the beginning
|
||||||
|
const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN);
|
||||||
|
|
||||||
|
if (frontmatterMatch) {
|
||||||
|
// Content has frontmatter - separate it from the main content
|
||||||
|
const frontmatter = frontmatterMatch[0];
|
||||||
|
const mainContent = content.slice(frontmatter.length);
|
||||||
|
|
||||||
|
// Process only the main content (after frontmatter)
|
||||||
|
const processedMainContent = this.processContentLines(mainContent);
|
||||||
|
|
||||||
|
// Recombine frontmatter with processed main content
|
||||||
|
return frontmatter + processedMainContent;
|
||||||
|
} else {
|
||||||
|
// No frontmatter - process the entire content
|
||||||
|
return this.processContentLines(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process lines for horizontal rule transformation
|
||||||
|
*/
|
||||||
|
private processContentLines(content: string): string {
|
||||||
|
// Split content into lines for processing
|
||||||
|
const lines = content.split('\n');
|
||||||
|
const processedLines: string[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
|
||||||
|
// Check if line is a horizontal rule made of dashes
|
||||||
|
// Must be at least 3 dashes, optionally with spaces
|
||||||
|
const dashRuleMatch = line.match(/^(\s*)(---+)(\s*)$/);
|
||||||
|
|
||||||
|
if (dashRuleMatch) {
|
||||||
|
// Transform dash horizontal rule to asterisk horizontal rule
|
||||||
|
const [, leadingSpaces, dashes, trailingSpaces] = dashRuleMatch;
|
||||||
|
const asterisks = '*'.repeat(dashes.length);
|
||||||
|
processedLines.push(`${leadingSpaces}${asterisks}${trailingSpaces}`);
|
||||||
|
} else {
|
||||||
|
// Keep line unchanged
|
||||||
|
processedLines.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedLines.join('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* MetadataExtractor.ts
|
||||||
|
*
|
||||||
|
* Handles extraction of metadata from markdown content for PDF export.
|
||||||
|
* Currently focuses on title extraction from markdown headings.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class MetadataExtractor {
|
||||||
|
/**
|
||||||
|
* Extracts title from markdown content by looking for the first heading.
|
||||||
|
*
|
||||||
|
* @param content - The markdown content to extract title from
|
||||||
|
* @returns The title text if found, undefined otherwise
|
||||||
|
*/
|
||||||
|
public static extractTitle(content: string): string | undefined {
|
||||||
|
// Look for first heading
|
||||||
|
const headingMatch = content.match(/^#+\s+(.+)$/m);
|
||||||
|
if (headingMatch) {
|
||||||
|
return headingMatch[1].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Could be enhanced to use filename or frontmatter title
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
/**
|
||||||
|
* WikilinkProcessor - Handles conversion of Obsidian wikilinks to standard markdown links
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface WikilinkConfig {
|
||||||
|
/** Format for wikilink conversion ('md' for .md extension, 'none' for no extension) */
|
||||||
|
format: 'md' | 'none';
|
||||||
|
/** File extension to append to wikilinks */
|
||||||
|
extension: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WikilinkProcessorConfig {
|
||||||
|
/** Wikilink conversion configuration */
|
||||||
|
wikilinkConfig: WikilinkConfig;
|
||||||
|
/** Base URL for relative link resolution */
|
||||||
|
baseUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: PreprocessingResult is imported from the parent MarkdownPreprocessor module
|
||||||
|
export interface PreprocessingResult {
|
||||||
|
/** Processed markdown content */
|
||||||
|
content: string;
|
||||||
|
/** Extracted metadata including tags and frontmatter */
|
||||||
|
metadata: {
|
||||||
|
tags: string[];
|
||||||
|
frontmatter?: Record<string, unknown>;
|
||||||
|
title?: string;
|
||||||
|
pdfEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
imageEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
sizeOrAlt?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
fileEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
fileType: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
/** Processing errors and warnings */
|
||||||
|
errors: string[];
|
||||||
|
/** Processing warnings */
|
||||||
|
warnings: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WikilinkProcessor {
|
||||||
|
private wikilinkConfig: WikilinkConfig;
|
||||||
|
private baseUrl?: string;
|
||||||
|
|
||||||
|
// Regex pattern for comprehensive wikilink matching with headings
|
||||||
|
private readonly WIKILINK_WITH_HEADING_PATTERN = /\[\[([^#|\]]+)(?:#([^|\]]+))?(?:\|([^\]]+))?\]\]/g;
|
||||||
|
|
||||||
|
constructor(config: WikilinkProcessorConfig) {
|
||||||
|
this.wikilinkConfig = config.wikilinkConfig;
|
||||||
|
this.baseUrl = config.baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert wikilinks to standard markdown links
|
||||||
|
*/
|
||||||
|
public processWikilinks(content: string, result: PreprocessingResult): string {
|
||||||
|
// Use the comprehensive pattern that handles headings
|
||||||
|
return content.replace(this.WIKILINK_WITH_HEADING_PATTERN, (match, notePath, headingPath, alias) => {
|
||||||
|
try {
|
||||||
|
// Clean the paths
|
||||||
|
const cleanNotePath = notePath ? notePath.trim() : '';
|
||||||
|
const cleanHeadingPath = headingPath ? headingPath.trim() : '';
|
||||||
|
const cleanAlias = alias ? alias.trim() : '';
|
||||||
|
|
||||||
|
if (!cleanNotePath) {
|
||||||
|
result.warnings.push(`Empty wikilink path found: ${match}`);
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle special characters in filenames
|
||||||
|
const sanitizedNotePath = this.sanitizeFilePath(cleanNotePath);
|
||||||
|
|
||||||
|
// Build the final path
|
||||||
|
let finalPath = sanitizedNotePath;
|
||||||
|
|
||||||
|
// Add extension based on configuration
|
||||||
|
if (this.wikilinkConfig.format === 'md') {
|
||||||
|
finalPath += this.wikilinkConfig.extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add heading anchor if present
|
||||||
|
if (cleanHeadingPath) {
|
||||||
|
const sanitizedHeading = this.sanitizeHeadingForLink(cleanHeadingPath);
|
||||||
|
finalPath += `#${sanitizedHeading}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine display text
|
||||||
|
let displayText: string;
|
||||||
|
if (cleanAlias) {
|
||||||
|
displayText = cleanAlias;
|
||||||
|
} else if (cleanHeadingPath) {
|
||||||
|
displayText = `${cleanNotePath}#${cleanHeadingPath}`;
|
||||||
|
} else {
|
||||||
|
displayText = cleanNotePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle relative path resolution if baseUrl is provided
|
||||||
|
if (this.baseUrl) {
|
||||||
|
finalPath = this.resolveRelativePath(finalPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create standard markdown link
|
||||||
|
return `[${displayText}](${finalPath})`;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Failed to process wikilink: ${match} - ${error.message}`);
|
||||||
|
return match; // Return original on error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize file paths for cross-platform compatibility
|
||||||
|
* Made public as it's also used by embed processors
|
||||||
|
*/
|
||||||
|
public sanitizeFilePath(filePath: string): string {
|
||||||
|
// Remove or replace characters that might cause issues
|
||||||
|
return filePath
|
||||||
|
.replace(/[<>:"|?*]/g, '_') // Replace problematic characters
|
||||||
|
.replace(/\s+/g, '%20') // URL encode spaces
|
||||||
|
.replace(/[\\]/g, '/'); // Normalize path separators
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize heading text for use in markdown links
|
||||||
|
*/
|
||||||
|
private sanitizeHeadingForLink(heading: string): string {
|
||||||
|
return heading
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/\s+/g, '-') // Replace spaces with dashes
|
||||||
|
.replace(/[^\w-]/g, '') // Remove special characters except dashes
|
||||||
|
.replace(/--+/g, '-'); // Collapse multiple dashes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve relative paths if baseUrl is configured
|
||||||
|
*/
|
||||||
|
private resolveRelativePath(path: string): string {
|
||||||
|
if (!this.baseUrl) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple relative path resolution
|
||||||
|
if (path.startsWith('/')) {
|
||||||
|
return path; // Already absolute
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseUrl = this.baseUrl.endsWith('/') ?
|
||||||
|
this.baseUrl :
|
||||||
|
`${this.baseUrl}/`;
|
||||||
|
|
||||||
|
return `${baseUrl}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update configuration
|
||||||
|
*/
|
||||||
|
public updateConfig(config: Partial<WikilinkProcessorConfig>): void {
|
||||||
|
if (config.wikilinkConfig) {
|
||||||
|
this.wikilinkConfig = { ...this.wikilinkConfig, ...config.wikilinkConfig };
|
||||||
|
}
|
||||||
|
if (config.baseUrl !== undefined) {
|
||||||
|
this.baseUrl = config.baseUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current configuration
|
||||||
|
*/
|
||||||
|
public getConfig(): WikilinkProcessorConfig {
|
||||||
|
return {
|
||||||
|
wikilinkConfig: this.wikilinkConfig,
|
||||||
|
baseUrl: this.baseUrl
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default configuration
|
||||||
|
export const DEFAULT_WIKILINK_CONFIG: WikilinkConfig = {
|
||||||
|
format: 'md',
|
||||||
|
extension: '.md'
|
||||||
|
};
|
||||||
+75
-246
@@ -3,13 +3,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { DEPENDENCY_CONSTANTS } from './constants';
|
import { DEPENDENCY_CONSTANTS } from './constants';
|
||||||
|
import { ExportErrorHandler } from './ExportErrorHandler';
|
||||||
export interface DependencyInfo {
|
import { ExecutableChecker, DependencyInfo } from './ExecutableChecker';
|
||||||
name: string;
|
|
||||||
version: string | null;
|
|
||||||
isAvailable: boolean;
|
|
||||||
executablePath: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DependencyCheckResult {
|
export interface DependencyCheckResult {
|
||||||
pandoc: DependencyInfo;
|
pandoc: DependencyInfo;
|
||||||
@@ -20,231 +15,12 @@ export interface DependencyCheckResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class DependencyChecker {
|
export class DependencyChecker {
|
||||||
/**
|
|
||||||
* Get augmented PATH with common binary locations and additional paths
|
|
||||||
*/
|
|
||||||
private static getAugmentedPath(additionalPaths: string[] = []): string {
|
|
||||||
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
|
||||||
|
|
||||||
// Build default system paths - always included regardless of user settings
|
|
||||||
const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p);
|
|
||||||
const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE;
|
|
||||||
const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths];
|
|
||||||
|
|
||||||
// Combine default system paths with user-provided additional paths
|
|
||||||
const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths];
|
|
||||||
|
|
||||||
return `${process.env.PATH}:${allAdditionalPaths.join(':')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get augmented environment with extended PATH
|
|
||||||
*/
|
|
||||||
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
|
|
||||||
return {
|
|
||||||
...process.env,
|
|
||||||
PATH: this.getAugmentedPath(additionalPaths)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Try to find an executable using which command
|
|
||||||
*/
|
|
||||||
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
|
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich: searching for "${executableName}"`);
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stdout = await new Promise<string>((resolve, reject) => {
|
|
||||||
const env = this.getAugmentedEnv(additionalPaths);
|
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich: using PATH="${env.PATH}"`);
|
|
||||||
|
|
||||||
const whichProcess = spawn('which', [executableName], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
env: env
|
|
||||||
});
|
|
||||||
|
|
||||||
let output = '';
|
|
||||||
let error = '';
|
|
||||||
|
|
||||||
whichProcess.stdout?.on('data', (data: Buffer) => {
|
|
||||||
output += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
whichProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
error += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
whichProcess.on('close', (code: number | null) => {
|
|
||||||
console.log(`[DependencyChecker] which ${executableName} exited with code ${code}, stdout: "${output.trim()}", stderr: "${error.trim()}"`);
|
|
||||||
if (code === 0) {
|
|
||||||
resolve(output);
|
|
||||||
} else {
|
|
||||||
reject(new Error(`which command failed with code ${code}: ${error}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
whichProcess.on('error', (err: Error) => {
|
|
||||||
console.log(`[DependencyChecker] which ${executableName} spawn error:`, err.message);
|
|
||||||
reject(new Error(`Failed to spawn which process: ${err.message}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const foundPath = stdout.trim();
|
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich result: "${foundPath}"`);
|
|
||||||
return foundPath || null;
|
|
||||||
} catch (error) {
|
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich caught error:`, error.message);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve the actual executable path, handling empty/undefined settings
|
|
||||||
*/
|
|
||||||
private static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
|
|
||||||
console.log(`[DependencyChecker] ASYNC Resolving path for ${defaultName}: userPath="${userPath}"`);
|
|
||||||
|
|
||||||
// If user provided a full path (contains /), use it as-is
|
|
||||||
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
|
|
||||||
console.log(`[DependencyChecker] ASYNC Using user-provided full path: ${userPath}`);
|
|
||||||
return userPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If user provided just an executable name or empty path, resolve it
|
|
||||||
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
|
|
||||||
console.log(`[DependencyChecker] ASYNC Searching for: ${searchName}`);
|
|
||||||
|
|
||||||
// Try to find the executable using which command
|
|
||||||
const foundPath = await this.findExecutableWithWhich(searchName, additionalPaths);
|
|
||||||
if (foundPath) {
|
|
||||||
console.log(`[DependencyChecker] ASYNC Found via which: ${foundPath}`);
|
|
||||||
return foundPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fall back to the search name (will be found via PATH if available)
|
|
||||||
console.log(`[DependencyChecker] ASYNC Falling back to search name: ${searchName}`);
|
|
||||||
return searchName;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a dependency is available and get its version
|
|
||||||
*/
|
|
||||||
private static async checkDependency(
|
|
||||||
name: string,
|
|
||||||
executablePath: string,
|
|
||||||
versionCommand: string,
|
|
||||||
versionRegex: RegExp
|
|
||||||
): Promise<DependencyInfo> {
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Use spawn instead of exec for security - arguments passed separately
|
|
||||||
const stdout = await new Promise<string>((resolve, reject) => {
|
|
||||||
const checkProcess = spawn(executablePath, versionCommand.split(' '), {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
|
||||||
env: this.getAugmentedEnv()
|
|
||||||
});
|
|
||||||
|
|
||||||
let output = '';
|
|
||||||
let error = '';
|
|
||||||
|
|
||||||
checkProcess.stdout?.on('data', (data: Buffer) => {
|
|
||||||
output += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
checkProcess.stderr?.on('data', (data: Buffer) => {
|
|
||||||
error += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
checkProcess.on('close', (code: number | null) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve(output);
|
|
||||||
} else {
|
|
||||||
reject(new Error(`Command failed with code ${code}: ${error}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
checkProcess.on('error', (err: Error) => {
|
|
||||||
reject(new Error(`Failed to spawn process: ${err.message}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const match = stdout.match(versionRegex);
|
|
||||||
const version = match ? match[1] : null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
version,
|
|
||||||
isAvailable: true,
|
|
||||||
executablePath
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
version: null,
|
|
||||||
isAvailable: false,
|
|
||||||
executablePath
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous version of resolving executable path
|
|
||||||
*/
|
|
||||||
private static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
|
|
||||||
console.log(`[DependencyChecker] SYNC Resolving path for ${defaultName}: userPath="${userPath}"`);
|
|
||||||
|
|
||||||
// If user provided a full path (contains /), use it as-is
|
|
||||||
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
|
|
||||||
console.log(`[DependencyChecker] SYNC Using user-provided full path: ${userPath}`);
|
|
||||||
return userPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If user provided just an executable name or empty path, resolve it
|
|
||||||
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
|
|
||||||
console.log(`[DependencyChecker] SYNC Searching for: ${searchName}`);
|
|
||||||
|
|
||||||
// Try to find the executable using which command synchronously
|
|
||||||
const { spawnSync } = require('child_process');
|
|
||||||
try {
|
|
||||||
const result = spawnSync('which', [searchName], {
|
|
||||||
encoding: 'utf8',
|
|
||||||
env: this.getAugmentedEnv(additionalPaths)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (result.status === 0 && result.stdout) {
|
|
||||||
const foundPath = result.stdout.trim();
|
|
||||||
if (foundPath) {
|
|
||||||
console.log(`[DependencyChecker] SYNC Found via which: ${foundPath}`);
|
|
||||||
return foundPath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Ignore errors from which command
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fall back to the search name (will be found via PATH if available)
|
|
||||||
console.log(`[DependencyChecker] SYNC Falling back to search name: ${searchName}`);
|
|
||||||
return searchName;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a dependency is available (synchronous version for startup)
|
|
||||||
*/
|
|
||||||
private static checkDependencySync(executablePath: string, versionCommand: string): boolean {
|
|
||||||
const { spawnSync } = require('child_process');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = spawnSync(executablePath, versionCommand.split(' '), {
|
|
||||||
encoding: 'utf8',
|
|
||||||
env: this.getAugmentedEnv()
|
|
||||||
});
|
|
||||||
return result.status === 0;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Comprehensive dependency check (async) - returns detailed information
|
* Comprehensive dependency check (async) - returns detailed information
|
||||||
@@ -255,21 +31,17 @@ export class DependencyChecker {
|
|||||||
imagemagickPath?: string,
|
imagemagickPath?: string,
|
||||||
additionalPaths: string[] = []
|
additionalPaths: string[] = []
|
||||||
): Promise<DependencyCheckResult> {
|
): Promise<DependencyCheckResult> {
|
||||||
console.log(`[DependencyChecker] checkAllDependencies called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
|
|
||||||
|
|
||||||
// Resolve actual executable paths, handling empty settings
|
// Resolve actual executable paths, handling empty settings
|
||||||
const [pandocExec, typstExec, imagemagickExec] = await Promise.all([
|
const [pandocExec, typstExec, imagemagickExec] = await Promise.all([
|
||||||
this.resolveExecutablePath(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths),
|
ExecutableChecker.resolveExecutablePath(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths),
|
||||||
this.resolveExecutablePath(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths),
|
ExecutableChecker.resolveExecutablePath(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths),
|
||||||
this.resolveExecutablePath(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths)
|
ExecutableChecker.resolveExecutablePath(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
console.log(`[DependencyChecker] Resolved paths:`, { pandocExec, typstExec, imagemagickExec });
|
|
||||||
|
|
||||||
const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([
|
const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([
|
||||||
this.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/),
|
ExecutableChecker.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/),
|
||||||
this.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/),
|
ExecutableChecker.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/),
|
||||||
this.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/)
|
ExecutableChecker.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo]
|
const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo]
|
||||||
@@ -294,27 +66,84 @@ export class DependencyChecker {
|
|||||||
imagemagickPath?: string,
|
imagemagickPath?: string,
|
||||||
additionalPaths: string[] = []
|
additionalPaths: string[] = []
|
||||||
): string[] {
|
): string[] {
|
||||||
console.log(`[DependencyChecker] checkDependenciesSync called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
|
|
||||||
|
|
||||||
// Resolve actual executable paths, handling empty settings
|
// Resolve actual executable paths, handling empty settings
|
||||||
const pandocExec = this.resolveExecutablePathSync(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths);
|
const pandocExec = ExecutableChecker.resolveExecutablePathSync(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths);
|
||||||
const typstExec = this.resolveExecutablePathSync(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths);
|
const typstExec = ExecutableChecker.resolveExecutablePathSync(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths);
|
||||||
const imagemagickExec = this.resolveExecutablePathSync(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths);
|
const imagemagickExec = ExecutableChecker.resolveExecutablePathSync(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths);
|
||||||
|
|
||||||
console.log(`[DependencyChecker] Resolved paths SYNC:`, { pandocExec, typstExec, imagemagickExec });
|
|
||||||
|
|
||||||
const missingDeps: string[] = [];
|
const missingDeps: string[] = [];
|
||||||
|
|
||||||
if (!this.checkDependencySync(pandocExec, '--version')) {
|
if (!ExecutableChecker.checkDependencySync(pandocExec, '--version')) {
|
||||||
missingDeps.push('Pandoc');
|
missingDeps.push('Pandoc');
|
||||||
}
|
}
|
||||||
if (!this.checkDependencySync(typstExec, '--version')) {
|
if (!ExecutableChecker.checkDependencySync(typstExec, '--version')) {
|
||||||
missingDeps.push('Typst');
|
missingDeps.push('Typst');
|
||||||
}
|
}
|
||||||
if (!this.checkDependencySync(imagemagickExec, '--version')) {
|
if (!ExecutableChecker.checkDependencySync(imagemagickExec, '--version')) {
|
||||||
missingDeps.push('ImageMagick');
|
missingDeps.push('ImageMagick');
|
||||||
}
|
}
|
||||||
|
|
||||||
return missingDeps;
|
return missingDeps;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show dependency status modal
|
||||||
|
*/
|
||||||
|
public static async showDependencyStatus(
|
||||||
|
pandocPath?: string,
|
||||||
|
typstPath?: string,
|
||||||
|
imagemagickPath?: string,
|
||||||
|
additionalPaths: string[] = []
|
||||||
|
): Promise<void> {
|
||||||
|
const dependencyResult = await this.checkAllDependencies(
|
||||||
|
pandocPath,
|
||||||
|
typstPath,
|
||||||
|
imagemagickPath,
|
||||||
|
additionalPaths
|
||||||
|
);
|
||||||
|
|
||||||
|
const formatVersion = (dep: DependencyInfo) => dep.isAvailable ? (dep.version || 'Available') : 'Not found';
|
||||||
|
|
||||||
|
const message = `Dependency Status:
|
||||||
|
Pandoc: ${formatVersion(dependencyResult.pandoc)}
|
||||||
|
Typst: ${formatVersion(dependencyResult.typst)}
|
||||||
|
ImageMagick: ${formatVersion(dependencyResult.imagemagick)}
|
||||||
|
|
||||||
|
${dependencyResult.allAvailable
|
||||||
|
? 'All dependencies found!'
|
||||||
|
: `Missing dependencies: ${dependencyResult.missingDependencies.join(', ')}. Please install them and check the paths in settings.`}`;
|
||||||
|
|
||||||
|
ExportErrorHandler.showProgressNotice(message, 12000); // Show for 12 seconds (longer due to more content)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check dependencies silently on startup and show notice if missing
|
||||||
|
*/
|
||||||
|
public static async checkDependenciesAsync(
|
||||||
|
pandocPath?: string,
|
||||||
|
typstPath?: string,
|
||||||
|
imagemagickPath?: string,
|
||||||
|
additionalPaths: string[] = []
|
||||||
|
): Promise<void> {
|
||||||
|
// Check dependencies silently on startup
|
||||||
|
try {
|
||||||
|
const missingDeps = this.checkDependenciesSync(
|
||||||
|
pandocPath,
|
||||||
|
typstPath,
|
||||||
|
imagemagickPath,
|
||||||
|
additionalPaths
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only show notice if dependencies are missing
|
||||||
|
if (missingDeps.length > 0) {
|
||||||
|
ExportErrorHandler.showProgressNotice(
|
||||||
|
`Typst PDF Export: Missing dependencies: ${missingDeps.join(', ')}. ` +
|
||||||
|
`Run "Check Dependencies" command for details.`,
|
||||||
|
8000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ExportErrorHandler.handleDependencyError('Dependencies', error, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
/**
|
||||||
|
* Executable checking utilities for Obsidian Typst PDF Export plugin
|
||||||
|
* Handles path resolution, version detection, and availability checking for external executables
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { DEPENDENCY_CONSTANTS } from './constants';
|
||||||
|
|
||||||
|
export interface DependencyInfo {
|
||||||
|
name: string;
|
||||||
|
version: string | null;
|
||||||
|
isAvailable: boolean;
|
||||||
|
executablePath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities for checking executable availability and versions
|
||||||
|
*/
|
||||||
|
export class ExecutableChecker {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an augmented PATH that includes common system paths and additional paths
|
||||||
|
*/
|
||||||
|
private static getAugmentedPath(additionalPaths: string[] = []): string {
|
||||||
|
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
||||||
|
|
||||||
|
// Build default system paths - always included regardless of user settings
|
||||||
|
const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p);
|
||||||
|
const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE;
|
||||||
|
const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths];
|
||||||
|
|
||||||
|
// Combine default system paths with user-provided additional paths
|
||||||
|
const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths];
|
||||||
|
|
||||||
|
return `${process.env.PATH}:${allAdditionalPaths.join(':')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an augmented environment with extended PATH
|
||||||
|
*/
|
||||||
|
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
PATH: this.getAugmentedPath(additionalPaths)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Try to find an executable using which command
|
||||||
|
*/
|
||||||
|
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stdout = await new Promise<string>((resolve, reject) => {
|
||||||
|
const env = this.getAugmentedEnv(additionalPaths);
|
||||||
|
|
||||||
|
const whichProcess = spawn('which', [executableName], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: env
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
let error = '';
|
||||||
|
|
||||||
|
whichProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
whichProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
whichProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve(output);
|
||||||
|
} else {
|
||||||
|
reject(new Error(`which command failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
whichProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn which process: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const foundPath = stdout.trim();
|
||||||
|
return foundPath || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve executable path - async version
|
||||||
|
*/
|
||||||
|
public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
|
||||||
|
// If user provided a full path (contains /), use it as-is
|
||||||
|
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
|
||||||
|
return userPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If user provided just an executable name or empty path, resolve it
|
||||||
|
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
|
||||||
|
|
||||||
|
// Try to find the executable using which command
|
||||||
|
const foundPath = await this.findExecutableWithWhich(searchName, additionalPaths);
|
||||||
|
if (foundPath) {
|
||||||
|
return foundPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to the search name (will be found via PATH if available)
|
||||||
|
return searchName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve executable path - sync version
|
||||||
|
*/
|
||||||
|
public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
|
||||||
|
// If user provided a full path (contains /), use it as-is
|
||||||
|
if (userPath && userPath.trim() !== '' && userPath.includes('/')) {
|
||||||
|
return userPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If user provided just an executable name or empty path, resolve it
|
||||||
|
const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName;
|
||||||
|
|
||||||
|
// Try to find the executable using which command synchronously
|
||||||
|
const { spawnSync } = require('child_process');
|
||||||
|
try {
|
||||||
|
const result = spawnSync('which', [searchName], {
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: this.getAugmentedEnv(additionalPaths)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.status === 0 && result.stdout) {
|
||||||
|
const foundPath = result.stdout.trim();
|
||||||
|
if (foundPath) {
|
||||||
|
return foundPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore errors from which command
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to the search name (will be found via PATH if available)
|
||||||
|
return searchName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a dependency is available and get its version - async version
|
||||||
|
*/
|
||||||
|
public static async checkDependency(
|
||||||
|
name: string,
|
||||||
|
executablePath: string,
|
||||||
|
versionCommand: string,
|
||||||
|
versionRegex: RegExp
|
||||||
|
): Promise<DependencyInfo> {
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Use spawn instead of exec for security - arguments passed separately
|
||||||
|
const stdout = await new Promise<string>((resolve, reject) => {
|
||||||
|
const checkProcess = spawn(executablePath, versionCommand.split(' '), {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: this.getAugmentedEnv()
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
let error = '';
|
||||||
|
|
||||||
|
checkProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
checkProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
checkProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve(output);
|
||||||
|
} else {
|
||||||
|
reject(new Error(`Command failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
checkProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn process: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const match = stdout.match(versionRegex);
|
||||||
|
const version = match ? match[1] : null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
isAvailable: true,
|
||||||
|
executablePath
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
version: null,
|
||||||
|
isAvailable: false,
|
||||||
|
executablePath
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quick sync check if a dependency is available
|
||||||
|
*/
|
||||||
|
public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
|
||||||
|
const { spawnSync } = require('child_process');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = spawnSync(executablePath, versionCommand.split(' '), {
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: this.getAugmentedEnv()
|
||||||
|
});
|
||||||
|
return result.status === 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -168,4 +168,59 @@ export class ExportErrorHandler {
|
|||||||
public static showCancellationNotice(): void {
|
public static showCancellationNotice(): void {
|
||||||
new Notice('Export cancelled');
|
new Notice('Export cancelled');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show settings validation error
|
||||||
|
*/
|
||||||
|
public static showValidationError(field: string, validationMessage: string): void {
|
||||||
|
new Notice(`Invalid ${field}: ${validationMessage}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show template loading error
|
||||||
|
*/
|
||||||
|
public static showTemplateError(error: Error | string): void {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
new Notice(`Failed to load available templates: ${errorMessage}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show font caching error
|
||||||
|
*/
|
||||||
|
public static showFontError(error: Error | string, showFallback: boolean = true): void {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000);
|
||||||
|
|
||||||
|
if (showFallback) {
|
||||||
|
new Notice('Font list may be incomplete. Check debug mode for details.', 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show export success notice
|
||||||
|
*/
|
||||||
|
public static showExportSuccess(outputPath: string): void {
|
||||||
|
new Notice(`PDF exported successfully to ${outputPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show file not found warning
|
||||||
|
*/
|
||||||
|
public static showFileNotFoundWarning(context: string): void {
|
||||||
|
new Notice(`Please open a ${context} file to export`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show no files warning
|
||||||
|
*/
|
||||||
|
public static showNoFilesWarning(context: string = 'files'): void {
|
||||||
|
new Notice(`No ${context} to export`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show settings reset confirmation
|
||||||
|
*/
|
||||||
|
public static showSettingsReset(): void {
|
||||||
|
new Notice('Settings reset to defaults');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ export class ModalSettingsHelper {
|
|||||||
/**
|
/**
|
||||||
* Build template variables object from plugin settings
|
* Build template variables object from plugin settings
|
||||||
*/
|
*/
|
||||||
private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, any> {
|
private static buildTemplateVariables(settings: obsidianTypstPDFExportSettings): Record<string, string | number | boolean | undefined> {
|
||||||
const baseVariables = {
|
const baseVariables = {
|
||||||
pageSize: settings.pageSetup.size,
|
pageSize: settings.pageSetup.size,
|
||||||
orientation: settings.pageSetup.orientation,
|
orientation: settings.pageSetup.orientation,
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// ABOUTME: Centralized path utilities for safe Obsidian API operations
|
||||||
|
// ABOUTME: Handles vault paths, plugin directories, and file operations
|
||||||
|
|
||||||
|
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
|
||||||
|
import type { App, PluginManifest } from 'obsidian';
|
||||||
|
|
||||||
|
export class PathUtils {
|
||||||
|
constructor(private app: App) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get vault base path safely with FileSystemAdapter check
|
||||||
|
*/
|
||||||
|
getVaultPath(): string {
|
||||||
|
const adapter = this.app.vault.adapter;
|
||||||
|
if (!(adapter instanceof FileSystemAdapter)) {
|
||||||
|
new Notice('This plugin requires desktop Obsidian');
|
||||||
|
throw new Error('FileSystemAdapter not available - desktop Obsidian required');
|
||||||
|
}
|
||||||
|
return adapter.getBasePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get plugin directory path
|
||||||
|
*/
|
||||||
|
getPluginDir(pluginManifest: PluginManifest): string {
|
||||||
|
return normalizePath(pluginManifest.dir || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Join path segments with normalizePath
|
||||||
|
*/
|
||||||
|
joinPath(...segments: string[]): string {
|
||||||
|
// Filter out empty segments
|
||||||
|
const filtered = segments.filter(s => s);
|
||||||
|
const joined = filtered.join('/');
|
||||||
|
return normalizePath(joined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure directory exists, create if necessary
|
||||||
|
*/
|
||||||
|
async ensureDir(path: string): Promise<void> {
|
||||||
|
const normalizedPath = normalizePath(path);
|
||||||
|
try {
|
||||||
|
const exists = await this.app.vault.adapter.exists(normalizedPath);
|
||||||
|
if (!exists) {
|
||||||
|
await this.app.vault.adapter.mkdir(normalizedPath);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
new Notice(`Failed to create directory: ${normalizedPath}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean up directory contents (files only, like current TempDirectoryManager)
|
||||||
|
*/
|
||||||
|
async cleanupDir(path: string): Promise<boolean> {
|
||||||
|
const normalizedPath = normalizePath(path);
|
||||||
|
try {
|
||||||
|
const exists = await this.app.vault.adapter.exists(normalizedPath);
|
||||||
|
if (exists && this.app.vault.adapter instanceof FileSystemAdapter) {
|
||||||
|
const list = await this.app.vault.adapter.list(normalizedPath);
|
||||||
|
// Remove only files, not subdirectories (matching current pattern)
|
||||||
|
for (const file of list.files) {
|
||||||
|
await this.app.vault.adapter.remove(file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Failed to cleanup directory ${normalizedPath}:`, error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if file or directory exists
|
||||||
|
* Handles both vault-relative paths and absolute filesystem paths
|
||||||
|
*/
|
||||||
|
async fileExists(path: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// First, try as vault-relative path
|
||||||
|
const normalizedPath = normalizePath(path);
|
||||||
|
const exists = await this.app.vault.adapter.exists(normalizedPath);
|
||||||
|
if (exists) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// If vault.adapter fails, path might be absolute
|
||||||
|
}
|
||||||
|
|
||||||
|
// If path is absolute, convert to vault-relative and try again
|
||||||
|
const vaultBasePath = this.getVaultPath();
|
||||||
|
if (path.startsWith(vaultBasePath)) {
|
||||||
|
try {
|
||||||
|
// Remove vault base path and leading separator
|
||||||
|
let relativePath = path.substring(vaultBasePath.length);
|
||||||
|
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
|
||||||
|
relativePath = relativePath.substring(1);
|
||||||
|
}
|
||||||
|
const normalizedRelativePath = normalizePath(relativePath);
|
||||||
|
return await this.app.vault.adapter.exists(normalizedRelativePath);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For paths outside vault, use fs fallback (needed for external file processing)
|
||||||
|
const isAbsolutePath = path.startsWith('/') || // Unix absolute
|
||||||
|
/^[a-zA-Z]:[/\\]/.test(path) || // Windows drive letter (C:\ or C:/)
|
||||||
|
path.startsWith('\\\\'); // Windows UNC path (\\server\share)
|
||||||
|
|
||||||
|
if (isAbsolutePath) {
|
||||||
|
try {
|
||||||
|
const fs = require('fs').promises;
|
||||||
|
await fs.access(path);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ export class SecurityUtils {
|
|||||||
// Check for command injection attempts
|
// Check for command injection attempts
|
||||||
const dangerousPatterns = [
|
const dangerousPatterns = [
|
||||||
/[;&|`$(){}[\]]/, // Shell metacharacters
|
/[;&|`$(){}[\]]/, // Shell metacharacters
|
||||||
|
// eslint-disable-next-line no-control-regex
|
||||||
/\x00/, // Null bytes
|
/\x00/, // Null bytes
|
||||||
/\n|\r/, // Newlines
|
/\n|\r/, // Newlines
|
||||||
/\s*[;&|]\s*/, // Command separators with whitespace
|
/\s*[;&|]\s*/, // Command separators with whitespace
|
||||||
@@ -113,7 +114,7 @@ export class SecurityUtils {
|
|||||||
if (/[;&|`$(){}[\]]/.test(normalizedPath)) {
|
if (/[;&|`$(){}[\]]/.test(normalizedPath)) {
|
||||||
return 'Shell metacharacters are not allowed in executable paths';
|
return 'Shell metacharacters are not allowed in executable paths';
|
||||||
}
|
}
|
||||||
if (/\x00/.test(normalizedPath)) {
|
if (/\x00/.test(normalizedPath)) { // eslint-disable-line no-control-regex
|
||||||
return 'Null bytes are not allowed in paths';
|
return 'Null bytes are not allowed in paths';
|
||||||
}
|
}
|
||||||
if (/\n|\r/.test(normalizedPath)) {
|
if (/\n|\r/.test(normalizedPath)) {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
/**
|
// ABOUTME: Manages temporary directories for export operations
|
||||||
* Manages temporary directories for export operations
|
// ABOUTME: Uses normalizePath for cross-platform path operations
|
||||||
*/
|
|
||||||
|
|
||||||
import { PLUGIN_DIRS } from './constants';
|
import { PLUGIN_DIRS } from './constants';
|
||||||
|
import { normalizePath } from 'obsidian';
|
||||||
|
import type { App } from 'obsidian';
|
||||||
|
|
||||||
export interface TempDirectoryOptions {
|
export interface TempDirectoryOptions {
|
||||||
/** Base path for the vault */
|
/** Base path for the vault */
|
||||||
@@ -11,26 +12,28 @@ export interface TempDirectoryOptions {
|
|||||||
configDir: string;
|
configDir: string;
|
||||||
/** Plugin directory name (defaults to 'typst-pdf-export') */
|
/** Plugin directory name (defaults to 'typst-pdf-export') */
|
||||||
pluginName?: string;
|
pluginName?: string;
|
||||||
|
/** App instance for vault.adapter operations */
|
||||||
|
app: App;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TempDirectoryManager {
|
export class TempDirectoryManager {
|
||||||
private readonly fs = require('fs');
|
|
||||||
private readonly path = require('path');
|
|
||||||
private readonly vaultPath: string;
|
private readonly vaultPath: string;
|
||||||
private readonly configDir: string;
|
private readonly configDir: string;
|
||||||
private readonly pluginName: string;
|
private readonly pluginName: string;
|
||||||
|
private readonly app: App;
|
||||||
|
|
||||||
constructor(options: TempDirectoryOptions) {
|
constructor(options: TempDirectoryOptions) {
|
||||||
this.vaultPath = options.vaultPath;
|
this.vaultPath = options.vaultPath;
|
||||||
this.configDir = options.configDir;
|
this.configDir = options.configDir;
|
||||||
this.pluginName = options.pluginName || 'typst-pdf-export';
|
this.pluginName = options.pluginName || 'typst-pdf-export';
|
||||||
|
this.app = options.app;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the plugin directory path
|
* Get the plugin directory path
|
||||||
*/
|
*/
|
||||||
private getPluginDir(): string {
|
private getPluginDir(): string {
|
||||||
return this.path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
|
return normalizePath([this.vaultPath, this.configDir, 'plugins', this.pluginName].join('/'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,17 +41,18 @@ export class TempDirectoryManager {
|
|||||||
*/
|
*/
|
||||||
public getTempDir(type: 'images' | 'pandoc'): string {
|
public getTempDir(type: 'images' | 'pandoc'): string {
|
||||||
const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC;
|
const dirName = type === 'images' ? PLUGIN_DIRS.TEMP_IMAGES : PLUGIN_DIRS.TEMP_PANDOC;
|
||||||
return this.path.join(this.getPluginDir(), dirName);
|
return normalizePath([this.getPluginDir(), dirName].join('/'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure a temp directory exists, creating it if necessary
|
* Ensure a temp directory exists, creating it if necessary
|
||||||
*/
|
*/
|
||||||
public ensureTempDir(type: 'images' | 'pandoc'): string {
|
public async ensureTempDir(type: 'images' | 'pandoc'): Promise<string> {
|
||||||
const tempDir = this.getTempDir(type);
|
const tempDir = this.getTempDir(type);
|
||||||
|
|
||||||
if (!this.fs.existsSync(tempDir)) {
|
const exists = await this.app.vault.adapter.exists(tempDir);
|
||||||
this.fs.mkdirSync(tempDir, { recursive: true });
|
if (!exists) {
|
||||||
|
await this.app.vault.adapter.mkdir(tempDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
return tempDir;
|
return tempDir;
|
||||||
@@ -57,40 +61,40 @@ export class TempDirectoryManager {
|
|||||||
/**
|
/**
|
||||||
* Clean up a specific temp directory
|
* Clean up a specific temp directory
|
||||||
*/
|
*/
|
||||||
public cleanupTempDir(type: 'images' | 'pandoc'): boolean {
|
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
|
||||||
const tempDir = this.getTempDir(type);
|
const tempDir = this.getTempDir(type);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (this.fs.existsSync(tempDir)) {
|
const exists = await this.app.vault.adapter.exists(tempDir);
|
||||||
const files = this.fs.readdirSync(tempDir);
|
if (exists) {
|
||||||
for (const file of files) {
|
const list = await this.app.vault.adapter.list(tempDir);
|
||||||
this.fs.unlinkSync(this.path.join(tempDir, file));
|
// Remove only files, not subdirectories (matching current pattern)
|
||||||
|
for (const file of list.files) {
|
||||||
|
await this.app.vault.adapter.remove(file);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Export: Failed to clean up ${type === 'images' ? 'temp-images' : 'temp-pandoc'} directory:`, error);
|
console.warn(`Export: Failed to clean up ${type === 'images' ? 'temp-images' : 'temp-pandoc'} directory:`, error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up all temp directories
|
* Clean up all temp directories
|
||||||
*/
|
*/
|
||||||
public cleanupAllTempDirs(): { images: boolean; pandoc: boolean } {
|
public async cleanupAllTempDirs(): Promise<{ images: boolean; pandoc: boolean }> {
|
||||||
return {
|
return {
|
||||||
images: this.cleanupTempDir('images'),
|
images: await this.cleanupTempDir('images'),
|
||||||
pandoc: this.cleanupTempDir('pandoc')
|
pandoc: await this.cleanupTempDir('pandoc')
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Static helper to create manager from vault path and configDir
|
* Static helper to create manager from vault path and configDir
|
||||||
*/
|
*/
|
||||||
public static create(vaultPath: string, configDir: string, pluginName?: string): TempDirectoryManager {
|
public static create(vaultPath: string, configDir: string, pluginName: string | undefined, app: App): TempDirectoryManager {
|
||||||
return new TempDirectoryManager({ vaultPath, configDir, pluginName });
|
return new TempDirectoryManager({ vaultPath, configDir, pluginName, app });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -98,10 +102,12 @@ export class TempDirectoryManager {
|
|||||||
*/
|
*/
|
||||||
public isPluginTempDir(dirPath: string): boolean {
|
public isPluginTempDir(dirPath: string): boolean {
|
||||||
const pluginDir = this.getPluginDir();
|
const pluginDir = this.getPluginDir();
|
||||||
const normalizedPath = this.path.resolve(dirPath);
|
const normalizedDirPath = normalizePath(dirPath);
|
||||||
const normalizedPluginDir = this.path.resolve(pluginDir);
|
const normalizedPluginDir = normalizePath(pluginDir);
|
||||||
|
const tempImagesDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_IMAGES].join('/'));
|
||||||
|
const tempPandocDir = normalizePath([normalizedPluginDir, PLUGIN_DIRS.TEMP_PANDOC].join('/'));
|
||||||
|
|
||||||
return normalizedPath.startsWith(normalizedPluginDir) &&
|
return normalizedDirPath.startsWith(tempImagesDir) ||
|
||||||
(dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC));
|
normalizedDirPath.startsWith(tempPandocDir);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,9 @@ export interface obsidianTypstPDFExportSettings {
|
|||||||
additionalPaths: string[];
|
additionalPaths: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Custom environment variables for subprocess execution */
|
||||||
|
customEnvironmentVariables: { [key: string]: string };
|
||||||
|
|
||||||
/** Export defaults */
|
/** Export defaults */
|
||||||
exportDefaults: {
|
exportDefaults: {
|
||||||
/** Default template to use for exports */
|
/** Default template to use for exports */
|
||||||
@@ -108,6 +111,8 @@ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
|
|||||||
additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']
|
additionalPaths: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']
|
||||||
},
|
},
|
||||||
|
|
||||||
|
customEnvironmentVariables: {},
|
||||||
|
|
||||||
exportDefaults: {
|
exportDefaults: {
|
||||||
template: 'default',
|
template: 'default',
|
||||||
format: ExportFormat.Standard,
|
format: ExportFormat.Standard,
|
||||||
@@ -156,4 +161,4 @@ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
|
|||||||
embedAllFiles: true,
|
embedAllFiles: true,
|
||||||
printFrontmatter: false
|
printFrontmatter: false
|
||||||
}
|
}
|
||||||
};;;;
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Command Registration
|
||||||
|
* Handles registration of all plugin commands and their callbacks
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Editor, MarkdownView } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
|
||||||
|
export class CommandRegistry {
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register all plugin commands
|
||||||
|
*/
|
||||||
|
registerCommands(): void {
|
||||||
|
// Export current note command
|
||||||
|
this.plugin.addCommand({
|
||||||
|
id: 'export-current-note',
|
||||||
|
name: 'Export current note(s)',
|
||||||
|
editorCallback: (editor: Editor, view: MarkdownView) => {
|
||||||
|
this.plugin.exportCurrentNote(view);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Export with configuration command
|
||||||
|
this.plugin.addCommand({
|
||||||
|
id: 'export-with-config',
|
||||||
|
name: 'Export with configuration…',
|
||||||
|
editorCallback: (editor: Editor, view: MarkdownView) => {
|
||||||
|
this.plugin.showExportModal(view);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check dependencies command
|
||||||
|
this.plugin.addCommand({
|
||||||
|
id: 'check-dependencies',
|
||||||
|
name: 'Check Pandoc and Typst dependencies',
|
||||||
|
callback: () => {
|
||||||
|
this.plugin.showDependencyStatus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
/**
|
||||||
|
* Embed Processing
|
||||||
|
* Handles processing of PDF, image, and file embeds for PDF export
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { TFile } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import type { PreprocessingResult } from '../converters/MarkdownPreprocessor';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
export class EmbedProcessor {
|
||||||
|
private readonly pathUtils: PathUtils;
|
||||||
|
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process PDF embeds - convert PDF pages to images for inclusion
|
||||||
|
*/
|
||||||
|
async processPdfEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise<void> {
|
||||||
|
const { PdfToImageConverter } = await import('../converters/PdfToImageConverter');
|
||||||
|
const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
|
||||||
|
let updatedContent = processedResult.content;
|
||||||
|
|
||||||
|
for (const pdfEmbed of processedResult.metadata?.pdfEmbeds || []) {
|
||||||
|
try {
|
||||||
|
// Resolve PDF path using helper method
|
||||||
|
const fullPdfPath = await this.resolvePdfPath(pdfEmbed.sanitizedPath, vaultBasePath, currentFile);
|
||||||
|
|
||||||
|
if (!fullPdfPath) {
|
||||||
|
console.warn(`Export: PDF file not found: ${decodeURIComponent(pdfEmbed.sanitizedPath)}`);
|
||||||
|
// Replace marker with fallback message
|
||||||
|
const fallbackOutput = `*⚠️ PDF not found: ${pdfEmbed.baseName}*`;
|
||||||
|
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert PDF first page to image - pass options object as third parameter
|
||||||
|
const result = await converter.convertFirstPageToImage(
|
||||||
|
fullPdfPath,
|
||||||
|
tempDir,
|
||||||
|
{
|
||||||
|
scale: 1.5,
|
||||||
|
maxWidth: 800,
|
||||||
|
maxHeight: 600,
|
||||||
|
format: 'png'
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.success && result.imagePath) {
|
||||||
|
// Copy image to vault temp directory and get relative paths
|
||||||
|
const { relativeImagePath, relativePdfPath } = await this.copyImageToVaultTemp(
|
||||||
|
result.imagePath,
|
||||||
|
fullPdfPath,
|
||||||
|
pdfEmbed.baseName,
|
||||||
|
vaultBasePath
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create combined output with image and optionally Typst pdf.embed using helper
|
||||||
|
const combinedOutput = this.generatePdfEmbedContent(
|
||||||
|
relativePdfPath,
|
||||||
|
pdfEmbed.baseName,
|
||||||
|
relativeImagePath,
|
||||||
|
undefined,
|
||||||
|
embedPdfFiles
|
||||||
|
);
|
||||||
|
|
||||||
|
// Replace the placeholder with the combined output
|
||||||
|
updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
console.warn(`Export: Failed to convert PDF to image: ${result.error}`);
|
||||||
|
const relativePdfPath = path.relative(vaultBasePath, fullPdfPath);
|
||||||
|
// Even without preview image, still embed the PDF if requested
|
||||||
|
const fallbackOutput = this.generatePdfEmbedContent(
|
||||||
|
relativePdfPath,
|
||||||
|
pdfEmbed.baseName,
|
||||||
|
undefined,
|
||||||
|
'(preview not available)',
|
||||||
|
embedPdfFiles
|
||||||
|
);
|
||||||
|
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ExportErrorHandler.handleProcessingError('PDF embed', pdfEmbed.originalPath, error);
|
||||||
|
// Still try to embed the PDF even if there's a processing error
|
||||||
|
const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath);
|
||||||
|
const fallbackOutput = this.generatePdfEmbedContent(
|
||||||
|
relativePdfPath,
|
||||||
|
pdfEmbed.baseName,
|
||||||
|
undefined,
|
||||||
|
'(error occurred)',
|
||||||
|
embedPdfFiles
|
||||||
|
);
|
||||||
|
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the processed result with the new content
|
||||||
|
processedResult.content = updatedContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process image embeds - ensure images are accessible for Typst
|
||||||
|
*/
|
||||||
|
async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise<void> {
|
||||||
|
let updatedContent = processedResult.content;
|
||||||
|
|
||||||
|
for (const imageEmbed of processedResult.metadata?.imageEmbeds || []) {
|
||||||
|
try {
|
||||||
|
// Decode the URL-encoded sanitized path back to normal characters
|
||||||
|
const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath);
|
||||||
|
|
||||||
|
// Try multiple path resolution strategies
|
||||||
|
const possiblePaths = [
|
||||||
|
// Strategy 1: Relative to vault root (standard Obsidian behavior)
|
||||||
|
path.resolve(vaultBasePath, decodedPath),
|
||||||
|
// Strategy 2: Relative to current file's directory (for local attachments)
|
||||||
|
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
|
||||||
|
// Strategy 3: Check in attachments folder (common pattern)
|
||||||
|
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath))
|
||||||
|
].filter((p): p is string => p !== null);
|
||||||
|
|
||||||
|
let fullImagePath = null;
|
||||||
|
|
||||||
|
// Try each possible path until we find one that exists
|
||||||
|
for (const possiblePath of possiblePaths) {
|
||||||
|
try {
|
||||||
|
const exists = await this.pathUtils.fileExists(possiblePath);
|
||||||
|
if (exists) {
|
||||||
|
fullImagePath = possiblePath;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// File doesn't exist, continue to next path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fullImagePath) {
|
||||||
|
console.warn(`Export: Image file not found: ${decodedPath}`);
|
||||||
|
// Keep the original marker or replace with placeholder
|
||||||
|
const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`;
|
||||||
|
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle WebP conversion if needed
|
||||||
|
let finalImagePath = fullImagePath;
|
||||||
|
const fileExtension = path.extname(fullImagePath).toLowerCase();
|
||||||
|
|
||||||
|
if (fileExtension === '.webp') {
|
||||||
|
// Convert WebP to PNG using ImageMagick
|
||||||
|
const originalImageName = path.basename(fullImagePath);
|
||||||
|
const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
|
||||||
|
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||||
|
await this.pathUtils.ensureDir(vaultTempImagesDir);
|
||||||
|
|
||||||
|
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
|
||||||
|
|
||||||
|
const { exec } = require('child_process');
|
||||||
|
const util = require('util');
|
||||||
|
const execAsync = util.promisify(exec);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Use PathResolver to get the correct ImageMagick path
|
||||||
|
const { PathResolver } = await import('./PathResolver');
|
||||||
|
const pathResolver = new PathResolver(this.plugin);
|
||||||
|
const imagemagickPath = pathResolver.resolveExecutablePath(
|
||||||
|
this.plugin.settings.executablePaths.imagemagickPath,
|
||||||
|
'magick'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!imagemagickPath) {
|
||||||
|
throw new Error('ImageMagick not found - please install ImageMagick or configure the path in settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use resolved ImageMagick path to convert WebP to PNG
|
||||||
|
await execAsync(`"${imagemagickPath}" "${fullImagePath}" "${convertedImagePath}"`);
|
||||||
|
finalImagePath = convertedImagePath;
|
||||||
|
} catch (convertError) {
|
||||||
|
console.error(`Export: Failed to convert WebP image: ${convertError.message}`);
|
||||||
|
// Fall back to original path and let Typst/Pandoc handle the error
|
||||||
|
console.warn(`Export: Proceeding with original WebP file: ${fullImagePath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get relative path from vault base for the final image
|
||||||
|
const relativeImagePath = path.relative(vaultBasePath, finalImagePath);
|
||||||
|
|
||||||
|
// Create the appropriate markdown output based on size/alt text
|
||||||
|
let imageOutput;
|
||||||
|
if (imageEmbed.sizeOrAlt) {
|
||||||
|
// Check if it's size information (width x height pattern)
|
||||||
|
const sizeMatch = imageEmbed.sizeOrAlt.match(/^(\d+)(?:x(\d+))?$/);
|
||||||
|
if (sizeMatch) {
|
||||||
|
const width = sizeMatch[1];
|
||||||
|
const height = sizeMatch[2];
|
||||||
|
|
||||||
|
// Create image with size attributes (optimized for Pandoc → Typst conversion)
|
||||||
|
if (height) {
|
||||||
|
imageOutput = `<img src="${relativeImagePath}" width="${width}" height="${height}" alt="${imageEmbed.baseName}" />`;
|
||||||
|
} else {
|
||||||
|
imageOutput = `<img src="${relativeImagePath}" width="${width}" alt="${imageEmbed.baseName}" />`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Treat as alt text
|
||||||
|
imageOutput = ``;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Standard image reference
|
||||||
|
imageOutput = ``;
|
||||||
|
}
|
||||||
|
|
||||||
|
updatedContent = updatedContent.replace(imageEmbed.marker, imageOutput);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
const { fallback } = ExportErrorHandler.handleProcessingError(
|
||||||
|
'image embed',
|
||||||
|
imageEmbed.originalPath,
|
||||||
|
error,
|
||||||
|
`[⚠️ **Image processing error:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`
|
||||||
|
);
|
||||||
|
updatedContent = updatedContent.replace(imageEmbed.marker, fallback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the processed result with the new content
|
||||||
|
processedResult.content = updatedContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process file embeds - Convert to attachments using Typst's pdf.embed
|
||||||
|
*/
|
||||||
|
async processFileEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise<void> {
|
||||||
|
let updatedContent = processedResult.content;
|
||||||
|
|
||||||
|
for (const fileEmbed of processedResult.metadata?.fileEmbeds || []) {
|
||||||
|
try {
|
||||||
|
// Resolve file path using helper method (similar to PDF processing)
|
||||||
|
const fullFilePath = await this.resolveFilePath(fileEmbed.sanitizedPath, vaultBasePath, currentFile);
|
||||||
|
|
||||||
|
if (!fullFilePath) {
|
||||||
|
console.warn(`Export: File not found: ${decodeURIComponent(fileEmbed.sanitizedPath)}`);
|
||||||
|
// Replace marker with fallback message
|
||||||
|
const fallbackOutput = `*⚠️ File not found: ${fileEmbed.baseName}*`;
|
||||||
|
updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (embedAllFiles) {
|
||||||
|
// Get relative path from vault base
|
||||||
|
const relativeFilePath = path.relative(vaultBasePath, fullFilePath);
|
||||||
|
|
||||||
|
// Create file embed content using helper method
|
||||||
|
const combinedOutput = this.generateFileEmbedContent(
|
||||||
|
relativeFilePath,
|
||||||
|
fileEmbed.baseName,
|
||||||
|
fileEmbed.fileType,
|
||||||
|
undefined
|
||||||
|
);
|
||||||
|
|
||||||
|
// Replace the placeholder with the combined output
|
||||||
|
updatedContent = updatedContent.replace(fileEmbed.marker, combinedOutput);
|
||||||
|
} else {
|
||||||
|
// Just show as a link if embedding is disabled
|
||||||
|
const relativeFilePath = path.relative(vaultBasePath, fullFilePath);
|
||||||
|
const fileIcon = this.getFileTypeIcon(fileEmbed.fileType);
|
||||||
|
const linkOutput = `[${fileIcon} ${fileEmbed.fileName}](${relativeFilePath})`;
|
||||||
|
updatedContent = updatedContent.replace(fileEmbed.marker, linkOutput);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ExportErrorHandler.handleProcessingError('File embed', fileEmbed.originalPath, error);
|
||||||
|
// Still try to show as a link even if there's a processing error
|
||||||
|
const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath);
|
||||||
|
const fileIcon = this.getFileTypeIcon(fileEmbed.fileType);
|
||||||
|
const fallbackOutput = `[${fileIcon} ${fileEmbed.fileName} (error occurred)](${relativeFilePath})`;
|
||||||
|
updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the processed result with the new content
|
||||||
|
processedResult.content = updatedContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve PDF path using Obsidian's link resolution API and filesystem fallbacks
|
||||||
|
* @param sanitizedPath The sanitized path from the embed
|
||||||
|
* @param vaultBasePath Base path of the vault
|
||||||
|
* @param currentFile Current file being processed (optional)
|
||||||
|
* @returns Full path to PDF file if found, null otherwise
|
||||||
|
*/
|
||||||
|
private async resolvePdfPath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise<string | null> {
|
||||||
|
// Decode the URL-encoded sanitized path back to normal characters
|
||||||
|
const decodedPath = decodeURIComponent(sanitizedPath);
|
||||||
|
|
||||||
|
// Strategy 1: Use Obsidian's link resolution API (primary strategy)
|
||||||
|
if (currentFile) {
|
||||||
|
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest(
|
||||||
|
decodedPath,
|
||||||
|
currentFile.path
|
||||||
|
);
|
||||||
|
|
||||||
|
if (resolvedFile && resolvedFile instanceof TFile) {
|
||||||
|
// Convert to full filesystem path
|
||||||
|
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
|
||||||
|
try {
|
||||||
|
const exists = await this.pathUtils.fileExists(fullPath);
|
||||||
|
if (exists) {
|
||||||
|
return fullPath;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// File exists in metadata but not on filesystem, continue to fallbacks
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback strategies: Try filesystem-based resolution
|
||||||
|
const possiblePaths = [
|
||||||
|
// Strategy 2: Relative to vault root (standard Obsidian behavior)
|
||||||
|
path.resolve(vaultBasePath, decodedPath),
|
||||||
|
// Strategy 3: Relative to current file's directory (for local attachments)
|
||||||
|
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null
|
||||||
|
].filter((p): p is string => p !== null);
|
||||||
|
|
||||||
|
// Try each possible path until we find one that exists
|
||||||
|
for (const possiblePath of possiblePaths) {
|
||||||
|
try {
|
||||||
|
const exists = await this.pathUtils.fileExists(possiblePath);
|
||||||
|
if (exists) {
|
||||||
|
return possiblePath;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// File doesn't exist, continue to next path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve file path using Obsidian's link resolution API and filesystem fallbacks
|
||||||
|
*/
|
||||||
|
private async resolveFilePath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise<string | null> {
|
||||||
|
// Decode the URL-encoded sanitized path back to normal characters
|
||||||
|
const decodedPath = decodeURIComponent(sanitizedPath);
|
||||||
|
|
||||||
|
// Strategy 1: Use Obsidian's link resolution API (primary strategy)
|
||||||
|
if (currentFile) {
|
||||||
|
const resolvedFile = this.plugin.app.metadataCache.getFirstLinkpathDest(
|
||||||
|
decodedPath,
|
||||||
|
currentFile.path
|
||||||
|
);
|
||||||
|
|
||||||
|
if (resolvedFile && resolvedFile instanceof TFile) {
|
||||||
|
// Convert to full filesystem path
|
||||||
|
const fullPath = path.resolve(vaultBasePath, resolvedFile.path);
|
||||||
|
try {
|
||||||
|
const exists = await this.pathUtils.fileExists(fullPath);
|
||||||
|
if (exists) {
|
||||||
|
return fullPath;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// File exists in metadata but not on filesystem, continue to fallbacks
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback strategies: Try filesystem-based resolution
|
||||||
|
const possiblePaths = [
|
||||||
|
// Strategy 2: Relative to vault root (standard Obsidian behavior)
|
||||||
|
path.resolve(vaultBasePath, decodedPath),
|
||||||
|
// Strategy 3: Relative to current file's directory (for local attachments)
|
||||||
|
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
|
||||||
|
// Strategy 4: Check in attachments folder (common pattern)
|
||||||
|
path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath))
|
||||||
|
].filter((p): p is string => p !== null);
|
||||||
|
|
||||||
|
// Try each possible path until we find one that exists
|
||||||
|
for (const possiblePath of possiblePaths) {
|
||||||
|
try {
|
||||||
|
const exists = await this.pathUtils.fileExists(possiblePath);
|
||||||
|
if (exists) {
|
||||||
|
return possiblePath;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// File doesn't exist, continue to next path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy converted PDF image to vault temp directory and get relative paths
|
||||||
|
* @param imagePath Path to the converted image
|
||||||
|
* @param pdfPath Path to the original PDF
|
||||||
|
* @param baseName Base name of the PDF
|
||||||
|
* @param vaultBasePath Base path of the vault
|
||||||
|
* @returns Object with relative paths for image and PDF
|
||||||
|
*/
|
||||||
|
private async copyImageToVaultTemp(
|
||||||
|
imagePath: string,
|
||||||
|
pdfPath: string,
|
||||||
|
baseName: string,
|
||||||
|
vaultBasePath: string
|
||||||
|
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
|
||||||
|
// Copy image to vault temp directory for access
|
||||||
|
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||||
|
await this.pathUtils.ensureDir(vaultTempImagesDir);
|
||||||
|
|
||||||
|
// Sanitize the basename for use in filename - replace problematic characters
|
||||||
|
const sanitizedBaseName = baseName
|
||||||
|
.replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore
|
||||||
|
.replace(/_{2,}/g, '_') // Collapse multiple underscores
|
||||||
|
.replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores
|
||||||
|
|
||||||
|
const imageFileName = `${sanitizedBaseName}_preview.png`;
|
||||||
|
const vaultImagePath = this.pathUtils.joinPath(vaultTempImagesDir, imageFileName);
|
||||||
|
|
||||||
|
// Copy file using vault adapter
|
||||||
|
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(imagePath);
|
||||||
|
await this.plugin.app.vault.adapter.writeBinary(vaultImagePath, sourceBuffer);
|
||||||
|
|
||||||
|
// Get relative paths from vault base
|
||||||
|
const relativeImagePath = path.relative(vaultBasePath, vaultImagePath);
|
||||||
|
const relativePdfPath = path.relative(vaultBasePath, pdfPath);
|
||||||
|
|
||||||
|
return { relativeImagePath, relativePdfPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
private generatePdfEmbedContent(
|
||||||
|
relativePdfPath: string,
|
||||||
|
baseName: string,
|
||||||
|
relativeImagePath?: string,
|
||||||
|
errorSuffix?: string,
|
||||||
|
embedPdfFiles: boolean = true
|
||||||
|
): string {
|
||||||
|
const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
|
||||||
|
|
||||||
|
const content = [];
|
||||||
|
|
||||||
|
// Always include image preview if available
|
||||||
|
if (relativeImagePath) {
|
||||||
|
content.push(``);
|
||||||
|
content.push('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only include PDF embedding and attachment note if embedPdfFiles is true
|
||||||
|
if (embedPdfFiles) {
|
||||||
|
content.push('```{=typst}');
|
||||||
|
content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`);
|
||||||
|
content.push('```');
|
||||||
|
content.push('');
|
||||||
|
content.push(`*PDF attached: ${description} - check your PDF reader's attachment panel*`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return content.filter(line => line !== null).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate file embed content with proper Typst pdf.embed syntax
|
||||||
|
*/
|
||||||
|
private generateFileEmbedContent(
|
||||||
|
relativeFilePath: string,
|
||||||
|
baseName: string,
|
||||||
|
fileExtension: string,
|
||||||
|
errorSuffix?: string
|
||||||
|
): string {
|
||||||
|
const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
|
||||||
|
const mimeType = this.getMimeTypeFromExtension(fileExtension);
|
||||||
|
const fileIcon = this.getFileTypeIcon(fileExtension);
|
||||||
|
|
||||||
|
const content = [];
|
||||||
|
|
||||||
|
// Add file embed using Typst's pdf.embed
|
||||||
|
content.push('```{=typst}');
|
||||||
|
content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`);
|
||||||
|
content.push('```');
|
||||||
|
content.push('');
|
||||||
|
content.push(`*File attached: ${fileIcon} ${description} - check your PDF reader's attachment panel*`);
|
||||||
|
|
||||||
|
return content.filter(line => line !== null).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get MIME type from file extension
|
||||||
|
*/
|
||||||
|
private getMimeTypeFromExtension(extension: string): string {
|
||||||
|
const mimeTypes: Record<string, string> = {
|
||||||
|
// Office documents
|
||||||
|
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
'.xls': 'application/vnd.ms-excel',
|
||||||
|
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||||
|
'.ppt': 'application/vnd.ms-powerpoint',
|
||||||
|
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||||
|
'.doc': 'application/msword',
|
||||||
|
// Open Document Format
|
||||||
|
'.odt': 'application/vnd.oasis.opendocument.text',
|
||||||
|
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
|
||||||
|
'.odp': 'application/vnd.oasis.opendocument.presentation',
|
||||||
|
// Archives
|
||||||
|
'.zip': 'application/zip',
|
||||||
|
'.rar': 'application/vnd.rar',
|
||||||
|
'.7z': 'application/x-7z-compressed',
|
||||||
|
'.tar': 'application/x-tar',
|
||||||
|
'.gz': 'application/gzip',
|
||||||
|
'.bz2': 'application/x-bzip2',
|
||||||
|
// Text/data formats
|
||||||
|
'.json': 'application/json',
|
||||||
|
'.xml': 'application/xml',
|
||||||
|
'.csv': 'text/csv',
|
||||||
|
'.yaml': 'text/yaml',
|
||||||
|
'.yml': 'text/yaml',
|
||||||
|
'.toml': 'text/plain',
|
||||||
|
'.txt': 'text/plain',
|
||||||
|
'.md': 'text/markdown',
|
||||||
|
'.rtf': 'application/rtf',
|
||||||
|
// Code files
|
||||||
|
'.js': 'text/javascript',
|
||||||
|
'.ts': 'text/typescript',
|
||||||
|
'.py': 'text/x-python',
|
||||||
|
'.java': 'text/x-java-source',
|
||||||
|
'.cpp': 'text/x-c++src',
|
||||||
|
'.c': 'text/x-csrc',
|
||||||
|
'.h': 'text/x-chdr',
|
||||||
|
'.css': 'text/css',
|
||||||
|
'.html': 'text/html',
|
||||||
|
'.php': 'text/x-php',
|
||||||
|
// Database files
|
||||||
|
'.db': 'application/x-sqlite3',
|
||||||
|
'.sqlite': 'application/x-sqlite3',
|
||||||
|
'.sql': 'application/sql',
|
||||||
|
// E-books
|
||||||
|
'.epub': 'application/epub+zip',
|
||||||
|
'.mobi': 'application/x-mobipocket-ebook',
|
||||||
|
// Other formats
|
||||||
|
'.ics': 'text/calendar',
|
||||||
|
'.vcf': 'text/vcard',
|
||||||
|
'.log': 'text/plain'
|
||||||
|
};
|
||||||
|
|
||||||
|
return mimeTypes[extension.toLowerCase()] || 'application/octet-stream';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get appropriate icon for file type
|
||||||
|
*/
|
||||||
|
private getFileTypeIcon(extension: string): string {
|
||||||
|
const iconMap: Record<string, string> = {
|
||||||
|
// Office documents
|
||||||
|
'.xlsx': '📊', '.xls': '📊',
|
||||||
|
'.pptx': '📽️', '.ppt': '📽️',
|
||||||
|
'.docx': '📄', '.doc': '📄',
|
||||||
|
// Open Document
|
||||||
|
'.odt': '📄', '.ods': '📊', '.odp': '📽️',
|
||||||
|
// Archives
|
||||||
|
'.zip': '📦', '.rar': '📦', '.7z': '📦', '.tar': '📦', '.gz': '📦', '.bz2': '📦',
|
||||||
|
// Text/data
|
||||||
|
'.json': '🗃️', '.xml': '🗃️', '.csv': '📊', '.yaml': '⚙️', '.yml': '⚙️',
|
||||||
|
'.toml': '⚙️', '.txt': '📄', '.md': '📝', '.rtf': '📄',
|
||||||
|
// Code files
|
||||||
|
'.js': '💻', '.ts': '💻', '.py': '🐍', '.java': '☕', '.cpp': '💻', '.c': '💻',
|
||||||
|
'.h': '💻', '.css': '🎨', '.html': '🌐', '.php': '💻',
|
||||||
|
// Database
|
||||||
|
'.db': '🗄️', '.sqlite': '🗄️', '.sql': '🗄️',
|
||||||
|
// E-books
|
||||||
|
'.epub': '📖', '.mobi': '📖',
|
||||||
|
// Other
|
||||||
|
'.ics': '📅', '.vcf': '👤', '.log': '📋'
|
||||||
|
};
|
||||||
|
|
||||||
|
return iconMap[extension.toLowerCase()] || '📎';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/**
|
||||||
|
* Event Handler Registration
|
||||||
|
* Handles registration of all plugin event handlers and menu items
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Menu, Editor, MarkdownView, TFile, TAbstractFile } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
|
||||||
|
export class EventHandlers {
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register all plugin event handlers
|
||||||
|
*/
|
||||||
|
registerEventHandlers(): void {
|
||||||
|
// Add context menu item
|
||||||
|
this.plugin.registerEvent(
|
||||||
|
this.plugin.app.workspace.on('file-menu', (menu: Menu, file: TFile) => {
|
||||||
|
if (file.extension === 'md') {
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle('Export to PDF (Typst)')
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportFile(file);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add editor menu item
|
||||||
|
this.plugin.registerEvent(
|
||||||
|
this.plugin.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => {
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle('Export to PDF (Typst)')
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportCurrentNote(view);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add multi-file menu item (for multiple selected files in file explorer)
|
||||||
|
this.plugin.registerEvent(
|
||||||
|
this.plugin.app.workspace.on('files-menu', (menu: Menu, files: TAbstractFile[]) => {
|
||||||
|
// Filter for markdown files only
|
||||||
|
const markdownFiles = files.filter(this.plugin.isMarkdownFile);
|
||||||
|
|
||||||
|
if (markdownFiles.length > 0) {
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle(`Export to PDF (Typst)`)
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportFiles(markdownFiles);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle(`Export with configuration...`)
|
||||||
|
.setIcon('settings')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.showExportModalForFiles(markdownFiles);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle ribbon icon click
|
||||||
|
*/
|
||||||
|
handleRibbonClick(event: MouseEvent): void {
|
||||||
|
const activeView = this.plugin.app.workspace.getActiveViewOfType(MarkdownView);
|
||||||
|
|
||||||
|
if (!activeView || !activeView.file) {
|
||||||
|
ExportErrorHandler.showFileNotFoundWarning('markdown');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create context menu for ribbon click
|
||||||
|
const menu = new Menu();
|
||||||
|
|
||||||
|
menu.addItem((item) =>
|
||||||
|
item
|
||||||
|
.setTitle('Export current note(s)')
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportFile(activeView.file!);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
menu.addItem((item) =>
|
||||||
|
item
|
||||||
|
.setTitle('Export with configuration…')
|
||||||
|
.setIcon('settings')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.showExportModal(activeView);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
menu.showAtMouseEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
/**
|
||||||
|
* Export Orchestration
|
||||||
|
* Handles the coordination and execution of all export workflows
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { TFile, TFolder, Notice, MarkdownView } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { ExportConfig } from '../ui/modal/modalTypes';
|
||||||
|
import { ExportConfigModal } from '../ui/modal/ExportConfigModal';
|
||||||
|
import { ModalSettingsHelper } from '../core/ModalSettingsHelper';
|
||||||
|
import { MarkdownPreprocessor } from '../converters/MarkdownPreprocessor';
|
||||||
|
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
|
||||||
|
export class ExportOrchestrator {
|
||||||
|
private readonly pathUtils: PathUtils;
|
||||||
|
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export a file with default configuration
|
||||||
|
*/
|
||||||
|
async exportFile(file: TFile): Promise<void> {
|
||||||
|
const config: ExportConfig = {
|
||||||
|
template: this.plugin.settings.exportDefaults.template,
|
||||||
|
format: this.plugin.settings.exportDefaults.format,
|
||||||
|
outputFolder: this.plugin.settings.outputFolder,
|
||||||
|
templateVariables: {
|
||||||
|
// Page setup - use NEW settings structure (same as modal)
|
||||||
|
pageSize: this.plugin.settings.pageSetup.size,
|
||||||
|
orientation: this.plugin.settings.pageSetup.orientation,
|
||||||
|
flipped: this.plugin.settings.pageSetup.orientation === 'landscape',
|
||||||
|
marginTop: this.plugin.settings.pageSetup.margins.top.toString(),
|
||||||
|
marginBottom: this.plugin.settings.pageSetup.margins.bottom.toString(),
|
||||||
|
marginLeft: this.plugin.settings.pageSetup.margins.left.toString(),
|
||||||
|
marginRight: this.plugin.settings.pageSetup.margins.right.toString(),
|
||||||
|
// Typography - use NEW settings structure (same as modal)
|
||||||
|
bodyFont: this.plugin.settings.typography.fonts.body,
|
||||||
|
headingFont: this.plugin.settings.typography.fonts.heading,
|
||||||
|
monospaceFont: this.plugin.settings.typography.fonts.monospace,
|
||||||
|
bodyFontSize: this.plugin.settings.typography.fontSizes.body
|
||||||
|
},
|
||||||
|
openAfterExport: this.plugin.settings.behavior.openAfterExport,
|
||||||
|
preserveFolderStructure: this.plugin.settings.behavior.preserveFolderStructure
|
||||||
|
};
|
||||||
|
|
||||||
|
await this.exportFileWithConfig(file, config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export multiple files with default configuration
|
||||||
|
*/
|
||||||
|
async exportFiles(files: TFile[]): Promise<void> {
|
||||||
|
await this.processBatchExport(
|
||||||
|
files,
|
||||||
|
`Exporting ${files.length} files to PDF...`,
|
||||||
|
(file: TFile) => this.exportFile(file)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the export configuration modal
|
||||||
|
*/
|
||||||
|
async showExportModal(view: MarkdownView): Promise<void> {
|
||||||
|
const file = view.file;
|
||||||
|
if (!file) {
|
||||||
|
ExportErrorHandler.showFileNotFoundWarning('markdown');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get available templates first
|
||||||
|
const availableTemplates = await this.plugin.templateManager.getAvailableTemplates();
|
||||||
|
|
||||||
|
// Prepare modal settings using helper
|
||||||
|
const modalSettings = ModalSettingsHelper.prepareForSingleFile(
|
||||||
|
file,
|
||||||
|
availableTemplates,
|
||||||
|
this.plugin.settings
|
||||||
|
);
|
||||||
|
|
||||||
|
// Show modal - ModalState will handle localStorage hierarchy automatically
|
||||||
|
const modal = new ExportConfigModal(
|
||||||
|
this.plugin.app,
|
||||||
|
this.plugin,
|
||||||
|
modalSettings,
|
||||||
|
async (config: ExportConfig) => {
|
||||||
|
await this.exportFileWithConfig(file, config);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
this.cancelExport();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
modal.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the export configuration modal for multiple files
|
||||||
|
*/
|
||||||
|
async showExportModalForFiles(files: TFile[]): Promise<void> {
|
||||||
|
if (files.length === 0) {
|
||||||
|
ExportErrorHandler.showNoFilesWarning();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get available templates first
|
||||||
|
const availableTemplates = await this.plugin.templateManager.getAvailableTemplates();
|
||||||
|
|
||||||
|
// Prepare modal settings using helper
|
||||||
|
const modalSettings = ModalSettingsHelper.prepareForMultiFile(
|
||||||
|
files,
|
||||||
|
availableTemplates,
|
||||||
|
this.plugin.settings
|
||||||
|
);
|
||||||
|
|
||||||
|
// Show modal - ModalState will handle localStorage hierarchy automatically
|
||||||
|
const modal = new ExportConfigModal(
|
||||||
|
this.plugin.app,
|
||||||
|
this.plugin,
|
||||||
|
modalSettings,
|
||||||
|
async (config: ExportConfig) => {
|
||||||
|
await this.exportFilesWithConfig(files, config);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
this.cancelExport();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
modal.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export a file with specific configuration
|
||||||
|
*/
|
||||||
|
async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
|
||||||
|
|
||||||
|
// Create controller for this export (allows cancellation)
|
||||||
|
this.plugin.currentExportController = new AbortController();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create temp directory for conversion
|
||||||
|
const tempManager = new TempDirectoryManager({
|
||||||
|
vaultPath: vaultPath,
|
||||||
|
configDir: this.plugin.app.vault.configDir,
|
||||||
|
app: this.plugin.app,
|
||||||
|
pluginName: this.plugin.manifest.id
|
||||||
|
});
|
||||||
|
const tempDir = await tempManager.ensureTempDir('pandoc');
|
||||||
|
|
||||||
|
// Load file content
|
||||||
|
const content = await this.plugin.app.vault.read(file);
|
||||||
|
|
||||||
|
// Create progress notice with cancel button
|
||||||
|
const progressNotice = new Notice('', 0);
|
||||||
|
const cancelButton = progressNotice.noticeEl.createEl('button', {
|
||||||
|
text: 'Cancel',
|
||||||
|
cls: 'mod-warning'
|
||||||
|
});
|
||||||
|
cancelButton.addEventListener('click', () => this.cancelExport());
|
||||||
|
progressNotice.setMessage('Preprocessing markdown content...');
|
||||||
|
|
||||||
|
// Preprocess markdown
|
||||||
|
const preprocessor = new MarkdownPreprocessor({
|
||||||
|
vaultPath: vaultPath,
|
||||||
|
options: {
|
||||||
|
preserveFrontmatter: config.printFrontmatter ?? this.plugin.settings.behavior.printFrontmatter,
|
||||||
|
baseUrl: undefined,
|
||||||
|
printFrontmatter: config.printFrontmatter ?? this.plugin.settings.behavior.printFrontmatter
|
||||||
|
},
|
||||||
|
wikilinkConfig: {
|
||||||
|
format: 'md',
|
||||||
|
extension: '.md'
|
||||||
|
},
|
||||||
|
noteTitle: file.basename
|
||||||
|
});
|
||||||
|
|
||||||
|
const processedResult = await preprocessor.process(content);
|
||||||
|
|
||||||
|
if (processedResult.errors.length > 0) {
|
||||||
|
console.warn('Preprocessing errors:', processedResult.errors);
|
||||||
|
}
|
||||||
|
if (processedResult.warnings.length > 0) {
|
||||||
|
console.warn('Preprocessing warnings:', processedResult.warnings);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process PDF embeds if any were found
|
||||||
|
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
|
||||||
|
const embedPdfFiles = config.embedPdfFiles ?? this.plugin.settings.behavior.embedPdfFiles;
|
||||||
|
await this.plugin.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process image embeds if any were found
|
||||||
|
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
|
||||||
|
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempDir, file);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process file embeds if any were found
|
||||||
|
if (processedResult.metadata.fileEmbeds && processedResult.metadata.fileEmbeds.length > 0) {
|
||||||
|
const embedAllFiles = config.embedAllFiles ?? this.plugin.settings.behavior.embedAllFiles;
|
||||||
|
await this.plugin.processFileEmbeds(processedResult, vaultPath, tempDir, file, embedAllFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare output path
|
||||||
|
const outputPath = await this.plugin.prepareOutputPath(file, config.outputFolder || this.plugin.settings.outputFolder);
|
||||||
|
|
||||||
|
// Get full template path
|
||||||
|
const templatePath = config.template ?
|
||||||
|
this.plugin.templateManager.getTemplatePath(config.template) :
|
||||||
|
this.plugin.templateManager.getTemplatePath('default.typ');
|
||||||
|
|
||||||
|
// Convert to PDF using the preprocessed content
|
||||||
|
const templateVariables = {
|
||||||
|
...(config.templateVariables || {}),
|
||||||
|
// Add format from config if specified (takes priority over settings default)
|
||||||
|
...(config.format && { export_format: config.format })
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await this.plugin.converter.convertMarkdownToPDF(
|
||||||
|
processedResult.content, // Use preprocessed content instead of raw content
|
||||||
|
outputPath,
|
||||||
|
{
|
||||||
|
template: templatePath,
|
||||||
|
variables: templateVariables,
|
||||||
|
pluginDir: pluginDir,
|
||||||
|
vaultBasePath: vaultPath
|
||||||
|
},
|
||||||
|
(message: string, progress?: number) => {
|
||||||
|
progressNotice.setMessage(`${message}${progress ? ` (${Math.round(progress)}%)` : ''}`);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Hide progress notice
|
||||||
|
progressNotice.hide();
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
ExportErrorHandler.showExportSuccess(result.outputPath!);
|
||||||
|
|
||||||
|
// Open PDF if configured
|
||||||
|
if (this.plugin.settings.behavior.openAfterExport) {
|
||||||
|
this.plugin.openPDF(result.outputPath!);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ExportErrorHandler.handleSingleExportError(result.error!);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ExportErrorHandler.handleSingleExportError(error);
|
||||||
|
} finally {
|
||||||
|
this.plugin.currentExportController = null;
|
||||||
|
|
||||||
|
// Clean up temporary directories
|
||||||
|
try {
|
||||||
|
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, this.plugin.manifest.id, this.plugin.app);
|
||||||
|
await cleanupManager.cleanupAllTempDirs();
|
||||||
|
} catch (cleanupError) {
|
||||||
|
console.warn('Export: Failed to clean up temporary directories:', cleanupError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export multiple files with specific configuration
|
||||||
|
*/
|
||||||
|
async exportFilesWithConfig(files: TFile[], config: ExportConfig): Promise<void> {
|
||||||
|
await this.processBatchExport(
|
||||||
|
files,
|
||||||
|
`Exporting ${files.length} files with custom configuration...`,
|
||||||
|
(file: TFile) => this.exportFileWithConfig(file, config)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common batch processing logic for exporting multiple files
|
||||||
|
*/
|
||||||
|
async processBatchExport(
|
||||||
|
files: TFile[],
|
||||||
|
progressMessage: string,
|
||||||
|
exportFunction: (file: TFile) => Promise<void>
|
||||||
|
): Promise<void> {
|
||||||
|
if (files.length === 0) {
|
||||||
|
ExportErrorHandler.showNoFilesWarning();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ExportErrorHandler.showProgressNotice(progressMessage);
|
||||||
|
|
||||||
|
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
await exportFunction(file);
|
||||||
|
recordSuccess();
|
||||||
|
} catch (error) {
|
||||||
|
recordError(file.name, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show final result
|
||||||
|
ExportErrorHandler.handleBatchResult(getResult());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancel the current export
|
||||||
|
*/
|
||||||
|
cancelExport(): void {
|
||||||
|
if (this.plugin.currentExportController) {
|
||||||
|
this.plugin.currentExportController.abort();
|
||||||
|
this.plugin.currentExportController = null;
|
||||||
|
ExportErrorHandler.showCancellationNotice();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export an entire folder to PDF
|
||||||
|
*/
|
||||||
|
async handleFolderExport(folder: TFolder): Promise<void> {
|
||||||
|
// Get all markdown files in the folder
|
||||||
|
const markdownFiles = folder.children.filter(this.plugin.isMarkdownFile);
|
||||||
|
|
||||||
|
if (markdownFiles.length === 0) {
|
||||||
|
new Notice('No markdown files found in this folder');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ExportErrorHandler.showProgressNotice(`Exporting ${markdownFiles.length} files from ${folder.name}...`);
|
||||||
|
|
||||||
|
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
|
||||||
|
|
||||||
|
for (const file of markdownFiles) {
|
||||||
|
try {
|
||||||
|
await this.exportFile(file);
|
||||||
|
recordSuccess();
|
||||||
|
} catch (error) {
|
||||||
|
recordError(file.name, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ExportErrorHandler.handleBatchResult(getResult());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
/**
|
||||||
|
* Font Management
|
||||||
|
* Handles font discovery, caching, and retrieval for the plugin
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
import { FALLBACK_FONTS } from '../core/constants';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
|
||||||
|
export class FontManager {
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache available fonts from typst to a file for quick access
|
||||||
|
*/
|
||||||
|
async cacheAvailableFonts(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
const typstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
|
||||||
|
|
||||||
|
// Use spawn instead of exec for security - arguments passed separately
|
||||||
|
const stdout = await new Promise<string>((resolve, reject) => {
|
||||||
|
// Build platform-specific environment with enhanced PATH
|
||||||
|
const pathValue = this.buildPlatformSpecificPATH();
|
||||||
|
const enhancedEnv = {
|
||||||
|
...process.env,
|
||||||
|
PATH: pathValue,
|
||||||
|
Path: pathValue
|
||||||
|
};
|
||||||
|
|
||||||
|
const typstProcess = spawn(typstPath, ['fonts'], {
|
||||||
|
stdio: ['pipe', 'pipe', 'pipe'],
|
||||||
|
env: enhancedEnv
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
let error = '';
|
||||||
|
|
||||||
|
typstProcess.stdout?.on('data', (data: Buffer) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
error += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.on('close', (code: number | null) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve(output);
|
||||||
|
} else {
|
||||||
|
reject(new Error(`typst fonts command failed with code ${code}: ${error}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
typstProcess.on('error', (err: Error) => {
|
||||||
|
reject(new Error(`Failed to spawn typst process: ${err.message}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const fonts = stdout
|
||||||
|
.split('\n')
|
||||||
|
.map((line: string) => line.trim())
|
||||||
|
.filter((line: string) => line.length > 0)
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
// Write fonts to cache file in plugin data directory
|
||||||
|
const cacheData = {
|
||||||
|
fonts: fonts,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
typstPath: typstPath,
|
||||||
|
platform: process.platform
|
||||||
|
};
|
||||||
|
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||||
|
// Use vault-relative path for adapter operations
|
||||||
|
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||||
|
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||||
|
JSON.stringify(cacheData, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to cache fonts from typst:', error);
|
||||||
|
|
||||||
|
// Notify user of font caching failure (only if debug mode is enabled or if it's a critical error)
|
||||||
|
ExportErrorHandler.showFontError(error, !this.plugin.settings.behavior.debugMode);
|
||||||
|
|
||||||
|
// Create fallback cache file
|
||||||
|
const fallbackFonts = FALLBACK_FONTS;
|
||||||
|
|
||||||
|
const cacheData = {
|
||||||
|
fonts: fallbackFonts,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
typstPath: 'fallback',
|
||||||
|
platform: process.platform,
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
};
|
||||||
|
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||||
|
// Use vault-relative path for adapter operations
|
||||||
|
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||||
|
await this.plugin.app.vault.adapter.write(fontsCachePath,
|
||||||
|
JSON.stringify(cacheData, null, 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get cached fonts list with improved validation and error recovery
|
||||||
|
*/
|
||||||
|
async getCachedFonts(): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const pluginDir = pathUtils.getPluginDir(this.plugin.manifest);
|
||||||
|
// Use vault-relative path for adapter operations
|
||||||
|
const fontsCachePath = pathUtils.joinPath(pluginDir, 'fonts-cache.json');
|
||||||
|
const cacheContent = await this.plugin.app.vault.adapter.read(fontsCachePath);
|
||||||
|
|
||||||
|
let cacheData;
|
||||||
|
try {
|
||||||
|
cacheData = JSON.parse(cacheContent);
|
||||||
|
} catch (parseError) {
|
||||||
|
console.error('Corrupted fonts cache file, regenerating:', parseError);
|
||||||
|
// Remove corrupted cache and regenerate
|
||||||
|
await this.plugin.app.vault.adapter.remove(fontsCachePath);
|
||||||
|
await this.cacheAvailableFonts();
|
||||||
|
return [...FALLBACK_FONTS];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate cache structure
|
||||||
|
if (!cacheData || typeof cacheData !== 'object' || !Array.isArray(cacheData.fonts)) {
|
||||||
|
console.warn('Invalid fonts cache structure, regenerating');
|
||||||
|
await this.plugin.app.vault.adapter.remove(fontsCachePath);
|
||||||
|
await this.cacheAvailableFonts();
|
||||||
|
return [...FALLBACK_FONTS];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if cache needs refresh
|
||||||
|
const isStale = Date.now() - (cacheData.timestamp || 0) > 24 * 60 * 60 * 1000;
|
||||||
|
const resolvedTypstPath = this.plugin.resolveExecutablePath(this.plugin.settings.typstPath, 'typst');
|
||||||
|
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
|
||||||
|
const platformChanged = cacheData.platform !== process.platform;
|
||||||
|
|
||||||
|
if (isStale || pathChanged || platformChanged) {
|
||||||
|
// Refresh cache in background
|
||||||
|
this.cacheAvailableFonts().catch(error => {
|
||||||
|
console.error('Background font cache refresh failed:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate fonts array contains valid strings
|
||||||
|
const validFonts = cacheData.fonts.filter((font: unknown) =>
|
||||||
|
typeof font === 'string' && font.trim().length > 0
|
||||||
|
);
|
||||||
|
|
||||||
|
return validFonts.length > 0 ? validFonts : [...FALLBACK_FONTS];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to read fonts cache:', error);
|
||||||
|
// Try to recreate cache
|
||||||
|
this.cacheAvailableFonts().catch(cacheError => {
|
||||||
|
console.error('Failed to recreate fonts cache:', cacheError);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return fallback fonts
|
||||||
|
return [...FALLBACK_FONTS];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get available fonts (wrapper for cached fonts)
|
||||||
|
*/
|
||||||
|
async getAvailableFonts(): Promise<string[]> {
|
||||||
|
return await this.getCachedFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build platform-specific PATH environment variable for font discovery
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private buildPlatformSpecificPATH(): string {
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const pathSeparator = process.platform === 'win32' ? ';' : ':';
|
||||||
|
|
||||||
|
// Helper function to expand tilde paths
|
||||||
|
const expandTildePath = (path: string): string => {
|
||||||
|
if (path.startsWith('~')) {
|
||||||
|
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
||||||
|
return path.replace('~', homeDir);
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Platform-specific common installation paths
|
||||||
|
let additionalPaths: string[] = [];
|
||||||
|
|
||||||
|
switch (process.platform) {
|
||||||
|
case 'darwin': // macOS
|
||||||
|
additionalPaths = [
|
||||||
|
'/opt/homebrew/bin',
|
||||||
|
'/usr/local/bin',
|
||||||
|
'/usr/bin',
|
||||||
|
'/bin',
|
||||||
|
'/opt/local/bin', // MacPorts
|
||||||
|
'/sw/bin' // Fink
|
||||||
|
];
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'linux':
|
||||||
|
additionalPaths = [
|
||||||
|
'/usr/local/bin',
|
||||||
|
'/usr/bin',
|
||||||
|
'/bin',
|
||||||
|
'/opt/bin',
|
||||||
|
'/snap/bin', // Snap packages
|
||||||
|
'~/.cargo/bin', // Rust/Cargo installations
|
||||||
|
'~/.local/bin' // User local installations
|
||||||
|
];
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'win32': // Windows
|
||||||
|
additionalPaths = [
|
||||||
|
'C:\\Program Files\\Typst',
|
||||||
|
'C:\\Program Files (x86)\\Typst',
|
||||||
|
process.env.LOCALAPPDATA ? `${process.env.LOCALAPPDATA}\\Programs\\Typst` : '',
|
||||||
|
process.env.APPDATA ? `${process.env.APPDATA}\\Typst` : '',
|
||||||
|
'C:\\tools\\typst', // Chocolatey common path
|
||||||
|
process.env.USERPROFILE ? `${process.env.USERPROFILE}\\.cargo\\bin` : ''
|
||||||
|
].filter(path => path.length > 0);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// Fallback for other platforms
|
||||||
|
additionalPaths = ['/usr/local/bin', '/usr/bin', '/bin'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expand tilde paths and filter empty strings
|
||||||
|
const expandedPaths = additionalPaths
|
||||||
|
.map(expandTildePath)
|
||||||
|
.filter(path => path.length > 0);
|
||||||
|
|
||||||
|
// Split current PATH and combine with additional paths
|
||||||
|
const currentPaths = currentPath.split(pathSeparator).filter(path => path.length > 0);
|
||||||
|
const allPaths = [...expandedPaths, ...currentPaths];
|
||||||
|
|
||||||
|
// Remove duplicates while preserving order
|
||||||
|
const uniquePaths = [...new Set(allPaths)];
|
||||||
|
|
||||||
|
return uniquePaths.join(pathSeparator);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/**
|
||||||
|
* Path Resolution Utilities
|
||||||
|
* Handles executable path resolution and output path preparation
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { TFile } from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { SecurityUtils } from '../core/SecurityUtils';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
export class PathResolver {
|
||||||
|
private readonly pathUtils: PathUtils;
|
||||||
|
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve an executable path, handling empty settings by falling back to system search
|
||||||
|
*/
|
||||||
|
resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
|
||||||
|
// If user provided a path and it's not empty, use it
|
||||||
|
if (userPath && userPath.trim() !== '') {
|
||||||
|
return userPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find the executable using which command
|
||||||
|
const { spawnSync } = require('child_process');
|
||||||
|
try {
|
||||||
|
const augmentedEnv = {
|
||||||
|
...process.env,
|
||||||
|
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = spawnSync('which', [defaultName], {
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: augmentedEnv
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.status === 0 && result.stdout) {
|
||||||
|
const foundPath = result.stdout.trim();
|
||||||
|
if (foundPath) {
|
||||||
|
return foundPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore errors from which command
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to the default name (will be found via PATH if available)
|
||||||
|
return defaultName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare the output path for a file
|
||||||
|
*/
|
||||||
|
async prepareOutputPath(file: TFile, outputFolder: string): Promise<string> {
|
||||||
|
// Validate output folder for security
|
||||||
|
if (!SecurityUtils.validateOutputPath(outputFolder)) {
|
||||||
|
throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const outputDir = this.pathUtils.joinPath(vaultPath, outputFolder);
|
||||||
|
|
||||||
|
// Create output directory if it doesn't exist
|
||||||
|
await this.pathUtils.ensureDir(outputDir);
|
||||||
|
|
||||||
|
// Preserve folder structure if configured
|
||||||
|
let relativePath = '';
|
||||||
|
if (this.plugin.settings.behavior.preserveFolderStructure) {
|
||||||
|
const folderPath = path.dirname(file.path);
|
||||||
|
if (folderPath !== '.') {
|
||||||
|
relativePath = folderPath;
|
||||||
|
const fullOutputDir = this.pathUtils.joinPath(outputDir, relativePath);
|
||||||
|
await this.pathUtils.ensureDir(fullOutputDir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate output filename (just use the note name without timestamp)
|
||||||
|
const baseName = file.basename;
|
||||||
|
const outputFileName = `${baseName}.pdf`;
|
||||||
|
|
||||||
|
return this.pathUtils.joinPath(outputDir, relativePath, outputFileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/**
|
||||||
|
* Plugin Lifecycle Management
|
||||||
|
* Handles plugin loading, unloading, initialization, and cleanup
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
import { PandocTypstConverter } from '../converters/PandocTypstConverter';
|
||||||
|
import { TemplateManager } from '../templates/TemplateManager';
|
||||||
|
import { EmbeddedTemplateManager } from '../templates/embeddedTemplates';
|
||||||
|
import { TempDirectoryManager } from '../core/TempDirectoryManager';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
|
|
||||||
|
export class PluginLifecycle {
|
||||||
|
private readonly pathUtils: PathUtils;
|
||||||
|
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the plugin during onload
|
||||||
|
*/
|
||||||
|
async initialize(): Promise<void> {
|
||||||
|
// Load settings first
|
||||||
|
await this.plugin.loadSettings();
|
||||||
|
|
||||||
|
// Initialize embedded template manager
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const pluginDir = this.pathUtils.joinPath(vaultPath, this.pathUtils.getPluginDir(this.plugin.manifest));
|
||||||
|
this.plugin.embeddedTemplateManager = new EmbeddedTemplateManager(pluginDir, this.plugin.app);
|
||||||
|
|
||||||
|
// Extract any missing templates from embedded data
|
||||||
|
try {
|
||||||
|
const extractionResult = await this.plugin.embeddedTemplateManager.extractAllMissingTemplates();
|
||||||
|
if (extractionResult.failed.length > 0) {
|
||||||
|
console.warn(`Failed to extract ${extractionResult.failed.length} templates:`, extractionResult.failed);
|
||||||
|
ExportErrorHandler.showTemplateError(`Failed to extract some templates. Plugin may not work correctly.`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error during template extraction:', error);
|
||||||
|
ExportErrorHandler.showTemplateError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize components with executable paths from settings
|
||||||
|
this.plugin.converter = new PandocTypstConverter(this.plugin, {
|
||||||
|
pandocPath: this.plugin.settings.pandocPath,
|
||||||
|
typstPath: this.plugin.settings.typstPath
|
||||||
|
});
|
||||||
|
this.plugin.templateManager = new TemplateManager(this.plugin);
|
||||||
|
|
||||||
|
// Clean up any leftover temp directories from previous sessions
|
||||||
|
this.cleanupStartupTempDirectories();
|
||||||
|
|
||||||
|
// Check dependencies on startup (async, don't await)
|
||||||
|
this.plugin.checkDependenciesAsync();
|
||||||
|
|
||||||
|
// Cache available fonts (async, don't await)
|
||||||
|
this.plugin.cacheAvailableFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean up resources during onunload
|
||||||
|
*/
|
||||||
|
cleanup(): void {
|
||||||
|
// Cancel any ongoing exports
|
||||||
|
if (this.plugin.currentExportController) {
|
||||||
|
this.plugin.currentExportController.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up temp directories on plugin unload (fire-and-forget async)
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||||
|
await cleanupManager.cleanupAllTempDirs();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Export: Failed to clean up temp directories during unload:', error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean up leftover temp directories from previous sessions
|
||||||
|
*/
|
||||||
|
private cleanupStartupTempDirectories(): void {
|
||||||
|
// Clean up temp directories (fire-and-forget async)
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||||
|
const _result = await cleanupManager.cleanupAllTempDirs();
|
||||||
|
|
||||||
|
if (this.plugin.settings.behavior.debugMode) {
|
||||||
|
// Debug logging was here but empty in original
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Export: Startup temp directory cleanup failed (non-critical):', error);
|
||||||
|
// Don't throw - this shouldn't prevent plugin from loading
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
/**
|
||||||
|
* Settings Tab
|
||||||
|
* Handles the plugin settings UI interface
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
App,
|
||||||
|
PluginSettingTab,
|
||||||
|
Setting,
|
||||||
|
normalizePath
|
||||||
|
} from 'obsidian';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { ExportFormat } from '../core/settings';
|
||||||
|
import { SecurityUtils } from '../core/SecurityUtils';
|
||||||
|
import { ExportErrorHandler } from '../core/ExportErrorHandler';
|
||||||
|
import { FolderSuggest } from '../ui/components/FolderSuggest';
|
||||||
|
import { SUPPORTED_PAPER_SIZES } from '../utils/paperSizeMapper';
|
||||||
|
|
||||||
|
export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
||||||
|
plugin: obsidianTypstPDFExport;
|
||||||
|
|
||||||
|
constructor(app: App, plugin: obsidianTypstPDFExport) {
|
||||||
|
super(app, plugin);
|
||||||
|
this.plugin = plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
display(): void {
|
||||||
|
const { containerEl } = this;
|
||||||
|
containerEl.empty();
|
||||||
|
|
||||||
|
containerEl.createEl('h2', { text: 'Typst PDF Export Settings' });
|
||||||
|
|
||||||
|
// Executable paths section
|
||||||
|
this.createExecutablePathsSection(containerEl);
|
||||||
|
|
||||||
|
// Export defaults section
|
||||||
|
this.createExportDefaultsSection(containerEl);
|
||||||
|
|
||||||
|
// Typography defaults section
|
||||||
|
this.createTypographyDefaultsSection(containerEl);
|
||||||
|
|
||||||
|
// Page setup section
|
||||||
|
this.createPageSetupSection(containerEl);
|
||||||
|
|
||||||
|
// Behavior section
|
||||||
|
this.createBehaviorSection(containerEl);
|
||||||
|
}
|
||||||
|
|
||||||
|
private createExecutablePathsSection(containerEl: HTMLElement): void {
|
||||||
|
containerEl.createEl('h3', { text: 'Executable Paths' });
|
||||||
|
|
||||||
|
// Add dependency check button
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Dependencies')
|
||||||
|
.setDesc('Check the status of external dependencies')
|
||||||
|
.addButton(button => button
|
||||||
|
.setButtonText('Check Dependencies')
|
||||||
|
.setCta()
|
||||||
|
.onClick(async () => {
|
||||||
|
await this.plugin.showDependencyStatus();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Pandoc path')
|
||||||
|
.setDesc('Path to pandoc executable (leave empty to use system PATH)')
|
||||||
|
.addText(text => text
|
||||||
|
.setPlaceholder('pandoc')
|
||||||
|
.setValue(this.plugin.settings.pandocPath)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||||
|
ExportErrorHandler.showValidationError('Pandoc path', SecurityUtils.getExecutablePathValidationError(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.plugin.settings.pandocPath = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Typst path')
|
||||||
|
.setDesc('Path to typst executable (leave empty to use system PATH)')
|
||||||
|
.addText(text => text
|
||||||
|
.setPlaceholder('typst')
|
||||||
|
.setValue(this.plugin.settings.typstPath)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||||
|
ExportErrorHandler.showValidationError('Typst path', SecurityUtils.getExecutablePathValidationError(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.plugin.settings.typstPath = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('ImageMagick path')
|
||||||
|
.setDesc('Path to ImageMagick executable (leave empty to use system PATH)')
|
||||||
|
.addText(text => text
|
||||||
|
.setPlaceholder('magick')
|
||||||
|
.setValue(this.plugin.settings.executablePaths.imagemagickPath)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
if (!SecurityUtils.validateExecutablePath(value)) {
|
||||||
|
ExportErrorHandler.showValidationError('ImageMagick path', SecurityUtils.getExecutablePathValidationError(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.plugin.settings.executablePaths.imagemagickPath = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Additional system paths')
|
||||||
|
.setDesc('Additional paths to search for executables (comma-separated)')
|
||||||
|
.addText(text => text
|
||||||
|
.setPlaceholder('/opt/homebrew/bin, /usr/local/bin')
|
||||||
|
.setValue(this.plugin.settings.executablePaths.additionalPaths.join(', '))
|
||||||
|
.onChange(async (value) => {
|
||||||
|
const paths = value
|
||||||
|
.split(',')
|
||||||
|
.map(p => p.trim())
|
||||||
|
.filter(p => p.length > 0);
|
||||||
|
|
||||||
|
// Validate each path
|
||||||
|
for (const pathItem of paths) {
|
||||||
|
if (!SecurityUtils.validateExecutablePath(pathItem)) {
|
||||||
|
ExportErrorHandler.showValidationError('system path', SecurityUtils.getExecutablePathValidationError(pathItem));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.plugin.settings.executablePaths.additionalPaths = paths;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private createExportDefaultsSection(containerEl: HTMLElement): void {
|
||||||
|
containerEl.createEl('h3', { text: 'Export Defaults' });
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Default template')
|
||||||
|
.setDesc('Default Typst template for exports')
|
||||||
|
.addDropdown(async (dropdown) => {
|
||||||
|
try {
|
||||||
|
const templates = await this.plugin.templateManager.getAvailableTemplates();
|
||||||
|
// Filter out universal-wrapper.pandoc.typ as requested
|
||||||
|
const filteredTemplates = templates.filter(template =>
|
||||||
|
template !== 'universal-wrapper.pandoc.typ'
|
||||||
|
);
|
||||||
|
|
||||||
|
filteredTemplates.forEach(template => {
|
||||||
|
dropdown.addOption(template, template);
|
||||||
|
});
|
||||||
|
|
||||||
|
dropdown
|
||||||
|
.setValue(this.plugin.settings.exportDefaults.template)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.exportDefaults.template = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load templates:', error);
|
||||||
|
// Fallback to text input
|
||||||
|
dropdown.addOption('default.typ', 'default.typ');
|
||||||
|
dropdown.setValue(this.plugin.settings.exportDefaults.template);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Default format')
|
||||||
|
.setDesc('Default PDF format')
|
||||||
|
.addDropdown(dropdown => dropdown
|
||||||
|
.addOption(ExportFormat.Standard, 'Standard (multi-page)')
|
||||||
|
.addOption(ExportFormat.SinglePage, 'Single-page (continuous)')
|
||||||
|
.setValue(this.plugin.settings.exportDefaults.format)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.exportDefaults.format = value as ExportFormat;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Output folder')
|
||||||
|
.setDesc('Default folder for exported PDFs (relative to vault root)')
|
||||||
|
.addText(text => {
|
||||||
|
text
|
||||||
|
.setPlaceholder('exports')
|
||||||
|
.setValue(this.plugin.settings.outputFolder)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
const normalizedValue = normalizePath(value);
|
||||||
|
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
|
||||||
|
ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.plugin.settings.outputFolder = normalizedValue;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
});
|
||||||
|
|
||||||
|
new FolderSuggest(this.app, text.inputEl);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to create a font dropdown setting
|
||||||
|
*/
|
||||||
|
private createFontDropdown(
|
||||||
|
containerEl: HTMLElement,
|
||||||
|
name: string,
|
||||||
|
desc: string,
|
||||||
|
getCurrentValue: () => string,
|
||||||
|
setNewValue: (value: string) => void
|
||||||
|
): void {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName(name)
|
||||||
|
.setDesc(desc)
|
||||||
|
.addDropdown(async (dropdown) => {
|
||||||
|
try {
|
||||||
|
const fonts = await this.getAvailableFonts();
|
||||||
|
fonts.forEach(font => {
|
||||||
|
dropdown.addOption(font, font);
|
||||||
|
});
|
||||||
|
|
||||||
|
dropdown
|
||||||
|
.setValue(getCurrentValue())
|
||||||
|
.onChange(async (value) => {
|
||||||
|
setNewValue(value);
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load fonts:', error);
|
||||||
|
dropdown.addOption(getCurrentValue(), getCurrentValue());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private createTypographyDefaultsSection(containerEl: HTMLElement): void {
|
||||||
|
containerEl.createEl('h3', { text: 'Typography Defaults' });
|
||||||
|
|
||||||
|
// Use helper method for all three font dropdowns
|
||||||
|
this.createFontDropdown(
|
||||||
|
containerEl,
|
||||||
|
'Body font',
|
||||||
|
'Default font for body text',
|
||||||
|
() => this.plugin.settings.typography.fonts.body,
|
||||||
|
(value) => { this.plugin.settings.typography.fonts.body = value; }
|
||||||
|
);
|
||||||
|
|
||||||
|
this.createFontDropdown(
|
||||||
|
containerEl,
|
||||||
|
'Heading font',
|
||||||
|
'Default font for headings',
|
||||||
|
() => this.plugin.settings.typography.fonts.heading,
|
||||||
|
(value) => { this.plugin.settings.typography.fonts.heading = value; }
|
||||||
|
);
|
||||||
|
|
||||||
|
this.createFontDropdown(
|
||||||
|
containerEl,
|
||||||
|
'Monospace font',
|
||||||
|
'Default font for code and monospace text',
|
||||||
|
() => this.plugin.settings.typography.fonts.monospace,
|
||||||
|
(value) => { this.plugin.settings.typography.fonts.monospace = value; }
|
||||||
|
);
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Body font size')
|
||||||
|
.setDesc('Default font size for body text (in points)')
|
||||||
|
.addSlider(slider => slider
|
||||||
|
.setLimits(8, 16, 0.5)
|
||||||
|
.setValue(this.plugin.settings.typography.fontSizes.body)
|
||||||
|
.setDynamicTooltip()
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.typography.fontSizes.body = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to create a margin input setting
|
||||||
|
*/
|
||||||
|
private createMarginInput(
|
||||||
|
containerEl: HTMLElement,
|
||||||
|
name: string,
|
||||||
|
placeholder: string,
|
||||||
|
getCurrentValue: () => number,
|
||||||
|
setNewValue: (value: number) => void,
|
||||||
|
defaultValue: number
|
||||||
|
): void {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName(name)
|
||||||
|
.setDesc(`${name.toLowerCase()} in centimeters`)
|
||||||
|
.addText(text => text
|
||||||
|
.setPlaceholder(placeholder)
|
||||||
|
.setValue(this.formatSingleMarginForDisplay(getCurrentValue()))
|
||||||
|
.onChange(async (value) => {
|
||||||
|
setNewValue(this.parseMarginValue(value, defaultValue));
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private createPageSetupSection(containerEl: HTMLElement): void {
|
||||||
|
containerEl.createEl('h3', { text: 'Page Setup' });
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Page size')
|
||||||
|
.setDesc('Paper size for PDF output')
|
||||||
|
.addDropdown(dropdown => {
|
||||||
|
// Add all supported paper sizes
|
||||||
|
SUPPORTED_PAPER_SIZES.forEach(paperSize => {
|
||||||
|
dropdown.addOption(paperSize.key, paperSize.displayName);
|
||||||
|
});
|
||||||
|
|
||||||
|
return dropdown
|
||||||
|
.setValue(this.plugin.settings.pageSetup.size)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.pageSetup.size = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Page orientation')
|
||||||
|
.setDesc('Page orientation')
|
||||||
|
.addDropdown(dropdown => dropdown
|
||||||
|
.addOption('portrait', 'Portrait')
|
||||||
|
.addOption('landscape', 'Landscape')
|
||||||
|
.setValue(this.plugin.settings.pageSetup.orientation)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.pageSetup.orientation = value as 'portrait' | 'landscape';
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Test with helper method for top margin only
|
||||||
|
this.createMarginInput(
|
||||||
|
containerEl,
|
||||||
|
'Top margin',
|
||||||
|
'2.5',
|
||||||
|
() => this.plugin.settings.pageSetup.margins.top,
|
||||||
|
(value) => { this.plugin.settings.pageSetup.margins.top = value; },
|
||||||
|
2.5
|
||||||
|
);
|
||||||
|
|
||||||
|
this.createMarginInput(
|
||||||
|
containerEl,
|
||||||
|
'Bottom margin',
|
||||||
|
'2.0',
|
||||||
|
() => this.plugin.settings.pageSetup.margins.bottom,
|
||||||
|
(value) => { this.plugin.settings.pageSetup.margins.bottom = value; },
|
||||||
|
2.0
|
||||||
|
);
|
||||||
|
|
||||||
|
this.createMarginInput(
|
||||||
|
containerEl,
|
||||||
|
'Left margin',
|
||||||
|
'2.5',
|
||||||
|
() => this.plugin.settings.pageSetup.margins.left,
|
||||||
|
(value) => { this.plugin.settings.pageSetup.margins.left = value; },
|
||||||
|
2.5
|
||||||
|
);
|
||||||
|
|
||||||
|
this.createMarginInput(
|
||||||
|
containerEl,
|
||||||
|
'Right margin',
|
||||||
|
'1.5',
|
||||||
|
() => this.plugin.settings.pageSetup.margins.right,
|
||||||
|
(value) => { this.plugin.settings.pageSetup.margins.right = value; },
|
||||||
|
1.5
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private createBehaviorSection(containerEl: HTMLElement): void {
|
||||||
|
containerEl.createEl('h3', { text: 'Behavior' });
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Open after export')
|
||||||
|
.setDesc('Automatically open PDF after successful export')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.openAfterExport)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.openAfterExport = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Preserve folder structure')
|
||||||
|
.setDesc('Maintain vault folder structure in output directory')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.preserveFolderStructure)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.preserveFolderStructure = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Embed PDF files')
|
||||||
|
.setDesc('Include PDF files as attachments in the exported PDF (in addition to preview images)')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.embedPdfFiles)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.embedPdfFiles = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Embed all file types')
|
||||||
|
.setDesc('Include all referenced file types (office documents, archives, etc.) as PDF attachments')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.embedAllFiles)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.embedAllFiles = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Print frontmatter')
|
||||||
|
.setDesc('Display frontmatter as formatted text at the beginning of documents')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.printFrontmatter)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.printFrontmatter = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Debug mode')
|
||||||
|
.setDesc('Enable verbose logging for troubleshooting')
|
||||||
|
.addToggle(toggle => toggle
|
||||||
|
.setValue(this.plugin.settings.behavior.debugMode)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
this.plugin.settings.behavior.debugMode = value;
|
||||||
|
await this.plugin.saveSettings();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper methods for fonts
|
||||||
|
private async getAvailableFonts(): Promise<string[]> {
|
||||||
|
return await this.plugin.fontManager.getCachedFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper methods for margin conversion
|
||||||
|
private formatSingleMarginForDisplay(marginCm: number): string {
|
||||||
|
// No conversion needed - directly return centimeters
|
||||||
|
return marginCm.toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseMarginValue(value: string, defaultCm: number): number {
|
||||||
|
const cm = parseFloat(value.trim());
|
||||||
|
return isNaN(cm) ? defaultCm : cm; // No conversion needed - directly use centimeters
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,19 +4,21 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { obsidianTypstPDFExport } from '../../main';
|
import { obsidianTypstPDFExport } from '../../main';
|
||||||
|
import { PathUtils } from '../core/PathUtils';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as fs from 'fs';
|
|
||||||
|
|
||||||
export class TemplateManager {
|
export class TemplateManager {
|
||||||
private plugin: obsidianTypstPDFExport;
|
private plugin: obsidianTypstPDFExport;
|
||||||
private templatesPath: string;
|
private templatesPath: string;
|
||||||
|
private pathUtils: PathUtils;
|
||||||
|
|
||||||
constructor(plugin: obsidianTypstPDFExport) {
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
// Templates are stored in the plugin directory
|
// Templates are stored in the plugin directory
|
||||||
this.templatesPath = path.join(
|
this.templatesPath = this.pathUtils.joinPath(
|
||||||
(this.plugin.app.vault.adapter as any).basePath,
|
this.pathUtils.getVaultPath(),
|
||||||
this.plugin.manifest.dir!,
|
this.pathUtils.getPluginDir(this.plugin.manifest),
|
||||||
'templates'
|
'templates'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -27,13 +29,25 @@ export class TemplateManager {
|
|||||||
async getAvailableTemplates(): Promise<string[]> {
|
async getAvailableTemplates(): Promise<string[]> {
|
||||||
try {
|
try {
|
||||||
// Check if templates directory exists
|
// Check if templates directory exists
|
||||||
if (!fs.existsSync(this.templatesPath)) {
|
const exists = await this.pathUtils.fileExists(this.templatesPath);
|
||||||
|
if (!exists) {
|
||||||
console.warn('Templates directory does not exist:', this.templatesPath);
|
console.warn('Templates directory does not exist:', this.templatesPath);
|
||||||
return ['default.typ'];
|
return ['default.typ'];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read directory contents
|
// Read directory contents - convert absolute path to vault-relative
|
||||||
const files = fs.readdirSync(this.templatesPath);
|
const vaultBasePath = this.pathUtils.getVaultPath();
|
||||||
|
let vaultRelativePath = this.templatesPath;
|
||||||
|
|
||||||
|
// Convert absolute path to vault-relative path
|
||||||
|
if (this.templatesPath.startsWith(vaultBasePath)) {
|
||||||
|
vaultRelativePath = this.templatesPath.substring(vaultBasePath.length);
|
||||||
|
// Remove leading separators
|
||||||
|
vaultRelativePath = vaultRelativePath.replace(/^[/\\]+/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await this.plugin.app.vault.adapter.list(vaultRelativePath);
|
||||||
|
const files = list.files.map(filePath => path.basename(filePath));
|
||||||
|
|
||||||
// Filter for .typ and .pandoc.typ files
|
// Filter for .typ and .pandoc.typ files
|
||||||
const templates = files.filter(file => {
|
const templates = files.filter(file => {
|
||||||
@@ -56,7 +70,7 @@ export class TemplateManager {
|
|||||||
* Get the full path to a template file
|
* Get the full path to a template file
|
||||||
*/
|
*/
|
||||||
getTemplatePath(templateName: string): string {
|
getTemplatePath(templateName: string): string {
|
||||||
return path.join(this.templatesPath, templateName);
|
return this.pathUtils.joinPath(this.templatesPath, templateName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -64,11 +78,7 @@ export class TemplateManager {
|
|||||||
*/
|
*/
|
||||||
async templateExists(templateName: string): Promise<boolean> {
|
async templateExists(templateName: string): Promise<boolean> {
|
||||||
const templatePath = this.getTemplatePath(templateName);
|
const templatePath = this.getTemplatePath(templateName);
|
||||||
try {
|
return await this.pathUtils.fileExists(templatePath);
|
||||||
return fs.existsSync(templatePath);
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,8 +87,9 @@ export class TemplateManager {
|
|||||||
async loadTemplate(templateName: string): Promise<string | null> {
|
async loadTemplate(templateName: string): Promise<string | null> {
|
||||||
const templatePath = this.getTemplatePath(templateName);
|
const templatePath = this.getTemplatePath(templateName);
|
||||||
try {
|
try {
|
||||||
if (fs.existsSync(templatePath)) {
|
const exists = await this.pathUtils.fileExists(templatePath);
|
||||||
return fs.readFileSync(templatePath, 'utf-8');
|
if (exists) {
|
||||||
|
return await this.plugin.app.vault.adapter.read(templatePath);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading template:', error);
|
console.error('Error loading template:', error);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { extractTemplate, getAllTemplateNames } from 'template-embed:templates';
|
import { extractTemplate, getAllTemplateNames } from 'template-embed:templates';
|
||||||
import * as fs from 'fs';
|
import { PathUtils } from '../core/PathUtils';
|
||||||
import * as path from 'path';
|
import type { App } from 'obsidian';
|
||||||
|
|
||||||
export interface TemplateInfo {
|
export interface TemplateInfo {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -14,22 +14,26 @@ export interface TemplateInfo {
|
|||||||
export class EmbeddedTemplateManager {
|
export class EmbeddedTemplateManager {
|
||||||
private pluginDir: string;
|
private pluginDir: string;
|
||||||
private templatesDir: string;
|
private templatesDir: string;
|
||||||
|
private pathUtils: PathUtils;
|
||||||
|
private app: App;
|
||||||
|
|
||||||
constructor(pluginDir: string) {
|
constructor(pluginDir: string, app: App) {
|
||||||
this.pluginDir = pluginDir;
|
this.pluginDir = pluginDir;
|
||||||
this.templatesDir = path.join(pluginDir, 'templates');
|
this.app = app;
|
||||||
|
this.pathUtils = new PathUtils(app);
|
||||||
|
this.templatesDir = this.pathUtils.joinPath(pluginDir, 'templates');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get information about all templates
|
* Get information about all templates
|
||||||
*/
|
*/
|
||||||
getTemplateInfo(): TemplateInfo[] {
|
async getTemplateInfo(): Promise<TemplateInfo[]> {
|
||||||
const embeddedNames = getAllTemplateNames();
|
const embeddedNames = getAllTemplateNames();
|
||||||
const templateInfo: TemplateInfo[] = [];
|
const templateInfo: TemplateInfo[] = [];
|
||||||
|
|
||||||
for (const name of embeddedNames) {
|
for (const name of embeddedNames) {
|
||||||
const filePath = path.join(this.templatesDir, name);
|
const filePath = this.pathUtils.joinPath(this.templatesDir, name);
|
||||||
const exists = fs.existsSync(filePath);
|
const exists = await this.pathUtils.fileExists(filePath);
|
||||||
|
|
||||||
templateInfo.push({
|
templateInfo.push({
|
||||||
name,
|
name,
|
||||||
@@ -44,25 +48,23 @@ export class EmbeddedTemplateManager {
|
|||||||
/**
|
/**
|
||||||
* Extract a single template if it doesn't exist
|
* Extract a single template if it doesn't exist
|
||||||
*/
|
*/
|
||||||
extractTemplateIfNeeded(templateName: string): boolean {
|
async extractTemplateIfNeeded(templateName: string): Promise<boolean> {
|
||||||
const filePath = path.join(this.templatesDir, templateName);
|
const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
|
||||||
|
|
||||||
// Check if template already exists
|
// Check if template already exists
|
||||||
if (fs.existsSync(filePath)) {
|
if (await this.pathUtils.fileExists(filePath)) {
|
||||||
return false; // No extraction needed
|
return false; // No extraction needed
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Ensure templates directory exists
|
// Ensure templates directory exists
|
||||||
if (!fs.existsSync(this.templatesDir)) {
|
await this.pathUtils.ensureDir(this.templatesDir);
|
||||||
fs.mkdirSync(this.templatesDir, { recursive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract template content
|
// Extract template content
|
||||||
const content = extractTemplate(templateName, filePath);
|
const content = extractTemplate(templateName, filePath);
|
||||||
|
|
||||||
// Write template to disk
|
// Write template to disk using vault.adapter
|
||||||
fs.writeFileSync(filePath, content, 'utf8');
|
await this.app.vault.adapter.write(filePath, content);
|
||||||
|
|
||||||
return true; // Extraction successful
|
return true; // Extraction successful
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -74,15 +76,15 @@ export class EmbeddedTemplateManager {
|
|||||||
/**
|
/**
|
||||||
* Extract all missing templates
|
* Extract all missing templates
|
||||||
*/
|
*/
|
||||||
extractAllMissingTemplates(): { extracted: string[], failed: string[] } {
|
async extractAllMissingTemplates(): Promise<{ extracted: string[], failed: string[] }> {
|
||||||
const extracted: string[] = [];
|
const extracted: string[] = [];
|
||||||
const failed: string[] = [];
|
const failed: string[] = [];
|
||||||
|
|
||||||
const templateInfo = this.getTemplateInfo();
|
const templateInfo = await this.getTemplateInfo();
|
||||||
|
|
||||||
for (const info of templateInfo) {
|
for (const info of templateInfo) {
|
||||||
if (info.needsExtraction) {
|
if (info.needsExtraction) {
|
||||||
const success = this.extractTemplateIfNeeded(info.name);
|
const success = await this.extractTemplateIfNeeded(info.name);
|
||||||
if (success) {
|
if (success) {
|
||||||
extracted.push(info.name);
|
extracted.push(info.name);
|
||||||
} else {
|
} else {
|
||||||
@@ -97,23 +99,21 @@ export class EmbeddedTemplateManager {
|
|||||||
/**
|
/**
|
||||||
* Force extract all templates (overwrites existing ones)
|
* Force extract all templates (overwrites existing ones)
|
||||||
*/
|
*/
|
||||||
forceExtractAllTemplates(): { extracted: string[], failed: string[] } {
|
async forceExtractAllTemplates(): Promise<{ extracted: string[], failed: string[] }> {
|
||||||
const extracted: string[] = [];
|
const extracted: string[] = [];
|
||||||
const failed: string[] = [];
|
const failed: string[] = [];
|
||||||
|
|
||||||
const embeddedNames = getAllTemplateNames();
|
const embeddedNames = getAllTemplateNames();
|
||||||
|
|
||||||
// Ensure templates directory exists
|
// Ensure templates directory exists
|
||||||
if (!fs.existsSync(this.templatesDir)) {
|
await this.pathUtils.ensureDir(this.templatesDir);
|
||||||
fs.mkdirSync(this.templatesDir, { recursive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const templateName of embeddedNames) {
|
for (const templateName of embeddedNames) {
|
||||||
try {
|
try {
|
||||||
const filePath = path.join(this.templatesDir, templateName);
|
const filePath = this.pathUtils.joinPath(this.templatesDir, templateName);
|
||||||
const content = extractTemplate(templateName, filePath);
|
const content = extractTemplate(templateName, filePath);
|
||||||
|
|
||||||
fs.writeFileSync(filePath, content, 'utf8');
|
await this.app.vault.adapter.write(filePath, content);
|
||||||
extracted.push(templateName);
|
extracted.push(templateName);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Failed to force extract template ${templateName}:`, error);
|
console.error(`Failed to force extract template ${templateName}:`, error);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
export interface TemplateVariable {
|
export interface TemplateVariable {
|
||||||
type: 'string' | 'number' | 'boolean';
|
type: 'string' | 'number' | 'boolean';
|
||||||
defaultValue: any;
|
defaultValue: string | number | boolean;
|
||||||
description?: string;
|
description?: string;
|
||||||
required: boolean;
|
required: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
* Refactored modular version that uses section components
|
* Refactored modular version that uses section components
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Modal, App, Notice } from 'obsidian';
|
import { Modal, App } from 'obsidian';
|
||||||
|
import { ExportErrorHandler } from '../../core/ExportErrorHandler';
|
||||||
import { obsidianTypstPDFExport } from '../../../main';
|
import { obsidianTypstPDFExport } from '../../../main';
|
||||||
import { ExportConfig, ExportConfigModalSettings, ModalSection } from './modalTypes';
|
import { ExportConfig, ExportConfigModalSettings, ModalSection } from './modalTypes';
|
||||||
import { ModalState } from './state/ModalState';
|
import { ModalState } from './state/ModalState';
|
||||||
@@ -12,6 +13,8 @@ import { TypographySection } from './sections/TypographySection';
|
|||||||
import { PageSetupSection } from './sections/PageSetupSection';
|
import { PageSetupSection } from './sections/PageSetupSection';
|
||||||
import { BehaviorSection } from './sections/BehaviorSection';
|
import { BehaviorSection } from './sections/BehaviorSection';
|
||||||
import { TemplateManager } from '../../templates/TemplateManager';
|
import { TemplateManager } from '../../templates/TemplateManager';
|
||||||
|
import { ModalRenderer, ModalRendererCallbacks } from './ModalRenderer';
|
||||||
|
import { ModalValidator } from './ModalValidator';
|
||||||
|
|
||||||
export class ExportConfigModal extends Modal {
|
export class ExportConfigModal extends Modal {
|
||||||
plugin: obsidianTypstPDFExport;
|
plugin: obsidianTypstPDFExport;
|
||||||
@@ -19,16 +22,8 @@ export class ExportConfigModal extends Modal {
|
|||||||
private sections: Map<string, ModalSection> = new Map();
|
private sections: Map<string, ModalSection> = new Map();
|
||||||
private onSubmit: (config: ExportConfig) => void;
|
private onSubmit: (config: ExportConfig) => void;
|
||||||
private onCancel?: () => void;
|
private onCancel?: () => void;
|
||||||
|
private renderer: ModalRenderer;
|
||||||
// UI elements
|
private validator: ModalValidator;
|
||||||
private contentContainer: HTMLElement;
|
|
||||||
private formContainer: HTMLElement;
|
|
||||||
private progressContainer: HTMLElement;
|
|
||||||
private progressBar: HTMLElement;
|
|
||||||
private progressText: HTMLElement;
|
|
||||||
private submitButton: HTMLButtonElement;
|
|
||||||
private cancelButton: HTMLButtonElement;
|
|
||||||
private resetButton: HTMLButtonElement;
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
app: App,
|
app: App,
|
||||||
@@ -48,6 +43,17 @@ export class ExportConfigModal extends Modal {
|
|||||||
// Register sections
|
// Register sections
|
||||||
this.registerSections();
|
this.registerSections();
|
||||||
|
|
||||||
|
// Initialize renderer with callbacks
|
||||||
|
const callbacks: ModalRendererCallbacks = {
|
||||||
|
onReset: () => this.handleReset(),
|
||||||
|
onCancel: () => this.handleCancel(),
|
||||||
|
onSubmit: () => this.handleSubmit()
|
||||||
|
};
|
||||||
|
this.renderer = new ModalRenderer(this.state, this.sections, callbacks, this.app);
|
||||||
|
|
||||||
|
// Initialize validator
|
||||||
|
this.validator = new ModalValidator();
|
||||||
|
|
||||||
// Listen for state changes
|
// Listen for state changes
|
||||||
this.state.onChange(() => this.handleStateChange());
|
this.state.onChange(() => this.handleStateChange());
|
||||||
}
|
}
|
||||||
@@ -70,107 +76,16 @@ export class ExportConfigModal extends Modal {
|
|||||||
const { contentEl } = this;
|
const { contentEl } = this;
|
||||||
contentEl.addClass('export-config-modal');
|
contentEl.addClass('export-config-modal');
|
||||||
|
|
||||||
// Add styles
|
|
||||||
this.addModalStyles();
|
|
||||||
|
|
||||||
// Create main container
|
// Create main container
|
||||||
this.contentContainer = contentEl.createDiv('export-config-container');
|
const contentContainer = contentEl.createDiv('export-config-container');
|
||||||
|
|
||||||
// Create header
|
// Initialize renderer with content container
|
||||||
this.createHeader();
|
this.renderer.initialize(contentContainer);
|
||||||
|
|
||||||
// Create form container
|
|
||||||
this.formContainer = this.contentContainer.createDiv('export-config-form');
|
|
||||||
|
|
||||||
// Render sections
|
|
||||||
this.renderSections();
|
|
||||||
|
|
||||||
// Create progress container (initially hidden)
|
|
||||||
this.createProgressContainer();
|
|
||||||
|
|
||||||
// Create action buttons
|
|
||||||
this.createActionButtons();
|
|
||||||
|
|
||||||
// Load available templates
|
// Load available templates
|
||||||
this.loadAvailableTemplates();
|
this.loadAvailableTemplates();
|
||||||
}
|
}
|
||||||
|
|
||||||
private createHeader(): void {
|
|
||||||
const header = this.contentContainer.createDiv('export-config-header');
|
|
||||||
header.createEl('h2', { text: 'Export to PDF' });
|
|
||||||
|
|
||||||
if (this.state.settings.noteTitle) {
|
|
||||||
const isMultiFile = this.state.settings.files && this.state.settings.files.length > 1;
|
|
||||||
const displayText = isMultiFile
|
|
||||||
? `Exporting ${this.state.settings.files!.length} files`
|
|
||||||
: `Exporting: ${this.state.settings.noteTitle}`;
|
|
||||||
|
|
||||||
header.createEl('p', {
|
|
||||||
text: displayText,
|
|
||||||
cls: 'export-note-title'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private renderSections(): void {
|
|
||||||
// Clear existing content
|
|
||||||
this.formContainer.empty();
|
|
||||||
|
|
||||||
// Render each section
|
|
||||||
this.sections.forEach(section => {
|
|
||||||
section.render(this.formContainer, this.state, this.app);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private createProgressContainer(): void {
|
|
||||||
this.progressContainer = this.contentContainer.createDiv('export-progress-container');
|
|
||||||
this.progressContainer.addClass('export-hidden');
|
|
||||||
|
|
||||||
// Progress text
|
|
||||||
this.progressText = this.progressContainer.createEl('div', {
|
|
||||||
cls: 'export-progress-text',
|
|
||||||
text: 'Preparing export...'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Progress bar container
|
|
||||||
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
|
|
||||||
this.progressBar = progressBarContainer.createDiv('export-progress-bar');
|
|
||||||
|
|
||||||
// Progress percentage
|
|
||||||
const progressPercent = this.progressContainer.createEl('div', {
|
|
||||||
cls: 'export-progress-percent',
|
|
||||||
text: '0%'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private createActionButtons(): void {
|
|
||||||
const buttonContainer = this.contentContainer.createDiv('export-config-buttons');
|
|
||||||
|
|
||||||
// Reset button (left side)
|
|
||||||
this.resetButton = buttonContainer.createEl('button', {
|
|
||||||
text: 'Reset to Defaults',
|
|
||||||
cls: 'mod-muted'
|
|
||||||
});
|
|
||||||
this.resetButton.addEventListener('click', () => this.handleReset());
|
|
||||||
|
|
||||||
// Right side buttons container
|
|
||||||
const rightButtons = buttonContainer.createDiv('right-buttons');
|
|
||||||
|
|
||||||
// Cancel button
|
|
||||||
this.cancelButton = rightButtons.createEl('button', {
|
|
||||||
text: 'Cancel',
|
|
||||||
cls: 'mod-cancel'
|
|
||||||
});
|
|
||||||
this.cancelButton.addEventListener('click', () => this.handleCancel());
|
|
||||||
|
|
||||||
// Export button
|
|
||||||
this.submitButton = rightButtons.createEl('button', {
|
|
||||||
text: 'Export',
|
|
||||||
cls: 'mod-cta'
|
|
||||||
});
|
|
||||||
this.submitButton.addEventListener('click', () => this.handleSubmit());
|
|
||||||
}
|
|
||||||
|
|
||||||
private async loadAvailableTemplates(): Promise<void> {
|
private async loadAvailableTemplates(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const templateManager = new TemplateManager(this.plugin);
|
const templateManager = new TemplateManager(this.plugin);
|
||||||
@@ -187,86 +102,64 @@ export class ExportConfigModal extends Modal {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load templates:', error);
|
console.error('Failed to load templates:', error);
|
||||||
new Notice(`Failed to load available templates: ${error.message}`);
|
ExportErrorHandler.showTemplateError(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleStateChange(): void {
|
private handleStateChange(): void {
|
||||||
// State change handler for any UI updates needed
|
// Refresh sections when state changes
|
||||||
// This is called whenever the state is updated
|
this.renderer.refreshSections();
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleReset(): void {
|
private handleReset(): void {
|
||||||
// Create plugin defaults object from settings tab values
|
// Reset state to plugin defaults using the full settings object
|
||||||
const pluginDefaults = {
|
this.state.reset(this.plugin.settings);
|
||||||
template: this.plugin.settings.exportDefaults.template,
|
|
||||||
format: this.plugin.settings.exportDefaults.format,
|
|
||||||
outputFolder: this.plugin.settings.outputFolder,
|
|
||||||
openAfterExport: this.plugin.settings.behavior.openAfterExport,
|
|
||||||
preserveFolderStructure: this.plugin.settings.behavior.preserveFolderStructure,
|
|
||||||
pageSize: this.plugin.settings.pageSetup.size,
|
|
||||||
orientation: this.plugin.settings.pageSetup.orientation,
|
|
||||||
marginTop: this.plugin.settings.pageSetup.margins.top.toString(),
|
|
||||||
marginBottom: this.plugin.settings.pageSetup.margins.bottom.toString(),
|
|
||||||
marginLeft: this.plugin.settings.pageSetup.margins.left.toString(),
|
|
||||||
marginRight: this.plugin.settings.pageSetup.margins.right.toString(),
|
|
||||||
bodyFont: this.plugin.settings.typography.fonts.body,
|
|
||||||
headingFont: this.plugin.settings.typography.fonts.heading,
|
|
||||||
monospaceFont: this.plugin.settings.typography.fonts.monospace,
|
|
||||||
bodyFontSize: this.plugin.settings.typography.fontSizes.body
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reset state to plugin defaults
|
|
||||||
this.state.reset(pluginDefaults);
|
|
||||||
|
|
||||||
// Re-render sections to update UI
|
// Re-render sections to update UI
|
||||||
this.renderSections();
|
this.renderer.refreshSections();
|
||||||
|
|
||||||
// Reload templates to update the dropdown
|
// Reload templates to update the dropdown
|
||||||
this.loadAvailableTemplates();
|
this.loadAvailableTemplates();
|
||||||
|
|
||||||
new Notice('Settings reset to defaults');
|
ExportErrorHandler.showSettingsReset();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleSubmit(): Promise<void> {
|
private async handleSubmit(): Promise<void> {
|
||||||
// Validate all sections
|
// Validate all sections
|
||||||
const validationResults = this.validateAllSections();
|
const validationResults = this.validator.validateAllSections(Array.from(this.sections.values()));
|
||||||
|
|
||||||
if (!validationResults.isValid) {
|
if (!validationResults.isValid) {
|
||||||
this.showValidationErrors(validationResults.errors);
|
this.renderer.showValidationErrors(validationResults.errors);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show any warnings
|
// Show any warnings
|
||||||
if (validationResults.warnings.length > 0) {
|
if (validationResults.warnings && validationResults.warnings.length > 0) {
|
||||||
this.showValidationWarnings(validationResults.warnings);
|
this.renderer.showValidationWarnings(validationResults.warnings);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build export configuration
|
// Build export configuration
|
||||||
const config = this.state.buildExportConfig();
|
const config = this.state.buildExportConfig();
|
||||||
|
|
||||||
// Show progress
|
// Show progress
|
||||||
this.showProgress('Starting export...', 0);
|
this.renderer.showProgress('Starting export...', 0);
|
||||||
|
|
||||||
// Disable buttons
|
// Set buttons to exporting state
|
||||||
this.submitButton.disabled = true;
|
this.renderer.setExportingState(true);
|
||||||
this.resetButton.disabled = true;
|
|
||||||
this.cancelButton.textContent = 'Close';
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Call the submit handler
|
// Call the submit handler
|
||||||
await this.onSubmit(config);
|
await this.onSubmit(config);
|
||||||
|
|
||||||
// Show success
|
// Show success
|
||||||
this.showProgress('Export completed successfully!', 100);
|
this.renderer.showProgress('Export completed successfully!', 100);
|
||||||
|
|
||||||
// Auto-close after delay
|
// Auto-close after delay
|
||||||
setTimeout(() => this.close(), 2000);
|
setTimeout(() => this.close(), 2000);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Export failed:', error);
|
console.error('Export failed:', error);
|
||||||
this.showProgress(`Export failed: ${error.message}`, -1);
|
this.renderer.showProgress(`Export failed: ${error.message}`, -1);
|
||||||
this.submitButton.disabled = false;
|
this.renderer.setExportingState(false);
|
||||||
this.resetButton.disabled = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,203 +169,19 @@ export class ExportConfigModal extends Modal {
|
|||||||
if (this.onCancel) {
|
if (this.onCancel) {
|
||||||
this.onCancel();
|
this.onCancel();
|
||||||
}
|
}
|
||||||
this.showProgress('Export cancelled', -1);
|
this.renderer.showProgress('Export cancelled', -1);
|
||||||
} else {
|
} else {
|
||||||
// Close modal
|
// Close modal
|
||||||
this.close();
|
this.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private validateAllSections(): { isValid: boolean; errors: string[]; warnings: string[] } {
|
|
||||||
const errors: string[] = [];
|
|
||||||
const warnings: string[] = [];
|
|
||||||
|
|
||||||
this.sections.forEach(section => {
|
|
||||||
if (section.validate) {
|
|
||||||
const result = section.validate();
|
|
||||||
errors.push(...result.errors);
|
|
||||||
if (result.warnings) {
|
|
||||||
warnings.push(...result.warnings);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
isValid: errors.length === 0,
|
|
||||||
errors,
|
|
||||||
warnings
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private showValidationErrors(errors: string[]): void {
|
|
||||||
const errorContainer = this.formContainer.createDiv('validation-errors');
|
|
||||||
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
|
|
||||||
|
|
||||||
const errorList = errorContainer.createEl('ul');
|
|
||||||
errors.forEach(error => {
|
|
||||||
errorList.createEl('li', { text: error });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Remove after 5 seconds
|
|
||||||
setTimeout(() => errorContainer.remove(), 5000);
|
|
||||||
}
|
|
||||||
|
|
||||||
private showValidationWarnings(warnings: string[]): void {
|
|
||||||
warnings.forEach(warning => {
|
|
||||||
new Notice(`Warning: ${warning}`, 3000);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private showProgress(message: string, percent: number): void {
|
|
||||||
this.progressContainer.addClass('export-progress-visible');
|
|
||||||
this.formContainer.addClass('export-form-hidden');
|
|
||||||
|
|
||||||
this.progressText.textContent = message;
|
|
||||||
|
|
||||||
if (percent >= 0) {
|
|
||||||
this.progressBar.style.setProperty('--progress-width', `${percent}%`);
|
|
||||||
const percentEl = this.progressContainer.querySelector('.export-progress-percent');
|
|
||||||
if (percentEl) {
|
|
||||||
percentEl.textContent = `${Math.round(percent)}%`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update state
|
|
||||||
this.state.setProgress(percent, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
updateProgress(message: string, percent: number): void {
|
updateProgress(message: string, percent: number): void {
|
||||||
this.showProgress(message, percent);
|
this.renderer.updateProgress(message, percent);
|
||||||
}
|
}
|
||||||
|
|
||||||
private getOutputFilename(): string {
|
|
||||||
const noteName = this.state.settings.noteTitle || 'document';
|
|
||||||
return `${noteName}.pdf`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private addModalStyles(): void {
|
|
||||||
// Add custom styles for the modal
|
|
||||||
const style = document.createElement('style');
|
|
||||||
style.textContent = `
|
|
||||||
.export-config-modal {
|
|
||||||
width: 90vw;
|
|
||||||
max-width: 520px;
|
|
||||||
height: 80vh;
|
|
||||||
max-height: 600px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-header {
|
|
||||||
padding: 20px;
|
|
||||||
border-bottom: 1px solid var(--background-modifier-border);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-header h2 {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-note-title {
|
|
||||||
margin: 10px 0 0 0;
|
|
||||||
color: var(--text-muted);
|
|
||||||
font-size: 0.9em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-form {
|
|
||||||
flex: 1;
|
|
||||||
overflow-y: auto;
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-section {
|
|
||||||
margin-bottom: 30px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-section h3 {
|
|
||||||
margin-bottom: 15px;
|
|
||||||
font-size: 1.1em;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-section h4 {
|
|
||||||
margin: 15px 0 10px 0;
|
|
||||||
font-size: 0.95em;
|
|
||||||
font-weight: 500;
|
|
||||||
color: var(--text-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-progress-container {
|
|
||||||
padding: 40px;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-progress-text {
|
|
||||||
margin-bottom: 20px;
|
|
||||||
font-size: 1.1em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-progress-bar-container {
|
|
||||||
width: 100%;
|
|
||||||
height: 20px;
|
|
||||||
background: var(--background-secondary);
|
|
||||||
border-radius: 10px;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-progress-bar {
|
|
||||||
height: 100%;
|
|
||||||
background: var(--interactive-accent);
|
|
||||||
transition: width 0.3s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-progress-percent {
|
|
||||||
margin-top: 10px;
|
|
||||||
color: var(--text-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-buttons {
|
|
||||||
padding: 20px;
|
|
||||||
border-top: 1px solid var(--background-modifier-border);
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.export-config-buttons .right-buttons {
|
|
||||||
display: flex;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.validation-errors {
|
|
||||||
background: var(--background-modifier-error);
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 5px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error-title {
|
|
||||||
color: var(--text-error);
|
|
||||||
margin: 0 0 10px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.validation-errors ul {
|
|
||||||
margin: 0;
|
|
||||||
padding-left: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.margins-container {
|
|
||||||
background: var(--background-secondary-alt);
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 5px;
|
|
||||||
margin-top: 15px;
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
document.head.appendChild(style);
|
|
||||||
}
|
|
||||||
|
|
||||||
onClose(): void {
|
onClose(): void {
|
||||||
// Clean up state listeners
|
// Clean up state listeners
|
||||||
|
|||||||
@@ -0,0 +1,491 @@
|
|||||||
|
/**
|
||||||
|
* Modal Rendering Logic
|
||||||
|
* Handles all DOM creation and styling for the ExportConfigModal
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { App } from 'obsidian';
|
||||||
|
import { ModalState } from './state/ModalState';
|
||||||
|
import { ModalSection } from './modalTypes';
|
||||||
|
|
||||||
|
export interface ModalRendererCallbacks {
|
||||||
|
onReset: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSubmit: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModalRenderer {
|
||||||
|
private state: ModalState;
|
||||||
|
private sections: Map<string, ModalSection>;
|
||||||
|
private callbacks: ModalRendererCallbacks;
|
||||||
|
private app?: App;
|
||||||
|
|
||||||
|
// UI elements managed by this renderer
|
||||||
|
private contentContainer!: HTMLElement;
|
||||||
|
private formContainer!: HTMLElement;
|
||||||
|
private progressContainer!: HTMLElement;
|
||||||
|
private progressBar!: HTMLElement;
|
||||||
|
private progressText!: HTMLElement;
|
||||||
|
private submitButton!: HTMLButtonElement;
|
||||||
|
private cancelButton!: HTMLButtonElement;
|
||||||
|
private resetButton!: HTMLButtonElement;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
state: ModalState,
|
||||||
|
sections: Map<string, ModalSection>,
|
||||||
|
callbacks: ModalRendererCallbacks,
|
||||||
|
app?: App
|
||||||
|
) {
|
||||||
|
this.state = state;
|
||||||
|
this.sections = sections;
|
||||||
|
this.callbacks = callbacks;
|
||||||
|
this.app = app;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the renderer with the modal's content container
|
||||||
|
*/
|
||||||
|
initialize(contentContainer: HTMLElement): void {
|
||||||
|
this.contentContainer = contentContainer;
|
||||||
|
this.setupInitialLayout();
|
||||||
|
this.addModalStyles();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set up the initial modal layout structure
|
||||||
|
*/
|
||||||
|
private setupInitialLayout(): void {
|
||||||
|
// Create main form container
|
||||||
|
this.formContainer = this.contentContainer.createDiv('export-config-form');
|
||||||
|
|
||||||
|
// Create header
|
||||||
|
this.createHeader();
|
||||||
|
|
||||||
|
// Render sections
|
||||||
|
this.renderSections();
|
||||||
|
|
||||||
|
// Create progress container (initially hidden)
|
||||||
|
this.createProgressContainer();
|
||||||
|
|
||||||
|
// Create action buttons
|
||||||
|
this.createActionButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the modal header with title and note information
|
||||||
|
*/
|
||||||
|
private createHeader(): void {
|
||||||
|
const header = this.contentContainer.createDiv('export-config-header');
|
||||||
|
header.createEl('h2', { text: 'Export to PDF' });
|
||||||
|
|
||||||
|
if (this.state.settings.noteTitle) {
|
||||||
|
const isMultiFile = this.state.settings.files && this.state.settings.files.length > 1;
|
||||||
|
const displayText = isMultiFile
|
||||||
|
? `Exporting ${this.state.settings.files!.length} files`
|
||||||
|
: `Exporting: ${this.state.settings.noteTitle}`;
|
||||||
|
|
||||||
|
header.createEl('p', {
|
||||||
|
text: displayText,
|
||||||
|
cls: 'export-note-title'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render all configuration sections
|
||||||
|
*/
|
||||||
|
private renderSections(): void {
|
||||||
|
// Clear existing content
|
||||||
|
this.formContainer.empty();
|
||||||
|
|
||||||
|
// Render each section
|
||||||
|
this.sections.forEach(section => {
|
||||||
|
section.render(this.formContainer, this.state, this.app);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the progress container with progress bar and text
|
||||||
|
*/
|
||||||
|
private createProgressContainer(): void {
|
||||||
|
this.progressContainer = this.contentContainer.createDiv('export-progress-container');
|
||||||
|
this.progressContainer.addClass('export-hidden');
|
||||||
|
|
||||||
|
// Progress text
|
||||||
|
this.progressText = this.progressContainer.createEl('div', {
|
||||||
|
cls: 'export-progress-text',
|
||||||
|
text: 'Preparing export...'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Progress bar container
|
||||||
|
const progressBarContainer = this.progressContainer.createDiv('export-progress-bar-container');
|
||||||
|
this.progressBar = progressBarContainer.createDiv('export-progress-bar');
|
||||||
|
|
||||||
|
// Progress percentage
|
||||||
|
const _progressPercent = this.progressContainer.createEl('div', {
|
||||||
|
cls: 'export-progress-percent',
|
||||||
|
text: '0%'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create action buttons (Reset, Cancel, Export)
|
||||||
|
*/
|
||||||
|
private createActionButtons(): void {
|
||||||
|
const buttonContainer = this.contentContainer.createDiv('export-config-buttons');
|
||||||
|
|
||||||
|
// Reset button (left side)
|
||||||
|
this.resetButton = buttonContainer.createEl('button', {
|
||||||
|
text: 'Reset to Defaults',
|
||||||
|
cls: 'mod-muted'
|
||||||
|
});
|
||||||
|
this.resetButton.addEventListener('click', () => this.callbacks.onReset());
|
||||||
|
|
||||||
|
// Right side buttons container
|
||||||
|
const rightButtons = buttonContainer.createDiv('right-buttons');
|
||||||
|
|
||||||
|
// Cancel button
|
||||||
|
this.cancelButton = rightButtons.createEl('button', {
|
||||||
|
text: 'Cancel',
|
||||||
|
cls: 'mod-cancel'
|
||||||
|
});
|
||||||
|
this.cancelButton.addEventListener('click', () => this.callbacks.onCancel());
|
||||||
|
|
||||||
|
// Export button
|
||||||
|
this.submitButton = rightButtons.createEl('button', {
|
||||||
|
text: 'Export',
|
||||||
|
cls: 'mod-cta'
|
||||||
|
});
|
||||||
|
this.submitButton.addEventListener('click', () => this.callbacks.onSubmit());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show progress with message and percentage
|
||||||
|
*/
|
||||||
|
showProgress(message: string, percent: number): void {
|
||||||
|
this.progressContainer.addClass('export-progress-visible');
|
||||||
|
this.formContainer.addClass('export-form-hidden');
|
||||||
|
|
||||||
|
this.progressText.textContent = message;
|
||||||
|
|
||||||
|
if (percent >= 0) {
|
||||||
|
this.progressBar.style.setProperty('--progress-width', `${percent}%`);
|
||||||
|
const percentEl = this.progressContainer.querySelector('.export-progress-percent');
|
||||||
|
if (percentEl) {
|
||||||
|
percentEl.textContent = `${Math.round(percent)}%`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update state
|
||||||
|
this.state.setProgress(percent, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update progress - public interface for modal to use
|
||||||
|
*/
|
||||||
|
updateProgress(message: string, percent: number): void {
|
||||||
|
this.showProgress(message, percent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-render sections when state changes
|
||||||
|
*/
|
||||||
|
refreshSections(): void {
|
||||||
|
this.renderSections();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set button states during export
|
||||||
|
*/
|
||||||
|
setExportingState(isExporting: boolean): void {
|
||||||
|
if (isExporting) {
|
||||||
|
this.submitButton.disabled = true;
|
||||||
|
this.resetButton.disabled = true;
|
||||||
|
this.cancelButton.textContent = 'Close';
|
||||||
|
} else {
|
||||||
|
this.submitButton.disabled = false;
|
||||||
|
this.resetButton.disabled = false;
|
||||||
|
this.cancelButton.textContent = 'Cancel';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show validation errors in the form
|
||||||
|
*/
|
||||||
|
showValidationErrors(errors: string[]): void {
|
||||||
|
// Remove any existing error containers
|
||||||
|
const existingErrors = this.formContainer.querySelector('.validation-errors');
|
||||||
|
if (existingErrors) {
|
||||||
|
existingErrors.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorContainer = this.formContainer.createDiv('validation-errors');
|
||||||
|
errorContainer.createEl('h4', { text: 'Validation Errors', cls: 'error-title' });
|
||||||
|
|
||||||
|
const errorList = errorContainer.createEl('ul');
|
||||||
|
errors.forEach(error => {
|
||||||
|
errorList.createEl('li', { text: error });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove after 5 seconds
|
||||||
|
setTimeout(() => errorContainer.remove(), 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show validation warnings in the form
|
||||||
|
*/
|
||||||
|
showValidationWarnings(warnings: string[]): void {
|
||||||
|
// Remove any existing warning containers
|
||||||
|
const existingWarnings = this.formContainer.querySelector('.validation-warnings');
|
||||||
|
if (existingWarnings) {
|
||||||
|
existingWarnings.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
const warningContainer = this.formContainer.createDiv('validation-warnings');
|
||||||
|
warningContainer.createEl('h4', { text: 'Warnings', cls: 'warning-title' });
|
||||||
|
|
||||||
|
const warningList = warningContainer.createEl('ul');
|
||||||
|
warnings.forEach(warning => {
|
||||||
|
warningList.createEl('li', { text: warning });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove after 5 seconds
|
||||||
|
setTimeout(() => warningContainer.remove(), 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add custom CSS styles for the modal
|
||||||
|
*/
|
||||||
|
private addModalStyles(): void {
|
||||||
|
// Add custom styles for the modal
|
||||||
|
const style = document.createElement('style');
|
||||||
|
style.textContent = `
|
||||||
|
.export-config-modal {
|
||||||
|
width: 90vw;
|
||||||
|
max-width: 520px;
|
||||||
|
height: 80vh;
|
||||||
|
max-height: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-header {
|
||||||
|
padding: 16px 24px 8px 24px;
|
||||||
|
border-bottom: 1px solid var(--background-modifier-border);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-header h2 {
|
||||||
|
margin: 0 0 8px 0;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-note-title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-form {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 16px 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-section {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-section:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-section-title {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
border-bottom: 1px solid var(--background-modifier-border-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-buttons {
|
||||||
|
padding: 16px 24px;
|
||||||
|
border-top: 1px solid var(--background-modifier-border);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-config-buttons .right-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Progress styles */
|
||||||
|
.export-progress-container {
|
||||||
|
padding: 24px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-container.export-hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-container.export-progress-visible {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-form-hidden {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-text {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-bar-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 8px;
|
||||||
|
background-color: var(--background-modifier-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-bar {
|
||||||
|
height: 100%;
|
||||||
|
background-color: var(--interactive-accent);
|
||||||
|
border-radius: 4px;
|
||||||
|
width: var(--progress-width, 0%);
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-progress-percent {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form field styles */
|
||||||
|
.export-setting-item {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-setting-item-info {
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-setting-item-name {
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-setting-item-description {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-setting-item-control {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-setting-item-control input,
|
||||||
|
.export-setting-item-control select {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Folder suggest styles */
|
||||||
|
.export-folder-suggest-container {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-folder-suggest-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid var(--background-modifier-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--background-primary);
|
||||||
|
color: var(--text-normal);
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-folder-suggest-input:focus {
|
||||||
|
border-color: var(--interactive-accent);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Validation styles */
|
||||||
|
.validation-errors, .validation-warnings {
|
||||||
|
background: var(--background-modifier-error);
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.validation-warnings {
|
||||||
|
background: var(--background-modifier-warning);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-title {
|
||||||
|
color: var(--text-error);
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.warning-title {
|
||||||
|
color: var(--text-warning);
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.validation-errors ul, .validation-warnings ul {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-validation-error {
|
||||||
|
color: var(--text-error);
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-validation-warning {
|
||||||
|
color: var(--text-warning);
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Template variable styles */
|
||||||
|
.export-template-variables {
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-template-variable {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
padding: 8px;
|
||||||
|
background: var(--background-secondary);
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-template-variable-name {
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-template-variable-description {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (!document.head.querySelector('style[data-export-config-modal]')) {
|
||||||
|
style.setAttribute('data-export-config-modal', 'true');
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
/**
|
||||||
|
* Modal validation orchestration
|
||||||
|
*
|
||||||
|
* This class handles validation logic for the export configuration modal,
|
||||||
|
* coordinating validation across all modal sections.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { ModalSection, ValidationResult } from './modalTypes';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles validation orchestration for modal sections
|
||||||
|
*/
|
||||||
|
export class ModalValidator {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates all sections and aggregates the results
|
||||||
|
*
|
||||||
|
* @param sections - Array of modal sections to validate
|
||||||
|
* @returns ValidationResult with aggregated errors and warnings
|
||||||
|
*/
|
||||||
|
public validateAllSections(sections: ModalSection[]): ValidationResult {
|
||||||
|
const errors: string[] = [];
|
||||||
|
const warnings: string[] = [];
|
||||||
|
|
||||||
|
sections.forEach(section => {
|
||||||
|
if (section.validate) {
|
||||||
|
const result = section.validate();
|
||||||
|
errors.push(...result.errors);
|
||||||
|
if (result.warnings) {
|
||||||
|
warnings.push(...result.warnings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
isValid: errors.length === 0,
|
||||||
|
errors,
|
||||||
|
warnings
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
* Type definitions for the Export Configuration Modal
|
* Type definitions for the Export Configuration Modal
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { TFile } from 'obsidian';
|
import { TFile, App } from 'obsidian';
|
||||||
import { ExportFormat } from '../../core/settings';
|
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../core/settings';
|
||||||
|
|
||||||
export interface ExportConfig {
|
export interface ExportConfig {
|
||||||
/** Override default template */
|
/** Override default template */
|
||||||
@@ -13,7 +13,7 @@ export interface ExportConfig {
|
|||||||
/** Override output folder */
|
/** Override output folder */
|
||||||
outputFolder?: string;
|
outputFolder?: string;
|
||||||
/** Template variables for this export */
|
/** Template variables for this export */
|
||||||
templateVariables?: Record<string, any>;
|
templateVariables?: Record<string, string | number | boolean | undefined>;
|
||||||
/** Open PDF after export */
|
/** Open PDF after export */
|
||||||
openAfterExport?: boolean;
|
openAfterExport?: boolean;
|
||||||
/** Preserve folder structure when exporting */
|
/** Preserve folder structure when exporting */
|
||||||
@@ -46,7 +46,7 @@ export interface ExportConfigModalSettings extends ExportConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ModalSection {
|
export interface ModalSection {
|
||||||
render(containerEl: HTMLElement, state: ModalState, app?: any): void;
|
render(containerEl: HTMLElement, state: ModalState, app?: App): void;
|
||||||
validate?(): ValidationResult;
|
validate?(): ValidationResult;
|
||||||
getId(): string;
|
getId(): string;
|
||||||
}
|
}
|
||||||
@@ -59,12 +59,12 @@ export interface ValidationResult {
|
|||||||
|
|
||||||
export interface ModalState {
|
export interface ModalState {
|
||||||
settings: ExportConfigModalSettings;
|
settings: ExportConfigModalSettings;
|
||||||
templateVariables: Record<string, any>;
|
templateVariables: Record<string, string | number | boolean | undefined>;
|
||||||
updateSettings(updates: Partial<ExportConfigModalSettings>): void;
|
updateSettings(updates: Partial<ExportConfigModalSettings>): void;
|
||||||
updateTemplateVariables(updates: Record<string, any>): void;
|
updateTemplateVariables(updates: Record<string, string | number | boolean | undefined>): void;
|
||||||
buildExportConfig(): ExportConfig;
|
buildExportConfig(): ExportConfig;
|
||||||
notifyChange(): void;
|
notifyChange(): void;
|
||||||
setProgress(percent: number, operation: string): void;
|
setProgress(percent: number, operation: string): void;
|
||||||
reset(pluginDefaults: any): void;
|
reset(pluginDefaults: obsidianTypstPDFExportSettings): void;
|
||||||
onChange(listener: () => void): void;
|
onChange(listener: () => void): void;
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
* Handles template selection, format options, and output settings
|
* Handles template selection, format options, and output settings
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Setting, App, normalizePath } from 'obsidian';
|
import { Setting, App, normalizePath, DropdownComponent } from 'obsidian';
|
||||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||||
import { ExportFormat } from '../../../core/settings';
|
import { ExportFormat } from '../../../core/settings';
|
||||||
import { FolderSuggest } from '../../components/FolderSuggest';
|
import { FolderSuggest } from '../../components/FolderSuggest';
|
||||||
@@ -11,7 +11,7 @@ import { SecurityUtils } from '../../../core/SecurityUtils';
|
|||||||
|
|
||||||
export class GeneralSection implements ModalSection {
|
export class GeneralSection implements ModalSection {
|
||||||
private container: HTMLElement | null = null;
|
private container: HTMLElement | null = null;
|
||||||
private templateDropdown: any = null;
|
private templateDropdown: DropdownComponent | null = null;
|
||||||
private outputFolderInput: HTMLInputElement | null = null;
|
private outputFolderInput: HTMLInputElement | null = null;
|
||||||
private app: App;
|
private app: App;
|
||||||
|
|
||||||
@@ -128,16 +128,16 @@ export class GeneralSection implements ModalSection {
|
|||||||
// Filter out universal-wrapper.pandoc.typ and clear/repopulate dropdown
|
// Filter out universal-wrapper.pandoc.typ and clear/repopulate dropdown
|
||||||
const filteredTemplates = templates.filter(template => template !== 'universal-wrapper.pandoc.typ');
|
const filteredTemplates = templates.filter(template => template !== 'universal-wrapper.pandoc.typ');
|
||||||
|
|
||||||
this.templateDropdown.selectEl.empty();
|
this.templateDropdown?.selectEl.empty();
|
||||||
filteredTemplates.forEach(template => {
|
filteredTemplates.forEach(template => {
|
||||||
this.templateDropdown.addOption(template, this.getTemplateDisplayName(template));
|
this.templateDropdown?.addOption(template, this.getTemplateDisplayName(template));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Restore selection if still available
|
// Restore selection if still available
|
||||||
if (filteredTemplates.includes(currentValue)) {
|
if (filteredTemplates.includes(currentValue)) {
|
||||||
this.templateDropdown.setValue(currentValue);
|
this.templateDropdown?.setValue(currentValue);
|
||||||
} else if (filteredTemplates.length > 0) {
|
} else if (filteredTemplates.length > 0) {
|
||||||
this.templateDropdown.setValue(filteredTemplates[0]);
|
this.templateDropdown?.setValue(filteredTemplates[0]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export class PageSetupSection implements ModalSection {
|
|||||||
});
|
});
|
||||||
|
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(state.templateVariables.pageSize || 'a4')
|
.setValue(String(state.templateVariables.pageSize || 'a4'))
|
||||||
.onChange(value => {
|
.onChange(value => {
|
||||||
state.updateTemplateVariables({ pageSize: value });
|
state.updateTemplateVariables({ pageSize: value });
|
||||||
});
|
});
|
||||||
@@ -50,7 +50,7 @@ export class PageSetupSection implements ModalSection {
|
|||||||
dropdown
|
dropdown
|
||||||
.addOption('portrait', 'Portrait')
|
.addOption('portrait', 'Portrait')
|
||||||
.addOption('landscape', 'Landscape')
|
.addOption('landscape', 'Landscape')
|
||||||
.setValue(state.templateVariables.orientation || 'portrait')
|
.setValue(String(state.templateVariables.orientation || 'portrait'))
|
||||||
.onChange(value => {
|
.onChange(value => {
|
||||||
const isLandscape = value === 'landscape';
|
const isLandscape = value === 'landscape';
|
||||||
state.updateTemplateVariables({
|
state.updateTemplateVariables({
|
||||||
@@ -90,7 +90,7 @@ export class PageSetupSection implements ModalSection {
|
|||||||
.addText(text => {
|
.addText(text => {
|
||||||
const input = text
|
const input = text
|
||||||
.setPlaceholder(marginDefaults[side as keyof typeof marginDefaults])
|
.setPlaceholder(marginDefaults[side as keyof typeof marginDefaults])
|
||||||
.setValue(state.templateVariables[`margin${side.charAt(0).toUpperCase() + side.slice(1)}`] || marginDefaults[side as keyof typeof marginDefaults])
|
.setValue(String(state.templateVariables[`margin${side.charAt(0).toUpperCase() + side.slice(1)}`] || marginDefaults[side as keyof typeof marginDefaults]))
|
||||||
.onChange(value => {
|
.onChange(value => {
|
||||||
const marginKey = `margin${side.charAt(0).toUpperCase() + side.slice(1)}`;
|
const marginKey = `margin${side.charAt(0).toUpperCase() + side.slice(1)}`;
|
||||||
state.updateTemplateVariables({ [marginKey]: value });
|
state.updateTemplateVariables({ [marginKey]: value });
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
* Handles font selection and size configuration
|
* Handles font selection and size configuration
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Setting, App } from 'obsidian';
|
import { Setting, App, DropdownComponent } from 'obsidian';
|
||||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||||
|
|
||||||
export class TypographySection implements ModalSection {
|
export class TypographySection implements ModalSection {
|
||||||
@@ -31,7 +31,7 @@ export class TypographySection implements ModalSection {
|
|||||||
.setName('Body font')
|
.setName('Body font')
|
||||||
.setDesc('Primary font for document text')
|
.setDesc('Primary font for document text')
|
||||||
.addDropdown(dropdown => {
|
.addDropdown(dropdown => {
|
||||||
const currentFont = state.templateVariables.bodyFont || 'Times New Roman';
|
const currentFont = String(state.templateVariables.bodyFont || 'Times New Roman');
|
||||||
|
|
||||||
// Add all available fonts
|
// Add all available fonts
|
||||||
availableFonts.forEach(font => {
|
availableFonts.forEach(font => {
|
||||||
@@ -56,7 +56,7 @@ export class TypographySection implements ModalSection {
|
|||||||
.setName('Heading font')
|
.setName('Heading font')
|
||||||
.setDesc('Font for headings and titles')
|
.setDesc('Font for headings and titles')
|
||||||
.addDropdown(dropdown => {
|
.addDropdown(dropdown => {
|
||||||
const currentFont = state.templateVariables.headingFont || 'Times New Roman';
|
const currentFont = String(state.templateVariables.headingFont || 'Times New Roman');
|
||||||
|
|
||||||
// Add all available fonts
|
// Add all available fonts
|
||||||
availableFonts.forEach(font => {
|
availableFonts.forEach(font => {
|
||||||
@@ -81,7 +81,7 @@ export class TypographySection implements ModalSection {
|
|||||||
.setName('Monospace font')
|
.setName('Monospace font')
|
||||||
.setDesc('Font for code blocks and inline code')
|
.setDesc('Font for code blocks and inline code')
|
||||||
.addDropdown(dropdown => {
|
.addDropdown(dropdown => {
|
||||||
const currentFont = state.templateVariables.monospaceFont || 'Courier New';
|
const currentFont = String(state.templateVariables.monospaceFont || 'Courier New');
|
||||||
|
|
||||||
// Add all available fonts
|
// Add all available fonts
|
||||||
availableFonts.forEach(font => {
|
availableFonts.forEach(font => {
|
||||||
@@ -111,7 +111,7 @@ export class TypographySection implements ModalSection {
|
|||||||
.setDesc('Base font size for document text (in points)')
|
.setDesc('Base font size for document text (in points)')
|
||||||
.addSlider(slider => slider
|
.addSlider(slider => slider
|
||||||
.setLimits(8, 16, 0.5)
|
.setLimits(8, 16, 0.5)
|
||||||
.setValue(state.templateVariables.bodyFontSize || 11)
|
.setValue(Number(state.templateVariables.bodyFontSize || 11))
|
||||||
.setDynamicTooltip()
|
.setDynamicTooltip()
|
||||||
.onChange(value => {
|
.onChange(value => {
|
||||||
state.updateTemplateVariables({ bodyFontSize: value });
|
state.updateTemplateVariables({ bodyFontSize: value });
|
||||||
@@ -161,7 +161,7 @@ export class TypographySection implements ModalSection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private addFallbackBodyFonts(dropdown: any, state: ModalState, fontType: 'body' | 'heading'): void {
|
private addFallbackBodyFonts(dropdown: DropdownComponent, state: ModalState, fontType: 'body' | 'heading'): void {
|
||||||
dropdown
|
dropdown
|
||||||
.addOption('Concourse OT', 'Concourse OT')
|
.addOption('Concourse OT', 'Concourse OT')
|
||||||
.addOption('Times New Roman', 'Times New Roman')
|
.addOption('Times New Roman', 'Times New Roman')
|
||||||
@@ -179,7 +179,7 @@ export class TypographySection implements ModalSection {
|
|||||||
: state.templateVariables.headingFont;
|
: state.templateVariables.headingFont;
|
||||||
|
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(currentValue || 'Concourse OT')
|
.setValue(String(currentValue || 'Concourse OT'))
|
||||||
.onChange((value: string) => {
|
.onChange((value: string) => {
|
||||||
if (fontType === 'body') {
|
if (fontType === 'body') {
|
||||||
state.updateTemplateVariables({ bodyFont: value });
|
state.updateTemplateVariables({ bodyFont: value });
|
||||||
@@ -189,7 +189,7 @@ export class TypographySection implements ModalSection {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private addFallbackMonospaceFonts(dropdown: any, state: ModalState): void {
|
private addFallbackMonospaceFonts(dropdown: DropdownComponent, state: ModalState): void {
|
||||||
dropdown
|
dropdown
|
||||||
.addOption('Source Code Pro', 'Source Code Pro')
|
.addOption('Source Code Pro', 'Source Code Pro')
|
||||||
.addOption('Courier New', 'Courier New')
|
.addOption('Courier New', 'Courier New')
|
||||||
@@ -199,7 +199,7 @@ export class TypographySection implements ModalSection {
|
|||||||
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
|
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
|
||||||
.addOption('Liberation Mono', 'Liberation Mono')
|
.addOption('Liberation Mono', 'Liberation Mono')
|
||||||
.addOption('Ubuntu Mono', 'Ubuntu Mono')
|
.addOption('Ubuntu Mono', 'Ubuntu Mono')
|
||||||
.setValue(state.templateVariables.monospaceFont || 'Source Code Pro')
|
.setValue(String(state.templateVariables.monospaceFont || 'Source Code Pro'))
|
||||||
.onChange((value: string) => {
|
.onChange((value: string) => {
|
||||||
state.updateTemplateVariables({ monospaceFont: value });
|
state.updateTemplateVariables({ monospaceFont: value });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
|
import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes';
|
||||||
import { ExportFormat } from '../../../core/settings';
|
import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings';
|
||||||
|
|
||||||
export class ModalState implements IModalState {
|
export class ModalState implements IModalState {
|
||||||
settings: ExportConfigModalSettings;
|
settings: ExportConfigModalSettings;
|
||||||
templateVariables: Record<string, any>;
|
templateVariables: Record<string, string | number | boolean | undefined>;
|
||||||
|
|
||||||
private changeListeners: Set<() => void> = new Set();
|
private changeListeners: Set<() => void> = new Set();
|
||||||
private static readonly STORAGE_KEY = 'typst-export-modal-state';
|
private static readonly STORAGE_KEY = 'typst-export-modal-state';
|
||||||
@@ -64,7 +64,7 @@ export class ModalState implements IModalState {
|
|||||||
/**
|
/**
|
||||||
* Update template variables
|
* Update template variables
|
||||||
*/
|
*/
|
||||||
updateTemplateVariables(updates: Record<string, any>): void {
|
updateTemplateVariables(updates: Record<string, string | number | boolean | undefined>): void {
|
||||||
this.templateVariables = {
|
this.templateVariables = {
|
||||||
...this.templateVariables,
|
...this.templateVariables,
|
||||||
...updates
|
...updates
|
||||||
@@ -138,34 +138,34 @@ export class ModalState implements IModalState {
|
|||||||
/**
|
/**
|
||||||
* Reset state to defaults
|
* Reset state to defaults
|
||||||
*/
|
*/
|
||||||
reset(pluginDefaults: any): void {
|
reset(pluginDefaults: obsidianTypstPDFExportSettings): void {
|
||||||
// Reset to plugin defaults, not hardcoded defaults
|
// Reset to plugin defaults, not hardcoded defaults
|
||||||
this.settings = {
|
this.settings = {
|
||||||
...this.settings,
|
...this.settings,
|
||||||
template: pluginDefaults.template,
|
template: pluginDefaults.exportDefaults.template,
|
||||||
format: pluginDefaults.format,
|
format: pluginDefaults.exportDefaults.format,
|
||||||
outputFolder: pluginDefaults.outputFolder || 'exports',
|
outputFolder: pluginDefaults.outputFolder || 'exports',
|
||||||
templateVariables: {},
|
templateVariables: {},
|
||||||
progressPercent: 0,
|
progressPercent: 0,
|
||||||
currentOperation: '',
|
currentOperation: '',
|
||||||
isExporting: false,
|
isExporting: false,
|
||||||
canCancel: false,
|
canCancel: false,
|
||||||
openAfterExport: pluginDefaults.openAfterExport || false,
|
openAfterExport: pluginDefaults.behavior.openAfterExport || false,
|
||||||
preserveFolderStructure: pluginDefaults.preserveFolderStructure || false
|
preserveFolderStructure: pluginDefaults.behavior.preserveFolderStructure || false
|
||||||
};
|
};
|
||||||
|
|
||||||
this.templateVariables = {
|
this.templateVariables = {
|
||||||
pageSize: pluginDefaults.pageSize,
|
pageSize: pluginDefaults.exportDefaults.pageSize,
|
||||||
orientation: pluginDefaults.orientation,
|
orientation: pluginDefaults.exportDefaults.orientation,
|
||||||
flipped: pluginDefaults.orientation === 'landscape',
|
flipped: pluginDefaults.exportDefaults.orientation === 'landscape',
|
||||||
marginTop: pluginDefaults.marginTop,
|
marginTop: pluginDefaults.exportDefaults.marginTop,
|
||||||
marginBottom: pluginDefaults.marginBottom,
|
marginBottom: pluginDefaults.exportDefaults.marginBottom,
|
||||||
marginLeft: pluginDefaults.marginLeft,
|
marginLeft: pluginDefaults.exportDefaults.marginLeft,
|
||||||
marginRight: pluginDefaults.marginRight,
|
marginRight: pluginDefaults.exportDefaults.marginRight,
|
||||||
bodyFont: pluginDefaults.bodyFont,
|
bodyFont: pluginDefaults.exportDefaults.bodyFont,
|
||||||
headingFont: pluginDefaults.headingFont,
|
headingFont: pluginDefaults.exportDefaults.headingFont,
|
||||||
monospaceFont: pluginDefaults.monospaceFont,
|
monospaceFont: pluginDefaults.exportDefaults.monospaceFont,
|
||||||
bodyFontSize: pluginDefaults.bodyFontSize
|
bodyFontSize: pluginDefaults.exportDefaults.bodyFontSize
|
||||||
};
|
};
|
||||||
|
|
||||||
this.settings.templateVariables = this.templateVariables;
|
this.settings.templateVariables = this.templateVariables;
|
||||||
@@ -198,7 +198,7 @@ export class ModalState implements IModalState {
|
|||||||
/**
|
/**
|
||||||
* Load state from localStorage
|
* Load state from localStorage
|
||||||
*/
|
*/
|
||||||
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, any> } | null {
|
private loadFromStorage(): { settings: Partial<ExportConfigModalSettings>, templateVariables: Record<string, string | number | boolean> } | null {
|
||||||
try {
|
try {
|
||||||
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
|
const saved = localStorage.getItem(ModalState.STORAGE_KEY);
|
||||||
if (saved) {
|
if (saved) {
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
|
||||||
|
|
||||||
// Email block styling function
|
// Email block styling function
|
||||||
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
block(
|
block(
|
||||||
|
|||||||
@@ -0,0 +1,414 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
|
||||||
|
|
||||||
|
// Email block styling function - elegant book style
|
||||||
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 18pt,
|
||||||
|
fill: rgb("#fafaf9"),
|
||||||
|
stroke: 1pt + rgb("#d6d3d1"),
|
||||||
|
radius: 0pt, // Square corners for book style
|
||||||
|
breakable: true
|
||||||
|
)[
|
||||||
|
#text(size: 1em, weight: "medium", style: "italic", fill: rgb("#57534e"))[Correspondence]
|
||||||
|
#v(0.4em)
|
||||||
|
#grid(
|
||||||
|
columns: (auto, 1fr),
|
||||||
|
row-gutter: 8pt,
|
||||||
|
column-gutter: 16pt,
|
||||||
|
if from != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#78716c"))[From:]
|
||||||
|
] else [],
|
||||||
|
if from != none [
|
||||||
|
#text(size: 0.9em)[#from]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#78716c"))[To:]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(size: 0.9em)[#to]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#78716c"))[Subject:]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(size: 0.9em, style: "italic")[#subject]
|
||||||
|
] else [],
|
||||||
|
if date != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#78716c"))[Date:]
|
||||||
|
] else [],
|
||||||
|
if date != none [
|
||||||
|
#text(size: 0.9em)[#date]
|
||||||
|
] else [],
|
||||||
|
)
|
||||||
|
#if body != none [
|
||||||
|
#v(0.6em)
|
||||||
|
#line(length: 100%, stroke: 0.5pt + rgb("#d6d3d1"))
|
||||||
|
#v(0.6em)
|
||||||
|
#block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 0pt,
|
||||||
|
)[
|
||||||
|
#text(size: 0.9em)[#body]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drop cap function for chapter openings
|
||||||
|
#let drop-cap(text-content) = {
|
||||||
|
if type(text-content) != str {
|
||||||
|
text-content
|
||||||
|
} else {
|
||||||
|
let first-letter = text-content.slice(0, 1)
|
||||||
|
let rest = text-content.slice(1)
|
||||||
|
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 0pt,
|
||||||
|
)[
|
||||||
|
#grid(
|
||||||
|
columns: (auto, 1fr),
|
||||||
|
column-gutter: 8pt,
|
||||||
|
align: (left + top, left + top),
|
||||||
|
// Large decorative first letter
|
||||||
|
text(
|
||||||
|
size: 48pt,
|
||||||
|
weight: "bold",
|
||||||
|
font: ("Baskerville", "Times New Roman"),
|
||||||
|
fill: rgb("#7c2d12")
|
||||||
|
)[#first-letter],
|
||||||
|
// Rest of the paragraph
|
||||||
|
text(size: 11pt)[#rest]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decorative section divider
|
||||||
|
#let section-divider = {
|
||||||
|
v(1em)
|
||||||
|
align(center)[
|
||||||
|
#text(20pt, fill: rgb("#a8a29e"))[❦ ❦ ❦]
|
||||||
|
]
|
||||||
|
v(1em)
|
||||||
|
}
|
||||||
|
|
||||||
|
#let conf(
|
||||||
|
title: none,
|
||||||
|
authors: (),
|
||||||
|
date: none,
|
||||||
|
lang: "en",
|
||||||
|
region: "US",
|
||||||
|
paper: "a4",
|
||||||
|
margin: (inside: 3cm, outside: 2.5cm, top: 2.5cm, bottom: 2.5cm),
|
||||||
|
cols: 1,
|
||||||
|
font: ("Baskerville", "Times New Roman", "Times"),
|
||||||
|
fontsize: 11pt,
|
||||||
|
sectionnumbering: none, // Chapters typically don't use numbered sections
|
||||||
|
pagenumbering: "1",
|
||||||
|
// Support for UI-configurable options
|
||||||
|
heading_font: none,
|
||||||
|
monospace_font: none,
|
||||||
|
margin_top: none,
|
||||||
|
margin_right: none,
|
||||||
|
margin_bottom: none,
|
||||||
|
margin_left: none,
|
||||||
|
orientation: "portrait",
|
||||||
|
export_format: none,
|
||||||
|
doc,
|
||||||
|
) = {
|
||||||
|
// Set document properties
|
||||||
|
set document(
|
||||||
|
title: title
|
||||||
|
// Skip author in document metadata to avoid type issues
|
||||||
|
)
|
||||||
|
|
||||||
|
// Book-style alternating margins for binding
|
||||||
|
let page-margin = if margin_top != none {
|
||||||
|
(
|
||||||
|
top: if margin_top != none { margin_top } else { 2.5cm },
|
||||||
|
right: if margin_right != none { margin_right } else { 2.5cm },
|
||||||
|
bottom: if margin_bottom != none { margin_bottom } else { 2.5cm },
|
||||||
|
left: if margin_left != none { margin_left } else { 3cm },
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
margin
|
||||||
|
}
|
||||||
|
|
||||||
|
// Book page layout with alternating margins
|
||||||
|
set page(
|
||||||
|
paper: paper,
|
||||||
|
flipped: orientation == "landscape",
|
||||||
|
margin: page-margin,
|
||||||
|
..if export_format == "single-page" and orientation == "landscape" {
|
||||||
|
(width: auto,)
|
||||||
|
} else if export_format == "single-page" {
|
||||||
|
(height: auto,)
|
||||||
|
} else {
|
||||||
|
(:)
|
||||||
|
},
|
||||||
|
numbering: pagenumbering,
|
||||||
|
// Running headers for book style
|
||||||
|
header: context {
|
||||||
|
let page-num = counter(page).get().first()
|
||||||
|
if page-num > 1 [
|
||||||
|
#set text(size: 9pt, style: "italic", fill: rgb("#6b7280"))
|
||||||
|
#if calc.even(page-num) [
|
||||||
|
// Even pages: book title on left
|
||||||
|
#if title != none [#title] else [Document]
|
||||||
|
#h(1fr)
|
||||||
|
#page-num
|
||||||
|
] else [
|
||||||
|
// Odd pages: chapter title on right
|
||||||
|
#page-num
|
||||||
|
#h(1fr)
|
||||||
|
#context {
|
||||||
|
let headings = query(heading.where(level: 1))
|
||||||
|
if headings.len() > 0 [
|
||||||
|
#headings.last().body
|
||||||
|
] else [
|
||||||
|
Chapter
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
#v(-0.5em)
|
||||||
|
#line(length: 100%, stroke: 0.5pt + rgb("#d1d5db"))
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Classic book typography - serif fonts
|
||||||
|
let body-font = if font != none and type(font) == str {
|
||||||
|
(font, "Baskerville", "Times New Roman", "Times")
|
||||||
|
} else if font != none {
|
||||||
|
font
|
||||||
|
} else {
|
||||||
|
("Baskerville", "Times New Roman", "Times")
|
||||||
|
}
|
||||||
|
|
||||||
|
let body-fontsize = fontsize
|
||||||
|
|
||||||
|
set text(
|
||||||
|
font: body-font,
|
||||||
|
size: body-fontsize,
|
||||||
|
lang: lang,
|
||||||
|
region: region,
|
||||||
|
fill: rgb("#1f2937")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Book-style paragraph settings with first-line indent
|
||||||
|
set par(
|
||||||
|
justify: true,
|
||||||
|
leading: 0.65em,
|
||||||
|
spacing: 0.65em,
|
||||||
|
first-line-indent: 1.2em
|
||||||
|
)
|
||||||
|
|
||||||
|
// Chapter and section numbering
|
||||||
|
if sectionnumbering != none {
|
||||||
|
set heading(numbering: sectionnumbering)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Book-style heading fonts (same as body for classic look)
|
||||||
|
let heading-font = if heading_font != none and type(heading_font) == str {
|
||||||
|
(heading_font, "Baskerville", "Times New Roman", "Times")
|
||||||
|
} else if heading_font != none {
|
||||||
|
heading_font
|
||||||
|
} else {
|
||||||
|
("Baskerville", "Times New Roman", "Times")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chapter styling (Level 1 headings)
|
||||||
|
show heading.where(level: 1): it => {
|
||||||
|
pagebreak(weak: true)
|
||||||
|
v(3cm)
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
above: 0em,
|
||||||
|
below: 2em,
|
||||||
|
)[
|
||||||
|
#set align(center)
|
||||||
|
#set par(first-line-indent: 0em)
|
||||||
|
|
||||||
|
// Chapter number (if numbered)
|
||||||
|
#if it.numbering != none [
|
||||||
|
#text(
|
||||||
|
size: 14pt,
|
||||||
|
weight: "regular",
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#6b7280"),
|
||||||
|
tracking: 2pt
|
||||||
|
)[CHAPTER #counter(heading).display("I")]
|
||||||
|
#v(1em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Chapter title
|
||||||
|
#text(
|
||||||
|
size: 24pt,
|
||||||
|
weight: "bold",
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#111827")
|
||||||
|
)[#it.body]
|
||||||
|
|
||||||
|
#v(1.5em)
|
||||||
|
|
||||||
|
// Decorative flourish
|
||||||
|
#text(16pt, fill: rgb("#9ca3af"))[❦]
|
||||||
|
|
||||||
|
#v(2em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Reset paragraph indentation for first paragraph after chapter
|
||||||
|
par(first-line-indent: 0em)[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section styling (Level 2 headings)
|
||||||
|
show heading.where(level: 2): it => {
|
||||||
|
v(1.5em)
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
below: 1em,
|
||||||
|
)[
|
||||||
|
#set align(center)
|
||||||
|
#set par(first-line-indent: 0em)
|
||||||
|
#text(
|
||||||
|
size: 16pt,
|
||||||
|
weight: "semibold",
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#374151")
|
||||||
|
)[#it.body]
|
||||||
|
#v(0.5em)
|
||||||
|
#line(length: 30%, stroke: 1pt + rgb("#9ca3af"))
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subsection styling (Level 3 headings)
|
||||||
|
show heading.where(level: 3): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 0.8em,
|
||||||
|
above: 1.2em,
|
||||||
|
)[
|
||||||
|
#set par(first-line-indent: 0em)
|
||||||
|
#text(
|
||||||
|
size: 13pt,
|
||||||
|
weight: "medium",
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#4b5563"),
|
||||||
|
style: "italic"
|
||||||
|
)[#it.body]
|
||||||
|
]
|
||||||
|
|
||||||
|
// Code styling (rare in books but sometimes needed)
|
||||||
|
let code-font = if monospace_font != none and type(monospace_font) == str {
|
||||||
|
(monospace_font, "Courier New", "Monaco")
|
||||||
|
} else {
|
||||||
|
("Courier New", "Monaco")
|
||||||
|
}
|
||||||
|
|
||||||
|
show raw: set text(font: code-font, size: body-fontsize * 0.9)
|
||||||
|
|
||||||
|
show raw.where(block: true): block.with(
|
||||||
|
width: 100%,
|
||||||
|
fill: rgb("#f9fafb"),
|
||||||
|
inset: 12pt,
|
||||||
|
radius: 0pt,
|
||||||
|
stroke: (left: 3pt + rgb("#d1d5db")),
|
||||||
|
breakable: true,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Enhanced quote styling for books
|
||||||
|
show quote: it => {
|
||||||
|
set par(first-line-indent: 0em)
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: (left: 2em, right: 2em, top: 1em, bottom: 1em),
|
||||||
|
)[
|
||||||
|
#set text(style: "italic", size: body-fontsize * 0.95)
|
||||||
|
#set par(leading: 0.7em)
|
||||||
|
#it.body
|
||||||
|
#if it.attribution != none [
|
||||||
|
#v(0.5em)
|
||||||
|
#align(right)[
|
||||||
|
#text(size: body-fontsize * 0.9, style: "normal")[— #it.attribution]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Book title page (if title provided)
|
||||||
|
if title != none and title != "" [
|
||||||
|
#set align(center)
|
||||||
|
#set par(first-line-indent: 0em)
|
||||||
|
|
||||||
|
#v(4cm)
|
||||||
|
|
||||||
|
// Main title
|
||||||
|
#text(
|
||||||
|
size: 28pt,
|
||||||
|
weight: "bold",
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#111827")
|
||||||
|
)[#title]
|
||||||
|
|
||||||
|
#v(2em)
|
||||||
|
|
||||||
|
// Decorative line
|
||||||
|
#line(length: 40%, stroke: 1pt + rgb("#6b7280"))
|
||||||
|
|
||||||
|
#v(2em)
|
||||||
|
|
||||||
|
// Authors
|
||||||
|
#if authors != () and authors != none [
|
||||||
|
#for (i, author) in authors.enumerate() [
|
||||||
|
#if author.name != none and author.name != "" [
|
||||||
|
#text(
|
||||||
|
size: 16pt,
|
||||||
|
font: heading-font,
|
||||||
|
fill: rgb("#374151")
|
||||||
|
)[#author.name]
|
||||||
|
#if i < authors.len() - 1 [
|
||||||
|
#v(0.5em)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
#v(2em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Date
|
||||||
|
#if date != none [
|
||||||
|
#text(
|
||||||
|
size: 12pt,
|
||||||
|
style: "italic",
|
||||||
|
fill: rgb("#6b7280")
|
||||||
|
)[#date]
|
||||||
|
]
|
||||||
|
|
||||||
|
#v(1fr)
|
||||||
|
|
||||||
|
#pagebreak()
|
||||||
|
|
||||||
|
// Copyright page (if authors provided)
|
||||||
|
#if authors != () and authors != none [
|
||||||
|
#v(1fr)
|
||||||
|
#set align(left)
|
||||||
|
#set text(size: 9pt, fill: rgb("#6b7280"))
|
||||||
|
#set par(first-line-indent: 0em, leading: 0.6em)
|
||||||
|
|
||||||
|
Copyright © #if date != none [#date] else [2024] by #if authors != () and authors != none [
|
||||||
|
#for (i, author) in authors.enumerate() [
|
||||||
|
#if author.name != none and author.name != "" [#author.name]#if i < authors.len() - 1 [, ]
|
||||||
|
]
|
||||||
|
] else [Author]
|
||||||
|
|
||||||
|
#v(0.5em)
|
||||||
|
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law.
|
||||||
|
|
||||||
|
#pagebreak()
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
// Document content
|
||||||
|
doc
|
||||||
|
}
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
|
||||||
|
|
||||||
// Email block styling function
|
// Email block styling function
|
||||||
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
block(
|
block(
|
||||||
|
|||||||
+10
-7
@@ -1,3 +1,6 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
|
||||||
|
|
||||||
// Email block styling function - compact for single page
|
// Email block styling function - compact for single page
|
||||||
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
block(
|
block(
|
||||||
@@ -146,7 +149,7 @@
|
|||||||
width: 100%,
|
width: 100%,
|
||||||
below: 1em,
|
below: 1em,
|
||||||
above: 1.2em,
|
above: 1.2em,
|
||||||
fill: rgb("#2563eb"),
|
fill: rgb("#0d9488"),
|
||||||
inset: (x: 12pt, y: 8pt),
|
inset: (x: 12pt, y: 8pt),
|
||||||
radius: 6pt,
|
radius: 6pt,
|
||||||
)[
|
)[
|
||||||
@@ -159,9 +162,9 @@
|
|||||||
below: 0.6em,
|
below: 0.6em,
|
||||||
above: 1em,
|
above: 1em,
|
||||||
inset: (bottom: 3pt),
|
inset: (bottom: 3pt),
|
||||||
stroke: (bottom: 2pt + rgb("#2563eb")),
|
stroke: (bottom: 2pt + rgb("#0d9488")),
|
||||||
)[
|
)[
|
||||||
#set text(font: heading-font, size: heading-fontsize * 0.85, weight: "semibold", fill: rgb("#1e40af"))
|
#set text(font: heading-font, size: heading-fontsize * 0.85, weight: "semibold", fill: rgb("#0f766e"))
|
||||||
#it.body
|
#it.body
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -187,7 +190,7 @@
|
|||||||
if title != none and title != "" [
|
if title != none and title != "" [
|
||||||
#block(
|
#block(
|
||||||
width: 100%,
|
width: 100%,
|
||||||
fill: gradient.linear(rgb("#1e40af"), rgb("#3b82f6"), angle: 45deg),
|
fill: gradient.linear(rgb("#0f766e"), rgb("#14b8a6"), angle: 45deg),
|
||||||
inset: 16pt,
|
inset: 16pt,
|
||||||
radius: (top: 8pt),
|
radius: (top: 8pt),
|
||||||
)[
|
)[
|
||||||
@@ -201,7 +204,7 @@
|
|||||||
#v(0.3em)
|
#v(0.3em)
|
||||||
#for author in authors [
|
#for author in authors [
|
||||||
#if author.name != none and author.name != "" [
|
#if author.name != none and author.name != "" [
|
||||||
#text(14pt, fill: rgb("#dbeafe"))[#author.name]
|
#text(14pt, fill: rgb("#ccfbf1"))[#author.name]
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
@@ -209,7 +212,7 @@
|
|||||||
// Contact info sidebar
|
// Contact info sidebar
|
||||||
align(right + top)[
|
align(right + top)[
|
||||||
#if date != none [
|
#if date != none [
|
||||||
#text(11pt, fill: rgb("#dbeafe"), style: "italic")[#date]
|
#text(11pt, fill: rgb("#ccfbf1"), style: "italic")[#date]
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -230,7 +233,7 @@
|
|||||||
if authors != () and authors != none [
|
if authors != () and authors != none [
|
||||||
#for author in authors [
|
#for author in authors [
|
||||||
#if author.name != none and author.name != "" [
|
#if author.name != none and author.name != "" [
|
||||||
#text(14pt, weight: "semibold", fill: rgb("#1e40af"))[#author.name]
|
#text(14pt, weight: "semibold", fill: rgb("#0f766e"))[#author.name]
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
] else [],
|
] else [],
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
|
||||||
|
|
||||||
// Email block styling function
|
// Email block styling function
|
||||||
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
block(
|
block(
|
||||||
|
|||||||
@@ -0,0 +1,376 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
|
||||||
|
|
||||||
|
// Email block styling function with modern sidebar-appropriate styling
|
||||||
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 14pt,
|
||||||
|
fill: rgb("#f8fafc"),
|
||||||
|
stroke: 1pt + rgb("#e2e8f0"),
|
||||||
|
radius: 8pt,
|
||||||
|
breakable: true
|
||||||
|
)[
|
||||||
|
#text(size: 0.9em, weight: "semibold", fill: rgb("#475569"))[Email]
|
||||||
|
#v(0.3em)
|
||||||
|
#grid(
|
||||||
|
columns: (auto, 1fr),
|
||||||
|
row-gutter: 6pt,
|
||||||
|
column-gutter: 12pt,
|
||||||
|
if from != none [
|
||||||
|
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[From:]
|
||||||
|
] else [],
|
||||||
|
if from != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#1e293b"))[#from]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[To:]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(size: 0.9em, fill: rgb("#1e293b"))[#to]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(style: "italic", size: 0.85em, fill: rgb("#64748b"))[Subject:]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(size: 0.9em, weight: "medium", fill: rgb("#0f172a"))[#subject]
|
||||||
|
] else [],
|
||||||
|
)
|
||||||
|
#if body != none [
|
||||||
|
#v(0.5em)
|
||||||
|
#block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 8pt,
|
||||||
|
fill: rgb("#ffffff"),
|
||||||
|
radius: 4pt,
|
||||||
|
stroke: 0.5pt + rgb("#e2e8f0"),
|
||||||
|
)[
|
||||||
|
#text(size: 0.85em, fill: rgb("#374151"))[#body]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sidebar navigation component
|
||||||
|
#let sidebar-nav(title: none, authors: (), date: none, body-fontsize: 11pt, pagenumbering: "1") = {
|
||||||
|
let sidebar-bg = gradient.linear(
|
||||||
|
rgb("#dc2626"),
|
||||||
|
rgb("#ea580c"),
|
||||||
|
rgb("#f97316"),
|
||||||
|
angle: 160deg
|
||||||
|
)
|
||||||
|
|
||||||
|
place(
|
||||||
|
top + left,
|
||||||
|
dx: 0pt,
|
||||||
|
dy: 0pt,
|
||||||
|
block(
|
||||||
|
width: 4.5cm,
|
||||||
|
height: 27cm,
|
||||||
|
fill: sidebar-bg,
|
||||||
|
inset: 18pt,
|
||||||
|
radius: (right: 12pt),
|
||||||
|
)[
|
||||||
|
#set text(fill: white, size: body-fontsize * 0.9)
|
||||||
|
|
||||||
|
// Document title in sidebar
|
||||||
|
#if title != none and title != "" [
|
||||||
|
#text(15pt, weight: "bold", tracking: 0.5pt)[#upper(title)]
|
||||||
|
#v(1.2em)
|
||||||
|
#line(length: 100%, stroke: 1.5pt + rgb("#dbeafe"))
|
||||||
|
#v(1.2em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Author information in sidebar
|
||||||
|
#if authors != () and authors != none [
|
||||||
|
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[AUTHORS]
|
||||||
|
#v(0.5em)
|
||||||
|
#for (i, author) in authors.enumerate() [
|
||||||
|
#if author.name != none and author.name != "" [
|
||||||
|
#text(10pt, weight: "regular")[#author.name]
|
||||||
|
#if i < authors.len() - 1 [#v(0.3em)]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
#v(1.5em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Date in sidebar
|
||||||
|
#if date != none [
|
||||||
|
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[DATE]
|
||||||
|
#v(0.5em)
|
||||||
|
#text(10pt)[#date]
|
||||||
|
#v(1.5em)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Enhanced Table of contents in sidebar
|
||||||
|
#text(9pt, weight: "medium", fill: rgb("#dbeafe"), tracking: 1pt)[CONTENTS]
|
||||||
|
#v(0.7em)
|
||||||
|
|
||||||
|
#context {
|
||||||
|
let headings-1 = query(heading.where(level: 1))
|
||||||
|
let headings-2 = query(heading.where(level: 2))
|
||||||
|
|
||||||
|
for h1 in headings-1 {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: (y: 0.2em),
|
||||||
|
fill: rgb(255, 255, 255, 10%),
|
||||||
|
radius: 3pt
|
||||||
|
)[
|
||||||
|
#text(9pt, weight: "semibold")[#h1.body]
|
||||||
|
]
|
||||||
|
|
||||||
|
// Show level 2 headings under this level 1
|
||||||
|
for h2 in headings-2 {
|
||||||
|
if h2.location().page() >= h1.location().page() {
|
||||||
|
text(8pt, fill: rgb("#dbeafe"))[ • #h2.body]
|
||||||
|
v(0.15em)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v(0.4em)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#v(1fr)
|
||||||
|
|
||||||
|
// Progress indicator
|
||||||
|
#context {
|
||||||
|
let current-page = counter(page).get().first()
|
||||||
|
let total-pages = counter(page).final().first()
|
||||||
|
let progress = current-page / total-pages * 100
|
||||||
|
|
||||||
|
text(8pt, fill: rgb("#dbeafe"))[Progress]
|
||||||
|
v(0.3em)
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
height: 4pt,
|
||||||
|
fill: rgb(255, 255, 255, 20%),
|
||||||
|
radius: 2pt
|
||||||
|
)[
|
||||||
|
#place(
|
||||||
|
left,
|
||||||
|
block(
|
||||||
|
width: progress * 1%,
|
||||||
|
height: 100%,
|
||||||
|
fill: rgb("#fbbf24"),
|
||||||
|
radius: 2pt
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
v(0.5em)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page number at bottom of sidebar
|
||||||
|
#if pagenumbering != none [
|
||||||
|
#line(length: 100%, stroke: 1pt + rgb("#dbeafe"))
|
||||||
|
#v(0.7em)
|
||||||
|
#set align(center)
|
||||||
|
#context {
|
||||||
|
let current = counter(page).get().first()
|
||||||
|
let total = counter(page).final().first()
|
||||||
|
text(13pt, weight: "bold")[#current]
|
||||||
|
v(0.2em)
|
||||||
|
text(8pt, fill: rgb("#dbeafe"))[of #total]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#let conf(
|
||||||
|
title: none,
|
||||||
|
authors: (),
|
||||||
|
date: none,
|
||||||
|
lang: "en",
|
||||||
|
region: "US",
|
||||||
|
paper: "a4",
|
||||||
|
margin: (left: 8cm, right: 1.5cm, top: 1.5cm, bottom: 1.5cm),
|
||||||
|
cols: 1,
|
||||||
|
font: ("Inter", "SF Pro", "Helvetica Neue", "Arial"),
|
||||||
|
fontsize: 11pt,
|
||||||
|
sectionnumbering: "1.",
|
||||||
|
pagenumbering: "1",
|
||||||
|
// Support for UI-configurable options
|
||||||
|
heading_font: none,
|
||||||
|
monospace_font: none,
|
||||||
|
margin_top: none,
|
||||||
|
margin_right: none,
|
||||||
|
margin_bottom: none,
|
||||||
|
margin_left: none,
|
||||||
|
orientation: "portrait",
|
||||||
|
export_format: none,
|
||||||
|
doc,
|
||||||
|
) = {
|
||||||
|
// Set document properties
|
||||||
|
set document(
|
||||||
|
title: title
|
||||||
|
)
|
||||||
|
|
||||||
|
// Sidebar layout with fixed left margin for floating sidebar
|
||||||
|
let page-margin = (
|
||||||
|
top: if margin_top != none { margin_top } else { 1.5cm },
|
||||||
|
right: if margin_right != none { margin_right } else { 1.5cm },
|
||||||
|
bottom: if margin_bottom != none { margin_bottom } else { 1.5cm },
|
||||||
|
left: 5cm, // Fixed for sidebar - not configurable
|
||||||
|
)
|
||||||
|
|
||||||
|
// Page layout optimized for sidebar
|
||||||
|
set page(
|
||||||
|
paper: paper,
|
||||||
|
flipped: orientation == "landscape",
|
||||||
|
margin: page-margin,
|
||||||
|
..if export_format == "single-page" and orientation == "landscape" {
|
||||||
|
(width: auto,)
|
||||||
|
} else if export_format == "single-page" {
|
||||||
|
(height: auto,)
|
||||||
|
} else {
|
||||||
|
(:)
|
||||||
|
},
|
||||||
|
numbering: pagenumbering,
|
||||||
|
background: {
|
||||||
|
// Add the floating sidebar
|
||||||
|
sidebar-nav(
|
||||||
|
title: title,
|
||||||
|
authors: authors,
|
||||||
|
date: date,
|
||||||
|
body-fontsize: fontsize,
|
||||||
|
pagenumbering: pagenumbering
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Modern sans-serif typography
|
||||||
|
let body-font = if font != none and type(font) == str {
|
||||||
|
(font, "Inter", "SF Pro", "Helvetica Neue", "Arial")
|
||||||
|
} else {
|
||||||
|
font
|
||||||
|
}
|
||||||
|
|
||||||
|
let body-fontsize = fontsize
|
||||||
|
|
||||||
|
set text(
|
||||||
|
font: body-font,
|
||||||
|
size: body-fontsize,
|
||||||
|
lang: lang,
|
||||||
|
region: region,
|
||||||
|
fill: rgb("#111827")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Clean paragraph settings
|
||||||
|
set par(justify: true, leading: 0.65em, spacing: 0.8em)
|
||||||
|
|
||||||
|
// Set heading numbering
|
||||||
|
if sectionnumbering != none {
|
||||||
|
set heading(numbering: sectionnumbering)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Modern heading fonts
|
||||||
|
let heading-font = if heading_font != none and type(heading_font) == str {
|
||||||
|
(heading_font, "Inter", "SF Pro", "Helvetica Neue", "Arial")
|
||||||
|
} else if heading_font != none {
|
||||||
|
heading_font
|
||||||
|
} else {
|
||||||
|
("Inter", "SF Pro", "Helvetica Neue", "Arial")
|
||||||
|
}
|
||||||
|
|
||||||
|
let heading-fontsize = body-fontsize * 1.3
|
||||||
|
|
||||||
|
// Color palette coordinated with orange-red sidebar
|
||||||
|
let primary-color = rgb("#dc2626")
|
||||||
|
let secondary-color = rgb("#ea580c")
|
||||||
|
let accent-color = rgb("#f97316")
|
||||||
|
let text-color = rgb("#374151")
|
||||||
|
|
||||||
|
show heading.where(level: 1): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 1.4em,
|
||||||
|
above: 2em,
|
||||||
|
breakable: false,
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize * 1.2, weight: "bold", fill: primary-color)
|
||||||
|
#it
|
||||||
|
#v(0.5em)
|
||||||
|
#line(length: 100%, stroke: 2pt + gradient.linear(primary-color, secondary-color))
|
||||||
|
]
|
||||||
|
|
||||||
|
show heading.where(level: 2): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 1em,
|
||||||
|
above: 1.6em,
|
||||||
|
inset: (left: 0pt, bottom: 8pt),
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize, weight: "semibold", fill: text-color)
|
||||||
|
#it
|
||||||
|
#v(0.3em)
|
||||||
|
#line(length: 40%, stroke: 1pt + primary-color)
|
||||||
|
]
|
||||||
|
|
||||||
|
show heading.where(level: 3): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 0.8em,
|
||||||
|
above: 1.2em,
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize * 0.85, weight: "medium", fill: accent-color)
|
||||||
|
#it
|
||||||
|
]
|
||||||
|
|
||||||
|
// Enhanced code styling
|
||||||
|
let code-font = if monospace_font != none and type(monospace_font) == str {
|
||||||
|
(monospace_font, "SF Mono", "JetBrains Mono", "Courier New")
|
||||||
|
} else {
|
||||||
|
("SF Mono", "JetBrains Mono", "Courier New")
|
||||||
|
}
|
||||||
|
|
||||||
|
show raw: set text(font: code-font, size: body-fontsize * 0.9, fill: rgb("#374151"))
|
||||||
|
|
||||||
|
show raw.where(block: true): block.with(
|
||||||
|
width: 100%,
|
||||||
|
fill: rgb("#f8fafc"),
|
||||||
|
stroke: 1pt + rgb("#e2e8f0"),
|
||||||
|
inset: 14pt,
|
||||||
|
radius: 6pt,
|
||||||
|
breakable: true,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Enhanced list styling
|
||||||
|
set list(indent: 1em, body-indent: 0.5em)
|
||||||
|
show list: it => {
|
||||||
|
set text(fill: rgb("#374151"))
|
||||||
|
it
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enhanced quote styling
|
||||||
|
show quote: it => block(
|
||||||
|
width: 100%,
|
||||||
|
fill: rgb("#f1f5f9"),
|
||||||
|
inset: (left: 16pt, right: 16pt, top: 12pt, bottom: 12pt),
|
||||||
|
stroke: (left: 4pt + accent-color),
|
||||||
|
radius: (right: 6pt),
|
||||||
|
)[
|
||||||
|
#set text(style: "italic", fill: rgb("#4b5563"))
|
||||||
|
#it
|
||||||
|
]
|
||||||
|
|
||||||
|
// Figure styling
|
||||||
|
show figure: it => block(
|
||||||
|
width: 100%,
|
||||||
|
breakable: false,
|
||||||
|
)[
|
||||||
|
#set align(center)
|
||||||
|
#it.body
|
||||||
|
#if it.caption != none [
|
||||||
|
#v(0.7em)
|
||||||
|
#text(
|
||||||
|
size: body-fontsize * 0.9,
|
||||||
|
style: "italic",
|
||||||
|
fill: rgb("#6b7280")
|
||||||
|
)[
|
||||||
|
Figure #counter(figure).display("1"): #it.caption
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
// Don't show title/authors in main content since they're in sidebar
|
||||||
|
// Just start with the document content
|
||||||
|
doc
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
// Horizontal rule definition for Pandoc compatibility
|
||||||
|
#let horizontalrule = pad(y: 11pt, (line(stroke: 2pt + gray, length: 75%)))
|
||||||
|
|
||||||
|
// Email block styling function
|
||||||
|
#let email-block(from: none, to: none, subject: none, date: none, body) = {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 16pt,
|
||||||
|
stroke: 0.5pt + blue,
|
||||||
|
radius: 5pt,
|
||||||
|
breakable: true
|
||||||
|
)[
|
||||||
|
#grid(
|
||||||
|
columns: (auto, 1fr),
|
||||||
|
row-gutter: 13pt,
|
||||||
|
column-gutter: 8pt,
|
||||||
|
if from != none [
|
||||||
|
#text(style: "italic", size: 1em)[From:]
|
||||||
|
] else [],
|
||||||
|
if from != none [
|
||||||
|
#text(size: 1em)[#from]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(style: "italic", size: 1em)[To:]
|
||||||
|
] else [],
|
||||||
|
if to != none [
|
||||||
|
#text(size: 1em)[#to]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(style: "italic", size: 1em)[Subject:]
|
||||||
|
] else [],
|
||||||
|
if subject != none [
|
||||||
|
#text(size: 1em)[#subject]
|
||||||
|
] else [],
|
||||||
|
if date != none [
|
||||||
|
#text(style: "italic", size: 1em)[Date:]
|
||||||
|
] else [],
|
||||||
|
if date != none [
|
||||||
|
#text(size: 1em)[#date]
|
||||||
|
] else [],
|
||||||
|
)
|
||||||
|
#if body != none [
|
||||||
|
#block(
|
||||||
|
width: 100%,
|
||||||
|
inset: (left: 5pt, top: 6pt),
|
||||||
|
stroke: (left: 2pt + gray),
|
||||||
|
)[
|
||||||
|
#body
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#let conf(
|
||||||
|
title: none,
|
||||||
|
authors: (),
|
||||||
|
date: none,
|
||||||
|
lang: "en",
|
||||||
|
region: "US",
|
||||||
|
paper: "a4",
|
||||||
|
margin: (x: 2.5cm, y: 2cm),
|
||||||
|
cols: 2,
|
||||||
|
font: ("Libertinus Serif", "Times New Roman", "Times"),
|
||||||
|
fontsize: 10pt,
|
||||||
|
sectionnumbering: "1.",
|
||||||
|
pagenumbering: "1",
|
||||||
|
// Support for UI-configurable options
|
||||||
|
heading_font: none,
|
||||||
|
monospace_font: none,
|
||||||
|
margin_top: none,
|
||||||
|
margin_right: none,
|
||||||
|
margin_bottom: none,
|
||||||
|
margin_left: none,
|
||||||
|
orientation: "portrait",
|
||||||
|
export_format: none,
|
||||||
|
doc,
|
||||||
|
) = {
|
||||||
|
// Set document properties
|
||||||
|
set document(
|
||||||
|
title: title
|
||||||
|
// Skip author in document metadata to avoid type issues
|
||||||
|
)
|
||||||
|
|
||||||
|
// Use UI-configured margins if available, otherwise fall back to template defaults
|
||||||
|
let page-margin = if margin_top != none {
|
||||||
|
(
|
||||||
|
top: if margin_top != none { margin_top } else { 2cm },
|
||||||
|
right: if margin_right != none { margin_right } else { 2.5cm },
|
||||||
|
bottom: if margin_bottom != none { margin_bottom } else { 2cm },
|
||||||
|
left: if margin_left != none { margin_left } else { 2.5cm },
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
margin
|
||||||
|
}
|
||||||
|
|
||||||
|
// globally set the gutter between page columns
|
||||||
|
set columns(gutter: 4% + 11pt)
|
||||||
|
|
||||||
|
// Single-column page layout
|
||||||
|
// Two-column page layout with configurable orientation
|
||||||
|
set page(
|
||||||
|
paper: paper,
|
||||||
|
flipped: orientation == "landscape",
|
||||||
|
margin: page-margin,
|
||||||
|
columns: 2,
|
||||||
|
..if export_format == "single-page" and orientation == "landscape" {
|
||||||
|
(width: auto,)
|
||||||
|
} else if export_format == "single-page" {
|
||||||
|
(height: auto,)
|
||||||
|
} else {
|
||||||
|
(:)
|
||||||
|
},
|
||||||
|
numbering: pagenumbering,
|
||||||
|
header: context {
|
||||||
|
if counter(page).get().first() > 1 [
|
||||||
|
#h(1fr) #counter(page).display("1")
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Academic typography - serif font with good readability
|
||||||
|
let body-font = if font != none and type(font) == str {
|
||||||
|
(font, "Libertinus Serif", "Times New Roman", "Times")
|
||||||
|
} else {
|
||||||
|
font
|
||||||
|
}
|
||||||
|
|
||||||
|
let body-fontsize = fontsize
|
||||||
|
|
||||||
|
set text(
|
||||||
|
font: body-font,
|
||||||
|
size: body-fontsize,
|
||||||
|
lang: lang,
|
||||||
|
region: region
|
||||||
|
)
|
||||||
|
|
||||||
|
// Justified paragraphs with proper spacing for columns
|
||||||
|
set par(justify: true, leading: 0.65em, spacing: 0.65em)
|
||||||
|
|
||||||
|
// Set heading numbering
|
||||||
|
if sectionnumbering != none {
|
||||||
|
set heading(numbering: sectionnumbering)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Academic heading styles
|
||||||
|
let heading-font = if heading_font != none and type(heading_font) == str {
|
||||||
|
(heading_font, "Libertinus Serif", "Times New Roman", "Times")
|
||||||
|
} else if heading_font != none {
|
||||||
|
heading_font
|
||||||
|
} else {
|
||||||
|
("Libertinus Serif", "Times New Roman", "Times")
|
||||||
|
}
|
||||||
|
|
||||||
|
let heading-fontsize = body-fontsize * 1.3
|
||||||
|
|
||||||
|
show heading.where(level: 1): it => {
|
||||||
|
// Level 1 headings span both columns and create section breaks
|
||||||
|
place(
|
||||||
|
top + left,
|
||||||
|
scope: "parent",
|
||||||
|
float: true,
|
||||||
|
clearance: 1em,
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
below: 1.2em,
|
||||||
|
above: 1.5em,
|
||||||
|
breakable: false,
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize * 1.2, weight: "bold")
|
||||||
|
#set align(left)
|
||||||
|
#it
|
||||||
|
#v(0.3em)
|
||||||
|
#line(length: 100%, stroke: 1pt + gray)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
show heading.where(level: 2): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 0.8em,
|
||||||
|
above: 1em,
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize, weight: "bold")
|
||||||
|
#it
|
||||||
|
]
|
||||||
|
|
||||||
|
show heading.where(level: 3): it => block(
|
||||||
|
width: 100%,
|
||||||
|
below: 0.6em,
|
||||||
|
above: 0.8em,
|
||||||
|
)[
|
||||||
|
#set text(font: heading-font, size: heading-fontsize * 0.9, weight: "semibold", style: "italic")
|
||||||
|
#it
|
||||||
|
]
|
||||||
|
|
||||||
|
// Code styling with monospace font
|
||||||
|
let code-font = if monospace_font != none and type(monospace_font) == str {
|
||||||
|
(monospace_font, "Courier New", "Monaco", "Menlo")
|
||||||
|
} else {
|
||||||
|
("Courier New", "Monaco", "Menlo")
|
||||||
|
}
|
||||||
|
|
||||||
|
show raw: set text(font: code-font, size: body-fontsize * 0.9)
|
||||||
|
|
||||||
|
// Code blocks with background
|
||||||
|
show raw.where(block: true): block.with(
|
||||||
|
width: 100%,
|
||||||
|
fill: luma(250),
|
||||||
|
inset: 8pt,
|
||||||
|
radius: 3pt,
|
||||||
|
breakable: true,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Full-width title and author section spanning both columns
|
||||||
|
if title != none and title != "" [
|
||||||
|
#place(
|
||||||
|
top + center,
|
||||||
|
scope: "parent",
|
||||||
|
float: true,
|
||||||
|
clearance: 2em,
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
breakable: false,
|
||||||
|
)[
|
||||||
|
#set align(center)
|
||||||
|
#text(18pt, weight: "bold", font: heading-font)[#title]
|
||||||
|
|
||||||
|
#if authors != () and authors != none [
|
||||||
|
#v(0.8em)
|
||||||
|
#for (i, author) in authors.enumerate() [
|
||||||
|
#if author.name != none and author.name != "" [
|
||||||
|
#text(12pt, style: "italic")[#author.name]
|
||||||
|
#if i < authors.len() - 1 [, ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
#if date != none [
|
||||||
|
#v(0.5em)
|
||||||
|
#text(10pt, style: "italic")[#date]
|
||||||
|
]
|
||||||
|
|
||||||
|
#v(1.5em)
|
||||||
|
#line(length: 60%, stroke: 0.5pt + gray)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
] else [
|
||||||
|
// If no title, still show authors and date in header if present
|
||||||
|
#if authors != () and authors != none or date != none [
|
||||||
|
#place(
|
||||||
|
top + center,
|
||||||
|
scope: "parent",
|
||||||
|
float: true,
|
||||||
|
clearance: 1em,
|
||||||
|
block(width: 100%)[
|
||||||
|
#set align(center)
|
||||||
|
#if authors != () and authors != none [
|
||||||
|
#for (i, author) in authors.enumerate() [
|
||||||
|
#if author.name != none and author.name != "" [
|
||||||
|
#text(12pt, weight: "semibold")[#author.name]
|
||||||
|
#if i < authors.len() - 1 [, ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
#if date != none [
|
||||||
|
#v(0.3em)
|
||||||
|
#text(10pt, style: "italic")[#date]
|
||||||
|
]
|
||||||
|
#v(1em)
|
||||||
|
#line(length: 40%, stroke: 0.5pt + gray)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
// Enhanced figure styling for two-column layout
|
||||||
|
show figure: it => {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
breakable: false,
|
||||||
|
)[
|
||||||
|
#set align(center)
|
||||||
|
#it.body
|
||||||
|
#if it.caption != none [
|
||||||
|
#v(0.5em)
|
||||||
|
#text(size: body-fontsize * 0.9, style: "italic")[
|
||||||
|
Figure #counter(figure).display("1"): #it.caption
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footnote styling for columns
|
||||||
|
show footnote.entry: it => {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: (top: 0.3em),
|
||||||
|
)[
|
||||||
|
#text(size: body-fontsize * 0.8)[
|
||||||
|
#super[#it.note.counter.display("1")] #it.note.body
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Document content
|
||||||
|
doc
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// Universal Pandoc wrapper for all Typst templates
|
// Universal Pandoc wrapper for all Typst templates
|
||||||
// This wrapper handles Pandoc's variable substitution and passes them to the actual Typst template
|
// This wrapper handles Pandoc's variable substitution and passes them to the actual Typst template
|
||||||
|
|
||||||
#import "$template_path$": conf, email-block
|
#import "$template_path$": conf, email-block, horizontalrule
|
||||||
|
|
||||||
#show: doc => conf(
|
#show: doc => conf(
|
||||||
$if(title)$title: [$title$],$else$title: none,$endif$
|
$if(title)$title: [$title$],$else$title: none,$endif$
|
||||||
|
|||||||
+3
-1
@@ -1,5 +1,7 @@
|
|||||||
{
|
{
|
||||||
"1.0.0": "1.9.12",
|
"1.0.0": "1.9.12",
|
||||||
"1.0.1": "1.9.12",
|
"1.0.1": "1.9.12",
|
||||||
"1.1.0": "1.9.12"
|
"1.1.0": "1.9.12",
|
||||||
|
"1.2.0": "1.9.12",
|
||||||
|
"1.2.1": "1.9.12"
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user