Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions server/html_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,48 @@ def stage_html_app(data: bytes, filename: str, name: str, apps_dir: Path) -> dic
raise


_VIEWPORT_META_RE = re.compile(
r'<meta[^>]*\bname\s*=\s*["\']?viewport["\']?[^>]*>', re.IGNORECASE)
_HEAD_OPEN_RE = re.compile(r'<head[^>]*>', re.IGNORECASE)
_CONTENT_ATTR_RE = re.compile(r'content\s*=\s*["\']([^"\']*)["\']', re.IGNORECASE)
_VIEWPORT_KEYS = {"width", "initial-scale", "minimum-scale", "maximum-scale",
"user-scalable", "viewport-fit"}
_APP_VIEWPORT = ("width=device-width,initial-scale=1,maximum-scale=1,"
"user-scalable=no,viewport-fit=cover")


def appify_index_html(data: bytes) -> bytes:
"""Patch a hosted page's viewport so it presents like an installed app:
edge-to-edge under iOS chrome and no browser-style pinch zoom. Other
viewport keys are preserved; everything else is untouched."""
try:
html = data.decode("utf-8")
except UnicodeDecodeError:
return data
head = _HEAD_OPEN_RE.search(html)
if not head:
return data
head_close = html.lower().find("</head>", head.end())
scope = head_close if head_close != -1 else min(len(html), head.end() + 8192)
region = html[head.end():scope]
m = _VIEWPORT_META_RE.search(region)
if m:
content_m = _CONTENT_ATTR_RE.search(m.group(0))
extra = []
if content_m:
for piece in content_m.group(1).split(","):
piece = piece.strip()
if piece and piece.split("=", 1)[0].strip().lower() not in _VIEWPORT_KEYS:
extra.append(piece)
content = _APP_VIEWPORT + ("," + ",".join(extra) if extra else "")
meta = f'<meta name="viewport" content="{content}">'
html = html[:head.end()] + region[:m.start()] + meta + region[m.end():] + html[scope:]
else:
meta = f'<meta name="viewport" content="{_APP_VIEWPORT}">'
html = html[:head.end()] + meta + html[head.end():]
return html.encode("utf-8")


def resolve_site_file(site_dir: Path, rel_path: str) -> Optional[Path]:
"""Resolve a served path inside a site dir; directories fall back to
``index.html``. Returns None when the path does not exist or escapes."""
Expand Down
11 changes: 10 additions & 1 deletion server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import httpx
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse, PlainTextResponse
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse, PlainTextResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Dict, List, Optional
Expand Down Expand Up @@ -1815,6 +1815,15 @@ async def serve_app_site(app_id: str, request: Request, file_path: str = ""):
if path is None:
raise HTTPException(404, "Site file not found")
history_store.record_visit(app_id, "site")
if path.suffix.lower() in (".html", ".htm"):
# Hosted HTML gets an app-grade viewport (edge-to-edge, no pinch zoom)
# so installed Web Clips don't look like a browser page.
patched = html_site.appify_index_html(path.read_bytes())
return Response(
patched,
media_type="text/html; charset=utf-8",
headers={"Cache-Control": "public, max-age=3600"},
)
return FileResponse(
path,
media_type=html_site.mime_for(path),
Expand Down
19 changes: 19 additions & 0 deletions tests/test_html_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,25 @@ def test_mime_types(self):
self.assertEqual(html_site.mime_for(Path("a.png")), "image/png")
self.assertEqual(html_site.mime_for(Path("a.xyz")), "application/octet-stream")

def test_appify_merges_existing_viewport(self):
out = html_site.appify_index_html(
b'<html><head><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"></head></html>')
text = out.decode()
self.assertIn('user-scalable=no', text)
self.assertIn('viewport-fit=cover', text)
self.assertIn('maximum-scale=1', text)
self.assertIn('shrink-to-fit=no', text)

def test_appify_inserts_missing_viewport(self):
out = html_site.appify_index_html(b'<html><head><title>x</title></head></html>')
self.assertIn('name="viewport"', out.decode())

def test_appify_leaves_non_html_and_headless(self):
blob = b'\x89PNG binary \x00\x01'
self.assertEqual(html_site.appify_index_html(blob), blob)
no_head = b'just text'
self.assertEqual(html_site.appify_index_html(no_head), no_head)

def test_extract_site_meta(self):
meta = html_site.extract_site_meta(self.site)
self.assertEqual(meta["title"], "My Html App")
Expand Down
Loading