File size: 5,088 Bytes
3806142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""HTML Widget converter — Hybrid embed package."""
from __future__ import annotations

import json
import zipfile
from pathlib import Path

from backend.app.config import TEMPLATES_DIR
from backend.app.converters.base import Artifact, BuildContext, Converter, ConverterResult
from backend.app.security.zipsafe import safe_add_tree


def _esc(s: str) -> str:
    return (
        str(s)
        .replace("&", "&")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def _slug(s: str) -> str:
    return "".join(c if c.isalnum() or c in "-_" else "-" for c in s)[:64]


DEFAULT_INDEX = """<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>{{EMOJI}} {{TITLE}} — SpaceForge Widget</title>
  <link rel="stylesheet" href="style.css"/>
</head>
<body>
  <header class="sf-header">
    <strong>{{EMOJI}} {{TITLE}}</strong>
    <span class="badge">{{MODE}}</span>
    <a href="{{SPACE_URL}}" target="_blank" rel="noopener">Open on HF</a>
  </header>
  <div id="sf-root" data-embed="{{EMBED_URL}}" data-repo="{{REPO_ID}}"></div>
  <script src="loader.js"></script>
</body>
</html>
"""

DEFAULT_LOADER = """(function () {
  const root = document.getElementById("sf-root");
  if (!root) return;
  const url = root.dataset.embed || "{{EMBED_URL}}";
  const iframe = document.createElement("iframe");
  iframe.src = url;
  iframe.title = root.dataset.repo || "Hugging Face Space";
  iframe.allow = "accelerometer; camera; microphone; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";
  iframe.allowFullscreen = true;
  iframe.referrerPolicy = "strict-origin-when-cross-origin";
  iframe.className = "sf-frame";
  root.appendChild(iframe);
})();
"""

DEFAULT_CSS = """html,body{margin:0;height:100%;font-family:system-ui,sans-serif;background:#0b1020;color:#e8eefc}
.sf-header{display:flex;gap:1rem;align-items:center;padding:.75rem 1rem;background:#121a33;border-bottom:1px solid #243056}
.sf-header a{color:#8ab4ff;margin-left:auto}
.badge{font-size:.75rem;padding:.15rem .5rem;border-radius:999px;background:#2a3d7a}
#sf-root,.sf-frame{width:100%;height:calc(100vh - 52px);border:0;display:block}
"""


class HtmlWidgetConverter(Converter):
    id = "html_widget"
    label = "HTML Widget"
    mode = "hybrid"

    async def convert(self, ctx: BuildContext) -> ConverterResult:
        info = ctx.space_info
        out_dir = ctx.work_dir / "html_widget"
        out_dir.mkdir(parents=True, exist_ok=True)
        tpl = TEMPLATES_DIR / "widget"
        ctx.info(f"Generating HTML widget for {info['repo_id']} (mode=hybrid)")

        title = info.get("title") or info["repo_id"]
        embed = info.get("embed_url") or ""
        space_url = info.get("space_url") or ""

        index = (tpl / "index.html").read_text(encoding="utf-8") if (tpl / "index.html").exists() else DEFAULT_INDEX
        index = (
            index.replace("{{TITLE}}", _esc(title))
            .replace("{{EMBED_URL}}", _esc(embed))
            .replace("{{SPACE_URL}}", _esc(space_url))
            .replace("{{REPO_ID}}", _esc(info["repo_id"]))
            .replace("{{EMOJI}}", info.get("emoji") or "🚀")
            .replace("{{MODE}}", "Hybrid")
        )
        (out_dir / "index.html").write_text(index, encoding="utf-8")

        loader = (tpl / "loader.js").read_text(encoding="utf-8") if (tpl / "loader.js").exists() else DEFAULT_LOADER
        loader = loader.replace("{{EMBED_URL}}", embed).replace("{{REPO_ID}}", info["repo_id"])
        (out_dir / "loader.js").write_text(loader, encoding="utf-8")

        style = (tpl / "style.css").read_text(encoding="utf-8") if (tpl / "style.css").exists() else DEFAULT_CSS
        (out_dir / "style.css").write_text(style, encoding="utf-8")

        meta = {
            "product": "SpaceForge",
            "target": self.id,
            "mode": self.mode,
            "space": info["repo_id"],
            "embed_url": embed,
            "disclaimer": "Hybrid Hosted Wrapper shell — requires the live Space URL.",
        }
        (out_dir / "spaceforge.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
        (out_dir / "README.md").write_text(
            f"# {title} — HTML Widget (Hybrid)\n\n"
            f"Open `index.html` or host this folder statically.\n"
            f"Embeds: `{embed}`\n\n"
            f"**Mode: Hybrid / Hosted Wrapper** — not a local offline app.\n",
            encoding="utf-8",
        )

        zip_path = ctx.work_dir / f"{_slug(info['name'])}-html-widget.zip"
        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
            safe_add_tree(zf, out_dir)
        ctx.info(f"Wrote {zip_path.name}")
        return ConverterResult(
            ok=True,
            artifact=Artifact(
                target_id=self.id,
                path=zip_path,
                filename=zip_path.name,
                mode=self.mode,
                notes="Hybrid HTML widget (iframe + loader).",
            ),
        )