Delete Unused Code

This commit is contained in:
AlexKucera committed 2025-09-03 19:23:44 +02:00
1 parent 42ad862ba0
commit ccc0e5aec6
11 files changed
-5974

No files matched your search

-393
View File
@@ -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<string, string>;
}
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<string, ExtractedStyle[]> = new Map();
private themeVariables: Map<string, string> = 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<ExtractedStyle[]> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
// 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<string, string> {
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<string, ExtractedStyle[]> {
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<typeof contentType, string[]> = {
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<string, string>;
fontOverrides?: Record<string, string>;
spacingOverrides?: Record<string, string>;
customCSS?: string;
}
export type ConflictResolution = 'user' | 'theme' | 'merge' | 'skip';
-737
View File
@@ -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<string, string>;
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<string, ColorRgb>();
constructor() {}
/**
* Map extracted styles to Typst style rules
*/
public mapToTypst(styles: ExtractedStyle[], options: MappingOptions = {}): TypstStyleRule[] {
const rules: TypstStyleRule[] = [];
const processedSelectors = new Set<string>();
// 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<string, string> = {};
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<string, ExtractedStyle[]> {
const grouped = new Map<string, ExtractedStyle[]>();
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<string, string> | null {
const result: Record<string, string> = {};
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<string, ColorRgb> = {
'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<string, string> = {
'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<string, string> = {
'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<string, string> = {
'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<string, string> = {
'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<string, string> | null {
if (!decoration || decoration === 'none' || decoration === 'inherit') return null;
const result: Record<string, string> = {};
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<string, string> | null {
if (!value || value === '0' || value === 'inherit') return null;
// For block elements, margins translate to above/below spacing
const result: Record<string, string> = {};
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');
}
}
-578
View File
@@ -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<DependencyConfig> = {}): Promise<DependencyCheckResult> {
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<DependencyConfig> = {}): Promise<DependencyCheckResult> {
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<DependencyConfig> = {}): Promise<DependencyCheckResult> {
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<DependencyConfig> = {},
typstConfig: Partial<DependencyConfig> = {},
imagemagickConfig: Partial<DependencyConfig> = {}
): 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<DependencyCheckResult> {
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<string | null> {
// 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<string | null> {
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<boolean> {
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<string | null> {
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;
}
}
-776
View File
@@ -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<HybridStyleResult> {
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<TypstStyleRule[]> {
const rules: TypstStyleRule[] = [];
const processedSelectors = new Set<string>();
// 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<string, string> = {};
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<string, ExtractedStyle[]> {
const grouped = new Map<string, ExtractedStyle[]>();
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<string, string>,
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<string, string>,
intensity: 'minimal' | 'moderate' | 'full'
): Record<string, string> {
const filtered: Record<string, string> = {};
// 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<string, string> = {
'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<string, TypstStyleRule[]>();
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, string>): 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
};
}
}
-671
View File
@@ -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<ExtractedStyle[]>;
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<string, PluginStyleProfile> = new Map();
private activePlugins: Set<string> = 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<string, string> = {};
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<PluginDetectionResult[]> {
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<PluginDetectionResult> {
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<ExtractedStyle[]> {
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<string, number>;
}> {
const detectionResults = await this.detectActivePlugins();
const supportedPlugins: string[] = [];
const unsupportedPlugins: string[] = [];
const styleExtractionResults: Record<string, number> = {};
// 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
});
}
}
-733
View File
@@ -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<TypstStyleRule[]>;
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<string, EnhancedThemeProfile> = 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<TypstStyleRule[]> {
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<TypstStyleRule[]> {
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<TypstStyleRule[]> {
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<TypstStyleRule[]> {
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<TypstStyleRule[]> {
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<ThemeTestResult> {
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<string, EnhancedThemeProfile> {
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<string, string> = {
'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
};
}
}
-585
View File
@@ -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<Map<string, string>>;
priority?: number; // Higher priority themes override lower ones
}
export interface ThemeDetectionResult {
theme: ThemeProfile;
confidence: number; // 0-1 score of detection confidence
variables: Map<string, string>;
}
/**
* Manages theme-specific variable handling and detection
*/
export class ThemeManager {
private app: any;
private registeredThemes: Map<string, ThemeProfile> = new Map();
private variableCache: Map<string, string> = 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<string, string>();
// 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<string, string>();
// 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<ThemeDetectionResult | null> {
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<Map<string, string>> {
const variables = new Map<string, string>();
// 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<TypstStyleRule[]> {
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<ThemeDetectionResult | null> {
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';
}
}
-43
View File
@@ -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';
-752
View File
@@ -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<string, Template> = 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<boolean> {
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<string> {
const fs = require('fs').promises;
return await fs.readFile(filePath, 'utf8');
}
/**
* Initialize built-in Typst templates (now reads from disk)
*/
private async initializeBuiltInTemplates(): Promise<void> {
// 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<string[]> {
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<boolean> {
// 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<Partial<Template> | 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<string, any> {
const variables: Record<string, any> = {};
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<string, string> = {
'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<string, string> = {
'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<void> {
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<void> {
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<string, TemplateVariable> {
const variables: Record<string, TemplateVariable> = {};
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<string, string> = {
'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<void> {
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<void> {
this.customTemplateDirectory = directory;
await this.discoverCustomTemplates();
}
/**
* Refresh custom templates (re-scan directory)
*/
async refreshCustomTemplates(): Promise<void> {
await this.discoverCustomTemplates();
new Notice('Custom templates refreshed');
}
/**
* Get template content by name (enhanced to handle custom templates)
*/
async getTemplateContent(templateName: string): Promise<string | null> {
// 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<TemplateValidationResult> {
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<string, TemplateValidationResult>;
customResults: Map<string, TemplateValidationResult>;
summary: {
totalTemplates: number;
validTemplates: number;
invalidTemplates: number;
templatesWithWarnings: number;
};
}> {
const builtInResults = new Map<string, TemplateValidationResult>();
const customResults = new Map<string, TemplateValidationResult>();
// 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<Template>;
analysis: {
totalVariables: number;
uniqueVariables: string[];
requiredVariables: string[];
optionalVariables: string[];
variableFrequency: Record<string, number>;
};
validation: TemplateValidationResult;
}> {
const templateContent = await this.getTemplateContent(templateName);
const info = await this.getTemplateInfo(templateName);
if (!templateContent) {
throw new Error(`Template '${templateName}' not found`);
}
const analysis = TemplateSubstitution.analyzeTemplate(templateContent);
const validation = TemplateValidator.validateTemplate(templateContent);
return {
info: info || {},
analysis,
validation
};
}
/**
* Check template health and compatibility
*/
async checkTemplateHealth(templateName: string): Promise<{
isHealthy: boolean;
issues: string[];
recommendations: string[];
compatibility: {
typstVersion: string[];
features: string[];
};
}> {
const templateContent = await this.getTemplateContent(templateName);
if (!templateContent) {
return {
isHealthy: false,
issues: [`Template '${templateName}' not found`],
recommendations: [],
compatibility: { typstVersion: [], features: [] }
};
}
const validation = TemplateValidator.validateTemplate(templateContent);
const issues: string[] = [...validation.errors, ...validation.warnings];
const recommendations: string[] = [];
// Add specific recommendations based on analysis
if (!templateContent.includes('#set page')) {
recommendations.push('Consider adding page setup (#set page) for better layout control');
}
if (!templateContent.includes('#set text')) {
recommendations.push('Consider adding text configuration (#set text) for consistent typography');
}
if (validation.variables.length === 1 && validation.variables[0] === 'body') {
recommendations.push('Template only uses body variable. Consider adding title, author, or date variables for more flexibility');
}
// Detect compatibility requirements
const typstVersions = ['0.11.0', '0.12.0'];
const features: string[] = [];
if (templateContent.includes('height: auto')) {
features.push('Dynamic page height');
}
if (templateContent.includes('#context')) {
features.push('Context blocks');
}
if (templateContent.includes('scope: "parent"')) {
features.push('Parent scope placement');
}
return {
isHealthy: validation.isValid && validation.warnings.length === 0,
issues,
recommendations,
compatibility: {
typstVersion: typstVersions,
features
}
};
}
}
-243
View File
@@ -1,243 +0,0 @@
import { SubstitutionContext, TemplateValidationResult } from './types';
/**
* Handles variable substitution in Typst templates
*/
export class TemplateSubstitution {
/**
* Substitute variables in template content
*/
static substitute(templateContent: string, context: SubstitutionContext): string {
let result = templateContent;
// Extract all variables from template
const variables = this.extractVariables(templateContent);
// Process each variable
for (const variable of variables) {
const value = context[variable] || this.getDefaultValue(variable);
const escapedValue = this.escapeTypstValue(value);
// Replace all instances of the variable
const variablePattern = new RegExp(`\\$${variable}\\$`, 'g');
result = result.replace(variablePattern, escapedValue);
}
return result;
}
/**
* Extract all variables from template content
*/
static extractVariables(templateContent: string): string[] {
const variables: string[] = [];
const variablePattern = /\$(\w+)\$/g;
let match;
while ((match = variablePattern.exec(templateContent)) !== null) {
const varName = match[1];
if (!variables.includes(varName)) {
variables.push(varName);
}
}
return variables;
}
/**
* Validate template and check for missing variables
*/
static validate(templateContent: string, context: SubstitutionContext): TemplateValidationResult {
const result: TemplateValidationResult = {
isValid: true,
errors: [],
warnings: [],
variables: []
};
// Extract variables from template
const templateVariables = this.extractVariables(templateContent);
result.variables = templateVariables;
// Check for required variables
const requiredVariables = ['body']; // body is always required
for (const variable of requiredVariables) {
if (templateVariables.includes(variable) && !context[variable]) {
result.errors.push(`Required variable '${variable}' is missing`);
result.isValid = false;
}
}
// Check for undefined variables
for (const variable of templateVariables) {
if (!context[variable] && !this.hasDefaultValue(variable)) {
result.warnings.push(`Variable '${variable}' is undefined and has no default value`);
}
}
// Basic syntax validation
try {
this.validateTypstSyntax(templateContent);
} catch (error) {
result.errors.push(`Template syntax error: ${error.message}`);
result.isValid = false;
}
return result;
}
/**
* Get default value for common variables
*/
private static getDefaultValue(variable: string): string {
const defaults: Record<string, string> = {
'title': '',
'author': '',
'date': new Date().toLocaleDateString(),
'font': 'Liberation Serif',
'fontSize': '12pt',
'pageSize': 'a4',
'margins': '2.5cm',
'body': ''
};
return defaults[variable] || '';
}
/**
* Check if variable has a default value
*/
private static hasDefaultValue(variable: string): boolean {
const defaults = ['title', 'author', 'date', 'font', 'fontSize', 'pageSize', 'margins'];
return defaults.includes(variable);
}
/**
* Escape special characters for Typst
*/
private static escapeTypstValue(value: string): string {
if (!value) return '';
// Escape special Typst characters
return value
.replace(/\\/g, '\\\\') // Escape backslashes
.replace(/\$/g, '\\$') // Escape dollar signs
.replace(/#/g, '\\#') // Escape hash symbols
.replace(/\[/g, '\\[') // Escape square brackets
.replace(/\]/g, '\\]')
.replace(/\{/g, '\\{') // Escape curly braces
.replace(/\}/g, '\\}')
.replace(/</g, '\\<') // Escape angle brackets
.replace(/>/g, '\\>');
}
/**
* Basic Typst syntax validation
*/
private static validateTypstSyntax(templateContent: string): void {
const errors: string[] = [];
// Check for balanced brackets
const brackets = [
{ open: '{', close: '}', name: 'curly braces' },
{ open: '[', close: ']', name: 'square brackets' },
{ open: '(', close: ')', name: 'parentheses' }
];
for (const bracket of brackets) {
const openCount = (templateContent.match(new RegExp(`\\${bracket.open}`, 'g')) || []).length;
const closeCount = (templateContent.match(new RegExp(`\\${bracket.close}`, 'g')) || []).length;
if (openCount !== closeCount) {
errors.push(`Unbalanced ${bracket.name}: ${openCount} opening, ${closeCount} closing`);
}
}
// Check for malformed function calls
const malformedFunctionPattern = /#\w+\s*\(/g;
let match;
while ((match = malformedFunctionPattern.exec(templateContent)) !== null) {
// This is a basic check - in practice, we'd need a more sophisticated parser
const functionCall = match[0];
if (!this.isValidTypstFunction(functionCall)) {
errors.push(`Potentially malformed function call: ${functionCall}`);
}
}
if (errors.length > 0) {
throw new Error(errors.join('; '));
}
}
/**
* Check if a function call looks valid (basic heuristic)
*/
private static isValidTypstFunction(functionCall: string): boolean {
const knownFunctions = [
'set', 'show', 'let', 'if', 'for', 'while', 'import', 'include',
'text', 'page', 'par', 'heading', 'align', 'block', 'box', 'grid',
'table', 'image', 'link', 'counter', 'context', 'place', 'lorem'
];
const functionName = functionCall.replace('#', '').replace(/\s*\($/, '');
return knownFunctions.includes(functionName);
}
/**
* Preview substitution without applying it
*/
static previewSubstitution(templateContent: string, context: SubstitutionContext): {
preview: string;
substitutions: { variable: string; value: string }[];
} {
const variables = this.extractVariables(templateContent);
const substitutions = variables.map(variable => ({
variable,
value: context[variable] || this.getDefaultValue(variable)
}));
const preview = this.substitute(templateContent, context);
return { preview, substitutions };
}
/**
* Get variable usage statistics from template
*/
static analyzeTemplate(templateContent: string): {
totalVariables: number;
uniqueVariables: string[];
requiredVariables: string[];
optionalVariables: string[];
variableFrequency: Record<string, number>;
} {
const allVariables = [];
const variablePattern = /\$(\w+)\$/g;
let match;
// Count all variable occurrences
while ((match = variablePattern.exec(templateContent)) !== null) {
allVariables.push(match[1]);
}
const uniqueVariables = [...new Set(allVariables)];
const requiredVariables = ['body'];
const optionalVariables = uniqueVariables.filter(v => !requiredVariables.includes(v));
// Count frequency
const variableFrequency: Record<string, number> = {};
for (const variable of allVariables) {
variableFrequency[variable] = (variableFrequency[variable] || 0) + 1;
}
return {
totalVariables: allVariables.length,
uniqueVariables,
requiredVariables: requiredVariables.filter(v => uniqueVariables.includes(v)),
optionalVariables,
variableFrequency
};
}
}
-463
View File
@@ -1,463 +0,0 @@
import { TemplateValidationResult, SubstitutionContext } from './types';
import { TemplateSubstitution } from './template-substitution';
import { getValidTypstPaperSizes } from './utils/paperSizeMapper';
/**
* Comprehensive template validation system
*/
export class TemplateValidator {
/**
* Validate template content comprehensively
*/
static validateTemplate(templateContent: string, context?: SubstitutionContext): TemplateValidationResult {
const result: TemplateValidationResult = {
isValid: true,
errors: [],
warnings: [],
variables: []
};
// Extract variables
result.variables = TemplateSubstitution.extractVariables(templateContent);
// Perform various validation checks
this.validateSyntax(templateContent, result);
this.validateStructure(templateContent, result);
this.validateVariables(templateContent, result, context);
this.validateTypstFeatures(templateContent, result);
this.validatePageSetup(templateContent, result);
// Set overall validity
result.isValid = result.errors.length === 0;
return result;
}
/**
* Validate basic Typst syntax
*/
private static validateSyntax(templateContent: string, result: TemplateValidationResult): void {
// Check for balanced brackets and parentheses
this.validateBrackets(templateContent, result);
// Check for malformed function calls
this.validateFunctionCalls(templateContent, result);
// Check for invalid characters in variable names
this.validateVariableNames(templateContent, result);
// Check for unclosed strings
this.validateStrings(templateContent, result);
}
/**
* Validate bracket balance
*/
private static validateBrackets(templateContent: string, result: TemplateValidationResult): void {
const brackets = [
{ open: '{', close: '}', name: 'curly braces', stack: [] as number[] },
{ open: '[', close: ']', name: 'square brackets', stack: [] as number[] },
{ open: '(', close: ')', name: 'parentheses', stack: [] as number[] }
];
const lines = templateContent.split('\n');
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex];
for (let charIndex = 0; charIndex < line.length; charIndex++) {
const char = line[charIndex];
for (const bracket of brackets) {
if (char === bracket.open) {
bracket.stack.push(lineIndex + 1);
} else if (char === bracket.close) {
if (bracket.stack.length === 0) {
result.errors.push(
`Unmatched closing ${bracket.name} at line ${lineIndex + 1}, column ${charIndex + 1}`
);
} else {
bracket.stack.pop();
}
}
}
}
}
// Check for unclosed brackets
for (const bracket of brackets) {
for (const lineNum of bracket.stack) {
result.errors.push(`Unclosed ${bracket.name} starting at line ${lineNum}`);
}
}
}
/**
* Validate function calls
*/
private static validateFunctionCalls(templateContent: string, result: TemplateValidationResult): void {
const functionPattern = /#(\w+)\s*\(/g;
const knownFunctions = [
'set', 'show', 'let', 'if', 'for', 'while', 'import', 'include',
'text', 'page', 'par', 'heading', 'align', 'block', 'box', 'grid',
'table', 'image', 'link', 'counter', 'context', 'place', 'lorem',
'v', 'h', 'linebreak', 'pagebreak', 'smallcaps', 'emph', 'strong'
];
let match;
while ((match = functionPattern.exec(templateContent)) !== null) {
const functionName = match[1];
if (!knownFunctions.includes(functionName)) {
const lineNum = templateContent.substring(0, match.index).split('\n').length;
result.warnings.push(
`Unknown function '${functionName}' at line ${lineNum}. This may be a custom function or newer Typst feature.`
);
}
}
}
/**
* Validate variable names
*/
private static validateVariableNames(templateContent: string, result: TemplateValidationResult): void {
const variablePattern = /\$(\w*[^a-zA-Z0-9_]\w*|\d+\w*)\$/g;
let match;
while ((match = variablePattern.exec(templateContent)) !== null) {
const varName = match[1];
const lineNum = templateContent.substring(0, match.index).split('\n').length;
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(varName)) {
result.errors.push(
`Invalid variable name '${varName}' at line ${lineNum}. Variable names must start with a letter or underscore and contain only letters, numbers, and underscores.`
);
}
}
}
/**
* Validate string literals
*/
private static validateStrings(templateContent: string, result: TemplateValidationResult): void {
// Check for unclosed string literals
const stringPattern = /"([^"\\]|\\.)*"/g;
const allQuotes = templateContent.match(/"/g);
if (allQuotes && allQuotes.length % 2 !== 0) {
result.errors.push('Unclosed string literal detected');
}
// Check for unclosed content blocks
let bracketCount = 0;
let inString = false;
let escaped = false;
for (let i = 0; i < templateContent.length; i++) {
const char = templateContent[i];
if (escaped) {
escaped = false;
continue;
}
if (char === '\\') {
escaped = true;
continue;
}
if (char === '"') {
inString = !inString;
continue;
}
if (!inString) {
if (char === '[') bracketCount++;
else if (char === ']') bracketCount--;
}
}
if (bracketCount !== 0) {
result.errors.push(`Unbalanced content blocks: ${Math.abs(bracketCount)} ${bracketCount > 0 ? 'unclosed' : 'extra closing'} bracket(s)`);
}
}
/**
* Validate template structure
*/
private static validateStructure(templateContent: string, result: TemplateValidationResult): void {
// Check for body variable (required for all templates)
if (!templateContent.includes('$body$')) {
result.errors.push("Template must contain a '$body$' variable to include the main content");
}
// Warn about missing common structural elements
const commonElements = ['#set page', '#set text', '#set par'];
const missingElements = commonElements.filter(element => !templateContent.includes(element));
if (missingElements.length > 0) {
result.warnings.push(
`Template may be missing common setup: ${missingElements.join(', ')}. This is not an error but may result in default formatting.`
);
}
// Check for potentially problematic patterns
this.validateProblematicPatterns(templateContent, result);
}
/**
* Validate potentially problematic patterns
*/
private static validateProblematicPatterns(templateContent: string, result: TemplateValidationResult): void {
const problematicPatterns = [
{
pattern: /#set\s+page\s*\([^)]*height:\s*auto[^)]*\)/,
message: "Templates with 'height: auto' may not work well with multi-page documents",
type: 'warning' as const
},
{
pattern: /#pagebreak\(\s*weak:\s*false\s*\)/,
message: "Hard page breaks may cause layout issues in generated documents",
type: 'warning' as const
},
{
pattern: /#import\s+[^:]*:/,
message: "Import statements may fail if the imported module is not available",
type: 'warning' as const
},
{
pattern: /\$\w+\$\s*\$\w+\$/,
message: "Adjacent variables without spacing may cause formatting issues",
type: 'warning' as const
}
];
for (const { pattern, message, type } of problematicPatterns) {
if (pattern.test(templateContent)) {
if (type === 'warning') {
result.warnings.push(message);
}
}
}
}
/**
* Validate variables and their usage
*/
private static validateVariables(templateContent: string, result: TemplateValidationResult, context?: SubstitutionContext): void {
const variables = result.variables;
// Check for empty variables
if (variables.length === 0) {
result.warnings.push('Template contains no variables. This may be intentional for static templates.');
}
// Check for duplicate variables (not an error, just inefficient)
const variableCounts = new Map<string, number>();
const variablePattern = /\$(\w+)\$/g;
let match;
while ((match = variablePattern.exec(templateContent)) !== null) {
const varName = match[1];
variableCounts.set(varName, (variableCounts.get(varName) || 0) + 1);
}
// Warn about variables used only once (might be typos)
for (const [varName, count] of variableCounts) {
if (count === 1 && varName !== 'body') {
result.warnings.push(`Variable '${varName}' is used only once. Verify this is intentional.`);
}
}
// If context is provided, validate against it
if (context) {
this.validateAgainstContext(variables, context, result);
}
// Check for common variable name typos
this.validateCommonVariables(variables, result);
}
/**
* Validate variables against substitution context
*/
private static validateAgainstContext(variables: string[], context: SubstitutionContext, result: TemplateValidationResult): void {
const requiredVars = variables.filter(v => v === 'body');
const optionalVars = variables.filter(v => v !== 'body');
// Check required variables
for (const varName of requiredVars) {
if (!context[varName]) {
result.errors.push(`Required variable '${varName}' is missing from context`);
}
}
// Warn about missing optional variables
for (const varName of optionalVars) {
if (!context[varName] && !this.hasImplicitDefault(varName)) {
result.warnings.push(`Optional variable '${varName}' is not provided and has no default value`);
}
}
}
/**
* Check if variable has an implicit default
*/
private static hasImplicitDefault(varName: string): boolean {
const defaultVars = ['title', 'author', 'date', 'font', 'fontSize', 'pageSize', 'margins'];
return defaultVars.includes(varName);
}
/**
* Validate common variable names for typos
*/
private static validateCommonVariables(variables: string[], result: TemplateValidationResult): void {
const commonVars = ['title', 'author', 'date', 'body', 'font', 'fontSize', 'pageSize', 'margins'];
const typoMap = {
'titel': 'title',
'autor': 'author',
'authur': 'author',
'dat': 'date',
'boby': 'body',
'bdy': 'body',
'fontsize': 'fontSize',
'font_size': 'fontSize',
'pagesize': 'pageSize',
'page_size': 'pageSize',
'margin': 'margins'
};
for (const variable of variables) {
if (variable in typoMap) {
result.warnings.push(
`Variable '${variable}' might be a typo. Did you mean '${typoMap[variable as keyof typeof typoMap]}'?`
);
}
}
}
/**
* Validate Typst-specific features
*/
private static validateTypstFeatures(templateContent: string, result: TemplateValidationResult): void {
// Check for version-specific features
this.validateVersionFeatures(templateContent, result);
// Check for proper page setup
this.validatePageFeatures(templateContent, result);
// Check for text formatting
this.validateTextFeatures(templateContent, result);
}
/**
* Validate version-specific features
*/
private static validateVersionFeatures(templateContent: string, result: TemplateValidationResult): void {
const v011Features = [
{ pattern: /height:\s*auto/, feature: 'height: auto (Typst 0.11+)' },
{ pattern: /#context/, feature: 'context blocks (Typst 0.11+)' },
{ pattern: /scope:\s*"parent"/, feature: 'scope: "parent" (Typst 0.11+)' }
];
for (const { pattern, feature } of v011Features) {
if (pattern.test(templateContent)) {
result.warnings.push(`Template uses ${feature}. Ensure Typst version 0.11+ is available.`);
}
}
}
/**
* Validate page setup features
*/
private static validatePageFeatures(templateContent: string, result: TemplateValidationResult): void {
// Check for conflicting page settings
if (templateContent.includes('height: auto') && templateContent.includes('columns:')) {
result.warnings.push('Using both "height: auto" and columns may cause unexpected layout behavior');
}
// Check for invalid paper sizes
const paperSizePattern = /paper:\s*"([^"]+)"/g;
const validPaperSizes = getValidTypstPaperSizes();
let match;
while ((match = paperSizePattern.exec(templateContent)) !== null) {
const paperSize = match[1];
if (!validPaperSizes.includes(paperSize)) {
result.warnings.push(`Unknown paper size '${paperSize}'. Valid sizes: ${validPaperSizes.join(', ')}`);
}
}
}
/**
* Validate text formatting features
*/
private static validateTextFeatures(templateContent: string, result: TemplateValidationResult): void {
// Check for deprecated font syntax
if (templateContent.match(/font:\s*\([^)]*\)/)) {
result.warnings.push('Using tuple syntax for fonts. Consider using string syntax for better compatibility.');
}
// Check for missing language setting
if (!templateContent.includes('lang:') && !templateContent.includes('language:')) {
result.warnings.push('Template does not specify language. Consider adding "lang: \\"en\\"" or appropriate language code.');
}
}
/**
* Validate page setup comprehensively
*/
private static validatePageSetup(templateContent: string, result: TemplateValidationResult): void {
// Check for margin specification
if (templateContent.includes('#set page') && !templateContent.match(/margin:\s*[^,\)]+/)) {
result.warnings.push('Page setup found but no margins specified. Consider setting margins for better layout control.');
}
// Check for header/footer balance
const hasHeader = templateContent.includes('header:');
const hasFooter = templateContent.includes('footer:');
const hasNumbering = templateContent.includes('numbering:');
if ((hasHeader || hasFooter) && !hasNumbering) {
result.warnings.push('Template has header/footer but no page numbering. Consider adding numbering for better navigation.');
}
}
/**
* Quick validation for basic template structure
*/
static quickValidate(templateContent: string): boolean {
// Basic checks for template usability
if (!templateContent.trim()) return false;
if (!templateContent.includes('$body$')) return false;
// Check for basic syntax errors
const openBraces = (templateContent.match(/\{/g) || []).length;
const closeBraces = (templateContent.match(/\}/g) || []).length;
const openBrackets = (templateContent.match(/\[/g) || []).length;
const closeBrackets = (templateContent.match(/\]/g) || []).length;
return openBraces === closeBraces && openBrackets === closeBrackets;
}
/**
* Get validation summary
*/
static getValidationSummary(result: TemplateValidationResult): string {
const { isValid, errors, warnings, variables } = result;
let summary = `Template validation ${isValid ? 'passed' : 'failed'}\n`;
summary += `Found ${variables.length} variables: ${variables.join(', ')}\n`;
if (errors.length > 0) {
summary += `\nErrors (${errors.length}):\n${errors.map(e => `• ${e}`).join('\n')}`;
}
if (warnings.length > 0) {
summary += `\nWarnings (${warnings.length}):\n${warnings.map(w => `• ${w}`).join('\n')}`;
}
return summary;
}
}