# Handlebars.js Template Engine Integration

## Overview
DesignFast使用Handlebars.js作为模板引擎来生成设计文档和原型HTML。

## Installation (for development)

```bash
npm install handlebars --save
```

## Basic Usage

### Compiling Templates

```javascript
const Handlebars = require('handlebars');

// Load template
const templateSource = fs.readFileSync('template.hbs', 'utf8');

// Compile template
const template = Handlebars.compile(templateSource);

// Render with data
const result = template({
  projectName: 'My Project',
  description: 'A cool project'
});

// Write output
fs.writeFileSync('output.html', result, 'utf8');
```

## Template Locations

```
src/templates/
├── documents/
│   ├── design-document.hbs       # 设计文档模板
│   ├── requirements.hbs           # 需求文档模板
│   └── design-system.hbs          # 设计系统模板
├── prototypes/
│   ├── base-prototype.hbs         # 基础原型模板
│   ├── page.hbs                   # 页面模板
│   └── component.hbs              # 组件模板
└── prompts/
    ├── design-director.hbs        # 代理提示模板
    └── requirements-analyzer.hbs  # 代理提示模板
```

## Custom Helpers

### Conditional Helpers

```javascript
// Register custom helpers
Handlebars.registerHelper('if_eq', function(a, b, options) {
  if (a === b) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Handlebars.registerHelper('if_gt', function(a, b, options) {
  if (a > b) {
    return options.fn(this);
  }
  return options.inverse(this);
});
```

Usage:
```handlebars
{{#if_eq priority 'P1'}}
  <span class="badge-high">高优先级</span>
{{/if_eq}}

{{#if_gt confidence 0.8}}
  <span class="badge-success">高置信度</span>
{{/if_gt}}
```

### Format Helpers

```javascript
// Date formatting
Handlebars.registerHelper('formatDate', function(date) {
  return new Date(date).toLocaleDateString('zh-CN');
});

// Markdown to HTML
Handlebars.registerHelper('markdown', function(text) {
  // Simple markdown conversion
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\n/g, '<br>');
});

// Truncate text
Handlebars.registerHelper('truncate', function(text, length) {
  if (text.length > length) {
    return text.substring(0, length) + '...';
  }
  return text;
});
```

Usage:
```handlebars
<p>创建时间: {{formatDate createdAt}}</p>
<div>{{{markdown description}}}</div>
<p>{{truncate summary 100}}</p>
```

### CSS Class Helpers

```javascript
// Generate Tailwind classes based on data
Handlebars.registerHelper('priorityClass', function(priority) {
  const classes = {
    'P1': 'bg-red-100 text-red-800',
    'P2': 'bg-yellow-100 text-yellow-800',
    'P3': 'bg-green-100 text-green-800'
  };
  return classes[priority] || 'bg-gray-100 text-gray-800';
});

Handlebars.registerHelper('statusClass', function(status) {
  const classes = {
    'draft': 'bg-gray-100 text-gray-800',
    'in-progress': 'bg-blue-100 text-blue-800',
    'completed': 'bg-green-100 text-green-800',
    'failed': 'bg-red-100 text-red-800'
  };
  return classes[status] || 'bg-gray-100 text-gray-800';
});
```

Usage:
```handlebars
<span class="px-2 py-1 rounded {{priorityClass priority}}">
  {{priority}}
</span>

<span class="px-2 py-1 rounded {{statusClass status}}">
  {{status}}
</span>
```

## Template Examples

### Design Document Template

