// WebsiteService.swift // CxIDE — Static website generation with templates and local preview // // Generates HTML/CSS/JS projects from built-in templates. // Supports local preview via a lightweight HTTP server. import Foundation #if canImport(Network) import Network #endif // MARK: - Website Service @MainActor final class WebsiteService: ObservableObject { @Published var projects: [WebsiteProject] = [] @Published var previewPort: Int = 8080 @Published var isPreviewRunning: Bool = false private var previewProcess: Process? // MARK: - Project Creation /// Create a new website project from a template func createProject( name: String, template: WebsiteTemplate, at directory: URL ) throws -> WebsiteProject { let projectDir = directory.appendingPathComponent(name) let fm = FileManager.default guard !fm.fileExists(atPath: projectDir.path) else { throw WebsiteError.projectExists(name) } try fm.createDirectory(at: projectDir, withIntermediateDirectories: true) // Generate files from template let files = template.generateFiles(name) for (relativePath, content) in files { let fileURL = projectDir.appendingPathComponent(relativePath) let parentDir = fileURL.deletingLastPathComponent() if !fm.fileExists(atPath: parentDir.path) { try fm.createDirectory(at: parentDir, withIntermediateDirectories: true) } try content.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } let project = WebsiteProject( name: name, directory: projectDir, template: template.id, createdAt: Date() ) projects.append(project) return project } // MARK: - Local Preview /// Start a local HTTP server for previewing func startPreview(projectDir: URL, port: Int = 8080) throws { stopPreview() previewPort = port // Use Python's built-in HTTP server (available on macOS) let proc = Process() proc.executableURL = URL(fileURLWithPath: "/usr/bin/python3") proc.arguments = ["-m", "http.server", "\(port)", "--directory", projectDir.path] proc.currentDirectoryURL = projectDir proc.terminationHandler = { [weak self] _ in Task { @MainActor [weak self] in self?.isPreviewRunning = false } } try proc.run() previewProcess = proc isPreviewRunning = true } /// Stop the local preview server func stopPreview() { if let proc = previewProcess, proc.isRunning { proc.terminate() } previewProcess = nil isPreviewRunning = false } /// Get the preview URL var previewURL: URL? { isPreviewRunning ? URL(string: "http://localhost:\(previewPort)") : nil } } // MARK: - Website Project struct WebsiteProject: Identifiable, Codable, Sendable { let id: UUID let name: String let directory: URL let template: String let createdAt: Date var deployedURL: String? var domain: String? init(name: String, directory: URL, template: String, createdAt: Date) { self.id = UUID() self.name = name self.directory = directory self.template = template self.createdAt = createdAt } } // MARK: - Website Template struct WebsiteTemplate: Identifiable, Sendable { let id: String let name: String let description: String let category: String let previewImageName: String? /// Generate the files for this template let generateFiles: @Sendable (_ projectName: String) -> [(path: String, content: String)] // MARK: - Built-in Templates static let allTemplates: [WebsiteTemplate] = [ blank, landingPage, portfolio, blog, documentation, dashboard ] static let blank = WebsiteTemplate( id: "blank", name: "Blank Site", description: "Empty HTML/CSS/JS project with modern defaults", category: "Starter", previewImageName: nil ) { name in [ ("index.html", Self.blankHTML(name)), ("css/style.css", Self.blankCSS()), ("js/main.js", Self.blankJS()), ("README.md", "# \(name)\n\nA website built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } static let landingPage = WebsiteTemplate( id: "landing", name: "Landing Page", description: "Modern responsive landing page with hero, features, and CTA", category: "Marketing", previewImageName: nil ) { name in [ ("index.html", Self.landingHTML(name)), ("css/style.css", Self.landingCSS()), ("js/main.js", Self.landingJS()), ("images/.gitkeep", ""), ("README.md", "# \(name)\n\nA landing page built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } static let portfolio = WebsiteTemplate( id: "portfolio", name: "Portfolio", description: "Personal portfolio with project showcase and about section", category: "Personal", previewImageName: nil ) { name in [ ("index.html", Self.portfolioHTML(name)), ("css/style.css", Self.portfolioCSS()), ("js/main.js", Self.portfolioJS()), ("projects.html", Self.portfolioProjectsHTML(name)), ("images/.gitkeep", ""), ("README.md", "# \(name)\n\nA portfolio site built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } static let blog = WebsiteTemplate( id: "blog", name: "Blog", description: "Clean blog with post listing and article pages", category: "Content", previewImageName: nil ) { name in [ ("index.html", Self.blogHTML(name)), ("css/style.css", Self.blogCSS()), ("js/main.js", Self.blogJS()), ("post.html", Self.blogPostHTML(name)), ("posts/.gitkeep", ""), ("README.md", "# \(name)\n\nA blog built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } static let documentation = WebsiteTemplate( id: "docs", name: "Documentation", description: "Technical documentation site with sidebar navigation", category: "Developer", previewImageName: nil ) { name in [ ("index.html", Self.docsHTML(name)), ("css/style.css", Self.docsCSS()), ("js/main.js", Self.docsJS()), ("getting-started.html", Self.docsGettingStartedHTML(name)), ("README.md", "# \(name) Documentation\n\nDocumentation site built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } static let dashboard = WebsiteTemplate( id: "dashboard", name: "Dashboard", description: "Admin dashboard with charts, tables, and dark theme", category: "Application", previewImageName: nil ) { name in [ ("index.html", Self.dashboardHTML(name)), ("css/style.css", Self.dashboardCSS()), ("js/main.js", Self.dashboardJS()), ("README.md", "# \(name)\n\nA dashboard built with CxIDE.\n"), (".gitignore", "node_modules/\n.DS_Store\n*.log\n"), ] } } // MARK: - Template HTML Generators extension WebsiteTemplate { // ── Blank ── static func blankHTML(_ name: String) -> String { """ \(name)

