Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62738c35b2 | ||
|
|
cf4de4ce36 | ||
|
|
b322e6801c | ||
|
|
9957e4fb58 | ||
|
|
d078215361 | ||
|
|
b5ca5d1e47 | ||
|
|
a69cf31951 | ||
|
|
b0f8755a56 | ||
|
|
d39ddd189e | ||
|
|
b70ad772f3 | ||
|
|
efbff4e172 | ||
|
|
d6d31afb16 | ||
|
|
b0df21d9c2 | ||
|
|
ae5df90eec | ||
|
|
5219ef76b0 | ||
|
|
c1c02ee553 | ||
|
|
7314776057 | ||
|
|
6c28b82a16 | ||
|
|
a71b20e9ba | ||
|
|
d56cb98d51 | ||
|
|
ec36b6334f | ||
|
|
6923644261 | ||
|
|
96859c98e5 | ||
|
|
6098f99c68 | ||
|
|
1ac2807320 | ||
|
|
003d6d105b | ||
|
|
5034e111eb | ||
|
|
dc59776379 | ||
|
|
2e8ac6a848 | ||
|
|
f0daebc8fd | ||
|
|
87f3894bf1 | ||
|
|
7d805eda45 | ||
|
|
2c4076f3c9 | ||
|
|
3c3f86ae4f | ||
|
|
39d66607af | ||
|
|
68238e3db2 | ||
|
|
c7b9a8b5b8 | ||
|
|
207e115699 | ||
|
|
35a5249607 | ||
|
|
a9f436f972 | ||
|
|
c788422cdf | ||
|
|
a37e8e1e40 | ||
|
|
1aeebed4bf | ||
|
|
4eb52d11c0 | ||
|
|
711eab4593 | ||
|
|
281c02210a | ||
|
|
7ac9e1f489 | ||
|
|
4a0376ec2b | ||
|
|
1ca3669e2f | ||
|
|
6e446048d2 | ||
|
|
2e1d2673b1 | ||
|
|
501f380644 | ||
|
|
9ca299cafd | ||
|
|
8329c9dd48 | ||
|
|
536351cbbf | ||
|
|
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
|
||||||
|
|||||||
@@ -70,3 +70,5 @@ CLAUDE.md
|
|||||||
repomix-output.xml
|
repomix-output.xml
|
||||||
|
|
||||||
guidance.md
|
guidance.md
|
||||||
|
|
||||||
|
coverage/
|
||||||
@@ -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
|
||||||
+132
@@ -5,6 +5,138 @@ 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).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [1.4.1] - 2025-01-09
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Windows path handling in Typst template variables - backslashes now normalized to forward slashes to prevent Typst syntax errors (OS error 123: "The syntax for the filename, directory name or volume label is incorrect")
|
||||||
|
|
||||||
|
## [1.4.0] - 2025-01-09
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Minimum version requirements for external dependencies (Pandoc 3.7.0+, Typst 0.13.0+, ImageMagick 7.1.2+)
|
||||||
|
- Version comparison utilities (`compareVersions`, `isVersionAtLeast`) for semantic version validation
|
||||||
|
- Outdated dependency warnings in dependency checker with detailed version information
|
||||||
|
- Enhanced dependency status display showing current version vs. minimum required version
|
||||||
|
- Comprehensive version checking documentation in README
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Updated README to document minimum version requirements in Quick Start and Requirements sections
|
||||||
|
- Enhanced dependency checker to validate installed versions against minimum requirements
|
||||||
|
- Improved user-facing dependency status messages with version-specific guidance
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Case-sensitive regex pattern for Typst version detection (now case-insensitive with `/i` flag)
|
||||||
|
- Version extraction now correctly handles "Typst 0.13.0" (capital T) format
|
||||||
|
|
||||||
|
## [1.3.1] - 2025-11-09
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Unit tests for core functionalities with comprehensive test coverage
|
||||||
|
- YAML parsing support (js-yaml) for enhanced frontmatter and configuration handling
|
||||||
|
- Extensive docstrings throughout codebase for improved maintainability
|
||||||
|
- Config directory existence check for enhanced error handling
|
||||||
|
- **Remote Image Download**: Automatic download and embedding of remote images (http:// and https:// URLs) during export. Works with both wikilink-style embeds `![[https://...]]` and standard markdown images ``. Falls back to placeholder text if download fails (10-second timeout)
|
||||||
|
- **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
|
||||||
|
- Path doubling issues in directory creation and file operations
|
||||||
|
- Executable path resolution on Windows for better cross-platform compatibility
|
||||||
|
- Bibliography errors by properly handling YAML parsing conflicts
|
||||||
|
- Image download order to ensure correct processing sequence
|
||||||
|
- Images without extensions now handled correctly
|
||||||
|
- **Windows Absolute Path Handling**: Fixed ENOENT errors on Windows caused by improper path joining when combining vault paths with plugin directories. PathUtils.joinPath() now properly detects and handles absolute paths using path.isAbsolute() to prevent invalid path construction like `C:\MyVault\C:\MyVault\...`
|
||||||
|
- **Remote URL Image Handling**: Fixed ENOENT errors when markdown contains remote image URLs. Remote images are now automatically downloaded and embedded, with graceful fallback to placeholder text if download fails
|
||||||
|
- **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
|
||||||
|
- Node.js requirement updated to version 18.20+ for latest LTS support
|
||||||
|
- Logging improvements: replaced 'info' with 'debug' for better log level hierarchy
|
||||||
|
- Path normalization simplified for Windows compatibility
|
||||||
|
- Refactored path handling throughout codebase for consistency and reliability
|
||||||
|
- Applied Obsidian linter rules and fixed code quality issues
|
||||||
|
- Standardized terminology and error handling across modules
|
||||||
|
- Automated cleanup with async lifecycle handling for better resource management
|
||||||
|
- **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
|
||||||
|
- Sanitizes frontmatter to prevent data leakage in exports
|
||||||
|
- Rejects absolute paths in vault exports for improved security
|
||||||
|
- Restricts shell metacharacters in paths to prevent injection attacks
|
||||||
|
- Strengthens path validation against reserved names and reserved filesystem names
|
||||||
|
- Enhanced cleanup ensures proper resource disposal
|
||||||
|
- **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] - 2025-09-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-09-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-09-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
|
||||||
@@ -59,7 +73,7 @@ Typst offers several advantages over standard PDF export:
|
|||||||
|
|
||||||
**⚠️ Important**: This plugin requires template files to function. Always use the complete ZIP package.
|
**⚠️ Important**: This plugin requires template files to function. Always use the complete ZIP package.
|
||||||
|
|
||||||
1. Go to [GitHub Releases](https://github.com/akucera/obsidian-typst-pdf-export/releases)
|
1. Go to [GitHub Releases](https://github.com/AlexKucera/obsidian-typst-pdf-export/releases)
|
||||||
2. Download the **complete ZIP package** (`typst-pdf-export.zip`) - **NOT just main.js**
|
2. Download the **complete ZIP package** (`typst-pdf-export.zip`) - **NOT just main.js**
|
||||||
3. Extract the entire contents to `{VaultFolder}/.obsidian/plugins/typst-pdf-export/`
|
3. Extract the entire contents to `{VaultFolder}/.obsidian/plugins/typst-pdf-export/`
|
||||||
4. Ensure the `templates/` directory is included with all `.typ` files:
|
4. Ensure the `templates/` directory is included with all `.typ` files:
|
||||||
@@ -81,7 +95,7 @@ Typst offers several advantages over standard PDF export:
|
|||||||
### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
|
### Method 3: BRAT (Beta Reviewer's Auto-update Tool)
|
||||||
|
|
||||||
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
1. Install the [BRAT plugin](https://github.com/TfTHacker/obsidian42-brat)
|
||||||
2. Add this repository: `akucera/obsidian-typst-pdf-export`
|
2. Add this repository: `https://github.com/AlexKucera/obsidian-typst-pdf-export`
|
||||||
3. Enable the plugin after installation
|
3. Enable the plugin after installation
|
||||||
|
|
||||||
### Method 4: Developer Installation
|
### Method 4: Developer Installation
|
||||||
@@ -91,7 +105,7 @@ For development or the latest changes:
|
|||||||
1. Clone the repository to your vault's plugins folder:
|
1. Clone the repository to your vault's plugins folder:
|
||||||
```bash
|
```bash
|
||||||
cd {VaultFolder}/.obsidian/plugins/
|
cd {VaultFolder}/.obsidian/plugins/
|
||||||
git clone https://github.com/akucera/obsidian-typst-pdf-export.git typst-pdf-export
|
git clone https://github.com/AlexKucera/obsidian-typst-pdf-export.git typst-pdf-export
|
||||||
cd typst-pdf-export
|
cd typst-pdf-export
|
||||||
```
|
```
|
||||||
2. Install dependencies and build:
|
2. Install dependencies and build:
|
||||||
@@ -117,9 +131,9 @@ For development or the latest changes:
|
|||||||
### 1. Install Dependencies
|
### 1. Install Dependencies
|
||||||
|
|
||||||
**Required:**
|
**Required:**
|
||||||
- [Pandoc](https://pandoc.org/installing.html) - Markdown to Typst conversion
|
- [Pandoc](https://pandoc.org/installing.html) 3.7.0+ - Markdown to Typst conversion
|
||||||
- [Typst](https://typst.app/docs/reference/foundations/) - PDF generation
|
- [Typst](https://typst.app/docs/reference/foundations/) 0.13.0+ - PDF generation
|
||||||
- [ImageMagick](https://imagemagick.org/script/download.php) - Enhanced image processing
|
- [ImageMagick](https://imagemagick.org/script/download.php) 7.1.2+ - Enhanced image processing
|
||||||
|
|
||||||
### 2. Export Your First Note
|
### 2. Export Your First Note
|
||||||
|
|
||||||
@@ -155,15 +169,17 @@ Go to the plugin settings and click **Check Dependencies** to ensure all require
|
|||||||
|
|
||||||
- **Obsidian**: Version 1.9.12 or higher
|
- **Obsidian**: Version 1.9.12 or higher
|
||||||
- **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it.
|
- **Platform**: Desktop only (Windows, macOS, Linux) - I develop this on macOS, but it should in theory work on Windows and Linux. I just have no way to test it.
|
||||||
- **Node.js**: Version 16+ (for development)
|
- **Node.js**: Version 18.20+ (for development)
|
||||||
|
|
||||||
### External Dependencies
|
### External Dependencies
|
||||||
|
|
||||||
| Tool | Purpose | Installation |
|
| Tool | Minimum Version | Purpose | Installation |
|
||||||
|------|---------|-------------|
|
|------|----------------|---------|-------------|
|
||||||
| **Pandoc** | Markdown → Typst conversion | [Download here](https://pandoc.org/installing.html) or `brew install pandoc` |
|
| **Pandoc** | 3.7.0 | Markdown → Typst conversion | [Download here](https://pandoc.org/installing.html) or `brew install pandoc` |
|
||||||
| **Typst** | PDF generation | [Download here](https://typst.app/docs/reference/foundations/) or `brew install typst` |
|
| **Typst** | 0.13.0 | PDF generation | [Download here](https://typst.app/docs/reference/foundations/) or `brew install typst` |
|
||||||
| **ImageMagick** | Enhanced image processing (optional) | [Download here](https://imagemagick.org/script/download.php) or `brew install imagemagick` |
|
| **ImageMagick** | 7.1.2 | Enhanced image processing (optional) | [Download here](https://imagemagick.org/script/download.php) or `brew install imagemagick` |
|
||||||
|
|
||||||
|
**Note**: The plugin will display warnings if your installed versions are below the minimum requirements. While older versions may work, they are not officially supported and may cause compatibility issues.
|
||||||
|
|
||||||
### Dependency Verification
|
### Dependency Verification
|
||||||
|
|
||||||
@@ -245,6 +261,7 @@ JB
|
|||||||
|---------|----------|
|
|---------|----------|
|
||||||
| **"Pandoc not found"** | Install Pandoc and ensure it's in your system PATH |
|
| **"Pandoc not found"** | Install Pandoc and ensure it's in your system PATH |
|
||||||
| **"Typst not found"** | Install Typst CLI and verify PATH configuration |
|
| **"Typst not found"** | Install Typst CLI and verify PATH configuration |
|
||||||
|
| **Outdated version warning** | Update dependencies to meet minimum versions (Pandoc 3.7.0+, Typst 0.13.0+, ImageMagick 7.1.2+) |
|
||||||
| **Export hangs** | Check if files are locked by other applications |
|
| **Export hangs** | Check if files are locked by other applications |
|
||||||
| **Images not showing** | Verify image paths and file permissions |
|
| **Images not showing** | Verify image paths and file permissions |
|
||||||
| **Template errors** | Check template syntax and file integrity |
|
| **Template errors** | Check template syntax and file integrity |
|
||||||
@@ -310,6 +327,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",
|
||||||
|
|||||||
+103
-42
@@ -1,50 +1,111 @@
|
|||||||
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 js from '@eslint/js';
|
||||||
const __dirname = path.dirname(__filename);
|
import tseslint from 'typescript-eslint';
|
||||||
const compat = new FlatCompat({
|
import obsidianmd from 'eslint-plugin-obsidianmd';
|
||||||
baseDirectory: __dirname,
|
import importPlugin from 'eslint-plugin-import';
|
||||||
recommendedConfig: js.configs.recommended,
|
import globals from 'globals';
|
||||||
allConfig: js.configs.all
|
|
||||||
});
|
|
||||||
|
|
||||||
export default defineConfig([globalIgnores(["**/node_modules/", "**/main.js"]), {
|
export default tseslint.config(
|
||||||
extends: compat.extends(
|
// Base JavaScript recommended rules
|
||||||
"eslint:recommended",
|
js.configs.recommended,
|
||||||
"plugin:@typescript-eslint/eslint-recommended",
|
|
||||||
"plugin:@typescript-eslint/recommended",
|
|
||||||
),
|
|
||||||
|
|
||||||
plugins: {
|
// TypeScript recommended type-checked rules
|
||||||
"@typescript-eslint": typescriptEslint,
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
},
|
|
||||||
|
|
||||||
languageOptions: {
|
// Obsidian-specific configuration
|
||||||
globals: {
|
{
|
||||||
...globals.node,
|
plugins: {
|
||||||
},
|
obsidianmd: obsidianmd,
|
||||||
|
import: importPlugin,
|
||||||
|
},
|
||||||
|
|
||||||
parser: tsParser,
|
languageOptions: {
|
||||||
ecmaVersion: 5,
|
globals: {
|
||||||
sourceType: "module",
|
...globals.node,
|
||||||
},
|
...globals.browser,
|
||||||
|
NodeJS: 'readonly', // TypeScript global namespace
|
||||||
|
},
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
rules: {
|
// Apply Obsidian plugin recommended rules (manually specified)
|
||||||
"no-unused-vars": "off",
|
rules: {
|
||||||
|
// Obsidian command rules
|
||||||
|
'obsidianmd/commands/no-command-in-command-id': 'error',
|
||||||
|
'obsidianmd/commands/no-command-in-command-name': 'error',
|
||||||
|
'obsidianmd/commands/no-default-hotkeys': 'error',
|
||||||
|
'obsidianmd/commands/no-plugin-id-in-command-id': 'error',
|
||||||
|
'obsidianmd/commands/no-plugin-name-in-command-name': 'error',
|
||||||
|
|
||||||
"@typescript-eslint/no-unused-vars": ["error", {
|
// Settings tab rules
|
||||||
args: "none",
|
'obsidianmd/settings-tab/no-manual-html-headings': 'error',
|
||||||
}],
|
'obsidianmd/settings-tab/no-problematic-settings-headings': 'error',
|
||||||
|
|
||||||
"@typescript-eslint/ban-ts-comment": "off",
|
// Other Obsidian rules
|
||||||
"no-prototype-builtins": "off",
|
'obsidianmd/vault/iterate': 'error',
|
||||||
"@typescript-eslint/no-empty-function": "off",
|
'obsidianmd/detach-leaves': 'error',
|
||||||
},
|
'obsidianmd/hardcoded-config-path': 'error',
|
||||||
}]);
|
'obsidianmd/no-forbidden-elements': 'error',
|
||||||
|
'obsidianmd/no-plugin-as-component': 'error',
|
||||||
|
'obsidianmd/no-sample-code': 'error',
|
||||||
|
'obsidianmd/no-tfile-tfolder-cast': 'error',
|
||||||
|
'obsidianmd/no-view-references-in-plugin': 'error',
|
||||||
|
'obsidianmd/no-static-styles-assignment': 'error',
|
||||||
|
'obsidianmd/object-assign': 'error',
|
||||||
|
'obsidianmd/platform': 'error',
|
||||||
|
'obsidianmd/prefer-file-manager-trash-file': 'warn',
|
||||||
|
'obsidianmd/prefer-abstract-input-suggest': 'error',
|
||||||
|
'obsidianmd/regex-lookbehind': 'error',
|
||||||
|
'obsidianmd/sample-names': 'error',
|
||||||
|
'obsidianmd/validate-manifest': 'error',
|
||||||
|
'obsidianmd/validate-license': 'error',
|
||||||
|
'obsidianmd/ui/sentence-case': ['warn', { enforceCamelCaseLower: true }],
|
||||||
|
|
||||||
|
// General ESLint rules from Obsidian recommended
|
||||||
|
'no-unused-vars': 'off',
|
||||||
|
'no-prototype-builtins': 'off',
|
||||||
|
'no-self-compare': 'warn',
|
||||||
|
'no-eval': 'error',
|
||||||
|
'no-implied-eval': 'error',
|
||||||
|
'prefer-const': 'off',
|
||||||
|
'no-implicit-globals': 'error',
|
||||||
|
'no-console': ['error', { allow: ['warn', 'error', 'debug'] }],
|
||||||
|
'no-alert': 'error',
|
||||||
|
'no-undef': 'error',
|
||||||
|
|
||||||
|
// TypeScript rules from Obsidian recommended
|
||||||
|
'@typescript-eslint/ban-ts-comment': 'off',
|
||||||
|
'@typescript-eslint/no-deprecated': 'error',
|
||||||
|
'@typescript-eslint/require-await': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': ['error', { fixToUnknown: true }],
|
||||||
|
|
||||||
|
// Downgrade strict type checking rules to warnings
|
||||||
|
'@typescript-eslint/no-unsafe-assignment': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-member-access': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-call': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-return': 'warn',
|
||||||
|
|
||||||
|
// Unused vars with underscore prefix
|
||||||
|
'@typescript-eslint/no-unused-vars': ['warn', { args: 'none', varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],
|
||||||
|
|
||||||
|
// Import rules
|
||||||
|
'import/no-extraneous-dependencies': 'error',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 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.4.1",
|
||||||
"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",
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
### Required
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L81-L81)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/mmandRegistry.ts#L37-L37)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L23-L23)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L38-L38)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L56-L56)
|
||||||
|
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L325-L325)
|
||||||
|
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L31-L31)
|
||||||
|
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L50-L50)
|
||||||
|
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L57-L57)
|
||||||
|
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L65-L65)
|
||||||
|
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L67-L67)
|
||||||
|
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L80-L80)
|
||||||
|
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L82-L82)
|
||||||
|
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L94-L94)
|
||||||
|
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L95-L95)
|
||||||
|
[16](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L97-L97)
|
||||||
|
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L134-L134)
|
||||||
|
[18](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L138-L138)
|
||||||
|
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L160-L160)
|
||||||
|
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L179-L179)
|
||||||
|
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L182-L182)
|
||||||
|
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L232-L232)
|
||||||
|
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
|
||||||
|
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L138-L138)
|
||||||
|
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L222-L222)
|
||||||
|
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/BehaviorSection.ts#L14-L14)
|
||||||
|
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/neralSection.ts#L21-L21)
|
||||||
|
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L75-L75)
|
||||||
|
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/GeneralSection.ts#L78-L78)
|
||||||
|
[30](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/youtSection.ts#L16-L16)
|
||||||
|
[31](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L16-L16)
|
||||||
|
[32](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/PageSetupSection.ts#L72-L72)
|
||||||
|
[33](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L166-L166)
|
||||||
|
[34](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L167-L167)
|
||||||
|
[35](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L174-L174)
|
||||||
|
[36](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L194-L194)
|
||||||
|
[37](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L195-L195)
|
||||||
|
[38](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L199-L199)
|
||||||
|
[39](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L200-L200)
|
||||||
|
[40](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/TypographySection.ts#L201-L201)
|
||||||
|
Use sentence case for UI text.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/main.ts#L215-L215)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/naryLocator.ts#L154-L154)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L38-L38)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L115-L115)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/FileDiscovery.ts#L183-L183)
|
||||||
|
[6](https://github.com/exKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L61-L61)
|
||||||
|
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L111-L111)
|
||||||
|
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L236-L236)
|
||||||
|
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ImageOptimizer.ts#L252-L252)
|
||||||
|
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/ageOptimizer.ts#L264-L264)
|
||||||
|
[11](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L114-L114)
|
||||||
|
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/PdfCliExecutor.ts#L115-L115)
|
||||||
|
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L35-L35)
|
||||||
|
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L46-L46)
|
||||||
|
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
|
||||||
|
[16](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
|
||||||
|
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
|
||||||
|
[18](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
|
||||||
|
[19](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/eprocessors/FrontmatterProcessor.ts#L208-L208)
|
||||||
|
[20](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
|
||||||
|
[21](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L51-L51)
|
||||||
|
[22](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ecutableChecker.ts#L128-L128)
|
||||||
|
[23](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L158-L158)
|
||||||
|
[24](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExecutableChecker.ts#L215-L215)
|
||||||
|
[25](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/PathUtils.ts#L115-L115)
|
||||||
|
[26](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EmbedProcessor.ts#L164-L164)
|
||||||
|
[27](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/bedProcessor.ts#L165-L165)
|
||||||
|
[28](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/FontManager.ts#L19-L19)
|
||||||
|
[29](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PathResolver.ts#L29-L29)
|
||||||
|
A `require()` style import is forbidden.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/MarkdownPreprocessor.ts#L117-L117)
|
||||||
|
Async method 'process' has no 'await' expression.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L138-L138)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/plugin/CommandRegistry.ts#L21-L21)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L30-L30)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/CommandRegistry.ts#L39-L39)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L26-L26)
|
||||||
|
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L41-L41)
|
||||||
|
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/entHandlers.ts#L59-L59)
|
||||||
|
[8](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L68-L68)
|
||||||
|
[9](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L95-L95)
|
||||||
|
[10](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L104-L104)
|
||||||
|
[11](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L56-L56)
|
||||||
|
[12](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/uginLifecycle.ts#L59-L59)
|
||||||
|
[13](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L72-L80)
|
||||||
|
[14](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L88-L101)
|
||||||
|
[15](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L86-L86)
|
||||||
|
[16](https://github.com/AlexKucerabsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L122-L122)
|
||||||
|
[17](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/sections/pographySection.ts#L19-L19)
|
||||||
|
Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/PandocTypstConverter.ts#L180-L180)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/c/converters/PandocTypstConverter.ts#L187-L187)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/pdf/BinaryLocator.ts#L33-L33)
|
||||||
|
Obsidian's configuration folder is not necessarily `.obsidian`, can be configured by the user. Use `Vault#configDir` to get the current value
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L35-L35)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L103-L103)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L118-L118)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L144-L144)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L188-L188)
|
||||||
|
[6](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L208-L208)
|
||||||
|
[7](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L233-L233)
|
||||||
|
'js-yaml' should be listed in the project's dependencies. n 'npm i -S js-yaml' to add it
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L49-L49)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L50-L50)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/ontmatterProcessor.ts#L155-L155)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L156-L156)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/ob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ExportErrorHandler.ts#L64-L64)
|
||||||
|
Unexpected console statement. Only these console methods are allowed: warn, error, debug.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/converters/preprocessors/FrontmatterProcessor.ts#L275-L275)
|
||||||
|
'value' will use Object's default stringification format ('[object Object]') when ringified.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/DependencyChecker.ts#L122-L122)
|
||||||
|
Static async method 'checkDependenciesAsync' has no 'await' expression.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/ModalSettingsHelper.ts#L72-L72)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/dal/sections/PageSetupSection.ts#L60-L60)
|
||||||
|
The two values in this comparison do not have a shared enum type.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/SecurityUtils.ts#L56-L56)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/core/curityUtils.ts#L117-L117)
|
||||||
|
Unexpected undescribed directive comment. Include descriptions to explain why the comment is necessary.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/EventHandlers.ts#L51-L51)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/portOrchestrator.ts#L322-L322)
|
||||||
|
A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object. Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an intended `this` value. If a function does not access `this`, it can be annotated with `this: void`.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L89-L91)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ugin/ExportOrchestrator.ts#L124-L126)
|
||||||
|
Promise returned in function argument where a void return was expected.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ExportOrchestrator.ts#L160-L160)
|
||||||
|
`noticeEl` is deprecated. Use `messageEl` instead
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L31-L31)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/ttingsTab.ts#L50-L50)
|
||||||
|
[3](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L134-L134)
|
||||||
|
[4](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/6351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L232-L232)
|
||||||
|
[5](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L296-L296)
|
||||||
|
[6](https://github.com/AlexKucera/sidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/SettingsTab.ts#L366-L366)
|
||||||
|
For a consistent UI use `new Setting(containerEl).setName(...).setHeading()` instead of creating HTML heading elements directly.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/templates/TemplateManager.ts#L132-L132)
|
||||||
|
Unexpected lexical declaration in case block.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L50-L50)
|
||||||
|
Promise-returning function provided to property where a void return was expected.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ExportConfigModal.ts#L152-L152)
|
||||||
|
Unexpected `await` of a non-Promise (non-"Thenable") value.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L260-L260)
|
||||||
|
Creating and attaching "style" elements is not allowed. For loading CSS, use a "styles.css" file instead, which sidian loads for you.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/state/ModalState.ts#L192-L192)
|
||||||
|
[2](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/uiodal/state/ModalState.ts#L203-L203)
|
||||||
|
Unexpected use of 'localStorage'. Prefer `App#saveLocalStorage` / `App#loadLocalStorage` functions to write / read localStorage data that's unique to a vault.
|
||||||
|
|
||||||
|
### Optional
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/plugin/PluginLifecycle.ts#L92-L92)
|
||||||
|
'_result' is assigned a value but never used.
|
||||||
|
|
||||||
|
|
||||||
|
[1](https://github.com/AlexKucera/obsidian-typst-pdf-export/blob/536351cbbf2e8065f83325a7a4d9b70836f68d38/src/ui/modal/ModalRenderer.ts#L124-L124)
|
||||||
|
'_progressPercent' is assigned a value but never used.
|
||||||
Generated
+5722
-458
File diff suppressed because it is too large.
Load diff
+27
-7
@@ -1,11 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "obsidian-typst-pdf-export",
|
"name": "obsidian-typst-pdf-export",
|
||||||
"version": "1.1.0",
|
"version": "1.4.1",
|
||||||
"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",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"test:ui": "vitest --ui",
|
||||||
|
"test:coverage": "vitest run --coverage",
|
||||||
"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"
|
||||||
},
|
},
|
||||||
@@ -18,22 +24,36 @@
|
|||||||
],
|
],
|
||||||
"author": "Alexander Kucera",
|
"author": "Alexander Kucera",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.20.0"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/eslintrc": "^3.3.1",
|
"@eslint/eslintrc": "^3.3.1",
|
||||||
"@eslint/js": "^9.34.0",
|
"@eslint/js": "^9.34.0",
|
||||||
"@types/node": "^16.11.6",
|
"@types/js-yaml": "^4.0.9",
|
||||||
"@typescript-eslint/eslint-plugin": "5.29.0",
|
"@types/node": "^20.19.24",
|
||||||
"@typescript-eslint/parser": "5.29.0",
|
"@typescript-eslint/eslint-plugin": "^8.46.3",
|
||||||
|
"@typescript-eslint/parser": "^8.46.3",
|
||||||
|
"@typescript-eslint/utils": "^8.46.3",
|
||||||
|
"@vitest/coverage-v8": "^4.0.6",
|
||||||
|
"@vitest/ui": "^4.0.6",
|
||||||
"archiver": "^7.0.1",
|
"archiver": "^7.0.1",
|
||||||
"builtin-modules": "3.3.0",
|
"builtin-modules": "3.3.0",
|
||||||
|
"electron": "^33.3.0",
|
||||||
"esbuild": "0.17.3",
|
"esbuild": "0.17.3",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-plugin-obsidianmd": "^0.1.8",
|
||||||
"globals": "^16.3.0",
|
"globals": "^16.3.0",
|
||||||
|
"happy-dom": "^20.0.10",
|
||||||
"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",
|
||||||
|
"vitest": "^4.0.6"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"gray-matter": "^4.0.3",
|
"gray-matter": "^4.0.3",
|
||||||
|
"js-yaml": "^4.1.0",
|
||||||
"pdf-to-img": "^4.5.0"
|
"pdf-to-img": "^4.5.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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/
|
||||||
+556
-1087
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,94 @@
|
|||||||
/**
|
/**
|
||||||
* PDF to Image Converter using pdf-to-img
|
* PDF to Image conversion for embedded PDF files in Obsidian notes.
|
||||||
* Converts PDF files to PNG images for preview in Typst exports
|
*
|
||||||
|
* This module provides a robust conversion system for transforming PDF files into
|
||||||
|
* images suitable for embedding in Typst-generated PDFs. Since Typst has limited
|
||||||
|
* native PDF embedding capabilities, this converter extracts the first page of
|
||||||
|
* embedded PDFs and converts them to high-quality PNG or JPEG images.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Singleton pattern for resource efficiency and state management
|
||||||
|
* - First-page-only conversion for preview purposes
|
||||||
|
* - Configurable image quality and dimensions
|
||||||
|
* - Multi-strategy PDF processing (pdf-to-img library with ImageMagick fallback)
|
||||||
|
* - Automatic format conversion and optimization
|
||||||
|
* - File discovery for handling various filename patterns
|
||||||
|
* - Comprehensive error handling and validation
|
||||||
|
*
|
||||||
|
* Conversion Pipeline:
|
||||||
|
* 1. PDF validation (file exists, valid format, readable)
|
||||||
|
* 2. Output directory preparation
|
||||||
|
* 3. CLI execution via pdf-to-img or ImageMagick
|
||||||
|
* 4. Generated file discovery (handles naming variations)
|
||||||
|
* 5. Image optimization (format conversion, dimension detection)
|
||||||
|
* 6. Result packaging with metadata
|
||||||
|
*
|
||||||
|
* The converter delegates to specialized utilities:
|
||||||
|
* - PdfProcessor: PDF validation and metadata extraction
|
||||||
|
* - PdfCliExecutor: Command-line tool execution
|
||||||
|
* - FileDiscovery: Generated file location
|
||||||
|
* - ImageOptimizer: Format conversion and dimension detection
|
||||||
|
*
|
||||||
|
* Architecture Notes:
|
||||||
|
* - Singleton pattern ensures consistent state across exports
|
||||||
|
* - Plugin reference enables vault file operations
|
||||||
|
* - Modular design allows easy extension for multi-page conversion
|
||||||
|
* - Error results preserve context for debugging
|
||||||
*/
|
*/
|
||||||
|
|
||||||
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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration options for PDF to image conversion.
|
||||||
|
*
|
||||||
|
* These options control the quality, dimensions, and format of generated images.
|
||||||
|
* All options are optional with sensible defaults optimized for embedding in PDFs.
|
||||||
|
*
|
||||||
|
* @property scale - Rendering scale factor for image quality (default: 2.0)
|
||||||
|
* Higher values produce sharper images but larger file sizes. 2.0 is optimal
|
||||||
|
* for HiDPI displays and print-quality PDFs. Use 1.0 for web-optimized exports.
|
||||||
|
* @property maxWidth - Maximum output image width in pixels (default: 800)
|
||||||
|
* Images wider than this are scaled down proportionally. Prevents excessive
|
||||||
|
* file sizes while maintaining readability in typical PDF layouts.
|
||||||
|
* @property maxHeight - Maximum output image height in pixels (default: 600)
|
||||||
|
* Images taller than this are scaled down proportionally. Balances quality
|
||||||
|
* with file size for typical document heights.
|
||||||
|
* @property format - Output image format (default: 'png')
|
||||||
|
* - 'png': Lossless compression, best for diagrams and text
|
||||||
|
* - 'jpeg': Lossy compression, smaller files for photos
|
||||||
|
* @property quality - JPEG compression quality 1-100 (default: 90)
|
||||||
|
* Only applies when format is 'jpeg'. Higher values preserve more detail
|
||||||
|
* but increase file size. 90 provides excellent quality with good compression.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // High-quality conversion for print
|
||||||
|
* const printOptions: PdfConversionOptions = {
|
||||||
|
* scale: 3.0,
|
||||||
|
* maxWidth: 1200,
|
||||||
|
* maxHeight: 900,
|
||||||
|
* format: 'png'
|
||||||
|
* };
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Web-optimized conversion
|
||||||
|
* const webOptions: PdfConversionOptions = {
|
||||||
|
* scale: 1.0,
|
||||||
|
* maxWidth: 600,
|
||||||
|
* maxHeight: 450,
|
||||||
|
* format: 'jpeg',
|
||||||
|
* quality: 85
|
||||||
|
* };
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
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) */
|
||||||
scale?: number;
|
scale?: number;
|
||||||
@@ -19,6 +102,58 @@ export interface PdfConversionOptions {
|
|||||||
quality?: number;
|
quality?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of PDF to image conversion operation.
|
||||||
|
*
|
||||||
|
* This interface provides comprehensive information about the conversion outcome,
|
||||||
|
* including file paths, dimensions, and success status. The result always includes
|
||||||
|
* a success flag - when false, the error field provides diagnostic information.
|
||||||
|
*
|
||||||
|
* @property imagePath - Absolute path to the generated image file
|
||||||
|
* Empty string if conversion failed. Use this path to embed the image in Typst.
|
||||||
|
* @property originalDimensions - Original PDF page dimensions in pixels
|
||||||
|
* Width and height of the PDF page before conversion. Set to {0, 0} on failure.
|
||||||
|
* Note: Currently estimates based on converted image due to library limitations.
|
||||||
|
* @property imageDimensions - Generated image dimensions in pixels
|
||||||
|
* Actual width and height of the output image file. May differ from original
|
||||||
|
* due to scaling, format conversion, or optimization. Set to {0, 0} on failure.
|
||||||
|
* @property success - Conversion success flag
|
||||||
|
* True if image was generated successfully, false if any error occurred.
|
||||||
|
* Always check this before using imagePath or dimension data.
|
||||||
|
* @property error - Error message if conversion failed
|
||||||
|
* Present only when success is false. Contains diagnostic information about
|
||||||
|
* what went wrong (file not found, invalid PDF, conversion failure, etc.).
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
|
||||||
|
*
|
||||||
|
* if (result.success) {
|
||||||
|
* console.log('Image created:', result.imagePath);
|
||||||
|
* console.log('Dimensions:', result.imageDimensions);
|
||||||
|
* // Use result.imagePath in Typst template
|
||||||
|
* } else {
|
||||||
|
* console.error('Conversion failed:', result.error);
|
||||||
|
* // Fallback to placeholder or skip embed
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Handle dimension information
|
||||||
|
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
|
||||||
|
*
|
||||||
|
* if (result.success) {
|
||||||
|
* const aspectRatio = result.imageDimensions.width / result.imageDimensions.height;
|
||||||
|
* console.log('Aspect ratio:', aspectRatio.toFixed(2));
|
||||||
|
*
|
||||||
|
* // Adjust Typst layout based on dimensions
|
||||||
|
* if (aspectRatio > 1.5) {
|
||||||
|
* // Wide image - use landscape layout
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export interface PdfConversionResult {
|
export interface PdfConversionResult {
|
||||||
/** Path to the generated image file */
|
/** Path to the generated image file */
|
||||||
imagePath: string;
|
imagePath: string;
|
||||||
@@ -38,32 +173,125 @@ export interface PdfConversionResult {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Singleton converter for transforming PDF files into embeddable images.
|
||||||
|
*
|
||||||
|
* This class provides the primary interface for PDF to image conversion in the
|
||||||
|
* export pipeline. It implements the singleton pattern to ensure consistent state
|
||||||
|
* and resource management across multiple conversion operations.
|
||||||
|
*
|
||||||
|
* Key Responsibilities:
|
||||||
|
* - First-page extraction from PDF files
|
||||||
|
* - High-quality image generation with configurable options
|
||||||
|
* - PDF validation and metadata extraction
|
||||||
|
* - Integration with Obsidian vault file system
|
||||||
|
* - Error handling and result reporting
|
||||||
|
*
|
||||||
|
* Architecture:
|
||||||
|
* The converter delegates to specialized utility classes:
|
||||||
|
* - **PdfProcessor**: PDF file validation and metadata
|
||||||
|
* - **PdfCliExecutor**: Command-line tool execution (pdf-to-img, ImageMagick)
|
||||||
|
* - **FileDiscovery**: Generated file location and verification
|
||||||
|
* - **ImageOptimizer**: Format conversion and dimension detection
|
||||||
|
* - **PathUtils**: Obsidian vault file operations
|
||||||
|
*
|
||||||
|
* Singleton Pattern:
|
||||||
|
* Use `getInstance()` to obtain the converter instance. The singleton ensures:
|
||||||
|
* - Single plugin reference across all conversions
|
||||||
|
* - Consistent configuration and state
|
||||||
|
* - Efficient resource usage
|
||||||
|
* - Simplified dependency injection
|
||||||
|
*
|
||||||
|
* Usage Flow:
|
||||||
|
* 1. Get instance with plugin reference: `PdfToImageConverter.getInstance(plugin)`
|
||||||
|
* 2. Convert PDF: `await converter.convertFirstPageToImage(path, outDir, options)`
|
||||||
|
* 3. Check result.success and use result.imagePath in Typst template
|
||||||
|
* 4. Handle errors via result.error message
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Initialize converter with plugin reference
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
*
|
||||||
|
* // Convert PDF with default options
|
||||||
|
* const result = await converter.convertFirstPageToImage(
|
||||||
|
* '/vault/attachments/document.pdf',
|
||||||
|
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (result.success) {
|
||||||
|
* console.log('Converted to:', result.imagePath);
|
||||||
|
* // Embed result.imagePath in Typst template
|
||||||
|
* } else {
|
||||||
|
* console.error('Conversion failed:', result.error);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // High-quality conversion with custom options
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
*
|
||||||
|
* const result = await converter.convertFirstPageToImage(
|
||||||
|
* pdfPath,
|
||||||
|
* outputDir,
|
||||||
|
* {
|
||||||
|
* scale: 3.0, // 3x rendering for print quality
|
||||||
|
* maxWidth: 1200, // Larger dimensions
|
||||||
|
* format: 'png' // Lossless format
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
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 for singleton pattern.
|
||||||
|
*
|
||||||
|
* Use getInstance() to obtain the converter instance instead of constructing directly.
|
||||||
|
*
|
||||||
|
* @param plugin - Optional plugin reference for vault operations
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private constructor(plugin?: obsidianTypstPDFExport) {
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get augmented environment with extended PATH for ImageMagick
|
* Gets or creates the singleton PdfToImageConverter instance.
|
||||||
|
*
|
||||||
|
* This method ensures only one converter instance exists throughout the application
|
||||||
|
* lifecycle. If a plugin reference is provided on subsequent calls, it updates the
|
||||||
|
* stored reference to ensure vault operations work correctly.
|
||||||
|
*
|
||||||
|
* Thread Safety:
|
||||||
|
* This implementation is safe for single-threaded JavaScript execution.
|
||||||
|
* The singleton is created on first access and reused thereafter.
|
||||||
|
*
|
||||||
|
* @param plugin - Optional plugin reference (updates stored reference if provided)
|
||||||
|
* @returns The singleton PdfToImageConverter instance
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // First call creates instance
|
||||||
|
* const converter1 = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
*
|
||||||
|
* // Subsequent calls return same instance
|
||||||
|
* const converter2 = PdfToImageConverter.getInstance();
|
||||||
|
* console.log(converter1 === converter2); // true
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Update plugin reference after initialization
|
||||||
|
* const converter = PdfToImageConverter.getInstance(); // No plugin initially
|
||||||
|
* // ... later ...
|
||||||
|
* PdfToImageConverter.getInstance(this.plugin); // Updates plugin reference
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
private getAugmentedEnv(): NodeJS.ProcessEnv {
|
public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter {
|
||||||
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(':')}`
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
||||||
@@ -74,11 +302,93 @@ export class PdfToImageConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert the first page of a PDF to an image
|
* Converts the first page of a PDF file to a high-quality image.
|
||||||
|
*
|
||||||
|
* This is the primary conversion method that orchestrates the complete PDF-to-image
|
||||||
|
* pipeline. It handles validation, conversion, optimization, and error reporting in
|
||||||
|
* a single operation suitable for embedding in Typst exports.
|
||||||
|
*
|
||||||
|
* Conversion Pipeline:
|
||||||
|
* 1. **Validation**: Verify PDF file exists and is valid
|
||||||
|
* 2. **Directory Setup**: Ensure output directory exists (via vault adapter)
|
||||||
|
* 3. **CLI Execution**: Run pdf-to-img or ImageMagick to convert first page
|
||||||
|
* 4. **File Discovery**: Locate generated image (handles various naming patterns)
|
||||||
|
* 5. **Optimization**: Convert format and detect dimensions
|
||||||
|
* 6. **Result Packaging**: Return success with image path and metadata
|
||||||
|
*
|
||||||
|
* Error Handling:
|
||||||
|
* Each stage reports specific errors via PdfConversionResult. Common failures:
|
||||||
|
* - File not found or inaccessible
|
||||||
|
* - Invalid or corrupted PDF format
|
||||||
|
* - CLI tool execution failure
|
||||||
|
* - Output file not found after conversion
|
||||||
|
* - Image optimization failure
|
||||||
|
*
|
||||||
|
* All errors are captured and returned in result.error, never thrown as exceptions.
|
||||||
|
*
|
||||||
|
* Performance:
|
||||||
|
* - First-page-only conversion is fast (~1-2 seconds typical)
|
||||||
|
* - Uses CLI tools for native-quality rendering
|
||||||
|
* - Temporary files cleaned up automatically by caller
|
||||||
|
* - Suitable for batch processing multiple PDFs
|
||||||
|
*
|
||||||
|
* @param pdfPath - Absolute path to PDF file to convert
|
||||||
|
* @param outputDir - Absolute path to output directory for generated image
|
||||||
|
* @param options - Optional conversion configuration (defaults to HiDPI quality)
|
||||||
|
* @returns Promise resolving to conversion result with success status and metadata
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Basic conversion with defaults
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
* const result = await converter.convertFirstPageToImage(
|
||||||
|
* '/vault/attachments/report.pdf',
|
||||||
|
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (result.success) {
|
||||||
|
* console.log('Image:', result.imagePath);
|
||||||
|
* console.log('Size:', result.imageDimensions.width, 'x', result.imageDimensions.height);
|
||||||
|
* // Use result.imagePath in Typst: #image("path")
|
||||||
|
* } else {
|
||||||
|
* new Notice(`PDF conversion failed: ${result.error}`);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // High-quality conversion for print
|
||||||
|
* const result = await converter.convertFirstPageToImage(
|
||||||
|
* pdfPath,
|
||||||
|
* outputDir,
|
||||||
|
* {
|
||||||
|
* scale: 3.0,
|
||||||
|
* maxWidth: 1600,
|
||||||
|
* maxHeight: 1200,
|
||||||
|
* format: 'png'
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Batch convert multiple PDFs
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
* const pdfPaths = ['/vault/doc1.pdf', '/vault/doc2.pdf', '/vault/doc3.pdf'];
|
||||||
|
*
|
||||||
|
* for (const pdfPath of pdfPaths) {
|
||||||
|
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
|
||||||
|
* if (result.success) {
|
||||||
|
* console.log(`✓ ${path.basename(pdfPath)}`);
|
||||||
|
* } else {
|
||||||
|
* console.error(`✗ ${path.basename(pdfPath)}: ${result.error}`);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public async convertFirstPageToImage(
|
public async convertFirstPageToImage(
|
||||||
pdfPath: string,
|
pdfPath: string,
|
||||||
outputDir: string,
|
outputDir: string,
|
||||||
options: PdfConversionOptions = {}
|
options: PdfConversionOptions = {}
|
||||||
): Promise<PdfConversionResult> {
|
): Promise<PdfConversionResult> {
|
||||||
try {
|
try {
|
||||||
@@ -91,285 +401,86 @@ 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 (convert absolute path to vault-relative for vault.adapter)
|
||||||
await fs.mkdir(outputDir, { recursive: true });
|
if (this.plugin?.app) {
|
||||||
|
const pathUtils = new PathUtils(this.plugin.app);
|
||||||
|
const relativeOutputDir = pathUtils.toVaultRelative(outputDir);
|
||||||
|
await pathUtils.ensureDir(relativeOutputDir);
|
||||||
|
}
|
||||||
|
|
||||||
// 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
|
||||||
|
},
|
||||||
// Look for any PNG files that might match
|
this.plugin
|
||||||
const pngFiles = files.filter(f => f.endsWith('.png'));
|
);
|
||||||
if (pngFiles.length > 0) {
|
|
||||||
|
if (!optimizationResult.success) {
|
||||||
// Try to find a file that matches the pattern (with or without exact name)
|
return {
|
||||||
// pdf2img might sanitize filenames differently
|
imagePath: '',
|
||||||
const matchingFile = pngFiles.find(f => {
|
originalDimensions: { width: 0, height: 0 },
|
||||||
// Try exact match first
|
imageDimensions: { width: 0, height: 0 },
|
||||||
if (f === expectedOutputFileName) return true;
|
success: false,
|
||||||
// Try partial match by removing special characters
|
error: optimizationResult.error
|
||||||
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,34 +489,137 @@ 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}`
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a file is a valid PDF
|
* Validates whether a file is a readable PDF document.
|
||||||
|
*
|
||||||
|
* This utility method provides quick PDF validation before attempting conversion.
|
||||||
|
* It checks both file existence and PDF format validity by delegating to PdfProcessor.
|
||||||
|
*
|
||||||
|
* Validation includes:
|
||||||
|
* - File exists and is accessible
|
||||||
|
* - File has PDF magic bytes (header signature)
|
||||||
|
* - File is not corrupted or truncated
|
||||||
|
*
|
||||||
|
* Use this for pre-flight checks before expensive conversion operations or to
|
||||||
|
* filter PDF files from mixed file lists.
|
||||||
|
*
|
||||||
|
* @param filePath - Absolute path to file to validate
|
||||||
|
* @returns Promise resolving to true if file is valid PDF, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
*
|
||||||
|
* // Validate before conversion
|
||||||
|
* if (await converter.isValidPdf(pdfPath)) {
|
||||||
|
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
|
||||||
|
* // Process result...
|
||||||
|
* } else {
|
||||||
|
* new Notice('Not a valid PDF file');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Filter PDF files from attachments
|
||||||
|
* const attachments = app.vault.getFiles();
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
*
|
||||||
|
* const validPdfs = [];
|
||||||
|
* for (const file of attachments) {
|
||||||
|
* if (file.extension === 'pdf' && await converter.isValidPdf(file.path)) {
|
||||||
|
* validPdfs.push(file);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* console.log(`Found ${validPdfs.length} valid PDFs`);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get PDF metadata (page count, dimensions, etc.)
|
* Retrieves metadata about a PDF file without converting it.
|
||||||
|
*
|
||||||
|
* This method extracts essential PDF information including page count and page
|
||||||
|
* dimensions. It's useful for:
|
||||||
|
* - Determining if multi-page conversion is needed
|
||||||
|
* - Checking PDF dimensions before conversion
|
||||||
|
* - Pre-flight validation with detailed error messages
|
||||||
|
* - UI display of PDF properties
|
||||||
|
*
|
||||||
|
* The method delegates to PdfProcessor for actual metadata extraction. On success,
|
||||||
|
* returns page count and first page dimensions. On failure, returns error details.
|
||||||
|
*
|
||||||
|
* Note: Dimensions are for the first page only. Multi-page PDFs may have varying
|
||||||
|
* page sizes, but this implementation focuses on first-page conversion.
|
||||||
|
*
|
||||||
|
* @param filePath - Absolute path to PDF file
|
||||||
|
* @returns Promise resolving to metadata object with page count, dimensions, and success status
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
* const info = await converter.getPdfInfo(pdfPath);
|
||||||
|
*
|
||||||
|
* if (info.success) {
|
||||||
|
* console.log(`Pages: ${info.pageCount}`);
|
||||||
|
* console.log(`Size: ${info.dimensions.width}x${info.dimensions.height}px`);
|
||||||
|
*
|
||||||
|
* if (info.pageCount > 1) {
|
||||||
|
* new Notice(`PDF has ${info.pageCount} pages - only first will be converted`);
|
||||||
|
* }
|
||||||
|
* } else {
|
||||||
|
* console.error('Failed to read PDF info:', info.error);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Adjust conversion options based on PDF dimensions
|
||||||
|
* const info = await converter.getPdfInfo(pdfPath);
|
||||||
|
*
|
||||||
|
* if (info.success) {
|
||||||
|
* const isLandscape = info.dimensions.width > info.dimensions.height;
|
||||||
|
*
|
||||||
|
* const options: PdfConversionOptions = {
|
||||||
|
* maxWidth: isLandscape ? 1200 : 800,
|
||||||
|
* maxHeight: isLandscape ? 800 : 1200
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir, options);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Check PDF before showing conversion dialog
|
||||||
|
* const info = await converter.getPdfInfo(pdfPath);
|
||||||
|
*
|
||||||
|
* if (!info.success) {
|
||||||
|
* new Notice(`Cannot process PDF: ${info.error}`);
|
||||||
|
* return;
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Show dialog with PDF details
|
||||||
|
* new PDFConversionModal(
|
||||||
|
* this.app,
|
||||||
|
* pdfPath,
|
||||||
|
* `${info.pageCount} pages, ${info.dimensions.width}x${info.dimensions.height}px`
|
||||||
|
* ).open();
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public async getPdfInfo(filePath: string): Promise<{
|
public async getPdfInfo(filePath: string): Promise<{
|
||||||
pageCount: number;
|
pageCount: number;
|
||||||
@@ -413,33 +627,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,398 @@
|
|||||||
|
/**
|
||||||
|
* Command-line argument builder for Pandoc-to-Typst PDF conversion.
|
||||||
|
*
|
||||||
|
* This module constructs complete Pandoc command-line arguments for converting
|
||||||
|
* preprocessed Markdown to Typst format, which is then compiled to PDF by the
|
||||||
|
* Typst engine. It orchestrates several key aspects of the conversion:
|
||||||
|
* - Input/output path specification
|
||||||
|
* - Typst PDF engine configuration
|
||||||
|
* - Template loading and variable passing
|
||||||
|
* - Resource path resolution for embedded media
|
||||||
|
* - Diagnostic and error reporting options
|
||||||
|
*
|
||||||
|
* Key Features:
|
||||||
|
* - Modular argument construction via specialized methods
|
||||||
|
* - Template system with universal wrapper for dynamic template selection
|
||||||
|
* - Comprehensive variable mapping from export config to Typst variables
|
||||||
|
* - Smart resource path resolution for Obsidian attachments
|
||||||
|
* - Enhanced diagnostics for debugging conversion failures
|
||||||
|
* - Safe path handling with automatic quoting via spawn
|
||||||
|
*
|
||||||
|
* Architecture:
|
||||||
|
* The builder delegates to specialized components:
|
||||||
|
* - **TypstVariableMapper**: Maps export config to Typst variables
|
||||||
|
* - **ResourcePathResolver**: Finds attachment directories in vault
|
||||||
|
* - **PathResolver**: Resolves executable paths with fallback logic
|
||||||
|
* - **PathUtils**: Obsidian vault file system operations
|
||||||
|
*
|
||||||
|
* Command Structure:
|
||||||
|
* ```bash
|
||||||
|
* pandoc input.md \
|
||||||
|
* -o output.pdf \
|
||||||
|
* --from markdown-smart \
|
||||||
|
* --pdf-engine=typst \
|
||||||
|
* --standalone \
|
||||||
|
* --no-citeproc \
|
||||||
|
* --embed-resources \
|
||||||
|
* --resource-path /vault/attachments \
|
||||||
|
* --template universal-wrapper.typ \
|
||||||
|
* -V template_path=default.typ \
|
||||||
|
* -V page_width=210mm \
|
||||||
|
* ... (more variables)
|
||||||
|
* --pdf-engine-opt --diagnostic-format=short
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* The universal wrapper template receives the actual template path as a variable,
|
||||||
|
* allowing dynamic template selection without requiring separate wrapper files
|
||||||
|
* for each template.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builder for Pandoc command-line arguments in the Markdown → Typst → PDF pipeline.
|
||||||
|
*
|
||||||
|
* This class encapsulates the complex logic for constructing Pandoc command arguments
|
||||||
|
* that correctly configure Typst PDF generation. It manages several interdependent
|
||||||
|
* concerns including template loading, variable mapping, resource path resolution,
|
||||||
|
* and diagnostic configuration.
|
||||||
|
*
|
||||||
|
* Design Philosophy:
|
||||||
|
* - Single responsibility: Only builds command arguments, doesn't execute
|
||||||
|
* - Modular construction: Each argument category handled by dedicated method
|
||||||
|
* - Dependency injection: Receives plugin reference for configuration access
|
||||||
|
* - Async-safe: Handles file system checks without blocking
|
||||||
|
*
|
||||||
|
* The builder pattern allows testing argument construction independently from
|
||||||
|
* command execution, and makes it easy to modify argument logic without touching
|
||||||
|
* the execution layer.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const builder = new PandocCommandBuilder(this.plugin);
|
||||||
|
*
|
||||||
|
* const args = await builder.buildPandocArgs(
|
||||||
|
* '/vault/note.md',
|
||||||
|
* '/vault/exports/note.pdf',
|
||||||
|
* {
|
||||||
|
* template: 'default',
|
||||||
|
* vaultBasePath: '/vault',
|
||||||
|
* pluginDir: '/vault/.obsidian/plugins/typst-pdf-export',
|
||||||
|
* typstPath: 'typst',
|
||||||
|
* exportConfig: { pageSize: 'a4', orientation: 'portrait' }
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Execute with spawn
|
||||||
|
* spawn('pandoc', args);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class PandocCommandBuilder {
|
||||||
|
private plugin: obsidianTypstPDFExport;
|
||||||
|
private variableMapper: TypstVariableMapper;
|
||||||
|
private resourcePathResolver: ResourcePathResolver;
|
||||||
|
private pathResolver: PathResolver;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new PandocCommandBuilder.
|
||||||
|
*
|
||||||
|
* Initializes all dependent components (variable mapper, resource path resolver,
|
||||||
|
* path resolver) that the builder needs to construct complete command arguments.
|
||||||
|
*
|
||||||
|
* @param plugin - Plugin instance for accessing configuration and vault operations
|
||||||
|
*/
|
||||||
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
this.variableMapper = new TypstVariableMapper(plugin);
|
||||||
|
this.resourcePathResolver = new ResourcePathResolver(plugin);
|
||||||
|
this.pathResolver = new PathResolver(plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds complete Pandoc command-line arguments for Typst PDF generation.
|
||||||
|
*
|
||||||
|
* This is the primary interface method that orchestrates all argument construction.
|
||||||
|
* It delegates to specialized private methods for each category of arguments,
|
||||||
|
* ensuring proper ordering and completeness.
|
||||||
|
*
|
||||||
|
* Argument Order (important for Pandoc):
|
||||||
|
* 1. Input file path
|
||||||
|
* 2. Output file specification (-o)
|
||||||
|
* 3. Input format (--from markdown-smart)
|
||||||
|
* 4. PDF engine configuration (--pdf-engine=typst)
|
||||||
|
* 5. Standalone mode (--standalone)
|
||||||
|
* 6. Citation processing (--no-citeproc)
|
||||||
|
* 7. Resource embedding (--embed-resources)
|
||||||
|
* 8. Resource paths (--resource-path, multiple)
|
||||||
|
* 9. Template configuration (--template, -V template_path)
|
||||||
|
* 10. Typst variables (-V key=value, multiple)
|
||||||
|
* 11. Engine options (--pdf-engine-opt, multiple)
|
||||||
|
* 12. Diagnostics (--pdf-engine-opt --diagnostic-format=short)
|
||||||
|
*
|
||||||
|
* Side Effects:
|
||||||
|
* - Changes process.cwd() if vaultBasePath is provided
|
||||||
|
* - Reads file system to verify template existence
|
||||||
|
* - May throw Error if universal wrapper template not found
|
||||||
|
*
|
||||||
|
* @param inputPath - Absolute path to preprocessed Markdown input file
|
||||||
|
* @param outputPath - Absolute path for generated PDF output file
|
||||||
|
* @param pandocOptions - Configuration for Pandoc execution and Typst variables
|
||||||
|
* @returns Promise resolving to array of command-line arguments for Pandoc
|
||||||
|
*
|
||||||
|
* @throws {Error} If universal wrapper template not found
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Basic usage
|
||||||
|
* const builder = new PandocCommandBuilder(this.plugin);
|
||||||
|
* const args = await builder.buildPandocArgs(
|
||||||
|
* '/vault/preprocessed.md',
|
||||||
|
* '/vault/output.pdf',
|
||||||
|
* {
|
||||||
|
* template: 'modern',
|
||||||
|
* vaultBasePath: '/vault',
|
||||||
|
* typstPath: '/usr/local/bin/typst',
|
||||||
|
* exportConfig: {
|
||||||
|
* pageSize: 'letter',
|
||||||
|
* margins: { top: '1in', bottom: '1in' }
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* console.log('Pandoc args:', args.join(' '));
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // With custom engine options
|
||||||
|
* const args = await builder.buildPandocArgs(
|
||||||
|
* inputPath,
|
||||||
|
* outputPath,
|
||||||
|
* {
|
||||||
|
* template: 'article',
|
||||||
|
* typstSettings: {
|
||||||
|
* engineOptions: ['--root', '/custom/root', '--font-path', '/fonts']
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds resource paths to command arguments for Obsidian attachment resolution.
|
||||||
|
*
|
||||||
|
* This method enables Pandoc to find embedded images, PDFs, and other attachments
|
||||||
|
* referenced in the markdown content. It uses ResourcePathResolver to discover all
|
||||||
|
* attachment directories in the vault and adds them via --resource-path flags.
|
||||||
|
*
|
||||||
|
* Multiple --resource-path arguments can be provided, and Pandoc searches them in
|
||||||
|
* order when resolving relative paths in the markdown. This allows attachments to
|
||||||
|
* be stored in various locations (root-level, nested folders, etc.) and still be
|
||||||
|
* found during conversion.
|
||||||
|
*
|
||||||
|
* @param args - Command arguments array to append to
|
||||||
|
* @param pandocOptions - Options including vaultBasePath for resource discovery
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds template configuration using the universal wrapper pattern.
|
||||||
|
*
|
||||||
|
* This method implements the plugin's template system using a universal wrapper
|
||||||
|
* template that dynamically loads the actual template via a Typst import. This
|
||||||
|
* approach allows template selection at runtime without maintaining separate
|
||||||
|
* wrapper files for each template.
|
||||||
|
*
|
||||||
|
* Template Resolution:
|
||||||
|
* 1. Locate universal-wrapper.pandoc.typ in plugin templates directory
|
||||||
|
* 2. Verify wrapper exists (throws if missing)
|
||||||
|
* 3. Add wrapper as Pandoc --template
|
||||||
|
* 4. Add templates directory to resource paths (enables Typst imports)
|
||||||
|
* 5. Pass actual template path as template_path variable
|
||||||
|
*
|
||||||
|
* Path Handling:
|
||||||
|
* - Absolute template paths are made relative to vault root for Typst imports
|
||||||
|
* - Relative paths are passed through unchanged
|
||||||
|
* - spawn automatically handles path quoting for spaces
|
||||||
|
*
|
||||||
|
* @param args - Command arguments array to append to
|
||||||
|
* @param pandocOptions - Options including template path and plugin directory
|
||||||
|
* @throws {Error} If universal wrapper template not found
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize to forward slashes for Typst (Typst uses forward slashes on all platforms)
|
||||||
|
// This prevents Windows backslashes from being interpreted as escape characters in Typst
|
||||||
|
templatePathForTypst = templatePathForTypst.replace(/\\/g, '/');
|
||||||
|
|
||||||
|
args.push('-V', `template_path=${templatePathForTypst}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds all Typst template variables mapped from export configuration.
|
||||||
|
*
|
||||||
|
* This method delegates to TypstVariableMapper to transform the export configuration
|
||||||
|
* into Typst template variables. These variables control typography, layout, margins,
|
||||||
|
* and other formatting aspects of the final PDF.
|
||||||
|
*
|
||||||
|
* Variable Mapping:
|
||||||
|
* - ExportConfig fields → Typst variable names (e.g., pageSize → page_size)
|
||||||
|
* - Plugin settings provide fallback values for missing config fields
|
||||||
|
* - Values converted to Typst-compatible formats (e.g., "2.5cm" for margins)
|
||||||
|
* - Variables passed via -V key=value arguments to Pandoc
|
||||||
|
*
|
||||||
|
* Example Variables:
|
||||||
|
* - page_width, page_height: Page dimensions
|
||||||
|
* - margin_top, margin_bottom, margin_left, margin_right: Margins
|
||||||
|
* - body_font, heading_font, monospace_font: Typography
|
||||||
|
* - font_size: Base font size
|
||||||
|
*
|
||||||
|
* @param args - Command arguments array to append to
|
||||||
|
* @param pandocOptions - Options including exportConfig and plugin settings
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds custom Typst engine options for advanced configuration.
|
||||||
|
*
|
||||||
|
* This method passes additional command-line options directly to the Typst engine
|
||||||
|
* via Pandoc's --pdf-engine-opt flag. These options can override Typst's default
|
||||||
|
* behavior for specific use cases.
|
||||||
|
*
|
||||||
|
* Common Engine Options:
|
||||||
|
* - --root /path: Set Typst root directory for imports
|
||||||
|
* - --font-path /fonts: Add custom font directories
|
||||||
|
* - --input key=value: Pass additional variables to Typst
|
||||||
|
*
|
||||||
|
* @param args - Command arguments array to append to
|
||||||
|
* @param pandocOptions - Options including typstSettings.engineOptions
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void {
|
||||||
|
if (pandocOptions.typstSettings?.engineOptions) {
|
||||||
|
for (const option of pandocOptions.typstSettings.engineOptions) {
|
||||||
|
args.push('--pdf-engine-opt', option);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds Typst diagnostic configuration for enhanced error reporting.
|
||||||
|
*
|
||||||
|
* This method enables short-format diagnostics in Typst, which provide cleaner
|
||||||
|
* and more readable error messages when compilation fails. The short format is
|
||||||
|
* easier to parse and present to users compared to the verbose default format.
|
||||||
|
*
|
||||||
|
* Diagnostic Format:
|
||||||
|
* - Short: Concise error messages with file:line:column locations
|
||||||
|
* - Default (verbose): Detailed multi-line error reports with context
|
||||||
|
*
|
||||||
|
* @param args - Command arguments array to append to
|
||||||
|
* @param pandocOptions - Pandoc options (currently unused but kept for consistency)
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
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,415 @@
|
|||||||
|
import { spawn, ChildProcess } from 'child_process';
|
||||||
|
import { ConversionResult, ProgressCallback, PandocOptions } from '../converterTypes';
|
||||||
|
import { PathResolver } from '../../plugin/PathResolver';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process executor for Pandoc command-line conversions with progress monitoring.
|
||||||
|
*
|
||||||
|
* This class manages the complete lifecycle of Pandoc subprocess execution including:
|
||||||
|
* - Process spawning with augmented PATH and working directory configuration
|
||||||
|
* - Real-time stdout/stderr streaming and parsing
|
||||||
|
* - Progress monitoring and user feedback via callbacks
|
||||||
|
* - Timeout enforcement to prevent hanging conversions
|
||||||
|
* - Error extraction and formatting for user-friendly messages
|
||||||
|
* - Graceful process termination and cleanup
|
||||||
|
*
|
||||||
|
* Key Features:
|
||||||
|
* - **Augmented PATH**: Ensures Pandoc and Typst are found in common locations
|
||||||
|
* - **Working Directory**: Sets vault root as CWD for proper attachment resolution
|
||||||
|
* - **Progress Callbacks**: Updates UI during conversion stages
|
||||||
|
* - **Timeout Protection**: Kills hung processes after configurable duration
|
||||||
|
* - **Error Parsing**: Extracts meaningful error messages from raw output
|
||||||
|
* - **Promise-based API**: Clean async interface for callers
|
||||||
|
*
|
||||||
|
* Process Lifecycle:
|
||||||
|
* 1. Resolve Pandoc executable path with PathResolver
|
||||||
|
* 2. Determine working directory (vault root preferred)
|
||||||
|
* 3. Augment PATH environment with common binary locations
|
||||||
|
* 4. Spawn Pandoc process with stdio piping
|
||||||
|
* 5. Set up timeout handler for hanging processes
|
||||||
|
* 6. Stream and parse stdout/stderr for progress
|
||||||
|
* 7. Handle process completion or error
|
||||||
|
* 8. Clean up timeout handler and resolve promise
|
||||||
|
*
|
||||||
|
* The executor is designed to work reliably across different environments (macOS,
|
||||||
|
* Linux, Windows) by handling path resolution and environment variables carefully.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const executor = new PandocExecutor(this.plugin);
|
||||||
|
*
|
||||||
|
* const result = await executor.executePandoc(
|
||||||
|
* ['input.md', '-o', 'output.pdf', '--pdf-engine=typst'],
|
||||||
|
* {
|
||||||
|
* pandocPath: 'pandoc',
|
||||||
|
* vaultBasePath: '/vault',
|
||||||
|
* timeout: 120000
|
||||||
|
* },
|
||||||
|
* (message, progress) => {
|
||||||
|
* console.log(`${progress}%: ${message}`);
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (result.success) {
|
||||||
|
* console.log('Conversion succeeded');
|
||||||
|
* } else {
|
||||||
|
* console.error('Error:', result.error);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class PandocExecutor {
|
||||||
|
private pathResolver: PathResolver;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new PandocExecutor.
|
||||||
|
*
|
||||||
|
* @param plugin - Plugin instance for accessing PathResolver configuration
|
||||||
|
*/
|
||||||
|
constructor(plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathResolver = new PathResolver(plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes Pandoc process with comprehensive monitoring and error handling.
|
||||||
|
*
|
||||||
|
* This is the primary execution method that spawns a Pandoc subprocess, monitors
|
||||||
|
* its progress, enforces timeouts, and returns a detailed result. The method is
|
||||||
|
* fully asynchronous and promise-based for clean integration with async workflows.
|
||||||
|
*
|
||||||
|
* Process Configuration:
|
||||||
|
* - **Executable Resolution**: Uses PathResolver to find Pandoc (handles custom paths)
|
||||||
|
* - **Working Directory**: Sets vault root for relative path resolution
|
||||||
|
* - **PATH Augmentation**: Adds common binary locations to ensure tool discovery
|
||||||
|
* - **Stdio Piping**: Captures stdout/stderr for progress parsing and error reporting
|
||||||
|
*
|
||||||
|
* Progress Monitoring:
|
||||||
|
* The progressCallback receives updates at various stages:
|
||||||
|
* - 45%: Reading input (parsing phase)
|
||||||
|
* - 60%: Processing document (conversion phase)
|
||||||
|
* - 75%: Generating output (template application)
|
||||||
|
* - 85%: Running Typst engine (PDF generation)
|
||||||
|
* - 90%: Complete
|
||||||
|
*
|
||||||
|
* Timeout Handling:
|
||||||
|
* - Default: 60 seconds (configurable via pandocOptions.timeout)
|
||||||
|
* - Process killed with SIGTERM on timeout
|
||||||
|
* - Returns error result with timeout message
|
||||||
|
* - Prevents hung processes from blocking export queue
|
||||||
|
*
|
||||||
|
* Error Handling:
|
||||||
|
* - Non-zero exit code → Parses stderr for meaningful error
|
||||||
|
* - Process spawn failure → Returns startup error
|
||||||
|
* - Timeout → Returns timeout error
|
||||||
|
* - All errors include diagnostic context for debugging
|
||||||
|
*
|
||||||
|
* @param args - Complete command-line arguments for Pandoc (from PandocCommandBuilder)
|
||||||
|
* @param pandocOptions - Configuration including paths, timeout, and working directory
|
||||||
|
* @param progressCallback - Optional callback for real-time progress updates
|
||||||
|
* @returns Promise resolving to ConversionResult with success status and output
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Basic execution
|
||||||
|
* const executor = new PandocExecutor(this.plugin);
|
||||||
|
* const result = await executor.executePandoc(args, options);
|
||||||
|
*
|
||||||
|
* if (!result.success) {
|
||||||
|
* new Notice(`Conversion failed: ${result.error}`);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // With progress callback for UI updates
|
||||||
|
* const result = await executor.executePandoc(
|
||||||
|
* args,
|
||||||
|
* options,
|
||||||
|
* (message, progress) => {
|
||||||
|
* progressModal.update(message, progress);
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // With custom timeout for large documents
|
||||||
|
* const result = await executor.executePandoc(
|
||||||
|
* args,
|
||||||
|
* {
|
||||||
|
* ...options,
|
||||||
|
* timeout: 300000 // 5 minutes for large PDF
|
||||||
|
* }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses Pandoc's stderr output to detect conversion progress and update the UI.
|
||||||
|
*
|
||||||
|
* This method implements heuristic progress detection by scanning stderr output for
|
||||||
|
* specific keywords that indicate which phase of the conversion pipeline is active.
|
||||||
|
* While Pandoc doesn't provide structured progress events, certain log patterns
|
||||||
|
* reliably appear during specific phases.
|
||||||
|
*
|
||||||
|
* Detection Heuristics:
|
||||||
|
* - **"parsing" or "reading"** → 45% (Input parsing phase)
|
||||||
|
* - Pandoc is reading and parsing the markdown input
|
||||||
|
* - AST construction is underway
|
||||||
|
* - **"writing" or "generating"** → 75% (Output generation phase)
|
||||||
|
* - Pandoc is generating Typst markup from the AST
|
||||||
|
* - Template application is occurring
|
||||||
|
* - **"typst"** → 85% (PDF generation phase)
|
||||||
|
* - Typst engine is compiling to PDF
|
||||||
|
* - Final rendering in progress
|
||||||
|
*
|
||||||
|
* Progress updates are only sent if a progressCallback was provided. Multiple
|
||||||
|
* matches to the same pattern won't duplicate callbacks - only one update per
|
||||||
|
* phase is typical.
|
||||||
|
*
|
||||||
|
* Enhancement Opportunities:
|
||||||
|
* - Parse Typst's own progress output for more granular PDF generation updates
|
||||||
|
* - Detect specific error keywords to provide early warning
|
||||||
|
* - Track file processing count for multi-file conversions
|
||||||
|
*
|
||||||
|
* @param output - Raw text from Pandoc's stderr stream
|
||||||
|
* @param progressCallback - Optional callback to invoke with progress updates
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Typical stderr patterns that trigger updates:
|
||||||
|
* parseProgressFromOutput('[INFO] Parsing markdown...', callback);
|
||||||
|
* // → Triggers: callback('Reading input...', 45)
|
||||||
|
*
|
||||||
|
* parseProgressFromOutput('[INFO] Writing typst output...', callback);
|
||||||
|
* // → Triggers: callback('Generating output...', 75)
|
||||||
|
*
|
||||||
|
* parseProgressFromOutput('Running typst compile...', callback);
|
||||||
|
* // → Triggers: callback('Running Typst engine...', 85)
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Used in stderr stream handler:
|
||||||
|
* pandocProcess.stderr?.on('data', (data: Buffer) => {
|
||||||
|
* const output = data.toString();
|
||||||
|
* stderr += output;
|
||||||
|
* this.parseProgressFromOutput(output, progressCallback);
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts meaningful, user-friendly error messages from Pandoc's raw output.
|
||||||
|
*
|
||||||
|
* This method implements a multi-tier fallback strategy to find the most relevant
|
||||||
|
* error information from Pandoc's stderr and stdout streams. Pandoc and Typst can
|
||||||
|
* produce verbose diagnostic output, so this method filters to find the most
|
||||||
|
* actionable error message for users.
|
||||||
|
*
|
||||||
|
* Extraction Strategy (in priority order):
|
||||||
|
* 1. **Pattern Matching**: Scan all output for common error indicators
|
||||||
|
* - Case-insensitive "error:" matches most Pandoc/Typst errors
|
||||||
|
* - Case-sensitive "Error:" catches Python and other tool errors
|
||||||
|
* - "failed" indicates operation failures
|
||||||
|
* - "Fatal" indicates critical termination errors
|
||||||
|
* - "pandoc:" catches Pandoc-specific diagnostic messages
|
||||||
|
*
|
||||||
|
* 2. **First Stderr Line**: If no pattern matches, use first non-empty stderr line
|
||||||
|
* - Assumes most important error appears early in stderr
|
||||||
|
* - Filters out empty lines for cleaner messages
|
||||||
|
*
|
||||||
|
* 3. **Generic Fallback**: If no stderr content, return generic error
|
||||||
|
* - Indicates process failure with no diagnostic output
|
||||||
|
* - Should be rare in practice
|
||||||
|
*
|
||||||
|
* Error Pattern Examples:
|
||||||
|
* - `Error: Could not find template: custom.typ` (Pandoc template error)
|
||||||
|
* - `pandoc: Cannot find file input.md` (File not found)
|
||||||
|
* - `error: font not found: "NonexistentFont"` (Typst font error)
|
||||||
|
* - `Fatal error: out of memory` (Resource exhaustion)
|
||||||
|
* - `failed to compile: syntax error at line 42` (Typst compilation error)
|
||||||
|
*
|
||||||
|
* The extracted message is displayed directly to users in error notices, so it
|
||||||
|
* should be concise and actionable without requiring interpretation.
|
||||||
|
*
|
||||||
|
* @param stderr - Complete stderr output captured from Pandoc process
|
||||||
|
* @param stdout - Complete stdout output captured from Pandoc process
|
||||||
|
* @returns User-friendly error message suitable for display in Notice
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Template not found error
|
||||||
|
* const stderr = "Error: Could not find template: custom.typ\nUsage: pandoc...";
|
||||||
|
* const error = this.extractErrorMessage(stderr, '');
|
||||||
|
* // Returns: "Error: Could not find template: custom.typ"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Typst compilation error
|
||||||
|
* const stderr = "typst compile failed\nerror: undefined function `foo`\n at line 15";
|
||||||
|
* const error = this.extractErrorMessage(stderr, '');
|
||||||
|
* // Returns: "error: undefined function `foo`"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Generic failure with no specific error
|
||||||
|
* const stderr = "";
|
||||||
|
* const stdout = "Some non-error output";
|
||||||
|
* const error = this.extractErrorMessage(stderr, stdout);
|
||||||
|
* // Returns: "Unknown error occurred during conversion"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Used in process close handler:
|
||||||
|
* pandocProcess.on('close', (code: number | null) => {
|
||||||
|
* if (!success) {
|
||||||
|
* result.error = this.extractErrorMessage(stderr, stdout);
|
||||||
|
* new Notice(`Export failed: ${result.error}`);
|
||||||
|
* }
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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,173 @@
|
|||||||
|
/**
|
||||||
|
* Binary locator utilities for finding external tool binaries.
|
||||||
|
* Handles discovery of pdf2img and other CLI tools in the Obsidian environment.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
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
|
||||||
|
// Extract just the plugin folder name from manifest.dir (e.g., "typst-pdf-export" from ".obsidian/plugins/typst-pdf-export")
|
||||||
|
const fullManifestDir = plugin?.manifest?.dir || 'typst-pdf-export';
|
||||||
|
const pluginDirName = path.basename(fullManifestDir);
|
||||||
|
const configDir = plugin?.app.vault.configDir;
|
||||||
|
if (!configDir) {
|
||||||
|
throw new Error('Unable to determine Obsidian configuration directory');
|
||||||
|
}
|
||||||
|
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[] {
|
||||||
|
const pathUtils = plugin ? new PathUtils(plugin.app) : null;
|
||||||
|
|
||||||
|
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
|
||||||
|
// Use PathUtils.joinPath to handle absolute paths correctly on Windows
|
||||||
|
...(pathUtils ? [pathUtils.joinPath(pathUtils.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
|
||||||
|
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,323 @@
|
|||||||
|
/**
|
||||||
|
* File discovery utilities for finding generated PDF to image conversion outputs.
|
||||||
|
* Handles filename pattern matching when pdf2img generates files with different names.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
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);
|
||||||
|
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
|
||||||
|
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 {
|
||||||
|
// 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,283 @@
|
|||||||
|
/**
|
||||||
|
* Image optimization utilities for PDF to image conversion.
|
||||||
|
* Handles format conversion, quality management, and dimension detection.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn } from 'child_process';
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
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 {
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
const relativePath = pathUtils.toVaultRelative(inputImagePath);
|
||||||
|
await plugin.app.vault.adapter.remove(relativePath);
|
||||||
|
} else {
|
||||||
|
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 pathUtils = new PathUtils(plugin.app);
|
||||||
|
const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
|
||||||
|
const relativePngPath = pathUtils.toVaultRelative(pngFinalPath);
|
||||||
|
|
||||||
|
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
|
||||||
|
await plugin.app.vault.adapter.writeBinary(relativePngPath, content);
|
||||||
|
await plugin.app.vault.adapter.remove(relativeInputPath);
|
||||||
|
} else {
|
||||||
|
await fs.rename(inputImagePath, pngFinalPath);
|
||||||
|
}
|
||||||
|
actualImagePath = pngFinalPath;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Keep as PNG, just rename to final location
|
||||||
|
if (plugin?.app) {
|
||||||
|
const pathUtils = new PathUtils(plugin.app);
|
||||||
|
const relativeInputPath = pathUtils.toVaultRelative(inputImagePath);
|
||||||
|
const relativeFinalPath = pathUtils.toVaultRelative(finalOutputPath);
|
||||||
|
|
||||||
|
const content = await plugin.app.vault.adapter.readBinary(relativeInputPath);
|
||||||
|
await plugin.app.vault.adapter.writeBinary(relativeFinalPath, content);
|
||||||
|
await plugin.app.vault.adapter.remove(relativeInputPath);
|
||||||
|
} else {
|
||||||
|
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 { exec } from 'child_process';
|
||||||
|
import { promisify } from 'util';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { BinaryLocator } from './BinaryLocator';
|
||||||
|
import { EnvironmentUtils } from './EnvironmentUtils';
|
||||||
|
import type { obsidianTypstPDFExport } from '../../../main';
|
||||||
|
|
||||||
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// 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,346 @@
|
|||||||
|
/**
|
||||||
|
* FrontmatterProcessor - Handles YAML frontmatter parsing and processing
|
||||||
|
* Extracted from MarkdownPreprocessor for better code organization
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as yaml from 'js-yaml';
|
||||||
|
import matter from 'gray-matter';
|
||||||
|
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 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
|
||||||
|
|
||||||
|
// Add debugging to see what's being parsed
|
||||||
|
console.debug('FrontmatterProcessor: Attempting to parse content with frontmatter pattern detected', `(content length: ${content.length})`);
|
||||||
|
|
||||||
|
const parsed = matter(content);
|
||||||
|
|
||||||
|
if (parsed.data && Object.keys(parsed.data).length > 0) {
|
||||||
|
// Sanitize frontmatter first to prevent citation fields from leaking to downstream consumers
|
||||||
|
const sanitizedFrontmatter = this.stripCitationFields(parsed.data);
|
||||||
|
|
||||||
|
// Store sanitized frontmatter in metadata (with title override if needed)
|
||||||
|
if (this.noteTitle) {
|
||||||
|
result.metadata.frontmatter = {
|
||||||
|
...sanitizedFrontmatter,
|
||||||
|
title: this.noteTitle
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
result.metadata.frontmatter = sanitizedFrontmatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the sanitized frontmatter from metadata for writing
|
||||||
|
const finalFrontmatter = result.metadata.frontmatter;
|
||||||
|
|
||||||
|
if (this.preserveFrontmatter) {
|
||||||
|
// Keep the frontmatter in the content, but reconstruct it with the modified title
|
||||||
|
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 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 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.error('FrontmatterProcessor: gray-matter failed with error:', errorMessage, `(content length: ${content.length})`);
|
||||||
|
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 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 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 titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
|
result.metadata.title = this.noteTitle;
|
||||||
|
result.metadata.frontmatter = { title: this.noteTitle };
|
||||||
|
return `---\n${titleFrontmatter}---\n${content}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip citation-related fields from frontmatter to prevent Pandoc bibliography processing
|
||||||
|
*/
|
||||||
|
private stripCitationFields(frontmatter: Record<string, unknown>): Record<string, unknown> {
|
||||||
|
const citationFields = ['bibliography', 'references', 'csl', 'citation-style', 'nocite', 'link-citations', 'reference-section-title'];
|
||||||
|
const sanitized = { ...frontmatter };
|
||||||
|
|
||||||
|
for (const field of citationFields) {
|
||||||
|
delete sanitized[field];
|
||||||
|
}
|
||||||
|
|
||||||
|
return sanitized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 => {
|
||||||
|
const itemStr = typeof item === 'object' ? JSON.stringify(item) : String(item);
|
||||||
|
return `- ${itemStr}`;
|
||||||
|
}).join('\n') + '\n';
|
||||||
|
} else {
|
||||||
|
formattedValue = value.map(item =>
|
||||||
|
typeof item === 'object' ? JSON.stringify(item) : String(item)
|
||||||
|
).join(', ');
|
||||||
|
}
|
||||||
|
} else if (typeof value === 'object' && value !== null) {
|
||||||
|
formattedValue = JSON.stringify(value);
|
||||||
|
} else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||||
|
// Handle primitive values
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Handle null, undefined, or any other unexpected types
|
||||||
|
console.debug('FrontmatterProcessor: Unexpected type in frontmatter display formatting', `key: ${key}, type: ${typeof value}`);
|
||||||
|
formattedValue = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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'
|
||||||
|
};
|
||||||
+334
-256
@@ -1,253 +1,133 @@
|
|||||||
/**
|
/**
|
||||||
* Dependency checking utilities for Obsidian Typst PDF Export plugin
|
* Dependency checking utilities for Obsidian Typst PDF Export plugin.
|
||||||
|
*
|
||||||
|
* This module provides comprehensive dependency checking for the three external
|
||||||
|
* tools required by the plugin:
|
||||||
|
* - Pandoc: Converts Markdown to Typst markup
|
||||||
|
* - Typst: Compiles Typst markup to PDF
|
||||||
|
* - ImageMagick: Handles PDF-to-image conversion for embedded PDFs (optional)
|
||||||
|
*
|
||||||
|
* The module offers both async and sync checking methods, automatic startup
|
||||||
|
* validation, and user-facing status display functionality.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { DEPENDENCY_CONSTANTS } from './constants';
|
import { DEPENDENCY_CONSTANTS } from './constants';
|
||||||
|
import { ExportErrorHandler } from './ExportErrorHandler';
|
||||||
|
import { ExecutableChecker, DependencyInfo } from './ExecutableChecker';
|
||||||
|
|
||||||
export interface DependencyInfo {
|
/**
|
||||||
name: string;
|
* Complete result of a dependency check operation.
|
||||||
version: string | null;
|
*
|
||||||
isAvailable: boolean;
|
* @property pandoc - Detailed information about Pandoc installation
|
||||||
executablePath: string;
|
* @property typst - Detailed information about Typst installation
|
||||||
}
|
* @property imagemagick - Detailed information about ImageMagick installation
|
||||||
|
* @property allAvailable - True if all dependencies are available
|
||||||
|
* @property missingDependencies - Array of names of missing dependencies
|
||||||
|
* @property outdatedDependencies - Array of names of dependencies with versions below minimum
|
||||||
|
*/
|
||||||
export interface DependencyCheckResult {
|
export interface DependencyCheckResult {
|
||||||
pandoc: DependencyInfo;
|
pandoc: DependencyInfo;
|
||||||
typst: DependencyInfo;
|
typst: DependencyInfo;
|
||||||
imagemagick: DependencyInfo;
|
imagemagick: DependencyInfo;
|
||||||
allAvailable: boolean;
|
allAvailable: boolean;
|
||||||
missingDependencies: string[];
|
missingDependencies: string[];
|
||||||
|
outdatedDependencies: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities for checking external dependency availability and versions.
|
||||||
|
*
|
||||||
|
* This class provides static methods for validating that Pandoc, Typst, and
|
||||||
|
* ImageMagick are properly installed and accessible. It supports both async
|
||||||
|
* and sync operations, configurable executable paths, and user notifications.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Comprehensive async checking with version detection
|
||||||
|
* - Fast sync checking for startup validation
|
||||||
|
* - User-facing status display with formatted output
|
||||||
|
* - Silent background checking with error notifications
|
||||||
|
* - Support for custom executable paths and search directories
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Comprehensive check with version information
|
||||||
|
* const result = await DependencyChecker.checkAllDependencies(
|
||||||
|
* settings.pandocPath,
|
||||||
|
* settings.typstPath,
|
||||||
|
* settings.imagemagickPath,
|
||||||
|
* settings.additionalPaths
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (!result.allAvailable) {
|
||||||
|
* console.error('Missing:', result.missingDependencies);
|
||||||
|
* } else {
|
||||||
|
* console.log(`Pandoc ${result.pandoc.version} found`);
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Quick startup check
|
||||||
|
* const missing = DependencyChecker.checkDependenciesSync(
|
||||||
|
* settings.pandocPath,
|
||||||
|
* settings.typstPath
|
||||||
|
* );
|
||||||
|
* if (missing.length > 0) {
|
||||||
|
* console.error('Missing dependencies:', missing);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
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
|
* Performs comprehensive dependency checking with version detection (async).
|
||||||
*/
|
*
|
||||||
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
|
* This method checks all three required external tools (Pandoc, Typst, and
|
||||||
return {
|
* ImageMagick) in parallel for maximum efficiency. It resolves executable
|
||||||
...process.env,
|
* paths, verifies availability, and extracts version information using regex
|
||||||
PATH: this.getAugmentedPath(additionalPaths)
|
* patterns.
|
||||||
};
|
*
|
||||||
}
|
* The method supports custom executable paths from user settings and falls
|
||||||
|
* back to searching system PATH if paths are not specified. Additional search
|
||||||
/**
|
* directories can be provided to help locate tools in non-standard locations.
|
||||||
* Try to find an executable using which command
|
*
|
||||||
*/
|
* @param pandocPath - Optional custom path to Pandoc executable
|
||||||
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
|
* @param typstPath - Optional custom path to Typst executable
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich: searching for "${executableName}"`);
|
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
|
||||||
const { spawn } = require('child_process');
|
* @param additionalPaths - Additional directories to search for executables
|
||||||
|
* @returns Detailed dependency check result including version information
|
||||||
try {
|
*
|
||||||
const stdout = await new Promise<string>((resolve, reject) => {
|
* @example
|
||||||
const env = this.getAugmentedEnv(additionalPaths);
|
* ```typescript
|
||||||
console.log(`[DependencyChecker] findExecutableWithWhich: using PATH="${env.PATH}"`);
|
* // Check with default paths (searches system PATH)
|
||||||
|
* const result = await DependencyChecker.checkAllDependencies();
|
||||||
const whichProcess = spawn('which', [executableName], {
|
* if (result.allAvailable) {
|
||||||
stdio: ['pipe', 'pipe', 'pipe'],
|
* console.log('All dependencies found!');
|
||||||
env: env
|
* console.log(`Pandoc: ${result.pandoc.version}`);
|
||||||
});
|
* console.log(`Typst: ${result.typst.version}`);
|
||||||
|
* }
|
||||||
let output = '';
|
*
|
||||||
let error = '';
|
* // Check with custom paths and additional search directories
|
||||||
|
* const result = await DependencyChecker.checkAllDependencies(
|
||||||
whichProcess.stdout?.on('data', (data: Buffer) => {
|
* '/usr/local/bin/pandoc',
|
||||||
output += data.toString();
|
* '/opt/typst/bin/typst',
|
||||||
});
|
* '/usr/bin/convert',
|
||||||
|
* ['/opt/local/bin', '/usr/local/opt/bin']
|
||||||
whichProcess.stderr?.on('data', (data: Buffer) => {
|
* );
|
||||||
error += data.toString();
|
*
|
||||||
});
|
* // Handle missing dependencies
|
||||||
|
* if (!result.allAvailable) {
|
||||||
whichProcess.on('close', (code: number | null) => {
|
* console.error('Missing:', result.missingDependencies.join(', '));
|
||||||
console.log(`[DependencyChecker] which ${executableName} exited with code ${code}, stdout: "${output.trim()}", stderr: "${error.trim()}"`);
|
* result.missingDependencies.forEach(name => {
|
||||||
if (code === 0) {
|
* const dep = name === 'Pandoc' ? result.pandoc :
|
||||||
resolve(output);
|
* name === 'Typst' ? result.typst : result.imagemagick;
|
||||||
} else {
|
* console.error(`${name} not found at: ${dep.executablePath}`);
|
||||||
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
|
|
||||||
*/
|
*/
|
||||||
public static async checkAllDependencies(
|
public static async checkAllDependencies(
|
||||||
pandocPath?: string,
|
pandocPath?: string,
|
||||||
@@ -255,38 +135,84 @@ 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.]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.pandoc),
|
||||||
this.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/),
|
ExecutableChecker.checkDependency('Typst', typstExec, '--version', /typst\s+([\d.]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.typst),
|
||||||
this.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/)
|
ExecutableChecker.checkDependency('ImageMagick', imagemagickExec, '--version', /ImageMagick\s+([\d.-]+)/i, DEPENDENCY_CONSTANTS.MINIMUM_VERSIONS.imagemagick)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo]
|
const missingDependencies = [pandocInfo, typstInfo, imagemagickInfo]
|
||||||
.filter(dep => !dep.isAvailable)
|
.filter(dep => !dep.isAvailable)
|
||||||
.map(dep => dep.name);
|
.map(dep => dep.name);
|
||||||
|
|
||||||
|
const outdatedDependencies = [pandocInfo, typstInfo, imagemagickInfo]
|
||||||
|
.filter(dep => dep.isAvailable && !dep.meetsMinimumVersion)
|
||||||
|
.map(dep => dep.name);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
pandoc: pandocInfo,
|
pandoc: pandocInfo,
|
||||||
typst: typstInfo,
|
typst: typstInfo,
|
||||||
imagemagick: imagemagickInfo,
|
imagemagick: imagemagickInfo,
|
||||||
allAvailable: missingDependencies.length === 0,
|
allAvailable: missingDependencies.length === 0,
|
||||||
missingDependencies
|
missingDependencies,
|
||||||
|
outdatedDependencies
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Quick dependency check (synchronous) - returns list of missing dependencies
|
* Performs fast synchronous dependency checking without version detection.
|
||||||
|
*
|
||||||
|
* This is a simplified version of checkAllDependencies that only checks if
|
||||||
|
* executables can be run successfully (exit code 0), without extracting version
|
||||||
|
* information. It's designed for scenarios where async operations are not
|
||||||
|
* possible (e.g., plugin initialization) or when only availability matters.
|
||||||
|
*
|
||||||
|
* The method checks all three tools sequentially and returns a list of missing
|
||||||
|
* dependency names. Empty array indicates all dependencies are available.
|
||||||
|
*
|
||||||
|
* @param pandocPath - Optional custom path to Pandoc executable
|
||||||
|
* @param typstPath - Optional custom path to Typst executable
|
||||||
|
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
|
||||||
|
* @param additionalPaths - Additional directories to search for executables
|
||||||
|
* @returns Array of missing dependency names (empty if all available)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Quick startup check in plugin onload()
|
||||||
|
* const missing = DependencyChecker.checkDependenciesSync(
|
||||||
|
* this.settings.pandocPath,
|
||||||
|
* this.settings.typstPath,
|
||||||
|
* this.settings.imagemagickPath
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (missing.length > 0) {
|
||||||
|
* new Notice(`Missing dependencies: ${missing.join(', ')}`);
|
||||||
|
* return;
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Check with additional search paths
|
||||||
|
* const missing = DependencyChecker.checkDependenciesSync(
|
||||||
|
* undefined, // Use default Pandoc
|
||||||
|
* undefined, // Use default Typst
|
||||||
|
* undefined, // Use default ImageMagick
|
||||||
|
* ['/opt/local/bin', '~/.local/bin']
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // React based on specific missing tools
|
||||||
|
* if (missing.includes('Pandoc')) {
|
||||||
|
* console.error('Pandoc is required for Markdown conversion');
|
||||||
|
* }
|
||||||
|
* if (missing.includes('Typst')) {
|
||||||
|
* console.error('Typst is required for PDF generation');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static checkDependenciesSync(
|
public static checkDependenciesSync(
|
||||||
pandocPath?: string,
|
pandocPath?: string,
|
||||||
@@ -294,27 +220,179 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays dependency status in a user-facing notice with version information.
|
||||||
|
*
|
||||||
|
* This method performs a comprehensive dependency check and displays the results
|
||||||
|
* in an Obsidian notice modal. The notice includes:
|
||||||
|
* - Status of each dependency (version or "Not found")
|
||||||
|
* - Overall availability message
|
||||||
|
* - Installation instructions if dependencies are missing
|
||||||
|
*
|
||||||
|
* The notice is displayed for 12 seconds to give users time to read the detailed
|
||||||
|
* information. This method is typically called from the plugin's settings or via
|
||||||
|
* a command palette action.
|
||||||
|
*
|
||||||
|
* @param pandocPath - Optional custom path to Pandoc executable
|
||||||
|
* @param typstPath - Optional custom path to Typst executable
|
||||||
|
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
|
||||||
|
* @param additionalPaths - Additional directories to search for executables
|
||||||
|
* @returns Promise that resolves when the status has been displayed
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Display status from settings panel
|
||||||
|
* await DependencyChecker.showDependencyStatus(
|
||||||
|
* this.plugin.settings.pandocPath,
|
||||||
|
* this.plugin.settings.typstPath,
|
||||||
|
* this.plugin.settings.imagemagickPath
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Display status via command palette
|
||||||
|
* this.addCommand({
|
||||||
|
* id: 'check-dependencies',
|
||||||
|
* name: 'Check Dependencies',
|
||||||
|
* callback: async () => {
|
||||||
|
* await DependencyChecker.showDependencyStatus(
|
||||||
|
* this.settings.pandocPath,
|
||||||
|
* this.settings.typstPath,
|
||||||
|
* this.settings.imagemagickPath,
|
||||||
|
* this.settings.additionalPaths
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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) => {
|
||||||
|
if (!dep.isAvailable) return 'Not found';
|
||||||
|
if (!dep.meetsMinimumVersion) return `${dep.version} (minimum: ${dep.minimumVersion})`;
|
||||||
|
return dep.version || 'Available';
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusLines: string[] = [];
|
||||||
|
|
||||||
|
// Build status messages
|
||||||
|
if (!dependencyResult.allAvailable) {
|
||||||
|
statusLines.push(`Missing dependencies: ${dependencyResult.missingDependencies.join(', ')}. Please install them and check the paths in settings.`);
|
||||||
|
} else if (dependencyResult.outdatedDependencies.length > 0) {
|
||||||
|
statusLines.push(`⚠️ Outdated versions detected: ${dependencyResult.outdatedDependencies.join(', ')}.`);
|
||||||
|
statusLines.push(`Please update to avoid compatibility issues.`);
|
||||||
|
} else {
|
||||||
|
statusLines.push('✓ All dependencies found and up to date!');
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = `Dependency Status:
|
||||||
|
Pandoc: ${formatVersion(dependencyResult.pandoc)}
|
||||||
|
Typst: ${formatVersion(dependencyResult.typst)}
|
||||||
|
ImageMagick: ${formatVersion(dependencyResult.imagemagick)}
|
||||||
|
|
||||||
|
${statusLines.join('\n')}`;
|
||||||
|
|
||||||
|
ExportErrorHandler.showProgressNotice(message, 15000); // Show for 15 seconds (longer due to version info)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs silent dependency checking on plugin startup with error notifications.
|
||||||
|
*
|
||||||
|
* This method is designed for plugin initialization and performs a fast synchronous
|
||||||
|
* check of all dependencies. It only displays a notice if dependencies are missing,
|
||||||
|
* keeping the user experience clean when everything is working correctly.
|
||||||
|
*
|
||||||
|
* If dependencies are missing, a notice is shown for 8 seconds directing the user
|
||||||
|
* to run the full "Check Dependencies" command for detailed information. If an
|
||||||
|
* error occurs during checking, it's handled gracefully via ExportErrorHandler.
|
||||||
|
*
|
||||||
|
* This method should be called early in the plugin lifecycle (typically in onload)
|
||||||
|
* to ensure users are aware of missing dependencies before attempting exports.
|
||||||
|
*
|
||||||
|
* @param pandocPath - Optional custom path to Pandoc executable
|
||||||
|
* @param typstPath - Optional custom path to Typst executable
|
||||||
|
* @param imagemagickPath - Optional custom path to ImageMagick convert executable
|
||||||
|
* @param additionalPaths - Additional directories to search for executables
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Call during plugin initialization
|
||||||
|
* export default class MyPlugin extends Plugin {
|
||||||
|
* async onload() {
|
||||||
|
* await this.loadSettings();
|
||||||
|
*
|
||||||
|
* // Silent startup check - only shows notice if problems exist
|
||||||
|
* DependencyChecker.checkDependenciesOnStartup(
|
||||||
|
* this.settings.pandocPath,
|
||||||
|
* this.settings.typstPath,
|
||||||
|
* this.settings.imagemagickPath,
|
||||||
|
* this.settings.additionalPaths
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Continue with plugin initialization
|
||||||
|
* this.registerCommands();
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // User will see a notice only if dependencies are missing:
|
||||||
|
* // "Typst PDF Export: Missing dependencies: Pandoc, Typst.
|
||||||
|
* // Run 'Check Dependencies' command for details."
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static checkDependenciesOnStartup(
|
||||||
|
pandocPath?: string,
|
||||||
|
typstPath?: string,
|
||||||
|
imagemagickPath?: string,
|
||||||
|
additionalPaths: string[] = []
|
||||||
|
): 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,424 @@
|
|||||||
|
/**
|
||||||
|
* Executable checking utilities for Obsidian Typst PDF Export plugin.
|
||||||
|
*
|
||||||
|
* This module provides comprehensive utilities for checking external executable
|
||||||
|
* availability and versions. It handles:
|
||||||
|
* - Path resolution with support for system PATH and additional paths
|
||||||
|
* - Version detection using configurable regex patterns
|
||||||
|
* - Both async and sync operations for different use cases
|
||||||
|
* - Cross-platform path handling (Unix and Windows)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn, spawnSync } from 'child_process';
|
||||||
|
import { DEPENDENCY_CONSTANTS } from './constants';
|
||||||
|
import { isVersionAtLeast } from '../utils/versionUtils';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Information about a checked dependency executable.
|
||||||
|
*
|
||||||
|
* @property name - Human-readable name of the dependency (e.g., "Pandoc")
|
||||||
|
* @property version - Detected version string, or null if unavailable
|
||||||
|
* @property isAvailable - Whether the executable was found and executed successfully
|
||||||
|
* @property executablePath - The resolved path to the executable
|
||||||
|
* @property meetsMinimumVersion - Whether the version meets the minimum requirement (true if no version check performed)
|
||||||
|
* @property minimumVersion - The minimum required version string (null if not checked)
|
||||||
|
*/
|
||||||
|
export interface DependencyInfo {
|
||||||
|
name: string;
|
||||||
|
version: string | null;
|
||||||
|
isAvailable: boolean;
|
||||||
|
executablePath: string;
|
||||||
|
meetsMinimumVersion: boolean;
|
||||||
|
minimumVersion: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities for checking executable availability and versions.
|
||||||
|
*
|
||||||
|
* This class provides static methods for:
|
||||||
|
* - Resolving executable paths from user input or system PATH
|
||||||
|
* - Augmenting PATH with common system directories
|
||||||
|
* - Checking if executables are available
|
||||||
|
* - Detecting executable versions using regex patterns
|
||||||
|
*
|
||||||
|
* All methods support additional search paths to extend the default system PATH,
|
||||||
|
* ensuring executables can be found in non-standard locations.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Resolve path to pandoc executable
|
||||||
|
* const pandocPath = await ExecutableChecker.resolveExecutablePath(
|
||||||
|
* settings.pandocPath,
|
||||||
|
* 'pandoc',
|
||||||
|
* settings.additionalPaths
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Check if pandoc is available and get version
|
||||||
|
* const info = await ExecutableChecker.checkDependency(
|
||||||
|
* 'Pandoc',
|
||||||
|
* pandocPath,
|
||||||
|
* '--version',
|
||||||
|
* /pandoc (\d+\.\d+(?:\.\d+)?)/
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (info.isAvailable) {
|
||||||
|
* console.log(`Pandoc ${info.version} found at ${info.executablePath}`);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class ExecutableChecker {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds an augmented PATH string that includes common system paths and additional paths.
|
||||||
|
*
|
||||||
|
* This method combines the current process PATH with:
|
||||||
|
* 1. Home-relative paths (e.g., ~/.local/bin, ~/.cargo/bin)
|
||||||
|
* 2. Common absolute paths (e.g., /usr/local/bin, /opt/homebrew/bin)
|
||||||
|
* 3. User-provided additional paths
|
||||||
|
*
|
||||||
|
* The resulting PATH helps find executables in non-standard locations that
|
||||||
|
* might not be in the user's shell PATH when running from Obsidian.
|
||||||
|
*
|
||||||
|
* Uses platform-specific path delimiters (';' on Windows, ':' on Unix) and
|
||||||
|
* filters out empty segments to prevent PATH corruption.
|
||||||
|
*
|
||||||
|
* @param additionalPaths - Optional array of additional paths to include
|
||||||
|
* @returns The augmented PATH string with all paths separated by platform-specific delimiter
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
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];
|
||||||
|
|
||||||
|
// Use platform-specific delimiter (';' on Windows, ':' on Unix)
|
||||||
|
const delimiter = process.platform === 'win32' ? ';' : ':';
|
||||||
|
|
||||||
|
// Filter out empty segments and join with platform-specific delimiter
|
||||||
|
const segments = [
|
||||||
|
process.env.PATH ?? '',
|
||||||
|
...allAdditionalPaths.filter(p => p && p.trim() !== '')
|
||||||
|
];
|
||||||
|
return segments.filter(Boolean).join(delimiter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds an augmented environment object with extended PATH.
|
||||||
|
*
|
||||||
|
* Creates a new environment object that inherits all current process environment
|
||||||
|
* variables but with an augmented PATH that includes common system directories
|
||||||
|
* and any additional paths specified.
|
||||||
|
*
|
||||||
|
* @param additionalPaths - Optional array of additional paths to include in PATH
|
||||||
|
* @returns Environment object suitable for child_process spawn/exec
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
PATH: this.getAugmentedPath(additionalPaths)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempts to find an executable's full path using the `which` command.
|
||||||
|
*
|
||||||
|
* This method spawns a `which` subprocess with an augmented PATH to locate
|
||||||
|
* the executable. It's more reliable than simple PATH searches as it uses
|
||||||
|
* the system's own executable resolution logic.
|
||||||
|
*
|
||||||
|
* @param executableName - Name of the executable to find (e.g., 'pandoc')
|
||||||
|
* @param additionalPaths - Optional additional paths to search
|
||||||
|
* @returns The full path to the executable, or null if not found
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const pandocPath = await findExecutableWithWhich('pandoc', ['/opt/local/bin']);
|
||||||
|
* // Returns: '/usr/local/bin/pandoc' or null
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const stdout = await new Promise<string>((resolve, reject) => {
|
||||||
|
const env = this.getAugmentedEnv(additionalPaths);
|
||||||
|
|
||||||
|
// Use platform-specific command: 'where' on Windows, 'which' on Unix
|
||||||
|
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
|
||||||
|
|
||||||
|
const whichProcess = spawn(whichCommand, [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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an executable path from user input or system PATH (async version).
|
||||||
|
*
|
||||||
|
* Resolution logic:
|
||||||
|
* 1. If userPath contains a '/', treat it as an absolute/relative path and use as-is
|
||||||
|
* 2. If userPath is just a name or empty, search for the executable using `which`
|
||||||
|
* 3. If `which` fails, fall back to the executable name (relies on runtime PATH)
|
||||||
|
*
|
||||||
|
* This method is useful for allowing users to specify either full paths or just
|
||||||
|
* executable names in plugin settings.
|
||||||
|
*
|
||||||
|
* @param userPath - User-provided path or executable name (can be undefined/empty)
|
||||||
|
* @param defaultName - Default executable name to use if userPath is empty
|
||||||
|
* @param additionalPaths - Additional directories to search for the executable
|
||||||
|
* @returns Resolved path to use for spawning the executable
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // User provided full path
|
||||||
|
* const path1 = await resolveExecutablePath('/usr/local/bin/pandoc', 'pandoc');
|
||||||
|
* // Returns: '/usr/local/bin/pandoc'
|
||||||
|
*
|
||||||
|
* // User provided just name
|
||||||
|
* const path2 = await resolveExecutablePath('pandoc', 'pandoc');
|
||||||
|
* // Returns: '/usr/bin/pandoc' (found via which)
|
||||||
|
*
|
||||||
|
* // User provided nothing
|
||||||
|
* const path3 = await resolveExecutablePath('', 'typst', ['/opt/bin']);
|
||||||
|
* // Returns: '/opt/bin/typst' (found via which with additional path)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
|
||||||
|
// If user provided an absolute path, use it as-is
|
||||||
|
if (userPath && userPath.trim() !== '' && path.isAbsolute(userPath)) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an executable path from user input or system PATH (synchronous version).
|
||||||
|
*
|
||||||
|
* This is the synchronous counterpart to `resolveExecutablePath`. Use this when
|
||||||
|
* async operations are not possible (e.g., in constructors or sync initialization).
|
||||||
|
* The resolution logic is identical to the async version.
|
||||||
|
*
|
||||||
|
* @param userPath - User-provided path or executable name (can be undefined/empty)
|
||||||
|
* @param defaultName - Default executable name to use if userPath is empty
|
||||||
|
* @param additionalPaths - Additional directories to search for the executable
|
||||||
|
* @returns Resolved path to use for spawning the executable
|
||||||
|
*
|
||||||
|
* @see {@link resolveExecutablePath} for detailed resolution logic and examples
|
||||||
|
*/
|
||||||
|
public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
|
||||||
|
// If user provided an absolute path, use it as-is
|
||||||
|
if (userPath && userPath.trim() !== '' && path.isAbsolute(userPath)) {
|
||||||
|
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
|
||||||
|
// Use platform-specific command: 'where' on Windows, 'which' on Unix
|
||||||
|
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = spawnSync(whichCommand, [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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a dependency executable is available and extracts its version (async version).
|
||||||
|
*
|
||||||
|
* This method:
|
||||||
|
* 1. Spawns the executable with the version command (e.g., '--version')
|
||||||
|
* 2. Captures stdout and parses version using the provided regex
|
||||||
|
* 3. Optionally validates against minimum required version
|
||||||
|
* 4. Returns comprehensive dependency information
|
||||||
|
*
|
||||||
|
* Security: Uses spawn instead of exec to prevent command injection. Arguments
|
||||||
|
* are passed separately from the command.
|
||||||
|
*
|
||||||
|
* @param name - Human-readable name for the dependency (e.g., "Pandoc")
|
||||||
|
* @param executablePath - Path to the executable to check
|
||||||
|
* @param versionCommand - Command argument for version (e.g., '--version')
|
||||||
|
* @param versionRegex - Regex with capture group for version number
|
||||||
|
* @param minimumVersion - Optional minimum required version (e.g., "0.13.0")
|
||||||
|
* @returns DependencyInfo object with availability and version information
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const info = await ExecutableChecker.checkDependency(
|
||||||
|
* 'Pandoc',
|
||||||
|
* '/usr/bin/pandoc',
|
||||||
|
* '--version',
|
||||||
|
* /pandoc (\d+\.\d+(?:\.\d+)?)/,
|
||||||
|
* '3.7.0'
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* if (info.isAvailable && info.meetsMinimumVersion) {
|
||||||
|
* console.log(`Found ${info.name} version ${info.version}`);
|
||||||
|
* } else if (info.isAvailable) {
|
||||||
|
* console.warn(`${info.name} ${info.version} is below minimum ${info.minimumVersion}`);
|
||||||
|
* } else {
|
||||||
|
* console.error(`${info.name} not available at ${info.executablePath}`);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static async checkDependency(
|
||||||
|
name: string,
|
||||||
|
executablePath: string,
|
||||||
|
versionCommand: string,
|
||||||
|
versionRegex: RegExp,
|
||||||
|
minimumVersion: string | null = null
|
||||||
|
): Promise<DependencyInfo> {
|
||||||
|
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;
|
||||||
|
|
||||||
|
// Check version against minimum if both are available
|
||||||
|
const meetsMinimumVersion = minimumVersion && version
|
||||||
|
? isVersionAtLeast(version, minimumVersion)
|
||||||
|
: true; // No minimum version check or version unavailable
|
||||||
|
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
isAvailable: true,
|
||||||
|
executablePath,
|
||||||
|
meetsMinimumVersion,
|
||||||
|
minimumVersion
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
version: null,
|
||||||
|
isAvailable: false,
|
||||||
|
executablePath,
|
||||||
|
meetsMinimumVersion: true, // Not checking if unavailable
|
||||||
|
minimumVersion
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs a quick synchronous check if a dependency is available.
|
||||||
|
*
|
||||||
|
* This is a simplified version of `checkDependency` that only checks if the
|
||||||
|
* executable can be run successfully (exit code 0), without parsing version
|
||||||
|
* information. Useful for fast availability checks during initialization.
|
||||||
|
*
|
||||||
|
* @param executablePath - Path to the executable to check
|
||||||
|
* @param versionCommand - Command argument to test (e.g., '--version')
|
||||||
|
* @returns True if the executable runs successfully, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const pandocAvailable = ExecutableChecker.checkDependencySync('/usr/bin/pandoc', '--version');
|
||||||
|
* if (!pandocAvailable) {
|
||||||
|
* console.error('Pandoc not available');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static checkDependencySync(executablePath: string, versionCommand: string): boolean {
|
||||||
|
try {
|
||||||
|
const result = spawnSync(executablePath, versionCommand.split(' '), {
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: this.getAugmentedEnv()
|
||||||
|
});
|
||||||
|
return result.status === 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+371
-13
@@ -1,27 +1,118 @@
|
|||||||
/**
|
/**
|
||||||
* Centralized error handling utilities for export operations
|
* Centralized error handling utilities for export operations.
|
||||||
|
*
|
||||||
|
* This module provides a unified interface for handling all types of errors that
|
||||||
|
* can occur during PDF export operations. It standardizes error logging, user
|
||||||
|
* notifications, and error message formatting across the plugin.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Consistent error messaging and logging
|
||||||
|
* - Batch export result tracking and reporting
|
||||||
|
* - User-facing notices with appropriate durations
|
||||||
|
* - Support for different log levels (error, warn, debug)
|
||||||
|
* - Specialized handlers for different error types (dependency, processing, validation)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Notice } from 'obsidian';
|
import { Notice } from 'obsidian';
|
||||||
import { EXPORT_CONSTANTS } from './constants';
|
import { EXPORT_CONSTANTS } from './constants';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result summary for batch export operations.
|
||||||
|
*
|
||||||
|
* @property successful - Number of files exported successfully
|
||||||
|
* @property failed - Number of files that failed to export
|
||||||
|
* @property errors - Array of error messages for failed exports
|
||||||
|
*/
|
||||||
export interface BatchExportResult {
|
export interface BatchExportResult {
|
||||||
successful: number;
|
successful: number;
|
||||||
failed: number;
|
failed: number;
|
||||||
errors: string[];
|
errors: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Structured error information for export operations.
|
||||||
|
*
|
||||||
|
* @property fileName - Optional file name where the error occurred
|
||||||
|
* @property operation - Description of the operation that failed (e.g., "Pandoc conversion")
|
||||||
|
* @property error - The error object or message
|
||||||
|
* @property shouldShowNotice - Whether to display a user-facing notice (default: false)
|
||||||
|
* @property logLevel - Logging severity level (default: 'error')
|
||||||
|
*/
|
||||||
export interface ExportError {
|
export interface ExportError {
|
||||||
fileName?: string;
|
fileName?: string;
|
||||||
operation: string;
|
operation: string;
|
||||||
error: Error | string;
|
error: Error | string;
|
||||||
shouldShowNotice?: boolean;
|
shouldShowNotice?: boolean;
|
||||||
logLevel?: 'error' | 'warn' | 'info';
|
logLevel?: 'error' | 'warn' | 'debug';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Centralized error handler for all export-related errors.
|
||||||
|
*
|
||||||
|
* This class provides static utility methods for handling various error scenarios
|
||||||
|
* in the PDF export pipeline. It ensures consistent error reporting to both users
|
||||||
|
* (via Obsidian notices) and developers (via console logs).
|
||||||
|
*
|
||||||
|
* The handler supports:
|
||||||
|
* - Single and batch export error tracking
|
||||||
|
* - Context-specific error messages (dependencies, validation, processing)
|
||||||
|
* - Configurable notice durations based on error severity
|
||||||
|
* - Graceful error recovery with fallback content
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Handle single export error
|
||||||
|
* try {
|
||||||
|
* await exportFile(file);
|
||||||
|
* } catch (error) {
|
||||||
|
* ExportErrorHandler.handleSingleExportError(error);
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Track batch export results
|
||||||
|
* const batch = ExportErrorHandler.createBatchTracker();
|
||||||
|
* for (const file of files) {
|
||||||
|
* try {
|
||||||
|
* await exportFile(file);
|
||||||
|
* batch.recordSuccess();
|
||||||
|
* } catch (error) {
|
||||||
|
* batch.recordError(file.name, error);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ExportErrorHandler.handleBatchResult(batch.getResult(), 'Folder export');
|
||||||
|
*
|
||||||
|
* // Handle processing error with fallback
|
||||||
|
* try {
|
||||||
|
* return await processImage(path);
|
||||||
|
* } catch (error) {
|
||||||
|
* const { fallback } = ExportErrorHandler.handleProcessingError(
|
||||||
|
* 'Image',
|
||||||
|
* path,
|
||||||
|
* error,
|
||||||
|
* '![Image unavailable]'
|
||||||
|
* );
|
||||||
|
* return fallback;
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export class ExportErrorHandler {
|
export class ExportErrorHandler {
|
||||||
/**
|
/**
|
||||||
* Handle batch export results with consistent messaging
|
* Displays batch export results with user-friendly summary messages.
|
||||||
|
*
|
||||||
|
* This method analyzes batch export results and shows appropriate notices
|
||||||
|
* based on the outcome. For fully successful exports, shows a success message.
|
||||||
|
* For partial or complete failures, shows a summary with counts and logs
|
||||||
|
* detailed errors to the console.
|
||||||
|
*
|
||||||
|
* @param result - The batch export result containing success/failure counts and errors
|
||||||
|
* @param operationDescription - Description of the operation (e.g., 'Export', 'Folder export')
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const batch = { successful: 8, failed: 2, errors: ['file1: error', 'file2: error'] };
|
||||||
|
* ExportErrorHandler.handleBatchResult(batch, 'Folder export');
|
||||||
|
* // Shows: "Folder export complete: 8 successful, 2 failed"
|
||||||
|
* // Logs detailed errors to console
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static handleBatchResult(
|
public static handleBatchResult(
|
||||||
result: BatchExportResult,
|
result: BatchExportResult,
|
||||||
@@ -44,7 +135,36 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle individual export errors consistently
|
* Handles individual export errors with configurable logging and notifications.
|
||||||
|
*
|
||||||
|
* This method provides flexible error handling that supports different log levels
|
||||||
|
* and optional user notices. It normalizes error messages, logs them at the
|
||||||
|
* appropriate level, and optionally displays a notice to the user.
|
||||||
|
*
|
||||||
|
* @param exportError - Structured error information including operation context
|
||||||
|
* @returns Formatted error message string suitable for collection or display
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Handle with notice
|
||||||
|
* const message = ExportErrorHandler.handleExportError({
|
||||||
|
* fileName: 'document.md',
|
||||||
|
* operation: 'Pandoc conversion',
|
||||||
|
* error: new Error('Invalid syntax'),
|
||||||
|
* shouldShowNotice: true,
|
||||||
|
* logLevel: 'error'
|
||||||
|
* });
|
||||||
|
* // Shows notice: "Pandoc conversion failed: Invalid syntax"
|
||||||
|
* // Returns: "document.md: Invalid syntax"
|
||||||
|
*
|
||||||
|
* // Handle silently (just logging)
|
||||||
|
* const message = ExportErrorHandler.handleExportError({
|
||||||
|
* operation: 'Image processing',
|
||||||
|
* error: 'File not found',
|
||||||
|
* logLevel: 'warn'
|
||||||
|
* });
|
||||||
|
* // Logs warning but no notice
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static handleExportError(exportError: ExportError): string {
|
public static handleExportError(exportError: ExportError): string {
|
||||||
const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError;
|
const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError;
|
||||||
@@ -60,8 +180,8 @@ export class ExportErrorHandler {
|
|||||||
case 'warn':
|
case 'warn':
|
||||||
console.warn(`${operation}:`, error);
|
console.warn(`${operation}:`, error);
|
||||||
break;
|
break;
|
||||||
case 'info':
|
case 'debug':
|
||||||
console.info(`${operation}:`, error);
|
console.debug(`${operation}:`, error);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +194,44 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle processing errors for embeds and similar operations
|
* Handles processing errors with fallback content generation.
|
||||||
|
*
|
||||||
|
* This method is designed for operations that can gracefully degrade when errors
|
||||||
|
* occur, such as embed processing or image handling. It logs the error and returns
|
||||||
|
* both an error message and fallback content to use in place of the failed operation.
|
||||||
|
*
|
||||||
|
* The fallback content ensures exports can continue even when individual embeds or
|
||||||
|
* resources fail to process, providing a visible indication of the failure in the
|
||||||
|
* output document.
|
||||||
|
*
|
||||||
|
* @param operation - Description of the operation (e.g., 'Image', 'PDF embed')
|
||||||
|
* @param itemPath - Path to the item being processed
|
||||||
|
* @param error - The error that occurred
|
||||||
|
* @param fallbackContent - Optional custom fallback content (auto-generated if not provided)
|
||||||
|
* @returns Object with error message and fallback content to use
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* try {
|
||||||
|
* return await processWikilink(link);
|
||||||
|
* } catch (error) {
|
||||||
|
* const { fallback } = ExportErrorHandler.handleProcessingError(
|
||||||
|
* 'Wikilink',
|
||||||
|
* '[[MyNote]]',
|
||||||
|
* error,
|
||||||
|
* '[Link unavailable]'
|
||||||
|
* );
|
||||||
|
* return fallback; // Use fallback in output
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Without custom fallback
|
||||||
|
* const { fallback } = ExportErrorHandler.handleProcessingError(
|
||||||
|
* 'Image',
|
||||||
|
* 'path/to/image.png',
|
||||||
|
* new Error('Not found')
|
||||||
|
* );
|
||||||
|
* // fallback: "[⚠️ **Image processing error:** path/to/image.png]"
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static handleProcessingError(
|
public static handleProcessingError(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -96,7 +253,39 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a batch export tracker for consistent error collection
|
* Creates a batch export tracker for systematic result collection.
|
||||||
|
*
|
||||||
|
* This method returns an object with methods to track successes and failures
|
||||||
|
* during batch export operations. It maintains counters and collects error
|
||||||
|
* messages, providing a clean API for recording results as exports progress.
|
||||||
|
*
|
||||||
|
* The tracker automatically logs individual errors to the console and formats
|
||||||
|
* error messages with file names for later reporting. Use getResult() to obtain
|
||||||
|
* the final BatchExportResult for display with handleBatchResult().
|
||||||
|
*
|
||||||
|
* @returns Object with tracker state and methods for recording results
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const batch = ExportErrorHandler.createBatchTracker();
|
||||||
|
*
|
||||||
|
* for (const file of filesToExport) {
|
||||||
|
* try {
|
||||||
|
* await exportFile(file);
|
||||||
|
* batch.recordSuccess();
|
||||||
|
* } catch (error) {
|
||||||
|
* batch.recordError(file.name, error);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Display final results
|
||||||
|
* const result = batch.getResult();
|
||||||
|
* ExportErrorHandler.handleBatchResult(result, 'Folder export');
|
||||||
|
* // result: { successful: 8, failed: 2, errors: ['file1.md: Error message', ...] }
|
||||||
|
*
|
||||||
|
* // Direct access to tracker state
|
||||||
|
* console.log(`Progress: ${batch.tracker.successful} / ${filesToExport.length}`);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static createBatchTracker(): {
|
public static createBatchTracker(): {
|
||||||
tracker: BatchExportResult;
|
tracker: BatchExportResult;
|
||||||
@@ -128,7 +317,22 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle single file export errors with proper notices
|
* Handles single file export errors with console logging and user notice.
|
||||||
|
*
|
||||||
|
* This is a convenience method for simple export error scenarios where the
|
||||||
|
* error should always be logged and shown to the user. Use this for single
|
||||||
|
* file exports or when you don't need the complexity of structured error handling.
|
||||||
|
*
|
||||||
|
* @param error - The error that occurred during export
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* try {
|
||||||
|
* await exportCurrentNote();
|
||||||
|
* } catch (error) {
|
||||||
|
* ExportErrorHandler.handleSingleExportError(error);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static handleSingleExportError(error: Error | string): void {
|
public static handleSingleExportError(error: Error | string): void {
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
@@ -137,7 +341,24 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle dependency or configuration errors
|
* Handles dependency checking or configuration errors with optional notices.
|
||||||
|
*
|
||||||
|
* This method is specifically for errors that occur during dependency validation
|
||||||
|
* or configuration loading. It supports silent error handling (logging only) or
|
||||||
|
* user-visible notices with extended duration for readability.
|
||||||
|
*
|
||||||
|
* @param dependency - Name of the dependency or configuration item
|
||||||
|
* @param error - The error that occurred
|
||||||
|
* @param showNotice - Whether to display a user-facing notice (default: true)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* try {
|
||||||
|
* await checkPandocVersion();
|
||||||
|
* } catch (error) {
|
||||||
|
* ExportErrorHandler.handleDependencyError('Pandoc', error);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static handleDependencyError(
|
public static handleDependencyError(
|
||||||
dependency: string,
|
dependency: string,
|
||||||
@@ -146,7 +367,7 @@ export class ExportErrorHandler {
|
|||||||
): void {
|
): void {
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
console.error(`Error checking ${dependency}:`, error);
|
console.error(`Error checking ${dependency}:`, error);
|
||||||
|
|
||||||
if (showNotice) {
|
if (showNotice) {
|
||||||
new Notice(
|
new Notice(
|
||||||
`${dependency} error: ${errorMessage}`,
|
`${dependency} error: ${errorMessage}`,
|
||||||
@@ -156,16 +377,153 @@ export class ExportErrorHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show export progress notice
|
* Displays a progress or informational notice with configurable duration.
|
||||||
|
*
|
||||||
|
* @param message - The message to display
|
||||||
|
* @param timeout - Optional duration in milliseconds (0 = persist until dismissed)
|
||||||
|
* @returns The Notice object for potential manual dismissal
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const notice = ExportErrorHandler.showProgressNotice('Exporting...', 0);
|
||||||
|
* await performExport();
|
||||||
|
* notice.hide(); // Dismiss when done
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static showProgressNotice(message: string, timeout?: number): Notice {
|
public static showProgressNotice(message: string, timeout?: number): Notice {
|
||||||
return new Notice(message, timeout || 0);
|
return new Notice(message, timeout || 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show export cancellation notice
|
* Displays a cancellation notice when user aborts an export operation.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* if (userCancelled) {
|
||||||
|
* ExportErrorHandler.showCancellationNotice();
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static showCancellationNotice(): void {
|
public static showCancellationNotice(): void {
|
||||||
new Notice('Export cancelled');
|
new Notice('Export cancelled');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a validation error for invalid settings or input.
|
||||||
|
*
|
||||||
|
* @param field - Name of the field that failed validation
|
||||||
|
* @param validationMessage - Explanation of why validation failed
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* if (pageSize < 0) {
|
||||||
|
* ExportErrorHandler.showValidationError('page size', 'must be positive');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static showValidationError(field: string, validationMessage: string): void {
|
||||||
|
new Notice(`Invalid ${field}: ${validationMessage}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays an error when template loading fails.
|
||||||
|
*
|
||||||
|
* @param error - The error that occurred during template loading
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* try {
|
||||||
|
* await loadTemplate(name);
|
||||||
|
* } catch (error) {
|
||||||
|
* ExportErrorHandler.showTemplateError(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}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays an error when font caching fails, with fallback notification.
|
||||||
|
*
|
||||||
|
* @param error - The error that occurred during font caching
|
||||||
|
* @param showFallback - Whether to show additional fallback notice (default: true)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* try {
|
||||||
|
* await cacheSystemFonts();
|
||||||
|
* } catch (error) {
|
||||||
|
* ExportErrorHandler.showFontError(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a success notice when export completes successfully.
|
||||||
|
*
|
||||||
|
* @param outputPath - Path where the PDF was saved
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* ExportErrorHandler.showExportSuccess('/path/to/output.pdf');
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static showExportSuccess(outputPath: string): void {
|
||||||
|
new Notice(`PDF exported successfully to ${outputPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a warning when no active file is available for export.
|
||||||
|
*
|
||||||
|
* @param context - Description of the expected file type (e.g., 'Markdown')
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* if (!activeFile) {
|
||||||
|
* ExportErrorHandler.showFileNotFoundWarning('Markdown');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static showFileNotFoundWarning(context: string): void {
|
||||||
|
new Notice(`Please open a ${context} file to export`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a warning when no files are available for batch export.
|
||||||
|
*
|
||||||
|
* @param context - Description of the file type (default: 'files')
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* if (files.length === 0) {
|
||||||
|
* ExportErrorHandler.showNoFilesWarning('Markdown files');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static showNoFilesWarning(context: string = 'files'): void {
|
||||||
|
new Notice(`No ${context} to export`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a confirmation notice when settings are reset to defaults.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* resetToDefaults();
|
||||||
|
* ExportErrorHandler.showSettingsReset();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static showSettingsReset(): void {
|
||||||
|
new Notice('Settings reset to defaults');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+179
-13
@@ -1,11 +1,30 @@
|
|||||||
/**
|
/**
|
||||||
* Helper utilities for preparing export modal settings
|
* Helper utilities for preparing export modal settings.
|
||||||
|
*
|
||||||
|
* This module provides utilities for transforming plugin settings and file context
|
||||||
|
* into the format expected by the export configuration modal. It handles both single
|
||||||
|
* and multi-file export scenarios, extracting defaults from plugin settings and
|
||||||
|
* building template variable objects.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Automatic template variable extraction from plugin settings
|
||||||
|
* - Multi-file export support with automatic title generation
|
||||||
|
* - Landscape mode width adjustment for single-page exports
|
||||||
|
* - Clean separation between single and multi-file modal preparation
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { TFile } from 'obsidian';
|
import { TFile } from 'obsidian';
|
||||||
import { obsidianTypstPDFExportSettings } from './settings';
|
import { obsidianTypstPDFExportSettings, ExportFormat } from './settings';
|
||||||
import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
|
import { ExportConfigModalSettings } from '../ui/modal/modalTypes';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Input parameters for modal settings preparation.
|
||||||
|
*
|
||||||
|
* @property file - Primary file for the export
|
||||||
|
* @property additionalFiles - Additional files for multi-file export (optional)
|
||||||
|
* @property availableTemplates - List of available template names
|
||||||
|
* @property settings - Plugin settings to extract defaults from
|
||||||
|
*/
|
||||||
export interface ModalSettingsInput {
|
export interface ModalSettingsInput {
|
||||||
/** Primary file for the export */
|
/** Primary file for the export */
|
||||||
file: TFile;
|
file: TFile;
|
||||||
@@ -17,9 +36,75 @@ export interface ModalSettingsInput {
|
|||||||
settings: obsidianTypstPDFExportSettings;
|
settings: obsidianTypstPDFExportSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility class for preparing export modal configuration from plugin settings.
|
||||||
|
*
|
||||||
|
* This class transforms plugin settings into the format required by the export
|
||||||
|
* configuration modal. It extracts defaults for all export options and builds
|
||||||
|
* template variable objects that can be customized in the modal before export.
|
||||||
|
*
|
||||||
|
* The helper handles special cases like:
|
||||||
|
* - Multi-file export title formatting ("5 files" instead of filename)
|
||||||
|
* - Landscape orientation width adjustments for single-page exports
|
||||||
|
* - Template variable extraction from typography and page setup settings
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Single file export
|
||||||
|
* const modalSettings = ModalSettingsHelper.prepareForSingleFile(
|
||||||
|
* file,
|
||||||
|
* ['default', 'modern', 'article'],
|
||||||
|
* this.plugin.settings
|
||||||
|
* );
|
||||||
|
* const modal = new ExportConfigModal(this.app, modalSettings, async (config) => {
|
||||||
|
* await this.exportWithConfig(config);
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // Multi-file export
|
||||||
|
* const modalSettings = ModalSettingsHelper.prepareForMultiFile(
|
||||||
|
* selectedFiles,
|
||||||
|
* ['default', 'modern'],
|
||||||
|
* this.plugin.settings
|
||||||
|
* );
|
||||||
|
* // Modal title will show "5 files" if 5 files selected
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export class ModalSettingsHelper {
|
export class ModalSettingsHelper {
|
||||||
/**
|
/**
|
||||||
* Prepare modal settings from plugin defaults and file context
|
* Prepares modal settings from plugin defaults and file context.
|
||||||
|
*
|
||||||
|
* This is the core method that transforms plugin settings and file information
|
||||||
|
* into the format expected by ExportConfigModal. It automatically detects multi-file
|
||||||
|
* scenarios, builds template variables from plugin settings, and extracts export
|
||||||
|
* defaults.
|
||||||
|
*
|
||||||
|
* For multi-file exports, the modal title is set to "{count} files" instead of
|
||||||
|
* the primary file name. Template variables include automatic width adjustment
|
||||||
|
* for landscape single-page exports.
|
||||||
|
*
|
||||||
|
* @param input - Configuration object containing file(s), templates, and settings
|
||||||
|
* @returns Partial modal settings ready for ExportConfigModal initialization
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Single file
|
||||||
|
* const settings = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
* file: activeFile,
|
||||||
|
* availableTemplates: ['default', 'modern'],
|
||||||
|
* settings: this.settings
|
||||||
|
* });
|
||||||
|
* // settings.noteTitle = "My Note"
|
||||||
|
*
|
||||||
|
* // Multiple files
|
||||||
|
* const settings = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
* file: files[0],
|
||||||
|
* additionalFiles: files.slice(1),
|
||||||
|
* availableTemplates: ['default'],
|
||||||
|
* settings: this.settings
|
||||||
|
* });
|
||||||
|
* // settings.noteTitle = "5 files"
|
||||||
|
* // settings.files = [file1, file2, file3, file4, file5]
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static prepareModalSettings(input: ModalSettingsInput): Partial<ExportConfigModalSettings> {
|
public static prepareModalSettings(input: ModalSettingsInput): Partial<ExportConfigModalSettings> {
|
||||||
const { file, additionalFiles, availableTemplates, settings } = input;
|
const { file, additionalFiles, availableTemplates, settings } = input;
|
||||||
@@ -50,9 +135,35 @@ export class ModalSettingsHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build template variables object from plugin settings
|
* Builds template variables object from plugin settings.
|
||||||
|
*
|
||||||
|
* This method extracts typography and page setup settings and formats them
|
||||||
|
* as template variables suitable for Typst compilation. It handles special cases
|
||||||
|
* like automatic width adjustment for landscape single-page exports.
|
||||||
|
*
|
||||||
|
* Variables include:
|
||||||
|
* - Page setup: pageSize, orientation, flipped, margins (top/bottom/left/right)
|
||||||
|
* - Typography: bodyFont, headingFont, monospaceFont, bodyFontSize
|
||||||
|
* - Format-specific: width='auto' for landscape single-page mode
|
||||||
|
*
|
||||||
|
* @param settings - Plugin settings containing typography and page setup configuration
|
||||||
|
* @returns Object with template variables ready for Pandoc/Typst
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const vars = ModalSettingsHelper.buildTemplateVariables(settings);
|
||||||
|
* // {
|
||||||
|
* // pageSize: 'a4',
|
||||||
|
* // orientation: 'landscape',
|
||||||
|
* // flipped: true, // auto-set for landscape
|
||||||
|
* // marginTop: '71',
|
||||||
|
* // bodyFont: 'Georgia',
|
||||||
|
* // width: 'auto' // for landscape single-page
|
||||||
|
* // }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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,
|
||||||
@@ -68,8 +179,8 @@ export class ModalSettingsHelper {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Auto-adjust width for single-page landscape mode
|
// Auto-adjust width for single-page landscape mode
|
||||||
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
|
const landscapeAdjustment = settings.pageSetup.orientation === 'landscape'
|
||||||
&& settings.exportDefaults.format === 'single-page'
|
&& settings.exportDefaults.format === ExportFormat.SinglePage
|
||||||
? { width: 'auto' }
|
? { width: 'auto' }
|
||||||
: {};
|
: {};
|
||||||
|
|
||||||
@@ -80,11 +191,35 @@ export class ModalSettingsHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper for single file export modal settings
|
* Convenience method for preparing modal settings for single file export.
|
||||||
|
*
|
||||||
|
* This is a simplified wrapper around prepareModalSettings for the common case
|
||||||
|
* of exporting a single file. It automatically sets up the modal with the file's
|
||||||
|
* basename as the title and extracts all defaults from plugin settings.
|
||||||
|
*
|
||||||
|
* @param file - The file to export
|
||||||
|
* @param availableTemplates - List of available template names
|
||||||
|
* @param settings - Plugin settings for default extraction
|
||||||
|
* @returns Partial modal settings for single file export
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const activeFile = this.app.workspace.getActiveFile();
|
||||||
|
* if (activeFile) {
|
||||||
|
* const modalSettings = ModalSettingsHelper.prepareForSingleFile(
|
||||||
|
* activeFile,
|
||||||
|
* this.templateManager.getAvailableTemplates(),
|
||||||
|
* this.settings
|
||||||
|
* );
|
||||||
|
* new ExportConfigModal(this.app, modalSettings, async (config) => {
|
||||||
|
* await this.exportFile(activeFile, config);
|
||||||
|
* }).open();
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static prepareForSingleFile(
|
public static prepareForSingleFile(
|
||||||
file: TFile,
|
file: TFile,
|
||||||
availableTemplates: string[],
|
availableTemplates: string[],
|
||||||
settings: obsidianTypstPDFExportSettings
|
settings: obsidianTypstPDFExportSettings
|
||||||
): Partial<ExportConfigModalSettings> {
|
): Partial<ExportConfigModalSettings> {
|
||||||
return this.prepareModalSettings({
|
return this.prepareModalSettings({
|
||||||
@@ -95,11 +230,42 @@ export class ModalSettingsHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper for multi-file export modal settings
|
* Convenience method for preparing modal settings for multi-file export.
|
||||||
|
*
|
||||||
|
* This method handles batch export scenarios where multiple files should be
|
||||||
|
* exported together. It automatically splits the files array into primary and
|
||||||
|
* additional files, and sets the modal title to show the file count.
|
||||||
|
*
|
||||||
|
* The first file in the array becomes the primary file (used for initial path
|
||||||
|
* resolution), and the remaining files are treated as additional files for the
|
||||||
|
* batch export.
|
||||||
|
*
|
||||||
|
* @param files - Array of files to export (must contain at least one file)
|
||||||
|
* @param availableTemplates - List of available template names
|
||||||
|
* @param settings - Plugin settings for default extraction
|
||||||
|
* @returns Partial modal settings for multi-file export with "{count} files" title
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Export all files in a folder
|
||||||
|
* const folder = this.app.vault.getAbstractFileByPath('my-folder');
|
||||||
|
* if (folder instanceof TFolder) {
|
||||||
|
* const files = folder.children.filter(f => f instanceof TFile) as TFile[];
|
||||||
|
* const modalSettings = ModalSettingsHelper.prepareForMultiFile(
|
||||||
|
* files,
|
||||||
|
* this.templateManager.getAvailableTemplates(),
|
||||||
|
* this.settings
|
||||||
|
* );
|
||||||
|
* // modalSettings.noteTitle = "15 files" (if 15 files)
|
||||||
|
* new ExportConfigModal(this.app, modalSettings, async (config) => {
|
||||||
|
* await this.exportFiles(files, config);
|
||||||
|
* }).open();
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public static prepareForMultiFile(
|
public static prepareForMultiFile(
|
||||||
files: TFile[],
|
files: TFile[],
|
||||||
availableTemplates: string[],
|
availableTemplates: string[],
|
||||||
settings: obsidianTypstPDFExportSettings
|
settings: obsidianTypstPDFExportSettings
|
||||||
): Partial<ExportConfigModalSettings> {
|
): Partial<ExportConfigModalSettings> {
|
||||||
const [primaryFile, ...additionalFiles] = files;
|
const [primaryFile, ...additionalFiles] = files;
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
// ABOUTME: Centralized path utilities for safe Obsidian API operations
|
||||||
|
// ABOUTME: Handles vault paths, plugin directories, and file operations
|
||||||
|
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
import { FileSystemAdapter, normalizePath, Notice } from 'obsidian';
|
||||||
|
import type { App, PluginManifest } from 'obsidian';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Centralized path utilities for safe Obsidian API operations.
|
||||||
|
*
|
||||||
|
* This class provides a unified interface for path operations that work correctly
|
||||||
|
* with both vault-relative and absolute filesystem paths. It handles cross-platform
|
||||||
|
* path normalization and provides safe wrappers around Obsidian's vault adapter.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Automatic path normalization for cross-platform compatibility
|
||||||
|
* - Safe handling of absolute and relative paths
|
||||||
|
* - FileSystemAdapter validation for desktop-only operations
|
||||||
|
* - Error handling with user notifications
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const pathUtils = new PathUtils(app);
|
||||||
|
* const vaultPath = pathUtils.getVaultPath();
|
||||||
|
* const pluginDir = pathUtils.getPluginDir(manifest);
|
||||||
|
* const fullPath = pathUtils.joinPath(vaultPath, pluginDir, 'templates');
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class PathUtils {
|
||||||
|
/**
|
||||||
|
* Creates a new PathUtils instance.
|
||||||
|
*
|
||||||
|
* @param app - The Obsidian App instance used for vault operations
|
||||||
|
*/
|
||||||
|
constructor(private app: App) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the absolute filesystem path to the vault root directory.
|
||||||
|
*
|
||||||
|
* This method requires desktop Obsidian as it relies on FileSystemAdapter.
|
||||||
|
* If the adapter is not available (e.g., mobile), it will show a notice
|
||||||
|
* and throw an error.
|
||||||
|
*
|
||||||
|
* @returns The absolute path to the vault root directory
|
||||||
|
* @throws {Error} If FileSystemAdapter is not available (non-desktop environment)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const vaultPath = pathUtils.getVaultPath();
|
||||||
|
* // Returns: '/Users/username/Documents/MyVault'
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the vault-relative path to the plugin directory.
|
||||||
|
*
|
||||||
|
* Extracts the directory path from the plugin manifest and normalizes it
|
||||||
|
* for cross-platform compatibility. This is typically something like
|
||||||
|
* '.obsidian/plugins/plugin-name'.
|
||||||
|
*
|
||||||
|
* @param pluginManifest - The plugin's manifest containing directory information
|
||||||
|
* @returns The normalized vault-relative path to the plugin directory
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const pluginDir = pathUtils.getPluginDir(this.manifest);
|
||||||
|
* // Returns: '.obsidian/plugins/typst-pdf-export'
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
getPluginDir(pluginManifest: PluginManifest): string {
|
||||||
|
return normalizePath(pluginManifest.dir || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Joins multiple path segments into a single normalized path.
|
||||||
|
*
|
||||||
|
* This method filters out empty segments, joins them using Node's path.join,
|
||||||
|
* and normalizes the result for Obsidian compatibility. It correctly handles
|
||||||
|
* absolute paths by using Node's standard path joining behavior (which uses
|
||||||
|
* the rightmost absolute path if multiple absolute paths are provided).
|
||||||
|
*
|
||||||
|
* @param segments - Variable number of path segments to join
|
||||||
|
* @returns The joined and normalized path, or empty string if no segments
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const fullPath = pathUtils.joinPath(vaultPath, '.obsidian', 'plugins', 'my-plugin');
|
||||||
|
* // Returns: '/path/to/vault/.obsidian/plugins/my-plugin'
|
||||||
|
*
|
||||||
|
* const withEmpty = pathUtils.joinPath('folder', '', 'subfolder');
|
||||||
|
* // Returns: 'folder/subfolder' (empty segments filtered)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
joinPath(...segments: string[]): string {
|
||||||
|
const filtered = segments.filter(s => s);
|
||||||
|
if (filtered.length === 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
const result = path.join(...filtered);
|
||||||
|
// Don't use normalizePath on absolute paths as it strips the leading slash
|
||||||
|
// Only normalize vault-relative paths
|
||||||
|
if (path.isAbsolute(result)) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
return normalizePath(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures a directory exists, creating it if necessary.
|
||||||
|
*
|
||||||
|
* This method checks if the directory exists and creates it if it doesn't.
|
||||||
|
* The path is automatically normalized before operations. If creation fails,
|
||||||
|
* a notice is shown to the user and the error is re-thrown.
|
||||||
|
*
|
||||||
|
* @param path - The path to the directory (vault-relative or absolute)
|
||||||
|
* @throws {Error} If directory creation fails
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* await pathUtils.ensureDir('.obsidian/plugins/my-plugin/temp');
|
||||||
|
* // Creates directory if it doesn't exist
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
const userMessage = `Failed to create output directory "${normalizedPath}". ${errorMessage.includes('parent') || errorMessage.includes('ENOENT') ? 'The parent directory may not exist or you may not have write permissions.' : 'You may not have write permissions or the path is invalid.'}`;
|
||||||
|
new Notice(userMessage);
|
||||||
|
throw new Error(userMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleans up directory contents by removing all files (but not subdirectories).
|
||||||
|
*
|
||||||
|
* This method removes only the files directly within the directory, leaving
|
||||||
|
* any subdirectories intact. This matches the behavior of TempDirectoryManager
|
||||||
|
* for safe cleanup operations. If the directory doesn't exist or cleanup fails,
|
||||||
|
* the method returns false and logs a warning.
|
||||||
|
*
|
||||||
|
* @param path - The path to the directory to clean (vault-relative or absolute)
|
||||||
|
* @returns True if cleanup succeeded or directory doesn't exist, false on error
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const success = await pathUtils.cleanupDir('temp-images');
|
||||||
|
* if (success) {
|
||||||
|
* console.log('Temp directory cleaned');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a file or directory exists at the given path.
|
||||||
|
*
|
||||||
|
* This method intelligently handles multiple path formats:
|
||||||
|
* 1. First attempts as vault-relative path
|
||||||
|
* 2. If that fails and path is within vault, converts absolute to relative
|
||||||
|
* 3. For paths outside vault, uses Node's fs module directly
|
||||||
|
*
|
||||||
|
* Supports:
|
||||||
|
* - Vault-relative paths: 'folder/file.md'
|
||||||
|
* - Absolute Unix paths: '/home/user/vault/file.md'
|
||||||
|
* - Windows drive letters: 'C:\\Users\\vault\\file.md'
|
||||||
|
* - Windows UNC paths: '\\\\server\\share\\file.md'
|
||||||
|
*
|
||||||
|
* @param path - The path to check (vault-relative or absolute)
|
||||||
|
* @returns True if the file or directory exists, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Check vault-relative path
|
||||||
|
* const exists = await pathUtils.fileExists('templates/default.typ');
|
||||||
|
*
|
||||||
|
* // Check absolute path
|
||||||
|
* const exists = await pathUtils.fileExists('/usr/bin/pandoc');
|
||||||
|
*
|
||||||
|
* // Check Windows path
|
||||||
|
* const exists = await pathUtils.fileExists('C:\\Program Files\\Pandoc\\pandoc.exe');
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
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 {
|
||||||
|
await fs.access(path);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts an absolute path to a vault-relative path.
|
||||||
|
*
|
||||||
|
* This method is used to convert absolute filesystem paths to vault-relative
|
||||||
|
* paths suitable for use with Obsidian's vault adapter operations. If the path
|
||||||
|
* does not start with the vault base path, it is returned unchanged.
|
||||||
|
*
|
||||||
|
* @param absolutePath - The absolute path to convert
|
||||||
|
* @returns The vault-relative path (without leading slash) or the original path if not within vault
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const pathUtils = new PathUtils(app);
|
||||||
|
* const vaultPath = '/Users/name/vault';
|
||||||
|
* const absolutePath = '/Users/name/vault/folder/file.md';
|
||||||
|
* const relative = pathUtils.toVaultRelative(absolutePath);
|
||||||
|
* // Returns: 'folder/file.md'
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
toVaultRelative(absolutePath: string): string {
|
||||||
|
const vaultBasePath = this.getVaultPath();
|
||||||
|
if (!absolutePath.startsWith(vaultBasePath)) {
|
||||||
|
return absolutePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
let relativePath = absolutePath.substring(vaultBasePath.length);
|
||||||
|
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
|
||||||
|
relativePath = relativePath.substring(1);
|
||||||
|
}
|
||||||
|
return relativePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
+302
-31
@@ -1,26 +1,132 @@
|
|||||||
/**
|
/**
|
||||||
* Security utilities for path validation and sanitization
|
* Security utilities for path validation and command injection prevention.
|
||||||
|
*
|
||||||
|
* This module provides critical security validation for user-provided paths and
|
||||||
|
* executable configurations to prevent common security vulnerabilities including:
|
||||||
|
* - Directory traversal attacks (../ path manipulation)
|
||||||
|
* - Command injection via shell metacharacters
|
||||||
|
* - Null byte injection attacks
|
||||||
|
* - Windows reserved name exploitation
|
||||||
|
* - Path manipulation via special characters
|
||||||
|
*
|
||||||
|
* All validation methods in this module are designed to fail safely - when in doubt,
|
||||||
|
* they reject the input rather than risk a security vulnerability. This defensive
|
||||||
|
* approach ensures the plugin cannot be exploited to access files outside the vault
|
||||||
|
* or execute arbitrary commands.
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Output path validation for PDF export destinations
|
||||||
|
* - Executable path validation for Pandoc/Typst/ImageMagick
|
||||||
|
* - Human-readable error messages for user feedback
|
||||||
|
* - Cross-platform security checks (Windows and Unix)
|
||||||
|
* - Zero-tolerance for suspicious patterns
|
||||||
|
*
|
||||||
|
* Security principles:
|
||||||
|
* - Whitelist approach where possible (allow known-safe patterns)
|
||||||
|
* - Multiple validation layers for defense in depth
|
||||||
|
* - Clear error messages without exposing implementation details
|
||||||
|
* - No automatic sanitization (reject rather than attempt to fix)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Security validation utilities for safe path and executable handling.
|
||||||
|
*
|
||||||
|
* This class provides static methods for validating user-provided paths and
|
||||||
|
* executable configurations before they are used in file operations or shell
|
||||||
|
* commands. All methods are designed with a security-first mindset:
|
||||||
|
* - Fail closed (reject when uncertain)
|
||||||
|
* - Multiple validation layers
|
||||||
|
* - No implicit trust of user input
|
||||||
|
* - Clear security error messages
|
||||||
|
*
|
||||||
|
* Use these methods to validate all user-configurable paths before:
|
||||||
|
* - Writing exported PDF files
|
||||||
|
* - Creating temporary directories
|
||||||
|
* - Executing external tools (Pandoc, Typst, ImageMagick)
|
||||||
|
* - Resolving output file paths
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Validate user-provided output folder
|
||||||
|
* const userFolder = settings.outputFolder;
|
||||||
|
* if (!SecurityUtils.validateOutputPath(userFolder)) {
|
||||||
|
* const error = SecurityUtils.getPathValidationError(userFolder);
|
||||||
|
* throw new Error(`Invalid output path: ${error}`);
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Safe to use the folder
|
||||||
|
* await exportToPDF(file, userFolder);
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Validate executable path before spawning process
|
||||||
|
* const pandocPath = settings.pandocPath;
|
||||||
|
* if (!SecurityUtils.validateExecutablePath(pandocPath)) {
|
||||||
|
* const error = SecurityUtils.getExecutablePathValidationError(pandocPath);
|
||||||
|
* new Notice(`Invalid Pandoc path: ${error}`);
|
||||||
|
* return;
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Safe to spawn process with this path
|
||||||
|
* spawn(pandocPath, args);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export class SecurityUtils {
|
export class SecurityUtils {
|
||||||
/**
|
/**
|
||||||
* Validates that an output folder path is safe and doesn't contain traversal attempts
|
* Validates that an output folder path is safe for file operations.
|
||||||
* @param outputFolder The folder path to validate
|
*
|
||||||
* @returns true if the path is safe, false otherwise
|
* This method performs comprehensive security checks to prevent directory
|
||||||
|
* traversal attacks and path manipulation. It rejects:
|
||||||
|
* - Directory traversal attempts (..)
|
||||||
|
* - Absolute paths (must be relative to vault root)
|
||||||
|
* - Null bytes and control characters
|
||||||
|
* - Double slashes and other suspicious patterns
|
||||||
|
* - Invalid filename characters (<>:"|?*)
|
||||||
|
* - Windows reserved system names in any path segment (CON, PRN, AUX, etc.)
|
||||||
|
* including when followed by extensions (e.g., CON.txt, AUX.log)
|
||||||
|
*
|
||||||
|
* The validation is intentionally strict - when in doubt, reject the path
|
||||||
|
* rather than risk a security vulnerability. Use getPathValidationError()
|
||||||
|
* to provide specific feedback to the user about why their path was rejected.
|
||||||
|
*
|
||||||
|
* @param outputFolder - The relative folder path to validate
|
||||||
|
* @returns True if the path is safe for file operations, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Valid relative paths
|
||||||
|
* SecurityUtils.validateOutputPath('exports'); // true
|
||||||
|
* SecurityUtils.validateOutputPath('exports/pdfs'); // true
|
||||||
|
* SecurityUtils.validateOutputPath('my documents'); // true
|
||||||
|
*
|
||||||
|
* // Invalid paths (security risks)
|
||||||
|
* SecurityUtils.validateOutputPath('../../../etc'); // false - traversal
|
||||||
|
* SecurityUtils.validateOutputPath('/tmp/evil'); // false - absolute
|
||||||
|
* SecurityUtils.validateOutputPath('CON'); // false - reserved name
|
||||||
|
* SecurityUtils.validateOutputPath('reports/CON/file'); // false - reserved in segment
|
||||||
|
* SecurityUtils.validateOutputPath('AUX.txt'); // false - reserved with extension
|
||||||
|
* SecurityUtils.validateOutputPath('test<>file'); // false - invalid chars
|
||||||
|
* SecurityUtils.validateOutputPath('path//with//double'); // false - suspicious
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
static validateOutputPath(outputFolder: string): boolean {
|
static validateOutputPath(outputFolder: string): boolean {
|
||||||
if (!outputFolder || typeof outputFolder !== 'string') {
|
if (!outputFolder || typeof outputFolder !== 'string') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normalize and resolve the path to detect traversal attempts
|
// Normalize path (reject absolute paths so exports stay inside the vault)
|
||||||
const normalizedPath = path.normalize(outputFolder.trim());
|
const trimmed = outputFolder.trim();
|
||||||
|
if (path.isAbsolute(trimmed)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const normalizedPath = path.normalize(trimmed);
|
||||||
|
|
||||||
// Check for path traversal attempts
|
// Check for path traversal attempts
|
||||||
if (normalizedPath.includes('..') ||
|
if (normalizedPath.includes('..') ||
|
||||||
normalizedPath.startsWith('/') ||
|
normalizedPath.startsWith('/') ||
|
||||||
normalizedPath.startsWith('\\') ||
|
normalizedPath.startsWith('\\') ||
|
||||||
normalizedPath.includes('\x00')) {
|
normalizedPath.includes('\x00')) {
|
||||||
return false;
|
return false;
|
||||||
@@ -30,17 +136,80 @@ export class SecurityUtils {
|
|||||||
const suspiciousPatterns = [
|
const suspiciousPatterns = [
|
||||||
/\.\./, // Directory traversal
|
/\.\./, // Directory traversal
|
||||||
/\/\//, // Double slashes
|
/\/\//, // Double slashes
|
||||||
/[<>:"|?*]/, // Invalid filename characters
|
/[<>:"|?*]/ // Invalid filename characters
|
||||||
/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i // Windows reserved names
|
|
||||||
];
|
];
|
||||||
|
|
||||||
return !suspiciousPatterns.some(pattern => pattern.test(normalizedPath));
|
if (suspiciousPatterns.some(pattern => pattern.test(normalizedPath))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for Windows reserved names in any path segment
|
||||||
|
// Reserved names are invalid even with extensions (e.g., CON.txt, AUX.log)
|
||||||
|
const reservedNamePattern = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
|
||||||
|
const hasReservedName = normalizedPath
|
||||||
|
.split(/[\\/]+/)
|
||||||
|
.filter(segment => segment && segment !== '.')
|
||||||
|
.some(segment => {
|
||||||
|
// Strip extension and check base name
|
||||||
|
const baseName = segment.split('.')[0] ?? '';
|
||||||
|
return reservedNamePattern.test(baseName);
|
||||||
|
});
|
||||||
|
|
||||||
|
return !hasReservedName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates that an executable path is safe for use in shell commands
|
* Validates that an executable path is safe for use in shell commands.
|
||||||
* @param executablePath The executable path to validate
|
*
|
||||||
* @returns true if the path is safe, false otherwise
|
* This method prevents command injection attacks by detecting shell
|
||||||
|
* metacharacters and command substitution patterns that could be used to
|
||||||
|
* execute arbitrary commands. It rejects paths containing:
|
||||||
|
* - Shell metacharacters (;&|`$(){}[]<>)
|
||||||
|
* - Null bytes and control characters
|
||||||
|
* - Newlines and carriage returns
|
||||||
|
* - Command separators (with or without whitespace)
|
||||||
|
* - Variable substitution patterns (${var}, $var)
|
||||||
|
* - Command substitution patterns (`cmd`, $(cmd))
|
||||||
|
*
|
||||||
|
* Empty or whitespace-only paths are allowed (plugin will use system PATH).
|
||||||
|
* This enables users to simply specify executable names like 'pandoc' rather
|
||||||
|
* than full paths, relying on shell resolution.
|
||||||
|
*
|
||||||
|
* Use getExecutablePathValidationError() to provide specific feedback about
|
||||||
|
* why an executable path was rejected.
|
||||||
|
*
|
||||||
|
* @param executablePath - The executable path or name to validate
|
||||||
|
* @returns True if the path is safe for shell execution, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Valid executable paths
|
||||||
|
* SecurityUtils.validateExecutablePath(''); // true - use PATH
|
||||||
|
* SecurityUtils.validateExecutablePath('pandoc'); // true - simple name
|
||||||
|
* SecurityUtils.validateExecutablePath('/usr/bin/pandoc'); // true - full path
|
||||||
|
* SecurityUtils.validateExecutablePath('/opt/typst'); // true - full path
|
||||||
|
* SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe'); // true
|
||||||
|
*
|
||||||
|
* // Invalid paths (command injection risks)
|
||||||
|
* SecurityUtils.validateExecutablePath('pandoc; rm -rf /'); // false - separator
|
||||||
|
* SecurityUtils.validateExecutablePath('$(evil)'); // false - substitution
|
||||||
|
* SecurityUtils.validateExecutablePath('`malicious`'); // false - substitution
|
||||||
|
* SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd'); // false - pipe
|
||||||
|
* SecurityUtils.validateExecutablePath('${HOME}/bin/fake'); // false - variable
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Use with spawn to prevent injection
|
||||||
|
* const userPath = settings.pandocPath;
|
||||||
|
* if (SecurityUtils.validateExecutablePath(userPath)) {
|
||||||
|
* // Safe to use with spawn (arguments passed separately)
|
||||||
|
* const process = spawn(userPath || 'pandoc', ['--version']);
|
||||||
|
* } else {
|
||||||
|
* const error = SecurityUtils.getExecutablePathValidationError(userPath);
|
||||||
|
* throw new Error(`Security violation: ${error}`);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
static validateExecutablePath(executablePath: string): boolean {
|
static validateExecutablePath(executablePath: string): boolean {
|
||||||
// Allow empty paths (will use system PATH)
|
// Allow empty paths (will use system PATH)
|
||||||
@@ -52,7 +221,8 @@ export class SecurityUtils {
|
|||||||
|
|
||||||
// Check for command injection attempts
|
// Check for command injection attempts
|
||||||
const dangerousPatterns = [
|
const dangerousPatterns = [
|
||||||
/[;&|`$(){}[\]]/, // Shell metacharacters
|
/[;&|`$<>{}[\]]/, // Shell metacharacters that can't appear in safe paths
|
||||||
|
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
|
||||||
/\x00/, // Null bytes
|
/\x00/, // Null bytes
|
||||||
/\n|\r/, // Newlines
|
/\n|\r/, // Newlines
|
||||||
/\s*[;&|]\s*/, // Command separators with whitespace
|
/\s*[;&|]\s*/, // Command separators with whitespace
|
||||||
@@ -65,17 +235,63 @@ export class SecurityUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a human-readable error message for invalid paths
|
* Generates a human-readable error message explaining why a path is invalid.
|
||||||
* @param outputFolder The invalid path
|
*
|
||||||
* @returns Description of why the path is invalid
|
* This method provides specific, actionable feedback to users when their
|
||||||
|
* output folder path fails validation. It identifies the exact security issue
|
||||||
|
* detected and explains it in user-friendly terms without exposing technical
|
||||||
|
* implementation details.
|
||||||
|
*
|
||||||
|
* The method checks for issues in priority order, returning the most critical
|
||||||
|
* security violation first. Use this alongside validateOutputPath() to provide
|
||||||
|
* clear feedback in error messages and UI validation.
|
||||||
|
*
|
||||||
|
* @param outputFolder - The path that failed validation
|
||||||
|
* @returns Descriptive error message explaining why the path is invalid
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Provide clear validation feedback in settings
|
||||||
|
* const userPath = folderInput.value;
|
||||||
|
* if (!SecurityUtils.validateOutputPath(userPath)) {
|
||||||
|
* const error = SecurityUtils.getPathValidationError(userPath);
|
||||||
|
* new Notice(`Invalid output folder: ${error}`);
|
||||||
|
* return;
|
||||||
|
* }
|
||||||
|
* // Continue with valid path...
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Display specific error for different violations
|
||||||
|
* const testPaths = [
|
||||||
|
* '../../../etc', // "Path traversal attempts (..) are not allowed"
|
||||||
|
* '/absolute/path', // "Absolute paths are not allowed..."
|
||||||
|
* 'CON', // "Reserved system names are not allowed in paths (found: CON)"
|
||||||
|
* 'reports/AUX/file', // "Reserved system names are not allowed in paths (found: AUX)"
|
||||||
|
* 'COM1.txt', // "Reserved system names are not allowed in paths (found: COM1.txt)"
|
||||||
|
* 'invalid<>chars' // "Invalid characters found in path"
|
||||||
|
* ];
|
||||||
|
*
|
||||||
|
* testPaths.forEach(path => {
|
||||||
|
* if (!SecurityUtils.validateOutputPath(path)) {
|
||||||
|
* console.error(`${path}: ${SecurityUtils.getPathValidationError(path)}`);
|
||||||
|
* }
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
static getPathValidationError(outputFolder: string): string {
|
static getPathValidationError(outputFolder: string): string {
|
||||||
if (!outputFolder || typeof outputFolder !== 'string') {
|
if (!outputFolder || typeof outputFolder !== 'string') {
|
||||||
return 'Output folder is required';
|
return 'Output folder is required';
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedPath = path.normalize(outputFolder.trim());
|
// Normalize path (reject absolute paths so exports stay inside the vault)
|
||||||
|
const trimmed = outputFolder.trim();
|
||||||
|
if (path.isAbsolute(trimmed)) {
|
||||||
|
return 'Absolute paths are not allowed - use relative paths from vault root';
|
||||||
|
}
|
||||||
|
const normalizedPath = path.normalize(trimmed);
|
||||||
|
|
||||||
if (normalizedPath.includes('..')) {
|
if (normalizedPath.includes('..')) {
|
||||||
return 'Path traversal attempts (..) are not allowed';
|
return 'Path traversal attempts (..) are not allowed';
|
||||||
}
|
}
|
||||||
@@ -91,17 +307,71 @@ export class SecurityUtils {
|
|||||||
if (/[<>:"|?*]/.test(normalizedPath)) {
|
if (/[<>:"|?*]/.test(normalizedPath)) {
|
||||||
return 'Invalid characters found in path';
|
return 'Invalid characters found in path';
|
||||||
}
|
}
|
||||||
if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(normalizedPath)) {
|
|
||||||
return 'Reserved system names are not allowed as folder names';
|
// Check for Windows reserved names in any path segment
|
||||||
|
const reservedNamePattern = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
|
||||||
|
const reservedSegment = normalizedPath
|
||||||
|
.split(/[\\/]+/)
|
||||||
|
.filter(segment => segment && segment !== '.')
|
||||||
|
.find(segment => {
|
||||||
|
const baseName = segment.split('.')[0] ?? '';
|
||||||
|
return reservedNamePattern.test(baseName);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (reservedSegment) {
|
||||||
|
return `Reserved system names are not allowed in paths (found: ${reservedSegment})`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Invalid path format';
|
return 'Invalid path format';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a human-readable error message for invalid executable paths
|
* Generates a human-readable error message for invalid executable paths.
|
||||||
* @param executablePath The invalid executable path
|
*
|
||||||
* @returns Description of why the path is invalid
|
* This method provides specific, security-focused feedback when an executable
|
||||||
|
* path fails validation. It identifies command injection attempts and explains
|
||||||
|
* them in terms users can understand without revealing exploit techniques.
|
||||||
|
*
|
||||||
|
* The error messages are designed to be clear about the security risk while
|
||||||
|
* remaining user-friendly. Use this alongside validateExecutablePath() to
|
||||||
|
* provide actionable feedback when users configure external tool paths.
|
||||||
|
*
|
||||||
|
* @param executablePath - The executable path that failed validation
|
||||||
|
* @returns Descriptive error message explaining the security issue
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Validate Pandoc path in settings with clear feedback
|
||||||
|
* const pandocPath = pandocInput.value;
|
||||||
|
* if (!SecurityUtils.validateExecutablePath(pandocPath)) {
|
||||||
|
* const error = SecurityUtils.getExecutablePathValidationError(pandocPath);
|
||||||
|
* new Notice(`Invalid Pandoc path: ${error}`, 8000);
|
||||||
|
* pandocInput.addClass('error');
|
||||||
|
* return;
|
||||||
|
* }
|
||||||
|
* pandocInput.removeClass('error');
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Log security violations for monitoring
|
||||||
|
* function validateAndLogExecutable(name: string, path: string): boolean {
|
||||||
|
* if (!SecurityUtils.validateExecutablePath(path)) {
|
||||||
|
* const error = SecurityUtils.getExecutablePathValidationError(path);
|
||||||
|
* console.error(`Security: Rejected ${name} path: ${error}`);
|
||||||
|
* console.error(`Attempted path: ${path.substring(0, 50)}...`);
|
||||||
|
* return false;
|
||||||
|
* }
|
||||||
|
* return true;
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Validate all external tools
|
||||||
|
* const valid = [
|
||||||
|
* validateAndLogExecutable('Pandoc', settings.pandocPath),
|
||||||
|
* validateAndLogExecutable('Typst', settings.typstPath),
|
||||||
|
* validateAndLogExecutable('ImageMagick', settings.imagemagickPath)
|
||||||
|
* ].every(v => v);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
static getExecutablePathValidationError(executablePath: string): string {
|
static getExecutablePathValidationError(executablePath: string): string {
|
||||||
if (!executablePath || typeof executablePath !== 'string') {
|
if (!executablePath || typeof executablePath !== 'string') {
|
||||||
@@ -110,9 +380,10 @@ export class SecurityUtils {
|
|||||||
|
|
||||||
const normalizedPath = path.normalize(executablePath.trim());
|
const normalizedPath = path.normalize(executablePath.trim());
|
||||||
|
|
||||||
if (/[;&|`$(){}[\]]/.test(normalizedPath)) {
|
if (/[;&|`$<>]/.test(normalizedPath)) {
|
||||||
return 'Shell metacharacters are not allowed in executable paths';
|
return 'Shell metacharacters are not allowed in executable paths';
|
||||||
}
|
}
|
||||||
|
// eslint-disable-next-line no-control-regex -- Intentionally checking for null byte character for security validation
|
||||||
if (/\x00/.test(normalizedPath)) {
|
if (/\x00/.test(normalizedPath)) {
|
||||||
return 'Null bytes are not allowed in paths';
|
return 'Null bytes are not allowed in paths';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,39 @@
|
|||||||
/**
|
/**
|
||||||
* Manages temporary directories for export operations
|
* Temporary directory management for Obsidian Typst PDF Export plugin.
|
||||||
|
*
|
||||||
|
* This module provides centralized management of temporary directories used during
|
||||||
|
* the PDF export process. It handles creation, cleanup, and validation of temporary
|
||||||
|
* storage locations for intermediate files such as:
|
||||||
|
* - Converted images from embedded PDFs
|
||||||
|
* - Intermediate Pandoc processing files
|
||||||
|
* - Temporary Typst compilation artifacts
|
||||||
|
*
|
||||||
|
* Key features:
|
||||||
|
* - Cross-platform path handling using Obsidian's normalizePath
|
||||||
|
* - Automatic directory creation on first use
|
||||||
|
* - Safe cleanup that preserves directory structure
|
||||||
|
* - Plugin-scoped temporary directories within .obsidian folder
|
||||||
|
* - Validation utilities for path security
|
||||||
|
*
|
||||||
|
* The manager creates temporary directories at:
|
||||||
|
* `<vault>/.obsidian/plugins/typst-pdf-export/temp-images/`
|
||||||
|
* `<vault>/.obsidian/plugins/typst-pdf-export/temp-pandoc/`
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { PLUGIN_DIRS } from './constants';
|
import { PLUGIN_DIRS } from './constants';
|
||||||
|
import { normalizePath } from 'obsidian';
|
||||||
|
import type { App } from 'obsidian';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration options for TempDirectoryManager initialization.
|
||||||
|
*
|
||||||
|
* @property vaultPath - Absolute path to the vault root directory
|
||||||
|
* @property configDir - Configuration directory path (typically '.obsidian')
|
||||||
|
* @property pluginName - Optional custom plugin directory name (defaults to 'typst-pdf-export')
|
||||||
|
* @property app - Obsidian App instance for vault.adapter file operations
|
||||||
|
*/
|
||||||
export interface TempDirectoryOptions {
|
export interface TempDirectoryOptions {
|
||||||
/** Base path for the vault */
|
/** Base path for the vault */
|
||||||
vaultPath: string;
|
vaultPath: string;
|
||||||
@@ -11,97 +41,431 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manager for plugin temporary directories used during PDF export operations.
|
||||||
|
*
|
||||||
|
* This class provides a centralized interface for managing temporary file storage
|
||||||
|
* during the Markdown → Typst → PDF conversion pipeline. It handles the full
|
||||||
|
* lifecycle of temporary directories:
|
||||||
|
* - Automatic directory creation on first use
|
||||||
|
* - Type-specific directory paths (images vs. pandoc processing)
|
||||||
|
* - Safe cleanup that removes files but preserves directory structure
|
||||||
|
* - Cross-platform path handling with proper normalization
|
||||||
|
* - Security validation to prevent directory traversal attacks
|
||||||
|
*
|
||||||
|
* The manager uses Obsidian's vault.adapter API for all file operations, ensuring
|
||||||
|
* compatibility with desktop-only features and proper permission handling.
|
||||||
|
*
|
||||||
|
* Temporary Directory Structure:
|
||||||
|
* ```
|
||||||
|
* <vault>/.obsidian/plugins/typst-pdf-export/
|
||||||
|
* ├── temp-images/ # Converted images from embedded PDFs
|
||||||
|
* └── temp-pandoc/ # Intermediate Pandoc/Typst processing files
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Lifecycle:
|
||||||
|
* 1. Initialize manager with vault path and app instance
|
||||||
|
* 2. Call ensureTempDir() to create directories as needed
|
||||||
|
* 3. Use getTempDir() to resolve paths for file operations
|
||||||
|
* 4. Call cleanupTempDir() to remove temporary files (preserves directories)
|
||||||
|
* 5. Use isPluginTempDir() to validate paths before operations
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Initialize for a specific vault
|
||||||
|
* const manager = new TempDirectoryManager({
|
||||||
|
* vaultPath: '/Users/name/vault',
|
||||||
|
* configDir: '.obsidian',
|
||||||
|
* app: this.app
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // Ensure temp directories exist before export
|
||||||
|
* const imagesDir = await manager.ensureTempDir('images');
|
||||||
|
* const pandocDir = await manager.ensureTempDir('pandoc');
|
||||||
|
*
|
||||||
|
* // Use directories for file operations
|
||||||
|
* await this.app.vault.adapter.write(
|
||||||
|
* `${imagesDir}/converted-pdf-page-1.png`,
|
||||||
|
* imageData
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Clean up after export
|
||||||
|
* await manager.cleanupAllTempDirs();
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Factory method for quick initialization
|
||||||
|
* const manager = TempDirectoryManager.create(
|
||||||
|
* vaultPath,
|
||||||
|
* '.obsidian',
|
||||||
|
* 'typst-pdf-export',
|
||||||
|
* app
|
||||||
|
* );
|
||||||
|
*
|
||||||
|
* // Validate paths before operations
|
||||||
|
* const userPath = '/some/user/provided/path';
|
||||||
|
* if (manager.isPluginTempDir(userPath)) {
|
||||||
|
* // Safe to operate on this path
|
||||||
|
* await manager.cleanupTempDir('images');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new TempDirectoryManager instance.
|
||||||
|
*
|
||||||
|
* Initializes the manager with vault configuration and Obsidian app instance.
|
||||||
|
* The manager will create temporary directories within the plugin folder using
|
||||||
|
* the provided paths.
|
||||||
|
*
|
||||||
|
* @param options - Configuration options for the temp directory manager
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const manager = new TempDirectoryManager({
|
||||||
|
* vaultPath: this.app.vault.adapter.getBasePath(),
|
||||||
|
* configDir: this.app.vault.configDir,
|
||||||
|
* pluginName: 'typst-pdf-export',
|
||||||
|
* app: this.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
|
* Resolves the absolute path to the plugin directory.
|
||||||
|
*
|
||||||
|
* Constructs the full path to the plugin's directory within the vault's
|
||||||
|
* .obsidian/plugins folder. Uses Node.js path.join for proper cross-platform
|
||||||
|
* path handling (Windows drive letters, Unix-style paths) and Obsidian's
|
||||||
|
* normalizePath to ensure consistent forward slashes.
|
||||||
|
*
|
||||||
|
* @returns Normalized absolute path to plugin directory
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // On Unix: '/Users/name/vault/.obsidian/plugins/typst-pdf-export'
|
||||||
|
* // On Windows: 'C:/Users/name/vault/.obsidian/plugins/typst-pdf-export'
|
||||||
|
* const pluginDir = this.getPluginDir();
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
private getPluginDir(): string {
|
private getPluginDir(): string {
|
||||||
return this.path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
|
// path.join automatically handles absolute paths correctly
|
||||||
|
const result = path.join(this.vaultPath, this.configDir, 'plugins', this.pluginName);
|
||||||
|
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||||
|
return path.isAbsolute(result) ? result : normalizePath(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the path for a specific temp directory
|
* Resolves the path for a specific temporary directory type.
|
||||||
|
*
|
||||||
|
* Returns the absolute path to either the images or pandoc temporary directory
|
||||||
|
* without creating it. Use ensureTempDir() to also create the directory if it
|
||||||
|
* doesn't exist.
|
||||||
|
*
|
||||||
|
* Directory types:
|
||||||
|
* - 'images': For converted images from embedded PDF files
|
||||||
|
* - 'pandoc': For intermediate Pandoc/Typst processing files
|
||||||
|
*
|
||||||
|
* Paths use Obsidian's normalizePath to ensure consistent forward slashes
|
||||||
|
* across all platforms.
|
||||||
|
*
|
||||||
|
* @param type - Type of temporary directory ('images' or 'pandoc')
|
||||||
|
* @returns Normalized absolute path to the temporary directory
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const imagesPath = manager.getTempDir('images');
|
||||||
|
* // Returns: '<vault>/.obsidian/plugins/typst-pdf-export/temp-images'
|
||||||
|
*
|
||||||
|
* const pandocPath = manager.getTempDir('pandoc');
|
||||||
|
* // Returns: '<vault>/.obsidian/plugins/typst-pdf-export/temp-pandoc'
|
||||||
|
*
|
||||||
|
* // Use with vault adapter for file operations
|
||||||
|
* const outputPath = `${imagesPath}/converted-page-1.png`;
|
||||||
|
* await this.app.vault.adapter.write(outputPath, imageData);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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);
|
const pluginDir = this.getPluginDir();
|
||||||
|
|
||||||
|
// Use path.join to properly handle absolute paths
|
||||||
|
const result = path.join(pluginDir, dirName);
|
||||||
|
|
||||||
|
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||||
|
return path.isAbsolute(result) ? result : normalizePath(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure a temp directory exists, creating it if necessary
|
* Ensures a temporary directory exists, creating it if necessary.
|
||||||
|
*
|
||||||
|
* This method checks if the specified temporary directory exists and creates
|
||||||
|
* it if missing. It uses Obsidian's vault.adapter API for directory creation,
|
||||||
|
* ensuring proper permissions and cross-platform compatibility.
|
||||||
|
*
|
||||||
|
* This is the recommended method to use before writing temporary files, as it
|
||||||
|
* handles both path resolution and directory creation in a single call.
|
||||||
|
*
|
||||||
|
* @param type - Type of temporary directory ('images' or 'pandoc')
|
||||||
|
* @returns Promise resolving to the normalized absolute path of the directory
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Ensure images directory exists before conversion
|
||||||
|
* const imagesDir = await manager.ensureTempDir('images');
|
||||||
|
* console.log('Images directory ready:', imagesDir);
|
||||||
|
* // Output: Images directory ready: /vault/.obsidian/plugins/typst-pdf-export/temp-images
|
||||||
|
*
|
||||||
|
* // Write converted image file
|
||||||
|
* await this.app.vault.adapter.write(
|
||||||
|
* `${imagesDir}/pdf-page-1.png`,
|
||||||
|
* imageBuffer
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Ensure both directories exist before export
|
||||||
|
* const [imagesDir, pandocDir] = await Promise.all([
|
||||||
|
* manager.ensureTempDir('images'),
|
||||||
|
* manager.ensureTempDir('pandoc')
|
||||||
|
* ]);
|
||||||
|
*
|
||||||
|
* // Use directories for export pipeline
|
||||||
|
* await convertPdfToImages(pdfPath, imagesDir);
|
||||||
|
* await runPandocConversion(inputPath, pandocDir);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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)) {
|
// Use fs.mkdir for temp directories since external tools (pdf2img, ImageMagick)
|
||||||
this.fs.mkdirSync(tempDir, { recursive: true });
|
// need to write to them directly with absolute paths
|
||||||
|
try {
|
||||||
|
await fs.access(tempDir);
|
||||||
|
} catch {
|
||||||
|
// Directory doesn't exist, create it with recursive option
|
||||||
|
await fs.mkdir(tempDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
return tempDir;
|
return tempDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up a specific temp directory
|
* Cleans up temporary files from a specific directory.
|
||||||
|
*
|
||||||
|
* This method removes all files from the specified temporary directory while
|
||||||
|
* preserving the directory structure itself. It only removes files, not
|
||||||
|
* subdirectories, ensuring that the temporary directory remains ready for
|
||||||
|
* future use.
|
||||||
|
*
|
||||||
|
* Cleanup failures are logged to the console but don't throw errors, allowing
|
||||||
|
* the export process to continue even if cleanup encounters issues. This is
|
||||||
|
* important for user experience - a failed cleanup shouldn't prevent export
|
||||||
|
* completion.
|
||||||
|
*
|
||||||
|
* @param type - Type of temporary directory to clean ('images' or 'pandoc')
|
||||||
|
* @returns Promise resolving to true if cleanup succeeded, false if it failed
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Clean up after successful export
|
||||||
|
* const success = await manager.cleanupTempDir('images');
|
||||||
|
* if (success) {
|
||||||
|
* console.log('Temporary images cleaned up');
|
||||||
|
* } else {
|
||||||
|
* console.warn('Cleanup failed, but export completed');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Clean up in finally block to ensure cleanup even on errors
|
||||||
|
* try {
|
||||||
|
* await exportToPDF(file);
|
||||||
|
* } finally {
|
||||||
|
* await manager.cleanupTempDir('pandoc');
|
||||||
|
* await manager.cleanupTempDir('images');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
public cleanupTempDir(type: 'images' | 'pandoc'): boolean {
|
public async cleanupTempDir(type: 'images' | 'pandoc'): Promise<boolean> {
|
||||||
const tempDir = this.getTempDir(type);
|
const tempDir = this.getTempDir(type);
|
||||||
|
|
||||||
|
// Use fs for temp directory cleanup since these directories contain
|
||||||
|
// files created by external tools
|
||||||
try {
|
try {
|
||||||
if (this.fs.existsSync(tempDir)) {
|
const exists = await fs.access(tempDir).then(() => true).catch(() => false);
|
||||||
const files = this.fs.readdirSync(tempDir);
|
if (exists) {
|
||||||
|
const files = await fs.readdir(tempDir);
|
||||||
|
// Remove only files, not subdirectories (matching current pattern)
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
this.fs.unlinkSync(this.path.join(tempDir, file));
|
const filePath = path.join(tempDir, file);
|
||||||
|
const stat = await fs.stat(filePath);
|
||||||
|
if (stat.isFile()) {
|
||||||
|
await fs.unlink(filePath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
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
|
* Cleans up all temporary directories in a single operation.
|
||||||
|
*
|
||||||
|
* This convenience method calls cleanupTempDir() for both the images and
|
||||||
|
* pandoc directories, running the cleanups in parallel for efficiency. It
|
||||||
|
* returns the success status for each directory independently, allowing
|
||||||
|
* partial cleanup if one directory fails.
|
||||||
|
*
|
||||||
|
* Use this method at the end of export operations to remove all temporary
|
||||||
|
* files created during the conversion process.
|
||||||
|
*
|
||||||
|
* @returns Promise resolving to object with cleanup success status for each directory type
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Clean up all temp directories after export
|
||||||
|
* const result = await manager.cleanupAllTempDirs();
|
||||||
|
* console.log('Images cleanup:', result.images ? 'Success' : 'Failed');
|
||||||
|
* console.log('Pandoc cleanup:', result.pandoc ? 'Success' : 'Failed');
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Use in plugin unload to ensure cleanup on disable
|
||||||
|
* async onunload() {
|
||||||
|
* await this.tempManager.cleanupAllTempDirs();
|
||||||
|
* console.log('Temporary files cleaned up');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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
|
* Factory method for creating a TempDirectoryManager instance.
|
||||||
|
*
|
||||||
|
* This static convenience method provides a simpler way to instantiate the
|
||||||
|
* manager when you have individual parameters rather than an options object.
|
||||||
|
* It's particularly useful when parameters are obtained separately from
|
||||||
|
* different sources.
|
||||||
|
*
|
||||||
|
* @param vaultPath - Absolute path to the vault root directory
|
||||||
|
* @param configDir - Configuration directory path (typically '.obsidian')
|
||||||
|
* @param pluginName - Optional plugin directory name (defaults to 'typst-pdf-export')
|
||||||
|
* @param app - Obsidian App instance for vault.adapter operations
|
||||||
|
* @returns New TempDirectoryManager instance
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Create manager from separate parameters
|
||||||
|
* const pathUtils = new PathUtils(this.app);
|
||||||
|
* const vaultPath = pathUtils.getVaultPath();
|
||||||
|
* const configDir = this.app.vault.configDir;
|
||||||
|
*
|
||||||
|
* const manager = TempDirectoryManager.create(
|
||||||
|
* vaultPath,
|
||||||
|
* configDir,
|
||||||
|
* 'typst-pdf-export',
|
||||||
|
* this.app
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Quick initialization with default plugin name
|
||||||
|
* const manager = TempDirectoryManager.create(
|
||||||
|
* this.app.vault.adapter.getBasePath(),
|
||||||
|
* this.app.vault.configDir,
|
||||||
|
* undefined, // Use default plugin name
|
||||||
|
* this.app
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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 });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a path is within the plugin's temp directories
|
* Validates if a path is within the plugin's temporary directories.
|
||||||
|
*
|
||||||
|
* This security utility checks whether a given path is contained within either
|
||||||
|
* the temp-images or temp-pandoc directories. Use this method to validate paths
|
||||||
|
* before performing operations to prevent directory traversal attacks or
|
||||||
|
* accidental operations on user files.
|
||||||
|
*
|
||||||
|
* The method performs normalized path comparisons using Obsidian's normalizePath
|
||||||
|
* to ensure consistent behavior across Windows and Unix-like systems.
|
||||||
|
*
|
||||||
|
* @param dirPath - Path to validate (can be absolute or relative)
|
||||||
|
* @returns True if the path is within plugin temp directories, false otherwise
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Validate user-provided path before cleanup
|
||||||
|
* const userPath = '/vault/.obsidian/plugins/typst-pdf-export/temp-images/file.png';
|
||||||
|
* if (manager.isPluginTempDir(userPath)) {
|
||||||
|
* await this.app.vault.adapter.remove(userPath);
|
||||||
|
* console.log('Safe to remove - within temp directory');
|
||||||
|
* } else {
|
||||||
|
* console.error('Unsafe path - outside temp directories');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Use as guard before bulk operations
|
||||||
|
* async safeCleanup(filePaths: string[]) {
|
||||||
|
* for (const filePath of filePaths) {
|
||||||
|
* if (manager.isPluginTempDir(filePath)) {
|
||||||
|
* await this.app.vault.adapter.remove(filePath);
|
||||||
|
* } else {
|
||||||
|
* console.warn('Skipping non-temp file:', filePath);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
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 tempImagesDir = normalizePath(path.join(pluginDir, PLUGIN_DIRS.TEMP_IMAGES));
|
||||||
return normalizedPath.startsWith(normalizedPluginDir) &&
|
const tempPandocDir = normalizePath(path.join(pluginDir, PLUGIN_DIRS.TEMP_PANDOC));
|
||||||
(dirPath.includes(PLUGIN_DIRS.TEMP_IMAGES) || dirPath.includes(PLUGIN_DIRS.TEMP_PANDOC));
|
|
||||||
|
const isImagesDir =
|
||||||
|
normalizedDirPath === tempImagesDir ||
|
||||||
|
normalizedDirPath.startsWith(`${tempImagesDir}/`);
|
||||||
|
const isPandocDir =
|
||||||
|
normalizedDirPath === tempPandocDir ||
|
||||||
|
normalizedDirPath.startsWith(`${tempPandocDir}/`);
|
||||||
|
|
||||||
|
return isImagesDir || isPandocDir;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+198
-10
@@ -1,9 +1,53 @@
|
|||||||
/**
|
/**
|
||||||
* Constants used throughout the Obsidian Typst PDF Export plugin
|
* Global constants for Obsidian Typst PDF Export plugin.
|
||||||
|
*
|
||||||
|
* This module defines all constant values used throughout the plugin, including:
|
||||||
|
* - Fallback fonts for cross-platform compatibility
|
||||||
|
* - Plugin directory structure and file names
|
||||||
|
* - Export operation timeouts and durations
|
||||||
|
* - Dependency checking paths and executables
|
||||||
|
*
|
||||||
|
* All constants are defined using `as const` for maximum type safety, ensuring
|
||||||
|
* they cannot be modified at runtime and TypeScript can infer literal types.
|
||||||
|
* This prevents accidental mutations and catches typos at compile time.
|
||||||
|
*
|
||||||
|
* These constants are imported and used across:
|
||||||
|
* - Font management and caching
|
||||||
|
* - Temporary directory management
|
||||||
|
* - Export pipeline timeouts
|
||||||
|
* - Dependency resolution and validation
|
||||||
|
* - User notifications and feedback
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fallback fonts used when Typst font detection fails
|
* Fallback fonts used when Typst cannot detect system fonts.
|
||||||
|
*
|
||||||
|
* This array provides a curated list of widely-available fonts that work across
|
||||||
|
* Windows, macOS, and Linux systems. When Typst's automatic font detection fails
|
||||||
|
* or specific fonts aren't found, the plugin will offer these fonts to users as
|
||||||
|
* safe alternatives.
|
||||||
|
*
|
||||||
|
* The list is organized by category:
|
||||||
|
* - Serif: Times New Roman, Georgia
|
||||||
|
* - Sans-serif: Arial, Helvetica, SF Pro Text
|
||||||
|
* - Monospace: Courier New, Monaco, SF Mono, Source Code Pro
|
||||||
|
* - Special: Concourse OT, UbuntuMono Nerd Font Mono
|
||||||
|
*
|
||||||
|
* These fonts are chosen for their:
|
||||||
|
* - Wide platform availability
|
||||||
|
* - Good readability in PDFs
|
||||||
|
* - Professional appearance
|
||||||
|
* - Comprehensive character coverage
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Use fallback fonts when system font detection fails
|
||||||
|
* let availableFonts = await detectSystemFonts();
|
||||||
|
* if (availableFonts.length === 0) {
|
||||||
|
* availableFonts = [...FALLBACK_FONTS];
|
||||||
|
* console.warn('Using fallback fonts - system font detection failed');
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
export const FALLBACK_FONTS = [
|
export const FALLBACK_FONTS = [
|
||||||
'Times New Roman',
|
'Times New Roman',
|
||||||
@@ -20,7 +64,27 @@ export const FALLBACK_FONTS = [
|
|||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin-specific directory names
|
* Plugin-specific directory and file names.
|
||||||
|
*
|
||||||
|
* Defines the structure of plugin-managed directories within the vault's
|
||||||
|
* .obsidian/plugins/typst-pdf-export folder. These directories are used for:
|
||||||
|
* - Temporary file storage during export operations
|
||||||
|
* - Font cache persistence for faster initialization
|
||||||
|
*
|
||||||
|
* Directory structure:
|
||||||
|
* ```
|
||||||
|
* .obsidian/plugins/typst-pdf-export/
|
||||||
|
* ├── temp-images/ # Converted images from embedded PDFs
|
||||||
|
* ├── temp-pandoc/ # Intermediate Pandoc/Typst processing files
|
||||||
|
* └── fonts-cache.json # Cached system font list
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* All paths are managed by TempDirectoryManager and automatically cleaned up
|
||||||
|
* to prevent disk space accumulation.
|
||||||
|
*
|
||||||
|
* @property TEMP_IMAGES - Directory for converted PDF images
|
||||||
|
* @property TEMP_PANDOC - Directory for Pandoc intermediate files
|
||||||
|
* @property FONTS_CACHE - JSON file storing cached font information
|
||||||
*/
|
*/
|
||||||
export const PLUGIN_DIRS = {
|
export const PLUGIN_DIRS = {
|
||||||
TEMP_IMAGES: 'temp-images',
|
TEMP_IMAGES: 'temp-images',
|
||||||
@@ -29,7 +93,31 @@ export const PLUGIN_DIRS = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Export-related constants
|
* Export operation timeouts and notification durations.
|
||||||
|
*
|
||||||
|
* Configures timing parameters for export operations and user feedback:
|
||||||
|
* - Process timeouts prevent hanging exports from blocking the UI
|
||||||
|
* - Notice durations ensure users have time to read important messages
|
||||||
|
*
|
||||||
|
* @property DEFAULT_TIMEOUT - Maximum time (ms) for export operations (2 minutes)
|
||||||
|
* @property NOTICE_DURATION - Standard durations for Obsidian notices
|
||||||
|
* @property NOTICE_DURATION.SHORT - Brief notices for status updates (5 seconds)
|
||||||
|
* @property NOTICE_DURATION.LONG - Extended notices for detailed info (12 seconds)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Use timeout for export process
|
||||||
|
* const result = await Promise.race([
|
||||||
|
* exportToPDF(file),
|
||||||
|
* new Promise((_, reject) =>
|
||||||
|
* setTimeout(() => reject(new Error('Timeout')),
|
||||||
|
* EXPORT_CONSTANTS.DEFAULT_TIMEOUT)
|
||||||
|
* )
|
||||||
|
* ]);
|
||||||
|
*
|
||||||
|
* // Show success notice with short duration
|
||||||
|
* new Notice('PDF exported successfully', EXPORT_CONSTANTS.NOTICE_DURATION.SHORT);
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
export const EXPORT_CONSTANTS = {
|
export const EXPORT_CONSTANTS = {
|
||||||
DEFAULT_TIMEOUT: 120000, // 2 minutes
|
DEFAULT_TIMEOUT: 120000, // 2 minutes
|
||||||
@@ -40,24 +128,113 @@ export const EXPORT_CONSTANTS = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dependency checking constants and utilities
|
* Dependency checking configuration and common paths.
|
||||||
|
*
|
||||||
|
* Defines default executable names and search paths for external tools required
|
||||||
|
* by the plugin (Pandoc, Typst, and ImageMagick). The plugin searches these
|
||||||
|
* paths in addition to the system PATH to handle various installation methods:
|
||||||
|
* - Package managers (brew, apt, snap, cargo)
|
||||||
|
* - User-local installations (~/.local/bin)
|
||||||
|
* - Language-specific package managers (cargo, npm, go)
|
||||||
|
* - System standard locations (/usr/bin, /usr/local/bin)
|
||||||
|
*
|
||||||
|
* These paths are always checked regardless of user settings, ensuring the plugin
|
||||||
|
* can find executables even when they're not in the user's shell PATH (common
|
||||||
|
* with GUI applications on macOS).
|
||||||
|
*
|
||||||
|
* @property DEFAULT_EXECUTABLES - Default command names for each dependency
|
||||||
|
* @property DEFAULT_EXECUTABLES.pandoc - Pandoc markdown converter (v2.0+)
|
||||||
|
* @property DEFAULT_EXECUTABLES.typst - Typst PDF compiler (v0.11+)
|
||||||
|
* @property DEFAULT_EXECUTABLES.imagemagick - ImageMagick convert utility (v7+)
|
||||||
|
* @property COMMON_PATHS - Standard installation locations to search
|
||||||
|
* @property COMMON_PATHS.HOME_RELATIVE - Paths relative to user home directory
|
||||||
|
* @property COMMON_PATHS.ABSOLUTE - System-wide absolute paths
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Build augmented PATH for dependency checking
|
||||||
|
* const homeDir = process.env.HOME || process.env.USERPROFILE;
|
||||||
|
* const homePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE
|
||||||
|
* .map(p => homeDir + p);
|
||||||
|
* const allPaths = [
|
||||||
|
* ...process.env.PATH.split(':'),
|
||||||
|
* ...homePaths,
|
||||||
|
* ...DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE
|
||||||
|
* ];
|
||||||
|
*
|
||||||
|
* // Search for pandoc in augmented PATH
|
||||||
|
* const pandocPath = findInPaths(
|
||||||
|
* DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc,
|
||||||
|
* allPaths
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Resolve executable with fallback to default name
|
||||||
|
* const executablePath = settings.pandocPath ||
|
||||||
|
* DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc;
|
||||||
|
*
|
||||||
|
* // Check if executable exists in common paths
|
||||||
|
* const resolved = await resolveExecutable(
|
||||||
|
* executablePath,
|
||||||
|
* DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.concat(
|
||||||
|
* DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE
|
||||||
|
* )
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
export const DEPENDENCY_CONSTANTS = {
|
export const DEPENDENCY_CONSTANTS = {
|
||||||
/**
|
/**
|
||||||
* Default executable names for dependencies
|
* Default executable names for external dependencies.
|
||||||
|
*
|
||||||
|
* These are the command names used when users haven't configured custom paths.
|
||||||
|
* The plugin will search for these in the augmented PATH.
|
||||||
|
*
|
||||||
|
* @property pandoc - Pandoc executable (markdown → typst converter)
|
||||||
|
* @property typst - Typst executable (typst → PDF compiler)
|
||||||
|
* @property imagemagick - ImageMagick executable (PDF → image converter)
|
||||||
*/
|
*/
|
||||||
DEFAULT_EXECUTABLES: {
|
DEFAULT_EXECUTABLES: {
|
||||||
pandoc: 'pandoc',
|
pandoc: 'pandoc',
|
||||||
typst: 'typst',
|
typst: 'typst',
|
||||||
imagemagick: 'magick'
|
imagemagick: 'magick'
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Common paths to augment PATH with - these are always checked regardless of user settings
|
* Minimum required versions for external dependencies.
|
||||||
|
*
|
||||||
|
* These versions represent the minimum supported versions that have been
|
||||||
|
* tested with this plugin. Users with older versions will receive warnings.
|
||||||
|
*
|
||||||
|
* @property pandoc - Pandoc 3.7.0 (current stable as of plugin development)
|
||||||
|
* @property typst - Typst 0.13.0 (version used during plugin development)
|
||||||
|
* @property imagemagick - ImageMagick 7.1.2 (current stable as of plugin development)
|
||||||
|
*/
|
||||||
|
MINIMUM_VERSIONS: {
|
||||||
|
pandoc: '3.7.0',
|
||||||
|
typst: '0.13.0',
|
||||||
|
imagemagick: '7.1.2'
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common installation paths to search for executables.
|
||||||
|
*
|
||||||
|
* These paths are checked in addition to the system PATH to handle tools
|
||||||
|
* installed via various methods. The plugin automatically augments PATH
|
||||||
|
* with these locations during dependency checking.
|
||||||
*/
|
*/
|
||||||
COMMON_PATHS: {
|
COMMON_PATHS: {
|
||||||
/**
|
/**
|
||||||
* Paths relative to home directory (will have HOME prepended)
|
* Paths relative to the user's home directory.
|
||||||
|
*
|
||||||
|
* These paths will have HOME or USERPROFILE prepended before searching:
|
||||||
|
* - .local/bin: Local user installations (Linux standard)
|
||||||
|
* - .cargo/bin: Rust/Cargo package installations
|
||||||
|
* - go/bin: Go package installations
|
||||||
|
* - .npm-global/bin: Global npm package installations
|
||||||
|
*
|
||||||
|
* @example ['~/.local/bin', '~/.cargo/bin', '~/go/bin', '~/.npm-global/bin']
|
||||||
*/
|
*/
|
||||||
HOME_RELATIVE: [
|
HOME_RELATIVE: [
|
||||||
'/.local/bin',
|
'/.local/bin',
|
||||||
@@ -66,7 +243,18 @@ export const DEPENDENCY_CONSTANTS = {
|
|||||||
'/.npm-global/bin'
|
'/.npm-global/bin'
|
||||||
],
|
],
|
||||||
/**
|
/**
|
||||||
* System-wide absolute paths (used as-is)
|
* System-wide absolute paths used as-is.
|
||||||
|
*
|
||||||
|
* Standard Unix/Linux system directories where executables are commonly
|
||||||
|
* installed by package managers:
|
||||||
|
* - /usr/local/bin: Homebrew (macOS), local installs
|
||||||
|
* - /opt/homebrew/bin: Homebrew on Apple Silicon
|
||||||
|
* - /usr/bin: System package manager installs
|
||||||
|
* - /bin: Essential system commands
|
||||||
|
* - /opt/local/bin: MacPorts installations
|
||||||
|
* - /snap/bin: Snap package installations (Linux)
|
||||||
|
*
|
||||||
|
* @example ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin', '/opt/local/bin', '/snap/bin']
|
||||||
*/
|
*/
|
||||||
ABSOLUTE: [
|
ABSOLUTE: [
|
||||||
'/usr/local/bin',
|
'/usr/local/bin',
|
||||||
|
|||||||
+195
-13
@@ -1,31 +1,162 @@
|
|||||||
/**
|
/**
|
||||||
* Core settings and configuration for Obsidian Typst PDF Export plugin
|
* Settings and configuration schema for Obsidian Typst PDF Export plugin.
|
||||||
|
*
|
||||||
|
* This module defines the complete configuration structure for the plugin, including:
|
||||||
|
* - External tool paths (Pandoc, Typst, ImageMagick)
|
||||||
|
* - Export defaults and presets
|
||||||
|
* - Typography and page layout settings
|
||||||
|
* - Behavior flags and preferences
|
||||||
|
* - Default values for fresh installations
|
||||||
|
*
|
||||||
|
* The settings are persisted to the vault's data.json file and can be modified
|
||||||
|
* through the plugin's settings tab. All settings have safe defaults that work
|
||||||
|
* out-of-the-box when external tools are available in PATH.
|
||||||
|
*
|
||||||
|
* Settings Organization:
|
||||||
|
* - Top-level: Core paths and output configuration
|
||||||
|
* - executablePaths: External tool configuration
|
||||||
|
* - exportDefaults: Default values for new exports
|
||||||
|
* - typography: Font configuration
|
||||||
|
* - pageSetup: Page layout and margins
|
||||||
|
* - behavior: Plugin behavior flags
|
||||||
|
*
|
||||||
|
* Type Safety:
|
||||||
|
* All settings use TypeScript for compile-time validation, preventing invalid
|
||||||
|
* configuration values and catching errors before runtime.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export format options for PDF generation.
|
||||||
|
*
|
||||||
|
* Determines the pagination and layout style of the exported PDF:
|
||||||
|
* - Standard: Traditional multi-page format with page breaks
|
||||||
|
* - Single-page: Continuous single-page format without pagination
|
||||||
|
*
|
||||||
|
* The format affects Typst compilation parameters and influences layout decisions
|
||||||
|
* like automatic width adjustment for landscape orientation.
|
||||||
|
*/
|
||||||
export enum ExportFormat {
|
export enum ExportFormat {
|
||||||
/** Standard multi-page PDF format */
|
/** Standard multi-page PDF format with automatic pagination */
|
||||||
Standard = 'standard',
|
Standard = 'standard',
|
||||||
/** Single-page continuous PDF format */
|
/** Single-page continuous PDF format without page breaks */
|
||||||
SinglePage = 'single-page'
|
SinglePage = 'single-page'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complete plugin settings interface.
|
||||||
|
*
|
||||||
|
* Defines all configurable options for the plugin, organized into logical groups.
|
||||||
|
* This interface serves as both the TypeScript type definition and the schema
|
||||||
|
* for the settings tab UI.
|
||||||
|
*
|
||||||
|
* Settings Lifecycle:
|
||||||
|
* 1. Plugin initializes with DEFAULT_SETTINGS
|
||||||
|
* 2. Persisted settings loaded from data.json (if exists)
|
||||||
|
* 3. User modifies via settings tab
|
||||||
|
* 4. Changes saved immediately to data.json
|
||||||
|
* 5. Export operations use current settings
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Load settings with defaults
|
||||||
|
* const settings: obsidianTypstPDFExportSettings = {
|
||||||
|
* ...DEFAULT_SETTINGS,
|
||||||
|
* ...await this.loadData()
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* // Use settings in export
|
||||||
|
* const converter = new PandocTypstConverter(
|
||||||
|
* this.plugin,
|
||||||
|
* { template: settings.exportDefaults.template },
|
||||||
|
* { ppi: 144 }
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export interface obsidianTypstPDFExportSettings {
|
export interface obsidianTypstPDFExportSettings {
|
||||||
/** Path to the Pandoc executable */
|
/**
|
||||||
|
* Path to the Pandoc executable.
|
||||||
|
*
|
||||||
|
* Can be either:
|
||||||
|
* - Empty string: Use system PATH resolution
|
||||||
|
* - Executable name: e.g., 'pandoc' (searches augmented PATH)
|
||||||
|
* - Absolute path: e.g., '/usr/local/bin/pandoc'
|
||||||
|
*
|
||||||
|
* Pandoc 2.0+ required for Typst output support.
|
||||||
|
*/
|
||||||
pandocPath: string;
|
pandocPath: string;
|
||||||
/** Path to the Typst executable */
|
|
||||||
|
/**
|
||||||
|
* Path to the Typst executable.
|
||||||
|
*
|
||||||
|
* Can be either:
|
||||||
|
* - Empty string: Use system PATH resolution
|
||||||
|
* - Executable name: e.g., 'typst' (searches augmented PATH)
|
||||||
|
* - Absolute path: e.g., '/opt/typst/bin/typst'
|
||||||
|
*
|
||||||
|
* Typst 0.11+ recommended for best compatibility.
|
||||||
|
*/
|
||||||
typstPath: string;
|
typstPath: string;
|
||||||
/** Default output folder for exported PDFs */
|
|
||||||
|
/**
|
||||||
|
* Default output folder for exported PDFs.
|
||||||
|
*
|
||||||
|
* Relative path from vault root. Will be created if it doesn't exist.
|
||||||
|
* Security: Must pass SecurityUtils.validateOutputPath() validation.
|
||||||
|
*
|
||||||
|
* @example 'exports' - PDF files saved to <vault>/exports/
|
||||||
|
* @example 'pdfs/from-notes' - PDF files saved to <vault>/pdfs/from-notes/
|
||||||
|
*/
|
||||||
outputFolder: string;
|
outputFolder: string;
|
||||||
|
|
||||||
/** Executable paths configuration */
|
/**
|
||||||
|
* Executable paths configuration for optional dependencies.
|
||||||
|
*
|
||||||
|
* Controls where the plugin searches for external tools and how
|
||||||
|
* it augments the PATH environment variable.
|
||||||
|
*/
|
||||||
executablePaths: {
|
executablePaths: {
|
||||||
/** Path to ImageMagick command (optional, uses PATH if not specified) */
|
/**
|
||||||
|
* Path to ImageMagick command (optional).
|
||||||
|
*
|
||||||
|
* ImageMagick is optional but recommended for embedded PDF support.
|
||||||
|
* If not configured, embedded PDFs will be skipped during export.
|
||||||
|
*
|
||||||
|
* Can be:
|
||||||
|
* - Empty string: Use system PATH (default)
|
||||||
|
* - Executable name: e.g., 'magick'
|
||||||
|
* - Absolute path: e.g., '/usr/bin/magick'
|
||||||
|
*/
|
||||||
imagemagickPath: string;
|
imagemagickPath: string;
|
||||||
/** Additional paths to append to PATH environment variable */
|
|
||||||
|
/**
|
||||||
|
* Additional directories to search for executables.
|
||||||
|
*
|
||||||
|
* These paths are added to the PATH environment variable when
|
||||||
|
* searching for external tools. Useful for non-standard installations
|
||||||
|
* or when tools aren't in the user's shell PATH.
|
||||||
|
*
|
||||||
|
* @example ['/opt/homebrew/bin', '/usr/local/bin']
|
||||||
|
*/
|
||||||
additionalPaths: string[];
|
additionalPaths: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Export defaults */
|
/**
|
||||||
|
* Custom environment variables for subprocess execution.
|
||||||
|
*
|
||||||
|
* Additional environment variables passed to Pandoc and Typst processes.
|
||||||
|
* Useful for configuring tool behavior or providing authentication.
|
||||||
|
*
|
||||||
|
* @example { 'TYPST_FONT_PATHS': '/custom/fonts:/system/fonts' }
|
||||||
|
* @example { 'PANDOC_USER_DATA_DIR': '/custom/pandoc/data' }
|
||||||
|
*/
|
||||||
|
customEnvironmentVariables: { [key: string]: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default values for new export operations.
|
||||||
|
*
|
||||||
|
* These settings are used when opening the export modal. Users can override
|
||||||
|
* them on a per-export basis through the modal interface.
|
||||||
|
*/
|
||||||
exportDefaults: {
|
exportDefaults: {
|
||||||
/** Default template to use for exports */
|
/** Default template to use for exports */
|
||||||
template: string;
|
template: string;
|
||||||
@@ -98,6 +229,55 @@ export interface obsidianTypstPDFExportSettings {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default settings for fresh plugin installations.
|
||||||
|
*
|
||||||
|
* These values are used when:
|
||||||
|
* - Plugin is first installed (no data.json exists)
|
||||||
|
* - Settings are reset to defaults
|
||||||
|
* - Individual settings are missing from persisted data
|
||||||
|
*
|
||||||
|
* The defaults are designed to:
|
||||||
|
* - Work out-of-the-box when external tools are in PATH
|
||||||
|
* - Produce professional-looking PDFs with minimal configuration
|
||||||
|
* - Use widely-available fonts as fallbacks
|
||||||
|
* - Enable helpful features (auto-open, folder structure preservation)
|
||||||
|
*
|
||||||
|
* Settings Strategy:
|
||||||
|
* - Empty paths for executables (rely on PATH resolution)
|
||||||
|
* - Common system paths in additionalPaths for macOS/Linux
|
||||||
|
* - Conservative concurrency (3) for stability
|
||||||
|
* - Professional typography (Concourse OT, SF Pro)
|
||||||
|
* - Standard A4 paper with reasonable margins
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Initialize plugin with defaults
|
||||||
|
* async onload() {
|
||||||
|
* await this.loadSettings(); // Merges with DEFAULT_SETTINGS
|
||||||
|
* this.registerSettingsTab();
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* async loadSettings() {
|
||||||
|
* this.settings = Object.assign(
|
||||||
|
* {},
|
||||||
|
* DEFAULT_SETTINGS,
|
||||||
|
* await this.loadData()
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Reset individual settings to defaults
|
||||||
|
* resetTypography() {
|
||||||
|
* this.settings.typography = {
|
||||||
|
* ...DEFAULT_SETTINGS.typography
|
||||||
|
* };
|
||||||
|
* await this.saveSettings();
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
|
export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
|
||||||
pandocPath: '',
|
pandocPath: '',
|
||||||
typstPath: '',
|
typstPath: '',
|
||||||
@@ -108,6 +288,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 +338,4 @@ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = {
|
|||||||
embedAllFiles: true,
|
embedAllFiles: true,
|
||||||
printFrontmatter: false
|
printFrontmatter: false
|
||||||
}
|
}
|
||||||
};;;;
|
};
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Command Registration
|
||||||
|
* Handles registration of all plugin commands and their callbacks
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Editor, MarkdownView, Notice } 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).catch(error => {
|
||||||
|
console.error('Failed to export current note:', error);
|
||||||
|
const errorMessage = error?.message ?? String(error);
|
||||||
|
new Notice(`Failed to export current note: ${errorMessage}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Export with configuration command
|
||||||
|
this.plugin.addCommand({
|
||||||
|
id: 'export-with-config',
|
||||||
|
name: 'Export with configuration…',
|
||||||
|
editorCallback: (editor: Editor, view: MarkdownView) => {
|
||||||
|
this.plugin.showExportModal(view).catch(error => {
|
||||||
|
console.error('Failed to show export modal:', error);
|
||||||
|
const errorMessage = error?.message ?? String(error);
|
||||||
|
new Notice(`Failed to show export modal: ${errorMessage}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check dependencies command
|
||||||
|
this.plugin.addCommand({
|
||||||
|
id: 'check-dependencies',
|
||||||
|
name: 'Check pandoc and typst dependencies',
|
||||||
|
callback: () => {
|
||||||
|
this.plugin.showDependencyStatus().catch(error => {
|
||||||
|
console.error('Failed to show dependency status:', error);
|
||||||
|
const errorMessage = error?.message ?? String(error);
|
||||||
|
new Notice(`Failed to show dependency status: ${errorMessage}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,720 @@
|
|||||||
|
/**
|
||||||
|
* Embed Processing
|
||||||
|
* Handles processing of PDF, image, and file embeds for PDF export
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { exec } from 'child_process';
|
||||||
|
import * as util from 'util';
|
||||||
|
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';
|
||||||
|
import * as https from 'https';
|
||||||
|
import * as http from 'http';
|
||||||
|
|
||||||
|
const execAsync = util.promisify(exec);
|
||||||
|
|
||||||
|
export class EmbedProcessor {
|
||||||
|
private readonly pathUtils: PathUtils;
|
||||||
|
|
||||||
|
constructor(private plugin: obsidianTypstPDFExport) {
|
||||||
|
this.pathUtils = new PathUtils(plugin.app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle completion of image download and write to vault.
|
||||||
|
* @param chunks Downloaded image data chunks
|
||||||
|
* @param outputPath Absolute path where the image should be written
|
||||||
|
* @param resolve Promise resolver to call with result
|
||||||
|
*/
|
||||||
|
private async handleDownloadComplete(
|
||||||
|
chunks: Buffer[],
|
||||||
|
outputPath: string,
|
||||||
|
resolve: (value: string | null) => void
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Check if file already exists to avoid overwriting
|
||||||
|
const exists = await this.pathUtils.fileExists(outputPath);
|
||||||
|
if (exists) {
|
||||||
|
console.warn(`Export: Image file already exists, using existing: ${outputPath}`);
|
||||||
|
resolve(outputPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combine chunks and write using vault adapter
|
||||||
|
const buffer = Buffer.concat(chunks);
|
||||||
|
// Convert Buffer to ArrayBuffer for vault adapter
|
||||||
|
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||||
|
|
||||||
|
// Convert absolute path to vault-relative for adapter operations
|
||||||
|
const relativeOutputPath = this.pathUtils.toVaultRelative(outputPath);
|
||||||
|
|
||||||
|
await this.plugin.app.vault.adapter.writeBinary(relativeOutputPath, arrayBuffer);
|
||||||
|
|
||||||
|
console.debug(`Export:Successfully downloaded image to: ${outputPath}`);
|
||||||
|
resolve(outputPath);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Export: Error writing image file: ${err.message}`);
|
||||||
|
resolve(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a local file path using Obsidian's API and filesystem fallbacks
|
||||||
|
* @param decodedPath The decoded (non-URL-encoded) path to resolve
|
||||||
|
* @param vaultBasePath Base path of the vault
|
||||||
|
* @param currentFile Current file being processed (optional, enables Obsidian API resolution)
|
||||||
|
* @param additionalPaths Additional paths to try after standard paths
|
||||||
|
* @param useObsidianApi Whether to try Obsidian's link resolution API first (requires currentFile)
|
||||||
|
* @returns Full path to file if found, null otherwise
|
||||||
|
*/
|
||||||
|
private async resolveLocalPath(
|
||||||
|
decodedPath: string,
|
||||||
|
vaultBasePath: string,
|
||||||
|
currentFile?: TFile,
|
||||||
|
additionalPaths: string[] = [],
|
||||||
|
useObsidianApi: boolean = true
|
||||||
|
): Promise<string | null> {
|
||||||
|
// Strategy 1: Use Obsidian's link resolution API (if enabled and currentFile provided)
|
||||||
|
if (useObsidianApi && 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 = [
|
||||||
|
// Standard path relative to vault root
|
||||||
|
path.resolve(vaultBasePath, decodedPath),
|
||||||
|
// Relative to current file's directory (for local attachments)
|
||||||
|
currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null,
|
||||||
|
// Additional paths provided by caller
|
||||||
|
...additionalPaths
|
||||||
|
].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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download a remote image to the temp directory
|
||||||
|
* Returns the local path if successful, null if failed
|
||||||
|
*/
|
||||||
|
private async downloadRemoteImage(imageUrl: string, tempDir: string): Promise<string | null> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
|
// Parse URL to get filename
|
||||||
|
const urlObj = new URL(imageUrl);
|
||||||
|
const urlPath = urlObj.pathname;
|
||||||
|
const fileName = path.basename(urlPath) || `remote-image-${Date.now()}`;
|
||||||
|
|
||||||
|
// Ensure we have a valid file extension
|
||||||
|
// Extract extension and normalize it (lowercase)
|
||||||
|
const ext = path.extname(fileName).toLowerCase();
|
||||||
|
|
||||||
|
// Preserve any existing extension, or append .png if no extension present
|
||||||
|
// This handles all image types (svg, ico, avif, etc.) without forcing .png
|
||||||
|
const finalFileName = ext
|
||||||
|
? fileName // Has an extension, preserve it
|
||||||
|
: `${fileName}.png`; // No extension, append .png
|
||||||
|
|
||||||
|
const outputPath = path.join(tempDir, finalFileName);
|
||||||
|
|
||||||
|
// Select appropriate protocol based on parsed URL (handles case-insensitive schemes)
|
||||||
|
const protocol = urlObj.protocol === 'https:' ? https : http;
|
||||||
|
|
||||||
|
console.debug(`Export:Downloading remote image: ${imageUrl}`);
|
||||||
|
|
||||||
|
// Use parsed URL object for the request to ensure correct protocol handling
|
||||||
|
const request = protocol.get(urlObj, (response) => {
|
||||||
|
// Handle redirects
|
||||||
|
if (response.statusCode === 301 || response.statusCode === 302) {
|
||||||
|
const redirectUrl = response.headers.location;
|
||||||
|
if (redirectUrl) {
|
||||||
|
// Resolve relative redirects against the original request URL
|
||||||
|
// This handles both absolute URLs (e.g., "https://example.com/img.png")
|
||||||
|
// and relative URLs (e.g., "/assets/img.png" or "../img.png")
|
||||||
|
const absoluteRedirectUrl = new URL(redirectUrl, imageUrl).href;
|
||||||
|
console.debug(`Export:Following redirect to: ${absoluteRedirectUrl}`);
|
||||||
|
// Recursively follow redirect with resolved absolute URL
|
||||||
|
this.downloadRemoteImage(absoluteRedirectUrl, tempDir).then(resolve).catch(reject);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for successful response
|
||||||
|
if (response.statusCode !== 200) {
|
||||||
|
console.warn(`Export: Failed to download image, status code: ${response.statusCode}`);
|
||||||
|
resolve(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect response data in memory
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
|
||||||
|
response.on('data', (chunk: Buffer) => {
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
|
||||||
|
response.on('end', () => {
|
||||||
|
void this.handleDownloadComplete(chunks, outputPath, resolve);
|
||||||
|
});
|
||||||
|
|
||||||
|
response.on('error', (err) => {
|
||||||
|
console.error(`Export: Error receiving image data: ${err.message}`);
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
request.on('error', (err) => {
|
||||||
|
console.error(`Export: Error downloading image: ${err.message}`);
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set timeout
|
||||||
|
request.setTimeout(10000, () => {
|
||||||
|
request.destroy();
|
||||||
|
console.warn(`Export: Image download timeout: ${imageUrl}`);
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Export: Error in downloadRemoteImage: ${error.message}`);
|
||||||
|
resolve(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
|
||||||
|
let fullImagePath: string | null = null;
|
||||||
|
|
||||||
|
// Check if this is a remote URL (http:// or https://)
|
||||||
|
const isRemoteUrl = /^https?:\/\//i.test(decodedPath);
|
||||||
|
|
||||||
|
if (isRemoteUrl) {
|
||||||
|
// Try to download the remote image
|
||||||
|
console.debug(`Export:Attempting to download remote image: ${decodedPath}`);
|
||||||
|
const downloadedPath = await this.downloadRemoteImage(decodedPath, tempDir);
|
||||||
|
|
||||||
|
if (downloadedPath) {
|
||||||
|
// Successfully downloaded, use it as a local image
|
||||||
|
fullImagePath = downloadedPath;
|
||||||
|
console.debug(`Export:Successfully downloaded and will embed remote image`);
|
||||||
|
} else {
|
||||||
|
// Download failed, use placeholder
|
||||||
|
console.warn(`Export: Failed to download remote image: ${decodedPath}`);
|
||||||
|
const fallbackOutput = `[🌐 **Remote image download failed:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`;
|
||||||
|
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Resolve local file path using helper method
|
||||||
|
// Note: Image embeds don't use Obsidian API, only filesystem resolution
|
||||||
|
const attachmentsPath = path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath));
|
||||||
|
fullImagePath = await this.resolveLocalPath(
|
||||||
|
decodedPath,
|
||||||
|
vaultBasePath,
|
||||||
|
currentFile,
|
||||||
|
[attachmentsPath],
|
||||||
|
false // Don't use Obsidian API for image embeds
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
// Use vault-relative path for ensureDir (it uses vault.adapter)
|
||||||
|
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||||
|
await this.pathUtils.ensureDir(vaultRelativeTempDir);
|
||||||
|
// But use absolute path for ImageMagick
|
||||||
|
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
|
||||||
|
|
||||||
|
const convertedImagePath = this.pathUtils.joinPath(vaultTempImagesDir, pngFileName);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Use helper method with Obsidian API enabled
|
||||||
|
return await this.resolveLocalPath(
|
||||||
|
decodedPath,
|
||||||
|
vaultBasePath,
|
||||||
|
currentFile,
|
||||||
|
[], // No additional paths for PDFs
|
||||||
|
true // Use Obsidian API
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
|
||||||
|
// Use helper method with Obsidian API enabled and attachments folder as additional path
|
||||||
|
const attachmentsPath = path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath));
|
||||||
|
return await this.resolveLocalPath(
|
||||||
|
decodedPath,
|
||||||
|
vaultBasePath,
|
||||||
|
currentFile,
|
||||||
|
[attachmentsPath], // Check attachments folder as additional path
|
||||||
|
true // Use Obsidian API
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
// Use vault-relative path for ensureDir (it uses vault.adapter)
|
||||||
|
const vaultRelativeTempDir = this.pathUtils.joinPath(this.pathUtils.getPluginDir(this.plugin.manifest), 'temp-images');
|
||||||
|
await this.pathUtils.ensureDir(vaultRelativeTempDir);
|
||||||
|
// But use absolute path for file operations
|
||||||
|
const vaultTempImagesDir = this.pathUtils.joinPath(vaultBasePath, vaultRelativeTempDir);
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// Convert absolute paths to vault-relative paths for adapter operations
|
||||||
|
const relativeSourcePath = this.pathUtils.toVaultRelative(imagePath);
|
||||||
|
const relativeVaultImagePath = this.pathUtils.toVaultRelative(vaultImagePath);
|
||||||
|
|
||||||
|
const sourceBuffer = await this.plugin.app.vault.adapter.readBinary(relativeSourcePath);
|
||||||
|
await this.plugin.app.vault.adapter.writeBinary(relativeVaultImagePath, 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,122 @@
|
|||||||
|
/**
|
||||||
|
* 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')
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportFile(file).catch(error => {
|
||||||
|
console.error('Failed to export file:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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')
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportCurrentNote(view).catch(error => {
|
||||||
|
console.error('Failed to export current note:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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((file) => this.plugin.isMarkdownFile(file));
|
||||||
|
|
||||||
|
if (markdownFiles.length > 0) {
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle(`Export to PDF`)
|
||||||
|
.setIcon('file-output')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.exportFiles(markdownFiles).catch(error => {
|
||||||
|
console.error('Failed to export files:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
menu.addItem((item) => {
|
||||||
|
item
|
||||||
|
.setTitle(`Export with configuration...`)
|
||||||
|
.setIcon('settings')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.showExportModalForFiles(markdownFiles).catch(error => {
|
||||||
|
console.error('Failed to show export modal for files:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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!).catch(error => {
|
||||||
|
console.error('Failed to export file:', error);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
menu.addItem((item) =>
|
||||||
|
item
|
||||||
|
.setTitle('Export with configuration…')
|
||||||
|
.setIcon('settings')
|
||||||
|
.onClick(() => {
|
||||||
|
this.plugin.showExportModal(activeView).catch(error => {
|
||||||
|
console.error('Failed to show export modal:', error);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
menu.showAtMouseEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
/**
|
||||||
|
* 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 directories 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');
|
||||||
|
const tempImagesDir = await tempManager.ensureTempDir('images');
|
||||||
|
|
||||||
|
// 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.messageEl.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 = 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, tempImagesDir, file, embedPdfFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process image embeds if any were found
|
||||||
|
if (processedResult.metadata.imageEmbeds && processedResult.metadata.imageEmbeds.length > 0) {
|
||||||
|
await this.plugin.processImageEmbeds(processedResult, vaultPath, tempImagesDir, 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((file) => this.plugin.isMarkdownFile(file));
|
||||||
|
|
||||||
|
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,249 @@
|
|||||||
|
/**
|
||||||
|
* Font Management
|
||||||
|
* Handles font discovery, caching, and retrieval for the plugin
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn } from 'child_process';
|
||||||
|
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 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,96 @@
|
|||||||
|
/**
|
||||||
|
* Path Resolution Utilities
|
||||||
|
* Handles executable path resolution and output path preparation
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawnSync } from 'child_process';
|
||||||
|
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
|
||||||
|
// Use platform-specific command: 'where' on Windows, 'which' on Unix
|
||||||
|
const whichCommand = process.platform === 'win32' ? 'where' : 'which';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const augmentedEnv = {
|
||||||
|
...process.env,
|
||||||
|
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = spawnSync(whichCommand, [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> {
|
||||||
|
// Check if output folder is set
|
||||||
|
if (!outputFolder || outputFolder.trim() === '') {
|
||||||
|
throw new Error('Output folder is not set. Please configure the output folder in plugin settings.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 (use vault-relative path for vault adapter)
|
||||||
|
await this.pathUtils.ensureDir(outputFolder);
|
||||||
|
|
||||||
|
// Preserve folder structure if configured
|
||||||
|
let relativePath = '';
|
||||||
|
if (this.plugin.settings.behavior.preserveFolderStructure) {
|
||||||
|
const folderPath = path.dirname(file.path);
|
||||||
|
if (folderPath !== '.') {
|
||||||
|
relativePath = folderPath;
|
||||||
|
// Use vault-relative path for vault adapter
|
||||||
|
const vaultRelativeOutputDir = this.pathUtils.joinPath(outputFolder, relativePath);
|
||||||
|
await this.pathUtils.ensureDir(vaultRelativeOutputDir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,106 @@
|
|||||||
|
/**
|
||||||
|
* 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
|
||||||
|
this.plugin.checkDependenciesOnStartup();
|
||||||
|
|
||||||
|
// Cache available fonts (async, don't await)
|
||||||
|
void this.plugin.cacheAvailableFonts();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean up resources during onunload
|
||||||
|
*/
|
||||||
|
async cleanup(): Promise<void> {
|
||||||
|
// Cancel any ongoing exports
|
||||||
|
if (this.plugin.currentExportController) {
|
||||||
|
this.plugin.currentExportController.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispose converter to clean up its temp directories
|
||||||
|
if (this.plugin.converter) {
|
||||||
|
await this.plugin.converter.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up temp directories on plugin unload
|
||||||
|
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)
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const vaultPath = this.pathUtils.getVaultPath();
|
||||||
|
const cleanupManager = TempDirectoryManager.create(vaultPath, this.plugin.app.vault.configDir, undefined, this.plugin.app);
|
||||||
|
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,454 @@
|
|||||||
|
/**
|
||||||
|
* Settings Tab
|
||||||
|
* Handles the plugin settings UI interface
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
App,
|
||||||
|
PluginSettingTab,
|
||||||
|
Setting,
|
||||||
|
normalizePath
|
||||||
|
} from 'obsidian';
|
||||||
|
import * as path from 'path';
|
||||||
|
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();
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Executable paths')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Export defaults')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
|
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('Folder for exported pdfs (relative to vault root)')
|
||||||
|
.addText(text => {
|
||||||
|
text
|
||||||
|
.setPlaceholder('Exports')
|
||||||
|
.setValue(this.plugin.settings.outputFolder)
|
||||||
|
.onChange(async (value) => {
|
||||||
|
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||||
|
const normalizedValue = path.isAbsolute(value) ? value : 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 {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Typography defaults')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Page setup')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
|
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 {
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName('Behavior')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
|
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,24 +29,28 @@ 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 vaultRelativePath = this.pathUtils.toVaultRelative(this.templatesPath);
|
||||||
|
|
||||||
|
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 => {
|
||||||
return file.endsWith('.typ') || file.endsWith('.pandoc.typ');
|
return file.endsWith('.typ') || file.endsWith('.pandoc.typ');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Always include default if not present
|
// Always include default if not present
|
||||||
if (!templates.includes('default.typ')) {
|
if (!templates.includes('default.typ')) {
|
||||||
templates.unshift('default.typ');
|
templates.unshift('default.typ');
|
||||||
}
|
}
|
||||||
|
|
||||||
return templates;
|
return templates;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading templates:', error);
|
console.error('Error loading templates:', error);
|
||||||
@@ -56,7 +62,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 +70,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 +79,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);
|
||||||
@@ -116,11 +119,12 @@ export class TemplateManager {
|
|||||||
case 'version':
|
case 'version':
|
||||||
metadata.version = value;
|
metadata.version = value;
|
||||||
break;
|
break;
|
||||||
case 'variable':
|
case 'variable': {
|
||||||
// Parse variable definition (e.g., @variable: font:string:Body font family)
|
// Parse variable definition (e.g., @variable: font:string:Body font family)
|
||||||
const [name, type, description] = value.split(':');
|
const [name, type, description] = value.split(':');
|
||||||
metadata.variables.push({ name, type, description });
|
metadata.variables.push({ name, type, description });
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,23 +14,27 @@ 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,
|
||||||
exists,
|
exists,
|
||||||
@@ -44,26 +48,25 @@ 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 (convert absolute to vault-relative for vault.adapter)
|
||||||
if (!fs.existsSync(this.templatesDir)) {
|
const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
|
||||||
fs.mkdirSync(this.templatesDir, { recursive: true });
|
await this.pathUtils.ensureDir(relativeTemplatesDir);
|
||||||
}
|
|
||||||
|
|
||||||
// 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) {
|
||||||
console.error(`Failed to extract template ${templateName}:`, error);
|
console.error(`Failed to extract template ${templateName}:`, error);
|
||||||
@@ -74,15 +77,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 +100,22 @@ 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 (convert absolute to vault-relative for vault.adapter)
|
||||||
if (!fs.existsSync(this.templatesDir)) {
|
const relativeTemplatesDir = this.pathUtils.toVaultRelative(this.templatesDir);
|
||||||
fs.mkdirSync(this.templatesDir, { recursive: true });
|
await this.pathUtils.ensureDir(relativeTemplatesDir);
|
||||||
}
|
|
||||||
|
|
||||||
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,29 +13,23 @@ 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;
|
||||||
private state: ModalState;
|
private state: ModalState;
|
||||||
private sections: Map<string, ModalSection> = new Map();
|
private sections: Map<string, ModalSection> = new Map();
|
||||||
private onSubmit: (config: ExportConfig) => void;
|
private onSubmit: (config: ExportConfig) => void | Promise<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,
|
||||||
plugin: obsidianTypstPDFExport,
|
plugin: obsidianTypstPDFExport,
|
||||||
settings: Partial<ExportConfigModalSettings>,
|
settings: Partial<ExportConfigModalSettings>,
|
||||||
onSubmit: (config: ExportConfig) => void,
|
onSubmit: (config: ExportConfig) => void | Promise<void>,
|
||||||
onCancel?: () => void
|
onCancel?: () => void
|
||||||
) {
|
) {
|
||||||
super(app);
|
super(app);
|
||||||
@@ -43,11 +38,22 @@ export class ExportConfigModal extends Modal {
|
|||||||
this.onCancel = onCancel;
|
this.onCancel = onCancel;
|
||||||
|
|
||||||
// Initialize state
|
// Initialize state
|
||||||
this.state = new ModalState(settings);
|
this.state = new ModalState(settings, app);
|
||||||
|
|
||||||
// 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,105 +76,14 @@ 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
|
|
||||||
this.createHeader();
|
|
||||||
|
|
||||||
// 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();
|
|
||||||
|
|
||||||
|
// Initialize renderer with content container
|
||||||
|
this.renderer.initialize(contentContainer);
|
||||||
|
|
||||||
// Load available templates
|
// Load available templates
|
||||||
this.loadAvailableTemplates();
|
void 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> {
|
||||||
@@ -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();
|
void 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,266 @@
|
|||||||
|
/**
|
||||||
|
* 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 | Promise<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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
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.setExportingState(true);
|
||||||
|
Promise.resolve(this.callbacks.onSubmit()).catch(err => {
|
||||||
|
// Log the error for debugging
|
||||||
|
console.error('Export submission failed:', err);
|
||||||
|
|
||||||
|
// Show user-facing error feedback
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred during export';
|
||||||
|
this.showValidationErrors([errorMessage]);
|
||||||
|
|
||||||
|
// Re-enable buttons so user can try again or cancel
|
||||||
|
this.setExportingState(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,9 @@ export class BehaviorSection implements ModalSection {
|
|||||||
|
|
||||||
render(containerEl: HTMLElement, state: ModalState): void {
|
render(containerEl: HTMLElement, state: ModalState): void {
|
||||||
this.container = containerEl.createDiv('export-section');
|
this.container = containerEl.createDiv('export-section');
|
||||||
this.container.createEl('h3', { text: 'Export Behavior' });
|
new Setting(this.container)
|
||||||
|
.setName('Export behavior')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
this.createBehaviorToggles(state);
|
this.createBehaviorToggles(state);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
* 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 * as path from 'path';
|
||||||
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,14 +12,16 @@ 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;
|
||||||
|
|
||||||
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
||||||
if (app) this.app = app;
|
if (app) this.app = app;
|
||||||
this.container = containerEl.createDiv('export-section');
|
this.container = containerEl.createDiv('export-section');
|
||||||
this.container.createEl('h3', { text: 'General Settings' });
|
new Setting(this.container)
|
||||||
|
.setName('General settings')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
this.createTemplateSelection(state);
|
this.createTemplateSelection(state);
|
||||||
this.createFormatSelection(state);
|
this.createFormatSelection(state);
|
||||||
@@ -72,13 +75,14 @@ export class GeneralSection implements ModalSection {
|
|||||||
|
|
||||||
new Setting(this.container)
|
new Setting(this.container)
|
||||||
.setName('Output folder')
|
.setName('Output folder')
|
||||||
.setDesc('Folder where PDFs will be saved (relative to vault root)')
|
.setDesc('Location for exported PDF files (relative to vault root or absolute path)')
|
||||||
.addText(text => {
|
.addText(text => {
|
||||||
const input = text
|
const input = text
|
||||||
.setPlaceholder('exports')
|
.setPlaceholder('PDF exports')
|
||||||
.setValue(state.settings.outputFolder || 'exports')
|
.setValue(state.settings.outputFolder || 'exports')
|
||||||
.onChange(value => {
|
.onChange(value => {
|
||||||
const normalizedValue = normalizePath(value);
|
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||||
|
const normalizedValue = path.isAbsolute(value) ? value : normalizePath(value);
|
||||||
state.updateSettings({ outputFolder: normalizedValue });
|
state.updateSettings({ outputFolder: normalizedValue });
|
||||||
});
|
});
|
||||||
this.outputFolderInput = input.inputEl;
|
this.outputFolderInput = input.inputEl;
|
||||||
@@ -102,9 +106,11 @@ export class GeneralSection implements ModalSection {
|
|||||||
|
|
||||||
// Validate output folder
|
// Validate output folder
|
||||||
if (this.outputFolderInput) {
|
if (this.outputFolderInput) {
|
||||||
const value = normalizePath(this.outputFolderInput.value.trim());
|
const rawValue = this.outputFolderInput.value.trim();
|
||||||
if (!SecurityUtils.validateOutputPath(value)) {
|
// Don't normalize absolute paths as normalizePath strips the leading slash
|
||||||
errors.push(SecurityUtils.getPathValidationError(value));
|
const normalizedValue = path.isAbsolute(rawValue) ? rawValue : normalizePath(rawValue);
|
||||||
|
if (!SecurityUtils.validateOutputPath(normalizedValue)) {
|
||||||
|
errors.push(SecurityUtils.getPathValidationError(normalizedValue));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,16 +134,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]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ export class LayoutSection implements ModalSection {
|
|||||||
|
|
||||||
render(containerEl: HTMLElement, state: ModalState): void {
|
render(containerEl: HTMLElement, state: ModalState): void {
|
||||||
this.container = containerEl.createDiv('export-section');
|
this.container = containerEl.createDiv('export-section');
|
||||||
this.container.createEl('h3', { text: 'Page Layout' });
|
new Setting(this.container)
|
||||||
|
.setName('Page layout')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
this.createPageSizeSettings(state);
|
this.createPageSizeSettings(state);
|
||||||
this.createOrientationSettings(state);
|
this.createOrientationSettings(state);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
import { Setting } from 'obsidian';
|
import { Setting } from 'obsidian';
|
||||||
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
import { ModalSection, ModalState, ValidationResult } from '../modalTypes';
|
||||||
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
|
import { SUPPORTED_PAPER_SIZES } from '../../../utils/paperSizeMapper';
|
||||||
|
import { ExportFormat } from '../../../core/settings';
|
||||||
|
|
||||||
export class PageSetupSection implements ModalSection {
|
export class PageSetupSection implements ModalSection {
|
||||||
private container: HTMLElement | null = null;
|
private container: HTMLElement | null = null;
|
||||||
@@ -13,7 +14,9 @@ export class PageSetupSection implements ModalSection {
|
|||||||
|
|
||||||
render(containerEl: HTMLElement, state: ModalState): void {
|
render(containerEl: HTMLElement, state: ModalState): void {
|
||||||
this.container = containerEl.createDiv('export-section');
|
this.container = containerEl.createDiv('export-section');
|
||||||
this.container.createEl('h3', { text: 'Page Setup' });
|
new Setting(this.container)
|
||||||
|
.setName('Page setup')
|
||||||
|
.setHeading();
|
||||||
|
|
||||||
this.createPageSizeSettings(state);
|
this.createPageSizeSettings(state);
|
||||||
this.createOrientationSettings(state);
|
this.createOrientationSettings(state);
|
||||||
@@ -33,7 +36,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,15 +53,15 @@ 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({
|
||||||
orientation: value,
|
orientation: value,
|
||||||
flipped: isLandscape,
|
flipped: isLandscape,
|
||||||
// Auto-adjust width for single-page mode when flipped
|
// Auto-adjust width for single-page mode when flipped
|
||||||
...(isLandscape && state.settings.format === 'single-page'
|
...(isLandscape && state.settings.format === ExportFormat.SinglePage
|
||||||
? { width: 'auto' }
|
? { width: 'auto' }
|
||||||
: {})
|
: {})
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -69,7 +72,7 @@ export class PageSetupSection implements ModalSection {
|
|||||||
if (!this.container) return;
|
if (!this.container) return;
|
||||||
|
|
||||||
const marginsContainer = this.container.createDiv('margins-container');
|
const marginsContainer = this.container.createDiv('margins-container');
|
||||||
marginsContainer.createEl('h4', { text: 'Text Margins' });
|
marginsContainer.createEl('h4', { text: 'Text margins' });
|
||||||
marginsContainer.createEl('p', {
|
marginsContainer.createEl('p', {
|
||||||
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
|
text: 'Enter margins in centimeters (e.g., "2.5", "1.8", "3.0")',
|
||||||
cls: 'setting-item-description'
|
cls: 'setting-item-description'
|
||||||
@@ -90,7 +93,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 });
|
||||||
|
|||||||
@@ -13,36 +13,41 @@ export class TypographySection implements ModalSection {
|
|||||||
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
render(containerEl: HTMLElement, state: ModalState, app?: App): void {
|
||||||
if (app) this.app = app;
|
if (app) this.app = app;
|
||||||
this.container = containerEl.createDiv('export-section');
|
this.container = containerEl.createDiv('export-section');
|
||||||
this.container.createEl('h3', { text: 'Typography' });
|
new Setting(this.container)
|
||||||
|
.setName('Typography')
|
||||||
// Create font settings asynchronously
|
.setHeading();
|
||||||
this.createFontSettings(state);
|
|
||||||
this.createFontSizeSettings(state);
|
// Create font settings asynchronously with explicit error handling
|
||||||
|
// Font size settings are created after font dropdowns to preserve logical ordering
|
||||||
|
this.createFontSettings(state).catch(error => {
|
||||||
|
console.error('Failed to create font settings:', error);
|
||||||
|
// If font loading fails, getAvailableFonts will use hardcoded fallback fonts
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createFontSettings(state: ModalState): Promise<void> {
|
private async createFontSettings(state: ModalState): Promise<void> {
|
||||||
if (!this.container) return;
|
if (!this.container) return;
|
||||||
|
|
||||||
// Get available fonts from cache
|
// Get available fonts from cache
|
||||||
const availableFonts = await this.getAvailableFonts(state);
|
const availableFonts = await this.getAvailableFonts(state);
|
||||||
|
|
||||||
// Body font dropdown
|
// Body font dropdown
|
||||||
new Setting(this.container)
|
new Setting(this.container)
|
||||||
.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 => {
|
||||||
dropdown.addOption(font, font);
|
dropdown.addOption(font, font);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add current font if it's not in the list
|
// Add current font if it's not in the list
|
||||||
if (!availableFonts.includes(currentFont)) {
|
if (!availableFonts.includes(currentFont)) {
|
||||||
dropdown.addOption(currentFont, currentFont);
|
dropdown.addOption(currentFont, currentFont);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set current value and change handler
|
// Set current value and change handler
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(currentFont)
|
.setValue(currentFont)
|
||||||
@@ -50,24 +55,24 @@ export class TypographySection implements ModalSection {
|
|||||||
state.updateTemplateVariables({ bodyFont: value });
|
state.updateTemplateVariables({ bodyFont: value });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Heading font dropdown
|
// Heading font dropdown
|
||||||
new Setting(this.container)
|
new Setting(this.container)
|
||||||
.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 => {
|
||||||
dropdown.addOption(font, font);
|
dropdown.addOption(font, font);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add current font if it's not in the list
|
// Add current font if it's not in the list
|
||||||
if (!availableFonts.includes(currentFont)) {
|
if (!availableFonts.includes(currentFont)) {
|
||||||
dropdown.addOption(currentFont, currentFont);
|
dropdown.addOption(currentFont, currentFont);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set current value and change handler
|
// Set current value and change handler
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(currentFont)
|
.setValue(currentFont)
|
||||||
@@ -75,24 +80,24 @@ export class TypographySection implements ModalSection {
|
|||||||
state.updateTemplateVariables({ headingFont: value });
|
state.updateTemplateVariables({ headingFont: value });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Monospace font dropdown
|
// Monospace font dropdown
|
||||||
new Setting(this.container)
|
new Setting(this.container)
|
||||||
.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 => {
|
||||||
dropdown.addOption(font, font);
|
dropdown.addOption(font, font);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add current font if it's not in the list
|
// Add current font if it's not in the list
|
||||||
if (!availableFonts.includes(currentFont)) {
|
if (!availableFonts.includes(currentFont)) {
|
||||||
dropdown.addOption(currentFont, currentFont);
|
dropdown.addOption(currentFont, currentFont);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set current value and change handler
|
// Set current value and change handler
|
||||||
dropdown
|
dropdown
|
||||||
.setValue(currentFont)
|
.setValue(currentFont)
|
||||||
@@ -100,8 +105,11 @@ export class TypographySection implements ModalSection {
|
|||||||
state.updateTemplateVariables({ monospaceFont: value });
|
state.updateTemplateVariables({ monospaceFont: value });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Create font size settings after font dropdowns for logical ordering
|
||||||
|
this.createFontSizeSettings(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
private createFontSizeSettings(state: ModalState): void {
|
private createFontSizeSettings(state: ModalState): void {
|
||||||
if (!this.container) return;
|
if (!this.container) return;
|
||||||
|
|
||||||
@@ -111,7 +119,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 });
|
||||||
@@ -160,51 +168,7 @@ export class TypographySection implements ModalSection {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private addFallbackBodyFonts(dropdown: any, state: ModalState, fontType: 'body' | 'heading'): void {
|
|
||||||
dropdown
|
|
||||||
.addOption('Concourse OT', 'Concourse OT')
|
|
||||||
.addOption('Times New Roman', 'Times New Roman')
|
|
||||||
.addOption('Georgia', 'Georgia')
|
|
||||||
.addOption('Arial', 'Arial')
|
|
||||||
.addOption('Helvetica', 'Helvetica')
|
|
||||||
.addOption('Calibri', 'Calibri')
|
|
||||||
.addOption('Cambria', 'Cambria')
|
|
||||||
.addOption('Palatino', 'Palatino')
|
|
||||||
.addOption('Book Antiqua', 'Book Antiqua');
|
|
||||||
|
|
||||||
// Set the appropriate value based on font type
|
|
||||||
const currentValue = fontType === 'body'
|
|
||||||
? state.templateVariables.bodyFont
|
|
||||||
: state.templateVariables.headingFont;
|
|
||||||
|
|
||||||
dropdown
|
|
||||||
.setValue(currentValue || 'Concourse OT')
|
|
||||||
.onChange((value: string) => {
|
|
||||||
if (fontType === 'body') {
|
|
||||||
state.updateTemplateVariables({ bodyFont: value });
|
|
||||||
} else {
|
|
||||||
state.updateTemplateVariables({ headingFont: value });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private addFallbackMonospaceFonts(dropdown: any, state: ModalState): void {
|
|
||||||
dropdown
|
|
||||||
.addOption('Source Code Pro', 'Source Code Pro')
|
|
||||||
.addOption('Courier New', 'Courier New')
|
|
||||||
.addOption('Monaco', 'Monaco')
|
|
||||||
.addOption('Consolas', 'Consolas')
|
|
||||||
.addOption('Menlo', 'Menlo')
|
|
||||||
.addOption('DejaVu Sans Mono', 'DejaVu Sans Mono')
|
|
||||||
.addOption('Liberation Mono', 'Liberation Mono')
|
|
||||||
.addOption('Ubuntu Mono', 'Ubuntu Mono')
|
|
||||||
.setValue(state.templateVariables.monospaceFont || 'Source Code Pro')
|
|
||||||
.onChange((value: string) => {
|
|
||||||
state.updateTemplateVariables({ monospaceFont: value });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
validate(): ValidationResult {
|
validate(): ValidationResult {
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
const warnings: string[] = [];
|
const warnings: string[] = [];
|
||||||
|
|||||||
@@ -3,17 +3,18 @@
|
|||||||
* Centralized state management for the Export Configuration Modal
|
* Centralized state management for the Export Configuration Modal
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { App } from 'obsidian';
|
||||||
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';
|
||||||
|
|
||||||
constructor(initialSettings: Partial<ExportConfigModalSettings>) {
|
constructor(initialSettings: Partial<ExportConfigModalSettings>, private app: App) {
|
||||||
// Load from localStorage if available
|
// Load from localStorage if available
|
||||||
const savedState = this.loadFromStorage();
|
const savedState = this.loadFromStorage();
|
||||||
|
|
||||||
@@ -64,7 +65,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 +139,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;
|
||||||
@@ -174,7 +175,7 @@ export class ModalState implements IModalState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save current state to localStorage
|
* Save current state to vault-specific storage
|
||||||
*/
|
*/
|
||||||
private saveToStorage(): void {
|
private saveToStorage(): void {
|
||||||
const stateToSave = {
|
const stateToSave = {
|
||||||
@@ -187,25 +188,25 @@ export class ModalState implements IModalState {
|
|||||||
},
|
},
|
||||||
templateVariables: this.templateVariables
|
templateVariables: this.templateVariables
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
|
this.app.saveLocalStorage(ModalState.STORAGE_KEY, JSON.stringify(stateToSave));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('Failed to save modal state to localStorage:', error);
|
console.warn('Failed to save modal state to vault storage:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load state from localStorage
|
* Load state from vault-specific storage
|
||||||
*/
|
*/
|
||||||
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 = this.app.loadLocalStorage(ModalState.STORAGE_KEY);
|
||||||
if (saved) {
|
if (saved) {
|
||||||
return JSON.parse(saved);
|
return JSON.parse(saved);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('Failed to load modal state from localStorage:', error);
|
console.warn('Failed to load modal state from vault storage:', error);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Version Utilities
|
||||||
|
*
|
||||||
|
* Lightweight utilities for comparing semantic version strings.
|
||||||
|
* Used for minimum version validation of external dependencies.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares two semantic version strings.
|
||||||
|
*
|
||||||
|
* @param version1 - First version string (e.g., "0.13.0")
|
||||||
|
* @param version2 - Second version string (e.g., "0.5.0")
|
||||||
|
* @returns Negative if version1 < version2, 0 if equal, positive if version1 > version2
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* compareVersions("0.13.0", "0.5.0") // Returns 8 (0.13.0 > 0.5.0)
|
||||||
|
* compareVersions("1.0.0", "1.0.0") // Returns 0 (equal)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function compareVersions(version1: string, version2: string): number {
|
||||||
|
// Extract numeric parts, ignoring pre-release tags and build metadata
|
||||||
|
const v1Parts = version1.split(/[-+]/)[0].split('.').map(Number);
|
||||||
|
const v2Parts = version2.split(/[-+]/)[0].split('.').map(Number);
|
||||||
|
|
||||||
|
const maxLength = Math.max(v1Parts.length, v2Parts.length);
|
||||||
|
for (let i = 0; i < maxLength; i++) {
|
||||||
|
const v1 = v1Parts[i] || 0;
|
||||||
|
const v2 = v2Parts[i] || 0;
|
||||||
|
|
||||||
|
if (v1 !== v2) {
|
||||||
|
return v1 - v2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a version meets a minimum required version.
|
||||||
|
*
|
||||||
|
* @param actualVersion - The detected version string
|
||||||
|
* @param minimumVersion - The minimum required version string
|
||||||
|
* @returns True if actualVersion >= minimumVersion
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* isVersionAtLeast("0.13.0", "0.13.0") // Returns true
|
||||||
|
* isVersionAtLeast("0.12.0", "0.13.0") // Returns false
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function isVersionAtLeast(actualVersion: string, minimumVersion: string): boolean {
|
||||||
|
return compareVersions(actualVersion, minimumVersion) >= 0;
|
||||||
|
}
|
||||||
+220
@@ -134,3 +134,223 @@
|
|||||||
.export-form-hidden {
|
.export-form-hidden {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Export config modal styles */
|
||||||
|
.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-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;
|
||||||
|
}
|
||||||
@@ -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$
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { ModalSettingsHelper } from '../src/core/ModalSettingsHelper';
|
||||||
|
import { obsidianTypstPDFExportSettings, ExportFormat } from '../src/core/settings';
|
||||||
|
import { TFile } from 'obsidian';
|
||||||
|
|
||||||
|
// Mock TFile
|
||||||
|
const createMockFile = (path: string, basename: string): TFile => ({
|
||||||
|
path,
|
||||||
|
basename,
|
||||||
|
extension: 'md',
|
||||||
|
} as TFile);
|
||||||
|
|
||||||
|
// Create mock settings
|
||||||
|
const createMockSettings = (overrides?: Partial<obsidianTypstPDFExportSettings>): obsidianTypstPDFExportSettings => ({
|
||||||
|
pandocPath: '/usr/bin/pandoc',
|
||||||
|
typstPath: '/usr/bin/typst',
|
||||||
|
outputFolder: 'exports',
|
||||||
|
executablePaths: {
|
||||||
|
imagemagickPath: '',
|
||||||
|
additionalPaths: [],
|
||||||
|
},
|
||||||
|
customEnvironmentVariables: {},
|
||||||
|
exportDefaults: {
|
||||||
|
template: 'default',
|
||||||
|
format: ExportFormat.Standard,
|
||||||
|
pageSize: 'a4',
|
||||||
|
orientation: 'portrait',
|
||||||
|
marginTop: '2.5cm',
|
||||||
|
marginBottom: '2.5cm',
|
||||||
|
marginLeft: '2.5cm',
|
||||||
|
marginRight: '2.5cm',
|
||||||
|
bodyFont: 'Georgia',
|
||||||
|
headingFont: 'Helvetica',
|
||||||
|
monospaceFont: 'Courier New',
|
||||||
|
bodyFontSize: '11pt',
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
fonts: {
|
||||||
|
body: 'Georgia',
|
||||||
|
heading: 'Helvetica',
|
||||||
|
monospace: 'Courier New',
|
||||||
|
},
|
||||||
|
fontSizes: {
|
||||||
|
body: 11,
|
||||||
|
heading: 16,
|
||||||
|
small: 9,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pageSetup: {
|
||||||
|
size: 'a4',
|
||||||
|
orientation: 'portrait',
|
||||||
|
margins: {
|
||||||
|
top: 71,
|
||||||
|
right: 71,
|
||||||
|
bottom: 71,
|
||||||
|
left: 71,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
behavior: {
|
||||||
|
openAfterExport: true,
|
||||||
|
preserveFolderStructure: false,
|
||||||
|
exportConcurrency: 3,
|
||||||
|
debugMode: false,
|
||||||
|
embedPdfFiles: false,
|
||||||
|
embedAllFiles: false,
|
||||||
|
printFrontmatter: false,
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ModalSettingsHelper', () => {
|
||||||
|
describe('prepareModalSettings', () => {
|
||||||
|
it('should prepare settings for single file', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const templates = ['default', 'modern'];
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: templates,
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.notePath).toBe('notes/test.md');
|
||||||
|
expect(result.noteTitle).toBe('test');
|
||||||
|
expect(result.files).toBeUndefined();
|
||||||
|
expect(result.template).toBe('default');
|
||||||
|
expect(result.format).toBe(ExportFormat.Standard);
|
||||||
|
expect(result.outputFolder).toBe('exports');
|
||||||
|
expect(result.availableTemplates).toEqual(templates);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should prepare settings for multi-file export', () => {
|
||||||
|
const file1 = createMockFile('notes/test1.md', 'test1');
|
||||||
|
const file2 = createMockFile('notes/test2.md', 'test2');
|
||||||
|
const file3 = createMockFile('notes/test3.md', 'test3');
|
||||||
|
const templates = ['default'];
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file: file1,
|
||||||
|
additionalFiles: [file2, file3],
|
||||||
|
availableTemplates: templates,
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.noteTitle).toBe('3 files');
|
||||||
|
expect(result.files).toHaveLength(3);
|
||||||
|
expect(result.files).toContain(file1);
|
||||||
|
expect(result.files).toContain(file2);
|
||||||
|
expect(result.files).toContain(file3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should include template variables from settings', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.templateVariables).toBeDefined();
|
||||||
|
expect(result.templateVariables?.pageSize).toBe('a4');
|
||||||
|
expect(result.templateVariables?.orientation).toBe('portrait');
|
||||||
|
expect(result.templateVariables?.flipped).toBe(false);
|
||||||
|
expect(result.templateVariables?.marginTop).toBe('71');
|
||||||
|
expect(result.templateVariables?.bodyFont).toBe('Georgia');
|
||||||
|
expect(result.templateVariables?.headingFont).toBe('Helvetica');
|
||||||
|
expect(result.templateVariables?.monospaceFont).toBe('Courier New');
|
||||||
|
expect(result.templateVariables?.bodyFontSize).toBe(11);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set flipped to true for landscape orientation', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const settings = createMockSettings({
|
||||||
|
pageSetup: {
|
||||||
|
size: 'a4',
|
||||||
|
orientation: 'landscape',
|
||||||
|
margins: { top: 71, right: 71, bottom: 71, left: 71 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.templateVariables?.orientation).toBe('landscape');
|
||||||
|
expect(result.templateVariables?.flipped).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add width:auto for landscape single-page format', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const settings = createMockSettings({
|
||||||
|
pageSetup: {
|
||||||
|
size: 'a4',
|
||||||
|
orientation: 'landscape',
|
||||||
|
margins: { top: 71, right: 71, bottom: 71, left: 71 },
|
||||||
|
},
|
||||||
|
exportDefaults: {
|
||||||
|
template: 'default',
|
||||||
|
format: ExportFormat.SinglePage,
|
||||||
|
pageSize: 'a4',
|
||||||
|
orientation: 'landscape',
|
||||||
|
marginTop: '2.5cm',
|
||||||
|
marginBottom: '2.5cm',
|
||||||
|
marginLeft: '2.5cm',
|
||||||
|
marginRight: '2.5cm',
|
||||||
|
bodyFont: 'Georgia',
|
||||||
|
headingFont: 'Helvetica',
|
||||||
|
monospaceFont: 'Courier New',
|
||||||
|
bodyFontSize: '11pt',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.templateVariables?.width).toBe('auto');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not add width:auto for portrait or standard format', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
|
||||||
|
// Test portrait orientation
|
||||||
|
const settingsPortrait = createMockSettings();
|
||||||
|
const resultPortrait = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings: settingsPortrait,
|
||||||
|
});
|
||||||
|
expect(resultPortrait.templateVariables?.width).toBeUndefined();
|
||||||
|
|
||||||
|
// Test landscape with standard format
|
||||||
|
const settingsLandscapeStandard = createMockSettings({
|
||||||
|
pageSetup: {
|
||||||
|
size: 'a4',
|
||||||
|
orientation: 'landscape',
|
||||||
|
margins: { top: 71, right: 71, bottom: 71, left: 71 },
|
||||||
|
},
|
||||||
|
exportDefaults: {
|
||||||
|
template: 'default',
|
||||||
|
format: ExportFormat.Standard,
|
||||||
|
pageSize: 'a4',
|
||||||
|
orientation: 'landscape',
|
||||||
|
marginTop: '2.5cm',
|
||||||
|
marginBottom: '2.5cm',
|
||||||
|
marginLeft: '2.5cm',
|
||||||
|
marginRight: '2.5cm',
|
||||||
|
bodyFont: 'Georgia',
|
||||||
|
headingFont: 'Helvetica',
|
||||||
|
monospaceFont: 'Courier New',
|
||||||
|
bodyFontSize: '11pt',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const resultLandscapeStandard = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings: settingsLandscapeStandard,
|
||||||
|
});
|
||||||
|
expect(resultLandscapeStandard.templateVariables?.width).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use settings behavior options', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const settings = createMockSettings({
|
||||||
|
behavior: {
|
||||||
|
openAfterExport: false,
|
||||||
|
preserveFolderStructure: true,
|
||||||
|
exportConcurrency: 3,
|
||||||
|
debugMode: false,
|
||||||
|
embedPdfFiles: false,
|
||||||
|
embedAllFiles: false,
|
||||||
|
printFrontmatter: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareModalSettings({
|
||||||
|
file,
|
||||||
|
availableTemplates: ['default'],
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.openAfterExport).toBe(false);
|
||||||
|
expect(result.preserveFolderStructure).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('prepareForSingleFile', () => {
|
||||||
|
it('should be a convenience wrapper for single file', () => {
|
||||||
|
const file = createMockFile('notes/test.md', 'test');
|
||||||
|
const templates = ['default', 'modern'];
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareForSingleFile(
|
||||||
|
file,
|
||||||
|
templates,
|
||||||
|
settings
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.notePath).toBe('notes/test.md');
|
||||||
|
expect(result.noteTitle).toBe('test');
|
||||||
|
expect(result.files).toBeUndefined();
|
||||||
|
expect(result.availableTemplates).toEqual(templates);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('prepareForMultiFile', () => {
|
||||||
|
it('should be a convenience wrapper for multiple files', () => {
|
||||||
|
const files = [
|
||||||
|
createMockFile('notes/test1.md', 'test1'),
|
||||||
|
createMockFile('notes/test2.md', 'test2'),
|
||||||
|
];
|
||||||
|
const templates = ['default'];
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareForMultiFile(
|
||||||
|
files,
|
||||||
|
templates,
|
||||||
|
settings
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.noteTitle).toBe('2 files');
|
||||||
|
expect(result.files).toEqual(files);
|
||||||
|
expect(result.notePath).toBe('notes/test1.md');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle single file array', () => {
|
||||||
|
const files = [createMockFile('notes/test.md', 'test')];
|
||||||
|
const settings = createMockSettings();
|
||||||
|
|
||||||
|
const result = ModalSettingsHelper.prepareForMultiFile(
|
||||||
|
files,
|
||||||
|
['default'],
|
||||||
|
settings
|
||||||
|
);
|
||||||
|
|
||||||
|
// Single file should still show as single file
|
||||||
|
expect(result.noteTitle).toBe('test');
|
||||||
|
expect(result.files).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { SecurityUtils } from '../src/core/SecurityUtils';
|
||||||
|
|
||||||
|
describe('SecurityUtils', () => {
|
||||||
|
describe('validateOutputPath', () => {
|
||||||
|
it('should accept valid relative paths', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateOutputPath('my-exports')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports/pdfs')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateOutputPath('folder_name')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject empty or invalid input', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath(null as any)).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath(undefined as any)).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath(123 as any)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject path traversal attempts', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('..')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('../')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('../../secret')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports/../../../etc')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject absolute paths', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('/etc/passwd')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('/usr/local')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('\\Windows\\System32')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('\\etc\\hosts')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject null bytes', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports\x00malicious')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('\x00')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject double slashes', () => {
|
||||||
|
// Note: path.normalize() resolves double slashes in the middle, so we test edge cases
|
||||||
|
// that remain problematic even after normalization
|
||||||
|
expect(SecurityUtils.validateOutputPath('//exports')).toBe(false); // Starts with //
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject invalid filename characters', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports<test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports>test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports:test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports"test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports|test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports?test')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('exports*test')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject Windows reserved names', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath('CON')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('PRN')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('AUX')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('NUL')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('COM1')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('COM9')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('LPT1')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateOutputPath('lpt9')).toBe(false); // Case insensitive
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle whitespace correctly', () => {
|
||||||
|
expect(SecurityUtils.validateOutputPath(' exports ')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateOutputPath(' .. ')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('validateExecutablePath', () => {
|
||||||
|
it('should accept empty paths (system PATH)', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateExecutablePath(' ')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept valid executable paths', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('/usr/bin/pandoc')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('/opt/typst/typst')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('C:\\Program Files\\Pandoc\\pandoc.exe')).toBe(true);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject shell metacharacters', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc;rm -rf /')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc&whoami')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc|cat /etc/passwd')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc`whoami`')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc$(whoami)')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc{}')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc[]')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject null bytes', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc\x00malicious')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('\x00')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject newlines', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc\nrm -rf /')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc\r\nmalicious')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject command separators with whitespace', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc ; whoami')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc & whoami')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('pandoc | whoami')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject variable and command substitution', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath('${MALICIOUS}')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('`whoami`')).toBe(false);
|
||||||
|
expect(SecurityUtils.validateExecutablePath('$(malicious)')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle whitespace in paths', () => {
|
||||||
|
expect(SecurityUtils.validateExecutablePath(' /usr/bin/pandoc ')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getPathValidationError', () => {
|
||||||
|
it('should return appropriate error for empty path', () => {
|
||||||
|
expect(SecurityUtils.getPathValidationError('')).toBe('Output folder is required');
|
||||||
|
expect(SecurityUtils.getPathValidationError(null as any)).toBe('Output folder is required');
|
||||||
|
expect(SecurityUtils.getPathValidationError(undefined as any)).toBe('Output folder is required');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for path traversal', () => {
|
||||||
|
const error = SecurityUtils.getPathValidationError('..');
|
||||||
|
expect(error).toBe('Path traversal attempts (..) are not allowed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for absolute paths', () => {
|
||||||
|
const error = SecurityUtils.getPathValidationError('/etc/passwd');
|
||||||
|
expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for null bytes', () => {
|
||||||
|
const error = SecurityUtils.getPathValidationError('exports\x00');
|
||||||
|
expect(error).toBe('Null bytes are not allowed in paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for double slashes', () => {
|
||||||
|
// Test with leading // which should fail the absolute path check
|
||||||
|
const error = SecurityUtils.getPathValidationError('//exports');
|
||||||
|
expect(error).toBe('Absolute paths are not allowed - use relative paths from vault root');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for invalid characters', () => {
|
||||||
|
const error = SecurityUtils.getPathValidationError('exports<test');
|
||||||
|
expect(error).toBe('Invalid characters found in path');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for reserved names', () => {
|
||||||
|
const error = SecurityUtils.getPathValidationError('CON');
|
||||||
|
expect(error).toBe('Reserved system names are not allowed in paths (found: CON)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return generic error for unknown issues', () => {
|
||||||
|
// For a valid path, it would still return 'Invalid path format' if called
|
||||||
|
// (though normally you wouldn't call this for valid paths)
|
||||||
|
const validPath = 'exports';
|
||||||
|
// This is a bit contrived since we wouldn't normally call this on valid paths
|
||||||
|
// but it tests the fallback case
|
||||||
|
expect(SecurityUtils.getPathValidationError(validPath)).toBe('Invalid path format');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getExecutablePathValidationError', () => {
|
||||||
|
it('should return appropriate error for empty path', () => {
|
||||||
|
expect(SecurityUtils.getExecutablePathValidationError(null as any))
|
||||||
|
.toBe('Executable path is required');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for shell metacharacters', () => {
|
||||||
|
const error = SecurityUtils.getExecutablePathValidationError('pandoc;whoami');
|
||||||
|
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for null bytes', () => {
|
||||||
|
const error = SecurityUtils.getExecutablePathValidationError('pandoc\x00');
|
||||||
|
expect(error).toBe('Null bytes are not allowed in paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for newlines', () => {
|
||||||
|
const error = SecurityUtils.getExecutablePathValidationError('pandoc\nrm');
|
||||||
|
expect(error).toBe('Newlines are not allowed in paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for command separators', () => {
|
||||||
|
// The semicolon is caught by shell metacharacters check first
|
||||||
|
const error = SecurityUtils.getExecutablePathValidationError('pandoc ; whoami');
|
||||||
|
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return appropriate error for substitution patterns', () => {
|
||||||
|
// These contain shell metacharacters, which are checked first
|
||||||
|
const error = SecurityUtils.getExecutablePathValidationError('${VAR}');
|
||||||
|
expect(error).toBe('Shell metacharacters are not allowed in executable paths');
|
||||||
|
|
||||||
|
const error2 = SecurityUtils.getExecutablePathValidationError('`cmd`');
|
||||||
|
expect(error2).toBe('Shell metacharacters are not allowed in executable paths');
|
||||||
|
|
||||||
|
const error3 = SecurityUtils.getExecutablePathValidationError('$(cmd)');
|
||||||
|
expect(error3).toBe('Shell metacharacters are not allowed in executable paths');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return generic error for valid paths when forced', () => {
|
||||||
|
const validPath = '/usr/bin/pandoc';
|
||||||
|
// Again, contrived - but tests the fallback
|
||||||
|
expect(SecurityUtils.getExecutablePathValidationError(validPath))
|
||||||
|
.toBe('Invalid executable path format');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
|
import { TempDirectoryManager } from '../src/core/TempDirectoryManager';
|
||||||
|
import type { App } from 'obsidian';
|
||||||
|
|
||||||
|
// Create mock functions that will be used in vi.mock - using vi.hoisted to ensure they're available
|
||||||
|
const { mockFsAccess, mockFsMkdir, mockFsReaddir, mockFsStat, mockFsUnlink } = vi.hoisted(() => ({
|
||||||
|
mockFsAccess: vi.fn(),
|
||||||
|
mockFsMkdir: vi.fn(),
|
||||||
|
mockFsReaddir: vi.fn(),
|
||||||
|
mockFsStat: vi.fn(),
|
||||||
|
mockFsUnlink: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock the fs module
|
||||||
|
vi.mock('fs', () => ({
|
||||||
|
default: {},
|
||||||
|
promises: {
|
||||||
|
access: mockFsAccess,
|
||||||
|
mkdir: mockFsMkdir,
|
||||||
|
readdir: mockFsReaddir,
|
||||||
|
stat: mockFsStat,
|
||||||
|
unlink: mockFsUnlink,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('TempDirectoryManager', () => {
|
||||||
|
let mockApp: App;
|
||||||
|
let mockVaultAdapter: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// Reset all mocks before each test
|
||||||
|
vi.clearAllMocks();
|
||||||
|
|
||||||
|
// Reset mocks before each test
|
||||||
|
mockVaultAdapter = {
|
||||||
|
exists: vi.fn(),
|
||||||
|
mkdir: vi.fn(),
|
||||||
|
remove: vi.fn(),
|
||||||
|
list: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
mockApp = {
|
||||||
|
vault: {
|
||||||
|
adapter: mockVaultAdapter,
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('constructor and static create', () => {
|
||||||
|
it('should create an instance with provided options', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'test-plugin',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(manager).toBeInstanceOf(TempDirectoryManager);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use default plugin name if not provided', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = manager.getTempDir('images');
|
||||||
|
expect(tempDir).toContain('typst-pdf-export');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create instance via static create method', () => {
|
||||||
|
const manager = TempDirectoryManager.create(
|
||||||
|
'/vault',
|
||||||
|
'.obsidian',
|
||||||
|
'test-plugin',
|
||||||
|
mockApp
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(manager).toBeInstanceOf(TempDirectoryManager);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getTempDir', () => {
|
||||||
|
it('should return correct path for images temp directory', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = manager.getTempDir('images');
|
||||||
|
expect(tempDir).toContain('temp-images');
|
||||||
|
expect(tempDir).toContain('.obsidian');
|
||||||
|
expect(tempDir).toContain('plugins');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return correct path for pandoc temp directory', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = manager.getTempDir('pandoc');
|
||||||
|
expect(tempDir).toContain('temp-pandoc');
|
||||||
|
expect(tempDir).toContain('.obsidian');
|
||||||
|
expect(tempDir).toContain('plugins');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should normalize paths correctly', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = manager.getTempDir('images');
|
||||||
|
// Should use forward slashes after normalization
|
||||||
|
expect(tempDir).not.toContain('\\');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle absolute vault paths on Windows', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: 'C:/Users/Test/Vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = manager.getTempDir('images');
|
||||||
|
expect(tempDir).toContain('C:/Users/Test/Vault');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ensureTempDir', () => {
|
||||||
|
it('should create directory if it does not exist', async () => {
|
||||||
|
// fs.access rejects when directory doesn't exist
|
||||||
|
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
|
||||||
|
mockFsMkdir.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.ensureTempDir('images');
|
||||||
|
|
||||||
|
expect(mockFsAccess).toHaveBeenCalledOnce();
|
||||||
|
expect(mockFsMkdir).toHaveBeenCalledOnce();
|
||||||
|
expect(result).toContain('temp-images');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not create directory if it already exists', async () => {
|
||||||
|
// fs.access resolves when directory exists
|
||||||
|
mockFsAccess.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.ensureTempDir('images');
|
||||||
|
|
||||||
|
expect(mockFsAccess).toHaveBeenCalledOnce();
|
||||||
|
expect(mockFsMkdir).not.toHaveBeenCalled();
|
||||||
|
expect(result).toContain('temp-images');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle both images and pandoc directories', async () => {
|
||||||
|
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
|
||||||
|
mockFsMkdir.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const imagesDir = await manager.ensureTempDir('images');
|
||||||
|
const pandocDir = await manager.ensureTempDir('pandoc');
|
||||||
|
|
||||||
|
expect(imagesDir).toContain('temp-images');
|
||||||
|
expect(pandocDir).toContain('temp-pandoc');
|
||||||
|
expect(mockFsMkdir).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cleanupTempDir', () => {
|
||||||
|
it('should remove all files from temp directory', async () => {
|
||||||
|
mockFsAccess.mockResolvedValue(undefined);
|
||||||
|
mockFsReaddir.mockResolvedValue(['file1.png', 'file2.png', 'file3.typ']);
|
||||||
|
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
|
||||||
|
mockFsUnlink.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupTempDir('images');
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(mockFsUnlink).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return true if directory does not exist', async () => {
|
||||||
|
mockFsAccess.mockRejectedValue(new Error('ENOENT'));
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupTempDir('images');
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(mockFsUnlink).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false and log warning on error', async () => {
|
||||||
|
mockFsAccess.mockResolvedValue(undefined);
|
||||||
|
mockFsReaddir.mockRejectedValue(new Error('Access denied'));
|
||||||
|
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupTempDir('images');
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalled();
|
||||||
|
|
||||||
|
consoleWarnSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle errors during file removal', async () => {
|
||||||
|
mockFsAccess.mockResolvedValue(undefined);
|
||||||
|
mockFsReaddir.mockResolvedValue(['file1.png']);
|
||||||
|
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
|
||||||
|
mockFsUnlink.mockRejectedValue(new Error('Cannot delete'));
|
||||||
|
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupTempDir('images');
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalled();
|
||||||
|
|
||||||
|
consoleWarnSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cleanupAllTempDirs', () => {
|
||||||
|
it('should clean up both temp directories', async () => {
|
||||||
|
mockFsAccess.mockResolvedValue(undefined);
|
||||||
|
mockFsReaddir.mockResolvedValue(['file1.png']);
|
||||||
|
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
|
||||||
|
mockFsUnlink.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupAllTempDirs();
|
||||||
|
|
||||||
|
expect(result).toEqual({ images: true, pandoc: true });
|
||||||
|
expect(mockFsReaddir).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return status for each directory independently', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
mockFsAccess.mockImplementation(() => {
|
||||||
|
callCount++;
|
||||||
|
// First call (images) succeeds, second call (pandoc) fails
|
||||||
|
if (callCount === 1) return Promise.resolve(undefined);
|
||||||
|
return Promise.reject(new Error('Access denied'));
|
||||||
|
});
|
||||||
|
mockFsReaddir.mockResolvedValue(['file1.png']);
|
||||||
|
mockFsStat.mockResolvedValue({ isFile: () => true } as any);
|
||||||
|
mockFsUnlink.mockResolvedValue(undefined);
|
||||||
|
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await manager.cleanupAllTempDirs();
|
||||||
|
|
||||||
|
expect(result.images).toBe(true);
|
||||||
|
expect(result.pandoc).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isPluginTempDir', () => {
|
||||||
|
it('should return true for images temp directory', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempImagesDir = manager.getTempDir('images');
|
||||||
|
expect(manager.isPluginTempDir(tempImagesDir)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return true for pandoc temp directory', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempPandocDir = manager.getTempDir('pandoc');
|
||||||
|
expect(manager.isPluginTempDir(tempPandocDir)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return true for subdirectories within temp directories', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempImagesDir = manager.getTempDir('images');
|
||||||
|
const subDir = `${tempImagesDir}/subfolder`;
|
||||||
|
expect(manager.isPluginTempDir(subDir)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false for non-temp directories', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: '/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(manager.isPluginTempDir('/vault/some-other-folder')).toBe(false);
|
||||||
|
expect(manager.isPluginTempDir('/vault/.obsidian/plugins/other-plugin')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle paths with different separators', () => {
|
||||||
|
const manager = new TempDirectoryManager({
|
||||||
|
vaultPath: 'C:/vault',
|
||||||
|
configDir: '.obsidian',
|
||||||
|
pluginName: 'typst-pdf-export',
|
||||||
|
app: mockApp,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempImagesDir = manager.getTempDir('images');
|
||||||
|
// Test with backslashes (should be normalized)
|
||||||
|
const windowsStylePath = tempImagesDir.replace(/\//g, '\\');
|
||||||
|
expect(manager.isPluginTempDir(windowsStylePath)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import { describe, it, expect, vi } from 'vitest';
|
||||||
|
import { TypstVariableMapper } from '../src/converters/pandoc/TypstVariableMapper';
|
||||||
|
import { PandocOptions } from '../src/converters/converterTypes';
|
||||||
|
import { ExportFormat, obsidianTypstPDFExportSettings } from '../src/core/settings';
|
||||||
|
|
||||||
|
const createMockPlugin = (settings: Partial<obsidianTypstPDFExportSettings> = {}) => ({
|
||||||
|
settings: {
|
||||||
|
pandocPath: '/usr/bin/pandoc',
|
||||||
|
typstPath: '/usr/bin/typst',
|
||||||
|
outputFolder: 'exports',
|
||||||
|
executablePaths: { imagemagickPath: '', additionalPaths: [] },
|
||||||
|
customEnvironmentVariables: {},
|
||||||
|
exportDefaults: {
|
||||||
|
template: 'default',
|
||||||
|
format: ExportFormat.Standard,
|
||||||
|
pageSize: 'a4',
|
||||||
|
orientation: 'portrait' as const,
|
||||||
|
marginTop: '2.5cm',
|
||||||
|
marginBottom: '2.5cm',
|
||||||
|
marginLeft: '2.5cm',
|
||||||
|
marginRight: '2.5cm',
|
||||||
|
bodyFont: 'Georgia',
|
||||||
|
headingFont: 'Helvetica',
|
||||||
|
monospaceFont: 'Courier',
|
||||||
|
bodyFontSize: '11pt',
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
fonts: { body: 'Georgia', heading: 'Helvetica', monospace: 'Courier' },
|
||||||
|
fontSizes: { body: 11, heading: 16, small: 9 },
|
||||||
|
},
|
||||||
|
pageSetup: {
|
||||||
|
size: 'a4',
|
||||||
|
orientation: 'portrait' as const,
|
||||||
|
margins: { top: 71, right: 71, bottom: 71, left: 71 },
|
||||||
|
},
|
||||||
|
behavior: {
|
||||||
|
openAfterExport: true,
|
||||||
|
preserveFolderStructure: false,
|
||||||
|
exportConcurrency: 3,
|
||||||
|
debugMode: false,
|
||||||
|
embedPdfFiles: false,
|
||||||
|
embedAllFiles: false,
|
||||||
|
printFrontmatter: false,
|
||||||
|
},
|
||||||
|
...settings,
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
describe('TypstVariableMapper', () => {
|
||||||
|
describe('transformExportConfigVariable', () => {
|
||||||
|
it('should map bodyFont to font', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: { bodyFont: 'Arial' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
const fontVar = vars.find(v => v.name === 'font');
|
||||||
|
|
||||||
|
expect(fontVar).toBeDefined();
|
||||||
|
expect(fontVar?.value).toBe('Arial');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should map headingFont to heading_font', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: { headingFont: 'Helvetica' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
const headingVar = vars.find(v => v.name === 'heading_font');
|
||||||
|
|
||||||
|
expect(headingVar).toBeDefined();
|
||||||
|
expect(headingVar?.value).toBe('Helvetica');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should map bodyFontSize to fontsize with pt unit', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: { bodyFontSize: 12 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
const sizeVar = vars.find(v => v.name === 'fontsize');
|
||||||
|
|
||||||
|
expect(sizeVar).toBeDefined();
|
||||||
|
expect(sizeVar?.value).toBe('12pt');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should map pageSize to paper with Typst value', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: { pageSize: 'a4' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
const paperVar = vars.find(v => v.name === 'paper');
|
||||||
|
|
||||||
|
expect(paperVar).toBeDefined();
|
||||||
|
expect(paperVar?.value).toBe('a4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should map margin variables with cm unit', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: {
|
||||||
|
marginTop: 2,
|
||||||
|
marginBottom: 3,
|
||||||
|
marginLeft: 2.5,
|
||||||
|
marginRight: 2.5,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
|
||||||
|
expect(vars.find(v => v.name === 'margin_top')?.value).toBe('2cm');
|
||||||
|
expect(vars.find(v => v.name === 'margin_bottom')?.value).toBe('3cm');
|
||||||
|
expect(vars.find(v => v.name === 'margin_left')?.value).toBe('2.5cm');
|
||||||
|
expect(vars.find(v => v.name === 'margin_right')?.value).toBe('2.5cm');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should preserve unmapped variables', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: {
|
||||||
|
orientation: 'landscape',
|
||||||
|
flipped: true,
|
||||||
|
customVar: 'value',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
|
||||||
|
expect(vars.find(v => v.name === 'orientation')?.value).toBe('landscape');
|
||||||
|
expect(vars.find(v => v.name === 'flipped')?.value).toBe('true');
|
||||||
|
expect(vars.find(v => v.name === 'customVar')?.value).toBe('value');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mapPluginSettingsVariables', () => {
|
||||||
|
it('should add typography variables from settings', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = { variables: {} };
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
|
||||||
|
expect(vars.find(v => v.name === 'font')?.value).toBe('Georgia');
|
||||||
|
expect(vars.find(v => v.name === 'heading_font')?.value).toBe('Helvetica');
|
||||||
|
expect(vars.find(v => v.name === 'fontsize')?.value).toBe('11pt');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not override export config variables', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: { bodyFont: 'Arial' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
const fontVars = vars.filter(v => v.name === 'font');
|
||||||
|
|
||||||
|
// Should only have one font variable from export config
|
||||||
|
expect(fontVars).toHaveLength(1);
|
||||||
|
expect(fontVars[0].value).toBe('Arial');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add page setup variables from settings', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = { variables: {} };
|
||||||
|
|
||||||
|
const vars = mapper.mapAllVariablesToTypst(options);
|
||||||
|
|
||||||
|
expect(vars.find(v => v.name === 'paper')?.value).toBe('a4');
|
||||||
|
expect(vars.find(v => v.name === 'orientation')?.value).toBe('portrait');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('convertVariablesToPandocArgs', () => {
|
||||||
|
it('should convert variables to pandoc -V arguments', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const variables = [
|
||||||
|
{ name: 'font', value: 'Arial' },
|
||||||
|
{ name: 'fontsize', value: '12pt' },
|
||||||
|
{ name: 'paper', value: 'a4' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const args = mapper.convertVariablesToPandocArgs(variables);
|
||||||
|
|
||||||
|
expect(args).toEqual([
|
||||||
|
'-V', 'font=Arial',
|
||||||
|
'-V', 'fontsize=12pt',
|
||||||
|
'-V', 'paper=a4',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle empty variables array', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const args = mapper.convertVariablesToPandocArgs([]);
|
||||||
|
|
||||||
|
expect(args).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getExportConfigVariableNames', () => {
|
||||||
|
it('should return set of variable names including mappings', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = {
|
||||||
|
variables: {
|
||||||
|
bodyFont: 'Arial',
|
||||||
|
pageSize: 'a4',
|
||||||
|
marginTop: 2,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const names = mapper.getExportConfigVariableNames(options);
|
||||||
|
|
||||||
|
expect(names.has('bodyFont')).toBe(true);
|
||||||
|
expect(names.has('font')).toBe(true);
|
||||||
|
expect(names.has('pageSize')).toBe(true);
|
||||||
|
expect(names.has('paper')).toBe(true);
|
||||||
|
expect(names.has('marginTop')).toBe(true);
|
||||||
|
expect(names.has('margin_top')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle empty variables', () => {
|
||||||
|
const mapper = new TypstVariableMapper(createMockPlugin());
|
||||||
|
const options: PandocOptions = { variables: {} };
|
||||||
|
|
||||||
|
const names = mapper.getExportConfigVariableNames(options);
|
||||||
|
|
||||||
|
expect(names.size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Mock Obsidian API for testing
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
|
||||||
|
export class Notice {
|
||||||
|
constructor(message: string) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Plugin {
|
||||||
|
app: any;
|
||||||
|
manifest: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PluginSettingTab {
|
||||||
|
constructor(app: any, plugin: any) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Setting {
|
||||||
|
constructor(containerEl: HTMLElement) {}
|
||||||
|
setName(name: string): this { return this; }
|
||||||
|
setDesc(desc: string): this { return this; }
|
||||||
|
addText(cb: any): this { return this; }
|
||||||
|
addToggle(cb: any): this { return this; }
|
||||||
|
addDropdown(cb: any): this { return this; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Modal {
|
||||||
|
constructor(app: any) {}
|
||||||
|
open(): void {}
|
||||||
|
close(): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FuzzySuggestModal {
|
||||||
|
constructor(app: any) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TFile {
|
||||||
|
path = '';
|
||||||
|
basename = '';
|
||||||
|
extension = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TFolder {
|
||||||
|
path = '';
|
||||||
|
name = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizePath(path: string): string {
|
||||||
|
return path.replace(/\\/g, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const requestUrl = vi.fn();
|
||||||
|
|
||||||
|
// Type exports for compatibility
|
||||||
|
export interface App {
|
||||||
|
vault: {
|
||||||
|
adapter: {
|
||||||
|
exists: (path: string) => Promise<boolean>;
|
||||||
|
mkdir: (path: string) => Promise<void>;
|
||||||
|
remove: (path: string) => Promise<void>;
|
||||||
|
list: (path: string) => Promise<{ files: string[]; folders: string[] }>;
|
||||||
|
read: (path: string) => Promise<string>;
|
||||||
|
write: (path: string, data: string) => Promise<void>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* Basic coverage tests for simpler modules
|
||||||
|
* These tests ensure basic functionality and increase overall coverage
|
||||||
|
*/
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
|
||||||
|
// Import type files and constants
|
||||||
|
import { FALLBACK_FONTS, PLUGIN_DIRS, EXPORT_CONSTANTS, DEPENDENCY_CONSTANTS } from '../src/core/constants';
|
||||||
|
import { ExportFormat } from '../src/core/settings';
|
||||||
|
|
||||||
|
// Import utilities
|
||||||
|
import { SUPPORTED_PAPER_SIZES, DEFAULT_PAPER_SIZE, mapToTypstPaperSize, isSupportedPaperSize } from '../src/utils/paperSizeMapper';
|
||||||
|
|
||||||
|
describe('Constants and Types Coverage', () => {
|
||||||
|
describe('FALLBACK_FONTS', () => {
|
||||||
|
it('should have defined fallback fonts', () => {
|
||||||
|
expect(FALLBACK_FONTS.length).toBeGreaterThan(0);
|
||||||
|
expect(FALLBACK_FONTS).toContain('Times New Roman');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PLUGIN_DIRS', () => {
|
||||||
|
it('should have temp directory names', () => {
|
||||||
|
expect(PLUGIN_DIRS.TEMP_IMAGES).toBe('temp-images');
|
||||||
|
expect(PLUGIN_DIRS.TEMP_PANDOC).toBe('temp-pandoc');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EXPORT_CONSTANTS', () => {
|
||||||
|
it('should have timeout constants', () => {
|
||||||
|
expect(EXPORT_CONSTANTS.DEFAULT_TIMEOUT).toBe(120000);
|
||||||
|
expect(EXPORT_CONSTANTS.NOTICE_DURATION.SHORT).toBe(5000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DEPENDENCY_CONSTANTS', () => {
|
||||||
|
it('should have default executables', () => {
|
||||||
|
expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc).toBe('pandoc');
|
||||||
|
expect(DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst).toBe('typst');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have common paths', () => {
|
||||||
|
expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE).toContain('/.local/bin');
|
||||||
|
expect(DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE).toContain('/usr/local/bin');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ExportFormat enum', () => {
|
||||||
|
it('should have standard and single-page formats', () => {
|
||||||
|
expect(ExportFormat.Standard).toBe('standard');
|
||||||
|
expect(ExportFormat.SinglePage).toBe('single-page');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Paper size utilities', () => {
|
||||||
|
it('should have multiple paper sizes', () => {
|
||||||
|
expect(SUPPORTED_PAPER_SIZES.length).toBeGreaterThan(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should map known sizes', () => {
|
||||||
|
expect(mapToTypstPaperSize('a4')).toBe('a4');
|
||||||
|
expect(mapToTypstPaperSize('us-letter')).toBe('us-letter');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate paper sizes', () => {
|
||||||
|
expect(isSupportedPaperSize('a4')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('invalid')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have a default paper size', () => {
|
||||||
|
expect(DEFAULT_PAPER_SIZE).toBe('a4');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { ExportFormat } from '../src/core/settings';
|
||||||
|
|
||||||
|
// Type definition file - basic import test to ensure types compile
|
||||||
|
describe('converterTypes', () => {
|
||||||
|
it('should export ExportFormat enum', () => {
|
||||||
|
expect(ExportFormat.Standard).toBe('standard');
|
||||||
|
expect(ExportFormat.SinglePage).toBe('single-page');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import {
|
||||||
|
SUPPORTED_PAPER_SIZES,
|
||||||
|
DEFAULT_PAPER_SIZE,
|
||||||
|
mapToTypstPaperSize,
|
||||||
|
getValidTypstPaperSizes,
|
||||||
|
isSupportedPaperSize,
|
||||||
|
} from '../src/utils/paperSizeMapper';
|
||||||
|
|
||||||
|
describe('paperSizeMapper', () => {
|
||||||
|
describe('SUPPORTED_PAPER_SIZES', () => {
|
||||||
|
it('should have all required paper sizes', () => {
|
||||||
|
expect(SUPPORTED_PAPER_SIZES).toHaveLength(8);
|
||||||
|
|
||||||
|
const keys = SUPPORTED_PAPER_SIZES.map(size => size.key);
|
||||||
|
expect(keys).toContain('a3');
|
||||||
|
expect(keys).toContain('a4');
|
||||||
|
expect(keys).toContain('a5');
|
||||||
|
expect(keys).toContain('a6');
|
||||||
|
expect(keys).toContain('eu-business-card');
|
||||||
|
expect(keys).toContain('us-letter');
|
||||||
|
expect(keys).toContain('us-legal');
|
||||||
|
expect(keys).toContain('us-business-card');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have correct structure for each paper size', () => {
|
||||||
|
SUPPORTED_PAPER_SIZES.forEach(size => {
|
||||||
|
expect(size).toHaveProperty('key');
|
||||||
|
expect(size).toHaveProperty('displayName');
|
||||||
|
expect(size).toHaveProperty('typstValue');
|
||||||
|
|
||||||
|
expect(typeof size.key).toBe('string');
|
||||||
|
expect(typeof size.displayName).toBe('string');
|
||||||
|
expect(typeof size.typstValue).toBe('string');
|
||||||
|
|
||||||
|
expect(size.key.length).toBeGreaterThan(0);
|
||||||
|
expect(size.displayName.length).toBeGreaterThan(0);
|
||||||
|
expect(size.typstValue.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have unique keys', () => {
|
||||||
|
const keys = SUPPORTED_PAPER_SIZES.map(size => size.key);
|
||||||
|
const uniqueKeys = new Set(keys);
|
||||||
|
expect(uniqueKeys.size).toBe(keys.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have display names with dimensions', () => {
|
||||||
|
SUPPORTED_PAPER_SIZES.forEach(size => {
|
||||||
|
// Display names should contain either 'mm' or 'in'
|
||||||
|
expect(size.displayName).toMatch(/\d+\s*×\s*\d+\s*(mm|in)/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DEFAULT_PAPER_SIZE', () => {
|
||||||
|
it('should be a4', () => {
|
||||||
|
expect(DEFAULT_PAPER_SIZE).toBe('a4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be a valid supported paper size', () => {
|
||||||
|
expect(isSupportedPaperSize(DEFAULT_PAPER_SIZE)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mapToTypstPaperSize', () => {
|
||||||
|
it('should map supported paper sizes correctly', () => {
|
||||||
|
expect(mapToTypstPaperSize('a3')).toBe('a3');
|
||||||
|
expect(mapToTypstPaperSize('a4')).toBe('a4');
|
||||||
|
expect(mapToTypstPaperSize('a5')).toBe('a5');
|
||||||
|
expect(mapToTypstPaperSize('a6')).toBe('a6');
|
||||||
|
expect(mapToTypstPaperSize('us-letter')).toBe('us-letter');
|
||||||
|
expect(mapToTypstPaperSize('us-legal')).toBe('us-legal');
|
||||||
|
expect(mapToTypstPaperSize('eu-business-card')).toBe('eu-business-card');
|
||||||
|
expect(mapToTypstPaperSize('us-business-card')).toBe('us-business-card');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return default for unsupported paper sizes', () => {
|
||||||
|
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
expect(mapToTypstPaperSize('invalid-size')).toBe('a4');
|
||||||
|
expect(mapToTypstPaperSize('unknown')).toBe('a4');
|
||||||
|
expect(mapToTypstPaperSize('')).toBe('a4');
|
||||||
|
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalledTimes(3);
|
||||||
|
consoleWarnSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should log warning for unsupported sizes', () => {
|
||||||
|
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
mapToTypstPaperSize('invalid-size');
|
||||||
|
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Unknown paper size: invalid-size')
|
||||||
|
);
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Using default: a4')
|
||||||
|
);
|
||||||
|
|
||||||
|
consoleWarnSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle case-sensitive keys', () => {
|
||||||
|
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
// Keys are case-sensitive
|
||||||
|
expect(mapToTypstPaperSize('A4')).toBe('a4'); // Should fall back to default
|
||||||
|
expect(consoleWarnSpy).toHaveBeenCalled();
|
||||||
|
|
||||||
|
consoleWarnSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getValidTypstPaperSizes', () => {
|
||||||
|
it('should return all Typst paper size values', () => {
|
||||||
|
const validSizes = getValidTypstPaperSizes();
|
||||||
|
|
||||||
|
expect(validSizes).toHaveLength(8);
|
||||||
|
expect(validSizes).toContain('a3');
|
||||||
|
expect(validSizes).toContain('a4');
|
||||||
|
expect(validSizes).toContain('a5');
|
||||||
|
expect(validSizes).toContain('a6');
|
||||||
|
expect(validSizes).toContain('eu-business-card');
|
||||||
|
expect(validSizes).toContain('us-letter');
|
||||||
|
expect(validSizes).toContain('us-legal');
|
||||||
|
expect(validSizes).toContain('us-business-card');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return a new array each time', () => {
|
||||||
|
const sizes1 = getValidTypstPaperSizes();
|
||||||
|
const sizes2 = getValidTypstPaperSizes();
|
||||||
|
|
||||||
|
// Should return different array instances
|
||||||
|
expect(sizes1).not.toBe(sizes2);
|
||||||
|
|
||||||
|
// But with same content
|
||||||
|
expect(sizes1).toEqual(sizes2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not include duplicate values', () => {
|
||||||
|
const validSizes = getValidTypstPaperSizes();
|
||||||
|
const uniqueSizes = new Set(validSizes);
|
||||||
|
|
||||||
|
expect(uniqueSizes.size).toBe(validSizes.length);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isSupportedPaperSize', () => {
|
||||||
|
it('should return true for supported sizes', () => {
|
||||||
|
expect(isSupportedPaperSize('a3')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('a4')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('a5')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('a6')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('us-letter')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('us-legal')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('eu-business-card')).toBe(true);
|
||||||
|
expect(isSupportedPaperSize('us-business-card')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false for unsupported sizes', () => {
|
||||||
|
expect(isSupportedPaperSize('invalid')).toBe(false);
|
||||||
|
expect(isSupportedPaperSize('unknown')).toBe(false);
|
||||||
|
expect(isSupportedPaperSize('')).toBe(false);
|
||||||
|
expect(isSupportedPaperSize('A4')).toBe(false); // Case-sensitive
|
||||||
|
expect(isSupportedPaperSize('letter')).toBe(false); // Missing 'us-' prefix
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle edge cases', () => {
|
||||||
|
expect(isSupportedPaperSize(null as any)).toBe(false);
|
||||||
|
expect(isSupportedPaperSize(undefined as any)).toBe(false);
|
||||||
|
expect(isSupportedPaperSize(123 as any)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
// Mock process.platform for cross-platform testing
|
||||||
|
Object.defineProperty(process, 'platform', {
|
||||||
|
value: 'darwin',
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
@@ -11,6 +11,8 @@
|
|||||||
"importHelpers": true,
|
"importHelpers": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
"lib": [
|
"lib": [
|
||||||
"DOM",
|
"DOM",
|
||||||
"ES5",
|
"ES5",
|
||||||
|
|||||||
+7
-1
@@ -1,5 +1,11 @@
|
|||||||
{
|
{
|
||||||
"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",
|
||||||
|
"1.3.0": "1.9.12",
|
||||||
|
"1.3.1": "1.9.12",
|
||||||
|
"1.4.0": "1.9.12",
|
||||||
|
"1.4.1": "1.9.12"
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: 'happy-dom',
|
||||||
|
setupFiles: ['./tests/setup.ts'],
|
||||||
|
coverage: {
|
||||||
|
provider: 'v8',
|
||||||
|
reporter: ['text', 'json', 'html', 'lcov'],
|
||||||
|
include: ['src/**/*.ts'],
|
||||||
|
exclude: [
|
||||||
|
'node_modules/**',
|
||||||
|
'tests/**',
|
||||||
|
'*.config.*',
|
||||||
|
'**/*.d.ts',
|
||||||
|
'**/*.test.ts',
|
||||||
|
'main.ts', // Entry point, tested through integration
|
||||||
|
'version-bump.mjs',
|
||||||
|
'scripts/**',
|
||||||
|
],
|
||||||
|
all: true, // Include all source files in coverage report
|
||||||
|
thresholds: {
|
||||||
|
lines: 80,
|
||||||
|
functions: 80,
|
||||||
|
branches: 80,
|
||||||
|
statements: 80,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: ['tests/**/*.test.ts'],
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, './src'),
|
||||||
|
'obsidian': path.resolve(__dirname, './tests/__mocks__/obsidian.ts'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in new issue
Block a user