```handlebars
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{projectName}} - 设计文档</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-8">
    <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-lg p-8">
        <h1 class="text-4xl font-bold mb-4">{{projectName}}</h1>
        <p class="text-gray-600 mb-8">{{description}}</p>
        
        <section class="mb-8">
            <h2 class="text-2xl font-semibold mb-4">需求列表</h2>
            {{#each requirements}}
            <div class="border-l-4 border-{{#if_eq priority 'P1'}}red{{else if_eq priority 'P2'}}yellow{{else}}green{{/if_eq}}-500 pl-4 mb-4">
                <h3 class="text-xl font-medium">{{title}}</h3>
                <span class="{{priorityClass priority}} px-2 py-1 rounded text-sm">
                    {{priority}}
                </span>
                <p class="mt-2 text-gray-700">{{{markdown description}}}</p>
                
                <div class="mt-2">
                    <strong>验收标准:</strong>
                    <ul class="list-disc list-inside">
                        {{#each acceptanceCriteria}}
                        <li>{{this}}</li>
                        {{/each}}
                    </ul>
                </div>
            </div>
            {{/each}}
        </section>
        
        <section class="mb-8">
            <h2 class="text-2xl font-semibold mb-4">设计系统</h2>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <h3 class="font-medium mb-2">颜色方案</h3>
                    <div class="flex space-x-2">
                        {{#each designSystem.colorPalette}}
                        <div class="w-12 h-12 rounded" style="background-color: {{this}}"></div>
                        {{/each}}
                    </div>
                </div>
                <div>
                    <h3 class="font-medium mb-2">排版</h3>
                    <p>字体: {{designSystem.typography.fontFamily}}</p>
                    <p>基础字号: {{designSystem.typography.baseFontSize}}</p>
                </div>
            </div>
        </section>
        
        <footer class="text-sm text-gray-500 mt-8 pt-4 border-t">
            <p>创建时间: {{formatDate createdAt}}</p>
            <p>最后更新: {{formatDate updatedAt}}</p>
        </footer>
    </div>
</body>
</html>
```

### Component Template

```handlebars
<!-- {{componentName}} Component -->
<div class="{{componentClasses}}" {{#if ariaLabel}}aria-label="{{ariaLabel}}"{{/if}}>
    {{#if hasHeader}}
    <div class="{{headerClasses}}">
        <h3>{{headerText}}</h3>
    </div>
    {{/if}}
    
    <div class="{{contentClasses}}">
        {{{content}}}
    </div>
    
    {{#if hasFooter}}
    <div class="{{footerClasses}}">
        {{{footerContent}}}
    </div>
    {{/if}}
</div>
```

## Partial Templates

### Register Partials

```javascript
Handlebars.registerPartial('header', fs.readFileSync('partials/header.hbs', 'utf8'));
Handlebars.registerPartial('footer', fs.readFileSync('partials/footer.hbs', 'utf8'));
Handlebars.registerPartial('nav', fs.readFileSync('partials/nav.hbs', 'utf8'));
```

### Use Partials

```handlebars
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    {{> header}}
    
    {{> nav}}
    
    <main>
        {{{content}}}
    </main>
    
    {{> footer}}
</body>
</html>
```

## PowerShell Integration

### Compile Template Script

```powershell
# compile-template.ps1
param(
    [string]$TemplatePath,
    [string]$DataPath,
    [string]$OutputPath
)

$templateContent = Get-Content $TemplatePath -Raw
$dataContent = Get-Content $DataPath -Raw | ConvertFrom-Json

# Call Node.js script to compile
node -e "
const Handlebars = require('handlebars');
const template = Handlebars.compile(\`$templateContent\`);
const result = template($($dataContent | ConvertTo-Json -Depth 10 -Compress));
console.log(result);
" | Out-File -FilePath $OutputPath -Encoding UTF8
```

## Error Handling

```javascript
// Strict mode
Handlebars.compile(templateSource, {
  strict: true,  // Throw on missing properties
  noEscape: false  // Auto-escape HTML
});

// Custom error handling
try {
  const result = template(data);
} catch (error) {
  console.error('Template compilation error:', error.message);
  // Fallback or error reporting
}
```

## Best Practices

1. **Always escape user input** (unless using {{{triple braces}}} intentionally)
2. **Use partials** for reusable components
3. **Register helpers** for complex logic
4. **Validate data** before passing to templates
5. **Cache compiled templates** for performance
6. **Use descriptive variable names** in templates

## Performance Considerations

```javascript
// Pre-compile templates for production
const fs = require('fs');
const Handlebars = require('handlebars');

// Compile once
const compiledTemplates = {};
const templateFiles = fs.readdirSync('src/templates/prototypes');

templateFiles.forEach(file => {
  const source = fs.readFileSync(`src/templates/prototypes/${file}`, 'utf8');
  compiledTemplates[file] = Handlebars.compile(source);
});

// Reuse compiled templates
const result = compiledTemplates['base-prototype.hbs'](data);
```

## Constitutional Compliance

✅ **File-Based**: Templates stored as .hbs files
✅ **Accessibility**: Helpers for ARIA attributes and semantic HTML
✅ **Mobile-First**: Templates use responsive Tailwind classes
✅ **Performance**: Pre-compilation for < 1s rendering
✅ **Maintainability**: Partials and helpers for DRY code