\(name)

Welcome to your new website.

""" } static func blankCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #0a0a0a; --fg: #e8e8e8; --accent: #3b82f6; --font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; } body { font-family: var(--font); background: var(--bg); color: var(--fg); line-height: 1.6; } main { max-width: 800px; margin: 4rem auto; padding: 0 2rem; } h1 { font-size: 2.5rem; margin-bottom: 1rem; } a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; } """ } static func blankJS() -> String { """ // main.js — \(Date()) document.addEventListener('DOMContentLoaded', () => { console.log('Site loaded successfully'); }); """ } // ── Landing Page ── static func landingHTML(_ name: String) -> String { """ \(name)

Build Something Amazing

A modern solution for modern problems. Start building today.

Get Started Free Learn More

Features

Lightning Fast

Optimized for speed and performance out of the box.

🔒

Secure

Enterprise-grade security built into every layer.

🚀

Scalable

Grows with your business from day one.

Simple Pricing

Starter

$0/mo
  • 1 Project
  • Basic Support
  • 1GB Storage
Start Free

Get In Touch

""" } static func landingCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #0f172a; --fg: #e2e8f0; --accent: #3b82f6; --accent-dark: #2563eb; --card-bg: #1e293b; --border: #334155; --font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; } body { font-family: var(--font); background: var(--bg); color: var(--fg); line-height: 1.6; } .navbar { display: flex; justify-content: space-between; align-items: center; padding: 1rem 4rem; border-bottom: 1px solid var(--border); } .nav-brand { font-size: 1.5rem; font-weight: 700; color: var(--accent); } .nav-links { display: flex; gap: 2rem; align-items: center; } .nav-links a { color: var(--fg); text-decoration: none; } .btn { display: inline-block; padding: 0.6rem 1.5rem; border-radius: 8px; font-weight: 600; text-decoration: none; transition: all 0.2s; cursor: pointer; border: none; font-size: 1rem; } .btn-primary { background: var(--accent); color: white; } .btn-primary:hover { background: var(--accent-dark); } .btn-outline { border: 2px solid var(--accent); color: var(--accent); background: transparent; } .btn-outline:hover { background: var(--accent); color: white; } .btn-lg { padding: 0.8rem 2rem; font-size: 1.1rem; } .hero { text-align: center; padding: 8rem 2rem; } .hero h1 { font-size: 3.5rem; margin-bottom: 1rem; background: linear-gradient(135deg, var(--accent), #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .hero p { font-size: 1.25rem; color: #94a3b8; max-width: 600px; margin: 0 auto 2rem; } .hero-buttons { display: flex; gap: 1rem; justify-content: center; } .features, .pricing, .contact { padding: 5rem 4rem; text-align: center; } h2 { font-size: 2rem; margin-bottom: 3rem; } .feature-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 2rem; max-width: 1000px; margin: 0 auto; } .feature-card { background: var(--card-bg); padding: 2rem; border-radius: 12px; border: 1px solid var(--border); } .feature-icon { font-size: 2.5rem; margin-bottom: 1rem; } .feature-card h3 { margin-bottom: 0.5rem; } .pricing-grid { display: flex; gap: 2rem; justify-content: center; flex-wrap: wrap; } .price-card { background: var(--card-bg); padding: 2.5rem; border-radius: 12px; border: 1px solid var(--border); min-width: 280px; } .price-card.featured { border-color: var(--accent); transform: scale(1.05); } .price { font-size: 3rem; font-weight: 700; margin: 1rem 0; } .price span { font-size: 1rem; color: #94a3b8; } .price-card ul { list-style: none; margin: 1.5rem 0; } .price-card li { padding: 0.4rem 0; color: #94a3b8; } .contact-form { max-width: 500px; margin: 0 auto; display: flex; flex-direction: column; gap: 1rem; } .contact-form input, .contact-form textarea { padding: 0.8rem; border-radius: 8px; border: 1px solid var(--border); background: var(--card-bg); color: var(--fg); font-size: 1rem; } footer { text-align: center; padding: 2rem; color: #64748b; border-top: 1px solid var(--border); } @media (max-width: 768px) { .navbar { padding: 1rem 2rem; flex-direction: column; gap: 1rem; } .hero h1 { font-size: 2.5rem; } .features, .pricing, .contact { padding: 3rem 2rem; } } """ } static func landingJS() -> String { """ document.addEventListener('DOMContentLoaded', () => { // Smooth scroll for anchor links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', e => { e.preventDefault(); const target = document.querySelector(anchor.getAttribute('href')); if (target) target.scrollIntoView({ behavior: 'smooth' }); }); }); // Animate cards on scroll const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.style.opacity = '1'; entry.target.style.transform = 'translateY(0)'; } }); }, { threshold: 0.1 }); document.querySelectorAll('.feature-card, .price-card').forEach(card => { card.style.opacity = '0'; card.style.transform = 'translateY(20px)'; card.style.transition = 'all 0.6s ease'; observer.observe(card); }); }); """ } // ── Portfolio ── static func portfolioHTML(_ name: String) -> String { """ \(name) — Portfolio

