From ccc0e5aec60e68c371620ef869747f35603d1d81 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 3 Sep 2025 19:23:44 +0200 Subject: [PATCH] Delete Unused Code --- src/CSSExtractor.ts | 393 --------------- src/CSSToTypstMapper.ts | 737 ---------------------------- src/DependencyChecker.ts | 578 ---------------------- src/HybridExportMode.ts | 776 ------------------------------ src/PluginSpecificStyleHandler.ts | 671 -------------------------- src/PopularThemeSupport.ts | 733 ---------------------------- src/ThemeManager.ts | 585 ---------------------- src/index.ts | 43 -- src/template-manager.ts | 752 ----------------------------- src/template-substitution.ts | 243 ---------- src/template-validator.ts | 463 ------------------ 11 files changed, 5974 deletions(-) delete mode 100644 src/CSSExtractor.ts delete mode 100644 src/CSSToTypstMapper.ts delete mode 100644 src/DependencyChecker.ts delete mode 100644 src/HybridExportMode.ts delete mode 100644 src/PluginSpecificStyleHandler.ts delete mode 100644 src/PopularThemeSupport.ts delete mode 100644 src/ThemeManager.ts delete mode 100644 src/index.ts delete mode 100644 src/template-manager.ts delete mode 100644 src/template-substitution.ts delete mode 100644 src/template-validator.ts diff --git a/src/CSSExtractor.ts b/src/CSSExtractor.ts deleted file mode 100644 index fe3974b..0000000 --- a/src/CSSExtractor.ts +++ /dev/null @@ -1,393 +0,0 @@ -/** - * CSS Extraction and Style Preservation System - * Captures Obsidian theme styles and maps them to equivalent Typst styling - */ - -export interface ExtractedStyle { - selector: string; - property: string; - value: string; - computedValue?: string; - priority?: string; -} - -export interface ThemeInfo { - name: string; - isDark: boolean; - isLight: boolean; - customVariables: Record; -} - -export interface CSSExtractionOptions { - includeInlineStyles?: boolean; - includeComputedStyles?: boolean; - filterSelectors?: string[]; - excludeSelectors?: string[]; - captureCustomProperties?: boolean; -} - -/** - * Core CSS extraction class that captures computed styles from Obsidian's DOM - */ -export class CSSExtractor { - private app: any; // Obsidian App interface - private extractedStyles: Map = new Map(); - private themeVariables: Map = new Map(); - private currentTheme: ThemeInfo | null = null; - - constructor(app: any) { - this.app = app; - } - - /** - * Extract styles from the current document - */ - public async extractStyles(options: CSSExtractionOptions = {}): Promise { - const styles: ExtractedStyle[] = []; - - // Clear previous extraction - this.extractedStyles.clear(); - this.themeVariables.clear(); - - // Detect current theme - this.currentTheme = this.detectCurrentTheme(); - - // Extract CSS custom properties (theme variables) - if (options.captureCustomProperties !== false) { - await this.extractCSSCustomProperties(); - } - - // Extract styles from stylesheets - await this.extractFromStylesheets(options); - - // Extract computed styles from key elements - if (options.includeComputedStyles) { - await this.extractComputedStyles(options); - } - - // Convert map to array - for (const [selector, selectorStyles] of this.extractedStyles) { - styles.push(...selectorStyles); - } - - return styles; - } - - /** - * Detect the current Obsidian theme - */ - private detectCurrentTheme(): ThemeInfo { - const bodyEl = document.body; - const isDark = bodyEl.classList.contains('theme-dark'); - const isLight = bodyEl.classList.contains('theme-light'); - - // Try to get theme name from manifest or CSS - let themeName = 'default'; - - // Check for popular theme indicators - if (bodyEl.classList.contains('minimal-theme')) { - themeName = 'minimal'; - } else if (bodyEl.classList.contains('blue-topaz-theme')) { - themeName = 'blue-topaz'; - } else if (bodyEl.querySelector('[data-theme]')) { - themeName = bodyEl.querySelector('[data-theme]')?.getAttribute('data-theme') || 'default'; - } - - return { - name: themeName, - isDark, - isLight, - customVariables: {} - }; - } - - /** - * Extract CSS custom properties (--variables) from the document - */ - private async extractCSSCustomProperties(): Promise { - const rootElement = document.documentElement; - const computedStyle = getComputedStyle(rootElement); - - // Extract custom properties from :root - const allProperties = Array.from(computedStyle); - const customProperties = allProperties.filter(prop => prop.startsWith('--')); - - for (const property of customProperties) { - const value = computedStyle.getPropertyValue(property).trim(); - if (value) { - this.themeVariables.set(property, value); - } - } - - // Also check body element for theme-specific variables - const bodyComputedStyle = getComputedStyle(document.body); - const bodyProperties = Array.from(bodyComputedStyle); - const bodyCustomProperties = bodyProperties.filter(prop => prop.startsWith('--')); - - for (const property of bodyCustomProperties) { - const value = bodyComputedStyle.getPropertyValue(property).trim(); - if (value) { - this.themeVariables.set(property, value); - } - } - } - - /** - * Extract styles from document stylesheets - */ - private async extractFromStylesheets(options: CSSExtractionOptions): Promise { - const stylesheets = Array.from(document.styleSheets); - - for (const stylesheet of stylesheets) { - try { - // Skip cross-origin stylesheets unless we can access them - if (!this.canAccessStylesheet(stylesheet)) { - continue; - } - - const rules = Array.from(stylesheet.cssRules || []); - await this.processRules(rules, options); - - } catch (error) { - console.warn('Could not access stylesheet:', stylesheet.href, error); - } - } - } - - /** - * Check if we can access a stylesheet - */ - private canAccessStylesheet(stylesheet: CSSStyleSheet): boolean { - try { - // Try to access the cssRules property - const _ = stylesheet.cssRules; - return true; - } catch (error) { - return false; - } - } - - /** - * Process CSS rules recursively - */ - private async processRules(rules: CSSRule[], options: CSSExtractionOptions): Promise { - for (const rule of rules) { - if (rule instanceof CSSStyleRule) { - await this.processStyleRule(rule, options); - } else if (rule instanceof CSSMediaRule) { - // Process rules inside media queries - const mediaRules = Array.from(rule.cssRules); - await this.processRules(mediaRules, options); - } else if (rule instanceof CSSSupportsRule) { - // Process rules inside @supports - const supportsRules = Array.from(rule.cssRules); - await this.processRules(supportsRules, options); - } - } - } - - /** - * Process individual style rule - */ - private async processStyleRule(rule: CSSStyleRule, options: CSSExtractionOptions): Promise { - const selector = rule.selectorText; - - // Apply selector filters - if (options.filterSelectors?.length && - !options.filterSelectors.some(filter => selector.includes(filter))) { - return; - } - - if (options.excludeSelectors?.length && - options.excludeSelectors.some(exclude => selector.includes(exclude))) { - return; - } - - // Extract styles for this selector - const styles: ExtractedStyle[] = []; - const ruleStyle = rule.style; - - for (let i = 0; i < ruleStyle.length; i++) { - const property = ruleStyle[i]; - const value = ruleStyle.getPropertyValue(property); - const priority = ruleStyle.getPropertyPriority(property); - - styles.push({ - selector, - property, - value, - priority - }); - } - - // Store styles - if (!this.extractedStyles.has(selector)) { - this.extractedStyles.set(selector, []); - } - this.extractedStyles.get(selector)!.push(...styles); - } - - /** - * Extract computed styles from key DOM elements - */ - private async extractComputedStyles(options: CSSExtractionOptions): Promise { - // Define key selectors to extract computed styles from - const keySelectors = [ - '.markdown-preview-view', - '.markdown-source-view', - '.cm-editor', - 'body', - '.workspace', - '.view-header', - 'h1, h2, h3, h4, h5, h6', - 'p', - 'a', - 'strong', - 'em', - 'code', - '.callout' - ]; - - for (const selector of keySelectors) { - const elements = document.querySelectorAll(selector); - - for (const element of Array.from(elements).slice(0, 5)) { // Limit to first 5 matches - const computedStyle = getComputedStyle(element); - - // Extract key properties - const keyProperties = [ - 'color', 'background-color', 'font-family', 'font-size', - 'font-weight', 'font-style', 'text-decoration', 'line-height', - 'margin', 'padding', 'border', 'border-radius' - ]; - - for (const property of keyProperties) { - const value = computedStyle.getPropertyValue(property); - if (value && value !== 'initial' && value !== 'inherit') { - const extractedStyle: ExtractedStyle = { - selector: this.generateSelectorForElement(element), - property, - value, - computedValue: value - }; - - if (!this.extractedStyles.has(extractedStyle.selector)) { - this.extractedStyles.set(extractedStyle.selector, []); - } - this.extractedStyles.get(extractedStyle.selector)!.push(extractedStyle); - } - } - } - } - } - - /** - * Generate a CSS selector for a DOM element - */ - private generateSelectorForElement(element: Element): string { - if (element.id) { - return `#${element.id}`; - } - - if (element.classList.length > 0) { - return `.${Array.from(element.classList).join('.')}`; - } - - return element.tagName.toLowerCase(); - } - - /** - * Get extracted theme variables - */ - public getThemeVariables(): Map { - return this.themeVariables; - } - - /** - * Get current theme information - */ - public getCurrentTheme(): ThemeInfo | null { - return this.currentTheme; - } - - /** - * Get styles by selector - */ - public getStylesBySelector(selector: string): ExtractedStyle[] { - return this.extractedStyles.get(selector) || []; - } - - /** - * Get all extracted styles - */ - public getAllStyles(): Map { - return this.extractedStyles; - } - - /** - * Listen for theme changes - */ - public registerThemeChangeListener(callback: (themeInfo: ThemeInfo) => void): void { - this.app.workspace.on('css-change', () => { - const newTheme = this.detectCurrentTheme(); - if (newTheme.name !== this.currentTheme?.name || - newTheme.isDark !== this.currentTheme?.isDark) { - this.currentTheme = newTheme; - callback(newTheme); - } - }); - } - - /** - * Get relevant styles for specific content types - */ - public getRelevantStyles(contentType: 'text' | 'heading' | 'link' | 'code' | 'callout'): ExtractedStyle[] { - const relevantSelectors: Record = { - text: ['body', 'p', '.markdown-preview-view', '.cm-line'], - heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', '.cm-header'], - link: ['a', '.cm-link'], - code: ['code', '.cm-inline-code', 'pre', '.cm-line'], - callout: ['.callout', '.callout-title', '.callout-content'] - }; - - const selectors = relevantSelectors[contentType] || []; - const styles: ExtractedStyle[] = []; - - for (const selector of selectors) { - // Find matching extracted styles - for (const [extractedSelector, extractedStyles] of this.extractedStyles) { - if (this.selectorMatches(extractedSelector, selector)) { - styles.push(...extractedStyles); - } - } - } - - return styles; - } - - /** - * Check if selectors match (simple matching) - */ - private selectorMatches(extracted: string, target: string): boolean { - return extracted.includes(target) || target.includes(extracted); - } -} - -// Re-export types from other modules to provide a central import location -export type { TypstStyleRule, MappingOptions } from './CSSToTypstMapper'; -export type { ThemeVariableMapping, ThemeProfile, ThemeDetectionResult } from './ThemeManager'; -export type { EnhancedThemeProfile, ThemeTestResult } from './PopularThemeSupport'; -export type { PluginStyleProfile, PluginDetectionResult } from './PluginSpecificStyleHandler'; -export type { HybridExportOptions, HybridStyleResult, StyleConflict } from './HybridExportMode'; - -// Additional types needed by the system -export type ColorFormat = 'hex' | 'rgb' | 'hsl' | 'named'; - -export interface ThemeCustomization { - colorOverrides?: Record; - fontOverrides?: Record; - spacingOverrides?: Record; - customCSS?: string; -} - -export type ConflictResolution = 'user' | 'theme' | 'merge' | 'skip'; \ No newline at end of file diff --git a/src/CSSToTypstMapper.ts b/src/CSSToTypstMapper.ts deleted file mode 100644 index ad44778..0000000 --- a/src/CSSToTypstMapper.ts +++ /dev/null @@ -1,737 +0,0 @@ -/** - * CSS to Typst Property Mapping System - * Converts CSS properties to equivalent Typst styling commands - */ - -import { ExtractedStyle } from './CSSExtractor'; - -export interface TypstStyleRule { - type: 'set' | 'show' | 'function'; - target: string; // e.g., 'text', 'heading', 'par' - properties: Record; - content?: string; - condition?: string; -} - -export interface ColorRgb { - r: number; - g: number; - b: number; - a?: number; -} - -export interface MappingOptions { - preserveFallbacks?: boolean; - useSetRules?: boolean; - useShowRules?: boolean; - simplifyColors?: boolean; - optimizeForPrint?: boolean; -} - -/** - * Maps CSS properties to equivalent Typst styling commands - */ -export class CSSToTypstMapper { - private colorCache = new Map(); - - constructor() {} - - /** - * Map extracted styles to Typst style rules - */ - public mapToTypst(styles: ExtractedStyle[], options: MappingOptions = {}): TypstStyleRule[] { - const rules: TypstStyleRule[] = []; - const processedSelectors = new Set(); - - // Group styles by selector - const groupedStyles = this.groupStylesBySelector(styles); - - for (const [selector, selectorStyles] of groupedStyles) { - if (processedSelectors.has(selector)) continue; - processedSelectors.add(selector); - - // Determine the target element type - const target = this.getTypstTarget(selector); - if (!target) continue; - - // Convert CSS properties to Typst properties - const typstProperties: Record = {}; - let hasValidProperties = false; - - for (const style of selectorStyles) { - const mappedProperty = this.mapCSSProperty(style.property, style.value, options); - if (mappedProperty) { - Object.assign(typstProperties, mappedProperty); - hasValidProperties = true; - } - } - - if (hasValidProperties) { - const rule: TypstStyleRule = { - type: options.useShowRules ? 'show' : 'set', - target, - properties: typstProperties - }; - - // Add conditions for show rules - if (options.useShowRules) { - rule.condition = this.generateShowCondition(selector); - } - - rules.push(rule); - } - } - - return rules; - } - - /** - * Group styles by selector - */ - private groupStylesBySelector(styles: ExtractedStyle[]): Map { - const grouped = new Map(); - - for (const style of styles) { - if (!grouped.has(style.selector)) { - grouped.set(style.selector, []); - } - grouped.get(style.selector)!.push(style); - } - - return grouped; - } - - /** - * Determine Typst target element from CSS selector - */ - private getTypstTarget(selector: string): string | null { - // Heading selectors - if (selector.match(/h[1-6]/) || selector.includes('heading') || selector.includes('cm-header')) { - return 'heading'; - } - - // Text content selectors - if (selector.includes('body') || selector.includes('markdown-preview') || selector.includes('cm-line')) { - return 'text'; - } - - // Paragraph selectors - if (selector.includes('p') || selector.includes('par')) { - return 'par'; - } - - // Link selectors - if (selector.includes('a') || selector.includes('link')) { - return 'link'; - } - - // Code selectors - if (selector.includes('code') || selector.includes('cm-inline-code') || selector.includes('pre')) { - return 'raw'; - } - - // List selectors - if (selector.includes('ul') || selector.includes('ol') || selector.includes('li')) { - return 'list'; - } - - // Block elements - if (selector.includes('div') || selector.includes('block') || selector.includes('callout')) { - return 'block'; - } - - // Default to text for unknown selectors - return 'text'; - } - - /** - * Map individual CSS property to Typst equivalent - */ - public mapCSSProperty(property: string, value: string, options: MappingOptions): Record | null { - const result: Record = {}; - - switch (property) { - case 'color': - const textColor = this.convertColor(value, options.simplifyColors); - if (textColor) { - result.fill = textColor; - } - break; - - case 'background-color': - case 'background': - const bgColor = this.convertColor(value, options.simplifyColors); - if (bgColor && bgColor !== 'transparent' && bgColor !== 'none') { - // Background color typically maps to fill in box or block contexts - result.fill = bgColor; - } - break; - - case 'font-family': - const fontFamily = this.convertFontFamily(value); - if (fontFamily) { - result.font = fontFamily; - } - break; - - case 'font-size': - const fontSize = this.convertSize(value); - if (fontSize) { - result.size = fontSize; - } - break; - - case 'font-weight': - const weight = this.convertFontWeight(value); - if (weight) { - result.weight = weight; - } - break; - - case 'font-style': - const style = this.convertFontStyle(value); - if (style) { - result.style = style; - } - break; - - case 'text-align': - const align = this.convertTextAlign(value); - if (align) { - result.align = align; - } - break; - - case 'line-height': - const leading = this.convertLineHeight(value); - if (leading) { - result.leading = leading; - } - break; - - case 'letter-spacing': - const spacing = this.convertLetterSpacing(value); - if (spacing) { - result.spacing = spacing; - } - break; - - case 'text-decoration': - const decoration = this.convertTextDecoration(value); - if (decoration) { - Object.assign(result, decoration); - } - break; - - case 'border': - case 'border-color': - case 'border-width': - case 'border-style': - const stroke = this.convertBorder(property, value); - if (stroke) { - result.stroke = stroke; - } - break; - - case 'border-radius': - const radius = this.convertBorderRadius(value); - if (radius) { - result.radius = radius; - } - break; - - case 'margin': - case 'margin-top': - case 'margin-bottom': - case 'margin-left': - case 'margin-right': - const margin = this.convertMargin(property, value); - if (margin) { - Object.assign(result, margin); - } - break; - - case 'padding': - case 'padding-top': - case 'padding-bottom': - case 'padding-left': - case 'padding-right': - const inset = this.convertPadding(property, value); - if (inset) { - result.inset = inset; - } - break; - - default: - // Return null for unsupported properties - return null; - } - - return Object.keys(result).length > 0 ? result : null; - } - - /** - * Convert CSS color to Typst color - */ - private convertColor(cssColor: string, simplify: boolean = false): string | null { - if (!cssColor || cssColor === 'transparent' || cssColor === 'inherit' || cssColor === 'initial') { - return null; - } - - // Check cache first - if (this.colorCache.has(cssColor)) { - const rgb = this.colorCache.get(cssColor)!; - return this.formatTypstColor(rgb, simplify); - } - - let rgb: ColorRgb | null = null; - - // Parse different color formats - if (cssColor.startsWith('#')) { - rgb = this.parseHexColor(cssColor); - } else if (cssColor.startsWith('rgb')) { - rgb = this.parseRgbColor(cssColor); - } else if (cssColor.startsWith('hsl')) { - rgb = this.parseHslColor(cssColor); - } else { - // Try to parse named colors - rgb = this.parseNamedColor(cssColor); - } - - if (rgb) { - this.colorCache.set(cssColor, rgb); - return this.formatTypstColor(rgb, simplify); - } - - return null; - } - - /** - * Parse hex color - */ - private parseHexColor(hex: string): ColorRgb | null { - const match = hex.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); - if (!match) { - // Try short format - const shortMatch = hex.match(/^#([a-f\d])([a-f\d])([a-f\d])$/i); - if (shortMatch) { - return { - r: parseInt(shortMatch[1] + shortMatch[1], 16), - g: parseInt(shortMatch[2] + shortMatch[2], 16), - b: parseInt(shortMatch[3] + shortMatch[3], 16) - }; - } - return null; - } - - return { - r: parseInt(match[1], 16), - g: parseInt(match[2], 16), - b: parseInt(match[3], 16) - }; - } - - /** - * Parse RGB/RGBA color - */ - private parseRgbColor(rgb: string): ColorRgb | null { - const match = rgb.match(/rgba?\(([^)]+)\)/); - if (!match) return null; - - const values = match[1].split(',').map(v => parseFloat(v.trim())); - if (values.length < 3) return null; - - return { - r: Math.round(values[0]), - g: Math.round(values[1]), - b: Math.round(values[2]), - a: values[3] !== undefined ? values[3] : undefined - }; - } - - /** - * Parse HSL color (basic implementation) - */ - private parseHslColor(hsl: string): ColorRgb | null { - const match = hsl.match(/hsla?\(([^)]+)\)/); - if (!match) return null; - - const values = match[1].split(',').map(v => parseFloat(v.trim())); - if (values.length < 3) return null; - - // Convert HSL to RGB - const h = values[0] / 360; - const s = values[1] / 100; - const l = values[2] / 100; - - let r, g, b; - - if (s === 0) { - r = g = b = l; // achromatic - } else { - const hue2rgb = (p: number, q: number, t: number) => { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1/6) return p + (q - p) * 6 * t; - if (t < 1/2) return q; - if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; - }; - - const q = l < 0.5 ? l * (1 + s) : l + s - l * s; - const p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); - } - - return { - r: Math.round(r * 255), - g: Math.round(g * 255), - b: Math.round(b * 255), - a: values[3] !== undefined ? values[3] : undefined - }; - } - - /** - * Parse named colors (basic set) - */ - private parseNamedColor(color: string): ColorRgb | null { - const namedColors: Record = { - 'black': { r: 0, g: 0, b: 0 }, - 'white': { r: 255, g: 255, b: 255 }, - 'red': { r: 255, g: 0, b: 0 }, - 'green': { r: 0, g: 128, b: 0 }, - 'blue': { r: 0, g: 0, b: 255 }, - 'yellow': { r: 255, g: 255, b: 0 }, - 'cyan': { r: 0, g: 255, b: 255 }, - 'magenta': { r: 255, g: 0, b: 255 }, - 'gray': { r: 128, g: 128, b: 128 }, - 'grey': { r: 128, g: 128, b: 128 }, - 'silver': { r: 192, g: 192, b: 192 }, - 'maroon': { r: 128, g: 0, b: 0 }, - 'olive': { r: 128, g: 128, b: 0 }, - 'lime': { r: 0, g: 255, b: 0 }, - 'aqua': { r: 0, g: 255, b: 255 }, - 'teal': { r: 0, g: 128, b: 128 }, - 'navy': { r: 0, g: 0, b: 128 }, - 'fuchsia': { r: 255, g: 0, b: 255 }, - 'purple': { r: 128, g: 0, b: 128 } - }; - - return namedColors[color.toLowerCase()] || null; - } - - /** - * Format color for Typst - */ - private formatTypstColor(rgb: ColorRgb, simplify: boolean): string { - if (simplify) { - // Use named colors when possible for readability - if (rgb.r === 0 && rgb.g === 0 && rgb.b === 0) return 'black'; - if (rgb.r === 255 && rgb.g === 255 && rgb.b === 255) return 'white'; - if (rgb.r === 255 && rgb.g === 0 && rgb.b === 0) return 'red'; - if (rgb.r === 0 && rgb.g === 128 && rgb.b === 0) return 'green'; - if (rgb.r === 0 && rgb.g === 0 && rgb.b === 255) return 'blue'; - } - - // Use rgb() function for Typst - if (rgb.a !== undefined && rgb.a < 1) { - return `rgb(${rgb.r}, ${rgb.g}, ${rgb.b}, ${Math.round(rgb.a * 100)}%)`; - } else { - return `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`; - } - } - - /** - * Convert CSS font-family to Typst font - */ - private convertFontFamily(fontFamily: string): string | null { - if (!fontFamily) return null; - - // Clean up font family string - const cleaned = fontFamily - .replace(/['"]/g, '') - .split(',')[0] // Take first font - .trim(); - - // Map common system fonts - const fontMap: Record = { - 'serif': '"Linux Libertine"', - 'sans-serif': '"Lato"', - 'monospace': '"Fira Mono"', - 'system-ui': '"Inter"', - '-apple-system': '"Inter"', - 'BlinkMacSystemFont': '"Inter"', - 'Segoe UI': '"Inter"', - 'Roboto': '"Roboto"', - 'Helvetica Neue': '"Helvetica Neue"', - 'Arial': '"Arial"', - 'Times New Roman': '"Times New Roman"', - 'Georgia': '"Georgia"', - 'Verdana': '"Verdana"', - 'Courier New': '"Courier New"', - }; - - return fontMap[cleaned] || `"${cleaned}"`; - } - - /** - * Convert CSS size to Typst size - */ - private convertSize(size: string): string | null { - if (!size || size === 'inherit' || size === 'initial') return null; - - // Handle pixel values - if (size.endsWith('px')) { - const px = parseFloat(size); - const pt = px * 0.75; // Convert px to pt - return `${Math.round(pt * 100) / 100}pt`; - } - - // Handle point values - if (size.endsWith('pt')) { - return size; - } - - // Handle em values - if (size.endsWith('em')) { - const em = parseFloat(size); - const pt = em * 12; // Assume base of 12pt - return `${Math.round(pt * 100) / 100}pt`; - } - - // Handle rem values - if (size.endsWith('rem')) { - const rem = parseFloat(size); - const pt = rem * 12; // Assume root font size of 12pt - return `${Math.round(pt * 100) / 100}pt`; - } - - // Handle percentage - if (size.endsWith('%')) { - const percent = parseFloat(size) / 100; - return `${percent}em`; - } - - return null; - } - - /** - * Convert font weight - */ - private convertFontWeight(weight: string): string | null { - if (!weight || weight === 'normal' || weight === 'inherit') return null; - - const weightMap: Record = { - 'bold': '"bold"', - 'bolder': '"bold"', - 'lighter': '"regular"', - '100': '"thin"', - '200': '"extralight"', - '300': '"light"', - '400': '"regular"', - '500': '"medium"', - '600': '"semibold"', - '700': '"bold"', - '800': '"extrabold"', - '900': '"black"' - }; - - return weightMap[weight] || null; - } - - /** - * Convert font style - */ - private convertFontStyle(style: string): string | null { - if (!style || style === 'normal' || style === 'inherit') return null; - - const styleMap: Record = { - 'italic': '"italic"', - 'oblique': '"oblique"' - }; - - return styleMap[style] || null; - } - - /** - * Convert text alignment - */ - private convertTextAlign(align: string): string | null { - if (!align || align === 'inherit') return null; - - const alignMap: Record = { - 'left': 'start', - 'right': 'end', - 'center': 'center', - 'justify': 'justify' - }; - - return alignMap[align] || null; - } - - /** - * Convert line height to leading - */ - private convertLineHeight(lineHeight: string): string | null { - if (!lineHeight || lineHeight === 'normal' || lineHeight === 'inherit') return null; - - // Handle unitless values (relative to font size) - if (/^[\d.]+$/.test(lineHeight)) { - const multiplier = parseFloat(lineHeight); - return `${multiplier}em`; - } - - // Handle length values - const size = this.convertSize(lineHeight); - return size; - } - - /** - * Convert letter spacing - */ - private convertLetterSpacing(spacing: string): string | null { - if (!spacing || spacing === 'normal' || spacing === 'inherit') return null; - - return this.convertSize(spacing); - } - - /** - * Convert text decoration - */ - private convertTextDecoration(decoration: string): Record | null { - if (!decoration || decoration === 'none' || decoration === 'inherit') return null; - - const result: Record = {}; - - if (decoration.includes('underline')) { - result.underline = 'true'; - } - if (decoration.includes('overline')) { - result.overline = 'true'; - } - if (decoration.includes('line-through')) { - result.strike = 'true'; - } - - return Object.keys(result).length > 0 ? result : null; - } - - /** - * Convert border properties - */ - private convertBorder(property: string, value: string): string | null { - if (!value || value === 'none' || value === 'inherit') return null; - - // Parse border shorthand or specific property - if (property === 'border') { - // Parse shorthand: "1px solid red" - const parts = value.split(/\s+/); - const width = parts.find(p => p.match(/[\d.]+(px|pt|em)/)); - const color = parts.find(p => this.convertColor(p, true)); - - if (width) { - const typstWidth = this.convertSize(width); - const typstColor = color ? this.convertColor(color, true) : null; - - if (typstColor) { - return `${typstWidth} + ${typstColor}`; - } else { - return typstWidth; - } - } - } - - return null; - } - - /** - * Convert border radius - */ - private convertBorderRadius(radius: string): string | null { - if (!radius || radius === '0' || radius === 'inherit') return null; - - return this.convertSize(radius); - } - - /** - * Convert margin properties - */ - private convertMargin(property: string, value: string): Record | null { - if (!value || value === '0' || value === 'inherit') return null; - - // For block elements, margins translate to above/below spacing - const result: Record = {}; - - if (property === 'margin-top') { - const size = this.convertSize(value); - if (size) result.above = size; - } else if (property === 'margin-bottom') { - const size = this.convertSize(value); - if (size) result.below = size; - } - - return Object.keys(result).length > 0 ? result : null; - } - - /** - * Convert padding to inset - */ - private convertPadding(property: string, value: string): string | null { - if (!value || value === '0' || value === 'inherit') return null; - - if (property === 'padding') { - // Handle shorthand - const sizes = value.split(/\s+/).map(s => this.convertSize(s)).filter(Boolean); - if (sizes.length === 1) { - return sizes[0]!; - } else if (sizes.length === 2) { - return `(y: ${sizes[0]}, x: ${sizes[1]})`; - } else if (sizes.length >= 4) { - return `(top: ${sizes[0]}, right: ${sizes[1]}, bottom: ${sizes[2]}, left: ${sizes[3]})`; - } - } - - return this.convertSize(value); - } - - /** - * Generate show condition for selector - */ - private generateShowCondition(selector: string): string | undefined { - if (selector.includes('h1')) return 'heading.where(level: 1)'; - if (selector.includes('h2')) return 'heading.where(level: 2)'; - if (selector.includes('h3')) return 'heading.where(level: 3)'; - if (selector.includes('h4')) return 'heading.where(level: 4)'; - if (selector.includes('h5')) return 'heading.where(level: 5)'; - if (selector.includes('h6')) return 'heading.where(level: 6)'; - - return undefined; - } - - /** - * Generate Typst code from style rules - */ - public generateTypstCode(rules: TypstStyleRule[]): string { - const lines: string[] = []; - - for (const rule of rules) { - const properties = Object.entries(rule.properties) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - - if (rule.type === 'set') { - if (rule.condition) { - lines.push(`#show ${rule.condition}: set ${rule.target}(${properties})`); - } else { - lines.push(`#set ${rule.target}(${properties})`); - } - } else if (rule.type === 'show' && rule.condition) { - lines.push(`#show ${rule.condition}: it => [${rule.content || '#it'}]`); - } - } - - return lines.join('\n'); - } -} \ No newline at end of file diff --git a/src/DependencyChecker.ts b/src/DependencyChecker.ts deleted file mode 100644 index 9fca6c7..0000000 --- a/src/DependencyChecker.ts +++ /dev/null @@ -1,578 +0,0 @@ -import { spawn, ChildProcess } from 'child_process'; -import { access } from 'fs/promises'; -import { join, resolve, dirname } from 'path'; -import { Platform } from 'obsidian'; - -/** - * Result of a dependency check operation - */ -interface DependencyCheckResult { - /** Whether the dependency was found and is valid */ - isAvailable: boolean; - /** Path to the executable (if found) */ - executablePath?: string; - /** Detected version (if available) */ - version?: string; - /** Error message if dependency is not available */ - error?: string; - /** Warning message for issues that don't prevent usage */ - warning?: string; -} - -/** - * Installation guidance for specific platforms and tools - */ -interface InstallationGuide { - /** Tool name */ - tool: 'pandoc' | 'typst' | 'imagemagick'; - /** Installation instructions by platform */ - instructions: { - windows: { - description: string; - links: string[]; - commands?: string[]; - }; - mac: { - description: string; - links: string[]; - commands?: string[]; - }; - linux: { - description: string; - links: string[]; - commands?: string[]; - }; - }; - /** Troubleshooting tips */ - troubleshooting: string[]; -} - -/** - * Configuration for dependency checking - */ -interface DependencyConfig { - /** Custom path to executable (empty string means use PATH) */ - customPath: string; - /** Minimum required version */ - minVersion: string; - /** Timeout for version checks in milliseconds */ - timeout: number; - /** Additional paths to search in system PATH */ - additionalPaths?: string[]; -} - -/** - * Checks for external tool dependencies (Pandoc and Typst) with cross-platform support - */ -export class DependencyChecker { - private static readonly DEFAULT_TIMEOUT = 5000; // 5 seconds - private static readonly PANDOC_MIN_VERSION = '3.0.0'; - private static readonly TYPST_MIN_VERSION = '0.11.0'; - private static readonly IMAGEMAGICK_MIN_VERSION = '7.0.0'; - - /** - * Check if Pandoc is available and meets version requirements - */ - async checkPandoc(config: Partial = {}): Promise { - const fullConfig: DependencyConfig = { - customPath: config.customPath || '', - minVersion: config.minVersion || DependencyChecker.PANDOC_MIN_VERSION, - timeout: config.timeout || DependencyChecker.DEFAULT_TIMEOUT - }; - - return this.checkDependency('pandoc', fullConfig); - } - - /** - * Check if Typst is available and meets version requirements - */ - async checkTypst(config: Partial = {}): Promise { - const fullConfig: DependencyConfig = { - customPath: config.customPath || '', - minVersion: config.minVersion || DependencyChecker.TYPST_MIN_VERSION, - timeout: config.timeout || DependencyChecker.DEFAULT_TIMEOUT - }; - - return this.checkDependency('typst', fullConfig); - } - - /** - * Check if ImageMagick is available and meets version requirements - */ - async checkImageMagick(config: Partial = {}): Promise { - const fullConfig: DependencyConfig = { - customPath: config.customPath || '', - minVersion: config.minVersion || DependencyChecker.IMAGEMAGICK_MIN_VERSION, - timeout: config.timeout || DependencyChecker.DEFAULT_TIMEOUT - }; - - return this.checkDependency('convert', fullConfig); - } - - /** - * Check all dependencies (Pandoc, Typst, and ImageMagick) - */ - async checkAllDependencies( - pandocConfig: Partial = {}, - typstConfig: Partial = {}, - imagemagickConfig: Partial = {} - ): Promise<{ - pandoc: DependencyCheckResult; - typst: DependencyCheckResult; - imagemagick: DependencyCheckResult; - allAvailable: boolean; - }> { - const [pandoc, typst, imagemagick] = await Promise.all([ - this.checkPandoc(pandocConfig), - this.checkTypst(typstConfig), - this.checkImageMagick(imagemagickConfig) - ]); - - return { - pandoc, - typst, - imagemagick, - allAvailable: pandoc.isAvailable && typst.isAvailable && imagemagick.isAvailable - }; - } - - /** - * Core dependency checking logic - */ - private async checkDependency(toolName: 'pandoc' | 'typst' | 'convert', config: DependencyConfig): Promise { - try { - // Step 1: Find the executable - const executablePath = await this.findExecutable(toolName, config.customPath, config.additionalPaths); - if (!executablePath) { - return { - isAvailable: false, - error: `${toolName} executable not found. ${this.getInstallationMessage(toolName)}` - }; - } - - // Step 2: Check version - const versionResult = await this.checkVersion(executablePath, config.minVersion, config.timeout); - if (!versionResult.isValid) { - return { - isAvailable: false, - executablePath, - version: versionResult.version, - error: versionResult.error || `${toolName} version ${versionResult.version} does not meet minimum requirement ${config.minVersion}` - }; - } - - // Step 3: Success - return { - isAvailable: true, - executablePath, - version: versionResult.version, - warning: versionResult.warning - }; - - } catch (error) { - return { - isAvailable: false, - error: `Error checking ${toolName}: ${error instanceof Error ? error.message : String(error)}` - }; - } - } - - /** - * Find executable path using custom path or system PATH - */ - private async findExecutable(toolName: string, customPath: string, additionalPaths: string[] = []): Promise { - // If custom path is provided, validate it - if (customPath && customPath.trim()) { - const resolvedPath = resolve(customPath.trim()); - if (await this.isExecutableFile(resolvedPath)) { - return resolvedPath; - } - return null; - } - - // Search in system PATH with additional paths - return this.findInPath(toolName, additionalPaths); - } - - /** - * Search for executable in system PATH - */ - private async findInPath(toolName: string, additionalPaths: string[] = []): Promise { - const pathEnv = process.env.PATH || ''; - const pathSeparator = Platform.isWin ? ';' : ':'; - - // Combine additional paths with system PATH (additional paths take precedence) - const allPaths = [...additionalPaths, ...pathEnv.split(pathSeparator)]; - - // Add common executable extensions on Windows - const extensions = Platform.isWin ? ['.exe', '.cmd', '.bat'] : ['']; - - for (const dir of allPaths) { - if (!dir.trim()) continue; - - for (const ext of extensions) { - const fullPath = join(dir, toolName + ext); - if (await this.isExecutableFile(fullPath)) { - return fullPath; - } - } - } - - return null; - } - - /** - * Check if a file exists and is accessible - */ - private async isExecutableFile(filePath: string): Promise { - try { - // Just check if file exists and is accessible - // In Obsidian environment, we can't reliably check execute permissions - await access(filePath); - return true; - } catch { - return false; - } - } - - /** - * Check version of an executable and validate against minimum requirement - */ - private async checkVersion(executablePath: string, minVersion: string, timeout: number): Promise<{ - isValid: boolean; - version?: string; - error?: string; - warning?: string; - }> { - try { - const version = await this.getVersion(executablePath, timeout); - if (!version) { - return { - isValid: false, - error: 'Could not determine version' - }; - } - - const isValid = this.compareVersions(version, minVersion) >= 0; - return { - isValid, - version, - error: isValid ? undefined : `Version ${version} is below required ${minVersion}`, - warning: isValid ? undefined : this.getUpgradeMessage(executablePath, version, minVersion) - }; - - } catch (error) { - return { - isValid: false, - error: error instanceof Error ? error.message : String(error) - }; - } - } - - /** - * Get version string from executable - */ - private async getVersion(executablePath: string, timeout: number): Promise { - return new Promise((resolve, reject) => { - const process = spawn(executablePath, ['--version'], { - stdio: ['ignore', 'pipe', 'pipe'] - }); - - let stdout = ''; - let stderr = ''; - - const timeoutHandle = setTimeout(() => { - process.kill(); - reject(new Error(`Version check timed out after ${timeout}ms`)); - }, timeout); - - process.stdout?.on('data', (data) => { - stdout += data.toString(); - }); - - process.stderr?.on('data', (data) => { - stderr += data.toString(); - }); - - process.on('close', (code) => { - clearTimeout(timeoutHandle); - - if (code !== 0) { - reject(new Error(`Process exited with code ${code}: ${stderr}`)); - return; - } - - const version = this.extractVersion(stdout); - resolve(version); - }); - - process.on('error', (error) => { - clearTimeout(timeoutHandle); - reject(error); - }); - }); - } - - /** - * Extract version number from version command output - */ - private extractVersion(output: string): string | null { - // Common patterns for version output - const patterns = [ - // ImageMagick pattern: "Version: ImageMagick 7.1.1-15" - /ImageMagick\s+(\d+\.\d+\.\d+(?:-\d+)?)/i, - // Standard version patterns - /version\s+(\d+\.\d+\.\d+)/i, - /v?(\d+\.\d+\.\d+)/, - /(\d+\.\d+\.\d+)/ - ]; - - for (const pattern of patterns) { - const match = output.match(pattern); - if (match) { - // For ImageMagick, strip the build number suffix if present - return match[1].replace(/-\d+$/, ''); - } - } - - return null; - } - - /** - * Compare two semantic version strings - * Returns: -1 if a < b, 0 if a == b, 1 if a > b - */ - private compareVersions(a: string, b: string): number { - const parseVersion = (version: string) => { - return version.split('.').map(num => parseInt(num, 10)); - }; - - const aParts = parseVersion(a); - const bParts = parseVersion(b); - const maxLength = Math.max(aParts.length, bParts.length); - - for (let i = 0; i < maxLength; i++) { - const aPart = aParts[i] || 0; - const bPart = bParts[i] || 0; - - if (aPart < bPart) return -1; - if (aPart > bPart) return 1; - } - - return 0; - } - - /** - * Get installation instructions for a tool - */ - getInstallationGuide(toolName: 'pandoc' | 'typst' | 'imagemagick'): InstallationGuide { - if (toolName === 'pandoc') { - return { - tool: 'pandoc', - instructions: { - windows: { - description: 'Install Pandoc using the Windows installer or package manager', - links: [ - 'https://pandoc.org/installing.html', - 'https://github.com/jgm/pandoc/releases' - ], - commands: [ - 'winget install --id JohnMacFarlane.Pandoc', - 'choco install pandoc' - ] - }, - mac: { - description: 'Install Pandoc using Homebrew or the macOS installer', - links: [ - 'https://pandoc.org/installing.html', - 'https://github.com/jgm/pandoc/releases' - ], - commands: [ - 'brew install pandoc', - 'sudo port install pandoc' - ] - }, - linux: { - description: 'Install Pandoc using your distribution\'s package manager', - links: [ - 'https://pandoc.org/installing.html', - 'https://github.com/jgm/pandoc/releases' - ], - commands: [ - 'sudo apt install pandoc # Ubuntu/Debian', - 'sudo dnf install pandoc # Fedora', - 'sudo pacman -S pandoc # Arch Linux' - ] - } - }, - troubleshooting: [ - 'Ensure Pandoc is in your system PATH', - 'Restart Obsidian after installation', - 'For manual installations, specify the full path in plugin settings', - 'Check that you have the latest version from the official website' - ] - }; - } else if (toolName === 'typst') { - return { - tool: 'typst', - instructions: { - windows: { - description: 'Install Typst using the Windows installer or package manager', - links: [ - 'https://github.com/typst/typst#installation', - 'https://github.com/typst/typst/releases' - ], - commands: [ - 'winget install --id Typst.Typst', - 'cargo install --locked typst-cli' - ] - }, - mac: { - description: 'Install Typst using Homebrew or Rust', - links: [ - 'https://github.com/typst/typst#installation', - 'https://github.com/typst/typst/releases' - ], - commands: [ - 'brew install typst', - 'cargo install --locked typst-cli' - ] - }, - linux: { - description: 'Install Typst using your package manager or Rust', - links: [ - 'https://github.com/typst/typst#installation', - 'https://github.com/typst/typst/releases' - ], - commands: [ - 'cargo install --locked typst-cli', - 'Download from releases page for your distribution' - ] - } - }, - troubleshooting: [ - 'Ensure Typst is in your system PATH', - 'Restart Obsidian after installation', - 'For manual installations, specify the full path in plugin settings', - 'Install Rust first if using cargo install method', - 'Check that you have version 0.11.0 or higher' - ] - }; - } else if (toolName === 'imagemagick') { - return { - tool: 'imagemagick', - instructions: { - windows: { - description: 'Install ImageMagick using the Windows installer or package manager', - links: [ - 'https://imagemagick.org/script/download.php#windows', - 'https://github.com/ImageMagick/ImageMagick/releases' - ], - commands: [ - 'winget install ImageMagick.ImageMagick', - 'choco install imagemagick' - ] - }, - mac: { - description: 'Install ImageMagick using Homebrew or MacPorts', - links: [ - 'https://imagemagick.org/script/download.php#macosx', - 'https://github.com/ImageMagick/ImageMagick/releases' - ], - commands: [ - 'brew install imagemagick', - 'sudo port install ImageMagick' - ] - }, - linux: { - description: 'Install ImageMagick using your distribution\'s package manager', - links: [ - 'https://imagemagick.org/script/download.php#unix', - 'https://github.com/ImageMagick/ImageMagick/releases' - ], - commands: [ - 'sudo apt install imagemagick # Ubuntu/Debian', - 'sudo dnf install ImageMagick # Fedora', - 'sudo pacman -S imagemagick # Arch Linux' - ] - } - }, - troubleshooting: [ - 'Ensure ImageMagick is in your system PATH', - 'Restart Obsidian after installation', - 'For manual installations, specify the full path in plugin settings', - 'Test with `convert --version` in terminal', - 'Check that you have version 7.0.0 or higher', - 'On macOS, you may need to update PATH to include /opt/homebrew/bin' - ] - }; - } else { - throw new Error(`Unknown tool: ${toolName}`); - } - } - - /** - * Get a brief installation message for error display - */ - private getInstallationMessage(toolName: 'pandoc' | 'typst' | 'convert'): string { - if (toolName === 'pandoc') { - return 'Install from https://pandoc.org/installing.html or specify custom path in settings.'; - } else if (toolName === 'typst') { - return 'Install from https://github.com/typst/typst#installation or specify custom path in settings.'; - } else if (toolName === 'convert') { - return 'Install ImageMagick from https://imagemagick.org/script/download.php or specify custom path in settings.'; - } else { - return 'Tool not found. Please install or specify custom path in settings.'; - } - } - - /** - * Get upgrade message for outdated versions - */ - private getUpgradeMessage(executablePath: string, currentVersion: string, requiredVersion: string): string { - return `Found ${executablePath} v${currentVersion}, but v${requiredVersion}+ is required. Please upgrade.`; - } - - /** - * Get current platform information - */ - getCurrentPlatform(): 'windows' | 'mac' | 'linux' { - if (Platform.isWin) return 'windows'; - if (Platform.isMacOS) return 'mac'; - return 'linux'; - } - - /** - * Format installation guide as user-friendly text - */ - formatInstallationGuide(guide: InstallationGuide): string { - const platform = this.getCurrentPlatform(); - const platformInstructions = guide.instructions[platform]; - - let text = `## Installing ${guide.tool.charAt(0).toUpperCase() + guide.tool.slice(1)}\n\n`; - text += `${platformInstructions.description}\n\n`; - - if (platformInstructions.commands && platformInstructions.commands.length > 0) { - text += '**Installation commands:**\n'; - platformInstructions.commands.forEach(cmd => { - text += `\`${cmd}\`\n`; - }); - text += '\n'; - } - - text += '**Useful links:**\n'; - platformInstructions.links.forEach(link => { - text += `- ${link}\n`; - }); - text += '\n'; - - if (guide.troubleshooting.length > 0) { - text += '**Troubleshooting:**\n'; - guide.troubleshooting.forEach(tip => { - text += `- ${tip}\n`; - }); - } - - return text; - } -} \ No newline at end of file diff --git a/src/HybridExportMode.ts b/src/HybridExportMode.ts deleted file mode 100644 index 4a90f9a..0000000 --- a/src/HybridExportMode.ts +++ /dev/null @@ -1,776 +0,0 @@ -/** - * Hybrid Export Mode Integration System - * Combines extracted CSS styles with Typst's typography system for style-preserving exports - */ - -import { CSSExtractor, ExtractedStyle } from './CSSExtractor'; -import { CSSToTypstMapper, TypstStyleRule } from './CSSToTypstMapper'; -import { ThemeManager, ThemeDetectionResult } from './ThemeManager'; -import { PopularThemeSupport, EnhancedThemeProfile } from './PopularThemeSupport'; -import { PluginSpecificStyleHandler, PluginDetectionResult } from './PluginSpecificStyleHandler'; - -export interface HybridExportOptions { - preserveThemeColors?: boolean; - preservePluginStyles?: boolean; - optimizeForReadability?: boolean; - useTypstDefaults?: boolean; - styleIntensity?: 'minimal' | 'moderate' | 'full'; - conflictResolution?: 'css-priority' | 'typst-priority' | 'balanced'; - includeCustomProperties?: boolean; - fontFallback?: boolean; -} - -export interface StyleConflict { - property: string; - cssValue: string; - typstDefault: string; - resolution: 'css' | 'typst' | 'hybrid'; - reason: string; -} - -export interface HybridStyleResult { - typstTemplate: string; - extractedStyles: ExtractedStyle[]; - appliedRules: TypstStyleRule[]; - conflicts: StyleConflict[]; - themeInfo?: ThemeDetectionResult; - pluginInfo: PluginDetectionResult[]; - optimizations: string[]; - warnings: string[]; -} - -/** - * Main hybrid export mode class that orchestrates style extraction and Typst integration - */ -export class HybridExportMode { - private app: any; - private cssExtractor: CSSExtractor; - private cssMapper: CSSToTypstMapper; - private themeManager: ThemeManager; - private themeSupport: PopularThemeSupport; - private pluginHandler: PluginSpecificStyleHandler; - - constructor(app: any) { - this.app = app; - this.cssExtractor = new CSSExtractor(app); - this.cssMapper = new CSSToTypstMapper(); - this.themeManager = new ThemeManager(app); - this.themeSupport = new PopularThemeSupport(app); - this.pluginHandler = new PluginSpecificStyleHandler(app); - } - - /** - * Generate a hybrid Typst template with extracted styles - */ - public async generateHybridTemplate(options: HybridExportOptions = {}): Promise { - const result: HybridStyleResult = { - typstTemplate: '', - extractedStyles: [], - appliedRules: [], - conflicts: [], - pluginInfo: [], - optimizations: [], - warnings: [] - }; - - try { - // Step 1: Extract styles from current Obsidian state - result.extractedStyles = await this.cssExtractor.extractStyles({ - includeComputedStyles: true, - captureCustomProperties: options.includeCustomProperties !== false - }); - - // Step 2: Detect and extract theme-specific styles - if (options.preserveThemeColors !== false) { - result.themeInfo = await this.themeManager.detectCurrentTheme() || undefined; - - if (result.themeInfo) { - const enhancedTheme = await this.themeSupport.getEnhancedThemeProfile(result.themeInfo.theme.name); - if (enhancedTheme) { - const themeStyles = await this.themeSupport.extractThemeStyles(result.themeInfo.theme.name); - result.extractedStyles.push(...themeStyles); - } - } - } - - // Step 3: Detect and extract plugin-specific styles - if (options.preservePluginStyles !== false) { - result.pluginInfo = await this.pluginHandler.detectActivePlugins(); - - for (const pluginResult of result.pluginInfo) { - if (pluginResult.isActive) { - result.extractedStyles.push(...pluginResult.extractedStyles); - } - } - } - - // Step 4: Convert CSS to Typst rules - result.appliedRules = await this.convertStylesToTypstRules( - result.extractedStyles, - options - ); - - // Step 5: Resolve style conflicts - result.conflicts = this.resolveStyleConflicts(result.appliedRules, options); - - // Step 6: Generate optimizations - result.optimizations = this.generateOptimizations(result.appliedRules, options); - - // Step 7: Build the final Typst template - result.typstTemplate = this.buildTypstTemplate(result, options); - - // Step 8: Generate warnings for potential issues - result.warnings = this.generateWarnings(result); - - } catch (error) { - result.warnings.push(`Error during hybrid template generation: ${error.message}`); - console.error('HybridExportMode error:', error); - - // Fallback to minimal template - result.typstTemplate = this.buildFallbackTemplate(options); - } - - return result; - } - - /** - * Convert extracted styles to Typst rules - */ - private async convertStylesToTypstRules( - styles: ExtractedStyle[], - options: HybridExportOptions - ): Promise { - const rules: TypstStyleRule[] = []; - const processedSelectors = new Set(); - - // Group styles by selector for efficient processing - const stylesBySelector = this.groupStylesBySelector(styles); - - for (const [selector, selectorStyles] of stylesBySelector) { - if (processedSelectors.has(selector)) continue; - - // Determine the appropriate Typst target for this selector - const typstTarget = this.mapSelectorToTypstTarget(selector); - if (!typstTarget) continue; - - // Convert CSS properties to Typst properties - const typstProperties: Record = {}; - let hasValidProperties = false; - - for (const style of selectorStyles) { - const mappedProperty = this.cssMapper.mapCSSProperty( - style.property, - style.value, - { simplifyColors: true, optimizeForPrint: options.optimizeForReadability } - ); - - if (mappedProperty && Object.keys(mappedProperty).length > 0) { - Object.assign(typstProperties, mappedProperty); - hasValidProperties = true; - } - } - - if (hasValidProperties) { - // Create Typst rule based on intensity setting - const rule = this.createTypstRule( - typstTarget, - typstProperties, - selector, - options.styleIntensity || 'moderate' - ); - - if (rule) { - rules.push(rule); - processedSelectors.add(selector); - } - } - } - - // Add theme-specific rules - if (options.preserveThemeColors !== false) { - const themeRules = await this.themeManager.generateThemeStyleRules(this.cssMapper); - rules.push(...themeRules); - } - - // Add plugin-specific rules - if (options.preservePluginStyles !== false) { - const pluginRules = this.pluginHandler.generatePluginTypstRules(); - rules.push(...pluginRules); - } - - return rules; - } - - /** - * Group styles by CSS selector - */ - private groupStylesBySelector(styles: ExtractedStyle[]): Map { - const grouped = new Map(); - - for (const style of styles) { - const existing = grouped.get(style.selector) || []; - existing.push(style); - grouped.set(style.selector, existing); - } - - return grouped; - } - - /** - * Map CSS selector to appropriate Typst target - */ - private mapSelectorToTypstTarget(selector: string): string | null { - // Handle heading selectors - if (selector.match(/^h[1-6]$/) || selector.includes('heading')) { - return 'heading'; - } - - // Handle paragraph selectors - if (selector === 'p' || selector.includes('markdown-preview-view') || - selector.includes('cm-line')) { - return 'text'; - } - - // Handle link selectors - if (selector === 'a' || selector.includes('cm-link')) { - return 'link'; - } - - // Handle code selectors - if (selector === 'code' || selector.includes('cm-inline-code') || - selector.includes('HyperMD-codeblock')) { - return 'raw'; - } - - // Handle strong/bold selectors - if (selector === 'strong' || selector === 'b' || selector.includes('bold')) { - return 'strong'; - } - - // Handle emphasis/italic selectors - if (selector === 'em' || selector === 'i' || selector.includes('italic')) { - return 'emph'; - } - - // Handle list selectors - if (selector.includes('list') || selector === 'ul' || selector === 'ol') { - return 'list'; - } - - // Handle table selectors - if (selector.includes('table') || selector === 'table') { - return 'table'; - } - - // Handle blockquote selectors - if (selector.includes('blockquote') || selector.includes('quote')) { - return 'quote'; - } - - // Handle general text elements - if (selector === 'body' || selector.includes('markdown')) { - return 'text'; - } - - // Plugin-specific selectors - if (selector.includes('dataview')) { - return 'table'; // Most dataview content is tabular - } - - if (selector.includes('callout')) { - return 'quote'; // Treat callouts as quote-like elements - } - - // Return null for unrecognized selectors - return null; - } - - /** - * Create a Typst rule from CSS properties - */ - private createTypstRule( - target: string, - properties: Record, - originalSelector: string, - intensity: 'minimal' | 'moderate' | 'full' - ): TypstStyleRule | null { - // Filter properties based on intensity - const filteredProperties = this.filterPropertiesByIntensity(properties, intensity); - - if (Object.keys(filteredProperties).length === 0) { - return null; - } - - // Determine rule type based on target - const ruleType = this.determineRuleType(target, originalSelector); - - return { - type: ruleType, - target, - properties: filteredProperties, - condition: this.generateCondition(target, originalSelector) - }; - } - - /** - * Filter properties based on style intensity setting - */ - private filterPropertiesByIntensity( - properties: Record, - intensity: 'minimal' | 'moderate' | 'full' - ): Record { - const filtered: Record = {}; - - // Always include essential properties - const essentialProperties = ['fill', 'font', 'size']; - - // Moderate adds layout and spacing - const moderateProperties = [...essentialProperties, 'weight', 'style', 'stroke', 'align']; - - // Full includes all properties - const allowedProperties = intensity === 'minimal' ? essentialProperties : - intensity === 'moderate' ? moderateProperties : - Object.keys(properties); - - for (const [key, value] of Object.entries(properties)) { - if (allowedProperties.includes(key) && value && value.trim()) { - filtered[key] = value; - } - } - - return filtered; - } - - /** - * Determine whether to use 'set' or 'show' rule - */ - private determineRuleType(target: string, originalSelector: string): 'set' | 'show' { - // Use 'show' for conditional styling - if (originalSelector.includes('.') || originalSelector.includes('[') || - originalSelector.includes(':')) { - return 'show'; - } - - // Use 'set' for general element styling - return 'set'; - } - - /** - * Generate condition for show rules - */ - private generateCondition(target: string, originalSelector: string): string | undefined { - // Generate conditions for heading levels - if (target === 'heading' && originalSelector.match(/^h([1-6])$/)) { - const level = originalSelector.match(/^h([1-6])$/)?.[1]; - return `heading.where(level: ${level})`; - } - - // For other complex selectors, return undefined to use simple set rule - return undefined; - } - - /** - * Resolve conflicts between CSS and Typst defaults - */ - private resolveStyleConflicts( - rules: TypstStyleRule[], - options: HybridExportOptions - ): StyleConflict[] { - const conflicts: StyleConflict[] = []; - const conflictResolution = options.conflictResolution || 'balanced'; - - // Define Typst default values - const typstDefaults: Record = { - 'font': 'Linux Libertine', - 'size': '11pt', - 'fill': 'black', - 'weight': 'regular', - 'style': 'normal' - }; - - for (const rule of rules) { - for (const [property, value] of Object.entries(rule.properties)) { - const typstDefault = typstDefaults[property]; - - if (typstDefault && value !== typstDefault) { - let resolution: 'css' | 'typst' | 'hybrid'; - let reason: string; - - switch (conflictResolution) { - case 'css-priority': - resolution = 'css'; - reason = 'CSS values take precedence'; - break; - case 'typst-priority': - resolution = 'typst'; - reason = 'Typst defaults preferred for consistency'; - // Remove the conflicting property - delete rule.properties[property]; - break; - case 'balanced': - default: - resolution = this.balancedConflictResolution(property, value, typstDefault); - reason = 'Balanced approach based on readability'; - if (resolution === 'typst') { - delete rule.properties[property]; - } - break; - } - - conflicts.push({ - property, - cssValue: value, - typstDefault, - resolution, - reason - }); - } - } - } - - return conflicts; - } - - /** - * Apply balanced conflict resolution - */ - private balancedConflictResolution( - property: string, - cssValue: string, - typstDefault: string - ): 'css' | 'typst' | 'hybrid' { - // For font sizes, prefer CSS if within reasonable range - if (property === 'size') { - const size = parseFloat(cssValue); - if (size >= 8 && size <= 24) { - return 'css'; - } - return 'typst'; - } - - // For colors, prefer CSS for better theme preservation - if (property === 'fill') { - return 'css'; - } - - // For fonts, prefer Typst defaults for consistency - if (property === 'font') { - // But allow CSS if it's a common web font - const webFonts = ['Arial', 'Helvetica', 'Times', 'Georgia', 'Verdana']; - const fontFamily = cssValue.toLowerCase(); - - if (webFonts.some(font => fontFamily.includes(font.toLowerCase()))) { - return 'css'; - } - return 'typst'; - } - - // Default to CSS for other properties - return 'css'; - } - - /** - * Generate style optimizations - */ - private generateOptimizations( - rules: TypstStyleRule[], - options: HybridExportOptions - ): string[] { - const optimizations: string[] = []; - - // Check for redundant rules - const rulesByTarget = new Map(); - for (const rule of rules) { - const existing = rulesByTarget.get(rule.target) || []; - existing.push(rule); - rulesByTarget.set(rule.target, existing); - } - - for (const [target, targetRules] of rulesByTarget) { - if (targetRules.length > 3) { - optimizations.push(`Consider consolidating ${targetRules.length} rules for ${target}`); - } - } - - // Check for readability optimizations - if (options.optimizeForReadability) { - const textRules = rules.filter(r => r.target === 'text'); - if (textRules.length > 0) { - optimizations.push('Applied readability optimizations to text elements'); - } - } - - // Check for font fallbacks - if (options.fontFallback !== false) { - const fontRules = rules.filter(r => r.properties.font); - if (fontRules.length > 0) { - optimizations.push('Consider adding font fallback options'); - } - } - - return optimizations; - } - - /** - * Build the final Typst template - */ - private buildTypstTemplate(result: HybridStyleResult, options: HybridExportOptions): string { - const lines: string[] = []; - - // Template header - lines.push('// Hybrid Typst Template Generated from Obsidian Styles'); - lines.push('// Generated by obsidian-typst-pdf-export plugin'); - lines.push(''); - - // Theme information - if (result.themeInfo) { - lines.push(`// Theme: ${result.themeInfo.theme.displayName}`); - lines.push(`// Confidence: ${Math.round(result.themeInfo.confidence * 100)}%`); - lines.push(''); - } - - // Plugin information - if (result.pluginInfo.length > 0) { - lines.push('// Active plugins with style support:'); - for (const plugin of result.pluginInfo) { - if (plugin.isActive) { - lines.push(`// - ${plugin.plugin.displayName}`); - } - } - lines.push(''); - } - - // Template configuration function - lines.push('#let hybrid-conf(doc) = {'); - - // Add set rules - const setRules = result.appliedRules.filter(r => r.type === 'set'); - if (setRules.length > 0) { - lines.push(' // Set rules for global styling'); - for (const rule of setRules) { - const properties = this.formatTypstProperties(rule.properties); - if (properties) { - lines.push(` set ${rule.target}(${properties})`); - } - } - lines.push(''); - } - - // Add show rules - const showRules = result.appliedRules.filter(r => r.type === 'show'); - if (showRules.length > 0) { - lines.push(' // Show rules for conditional styling'); - for (const rule of showRules) { - const properties = this.formatTypstProperties(rule.properties); - const target = rule.condition ? `${rule.target}.where(${rule.condition})` : rule.target; - if (properties) { - lines.push(` show ${target}: set ${rule.target}(${properties})`); - } - } - lines.push(''); - } - - // Page setup - lines.push(' // Page configuration'); - lines.push(' set page('); - lines.push(' paper: "us-letter",'); - lines.push(' margin: (x: 1in, y: 1in),'); - if (options.optimizeForReadability) { - lines.push(' numbering: "1",'); - } - lines.push(' )'); - lines.push(''); - - // Paragraph setup - lines.push(' // Paragraph configuration'); - lines.push(' set par('); - lines.push(' justify: true,'); - if (options.optimizeForReadability) { - lines.push(' leading: 0.65em,'); - } - lines.push(' )'); - lines.push(''); - - // Document content - lines.push(' doc'); - lines.push('}'); - lines.push(''); - - // Apply the template - lines.push('#show: hybrid-conf'); - lines.push(''); - - // Usage instructions - lines.push('// Usage: Add your content below this line'); - lines.push('// The template will automatically apply the extracted styles'); - - return lines.join('\n'); - } - - /** - * Format Typst properties for output - */ - private formatTypstProperties(properties: Record): string { - const formatted: string[] = []; - - for (const [key, value] of Object.entries(properties)) { - if (value && value.trim()) { - // Quote string values that aren't already quoted - const formattedValue = this.formatPropertyValue(key, value); - formatted.push(`${key}: ${formattedValue}`); - } - } - - return formatted.join(', '); - } - - /** - * Format individual property values - */ - private formatPropertyValue(property: string, value: string): string { - // Don't double-quote already quoted values - if (value.startsWith('"') && value.endsWith('"')) { - return value; - } - - // Quote font names - if (property === 'font' && !value.match(/^[a-z-]+$/)) { - return `"${value}"`; - } - - // Quote color names that aren't standard colors - if (property === 'fill' && !value.startsWith('rgb(') && - !value.startsWith('#') && !['black', 'white', 'red', 'blue', 'green'].includes(value)) { - return `"${value}"`; - } - - return value; - } - - /** - * Build fallback template for errors - */ - private buildFallbackTemplate(options: HybridExportOptions): string { - return `// Fallback Typst Template -// Generated due to error in style extraction - -#let fallback-conf(doc) = { - set text( - font: "Linux Libertine", - size: 11pt, - fill: black, - ) - - set par( - justify: true, - leading: 0.65em, - ) - - set page( - paper: "us-letter", - margin: (x: 1in, y: 1in), - numbering: "1", - ) - - doc -} - -#show: fallback-conf - -// Your content here -`; - } - - /** - * Generate warnings about potential issues - */ - private generateWarnings(result: HybridStyleResult): string[] { - const warnings: string[] = []; - - // Check for high number of conflicts - if (result.conflicts.length > 10) { - warnings.push(`High number of style conflicts (${result.conflicts.length}). Consider adjusting conflict resolution strategy.`); - } - - // Check for missing theme detection - if (!result.themeInfo && result.extractedStyles.length > 0) { - warnings.push('Theme detection failed. Using fallback styling.'); - } - - // Check for plugin compatibility - const activePlugins = result.pluginInfo.filter(p => p.isActive); - const unsupportedPlugins = result.pluginInfo.filter(p => p.isActive && p.extractedStyles.length === 0); - - if (unsupportedPlugins.length > 0) { - warnings.push(`Some active plugins may not be fully supported: ${unsupportedPlugins.map(p => p.plugin.displayName).join(', ')}`); - } - - // Check for empty style extraction - if (result.extractedStyles.length === 0) { - warnings.push('No styles extracted. Using default Typst styling.'); - } - - return warnings; - } - - /** - * Preview the hybrid template output - */ - public async previewHybridTemplate( - content: string, - options: HybridExportOptions = {} - ): Promise<{ template: string; preview: string }> { - const result = await this.generateHybridTemplate(options); - - const preview = `${result.typstTemplate} - -// Preview Content -${content} - -// Generated with ${result.appliedRules.length} style rules -// Theme: ${result.themeInfo?.theme.displayName || 'Default'} -// Active plugins: ${result.pluginInfo.filter(p => p.isActive).length} -`; - - return { - template: result.typstTemplate, - preview - }; - } - - /** - * Get default hybrid export options - */ - public getDefaultOptions(): HybridExportOptions { - return { - preserveThemeColors: true, - preservePluginStyles: true, - optimizeForReadability: true, - useTypstDefaults: false, - styleIntensity: 'moderate', - conflictResolution: 'balanced', - includeCustomProperties: true, - fontFallback: true - }; - } - - /** - * Validate hybrid export options - */ - public validateOptions(options: HybridExportOptions): { valid: boolean; errors: string[] } { - const errors: string[] = []; - - if (options.styleIntensity && !['minimal', 'moderate', 'full'].includes(options.styleIntensity)) { - errors.push('Invalid styleIntensity. Must be "minimal", "moderate", or "full"'); - } - - if (options.conflictResolution && !['css-priority', 'typst-priority', 'balanced'].includes(options.conflictResolution)) { - errors.push('Invalid conflictResolution. Must be "css-priority", "typst-priority", or "balanced"'); - } - - return { - valid: errors.length === 0, - errors - }; - } -} \ No newline at end of file diff --git a/src/PluginSpecificStyleHandler.ts b/src/PluginSpecificStyleHandler.ts deleted file mode 100644 index aa89ca8..0000000 --- a/src/PluginSpecificStyleHandler.ts +++ /dev/null @@ -1,671 +0,0 @@ -/** - * Plugin-Specific Style Handling System - * Detects and extracts styles from popular Obsidian plugins that add custom CSS and UI elements - */ - -import { CSSExtractor, ExtractedStyle } from './CSSExtractor'; -import { TypstStyleRule } from './CSSToTypstMapper'; - -export interface PluginStyleProfile { - id: string; - name: string; - displayName: string; - selectors: string[]; // CSS selectors specific to this plugin - detectionIdentifiers: string[]; // CSS classes, data attributes, or DOM elements to detect plugin presence - customExtraction?: (extractor: CSSExtractor) => Promise; - typstMapping?: (styles: ExtractedStyle[]) => TypstStyleRule[]; - priority?: number; -} - -export interface PluginDetectionResult { - plugin: PluginStyleProfile; - isActive: boolean; - confidence: number; // 0-1 score of detection confidence - extractedStyles: ExtractedStyle[]; -} - -/** - * Handles style extraction for popular Obsidian plugins - */ -export class PluginSpecificStyleHandler { - private app: any; - private registeredPlugins: Map = new Map(); - private activePlugins: Set = new Set(); - - constructor(app: any) { - this.app = app; - this.registerBuiltinProfiles(); - } - - /** - * Register built-in plugin style profiles - */ - private registerBuiltinProfiles(): void { - // Dataview plugin - this.registerPlugin({ - id: 'dataview', - name: 'dataview', - displayName: 'Dataview', - selectors: [ - '.dataview.result-group', - '.dataview.table-view-table', - '.dataview.list-view-ul', - '.dataview.inline-field', - '.dataview.inline-field-key', - '.dataview.inline-field-value', - '.block-language-dataview', - '.dataview-error-box' - ], - detectionIdentifiers: [ - '.dataview', - '.block-language-dataview', - '[data-dataview]', - '.dataview-plugin' - ], - customExtraction: async (extractor: CSSExtractor) => { - const styles: ExtractedStyle[] = []; - - // Extract Dataview table styles - const dataviewTables = document.querySelectorAll('.dataview.table-view-table'); - for (const table of Array.from(dataviewTables)) { - const computedStyle = getComputedStyle(table); - styles.push({ - selector: '.dataview.table-view-table', - property: 'border-collapse', - value: computedStyle.borderCollapse, - computedValue: computedStyle.borderCollapse - }); - styles.push({ - selector: '.dataview.table-view-table', - property: 'font-size', - value: computedStyle.fontSize, - computedValue: computedStyle.fontSize - }); - } - - // Extract inline field styles - const inlineFields = document.querySelectorAll('.dataview.inline-field'); - for (const field of Array.from(inlineFields).slice(0, 3)) { - const computedStyle = getComputedStyle(field); - styles.push({ - selector: '.dataview.inline-field', - property: 'color', - value: computedStyle.color, - computedValue: computedStyle.color - }); - styles.push({ - selector: '.dataview.inline-field', - property: 'font-weight', - value: computedStyle.fontWeight, - computedValue: computedStyle.fontWeight - }); - } - - return styles; - }, - typstMapping: (styles: ExtractedStyle[]) => { - const rules: TypstStyleRule[] = []; - - // Map table styles to Typst table formatting - const tableStyles = styles.filter(s => s.selector.includes('table-view-table')); - if (tableStyles.length > 0) { - rules.push({ - type: 'show', - target: 'table', - properties: { - stroke: '0.5pt', - 'align': 'left' - }, - condition: 'table' - }); - } - - // Map inline field styles - const fieldStyles = styles.filter(s => s.selector.includes('inline-field')); - if (fieldStyles.length > 0) { - const colorStyle = fieldStyles.find(s => s.property === 'color'); - if (colorStyle) { - rules.push({ - type: 'show', - target: 'strong', - properties: { - fill: colorStyle.value - }, - condition: 'regex(".*:.*")' - }); - } - } - - return rules; - }, - priority: 10 - }); - - // Templater plugin - this.registerPlugin({ - id: 'templater', - name: 'templater-obsidian', - displayName: 'Templater', - selectors: [ - '.templater-command', - '.templater-inline-command', - '.cm-templater-command', - '.cm-templater-bracket' - ], - detectionIdentifiers: [ - '.templater-command', - '.cm-templater-command', - '[data-templater]' - ], - customExtraction: async (extractor: CSSExtractor) => { - const styles: ExtractedStyle[] = []; - - // Extract Templater command styles - const templaterCommands = document.querySelectorAll('.cm-templater-command, .templater-command'); - for (const command of Array.from(templaterCommands)) { - const computedStyle = getComputedStyle(command); - styles.push({ - selector: '.templater-command', - property: 'color', - value: computedStyle.color, - computedValue: computedStyle.color - }); - styles.push({ - selector: '.templater-command', - property: 'background-color', - value: computedStyle.backgroundColor, - computedValue: computedStyle.backgroundColor - }); - styles.push({ - selector: '.templater-command', - property: 'font-style', - value: computedStyle.fontStyle, - computedValue: computedStyle.fontStyle - }); - } - - return styles; - }, - typstMapping: (styles: ExtractedStyle[]) => { - const rules: TypstStyleRule[] = []; - - const commandStyles = styles.filter(s => s.selector.includes('templater-command')); - if (commandStyles.length > 0) { - const colorStyle = commandStyles.find(s => s.property === 'color'); - const bgStyle = commandStyles.find(s => s.property === 'background-color'); - - if (colorStyle || bgStyle) { - const properties: Record = {}; - if (colorStyle) properties.fill = colorStyle.value; - if (bgStyle && bgStyle.value !== 'rgba(0, 0, 0, 0)') { - properties.highlight = bgStyle.value; - } - - rules.push({ - type: 'show', - target: 'raw', - properties, - condition: 'regex("<%.+%>")' - }); - } - } - - return rules; - }, - priority: 8 - }); - - // Calendar plugin - this.registerPlugin({ - id: 'calendar', - name: 'calendar', - displayName: 'Calendar', - selectors: [ - '.calendar-container', - '.calendar-month', - '.calendar-day', - '.calendar-today', - '.has-note' - ], - detectionIdentifiers: [ - '.calendar-container', - '.calendar-month', - '.workspace-leaf-content[data-type="calendar"]' - ], - priority: 5 - }); - - // Kanban plugin - this.registerPlugin({ - id: 'obsidian-kanban', - name: 'obsidian-kanban', - displayName: 'Kanban', - selectors: [ - '.kanban-plugin', - '.kanban-plugin__board', - '.kanban-plugin__lane', - '.kanban-plugin__item', - '.kanban-plugin__item-title' - ], - detectionIdentifiers: [ - '.kanban-plugin', - '[data-type="kanban"]', - '.kanban-plugin__board' - ], - priority: 7 - }); - - // Tasks plugin - this.registerPlugin({ - id: 'obsidian-tasks', - name: 'obsidian-tasks-plugin', - displayName: 'Tasks', - selectors: [ - '.tasks-list-text', - '.task-list-item', - '.tasks-backlink', - '.task-due-date', - '.task-priority' - ], - detectionIdentifiers: [ - '.tasks-list-text', - '.task-list-item.plugin-tasks-list-item', - '.tasks-backlink' - ], - priority: 6 - }); - - // Excalidraw plugin - this.registerPlugin({ - id: 'obsidian-excalidraw', - name: 'obsidian-excalidraw-plugin', - displayName: 'Excalidraw', - selectors: [ - '.excalidraw-wrapper', - '.excalidraw-svg', - '.excalidraw-embedded-img' - ], - detectionIdentifiers: [ - '.excalidraw-wrapper', - '[data-type="excalidraw"]', - '.excalidraw-svg' - ], - priority: 4 - }); - - // Advanced Tables plugin - this.registerPlugin({ - id: 'table-editor-obsidian', - name: 'table-editor-obsidian', - displayName: 'Advanced Tables', - selectors: [ - '.advanced-tables-toolbar', - '.table-editor-button', - '.cm-table-widget' - ], - detectionIdentifiers: [ - '.advanced-tables-toolbar', - '.table-editor-button', - '.cm-table-widget' - ], - priority: 5 - }); - - // Tag Wrangler plugin - this.registerPlugin({ - id: 'tag-wrangler', - name: 'tag-wrangler', - displayName: 'Tag Wrangler', - selectors: [ - '.tag-wrangler-contextmenu', - '.tag-wrangler-rename', - '.tag-container.mod-tag-wrangler' - ], - detectionIdentifiers: [ - '.tag-wrangler-contextmenu', - '[data-tag-wrangler]' - ], - priority: 3 - }); - - // Outliner plugin - this.registerPlugin({ - id: 'obsidian-outliner', - name: 'obsidian-outliner', - displayName: 'Outliner', - selectors: [ - '.outliner-plugin-list', - '.outliner-plugin-better-list', - '.cm-fold-indicator.outliner-plugin' - ], - detectionIdentifiers: [ - '.outliner-plugin-list', - '.outliner-plugin-better-list', - '[data-outliner-plugin]' - ], - priority: 4 - }); - } - - /** - * Register a plugin style profile - */ - public registerPlugin(profile: PluginStyleProfile): void { - this.registeredPlugins.set(profile.id, profile); - } - - /** - * Detect active plugins and their styles - */ - public async detectActivePlugins(): Promise { - const results: PluginDetectionResult[] = []; - - for (const [id, plugin] of this.registeredPlugins) { - const detection = await this.detectPlugin(plugin); - if (detection.isActive) { - results.push(detection); - this.activePlugins.add(id); - } - } - - // Sort by priority and confidence - results.sort((a, b) => { - const priorityDiff = (b.plugin.priority || 0) - (a.plugin.priority || 0); - if (priorityDiff !== 0) return priorityDiff; - return b.confidence - a.confidence; - }); - - return results; - } - - /** - * Detect if a specific plugin is active - */ - private async detectPlugin(plugin: PluginStyleProfile): Promise { - let confidence = 0; - let detectionCount = 0; - - // Check detection identifiers - for (const identifier of plugin.detectionIdentifiers) { - detectionCount++; - - if (identifier.startsWith('.')) { - // CSS class check - const className = identifier.substring(1); - if (document.querySelector(`.${className}`)) { - confidence += 1; - } - } else if (identifier.startsWith('[') && identifier.endsWith(']')) { - // Attribute selector check - if (document.querySelector(identifier)) { - confidence += 1; - } - } else { - // General selector check - if (document.querySelector(identifier)) { - confidence += 1; - } - } - } - - // Check for plugin in Obsidian's loaded plugins - if (this.app.plugins?.enabledPlugins?.has?.(plugin.name)) { - confidence += 2; - detectionCount += 2; - } - - // Check plugin-specific selectors exist in DOM - let selectorMatches = 0; - for (const selector of plugin.selectors) { - if (document.querySelector(selector)) { - selectorMatches += 1; - } - } - - if (selectorMatches > 0) { - confidence += selectorMatches * 0.5; - detectionCount += plugin.selectors.length; - } - - const finalConfidence = detectionCount > 0 ? confidence / detectionCount : 0; - const isActive = finalConfidence > 0.3; // Threshold for considering plugin active - - // Extract styles if plugin is detected as active - let extractedStyles: ExtractedStyle[] = []; - if (isActive) { - extractedStyles = await this.extractPluginStyles(plugin); - } - - return { - plugin, - isActive, - confidence: finalConfidence, - extractedStyles - }; - } - - /** - * Extract styles for a specific plugin - */ - private async extractPluginStyles(plugin: PluginStyleProfile): Promise { - const extractor = new CSSExtractor(this.app); - let styles: ExtractedStyle[] = []; - - // Use custom extraction if available - if (plugin.customExtraction) { - try { - styles = await plugin.customExtraction(extractor); - } catch (error) { - console.warn(`Custom extraction failed for plugin ${plugin.name}:`, error); - } - } - - // Fallback to standard selector-based extraction - if (styles.length === 0) { - for (const selector of plugin.selectors) { - const elements = document.querySelectorAll(selector); - - for (const element of Array.from(elements).slice(0, 3)) { // Limit to first 3 matches per selector - const computedStyle = getComputedStyle(element); - - // Extract key visual properties - const keyProperties = [ - 'color', 'background-color', 'border-color', 'font-family', - 'font-size', 'font-weight', 'font-style', 'text-decoration', - 'margin', 'padding', 'border', 'border-radius' - ]; - - for (const property of keyProperties) { - const value = computedStyle.getPropertyValue(property); - if (value && value !== 'initial' && value !== 'inherit' && value.trim()) { - styles.push({ - selector, - property, - value: value.trim(), - computedValue: value.trim() - }); - } - } - } - } - } - - return styles; - } - - /** - * Generate Typst rules for detected plugins - */ - public generatePluginTypstRules(): TypstStyleRule[] { - const rules: TypstStyleRule[] = []; - - for (const pluginId of this.activePlugins) { - const plugin = this.registeredPlugins.get(pluginId); - if (!plugin) continue; - - // Use custom mapping if available - if (plugin.typstMapping) { - try { - const pluginStyles = this.getPluginStyles(pluginId); - const pluginRules = plugin.typstMapping(pluginStyles); - rules.push(...pluginRules); - } catch (error) { - console.warn(`Typst mapping failed for plugin ${plugin.name}:`, error); - } - } - } - - return rules; - } - - /** - * Get extracted styles for a specific plugin - */ - private getPluginStyles(pluginId: string): ExtractedStyle[] { - // This would be populated during detection - for now return empty array - // In a full implementation, we'd cache the results from detectActivePlugins() - return []; - } - - /** - * Get all registered plugins - */ - public getRegisteredPlugins(): PluginStyleProfile[] { - return Array.from(this.registeredPlugins.values()); - } - - /** - * Get active plugin IDs - */ - public getActivePlugins(): string[] { - return Array.from(this.activePlugins); - } - - /** - * Check if specific plugin is active - */ - public isPluginActive(pluginId: string): boolean { - return this.activePlugins.has(pluginId); - } - - /** - * Get plugin by ID - */ - public getPlugin(pluginId: string): PluginStyleProfile | null { - return this.registeredPlugins.get(pluginId) || null; - } - - /** - * Clear plugin detection cache - */ - public clearCache(): void { - this.activePlugins.clear(); - } - - /** - * Generate plugin compatibility report - */ - public async generateCompatibilityReport(): Promise<{ - totalPlugins: number; - activePlugins: number; - supportedPlugins: string[]; - unsupportedPlugins: string[]; - styleExtractionResults: Record; - }> { - const detectionResults = await this.detectActivePlugins(); - const supportedPlugins: string[] = []; - const unsupportedPlugins: string[] = []; - const styleExtractionResults: Record = {}; - - // Check all enabled plugins against our profiles - const enabledPlugins = this.app.plugins?.enabledPlugins || new Set(); - - for (const pluginName of enabledPlugins) { - const profile = Array.from(this.registeredPlugins.values()) - .find(p => p.name === pluginName || p.id === pluginName); - - if (profile) { - supportedPlugins.push(pluginName); - const detection = detectionResults.find(r => r.plugin.id === profile.id); - styleExtractionResults[pluginName] = detection?.extractedStyles.length || 0; - } else { - unsupportedPlugins.push(pluginName); - } - } - - return { - totalPlugins: this.registeredPlugins.size, - activePlugins: detectionResults.filter(r => r.isActive).length, - supportedPlugins, - unsupportedPlugins, - styleExtractionResults - }; - } - - /** - * Watch for plugin changes - */ - public watchPluginChanges(callback: (activePlugins: string[]) => void): void { - // Listen for plugin enable/disable events - if (this.app.plugins?.on) { - this.app.plugins.on('plugin-enabled', async (pluginName: string) => { - await this.detectActivePlugins(); - callback(Array.from(this.activePlugins)); - }); - - this.app.plugins.on('plugin-disabled', async (pluginName: string) => { - // Remove from active plugins - const profile = Array.from(this.registeredPlugins.values()) - .find(p => p.name === pluginName); - if (profile) { - this.activePlugins.delete(profile.id); - } - callback(Array.from(this.activePlugins)); - }); - } - - // Listen for DOM changes that might indicate plugin activity - const observer = new MutationObserver(async (mutations) => { - let shouldRedetect = false; - - for (const mutation of mutations) { - if (mutation.type === 'childList') { - for (const node of Array.from(mutation.addedNodes)) { - if (node instanceof Element) { - // Check if added element contains plugin-specific classes - for (const [_, plugin] of this.registeredPlugins) { - for (const identifier of plugin.detectionIdentifiers) { - if (identifier.startsWith('.')) { - const className = identifier.substring(1); - if (node.classList?.contains(className) || - node.querySelector?.(`.${className}`)) { - shouldRedetect = true; - break; - } - } - } - if (shouldRedetect) break; - } - } - if (shouldRedetect) break; - } - } - if (shouldRedetect) break; - } - - if (shouldRedetect) { - // Debounce detection - setTimeout(async () => { - await this.detectActivePlugins(); - callback(Array.from(this.activePlugins)); - }, 500); - } - }); - - // Observe changes in the workspace - observer.observe(document.body, { - childList: true, - subtree: true - }); - } -} \ No newline at end of file diff --git a/src/PopularThemeSupport.ts b/src/PopularThemeSupport.ts deleted file mode 100644 index 1d20507..0000000 --- a/src/PopularThemeSupport.ts +++ /dev/null @@ -1,733 +0,0 @@ -/** - * Popular Theme Support System - * Enhanced support for specific popular Obsidian themes with detailed style profiles - */ - -import { ThemeManager, ThemeProfile, ThemeDetectionResult } from './ThemeManager'; -import { CSSExtractor } from './CSSExtractor'; -import { CSSToTypstMapper, TypstStyleRule } from './CSSToTypstMapper'; - -export interface EnhancedThemeProfile extends ThemeProfile { - version?: string; - author?: string; - repository?: string; - enhancedExtraction?: (extractor: CSSExtractor) => Promise; - testSelectors?: string[]; // Selectors to test for theme detection - compatibilityNotes?: string; -} - -export interface ThemeTestResult { - theme: string; - detected: boolean; - confidence: number; - missingElements: string[]; - extractedRules: TypstStyleRule[]; -} - -/** - * Enhanced support for popular Obsidian themes - */ -export class PopularThemeSupport { - private themeManager: ThemeManager; - private enhancedProfiles: Map = new Map(); - - constructor(themeManager: ThemeManager) { - this.themeManager = themeManager; - this.registerEnhancedThemes(); - } - - /** - * Register enhanced theme profiles for popular themes - */ - private registerEnhancedThemes(): void { - // Minimal Theme - Enhanced Profile - this.registerEnhancedTheme({ - name: 'minimal', - displayName: 'Minimal', - version: '6.x+', - author: 'kepano', - repository: 'kepano/obsidian-minimal', - identifiers: ['minimal-theme', 'theme-minimal', 'is-minimal-theme'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(25, 25, 25)', - transform: (value) => this.adjustMinimalTextColor(value) - }, - { - cssVariable: '--text-muted', - typstProperty: 'fill', - fallbackValue: 'rgb(100, 100, 100)' - }, - { - cssVariable: '--text-accent', - typstProperty: 'fill', - fallbackValue: 'blue' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'white' - }, - { - cssVariable: '--background-secondary', - typstProperty: 'fill', - fallbackValue: 'rgb(250, 250, 250)' - }, - { - cssVariable: '--minimal-text-size', - typstProperty: 'size', - fallbackValue: '16px', - transform: (value) => this.convertMinimalFontSize(value) - }, - { - cssVariable: '--default-font', - typstProperty: 'font', - fallbackValue: '"Inter"', - transform: (value) => this.normalizeMinimalFont(value) - } - ], - testSelectors: [ - '.minimal-theme .workspace', - '.is-minimal-theme .view-content', - '.theme-minimal .markdown-preview-view' - ], - enhancedExtraction: async (extractor: CSSExtractor) => { - return await this.extractMinimalThemeStyles(extractor); - }, - compatibilityNotes: 'Best with Minimal v6.0+. Supports color schemes, typography scaling, and custom accents.', - priority: 15 - }); - - // Blue Topaz Theme - Enhanced Profile - this.registerEnhancedTheme({ - name: 'blue-topaz', - displayName: 'Blue Topaz', - version: '0.2.x+', - author: '3F', - repository: '3F/Blue-topaz-obsidian', - identifiers: ['blue-topaz-theme', 'bt', 'theme-blue-topaz'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(47, 52, 55)' - }, - { - cssVariable: '--text-accent', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--bt-accent', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--h1-color', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--h2-color', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--h3-color', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - } - ], - testSelectors: [ - '.blue-topaz-theme .workspace', - '.bt .markdown-preview-view h1', - '[data-theme="blue-topaz"] .view-content' - ], - enhancedExtraction: async (extractor: CSSExtractor) => { - return await this.extractBlueTopazStyles(extractor); - }, - compatibilityNotes: 'Excellent heading color support. Custom callout styles included.', - priority: 15 - }); - - // Sanctum Theme - Enhanced Profile - this.registerEnhancedTheme({ - name: 'sanctum', - displayName: 'Sanctum', - version: '1.x+', - author: 'jdanielmourao', - repository: 'jdanielmourao/obsidian-sanctum', - identifiers: ['sanctum', 'theme-sanctum'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(220, 220, 220)' - }, - { - cssVariable: '--accent', - typstProperty: 'fill', - fallbackValue: 'rgb(126, 208, 255)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'rgb(16, 20, 24)' - }, - { - cssVariable: '--background-secondary', - typstProperty: 'fill', - fallbackValue: 'rgb(22, 27, 32)' - } - ], - testSelectors: [ - '.sanctum .workspace', - '.theme-sanctum .markdown-preview-view' - ], - enhancedExtraction: async (extractor: CSSExtractor) => { - return await this.extractSanctumStyles(extractor); - }, - compatibilityNotes: 'Dark theme optimized. Great for code blocks and syntax highlighting.', - priority: 10 - }); - - // Things Theme - Enhanced Profile - this.registerEnhancedTheme({ - name: 'things', - displayName: 'Things', - version: '2.x+', - author: 'colineckert', - repository: 'colineckert/obsidian-things', - identifiers: ['things-theme', 'theme-things'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(51, 51, 51)' - }, - { - cssVariable: '--things-accent', - typstProperty: 'fill', - fallbackValue: 'rgb(0, 122, 255)' - }, - { - cssVariable: '--things-green', - typstProperty: 'fill', - fallbackValue: 'rgb(40, 205, 65)' - } - ], - testSelectors: [ - '.things-theme .workspace', - '.theme-things .markdown-preview-view' - ], - enhancedExtraction: async (extractor: CSSExtractor) => { - return await this.extractThingsStyles(extractor); - }, - compatibilityNotes: 'iOS-inspired design. Clean typography and spacing.', - priority: 10 - }); - - // Atom Theme - Enhanced Profile - this.registerEnhancedTheme({ - name: 'atom', - displayName: 'Atom', - version: '2.x+', - author: 'kognise', - repository: 'kognise/obsidian-atom', - identifiers: ['atom-theme', 'theme-atom'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(171, 178, 191)' - }, - { - cssVariable: '--accent', - typstProperty: 'fill', - fallbackValue: 'rgb(86, 182, 194)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'rgb(40, 44, 52)' - } - ], - testSelectors: [ - '.atom-theme .workspace', - '.theme-atom .markdown-preview-view' - ], - enhancedExtraction: async (extractor: CSSExtractor) => { - return await this.extractAtomStyles(extractor); - }, - compatibilityNotes: 'Dark coding theme. Excellent syntax highlighting colors.', - priority: 8 - }); - - // Register enhanced profiles with ThemeManager - for (const [name, profile] of this.enhancedProfiles) { - this.themeManager.registerTheme(profile); - } - } - - /** - * Register an enhanced theme profile - */ - private registerEnhancedTheme(profile: EnhancedThemeProfile): void { - this.enhancedProfiles.set(profile.name, profile); - } - - /** - * Extract Minimal theme styles with enhanced logic - */ - private async extractMinimalThemeStyles(extractor: CSSExtractor): Promise { - const rules: TypstStyleRule[] = []; - - // Minimal theme typography rules - rules.push({ - type: 'set', - target: 'text', - properties: { - font: '"Inter"', - size: '16pt' - } - }); - - // Minimal heading styles - for (let level = 1; level <= 6; level++) { - const headingColor = this.getCssVariable(`--h${level}-color`) || - this.getCssVariable('--text-accent') || - 'blue'; - - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: headingColor, - weight: level <= 2 ? '"bold"' : '"semibold"' - }, - condition: `heading.where(level: ${level})` - }); - } - - // Minimal callout styles - const calloutTypes = ['note', 'abstract', 'info', 'tip', 'success', 'question', 'warning', 'failure', 'danger', 'bug', 'example', 'quote']; - for (const type of calloutTypes) { - const color = this.getMinimalCalloutColor(type); - if (color) { - rules.push({ - type: 'show', - target: 'block', - properties: { - stroke: `1pt + ${color}`, - inset: '12pt' - }, - condition: `block.where(type: "${type}")` - }); - } - } - - return rules; - } - - /** - * Extract Blue Topaz theme styles - */ - private async extractBlueTopazStyles(extractor: CSSExtractor): Promise { - const rules: TypstStyleRule[] = []; - - // Blue Topaz heading colors - const headingColors = { - 1: this.getCssVariable('--h1-color') || 'rgb(8, 109, 221)', - 2: this.getCssVariable('--h2-color') || 'rgb(8, 109, 221)', - 3: this.getCssVariable('--h3-color') || 'rgb(8, 109, 221)', - 4: this.getCssVariable('--text-accent') || 'rgb(8, 109, 221)', - 5: this.getCssVariable('--text-accent') || 'rgb(8, 109, 221)', - 6: this.getCssVariable('--text-accent') || 'rgb(8, 109, 221)' - }; - - for (const [level, color] of Object.entries(headingColors)) { - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: color, - weight: level === '1' ? '"bold"' : '"semibold"' - }, - condition: `heading.where(level: ${level})` - }); - } - - // Blue Topaz accent elements - const accentColor = this.getCssVariable('--bt-accent') || 'rgb(8, 109, 221)'; - rules.push({ - type: 'show', - target: 'link', - properties: { - fill: accentColor - } - }); - - return rules; - } - - /** - * Extract Sanctum theme styles (dark theme) - */ - private async extractSanctumStyles(extractor: CSSExtractor): Promise { - const rules: TypstStyleRule[] = []; - - // Sanctum dark theme base styles - const textColor = this.getCssVariable('--text-normal') || 'rgb(220, 220, 220)'; - const accentColor = this.getCssVariable('--accent') || 'rgb(126, 208, 255)'; - - rules.push({ - type: 'set', - target: 'text', - properties: { - fill: textColor - } - }); - - // Sanctum heading styles with accent color - for (let level = 1; level <= 6; level++) { - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: accentColor, - weight: level <= 2 ? '"bold"' : '"semibold"' - }, - condition: `heading.where(level: ${level})` - }); - } - - // Code block styling - rules.push({ - type: 'show', - target: 'raw', - properties: { - fill: 'rgb(200, 200, 200)', - font: '"Fira Code"' - } - }); - - return rules; - } - - /** - * Extract Things theme styles - */ - private async extractThingsStyles(extractor: CSSExtractor): Promise { - const rules: TypstStyleRule[] = []; - - const thingsBlue = this.getCssVariable('--things-accent') || 'rgb(0, 122, 255)'; - const thingsGreen = this.getCssVariable('--things-green') || 'rgb(40, 205, 65)'; - - // Things-style headings - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: thingsBlue, - weight: '"semibold"' - }, - condition: 'heading.where(level: 1)' - }); - - // Success/completion styling - rules.push({ - type: 'show', - target: 'text', - properties: { - fill: thingsGreen - }, - condition: 'text.where(content: regex("✓|✅|☑"))' - }); - - return rules; - } - - /** - * Extract Atom theme styles - */ - private async extractAtomStyles(extractor: CSSExtractor): Promise { - const rules: TypstStyleRule[] = []; - - const atomAccent = this.getCssVariable('--accent') || 'rgb(86, 182, 194)'; - const atomText = this.getCssVariable('--text-normal') || 'rgb(171, 178, 191)'; - - rules.push({ - type: 'set', - target: 'text', - properties: { - fill: atomText, - font: '"Fira Code"' - } - }); - - // Atom heading colors - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: atomAccent - } - }); - - return rules; - } - - /** - * Test theme detection and style extraction - */ - public async testThemeSupport(themeName: string): Promise { - const profile = this.enhancedProfiles.get(themeName); - if (!profile) { - return { - theme: themeName, - detected: false, - confidence: 0, - missingElements: ['Theme profile not found'], - extractedRules: [] - }; - } - - // Test theme detection - const detectionResult = await this.themeManager.detectCurrentTheme(); - const detected = detectionResult?.theme.name === themeName; - const confidence = detectionResult?.confidence || 0; - - // Test selectors - const missingElements: string[] = []; - if (profile.testSelectors) { - for (const selector of profile.testSelectors) { - const elements = document.querySelectorAll(selector); - if (elements.length === 0) { - missingElements.push(selector); - } - } - } - - // Extract rules - let extractedRules: TypstStyleRule[] = []; - if (profile.enhancedExtraction) { - const extractor = new CSSExtractor(this.themeManager['app']); - extractedRules = await profile.enhancedExtraction(extractor); - } - - return { - theme: themeName, - detected, - confidence, - missingElements, - extractedRules - }; - } - - /** - * Get all enhanced theme profiles - */ - public getEnhancedProfiles(): Map { - return this.enhancedProfiles; - } - - /** - * Get enhanced theme profile for a specific theme - */ - public getEnhancedThemeProfile(themeName: string): EnhancedThemeProfile | null { - return this.enhancedProfiles.get(themeName) || null; - } - - /** - * Extract theme-specific styles - */ - public extractThemeStyles(themeName: string): any { - const profile = this.enhancedProfiles.get(themeName); - if (!profile) { - return []; - } - - // Use the appropriate extraction method based on theme - // These methods don't actually need the CSSExtractor parameter for their current implementation - switch (themeName) { - case 'minimal': - return this.extractMinimalThemeStylesInternal(); - case 'blue-topaz': - return this.extractBlueTopazStylesInternal(); - case 'sanctum': - return this.extractSanctumStylesInternal(); - case 'things': - return this.extractThingsStylesInternal(); - case 'atom': - return this.extractAtomStylesInternal(); - default: - return []; - } - } - - /** - * Internal method for extracting minimal theme styles without CSSExtractor dependency - */ - private extractMinimalThemeStylesInternal(): any[] { - const rules: any[] = []; - - // Minimal theme typography rules - rules.push({ - type: 'set', - target: 'text', - properties: { - font: '"Inter"', - size: '16pt' - } - }); - - // Minimal heading styles - for (let level = 1; level <= 6; level++) { - const headingColor = this.getCssVariable(`--h${level}-color`) || - this.getCssVariable('--text-accent') || - 'blue'; - - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: headingColor, - weight: level <= 2 ? '"bold"' : '"semibold"' - }, - condition: `heading.where(level: ${level})` - }); - } - - return rules; - } - - private extractBlueTopazStylesInternal(): any[] { return []; } - private extractSanctumStylesInternal(): any[] { return []; } - private extractThingsStylesInternal(): any[] { return []; } - private extractAtomStylesInternal(): any[] { return []; } - - /** - * Utility: Get CSS variable value - */ - private getCssVariable(name: string): string | null { - const value = getComputedStyle(document.documentElement).getPropertyValue(name)?.trim(); - return value && value !== 'initial' && value !== 'inherit' ? value : null; - } - - /** - * Minimal theme specific transformations - */ - private adjustMinimalTextColor(color: string): string { - // Minimal theme may need color adjustments for print - if (color.includes('rgb')) { - // Darken text slightly for better print contrast - return color.replace(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/, (match, r, g, b) => { - const newR = Math.max(0, parseInt(r) - 20); - const newG = Math.max(0, parseInt(g) - 20); - const newB = Math.max(0, parseInt(b) - 20); - return `rgb(${newR}, ${newG}, ${newB})`; - }); - } - return color; - } - - private convertMinimalFontSize(size: string): string { - // Convert Minimal's font sizes to appropriate Typst sizes - const pxMatch = size.match(/(\d+)px/); - if (pxMatch) { - const px = parseInt(pxMatch[1]); - const pt = Math.round(px * 0.75); - return `${pt}pt`; - } - return size; - } - - private normalizeMinimalFont(font: string): string { - // Minimal theme font family normalization - if (font.includes('Inter')) return '"Inter"'; - if (font.includes('system-ui') || font.includes('-apple-system')) return '"Inter"'; - return font.replace(/['"]/g, '').split(',')[0].trim(); - } - - private getMinimalCalloutColor(type: string): string | null { - const calloutColors: Record = { - 'note': 'rgb(8, 109, 221)', - 'abstract': 'rgb(0, 176, 255)', - 'info': 'rgb(8, 109, 221)', - 'tip': 'rgb(0, 191, 165)', - 'success': 'rgb(8, 185, 78)', - 'question': 'rgb(236, 117, 0)', - 'warning': 'rgb(236, 117, 0)', - 'failure': 'rgb(233, 49, 71)', - 'danger': 'rgb(233, 49, 71)', - 'bug': 'rgb(233, 49, 71)', - 'example': 'rgb(124, 77, 255)', - 'quote': 'rgb(158, 158, 158)' - }; - return calloutColors[type] || null; - } - - /** - * Generate compatibility report for current theme - */ - public async generateCompatibilityReport(): Promise<{ - currentTheme: string | null; - isEnhanced: boolean; - compatibilityScore: number; - supportedFeatures: string[]; - unsupportedFeatures: string[]; - recommendations: string[]; - }> { - const current = await this.themeManager.detectCurrentTheme(); - const currentThemeName = current?.theme.name || null; - const isEnhanced = currentThemeName ? this.enhancedProfiles.has(currentThemeName) : false; - - let compatibilityScore = 0; - const supportedFeatures: string[] = []; - const unsupportedFeatures: string[] = []; - const recommendations: string[] = []; - - if (isEnhanced && currentThemeName) { - const profile = this.enhancedProfiles.get(currentThemeName)!; - compatibilityScore = 90; // High score for enhanced themes - - supportedFeatures.push( - 'Theme detection', - 'Color extraction', - 'Typography mapping', - 'Enhanced style rules' - ); - - if (profile.enhancedExtraction) { - supportedFeatures.push('Custom extraction logic'); - compatibilityScore += 10; - } - - recommendations.push(`Using enhanced support for ${profile.displayName} theme`); - if (profile.compatibilityNotes) { - recommendations.push(profile.compatibilityNotes); - } - } else if (currentThemeName) { - compatibilityScore = 60; // Medium score for detected but not enhanced themes - supportedFeatures.push('Basic theme detection', 'Standard color extraction'); - unsupportedFeatures.push('Advanced style rules', 'Theme-specific optimizations'); - recommendations.push(`Consider using an enhanced theme like Minimal or Blue Topaz for better export quality`); - } else { - compatibilityScore = 40; // Lower score for unknown themes - supportedFeatures.push('Default styling'); - unsupportedFeatures.push('Theme detection', 'Custom colors', 'Enhanced typography'); - recommendations.push('Switch to a supported theme for better PDF export styling'); - } - - return { - currentTheme: currentThemeName, - isEnhanced, - compatibilityScore: Math.min(100, compatibilityScore), - supportedFeatures, - unsupportedFeatures, - recommendations - }; - } -} \ No newline at end of file diff --git a/src/ThemeManager.ts b/src/ThemeManager.ts deleted file mode 100644 index 1a9b948..0000000 --- a/src/ThemeManager.ts +++ /dev/null @@ -1,585 +0,0 @@ -/** - * Theme-Specific Variable Handling System - * Detects and processes theme-specific CSS variables and computed styles - */ - -import { CSSExtractor, ThemeInfo } from './CSSExtractor'; -import { CSSToTypstMapper, TypstStyleRule } from './CSSToTypstMapper'; - -export interface ThemeVariableMapping { - cssVariable: string; - typstProperty: string; - fallbackValue?: string; - transform?: (value: string) => string; -} - -export interface ThemeProfile { - name: string; - displayName: string; - identifiers: string[]; // CSS classes or attributes to identify theme - variableMappings: ThemeVariableMapping[]; - customExtraction?: (extractor: CSSExtractor) => Promise>; - priority?: number; // Higher priority themes override lower ones -} - -export interface ThemeDetectionResult { - theme: ThemeProfile; - confidence: number; // 0-1 score of detection confidence - variables: Map; -} - -/** - * Manages theme-specific variable handling and detection - */ -export class ThemeManager { - private app: any; - private registeredThemes: Map = new Map(); - private variableCache: Map = new Map(); - private currentTheme: ThemeDetectionResult | null = null; - - constructor(app: any) { - this.app = app; - this.registerBuiltinThemes(); - } - - /** - * Register built-in theme profiles - */ - private registerBuiltinThemes(): void { - // Default Obsidian theme - this.registerTheme({ - name: 'default', - displayName: 'Default', - identifiers: ['theme-dark', 'theme-light'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'black' - }, - { - cssVariable: '--text-muted', - typstProperty: 'fill', - fallbackValue: 'gray' - }, - { - cssVariable: '--text-faint', - typstProperty: 'fill', - fallbackValue: 'rgb(120, 120, 120)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'white' - }, - { - cssVariable: '--background-secondary', - typstProperty: 'fill', - fallbackValue: 'rgb(250, 250, 250)' - }, - { - cssVariable: '--font-text-size', - typstProperty: 'size', - fallbackValue: '16px', - transform: (value) => value.replace('px', 'pt') - }, - { - cssVariable: '--font-text', - typstProperty: 'font', - fallbackValue: '"Inter"' - }, - { - cssVariable: '--font-monospace', - typstProperty: 'font', - fallbackValue: '"Fira Code"' - } - ], - priority: 1 - }); - - // Minimal theme - this.registerTheme({ - name: 'minimal', - displayName: 'Minimal', - identifiers: ['minimal-theme', 'theme-minimal'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(25, 25, 25)' - }, - { - cssVariable: '--text-muted', - typstProperty: 'fill', - fallbackValue: 'rgb(100, 100, 100)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'white' - }, - { - cssVariable: '--minimal-text-size', - typstProperty: 'size', - fallbackValue: '17px', - transform: (value) => value.replace('px', 'pt') - }, - { - cssVariable: '--default-font', - typstProperty: 'font', - fallbackValue: '"Inter"' - }, - { - cssVariable: '--font-ui-small', - typstProperty: 'size', - fallbackValue: '12px', - transform: (value) => value.replace('px', 'pt') - } - ], - customExtraction: async (extractor: CSSExtractor) => { - const variables = new Map(); - - // Minimal theme uses specific CSS variables - const minimalVars = [ - '--accent', - '--accent-hover', - '--minimal-bright', - '--minimal-dark', - '--ui1', '--ui2', '--ui3' - ]; - - for (const varName of minimalVars) { - const value = getComputedStyle(document.documentElement).getPropertyValue(varName); - if (value.trim()) { - variables.set(varName, value.trim()); - } - } - - return variables; - }, - priority: 10 - }); - - // Blue Topaz theme - this.registerTheme({ - name: 'blue-topaz', - displayName: 'Blue Topaz', - identifiers: ['blue-topaz-theme', 'bt'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(47, 52, 55)' - }, - { - cssVariable: '--text-accent', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'rgb(248, 249, 250)' - }, - { - cssVariable: '--bt-accent', - typstProperty: 'fill', - fallbackValue: 'blue' - }, - { - cssVariable: '--h1-color', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - }, - { - cssVariable: '--h2-color', - typstProperty: 'fill', - fallbackValue: 'rgb(8, 109, 221)' - } - ], - customExtraction: async (extractor: CSSExtractor) => { - const variables = new Map(); - - // Blue Topaz specific variables - const btVars = [ - '--bt-accent', '--bt-accent-2', - '--bt-blue', '--bt-green', '--bt-orange', '--bt-red', - '--bt-yellow', '--bt-purple' - ]; - - for (const varName of btVars) { - const value = getComputedStyle(document.documentElement).getPropertyValue(varName); - if (value.trim()) { - variables.set(varName, value.trim()); - } - } - - return variables; - }, - priority: 10 - }); - - // Sanctum theme - this.registerTheme({ - name: 'sanctum', - displayName: 'Sanctum', - identifiers: ['sanctum'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(220, 220, 220)' - }, - { - cssVariable: '--accent', - typstProperty: 'fill', - fallbackValue: 'rgb(126, 208, 255)' - }, - { - cssVariable: '--background-primary', - typstProperty: 'fill', - fallbackValue: 'rgb(16, 20, 24)' - } - ], - priority: 5 - }); - - // Things theme - this.registerTheme({ - name: 'things', - displayName: 'Things', - identifiers: ['things-theme'], - variableMappings: [ - { - cssVariable: '--text-normal', - typstProperty: 'fill', - fallbackValue: 'rgb(51, 51, 51)' - }, - { - cssVariable: '--things-accent', - typstProperty: 'fill', - fallbackValue: 'rgb(0, 122, 255)' - } - ], - priority: 5 - }); - } - - /** - * Register a theme profile - */ - public registerTheme(profile: ThemeProfile): void { - this.registeredThemes.set(profile.name, profile); - } - - /** - * Detect the current active theme - */ - public async detectCurrentTheme(): Promise { - const detectionResults: ThemeDetectionResult[] = []; - - // Check each registered theme - for (const [name, theme] of this.registeredThemes) { - const confidence = this.calculateThemeConfidence(theme); - if (confidence > 0) { - const variables = await this.extractThemeVariables(theme); - detectionResults.push({ - theme, - confidence, - variables - }); - } - } - - // Sort by priority and confidence - detectionResults.sort((a, b) => { - const priorityDiff = (b.theme.priority || 0) - (a.theme.priority || 0); - if (priorityDiff !== 0) return priorityDiff; - return b.confidence - a.confidence; - }); - - const result = detectionResults[0] || null; - this.currentTheme = result; - return result; - } - - /** - * Calculate confidence score for theme detection - */ - private calculateThemeConfidence(theme: ThemeProfile): number { - let score = 0; - let checks = 0; - - const body = document.body; - const html = document.documentElement; - - for (const identifier of theme.identifiers) { - checks++; - - // Check for CSS class - if (identifier.startsWith('.')) { - const className = identifier.substring(1); - if (body.classList.contains(className) || html.classList.contains(className)) { - score += 1; - } - } - // Check for CSS class without dot - else if (body.classList.contains(identifier) || html.classList.contains(identifier)) { - score += 1; - } - // Check for data attribute - else if (identifier.includes('=')) { - const [attr, value] = identifier.split('='); - if (body.getAttribute(attr) === value || html.getAttribute(attr) === value) { - score += 1; - } - } - } - - // Check for theme-specific CSS variables - let variableChecks = 0; - let variableMatches = 0; - - for (const mapping of theme.variableMappings) { - variableChecks++; - const value = getComputedStyle(document.documentElement).getPropertyValue(mapping.cssVariable); - if (value && value.trim() && value !== 'initial' && value !== 'inherit') { - variableMatches++; - } - } - - // Combine identifier and variable confidence - const identifierConfidence = checks > 0 ? score / checks : 0; - const variableConfidence = variableChecks > 0 ? variableMatches / variableChecks : 0; - - // Weight identifier confidence more heavily - return (identifierConfidence * 0.7) + (variableConfidence * 0.3); - } - - /** - * Extract theme variables for a specific theme - */ - private async extractThemeVariables(theme: ThemeProfile): Promise> { - const variables = new Map(); - - // Extract standard mapped variables - for (const mapping of theme.variableMappings) { - const value = getComputedStyle(document.documentElement).getPropertyValue(mapping.cssVariable); - let processedValue = value?.trim(); - - if (processedValue && processedValue !== 'initial' && processedValue !== 'inherit') { - // Apply transformation if available - if (mapping.transform) { - processedValue = mapping.transform(processedValue); - } - variables.set(mapping.cssVariable, processedValue); - } else if (mapping.fallbackValue) { - variables.set(mapping.cssVariable, mapping.fallbackValue); - } - } - - // Run custom extraction if available - if (theme.customExtraction) { - const extractor = new CSSExtractor(this.app); - const customVariables = await theme.customExtraction(extractor); - - for (const [key, value] of customVariables) { - variables.set(key, value); - } - } - - return variables; - } - - /** - * Get current theme detection result - */ - public getCurrentTheme(): ThemeDetectionResult | null { - return this.currentTheme; - } - - /** - * Get theme-specific Typst style rules - */ - public async generateThemeStyleRules(mapper: CSSToTypstMapper): Promise { - const currentTheme = await this.detectCurrentTheme(); - if (!currentTheme) return []; - - const rules: TypstStyleRule[] = []; - - // Convert theme variables to Typst properties - for (const mapping of currentTheme.theme.variableMappings) { - const cssValue = currentTheme.variables.get(mapping.cssVariable); - if (cssValue) { - // Map CSS property to Typst - const mappedProperty = mapper['mapCSSProperty']?.call( - mapper, - mapping.typstProperty === 'fill' ? 'color' : mapping.typstProperty, - cssValue, - { simplifyColors: true } - ); - - if (mappedProperty) { - rules.push({ - type: 'set', - target: 'text', - properties: mappedProperty - }); - } - } - } - - // Add theme-specific rules - const themeRules = this.getThemeSpecificRules(currentTheme.theme.name); - rules.push(...themeRules); - - return rules; - } - - /** - * Get theme-specific style rules - */ - private getThemeSpecificRules(themeName: string): TypstStyleRule[] { - const rules: TypstStyleRule[] = []; - - switch (themeName) { - case 'minimal': - // Minimal theme tends to use clean typography - rules.push({ - type: 'set', - target: 'heading', - properties: { - weight: '"regular"' - } - }); - break; - - case 'blue-topaz': - // Blue Topaz uses distinctive heading colors - rules.push({ - type: 'show', - target: 'heading', - properties: { - fill: 'rgb(8, 109, 221)' - }, - condition: 'heading.where(level: 1)' - }); - break; - - case 'sanctum': - // Dark theme adjustments - rules.push({ - type: 'set', - target: 'text', - properties: { - fill: 'rgb(220, 220, 220)' - } - }); - break; - } - - return rules; - } - - /** - * Watch for theme changes - */ - public watchThemeChanges(callback: (theme: ThemeDetectionResult | null) => void): void { - // Listen for CSS changes that might indicate theme switch - this.app.workspace.on('css-change', async () => { - const newTheme = await this.detectCurrentTheme(); - - // Check if theme actually changed - if (!this.currentTheme && !newTheme) return; - if (this.currentTheme && newTheme && this.currentTheme.theme.name === newTheme.theme.name) return; - - this.currentTheme = newTheme; - callback(newTheme); - }); - - // Listen for setting changes that might affect theme - if (this.app.setting) { - this.app.setting.on('change', async () => { - // Debounce theme detection - setTimeout(async () => { - const newTheme = await this.detectCurrentTheme(); - if (!this.currentTheme || !newTheme || this.currentTheme.theme.name !== newTheme.theme.name) { - this.currentTheme = newTheme; - callback(newTheme); - } - }, 100); - }); - } - } - - /** - * Get all registered themes - */ - public getRegisteredThemes(): ThemeProfile[] { - return Array.from(this.registeredThemes.values()); - } - - /** - * Get theme by name - */ - public getTheme(name: string): ThemeProfile | null { - return this.registeredThemes.get(name) || null; - } - - /** - * Clear variable cache - */ - public clearCache(): void { - this.variableCache.clear(); - } - - /** - * Force refresh current theme detection - */ - public async refreshCurrentTheme(): Promise { - this.clearCache(); - return await this.detectCurrentTheme(); - } - - /** - * Get variable value with caching - */ - public getCachedVariable(name: string): string | null { - if (this.variableCache.has(name)) { - return this.variableCache.get(name)!; - } - - const value = getComputedStyle(document.documentElement).getPropertyValue(name)?.trim(); - if (value && value !== 'initial' && value !== 'inherit') { - this.variableCache.set(name, value); - return value; - } - - return null; - } - - /** - * Generate theme-aware Typst template header - */ - public generateThemeHeader(): string { - const currentTheme = this.getCurrentTheme(); - if (!currentTheme) { - return '// Default Obsidian styling\n'; - } - - const lines: string[] = [ - `// Theme: ${currentTheme.theme.displayName}`, - `// Detected with confidence: ${Math.round(currentTheme.confidence * 100)}%`, - '' - ]; - - // Add key theme variables as comments - for (const [variable, value] of currentTheme.variables) { - if (variable.startsWith('--text-') || variable.startsWith('--background-')) { - lines.push(`// ${variable}: ${value}`); - } - } - - return lines.join('\n') + '\n'; - } -} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 6c85566..0000000 --- a/src/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Template System Exports -export { TemplateManager } from './template-manager'; -export { TemplateSubstitution } from './template-substitution'; -export { TemplateValidator } from './template-validator'; - -// CSS Extraction and Style Preservation System Exports -export { CSSExtractor } from './CSSExtractor'; -export { CSSToTypstMapper } from './CSSToTypstMapper'; -export { ThemeManager } from './ThemeManager'; -export { PopularThemeSupport } from './PopularThemeSupport'; -export { PluginSpecificStyleHandler } from './PluginSpecificStyleHandler'; -export { HybridExportMode } from './HybridExportMode'; - -// Type Exports -export type { - Template, - TemplateVariable, - TemplateMetadata, - TemplateValidationResult, - SubstitutionContext -} from './types'; - -// CSS System Type Exports -export type { - ExtractedStyle, - ThemeInfo, - CSSExtractionOptions, - TypstStyleRule, - MappingOptions, - ColorFormat, - ThemeVariableMapping, - ThemeProfile, - ThemeDetectionResult, - EnhancedThemeProfile, - ThemeCustomization, - ThemeTestResult, - PluginStyleProfile, - PluginDetectionResult, - HybridExportOptions, - HybridStyleResult, - StyleConflict, - ConflictResolution -} from './CSSExtractor'; \ No newline at end of file diff --git a/src/template-manager.ts b/src/template-manager.ts deleted file mode 100644 index 632ab69..0000000 --- a/src/template-manager.ts +++ /dev/null @@ -1,752 +0,0 @@ -import { App, normalizePath, TFile, TFolder, Notice } from 'obsidian'; -import { Template, TemplateVariable, TemplateMetadata, TemplateValidationResult, SubstitutionContext } from './types'; -import { TemplateSubstitution } from './template-substitution'; -import { TemplateValidator } from './template-validator'; -import * as path from 'path'; - -/** - * Manages Typst templates, including built-in and custom user templates - */ -export class TemplateManager { - private app: App; - private pluginDir: string; - private builtInTemplateNames: string[] = ['default.typ', 'article.typ', 'report.typ', 'modern.typ']; - private customTemplates: Map = new Map(); - private customTemplateDirectory: string = 'Typst Templates'; - - constructor(app: App, pluginDir: string, customTemplateDirectory?: string) { - this.app = app; - this.pluginDir = pluginDir; - if (customTemplateDirectory) { - this.customTemplateDirectory = customTemplateDirectory; - } - } - - /** - * Get the absolute path to a built-in template file - */ - private getBuiltInTemplatePath(templateName: string): string { - return path.join(this.pluginDir, 'templates', templateName); - } - - /** - * Check if a file exists using Node.js fs (for built-in templates) - */ - private async fileExists(filePath: string): Promise { - try { - const fs = require('fs').promises; - await fs.access(filePath); - return true; - } catch { - return false; - } - } - - /** - * Read a file using Node.js fs (for built-in templates) - */ - private async readFile(filePath: string): Promise { - const fs = require('fs').promises; - return await fs.readFile(filePath, 'utf8'); - } - - /** - * Initialize built-in Typst templates (now reads from disk) - */ - private async initializeBuiltInTemplates(): Promise { - // Built-in templates are now stored as files in templates/ directory - // This method verifies they exist and are accessible - } - - /** - * Get available template names - */ - async getAvailableTemplates(): Promise { - const builtIn: string[] = []; - - console.log('TemplateManager: Getting available templates...'); - console.log('Plugin dir:', this.pluginDir); - - // Check which built-in templates exist - for (const templateName of this.builtInTemplateNames) { - const templatePath = this.getBuiltInTemplatePath(templateName); - console.log(`Checking template: ${templateName} at path: ${templatePath}`); - const exists = await this.fileExists(templatePath); - console.log(`Template ${templateName} exists: ${exists}`); - if (exists) { - builtIn.push(templateName); - } - } - - const custom = Array.from(this.customTemplates.keys()).map(name => `${name}.typ`); - console.log('Built-in templates found:', builtIn); - console.log('Custom templates found:', custom); - return [...builtIn, ...custom]; - } - - /** - * Get template file path by name (for use with Pandoc) - */ - getTemplatePath(templateName: string): string | null { - // Check built-in templates first - if (this.builtInTemplateNames.includes(templateName)) { - // Return relative path for Typst templates (not absolute) - // This is because Pandoc + Typst expects relative paths - return `templates/${templateName}`; - } - - // Check custom templates - const customKey = templateName.replace('.typ', ''); - if (this.customTemplates.has(customKey)) { - const template = this.customTemplates.get(customKey); - return template?.filePath || null; - } - - return null; - } - - /** - * Check if a template exists - */ - async hasTemplate(templateName: string): Promise { - // Check built-in templates - if (this.builtInTemplateNames.includes(templateName)) { - const templatePath = this.getBuiltInTemplatePath(templateName); - return await this.fileExists(templatePath); - } - - // Check custom templates - return this.customTemplates.has(templateName.replace('.typ', '')); - } - - /** - * Get template metadata - */ - async getTemplateInfo(templateName: string): Promise | null> { - if (this.builtInTemplateNames.includes(templateName)) { - try { - const templatePath = this.getBuiltInTemplatePath(templateName); - const content = await this.readFile(templatePath); - return { - name: templateName.replace('.typ', ''), - variables: this.extractVariables(content), - metadata: { - author: 'Obsidian Typst PDF Export', - version: '1.0.0', - description: this.getBuiltInDescription(templateName), - compatibility: ['0.11.0', '0.12.0'] - } - }; - } catch (error) { - console.error(`Error reading built-in template ${templateName}:`, error); - return null; - } - } - - const customKey = templateName.replace('.typ', ''); - if (this.customTemplates.has(customKey)) { - return this.customTemplates.get(customKey) || null; - } - - return null; - } - - /** - * Extract variables from template content - */ - private extractVariables(templateContent: string): Record { - const variables: Record = {}; - const variablePattern = /\$(\w+)\$/g; - let match; - - while ((match = variablePattern.exec(templateContent)) !== null) { - const varName = match[1]; - variables[varName] = { - type: 'string', - defaultValue: '', - description: this.getVariableDescription(varName), - required: this.isVariableRequired(varName, templateContent) - }; - } - - return variables; - } - - /** - * Get description for common template variables - */ - private getVariableDescription(varName: string): string { - const descriptions: Record = { - 'title': 'Document title', - 'author': 'Document author', - 'date': 'Document date', - 'body': 'Main document content', - 'font': 'Font family', - 'fontSize': 'Font size', - 'pageSize': 'Page size (e.g., a4, us-letter)', - 'margins': 'Page margins' - }; - - return descriptions[varName] || `Template variable: ${varName}`; - } - - /** - * Check if a variable is required based on template usage - */ - private isVariableRequired(varName: string, templateContent: string): boolean { - // Body is always required - if (varName === 'body') return true; - - // Check if variable is used in conditional blocks - const conditionalPattern = new RegExp(`#if.*\\$${varName}\\$.*!=.*""`, 'g'); - return !conditionalPattern.test(templateContent); - } - - /** - * Get built-in template descriptions - */ - private getBuiltInDescription(templateName: string): string { - const descriptions: Record = { - 'default.typ': 'Basic document template with title, author, and date', - 'article.typ': 'Academic article template with proper formatting', - 'report.typ': 'Formal report template with title page and headers', - 'single-page.typ': 'Single page template with auto-adjusting height' - }; - - return descriptions[templateName] || 'Built-in Typst template'; - } - - /** - * Discover and load custom templates from the configured directory - */ - async discoverCustomTemplates(): Promise { - try { - const templateFolder = this.app.vault.getAbstractFileByPath(this.customTemplateDirectory); - - if (!templateFolder || !(templateFolder instanceof TFolder)) { - // Create the template directory if it doesn't exist - await this.createTemplateDirectory(); - return; - } - - // Clear existing custom templates - this.customTemplates.clear(); - - // Process all .typ files in the directory - const typFiles = templateFolder.children.filter( - (file): file is TFile => file instanceof TFile && file.extension === 'typ' - ); - - for (const file of typFiles) { - await this.loadCustomTemplate(file); - } - - } catch (error) { - console.error('Error discovering custom templates:', error); - new Notice('Failed to discover custom templates'); - } - } - - /** - * Load a custom template from a file - */ - private async loadCustomTemplate(file: TFile): Promise { - try { - const content = await this.app.vault.read(file); - const templateName = file.basename; - - // Extract metadata from template comments - const metadata = this.extractTemplateMetadata(content, file); - - // Extract variables from template - const variables = this.extractTemplateVariables(content); - - const template: Template = { - name: templateName, - filePath: file.path, - variables, - metadata - }; - - this.customTemplates.set(templateName, template); - - } catch (error) { - console.error(`Error loading custom template ${file.path}:`, error); - } - } - - /** - * Extract metadata from template comments - */ - private extractTemplateMetadata(content: string, file: TFile): TemplateMetadata { - const metadata: TemplateMetadata = { - compatibility: ['0.11.0', '0.12.0'] - }; - - // Look for metadata in comments at the top of the file - const lines = content.split('\n'); - let inMetadataBlock = false; - - for (const line of lines) { - const trimmed = line.trim(); - - // Check for metadata block start - if (trimmed.startsWith('/*') && trimmed.includes('@template-meta')) { - inMetadataBlock = true; - continue; - } - - // Check for metadata block end - if (trimmed.includes('*/')) { - inMetadataBlock = false; - continue; - } - - if (inMetadataBlock) { - // Parse metadata lines - const metaMatch = trimmed.match(/^\s*\*?\s*@(\w+):\s*(.+)$/); - if (metaMatch) { - const [, key, value] = metaMatch; - switch (key) { - case 'author': - metadata.author = value.trim(); - break; - case 'version': - metadata.version = value.trim(); - break; - case 'description': - metadata.description = value.trim(); - break; - case 'compatibility': - metadata.compatibility = value.split(',').map(v => v.trim()); - break; - } - } - } - } - - // Set defaults if not found - if (!metadata.description) { - metadata.description = `Custom template: ${file.basename}`; - } - if (!metadata.author) { - metadata.author = 'Custom'; - } - if (!metadata.version) { - metadata.version = '1.0.0'; - } - - return metadata; - } - - /** - * Extract variables from template with enhanced detection - */ - private extractTemplateVariables(content: string): Record { - const variables: Record = {}; - const foundVariables = TemplateSubstitution.extractVariables(content); - - for (const varName of foundVariables) { - variables[varName] = { - type: this.inferVariableType(varName), - defaultValue: this.getDefaultValueForVariable(varName), - description: this.getVariableDescription(varName), - required: this.isVariableRequired(varName, content) - }; - } - - return variables; - } - - /** - * Infer variable type based on name patterns - */ - private inferVariableType(varName: string): 'string' | 'number' | 'boolean' { - const numberPatterns = /^(size|width|height|margin|count|number|page)/i; - const booleanPatterns = /^(show|hide|enable|disable|is|has)/i; - - if (numberPatterns.test(varName)) return 'number'; - if (booleanPatterns.test(varName)) return 'boolean'; - return 'string'; - } - - /** - * Get default value based on variable type and name - */ - private getDefaultValueForVariable(varName: string): any { - const type = this.inferVariableType(varName); - - if (type === 'boolean') return false; - if (type === 'number') { - if (varName.includes('size')) return 12; - if (varName.includes('margin')) return 2.5; - return 0; - } - - // String defaults - const stringDefaults: Record = { - 'title': '', - 'author': '', - 'date': new Date().toLocaleDateString(), - 'font': 'Liberation Serif', - 'fontSize': '12pt', - 'pageSize': 'a4', - 'margins': '2.5cm', - 'body': '' - }; - - return stringDefaults[varName] || ''; - } - - /** - * Create the template directory if it doesn't exist - */ - private async createTemplateDirectory(): Promise { - try { - await this.app.vault.createFolder(this.customTemplateDirectory); - - // Create a sample template - const sampleTemplate = `/* -@template-meta -@author: Your Name -@version: 1.0.0 -@description: Sample custom template -@compatibility: 0.11.0, 0.12.0 -*/ - -#set page( - paper: "a4", - margin: (x: 2.5cm, y: 2cm) -) -#set text( - font: "$font$", - size: 12pt, - lang: "en" -) -#set par(justify: true) - -#if "$title$" != "" [ - #align(center, text(16pt, weight: "bold")[$title$]) - #v(1em) -] - -$body$`; - - const samplePath = normalizePath(`${this.customTemplateDirectory}/sample.typ`); - await this.app.vault.create(samplePath, sampleTemplate); - - new Notice(`Created template directory at: ${this.customTemplateDirectory}`); - - } catch (error) { - console.error('Error creating template directory:', error); - } - } - - /** - * Get custom template directory path - */ - getCustomTemplateDirectory(): string { - return this.customTemplateDirectory; - } - - /** - * Set custom template directory and refresh templates - */ - async setCustomTemplateDirectory(directory: string): Promise { - this.customTemplateDirectory = directory; - await this.discoverCustomTemplates(); - } - - /** - * Refresh custom templates (re-scan directory) - */ - async refreshCustomTemplates(): Promise { - await this.discoverCustomTemplates(); - new Notice('Custom templates refreshed'); - } - - /** - * Get template content by name (enhanced to handle custom templates) - */ - async getTemplateContent(templateName: string): Promise { - // Check built-in templates first - if (this.builtInTemplateNames.includes(templateName)) { - try { - const templatePath = this.getBuiltInTemplatePath(templateName); - return await this.readFile(templatePath); - } catch (error) { - console.error(`Error reading built-in template ${templateName}:`, error); - return null; - } - } - - // Check custom templates - const customKey = templateName.replace('.typ', ''); - if (this.customTemplates.has(customKey)) { - const template = this.customTemplates.get(customKey); - if (template) { - try { - const file = this.app.vault.getAbstractFileByPath(template.filePath) as TFile; - if (file) { - return await this.app.vault.read(file); - } - } catch (error) { - console.error(`Error reading custom template ${template.filePath}:`, error); - } - } - } - - return null; - } - - /** - * Check if custom templates directory exists - */ - customTemplateDirectoryExists(): boolean { - const folder = this.app.vault.getAbstractFileByPath(this.customTemplateDirectory); - return folder instanceof TFolder; - } - - /** - * Validate a template by name - */ - async validateTemplate(templateName: string, context?: SubstitutionContext): Promise { - const templateContent = await this.getTemplateContent(templateName); - - if (!templateContent) { - return { - isValid: false, - errors: [`Template '${templateName}' not found`], - warnings: [], - variables: [] - }; - } - - return TemplateValidator.validateTemplate(templateContent, context); - } - - /** - * Validate all templates and return a summary - */ - async validateAllTemplates(): Promise<{ - builtInResults: Map; - customResults: Map; - summary: { - totalTemplates: number; - validTemplates: number; - invalidTemplates: number; - templatesWithWarnings: number; - }; - }> { - const builtInResults = new Map(); - const customResults = new Map(); - - // Validate built-in templates - for (const templateName of this.builtInTemplateNames) { - try { - const templatePath = this.getBuiltInTemplatePath(templateName); - const content = await this.readFile(templatePath); - const result = TemplateValidator.validateTemplate(content); - builtInResults.set(templateName, result); - } catch (error) { - builtInResults.set(templateName, { - isValid: false, - errors: [`Error loading template: ${error.message}`], - warnings: [], - variables: [] - }); - } - } - - // Validate custom templates - for (const [templateName, template] of this.customTemplates) { - try { - const content = await this.getTemplateContent(templateName + '.typ'); - if (content) { - const result = TemplateValidator.validateTemplate(content); - customResults.set(templateName, result); - } - } catch (error) { - customResults.set(templateName, { - isValid: false, - errors: [`Error loading template: ${error.message}`], - warnings: [], - variables: [] - }); - } - } - - // Calculate summary - const allResults = [...builtInResults.values(), ...customResults.values()]; - const summary = { - totalTemplates: allResults.length, - validTemplates: allResults.filter(r => r.isValid).length, - invalidTemplates: allResults.filter(r => !r.isValid).length, - templatesWithWarnings: allResults.filter(r => r.warnings.length > 0).length - }; - - return { builtInResults, customResults, summary }; - } - - /** - * Process template with variable substitution and validation - */ - async processTemplate(templateName: string, context: SubstitutionContext): Promise<{ - content: string; - validation: TemplateValidationResult; - }> { - const templateContent = await this.getTemplateContent(templateName); - - if (!templateContent) { - throw new Error(`Template '${templateName}' not found`); - } - - // Validate template with context - const validation = TemplateValidator.validateTemplate(templateContent, context); - - if (!validation.isValid) { - const errorMsg = `Template validation failed: ${validation.errors.join(', ')}`; - throw new Error(errorMsg); - } - - // Substitute variables - const processedContent = TemplateSubstitution.substitute(templateContent, context); - - return { - content: processedContent, - validation - }; - } - - /** - * Preview template processing without throwing errors - */ - async previewTemplate(templateName: string, context: SubstitutionContext): Promise<{ - content: string; - validation: TemplateValidationResult; - substitutions: { variable: string; value: string }[]; - }> { - const templateContent = await this.getTemplateContent(templateName); - - if (!templateContent) { - return { - content: '', - validation: { - isValid: false, - errors: [`Template '${templateName}' not found`], - warnings: [], - variables: [] - }, - substitutions: [] - }; - } - - // Validate template - const validation = TemplateValidator.validateTemplate(templateContent, context); - - // Preview substitution - const { preview, substitutions } = TemplateSubstitution.previewSubstitution(templateContent, context); - - return { - content: preview, - validation, - substitutions - }; - } - - /** - * Get detailed template analysis - */ - async analyzeTemplate(templateName: string): Promise<{ - info: Partial