useUpdater

自动更新功能的 Hook

概述

useUpdater 提供了完整的自动更新流程控制。

导入

import { useUpdater } from '@linch-tech/desktop-core';

基本用法

import { useUpdater } from '@linch-tech/desktop-core';

function UpdateChecker() {
  const { status, updateInfo, progress, error, check, download, install } = useUpdater();

  return (
    <div>
      {status === 'idle' && (
        <button onClick={check}>检查更新</button>
      )}

      {status === 'checking' && <p>检查中...</p>}

      {status === 'available' && (
        <div>
          <p>发现新版本: {updateInfo?.version}</p>
          <button onClick={download}>下载更新</button>
        </div>
      )}

      {status === 'downloading' && (
        <div>
          <p>下载中: {progress?.percent}%</p>
          <progress value={progress?.percent} max={100} />
        </div>
      )}

      {status === 'ready' && (
        <button onClick={install}>立即重启</button>
      )}

      {status === 'up-to-date' && <p>已是最新版本</p>}

      {error && <p className="text-red-500">{error.message}</p>}
    </div>
  );
}

返回值

interface UseUpdaterReturn {
  enabled: boolean;             // 更新功能是否启用
  status: UpdateStatus;         // 当前状态
  updateInfo: UpdateInfo | null; // 更新信息
  progress: UpdateProgress | null; // 下载进度
  error: Error | null;          // 错误信息
  check: () => Promise<UpdateInfo>; // 检查更新
  download: () => Promise<void>;    // 下载更新
  install: () => Promise<void>;     // 安装并重启
}

参数

useUpdater(options?: { enabled?: boolean })

如果 enabledfalse,所有操作都会返回禁用错误。

状态说明

type UpdateStatus =
  | 'idle'           // 初始状态
  | 'checking'       // 检查更新中
  | 'available'      // 有可用更新
  | 'up-to-date'     // 已是最新版本
  | 'downloading'    // 下载中
  | 'ready'          // 准备安装
  | 'check-error'    // 检查失败
  | 'download-error' // 下载失败

更新信息

interface UpdateInfo {
  available: boolean;  // 是否有可用更新
  version?: string;    // 新版本号
  notes?: string;      // 更新说明
  date?: string;       // 发布日期
}

下载进度

interface UpdateProgress {
  downloaded: number;  // 已下载字节
  total: number;       // 总字节数
  percent: number;     // 进度百分比 (0-100)
}

启动时自动检查

import { useEffect } from 'react';
import { useUpdater } from '@linch-tech/desktop-core';

function App() {
  const { check } = useUpdater();

  useEffect(() => {
    // 启动后 2 秒检查更新
    const timer = setTimeout(() => {
      check().catch(console.error);
    }, 2000);

    return () => clearTimeout(timer);
  }, [check]);

  return <MainApp />;
}

配合 SettingsPage 使用

SettingsPage 组件已内置更新 UI,无需额外编写:

import { SettingsPage } from '@linch-tech/desktop-core';

function Settings() {
  return <SettingsPage />;
}

配置要求

要使自动更新工作,需要:

  1. features.updatertrue(默认)
  2. tauri.conf.json 中配置 updater
{
  "plugins": {
    "updater": {
      "endpoints": [
        "https://your-server.com/updates/{{target}}/{{arch}}/{{current_version}}"
      ],
      "pubkey": "your-public-key"
    }
  }
}

注意事项

更新功能仅在生产构建中可用,开发模式下 check() 会返回 "up-to-date"。

install() 会重启应用。确保在调用前保存所有用户数据。