Hi, I'm \(name)

Developer, designer, creator.

About Me

A passionate developer building modern web experiences.

Contact

Email: hello@example.com

""" } static func portfolioProjectsHTML(_ name: String) -> String { """ \(name) — Projects

My Projects

Project Alpha

A full-stack web application built with modern tools.

SwiftSwiftUI

Project Beta

An open-source library for data visualization.

JavaScriptD3.js
""" } static func portfolioCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #0a0a0a; --fg: #e8e8e8; --accent: #10b981; --card-bg: #171717; --border: #262626; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--fg); line-height: 1.7; } .navbar { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem 4rem; } .nav-brand { font-size: 1.4rem; font-weight: 700; color: var(--accent); text-decoration: none; } .nav-links { display: flex; gap: 2rem; } .nav-links a { color: var(--fg); text-decoration: none; } .nav-links a.active { color: var(--accent); } .hero { text-align: center; padding: 8rem 2rem 4rem; } .hero h1 { font-size: 3rem; } .accent { color: var(--accent); } .about, .projects, .contact { padding: 4rem; max-width: 900px; margin: 0 auto; } h2 { font-size: 2rem; margin-bottom: 1.5rem; } .project-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; } .project-card { background: var(--card-bg); padding: 2rem; border-radius: 12px; border: 1px solid var(--border); } .project-card h3 { margin-bottom: 0.5rem; } .tags { display: flex; gap: 0.5rem; margin-top: 1rem; } .tags span { background: var(--accent); color: #000; padding: 0.2rem 0.8rem; border-radius: 20px; font-size: 0.85rem; font-weight: 600; } footer { text-align: center; padding: 2rem; color: #666; } """ } static func portfolioJS() -> String { "document.addEventListener('DOMContentLoaded', () => { console.log('Portfolio loaded'); });\n" } // ── Blog ── static func blogHTML(_ name: String) -> String { """ \(name) — Blog

Blog

Getting Started with Web Development

A beginner's guide to building your first website with HTML, CSS, and JavaScript.

Why I Built This Blog

The story behind creating a personal blog from scratch.

""" } static func blogPostHTML(_ name: String) -> String { """ Blog Post — \(name)

Getting Started with Web Development

Welcome to your first blog post. Edit this file to add your content.

Getting Started

Start by editing the HTML files in your project directory.

<h1>Hello World</h1>
""" } static func blogCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #fafafa; --fg: #1a1a1a; --accent: #2563eb; --muted: #6b7280; } body { font-family: Georgia, 'Times New Roman', serif; background: var(--bg); color: var(--fg); line-height: 1.8; } .navbar { padding: 1.5rem 4rem; border-bottom: 1px solid #e5e7eb; } .nav-brand { font-size: 1.4rem; font-weight: 700; color: var(--fg); text-decoration: none; } .blog, .post { max-width: 700px; margin: 0 auto; padding: 3rem 2rem; } h1 { font-size: 2.5rem; margin-bottom: 1rem; } h2 { font-size: 1.5rem; margin: 2rem 0 1rem; } time { color: var(--muted); font-size: 0.9rem; } .post-preview { margin-bottom: 2.5rem; padding-bottom: 2.5rem; border-bottom: 1px solid #e5e7eb; } .post-preview h2 a { color: var(--fg); text-decoration: none; } .post-preview h2 a:hover { color: var(--accent); } pre { background: #1e293b; color: #e2e8f0; padding: 1.5rem; border-radius: 8px; overflow-x: auto; margin: 1.5rem 0; } code { font-family: 'SF Mono', Menlo, monospace; } footer { text-align: center; padding: 2rem; color: var(--muted); } """ } static func blogJS() -> String { "document.addEventListener('DOMContentLoaded', () => { console.log('Blog loaded'); });\n" } // ── Documentation ── static func docsHTML(_ name: String) -> String { """ \(name) — Documentation

Introduction

Welcome to the \(name) documentation. This guide will help you get started.

Overview

This is a documentation template. Edit these files to document your project.

""" } static func docsGettingStartedHTML(_ name: String) -> String { """ Getting Started — \(name) Docs

Getting Started

Installation

git clone https://github.com/your-repo.git
        cd your-repo

Quick Start

Open index.html in your browser to preview the site.

