/** * Template Engine - Handlebars Template Rendering * * Renders slide data into HTML using Handlebars templates. * Supports custom templates and helper functions. */ import Handlebars from 'handlebars'; import type { Slide, SlideType, ThemeName } from '../types/index.js'; interface TemplateConfig { customTemplates?: Record; theme?: ThemeName; } export class TemplateEngine { private handlebars: typeof Handlebars; private templates: Map; private partials: Map; constructor() { this.handlebars = Handlebars.create(); this.templates = new Map(); this.partials = new Map(); this.registerHelpers(); this.registerPartials(); this.compileTemplates(); } /** * Render a slide to HTML. */ render(slide: Slide, config?: TemplateConfig): string { // Check for custom template override if (config?.customTemplates?.[slide.type]) { const customTemplate = this.handlebars.compile(config.customTemplates[slide.type]); return customTemplate(this.prepareContext(slide, config)); } // Use built-in template const template = this.templates.get(slide.type); if (!template) { console.warn(`No template for slide type: ${slide.type}, using fallback`); return this.renderFallback(slide); } return template(this.prepareContext(slide, config)); } /** * Render multiple slides. */ renderAll(slides: Slide[], config?: TemplateConfig): string[] { return slides.map(slide => this.render(slide, config)); } /** * Prepare template context with computed properties. */ private prepareContext(slide: Slide, config?: TemplateConfig): Record { return { ...slide.data, slideIndex: slide.index, slideType: slide.type, classes: this.buildClassList(slide, config?.theme), styles: this.buildStyleString(slide), hasImage: slide.data.images && slide.data.images.length > 0, hasMetrics: slide.data.metrics && slide.data.metrics.length > 0, hasBullets: slide.data.bullets && slide.data.bullets.length > 0, bulletCount: slide.data.bullets?.length ?? 0, theme: config?.theme ?? 'default' }; } /** * Build CSS class list for slide. */ private buildClassList(slide: Slide, theme?: ThemeName): string { const classes = [ 'slide', `slide-${slide.type}`, ...(slide.classes ?? []) ]; if (theme && theme !== 'default') { classes.push(`theme-${theme}`); } return classes.join(' '); } /** * Build inline style string. */ private buildStyleString(slide: Slide): string { if (!slide.styles) return ''; return Object.entries(slide.styles) .map(([prop, value]) => `${this.kebabCase(prop)}: ${value}`) .join('; '); } /** * Register Handlebars helpers. */ private registerHelpers(): void { // Conditional helper this.handlebars.registerHelper('ifEquals', function(this: unknown, arg1: unknown, arg2: unknown, options: Handlebars.HelperOptions) { return arg1 === arg2 ? options.fn(this) : options.inverse(this); }); // Loop with index this.handlebars.registerHelper('eachWithIndex', function(this: unknown, context: Record[], options: Handlebars.HelperOptions) { let result = ''; for (let i = 0; i < context.length; i++) { const item = context[i] || {}; result += options.fn({ ...item, index: i, first: i === 0, last: i === context.length - 1 }); } return result; }); // Truncate text this.handlebars.registerHelper('truncate', function(text: string, length: number) { if (!text || text.length <= length) return text; return text.slice(0, length) + '...'; }); // Format number with commas this.handlebars.registerHelper('formatNumber', function(num: number | string) { const n = typeof num === 'string' ? parseFloat(num) : num; return n.toLocaleString(); }); // Trend icon this.handlebars.registerHelper('trendIcon', function(trend: 'up' | 'down' | 'neutral') { switch (trend) { case 'up': return '↑'; case 'down': return '↓'; default: return '→'; } }); // Animation delay calculator this.handlebars.registerHelper('animDelay', function(index: number, baseMs = 100) { return `animation-delay: ${index * baseMs}ms`; }); // Safe HTML output this.handlebars.registerHelper('safeHTML', function(text: string) { return new Handlebars.SafeString(text); }); // Markdown-light processing (basic formatting) this.handlebars.registerHelper('markdown', function(text: string) { if (!text) return ''; let html = text .replace(/\*\*(.+?)\*\*/g, '$1') .replace(/\*(.+?)\*/g, '$1') .replace(/`(.+?)`/g, '$1'); return new Handlebars.SafeString(html); }); } /** * Register reusable partials. */ private registerPartials(): void { // Bullet list partial this.handlebars.registerPartial('bulletList', `
    {{#each bullets}}
  • {{markdown this}}
  • {{/each}}
`); // Metrics grid partial this.handlebars.registerPartial('metricsGrid', `
{{#each metrics}}
{{value}}
{{label}}
{{#if change}}
{{trendIcon trend}} {{change}}
{{/if}}
{{/each}}
`); // Image with caption partial this.handlebars.registerPartial('imageWithCaption', `
{{alt}} {{#if caption}}
{{caption}}
{{/if}}
`); // Source citation partial this.handlebars.registerPartial('source', ` {{#if source}}
Source: {{source}}
{{/if}} `); // Speaker notes partial this.handlebars.registerPartial('speakerNotes', ` {{#if notes}} {{/if}} `); } /** * Compile built-in templates. */ private compileTemplates(): void { // Title slide this.templates.set('title', this.handlebars.compile(`

{{title}}

{{#if subtitle}}

{{subtitle}}

{{/if}} {{#if author}}

{{author}}

{{/if}}
{{> speakerNotes}}
`)); // Agenda slide this.templates.set('agenda', this.handlebars.compile(`

{{title}}

{{> bulletList staggered=true}}
{{> speakerNotes}}
`)); // Section divider this.templates.set('section-divider', this.handlebars.compile(`

{{title}}

{{#if subtitle}}

{{subtitle}}

{{/if}}
{{> speakerNotes}}
`)); // Big idea (keynote) this.templates.set('big-idea', this.handlebars.compile(`

{{title}}

{{> speakerNotes}}
`)); // Single statement (keynote) this.templates.set('single-statement', this.handlebars.compile(`

{{title}}

{{> speakerNotes}}
`)); // Big number this.templates.set('big-number', this.handlebars.compile(`
{{title}}
{{#if subtitle}}

{{subtitle}}

{{/if}} {{> source}}
{{> speakerNotes}}
`)); // Quote this.templates.set('quote', this.handlebars.compile(`

"{{quote}}"

{{#if attribution}} — {{attribution}} {{/if}}
{{> source}}
{{> speakerNotes}}
`)); // Full image this.templates.set('full-image', this.handlebars.compile(`
{{#if title}}

{{title}}

{{/if}} {{#if caption}}

{{caption}}

{{/if}}
{{> speakerNotes}}
`)); // Bullet points this.templates.set('bullet-points', this.handlebars.compile(`

{{title}}

{{#if body}}

{{body}}

{{/if}} {{> bulletList staggered=true}} {{> source}}
{{> speakerNotes}}
`)); // Two column this.templates.set('two-column', this.handlebars.compile(`

{{title}}

{{#if body}}

{{markdown body}}

{{/if}} {{#if hasBullets}} {{> bulletList}} {{/if}}
{{#if hasImage}} {{> imageWithCaption images.[0]}} {{else if metrics}} {{> metricsGrid}} {{/if}}
{{> source}}
{{> speakerNotes}}
`)); // Three column this.templates.set('three-column', this.handlebars.compile(`

{{title}}

{{#each columns}}
{{#if title}}

{{title}}

{{/if}} {{#if body}}

{{markdown body}}

{{/if}} {{#if icon}}
{{icon}}
{{/if}}
{{/each}}
{{> speakerNotes}}
`)); // Comparison this.templates.set('comparison', this.handlebars.compile(`

{{title}}

{{leftTitle}}

    {{#each leftItems}}
  • {{this}}
  • {{/each}}

{{rightTitle}}

    {{#each rightItems}}
  • {{this}}
  • {{/each}}
{{> speakerNotes}}
`)); // Metrics grid this.templates.set('metrics-grid', this.handlebars.compile(`

{{title}}

{{> metricsGrid}} {{> source}}
{{> speakerNotes}}
`)); // Screenshot this.templates.set('screenshot', this.handlebars.compile(`

{{title}}

{{> imageWithCaption images.[0]}}
{{> speakerNotes}}
`)); // Screenshot left this.templates.set('screenshot-left', this.handlebars.compile(`

{{title}}

{{> imageWithCaption images.[0]}}
{{#if body}}

{{markdown body}}

{{/if}} {{#if hasBullets}}{{> bulletList}}{{/if}}
{{> speakerNotes}}
`)); // Screenshot right this.templates.set('screenshot-right', this.handlebars.compile(`

{{title}}

{{#if body}}

{{markdown body}}

{{/if}} {{#if hasBullets}}{{> bulletList}}{{/if}}
{{> imageWithCaption images.[0]}}
{{> speakerNotes}}
`)); // Timeline this.templates.set('timeline', this.handlebars.compile(`

{{title}}

{{#each events}}
{{date}}
{{title}}
{{#if description}}
{{description}}
{{/if}}
{{/each}}
{{> speakerNotes}}
`)); // Process/Steps this.templates.set('process', this.handlebars.compile(`

{{title}}

{{#each steps}}
{{add @index 1}}
{{title}}
{{#if description}}
{{description}}
{{/if}}
{{#unless last}}
→
{{/unless}} {{/each}}
{{> speakerNotes}}
`)); // Social proof / Testimonial this.templates.set('social-proof', this.handlebars.compile(`

{{title}}

{{#each testimonials}}
"{{quote}}"
{{#if avatar}}{{name}}{{/if}}
{{name}}
{{#if role}}
{{role}}
{{/if}}
{{/each}}
{{> speakerNotes}}
`)); // Case study this.templates.set('case-study', this.handlebars.compile(`

{{title}}

{{#if logo}}{{/if}}

Challenge

{{challenge}}

Solution

{{solution}}

Results

{{> metricsGrid metrics=results}}
{{> speakerNotes}}
`)); // CTA this.templates.set('cta', this.handlebars.compile(`

{{title}}

{{#if body}}

{{body}}

{{/if}} {{#if actionText}}
{{actionText}}
{{/if}}
{{> speakerNotes}}
`)); // Thank you this.templates.set('thank-you', this.handlebars.compile(`

{{title}}

{{#if subtitle}}

{{subtitle}}

{{/if}} {{#if contact}}
{{contact}}
{{/if}}
{{> speakerNotes}}
`)); } /** * Render fallback for unknown slide types. */ private renderFallback(slide: Slide): string { return `
${slide.data.title ? `

${slide.data.title}

` : ''} ${slide.data.body ? `

${slide.data.body}

` : ''} ${slide.data.bullets ? `
    ${slide.data.bullets.map(b => `
  • ${b}
  • `).join('')}
` : ''}
`; } /** * Convert camelCase to kebab-case. */ private kebabCase(str: string): string { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } }