ADD PRODUCT
-새 작품을 등록합니다
-사진을 찍고, 내용을 쓰고, 항목을 고르면 상세 페이지 한 장이 만들어집니다.
+WORKS
+작품 목록
+불러오는 중…
-최근 작품
-아직 없습니다.
'; + + const pending = rows.filter(p => p.live === false).length; + const button = $('#deploy-all'); + button.disabled = pending === 0; + button.textContent = pending ? `사이트에 올리기 (미발행 ${pending}점)` : '사이트 최신 상태'; + }catch(e){ + $('#home-note').textContent = ''; + $('#home-list').innerHTML = `${e.message}`; + } } $('#start').onclick = () => { - S.photos = []; S.facts=''; S.draft={}; + S.photos = []; S.facts=''; S.draft={}; S.lastSlug = null; + $('#after-publish').hidden = true; $('#pub-status').textContent = ''; ['#f-title','#f-subtitle','#f-body','#f-alt','#f-size','#f-material','#f-care','#f-price', '#f-pricenote','#f-naver','#note'].forEach(s=>{ if($(s)) $(s).value=''; }); $('#f-date').value = new Date().toISOString().slice(0,10); @@ -418,10 +456,15 @@ async function doPublish(deploy){ const d = await api('/api/publish', Object.assign(payload(), {deploy})); const tail = d.deployed ? '사이트에 올렸습니다. ' : (deploy ? '저장은 했지만 배포하지 못했습니다.' + (d.deploy_log||'') + '' - : '배포는 하지 않았습니다. '); + : '저장했습니다. 사이트에는 아직 안 올라갔습니다 — 목록에서 [사이트에 올리기]를 누르세요.'); $('#pub-status').innerHTML = `저장했습니다 — ${d.slug} · 커밋 ${String(d.commit).slice(0,40)}
` + tail + `상세 페이지 열기`; + S.lastSlug = d.slug; + $('#open-preview').href = d.url; + const live = $('#open-live'); + if (d.deployed && d.live_url) { live.href = d.live_url; live.hidden = false; } else { live.hidden = true; } + $('#after-publish').hidden = false; toast('등록 완료'); loadHome(); }catch(e){ $('#pub-status').innerHTML = `${e.message}`; } @@ -429,6 +472,32 @@ async function doPublish(deploy){ } $('#pub-deploy').onclick = () => doPublish(true); $('#pub-only').onclick = () => doPublish(false); +$('#to-list').onclick = () => go('home'); +document.querySelector('.brand').onclick = () => go('home'); + +/* ---------- 사이트에 올리기(배포만) ---------- */ +$('#deploy-all').onclick = async () => { + const status = $('#deploy-status'); + const run = async (force) => { + status.innerHTML = ' 사이트에 올리는 중…'; + try{ + const d = await api('/api/deploy', {force}); + status.innerHTML = d.ok ? '올렸습니다. ' + (d.log||'').split('\n').pop() : `${d.log||'실패'}`; + toast('사이트에 올렸습니다'); + loadHome(); + return true; + }catch(e){ + if (String(e.message).includes('초안')){ + if (confirm(e.message + '\n\n그 초안까지 함께 올릴까요?')) return run(true); + status.textContent = '취소했습니다'; + return true; + } + status.innerHTML = `${e.message}`; + return false; + } + }; + await run(false); +}; /* ---------- 시작 ---------- */ loadHome(); loadPresets(); diff --git a/studio/register.py b/studio/register.py index 932cbf5..0f24e56 100644 --- a/studio/register.py +++ b/studio/register.py @@ -346,14 +346,15 @@ def _to_jpeg(source: Path, target: Path, limit: int = 1400) -> None: def _other_drafts(slug: str) -> List[str]: """커밋되지 않은 다른 작품 초안. 배포하면 함께 올라가므로 미리 알린다.""" + return [name for name in pending_drafts() if not name.endswith(f"/{slug}")] + + +def pending_drafts() -> List[str]: + """커밋되지 않은 작품 초안 전체(경로 기준).""" proc = subprocess.run(["git", "status", "--porcelain", "--", "content/products"], cwd=str(ROOT), capture_output=True, text=True, timeout=30) - names: List[str] = [] - for line in (proc.stdout or "").splitlines(): - path = line[3:].strip() - if path.endswith(".md") and not path.endswith(f"/{slug}.md"): - names.append(Path(path).stem) - return names + return [Path(line[3:].strip()).stem for line in (proc.stdout or "").splitlines() + if line[3:].strip().endswith(".md")] def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]: diff --git a/studio/server.py b/studio/server.py index d0b498f..575e44c 100644 --- a/studio/server.py +++ b/studio/server.py @@ -34,6 +34,7 @@ APP = BASE / "app.html" MOBILE = BASE / "m.html" MANIFEST = BASE / "manifest.json" DIST = ROOT / "dist" +SITE_URL = os.environ.get("TEAMAT_SITE_URL", "https://teamat.lala.dedyn.io").rstrip("/") # 폰 우선 배포(QNAP)에서는 첫 화면이 등록 화면이다. 데스크톱 편집 화면은 /desk. DEFAULT_MOBILE = os.environ.get("TEAMAT_DEFAULT_PAGE", "").strip().lower() in ("m", "mobile") TOKEN_FILE = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (Path.home() / ".config" / "teamat-studio")) / "token" @@ -722,16 +723,36 @@ class Handler(BaseHTTPRequestHandler): ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream" self.send_body(200, target.read_bytes(), ctype) return + if path.startswith("/p/") or path in ("/preview", "/preview/"): + # 빌드 결과(dist)를 그대로 보여준다 — 저장만 한 작품도 여기서 확인할 수 있다. + rel = "index.html" if path.startswith("/preview") else path.lstrip("/") + target = (DIST / rel).resolve() + try: + target.relative_to(DIST.resolve()) + except ValueError: + self.send_json({"ok": False, "error": "허용되지 않은 경로"}, 403) + return + if not target.is_file(): + self.send_json({"ok": False, "error": "아직 만들어진 페이지가 없습니다"}, 404) + return + ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream" + self.send_body(200, target.read_bytes(), ctype) + return if path == "/api/presets": self.send_json({"ok": True, "presets": reg.PRESETS, "vision": reg.vision_status()}) return if path == "/api/state": rows = summaries() + web_root = os.environ.get("TEAMAT_WEB_ROOT", "").strip() + if web_root: + for row in rows: + row["live"] = (Path(web_root) / "p" / f"{row['slug']}.html").is_file() self.send_json( { "ok": True, "products": rows, "count": len(rows), + "site_url": SITE_URL, "head": head_sha(), "history": history(8), "fields": FIELDS, @@ -796,10 +817,22 @@ class Handler(BaseHTTPRequestHandler): except RuntimeError as error: self.send_json({"ok": False, "error": str(error)}, 502) return + if path == "/api/deploy": + payload = self.read_json() + drafts = reg.pending_drafts() + if drafts and not payload.get("force"): + self.send_json({"ok": False, "needs_force": True, "drafts": drafts, + "error": "커밋하지 않은 초안이 있어 배포를 멈췄습니다: " + ", ".join(drafts)}, 409) + return + ok, log = deploy() + self.send_json({"ok": ok, "log": log[-500:], "head": head_sha()}) + return if path == "/api/publish": helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push} try: - self.send_json(reg.publish(self.read_json(), helpers)) + result = reg.publish(self.read_json(), helpers) + result["live_url"] = SITE_URL + str(result.get("url") or "") + self.send_json(result) except ValueError as error: self.send_json({"ok": False, "error": str(error)}, 400) except (RuntimeError, FileNotFoundError) as error: