示例工程 56-auto-update

56-auto-update/app/.tsc/src/App.js

javascript · 14 KB

function escapeHtml(text) {
    return text.replace(/[&<>"]/g, (char) => {
        if (char === "&")
            return "&amp;";
        if (char === "<")
            return "&lt;";
        if (char === ">")
            return "&gt;";
        return "&quot;";
    });
}
function time(at) {
    return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function checkRow(check) {
    return `<li class="check-row" data-testid="check-row">
    <span class="tag ${check.pass ? "ok" : "bad"}">${check.pass ? "PASS" : "FAIL"}</span>
    <span>${escapeHtml(check.label)}</span>
    <code>${escapeHtml(check.detail)}</code>
  </li>`;
}
function schemeRow(row) {
    return `<tr data-testid="scheme-row" data-scheme="${row.id}">
    <td><b>${escapeHtml(row.name)}</b></td>
    <td>${escapeHtml(row.feed)}</td>
    <td>${escapeHtml(row.updates)}</td>
    <td>${escapeHtml(row.limits)}</td>
  </tr>`;
}
function feedButton(row, active) {
    return `<button class="btn ${active ? "primary" : ""}" data-testid="feed-${row.id}">${escapeHtml(row.label)}</button>`;
}
export function mountApp(root) {
    root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <span class="logo">U</span>
          <div>
            <h1>自动更新决策台</h1>
            <span class="muted small">feed 解析 · 版本决策 · 提示状态机 · 不安装替换</span>
          </div>
        </div>
        <div class="header-side">
          <span class="pill warn-pill">只决策 · 不安装</span>
          <span class="pill ok-pill" data-testid="score">—</span>
          <button class="btn" data-testid="refresh">重新检查</button>
        </div>
      </header>

      <div class="banner" data-testid="banner">
        本章只验证 feed 元数据、版本比较与提示状态;不下载、不替换安装包。
      </div>

      <main class="layout">
        <div class="column">
          <section class="card pad schemes-card">
            <div class="card-head">
              <h2>四类更新方案</h2>
              <span class="muted small" data-testid="scheme-count">—</span>
            </div>
            <table class="matrix">
              <thead><tr><th>方案</th><th>feed</th><th>更新方</th><th>限制</th></tr></thead>
              <tbody data-testid="schemes"></tbody>
            </table>
          </section>

          <section class="card pad decision-card">
            <div class="card-head">
              <h2>检查与决策</h2>
              <span class="muted small" data-testid="decision-state">—</span>
            </div>
            <div class="controls">
              <div class="feed-buttons" data-testid="feed-buttons"></div>
              <span class="muted small">当前版本 <code data-testid="current-version">—</code></span>
            </div>
            <div class="decision" data-testid="decision"></div>
            <div class="actions" data-testid="prompt-actions"></div>
            <p class="muted small prompt-note" data-testid="prompt-note">
              提示状态只影响 UI,不会触发下载或安装。
            </p>
          </section>
        </div>

        <div class="column">
          <section class="card pad feed-card">
            <div class="card-head">
              <h2>Feed 预览</h2>
              <span class="muted small" data-testid="feed-label">—</span>
            </div>
            <pre class="feed-raw" data-testid="feed-raw"></pre>
          </section>

          <section class="card pad eligibility-card">
            <div class="card-head">
              <h2>官方服务门槛</h2>
              <span class="muted small">update.electronjs.org</span>
            </div>
            <ul class="eligibility" data-testid="eligibility"></ul>
            <p class="muted small eligibility-note">
              需要公开 GitHub 仓库 + GitHub Releases;仅 macOS/Windows;
              macOS 需签名;不支持 Linux。
            </p>
          </section>

          <section class="card pad checks-card">
            <div class="card-head">
              <h2>决策自检</h2>
              <span class="muted small" data-testid="check-count">—</span>
            </div>
            <ul class="checks" data-testid="checks"></ul>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>活动</h2>
              <span class="muted small">解析 / 决策</span>
            </div>
            <ul class="activity" data-testid="events"></ul>
          </section>
        </div>
      </main>
    </div>
  `;
    const score = root.querySelector('[data-testid="score"]');
    const schemeCount = root.querySelector('[data-testid="scheme-count"]');
    const schemesEl = root.querySelector('[data-testid="schemes"]');
    const feedButtons = root.querySelector('[data-testid="feed-buttons"]');
    const currentVersion = root.querySelector('[data-testid="current-version"]');
    const decisionState = root.querySelector('[data-testid="decision-state"]');
    const decisionEl = root.querySelector('[data-testid="decision"]');
    const promptActions = root.querySelector('[data-testid="prompt-actions"]');
    const promptNote = root.querySelector('[data-testid="prompt-note"]');
    const feedLabel = root.querySelector('[data-testid="feed-label"]');
    const feedRaw = root.querySelector('[data-testid="feed-raw"]');
    const eligibilityEl = root.querySelector('[data-testid="eligibility"]');
    const checksEl = root.querySelector('[data-testid="checks"]');
    const checkCount = root.querySelector('[data-testid="check-count"]');
    const eventsEl = root.querySelector('[data-testid="events"]');
    let state = null;
    let selectedFeed = "mac";
    let prompt = "idle";
    function feed() {
        return state?.feeds.find((row) => row.id === selectedFeed);
    }
    function renderSchemes() {
        if (!state)
            return;
        if (schemesEl)
            schemesEl.innerHTML = state.schemes.map(schemeRow).join("");
        if (schemeCount)
            schemeCount.textContent = `${state.schemes.length} 类方案`;
    }
    function renderFeed() {
        if (!state)
            return;
        const row = feed();
        if (feedButtons) {
            feedButtons.innerHTML = state.feeds
                .map((item) => feedButton(item, item.id === selectedFeed))
                .join("");
            for (const item of state.feeds) {
                root
                    .querySelector(`[data-testid="feed-${item.id}"]`)
                    ?.addEventListener("click", () => {
                    selectedFeed = item.id;
                    prompt = "idle";
                    renderFeed();
                    renderDecision();
                });
            }
        }
        if (currentVersion)
            currentVersion.textContent = state.currentVersion;
        if (feedLabel)
            feedLabel.textContent = row?.label ?? "—";
        if (feedRaw)
            feedRaw.textContent = (row?.raw ?? "").slice(0, 520);
        if (decisionState) {
            decisionState.textContent = row?.decision.status ?? "—";
            decisionState.className = `muted small status-${row?.decision.status ?? "none"}`;
        }
    }
    function renderDecision() {
        const row = feed();
        if (!row)
            return;
        const decision = row.decision;
        if (decisionEl) {
            const tag = decision.status === "update"
                ? '<span class="tag ok">有更新</span>'
                : decision.status === "none"
                    ? '<span class="tag warn">已是最新</span>'
                    : '<span class="tag bad">feed 错误</span>';
            decisionEl.innerHTML = `
        <div class="decision-head">${tag}
          <b>${escapeHtml(decision.current)} → ${escapeHtml(decision.latest || "—")}</b>
          <code>${escapeHtml(decision.reason)}</code>
        </div>
        <p class="muted small">${escapeHtml(decision.notes || "无 release notes")}</p>`;
        }
        if (promptActions) {
            promptActions.innerHTML =
                decision.status === "update"
                    ? `<button class="btn" data-testid="action-later">稍后</button>
             <button class="btn" data-testid="action-skip">忽略此版本</button>
             <button class="btn primary" data-testid="action-download">下载(模拟)</button>`
                    : `<button class="btn" data-testid="action-check">再次检查</button>`;
            const later = root.querySelector('[data-testid="action-later"]');
            const skip = root.querySelector('[data-testid="action-skip"]');
            const download = root.querySelector('[data-testid="action-download"]');
            const check = root.querySelector('[data-testid="action-check"]');
            later?.addEventListener("click", () => {
                prompt = "deferred";
                updatePromptNote();
            });
            skip?.addEventListener("click", () => {
                prompt = "skipped";
                updatePromptNote();
            });
            download?.addEventListener("click", () => {
                prompt = "downloading";
                updatePromptNote();
            });
            check?.addEventListener("click", () => {
                prompt = "idle";
                updatePromptNote();
            });
        }
        updatePromptNote();
    }
    function updatePromptNote() {
        if (!promptNote)
            return;
        const label = prompt === "deferred"
            ? "已推迟:下次启动再提示(仅 UI 状态)"
            : prompt === "skipped"
                ? "已忽略此版本:不再提示该版本(仅 UI 状态)"
                : prompt === "downloading"
                    ? "模拟下载中:不会写入磁盘,也不会安装(仅 UI 状态)"
                    : "提示状态只影响 UI,不会触发下载或安装。";
        promptNote.textContent = label;
        promptNote.className = `muted small prompt-note ${prompt === "idle" ? "" : "active"}`;
    }
    function renderEligibility() {
        if (!eligibilityEl)
            return;
        const rows = [
            ["公开 GitHub 仓库", true, "必需"],
            ["GitHub Releases", true, "必需"],
            ["macOS + 签名", true, "可用"],
            ["Windows", true, "可用"],
            ["Linux", false, "不支持"],
            ["私有仓库", false, "不支持"],
        ];
        eligibilityEl.innerHTML = rows
            .map(([label, ok, note]) => `<li class="elig-row">
          <span class="tag ${ok ? "ok" : "bad"}">${ok ? "可" : "否"}</span>
          <span>${escapeHtml(label)}</span>
          <span class="muted small">${escapeHtml(note)}</span>
        </li>`)
            .join("");
    }
    function renderChecks() {
        if (!state)
            return;
        if (checksEl)
            checksEl.innerHTML = state.checks.map(checkRow).join("");
        if (checkCount) {
            const passed = state.checks.filter((check) => check.pass).length;
            checkCount.textContent = `${passed}/${state.checks.length} 通过`;
        }
        if (score) {
            score.textContent = `${state.score} / 100`;
            score.className = `pill ${state.score === 100 ? "ok-pill" : "bad-pill"}`;
        }
    }
    function renderEvents() {
        if (!eventsEl || !state)
            return;
        eventsEl.innerHTML =
            state.events.length === 0
                ? `<li class="muted small">暂无活动</li>`
                : state.events
                    .slice(0, 8)
                    .map((row) => `
              <li class="event-row" data-testid="event-row">
                <span class="muted">${time(row.at)}</span>
                <span class="kind">${escapeHtml(row.kind)}</span>
                <span>${escapeHtml(row.detail)}</span>
              </li>`)
                    .join("");
    }
    function render(next) {
        state = next;
        renderSchemes();
        renderFeed();
        renderDecision();
        renderEligibility();
        renderChecks();
        renderEvents();
    }
    void window.api.updates.snapshot().then(render);
    window.api.updates.onEvent(() => {
        void window.api.updates.snapshot().then(render);
    });
    root
        .querySelector('[data-testid="refresh"]')
        ?.addEventListener("click", async () => {
        render(await window.api.updates.refresh());
    });
    window.__prepareShots = async (stage) => {
        document.body.dataset.shot = stage;
        render(await window.api.updates.refresh());
        if (stage === "available") {
            selectedFeed = "mac";
            prompt = "idle";
            renderFeed();
            renderDecision();
            document
                .querySelector(".decision-card")
                ?.scrollIntoView({ block: "start" });
        }
        else if (stage === "limits") {
            selectedFeed = "invalid";
            prompt = "idle";
            renderFeed();
            renderDecision();
            document
                .querySelector(".eligibility-card")
                ?.scrollIntoView({ block: "start" });
        }
        else {
            selectedFeed = "mac";
            prompt = "idle";
            renderFeed();
            renderDecision();
            document
                .querySelector(".schemes-card")
                ?.scrollIntoView({ block: "start" });
        }
    };
    window.__demo = async () => {
        const next = await window.api.updates.snapshot();
        state = next;
        const find = (id) => next.feeds.find((row) => row.id === id);
        return {
            score: next.score,
            checks: next.checks.length,
            passed: next.checks.filter((check) => check.pass).length,
            schemes: next.schemes.length,
            feeds: next.feeds.length,
            macStatus: find("mac")?.decision.status ?? "",
            macLatest: find("mac")?.decision.latest ?? "",
            winStatus: find("win")?.decision.status ?? "",
            winLatest: find("win")?.decision.latest ?? "",
            noneStatus: find("none")?.decision.status ?? "",
            invalidStatus: find("invalid")?.decision.status ?? "",
            noInstall: next.checks.find((check) => check.id === "no-install")?.pass ?? false,
        };
    };
}
//# sourceMappingURL=App.js.map