""" } static func docsCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #ffffff; --fg: #1a1a2e; --accent: #3b82f6; --sidebar-bg: #f8fafc; --border: #e2e8f0; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--fg); } .topnav { display: flex; align-items: center; justify-content: space-between; padding: 0.8rem 2rem; border-bottom: 1px solid var(--border); } .brand { font-weight: 700; font-size: 1.2rem; } .search-input { padding: 0.4rem 1rem; border: 1px solid var(--border); border-radius: 6px; width: 250px; } .layout { display: flex; min-height: calc(100vh - 50px); } .sidebar { width: 260px; padding: 2rem 1.5rem; background: var(--sidebar-bg); border-right: 1px solid var(--border); } .sidebar h3 { font-size: 0.8rem; text-transform: uppercase; color: #6b7280; margin: 1.5rem 0 0.5rem; } .sidebar ul { list-style: none; } .sidebar li a { display: block; padding: 0.3rem 0.8rem; color: var(--fg); text-decoration: none; border-radius: 4px; font-size: 0.95rem; } .sidebar li a:hover { background: #e2e8f0; } .sidebar li a.active { background: var(--accent); color: white; } .content { flex: 1; padding: 3rem 4rem; max-width: 800px; } .content h1 { font-size: 2rem; margin-bottom: 1rem; } .content h2 { font-size: 1.4rem; margin: 2rem 0 1rem; } pre { background: #1e293b; color: #e2e8f0; padding: 1.2rem; border-radius: 8px; overflow-x: auto; margin: 1rem 0; } code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.9rem; } """ } static func docsJS() -> String { """ document.addEventListener('DOMContentLoaded', () => { const searchInput = document.querySelector('.search-input'); if (searchInput) { searchInput.addEventListener('input', e => { console.log('Searching:', e.target.value); }); } }); """ } // ── Dashboard ── static func dashboardHTML(_ name: String) -> String { """ \(name) — Dashboard

Dashboard

Admin

Users

1,234

Revenue

$12,345

Orders

567

Conversion

3.2%

Recent Activity

UserActionDateStatus
AlicePurchaseTodayCompleted
BobSign upTodayActive
CarolRefundYesterdayPending
""" } static func dashboardCSS() -> String { """ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --bg: #0f172a; --fg: #e2e8f0; --sidebar: #1e293b; --card: #1e293b; --accent: #3b82f6; --border: #334155; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--fg); } .dashboard { display: flex; min-height: 100vh; } .sidebar { width: 220px; background: var(--sidebar); padding: 1.5rem; border-right: 1px solid var(--border); } .logo { font-size: 1.3rem; font-weight: 700; color: var(--accent); margin-bottom: 2rem; } .sidebar nav { display: flex; flex-direction: column; gap: 0.3rem; } .sidebar nav a { color: var(--fg); text-decoration: none; padding: 0.6rem 1rem; border-radius: 6px; } .sidebar nav a:hover, .sidebar nav a.active { background: var(--accent); color: white; } main { flex: 1; padding: 2rem; } header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; } .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; } .stat-card { background: var(--card); padding: 1.5rem; border-radius: 12px; border: 1px solid var(--border); } .stat-card h3 { font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.5rem; } .stat-value { font-size: 2rem; font-weight: 700; } .table-section h2 { margin-bottom: 1rem; } table { width: 100%; border-collapse: collapse; background: var(--card); border-radius: 12px; overflow: hidden; } th, td { padding: 0.8rem 1.2rem; text-align: left; border-bottom: 1px solid var(--border); } th { color: #94a3b8; font-size: 0.85rem; text-transform: uppercase; } .status-ok { color: #10b981; } .status-warn { color: #f59e0b; } """ } static func dashboardJS() -> String { """ document.addEventListener('DOMContentLoaded', () => { // Animate stat values document.querySelectorAll('.stat-value').forEach(el => { el.style.opacity = '0'; el.style.transform = 'translateY(10px)'; el.style.transition = 'all 0.4s ease'; setTimeout(() => { el.style.opacity = '1'; el.style.transform = 'translateY(0)'; }, 100); }); }); """ } } // MARK: - Errors enum WebsiteError: LocalizedError { case projectExists(String) case templateNotFound(String) case previewFailed(String) var errorDescription: String? { switch self { case .projectExists(let name): return "Project '\(name)' already exists" case .templateNotFound(let id): return "Template '\(id)' not found" case .previewFailed(let msg): return "Preview failed: \(msg)" } } }