init
This commit is contained in:
12
html-generator/backend/.env
Normal file
12
html-generator/backend/.env
Normal file
@@ -0,0 +1,12 @@
|
||||
# 应用配置
|
||||
APP_NAME="HTML Generator API"
|
||||
API_PREFIX="/api"
|
||||
|
||||
# 前端配置
|
||||
FRONTEND_BASE_URL="http://localhost:3000"
|
||||
|
||||
# 允许的跨域来源
|
||||
ALLOWED_ORIGINS=["*"]
|
||||
|
||||
# 静态文件目录
|
||||
STATIC_DIR="../frontend/public/static"
|
||||
12
html-generator/backend/.env.example
Normal file
12
html-generator/backend/.env.example
Normal file
@@ -0,0 +1,12 @@
|
||||
# 应用配置
|
||||
APP_NAME="HTML Generator API"
|
||||
API_PREFIX="/api"
|
||||
|
||||
# 前端配置
|
||||
FRONTEND_BASE_URL="http://localhost:3000"
|
||||
|
||||
# 允许的跨域来源
|
||||
ALLOWED_ORIGINS=["*"]
|
||||
|
||||
# 静态文件目录
|
||||
STATIC_DIR="../frontend/public/static"
|
||||
0
html-generator/backend/app/__init__.py
Normal file
0
html-generator/backend/app/__init__.py
Normal file
BIN
html-generator/backend/app/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
html-generator/backend/app/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
html-generator/backend/app/__pycache__/config.cpython-313.pyc
Normal file
BIN
html-generator/backend/app/__pycache__/config.cpython-313.pyc
Normal file
Binary file not shown.
BIN
html-generator/backend/app/__pycache__/database.cpython-313.pyc
Normal file
BIN
html-generator/backend/app/__pycache__/database.cpython-313.pyc
Normal file
Binary file not shown.
BIN
html-generator/backend/app/__pycache__/main.cpython-313.pyc
Normal file
BIN
html-generator/backend/app/__pycache__/main.cpython-313.pyc
Normal file
Binary file not shown.
22
html-generator/backend/app/config.py
Normal file
22
html-generator/backend/app/config.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
backend_dir = Path(__file__).resolve().parent.parent
|
||||
load_dotenv(backend_dir / ".env")
|
||||
|
||||
|
||||
class Settings:
|
||||
app_name = "HTML Generator API"
|
||||
api_prefix = "/api"
|
||||
backend_dir = backend_dir
|
||||
data_dir = backend_dir / "data"
|
||||
database_path = data_dir / "html_generator.db"
|
||||
database_url = f"sqlite:///{database_path.as_posix()}"
|
||||
allowed_origins = ["*"]
|
||||
frontend_base_url = os.environ.get("FRONTEND_BASE_URL", "http://localhost:3000")
|
||||
static_dir = backend_dir / "../frontend/public/static"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
23
html-generator/backend/app/database.py
Normal file
23
html-generator/backend/app/database.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import declarative_base, sessionmaker
|
||||
|
||||
from app.config import settings
|
||||
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.database_url,
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db() -> Generator:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
43
html-generator/backend/app/main.py
Normal file
43
html-generator/backend/app/main.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.config import settings
|
||||
from app.database import Base, engine, SessionLocal
|
||||
from app.models import HTMLFile
|
||||
from app.routers import html
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# 删除过期记录
|
||||
db = SessionLocal()
|
||||
try:
|
||||
deleted_count = HTMLFile.delete_expired_records(db)
|
||||
if deleted_count > 0:
|
||||
logger.info(f"Deleted {deleted_count} expired HTML file records")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app = FastAPI(title=settings.app_name)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.allowed_origins,
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(html.router, prefix=settings.api_prefix)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def health_check() -> dict[str, str]:
|
||||
return {"message": "HTML Generator API is running"}
|
||||
30
html-generator/backend/app/models.py
Normal file
30
html-generator/backend/app/models.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, Session
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class HTMLFile(Base):
|
||||
__tablename__ = "html_files"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
unique_id: Mapped[str] = mapped_column(
|
||||
String(32), unique=True, index=True, nullable=False
|
||||
)
|
||||
filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def delete_expired_records(cls, db: Session, days: int = 5) -> int:
|
||||
"""删除超过指定天数的记录"""
|
||||
cutoff_date = datetime.utcnow() - timedelta(days=days)
|
||||
deleted = db.query(cls).filter(cls.created_at < cutoff_date).delete()
|
||||
db.commit()
|
||||
return deleted
|
||||
0
html-generator/backend/app/routers/__init__.py
Normal file
0
html-generator/backend/app/routers/__init__.py
Normal file
86
html-generator/backend/app/routers/html.py
Normal file
86
html-generator/backend/app/routers/html.py
Normal file
@@ -0,0 +1,86 @@
|
||||
import os
|
||||
import secrets
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import settings
|
||||
from app.database import get_db
|
||||
from app.models import HTMLFile
|
||||
from app.schemas import HTMLGenerateRequest, HTMLGenerateResponse
|
||||
|
||||
router = APIRouter(prefix="/html", tags=["html"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_unique_id() -> str:
|
||||
return secrets.token_urlsafe(16)
|
||||
|
||||
|
||||
@router.post("/generate", response_model=HTMLGenerateResponse, status_code=status.HTTP_201_CREATED)
|
||||
def generate_html(request: HTMLGenerateRequest, db: Session = Depends(get_db)):
|
||||
try:
|
||||
# 先删除过期记录
|
||||
deleted_count = HTMLFile.delete_expired_records(db)
|
||||
if deleted_count > 0:
|
||||
logger.info(f"Deleted {deleted_count} expired HTML file records")
|
||||
|
||||
# 生成唯一 ID
|
||||
unique_id = generate_unique_id()
|
||||
|
||||
# 确保静态文件目录存在
|
||||
static_dir = settings.static_dir.resolve()
|
||||
static_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 生成 HTML 文件路径
|
||||
html_filename = f"{unique_id}.html"
|
||||
html_path = static_dir / html_filename
|
||||
|
||||
# 写入 HTML 内容
|
||||
with open(html_path, "w", encoding="utf-8") as f:
|
||||
f.write(request.html_content)
|
||||
|
||||
# 保存到数据库
|
||||
html_file = HTMLFile(
|
||||
unique_id=unique_id,
|
||||
filename=html_filename,
|
||||
)
|
||||
db.add(html_file)
|
||||
db.commit()
|
||||
db.refresh(html_file)
|
||||
|
||||
# 生成完整链接
|
||||
html_url = f"{settings.frontend_base_url}/static/{html_filename}"
|
||||
|
||||
return HTMLGenerateResponse(
|
||||
message="HTML 文件生成成功",
|
||||
unique_id=unique_id,
|
||||
url=html_url
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"生成 HTML 文件失败: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"生成 HTML 文件失败: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{unique_id}")
|
||||
def get_html_file(unique_id: str, db: Session = Depends(get_db)):
|
||||
html_file = db.query(HTMLFile).filter(HTMLFile.unique_id == unique_id).first()
|
||||
|
||||
if not html_file:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="HTML 文件不存在"
|
||||
)
|
||||
|
||||
# 生成完整链接
|
||||
html_url = f"{settings.frontend_base_url}/static/{html_file.filename}"
|
||||
|
||||
return {
|
||||
"message": "HTML 文件查询成功",
|
||||
"unique_id": html_file.unique_id,
|
||||
"url": html_url
|
||||
}
|
||||
23
html-generator/backend/app/schemas.py
Normal file
23
html-generator/backend/app/schemas.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class HTMLGenerateRequest(BaseModel):
|
||||
html_content: str
|
||||
|
||||
|
||||
class HTMLGenerateResponse(BaseModel):
|
||||
message: str
|
||||
unique_id: str
|
||||
url: str
|
||||
|
||||
|
||||
class HTMLFileResponse(BaseModel):
|
||||
id: int
|
||||
unique_id: str
|
||||
filename: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
18
html-generator/backend/package.json
Normal file
18
html-generator/backend/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "html-generator-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "HTML Generator Backend",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "nodemon server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.1"
|
||||
}
|
||||
}
|
||||
4
html-generator/backend/requirements.txt
Normal file
4
html-generator/backend/requirements.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0.post1
|
||||
python-dotenv==1.0.0
|
||||
sqlalchemy==2.0.23
|
||||
70
html-generator/backend/server.js
Normal file
70
html-generator/backend/server.js
Normal file
@@ -0,0 +1,70 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const dotenv = require('dotenv');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 加载环境变量
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const port = 8000;
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// 生成唯一 ID
|
||||
function generateUniqueId() {
|
||||
return Math.random().toString(36).substring(2, 18) + Math.random().toString(36).substring(2, 18);
|
||||
}
|
||||
|
||||
// 确保静态文件目录存在
|
||||
const staticDir = path.resolve(__dirname, '../frontend/public/static');
|
||||
if (!fs.existsSync(staticDir)) {
|
||||
fs.mkdirSync(staticDir, { recursive: true });
|
||||
}
|
||||
|
||||
// API 路由
|
||||
app.post('/api/html/generate', (req, res) => {
|
||||
try {
|
||||
const { html_content } = req.body;
|
||||
|
||||
if (!html_content) {
|
||||
return res.status(400).json({ error: 'HTML 内容不能为空' });
|
||||
}
|
||||
|
||||
// 生成唯一 ID
|
||||
const uniqueId = generateUniqueId();
|
||||
|
||||
// 生成 HTML 文件路径
|
||||
const htmlFilename = `${uniqueId}.html`;
|
||||
const htmlPath = path.join(staticDir, htmlFilename);
|
||||
|
||||
// 写入 HTML 内容
|
||||
fs.writeFileSync(htmlPath, html_content, 'utf-8');
|
||||
|
||||
// 生成完整链接
|
||||
const frontendBaseUrl = process.env.FRONTEND_BASE_URL || 'http://localhost:3000';
|
||||
const htmlUrl = `${frontendBaseUrl}/static/${htmlFilename}`;
|
||||
|
||||
res.status(201).json({
|
||||
message: 'HTML 文件生成成功',
|
||||
unique_id: uniqueId,
|
||||
url: htmlUrl
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('生成 HTML 文件失败:', error);
|
||||
res.status(500).json({ error: `生成 HTML 文件失败: ${error.message}` });
|
||||
}
|
||||
});
|
||||
|
||||
// 健康检查
|
||||
app.get('/', (req, res) => {
|
||||
res.json({ message: 'HTML Generator API is running' });
|
||||
});
|
||||
|
||||
// 启动服务器
|
||||
app.listen(port, () => {
|
||||
console.log(`服务器运行在 http://localhost:${port}`);
|
||||
});
|
||||
87
html-generator/backend/server.py
Normal file
87
html-generator/backend/server.py
Normal file
@@ -0,0 +1,87 @@
|
||||
import http.server
|
||||
import socketserver
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
|
||||
PORT = 8000
|
||||
|
||||
# 生成唯一 ID
|
||||
def generate_unique_id():
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=16))
|
||||
|
||||
# 确保静态文件目录存在
|
||||
static_dir = os.path.join(os.path.dirname(__file__), '../frontend/public/static')
|
||||
if not os.path.exists(static_dir):
|
||||
os.makedirs(static_dir, exist_ok=True)
|
||||
|
||||
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
if self.path == '/api/html/generate':
|
||||
# 读取请求体
|
||||
content_length = int(self.headers['Content-Length'])
|
||||
post_data = self.rfile.read(content_length)
|
||||
|
||||
try:
|
||||
# 解析 JSON 数据
|
||||
data = json.loads(post_data)
|
||||
html_content = data.get('html_content', '')
|
||||
|
||||
if not html_content:
|
||||
self.send_response(400)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({'error': 'HTML 内容不能为空'}).encode('utf-8'))
|
||||
return
|
||||
|
||||
# 生成唯一 ID
|
||||
unique_id = generate_unique_id()
|
||||
|
||||
# 生成 HTML 文件路径
|
||||
html_filename = f"{unique_id}.html"
|
||||
html_path = os.path.join(static_dir, html_filename)
|
||||
|
||||
# 写入 HTML 内容
|
||||
with open(html_path, 'w', encoding='utf-8') as f:
|
||||
f.write(html_content)
|
||||
|
||||
# 生成完整链接
|
||||
frontend_base_url = 'http://localhost:3000'
|
||||
html_url = f"{frontend_base_url}/static/{html_filename}"
|
||||
|
||||
# 返回响应
|
||||
self.send_response(201)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
response = {
|
||||
'message': 'HTML 文件生成成功',
|
||||
'unique_id': unique_id,
|
||||
'url': html_url
|
||||
}
|
||||
self.wfile.write(json.dumps(response).encode('utf-8'))
|
||||
except Exception as e:
|
||||
self.send_response(500)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({'error': f'生成 HTML 文件失败: {str(e)}'}).encode('utf-8'))
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == '/':
|
||||
# 健康检查
|
||||
self.send_response(200)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({'message': 'HTML Generator API is running'}).encode('utf-8'))
|
||||
else:
|
||||
# 静态文件服务
|
||||
super().do_GET()
|
||||
|
||||
if __name__ == "__main__":
|
||||
with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd:
|
||||
print(f"服务器运行在 http://localhost:{PORT}")
|
||||
httpd.serve_forever()
|
||||
54
html-generator/frontend/app/globals.css
Normal file
54
html-generator/frontend/app/globals.css
Normal file
@@ -0,0 +1,54 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--background: oklch(0.9816 0.0017 247.8577);
|
||||
--foreground: oklch(0.1221 0 0);
|
||||
--card: oklch(0.9911 0 0);
|
||||
--card-foreground: oklch(0.1221 0 0);
|
||||
--popover: oklch(0.9911 0 0);
|
||||
--popover-foreground: oklch(0.1221 0 0);
|
||||
--primary: oklch(0.6264 0.1942 259.2027);
|
||||
--primary-foreground: oklch(0.9911 0 0);
|
||||
--secondary: oklch(0.2795 0.0368 259.8165);
|
||||
--secondary-foreground: oklch(0.9911 0 0);
|
||||
--muted: oklch(0.9700 0 0);
|
||||
--muted-foreground: oklch(0.5560 0 0);
|
||||
--accent: oklch(0.6755 0.1303 40.7093);
|
||||
--accent-foreground: oklch(0.9911 0 0);
|
||||
--destructive: oklch(0.6498 0.1805 9.8598);
|
||||
--destructive-foreground: oklch(0.9911 0 0);
|
||||
--border: oklch(0.9189 0 0);
|
||||
--input: oklch(0.9491 0 0);
|
||||
--ring: oklch(0.6264 0.1942 259.2027);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.1221 0 0);
|
||||
--foreground: oklch(0.9816 0.0017 247.8577);
|
||||
--card: oklch(0.1565 0 0);
|
||||
--card-foreground: oklch(0.9816 0.0017 247.8577);
|
||||
--popover: oklch(0.1565 0 0);
|
||||
--popover-foreground: oklch(0.9816 0.0017 247.8577);
|
||||
--primary: oklch(0.6264 0.1942 259.2027);
|
||||
--primary-foreground: oklch(0.9911 0 0);
|
||||
--secondary: oklch(0.2795 0.0368 259.8165);
|
||||
--secondary-foreground: oklch(0.9911 0 0);
|
||||
--muted: oklch(0.2686 0 0);
|
||||
--muted-foreground: oklch(0.7155 0 0);
|
||||
--accent: oklch(0.6755 0.1303 40.7093);
|
||||
--accent-foreground: oklch(0.9911 0 0);
|
||||
--destructive: oklch(0.6498 0.1805 9.8598);
|
||||
--destructive-foreground: oklch(0.9911 0 0);
|
||||
--border: oklch(0.2750 0 0);
|
||||
--input: oklch(0.3250 0 0);
|
||||
--ring: oklch(0.6264 0.1942 259.2027);
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background-color: var(--background);
|
||||
color: var(--foreground);
|
||||
line-height: 1.6;
|
||||
}
|
||||
36
html-generator/frontend/app/layout.tsx
Normal file
36
html-generator/frontend/app/layout.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'HTML Generator',
|
||||
description: '生成HTML文件并返回可访问链接',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body>
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<header className="bg-primary text-primary-foreground py-4 px-6 shadow-md">
|
||||
<div className="container mx-auto">
|
||||
<h1 className="text-2xl font-bold">HTML Generator</h1>
|
||||
</div>
|
||||
</header>
|
||||
<main className="flex-1 container mx-auto py-8 px-6">
|
||||
{children}
|
||||
</main>
|
||||
<footer className="bg-muted text-muted-foreground py-4 px-6 border-t">
|
||||
<div className="container mx-auto text-center">
|
||||
<p>© 2026 HTML Generator</p>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
88
html-generator/frontend/app/page.tsx
Normal file
88
html-generator/frontend/app/page.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function Home() {
|
||||
const [htmlContent, setHtmlContent] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:8000/api/html/generate', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ html_content: htmlContent }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('生成 HTML 文件失败');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setResult({ url: data.url });
|
||||
} catch (err) {
|
||||
setError('生成 HTML 文件失败,请稍后重试');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<h2 className="text-2xl font-bold mb-6">HTML 文件生成器</h2>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div>
|
||||
<label htmlFor="html-content" className="block text-sm font-medium mb-2">
|
||||
HTML 内容
|
||||
</label>
|
||||
<textarea
|
||||
id="html-content"
|
||||
value={htmlContent}
|
||||
onChange={(e) => setHtmlContent(e.target.value)}
|
||||
rows={10}
|
||||
className="w-full p-4 border border-border rounded-md bg-card focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
placeholder="请输入 HTML 内容..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !htmlContent.trim()}
|
||||
className="bg-primary text-primary-foreground px-6 py-2 rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{loading ? '生成中...' : '生成 HTML 文件'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div className="mt-6 p-4 bg-destructive/10 text-destructive rounded-md">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="mt-6 p-4 bg-accent/10 text-accent rounded-md">
|
||||
<h3 className="font-medium mb-2">生成成功!</h3>
|
||||
<p className="mb-2">您的 HTML 文件已生成,可通过以下链接访问:</p>
|
||||
<a
|
||||
href={result.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{result.url}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
250
html-generator/frontend/index.html
Normal file
250
html-generator/frontend/index.html
Normal file
@@ -0,0 +1,250 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>HTML Generator</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary-color: #4f46e5;
|
||||
--primary-hover: #4338ca;
|
||||
--success-color: #065f46;
|
||||
--success-bg: #d1fae5;
|
||||
--error-color: #b91c1c;
|
||||
--error-bg: #fee2e2;
|
||||
--border-color: #e2e8f0;
|
||||
--text-color: #1e293b;
|
||||
--bg-color: #f8fafc;
|
||||
--card-bg: #ffffff;
|
||||
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
header {
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
padding: 1.5rem 0;
|
||||
margin-bottom: 2rem;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
font-size: 1.875rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--card-bg);
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: var(--shadow);
|
||||
padding: 2rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1.5rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.375rem;
|
||||
resize: vertical;
|
||||
min-height: 200px;
|
||||
font-family: inherit;
|
||||
font-size: 0.875rem;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
padding: 0.75rem 1.5rem;
|
||||
border: none;
|
||||
border-radius: 0.375rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: var(--primary-hover);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background-color: #a5b4fc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.result {
|
||||
margin-top: 2rem;
|
||||
padding: 1rem;
|
||||
border-radius: 0.375rem;
|
||||
}
|
||||
|
||||
.success {
|
||||
background-color: var(--success-bg);
|
||||
color: var(--success-color);
|
||||
border-left: 4px solid var(--success-color);
|
||||
}
|
||||
|
||||
.error {
|
||||
background-color: var(--error-bg);
|
||||
color: var(--error-color);
|
||||
border-left: 4px solid var(--error-color);
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
color: var(--primary-hover);
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||
border-radius: 50%;
|
||||
border-top-color: white;
|
||||
animation: spin 1s ease-in-out infinite;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
footer {
|
||||
text-align: center;
|
||||
margin-top: 4rem;
|
||||
padding: 1rem 0;
|
||||
color: #64748b;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>HTML Generator</h1>
|
||||
</header>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h2>HTML 文件生成器</h2>
|
||||
<form id="htmlForm">
|
||||
<div class="form-group">
|
||||
<label for="htmlContent">HTML 内容</label>
|
||||
<textarea id="htmlContent" placeholder="请输入 HTML 内容..."></textarea>
|
||||
</div>
|
||||
<button type="submit" id="submitBtn">
|
||||
<span id="loadingSpinner" class="loading" style="display: none;"></span>
|
||||
<span id="buttonText">生成 HTML 文件</span>
|
||||
</button>
|
||||
</form>
|
||||
<div id="result" class="result" style="display: none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<footer>
|
||||
<p>© 2026 HTML Generator</p>
|
||||
</footer>
|
||||
<script>
|
||||
document.getElementById('htmlForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const htmlContent = document.getElementById('htmlContent').value;
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const resultDiv = document.getElementById('result');
|
||||
const loadingSpinner = document.getElementById('loadingSpinner');
|
||||
const buttonText = document.getElementById('buttonText');
|
||||
|
||||
if (!htmlContent.trim()) {
|
||||
resultDiv.className = 'result error';
|
||||
resultDiv.innerHTML = 'HTML 内容不能为空';
|
||||
resultDiv.style.display = 'block';
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
submitBtn.disabled = true;
|
||||
loadingSpinner.style.display = 'inline-block';
|
||||
buttonText.textContent = '生成中...';
|
||||
resultDiv.style.display = 'none';
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:8000/api/html/generate', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ html_content: htmlContent })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('生成 HTML 文件失败');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
resultDiv.className = 'result success';
|
||||
resultDiv.innerHTML = `
|
||||
<h3>生成成功!</h3>
|
||||
<p>您的 HTML 文件已生成,可通过以下链接访问:</p>
|
||||
<a href="${data.url}" target="_blank">${data.url}</a>
|
||||
`;
|
||||
} catch (error) {
|
||||
resultDiv.className = 'result error';
|
||||
resultDiv.innerHTML = '生成 HTML 文件失败,请稍后重试';
|
||||
console.error(error);
|
||||
} finally {
|
||||
// 恢复按钮状态
|
||||
submitBtn.disabled = false;
|
||||
loadingSpinner.style.display = 'none';
|
||||
buttonText.textContent = '生成 HTML 文件';
|
||||
resultDiv.style.display = 'block';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
5
html-generator/frontend/next-env.d.ts
vendored
Normal file
5
html-generator/frontend/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||
7
html-generator/frontend/next.config.mjs
Normal file
7
html-generator/frontend/next.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
output: 'standalone',
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
27
html-generator/frontend/package.json
Normal file
27
html-generator/frontend/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "html-generator-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "14.2.26",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "22.10.1",
|
||||
"@types/react": "18.3.18",
|
||||
"@types/react-dom": "18.3.5",
|
||||
"autoprefixer": "10.4.20",
|
||||
"eslint": "8.57.1",
|
||||
"eslint-config-next": "14.2.26",
|
||||
"postcss": "8.4.49",
|
||||
"tailwindcss": "3.4.16",
|
||||
"typescript": "5.7.2"
|
||||
}
|
||||
}
|
||||
6
html-generator/frontend/postcss.config.js
Normal file
6
html-generator/frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
<html><body><h1>Hello World</h1></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
<html><body><h1>Hello World</h1></body></html>
|
||||
38
html-generator/frontend/tailwind.config.ts
Normal file
38
html-generator/frontend/tailwind.config.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
'./components/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
'./app/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
background: 'oklch(0.9816 0.0017 247.8577)',
|
||||
foreground: 'oklch(0.1221 0 0)',
|
||||
card: 'oklch(0.9911 0 0)',
|
||||
'card-foreground': 'oklch(0.1221 0 0)',
|
||||
popover: 'oklch(0.9911 0 0)',
|
||||
'popover-foreground': 'oklch(0.1221 0 0)',
|
||||
primary: 'oklch(0.6264 0.1942 259.2027)',
|
||||
'primary-foreground': 'oklch(0.9911 0 0)',
|
||||
secondary: 'oklch(0.2795 0.0368 259.8165)',
|
||||
'secondary-foreground': 'oklch(0.9911 0 0)',
|
||||
muted: 'oklch(0.9700 0 0)',
|
||||
'muted-foreground': 'oklch(0.5560 0 0)',
|
||||
accent: 'oklch(0.6755 0.1303 40.7093)',
|
||||
'accent-foreground': 'oklch(0.9911 0 0)',
|
||||
destructive: 'oklch(0.6498 0.1805 9.8598)',
|
||||
'destructive-foreground': 'oklch(0.9911 0 0)',
|
||||
border: 'oklch(0.9189 0 0)',
|
||||
input: 'oklch(0.9491 0 0)',
|
||||
ring: 'oklch(0.6264 0.1942 259.2027)',
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ['var(--font-sans)', 'sans-serif'],
|
||||
mono: ['var(--font-mono)', 'monospace'],
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
26
html-generator/frontend/tsconfig.json
Normal file
26
html-generator/frontend/tsconfig.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user