在鸿蒙 PC 上用 Electron 写鸿蒙 PC 应用:星枢 AstroHub 的跨平台框架落地与 16 路能力调用拓扑

在鸿蒙 PC 上用 Electron 写鸿蒙 PC 应用:星枢 AstroHub 的跨平台框架落地与 16 路能力调用拓扑

欢迎加入开源鸿蒙PC社区: https://harmonypc.csdn.net/
欢迎在PC社区平台申请新建项目:https://atomgit.com/OpenHarmonyPCDeveloper

基于 Electron 的鸿蒙化适配项目地址:https://atomgit.com/CPF-Electron/Electron

一、前言

鸿蒙 PC 出来之后,我一直在想一个很实际的问题:如果团队手里已经有一整套前端工程能力和 Node 生态积累,能不能不重写 UI,直接在鸿蒙 PC 上产出原生 HAP 应用?答案是能,路径就是 Electron 这条跨平台框架路线------但"能跑"和"跑得像个桌面应用"之间隔着不少工程细节。

星枢 AstroHub 是我在鸿蒙 PC 本机上完整开发、签名、装包、上屏的一个能力调用拓扑星图应用。它把文件、外设、系统三类共 16 路能力抽象成绕内核运行的三条轨道星体,点亮星体即发起一次调用,调用脉冲沿连线往返,右侧遥测面板实时给出成功率等级、平均响应和各轨活跃度。整个业务层是纯 JavaScript(Electron 主进程 + 预加载 + 渲染进程 + 一个无副作用的纯函数引擎),壳层是官方 Electron for HarmonyOS 的 ArkTS 工程,最终产物是一个签名 HAP。

这篇文章不复述"Electron 是什么",而是把这条跨平台框架在鸿蒙 PC 上的真实形态拆开:三层结构怎么分工、业务代码凭什么能热插拔、主进程的安全基线和 IPC 可信校验怎么写、16 路能力如何建模成可测的纯函数、星图为什么选 SVG 而不是图表库、以及从 hap:sign 到 hdc install 上屏时踩到的五个坑。所有代码都来自这个工程本身,截图都是鸿蒙 PC 桌面上的完整窗口。

关键词:鸿蒙 PC、Electron、跨平台框架、ArkTS、HAP 打包、能力调用拓扑、调用链追踪、contextIsolation

图:DevEco Studio Beta 启动画面。工程在鸿蒙PC电脑上完成编辑、构建与真机运行。

二、先把形态说清楚:Electron 在鸿蒙 PC 上是三层,不是一层

很多同学对"Electron 上鸿蒙"的第一反应是"PC 版的 Electron 安装包打不进 HAP 吧"。确实,OpenHarmony 上没有 npm 官方 Electron 二进制,node_modules/electron 那条 postinstall 下载链路在这里是断的。所以这个工程的 check.mjs 里有一条硬性断言:

js 复制代码
if (rootPackage.devDependencies?.electron) {
  throw new Error('不应依赖 npm 标准 Electron:OpenHarmony 无官方二进制,业务代码运行在 HAP 内的 libelectron.so');
}

真正的运行形态是三层:

  1. HAP 壳层(ArkTS) :hap/ 下的官方工程,包含 electron、web_engine、account_quick_login 三个模块。electron 模块的 libs/arm64-v8a/ 里放着 libelectron.so 与 libadapter.so------前者是 Electron 运行时本体(内核里带 Chromium 与 Node),后者是 ArkTS 与 C++ 之间的适配桥。
  2. 窗口承载层(ArkUI) :web_engine 导出一个 WebWindow 组件,本质是 XComponent 表面,Electron 的渲染输出直接贴在这个 native surface 上。所以你在鸿蒙 PC 上看到的应用窗口,是 ArkUI 窗口 + XComponent + Chromium 合成后的结果。
  3. 业务层(JavaScript) :Electron 的 app 目录,落在 hap/web_engine/src/main/resources/resfile/resources/app,里面就是普通的 package.json + main.js + index.html。Electron 主进程启动后按 package.json 的 main 字段加载入口,剩下的事情和在任何桌面系统上写 Electron 完全一样。

窗口承载那一层非常薄,Index.ets 全文六十来行,核心只有这些:

ets 复制代码
@Entry(storage)
@Component
struct Index {
  @LocalStorageLink('xcomponentId') xComponentId: string = '';
  @LocalStorageProp('statusBarHeight') statusBarHeight: number = 0;
  @State density: number = 0;
  private nativeContext: NativeContext =
    JsBindingUtils.getNativeContext(ContextType.kMainProcess);

  aboutToAppear(): void {
    uiObserver.on('densityUpdate', this.getUIContext(), (info: uiObserver.DensityInfo) => {
      this.density = info.density;
    });
  }

  build() {
    Row() {
      WebWindow()          // ← XComponent 表面,Chromium 画面贴在这里
    }
    .width('100%')
    .height('100%')
    .padding({ top: this.getStatusBarHeight() })
  }
}

注意 padding({ top: this.getStatusBarHeight() }) 这一句。鸿蒙 PC 的窗口顶部有系统自绘的状态区(时间、输入法、电量那一行),statusBarHeight 从 LocalStorage 进来,再经 px2vp 换算成 vp 才拿去留白------直接拿 px 用会在不同缩放的屏幕上错位。这一层做好之后,业务侧完全感知不到自己是跑在鸿蒙 PC 上还是别的桌面系统,除了一个字段:process.platform。

三、一个仓库,两种宿主:业务代码凭什么能换

工程根目录的 hap.config.json 是整个仓库的唯一事实源,七个字段决定了业务代码往哪注入、包名是什么、构建产物在哪:

json 复制代码
{
  "bundleName": "com.astrohub.atlas",
  "moduleName": "electron",
  "abilityName": "EntryAbility",
  "productName": "default",
  "sdkBranch": "v40.0.1",
  "runtimeDirectory": "web_engine/src/main/resources/resfile/resources",
  "hmosCltHome": "/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0"
}

hap-sync.mjs 做的事非常克制:整目录删掉 resources/app,把根目录 app/ 拷进去,然后校验两侧 package.json 的 main 指向的文件确实存在。它刻意不碰 Chromium 的运行时资源,也不碰 libelectron.so------那部分是官方交付物,改动它等于自己维护一个 Chromium 分支。

js 复制代码
await rm(paths.app, { recursive: true, force: true });
await cp(source, paths.app, { recursive: true });
const syncedPackage = await readJson(path.join(paths.app, 'package.json'));
await readFile(path.join(paths.app, syncedPackage.main), 'utf8');
console.log('Chromium 运行时资源与官方动态库保持原样');

这套结构带来一个很舒服的开发节奏:日常写业务就在根目录 app/ 里改,用浏览器直接打开 index.html 就能看渲染结果(没有 Electron 桥的时候,运行探测会自动降级,星图动画、脉冲、遥测逻辑全部照跑);要出 HAP 时执行一次 hap:sync,注入、打包、装机走流水线。同一份业务代码,两种宿主,零分支。

这里有个容易忽略的点:assertOfficialHap 会逐个检查 libelectron.so、libadapter.so、AppScope/app.json5、build-profile.json5 是否存在,缺一个就直接报"HAP 工程不完整"。这个断言的价值不在于报错,而在于让"壳工程是外部交付物"这件事在代码里显式化------新手最常犯的错就是以为 hap/ 是 npm run build 生成的产物。

四、主进程:窗口生命周期与安全基线

鸿蒙 PC 上的 Electron 主进程,和 Windows 上写起来没区别,但有几个必须踩准的开关。这是 main.js 的窗口创建段:

js 复制代码
// 鸿蒙 PC 上 platform 实测返回 'openharmony',也见过 'ohos',两者都要识别
const isOhos = process.platform === 'ohos' || process.platform === 'openharmony';

function createWindow() {
  mainWindow = new BrowserWindow({
    title: '星枢 AstroHub · 能力调用拓扑星图',
    width: 1600, height: 1000, minWidth: 900, minHeight: 620,
    backgroundColor: '#060a18',
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webSecurity: true,
      allowRunningInsecureContent: false
    }
  });

  mainWindow.once('ready-to-show', () => { mainWindow?.show(); });
  mainWindow.loadFile(indexPath).catch((error) => {
    console.error('[astrohub] loadFile 失败:', error.message);
    mainWindow?.loadURL(pathToFileURL(indexPath).href);
  });
}

show: false 配 ready-to-show 是为了避免 Chromium 首帧未合成时先露出底色,鸿蒙 PC 上窗口合成比传统桌面更快,不加这个会看到一次明显的深色闪屏。loadFile 后面挂 catch 也是有原因的:HAP 内的资源路径是 resfile 映射出来的,loadFile 在某些运行时版本上会因路径规范问题失败,退化成 pathToFileURL 能救回来。

platform 那个双值判断值得单独说。同一个运行时,不同版本里 process.platform 可能返回 'openharmony' 也可能返回 'ohos',只认一个就会出现"明明跑在鸿蒙 PC 上,遥测却退回降级状态"的诡异现象。工程里对它做了两处断言:main.js 里识别双值,check.mjs 里也强制要求源码同时包含两个字面量,防止后续重构时被顺手删掉。

安全边界这边,Electron 的经典五件套之外,还多加了三道鸿蒙 PC 场景下的约束。第一道是权限请求一律拒绝------Electron 侧的 setPermissionRequestHandler 拦的是 Chromium 权限(地理位置、媒体设备等),这些能力应该走 ArkTS 侧的系统授权,而不是让网页层自己决定:

js 复制代码
app.whenReady().then(() => {
  session.defaultSession.setPermissionRequestHandler((_webContents, _permission, callback) => {
    callback(false);
  });

  ipcMain.handle('runtime:get', (event) => {
    assertTrustedSender(event);
    return getRuntimeInfo(app, process);
  });

  ipcMain.handle('system:probe', (event) => {
    assertTrustedSender(event);
    const usage = process.memoryUsage();
    return {
      platform: process.platform,
      architecture: process.arch,
      uptime: Math.round(process.uptime()),
      memoryMB: Math.round(usage.heapUsed / 1024 / 1024),
      ohos: isOhos
    };
  });

  // 鸿蒙 PC 窗口自带系统菜单区,应用内菜单必须置空,否则叠成两层
  Menu.setApplicationMenu(null);
  createWindow();
});

第二道是 IPC 发起方校验。file: 协议的 URL 有个特性:origin 是 null,拿 origin 做白名单毫无意义,所以只能比协议 + 规范化路径 + 拒绝查询串和片段:

js 复制代码
function isTrustedUrl(candidate, indexPath) {
  if (!candidate || typeof candidate !== 'string') return false;
  try {
    const url = new URL(candidate);
    const trusted = pathToFileURL(indexPath);
    return url.protocol === 'file:' && url.origin === trusted.origin &&
      url.pathname === trusted.pathname && !url.search && !url.hash;
  } catch {
    return false;
  }
}

多出来的 !url.search && !url.hash 不是洁癖。file:///.../index.html?payload=... 这类拼接在桌面端被大量钓鱼手法复用,路径白名单放行它,等于给渲染层开了一个可以把参数喂进主进程的口子。同一套判断同时用在 will-navigate 与 setWindowOpenHandler 上,任何试图把窗口导航去外部的行为都会被 preventDefault。

第三道是预加载白名单。渲染进程拿不到 ipcRenderer,只能看到两个方法:

js 复制代码
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('astrohub', {
  getRuntime: () => ipcRenderer.invoke('runtime:get'),
  probeSystem: () => ipcRenderer.invoke('system:probe')
});

加上 index.html 里那条 default-src 'self'; script-src 'self'; object-src 'none' 的 CSP,渲染层的攻击面就被压到很小了。顺带说明 sandbox: false 这个看起来"不安全"的设置:官方运行时下预加载脚本需要拿到完整的 Node 模块能力才能稳定桥接,实测关闭沙箱后桥接才稳定;补偿手段就是 contextIsolation: true + nodeIntegration: false + 只暴露两个白名单方法,这三条在 check.mjs 里都是硬断言,改错一个直接构建失败。
#mermaid-svg-392MH4fxViWFyrTw{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-392MH4fxViWFyrTw .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-392MH4fxViWFyrTw .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-392MH4fxViWFyrTw .error-icon{fill:#552222;}#mermaid-svg-392MH4fxViWFyrTw .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-392MH4fxViWFyrTw .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-392MH4fxViWFyrTw .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-392MH4fxViWFyrTw .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-392MH4fxViWFyrTw .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-392MH4fxViWFyrTw .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-392MH4fxViWFyrTw .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-392MH4fxViWFyrTw .marker{fill:#333333;stroke:#333333;}#mermaid-svg-392MH4fxViWFyrTw .marker.cross{stroke:#333333;}#mermaid-svg-392MH4fxViWFyrTw svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-392MH4fxViWFyrTw p{margin:0;}#mermaid-svg-392MH4fxViWFyrTw .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-392MH4fxViWFyrTw .cluster-label text{fill:#333;}#mermaid-svg-392MH4fxViWFyrTw .cluster-label span{color:#333;}#mermaid-svg-392MH4fxViWFyrTw .cluster-label span p{background-color:transparent;}#mermaid-svg-392MH4fxViWFyrTw .label text,#mermaid-svg-392MH4fxViWFyrTw span{fill:#333;color:#333;}#mermaid-svg-392MH4fxViWFyrTw .node rect,#mermaid-svg-392MH4fxViWFyrTw .node circle,#mermaid-svg-392MH4fxViWFyrTw .node ellipse,#mermaid-svg-392MH4fxViWFyrTw .node polygon,#mermaid-svg-392MH4fxViWFyrTw .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-392MH4fxViWFyrTw .rough-node .label text,#mermaid-svg-392MH4fxViWFyrTw .node .label text,#mermaid-svg-392MH4fxViWFyrTw .image-shape .label,#mermaid-svg-392MH4fxViWFyrTw .icon-shape .label{text-anchor:middle;}#mermaid-svg-392MH4fxViWFyrTw .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-392MH4fxViWFyrTw .rough-node .label,#mermaid-svg-392MH4fxViWFyrTw .node .label,#mermaid-svg-392MH4fxViWFyrTw .image-shape .label,#mermaid-svg-392MH4fxViWFyrTw .icon-shape .label{text-align:center;}#mermaid-svg-392MH4fxViWFyrTw .node.clickable{cursor:pointer;}#mermaid-svg-392MH4fxViWFyrTw .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-392MH4fxViWFyrTw .arrowheadPath{fill:#333333;}#mermaid-svg-392MH4fxViWFyrTw .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-392MH4fxViWFyrTw .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-392MH4fxViWFyrTw .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-392MH4fxViWFyrTw .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-392MH4fxViWFyrTw .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-392MH4fxViWFyrTw .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-392MH4fxViWFyrTw .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-392MH4fxViWFyrTw .cluster text{fill:#333;}#mermaid-svg-392MH4fxViWFyrTw .cluster span{color:#333;}#mermaid-svg-392MH4fxViWFyrTw div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-392MH4fxViWFyrTw .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-392MH4fxViWFyrTw rect.text{fill:none;stroke-width:0;}#mermaid-svg-392MH4fxViWFyrTw .icon-shape,#mermaid-svg-392MH4fxViWFyrTw .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-392MH4fxViWFyrTw .icon-shape p,#mermaid-svg-392MH4fxViWFyrTw .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-392MH4fxViWFyrTw .icon-shape .label rect,#mermaid-svg-392MH4fxViWFyrTw .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-392MH4fxViWFyrTw .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-392MH4fxViWFyrTw .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-392MH4fxViWFyrTw :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 16 路能力
轨一 数据
轨二 外设
轨三 系统
三轨星表
拓扑星图 Canvas
能力探针

图:16 路能力归入三条轨道形成星表,探针真实读数驱动拓扑星图的节点亮度。

五、把 16 路能力建成三轨星表:先建模,再画图

这个应用真正花时间的不是渲染,是"能力"这件事怎么抽象。鸿蒙 PC 的系统能力散落在几十个 @ohos.* 模块里,直接平铺成列表会变成文档搬运。我按"谁在管资源"切成三类,每类一条轨道:

轨道 数量 代表 API 交互特征
文件轨 FILE 5 @ohos.file.picker、@ohos.file.fs、@ohos.fileShare、@ohos.zlib 选、读、授权、压缩,链路短但权限敏感
外设轨 DEVICE 5 @ohos.bluetooth、@ohos.usbManager、@ohos.multimodalInput、@ohos.multimedia.camera 需要设备在场,耗时波动大
系统轨 SYSTEM 6 @ohos.pasteboard、@ohos.batteryInfo、@ohos.net.connection、@ohos.window 全局单例,响应稳定

轨道几何是数据的一部分,不是 CSS:

js 复制代码
export const CATEGORY_META = {
  file:       { key: 'file',       label: '文件', latin: 'FILE',   color: '#5eead4', radius: 132, start: -90 },
  peripheral: { key: 'peripheral', label: '外设', latin: 'DEVICE', color: '#a78bfa', radius: 214, start: -62 },
  system:     { key: 'system',     label: '系统', latin: 'SYSTEM', color: '#fbbf24', radius: 296, start: -78 }
};

半径 132 / 214 / 296 是三个同心圆,start 角度各不相同(-90、-62、-78),这样三条轨道上最近的两个星体不会在视觉上连成一条直线,脉冲往返时也不会撞在一起。如果三条轨都从 -90 起排,文件轨和系统轨的节点会在同一方位角上重叠,点击命中测试就会打架。

每条能力记录还带两样东西:risk 和 latency。risk 分三档------normal 直接成功、sensitive 需要授权、restricted 形态受限;latency 是该 API 的基准耗时。判定逻辑是一个纯函数,抖动由调用方注入,这样 node --test 里可以精确断言:

js 复制代码
export function invocationResult(capability, context = {}) {
  const mode = context.mode === 'device' ? 'device' : 'preview';
  const jitter = Math.min(1, Math.max(0, Number(context.jitter) || 0));
  const latency = Math.round(capability.latency * (0.82 + 0.36 * jitter));
  const base = { id: capability.id, name: capability.name, api: capability.api,
    at: Number(context.at) || 0, seq: Math.max(0, Math.round(Number(context.sequence) || 0)),
    latency, mode };
  if (capability.risk === 'restricted') {
    return { ...base, ok: false, status: 'blocked', reason: '当前 PC 形态不提供该能力' };
  }
  if (capability.risk === 'sensitive') {
    return { ...base, ok: true, status: mode === 'device' ? 'granted' : 'simulated', reason: '' };
  }
  return { ...base, ok: true, status: mode === 'device' ? 'ok' : 'simulated', reason: '' };
}

0.82 + 0.36 * jitter 把抖动限定在 ±18% 的带宽内,测试里传 jitter: 0.5 得到的就是基准值本身,断言可以写成 latency === 12 这种硬数字,不需要快照或容差。这是纯函数建模最实际的收益:行为和渲染彻底解耦,界面上看到的一切都可以在 Node 里用断言钉住。

restricted 那档也值得说一下。马达振动在鸿蒙 PC 的形态下没有执行器,但它仍然在星表里,调用时脉冲照样往返内核,只是链路日志标红并写明"当前 PC 形态不提供该能力"。把"不支持"做成显式状态,比静默过滤掉这类能力更有信息量------用户能知道这条路为什么走不通。

六、星图渲染:SVG 六层 + 一帧一算的脉冲

星图画布是 SVG,viewBox 定死 0 0 1000 720,里面叠了六个 <g> 图层,顺序就是绘制顺序:

html 复制代码
<g id="bg-layer"></g>     <!-- 星云 + 96 颗固定星点 -->
<g id="orbit-layer"></g>  <!-- 三条轨道环与类别标签 -->
<g id="link-layer"></g>   <!-- 内核到星体的连线 -->
<g id="core-layer"></g>   <!-- 内核圆盘 -->
<g id="node-layer"></g>   <!-- 星体节点,承载点击 -->
<g id="pulse-layer"></g>  <!-- 脉冲点,最上层,永不遮挡点击 -->

选 SVG 而不是 Canvas,理由很具体:节点只有 16 个,SVG 的 DOM 自带命中测试,event.target.closest('.node-group') 一行就能把点击落到正确的星体上,还能顺手用 [data-pin] 区分"钉选"和"调用"两种点击意图。用 Canvas 的话得自己写一遍圆形碰撞检测,为了 16 个节点不值当。悬浮浮卡也是同理,直接读 getBoundingClientRect() 做边界钳制即可。

节点坐标由极坐标换算,同类能力均分圆周:

js 复制代码
export function layoutNodes(catalog, geometry = {}) {
  const cx = geometry.cx ?? 500, cy = geometry.cy ?? 360;
  const nodes = [];
  for (const category of CATEGORY_ORDER) {
    const meta = CATEGORY_META[category];
    const members = catalog.filter((item) => item.category === category);
    members.forEach((item, index) => {
      const angleDeg = meta.start + (360 / members.length) * index;
      const point = orbitPoint({ cx, cy, radius: meta.radius, angleDeg });
      nodes.push({ ...item, angleDeg, x: point.x, y: point.y, color: meta.color });
    });
  }
  return nodes;
}

这里有个容易忽略的取舍:layoutNodes 只对已点亮的能力排布。文件轨 5 路全亮时是 72° 一档,只亮 2 路时就是 180° 一档------星体会自动散开,永远不会出现"点亮三路以后全挤在左上角"的情况。代价是每次点亮都要重排,节点换位时有位移感;我接受这个代价,因为"轨道随能力数量自适应"本身就是这个界面的主要叙事。

脉冲是逐帧算的,一次往返 720 ms,前三段加速冲进内核,后三段减速折返:

js 复制代码
function animatePulse(node, color) {
  const dot = svgEl('circle', { r: 7, class: 'pulse-dot', fill: color });
  const ring = svgEl('circle', { r: 15, class: 'pulse-ring', stroke: color });
  el.pulseLayer.append(dot, ring);
  const start = performance.now();
  const duration = 720;
  function frame(now) {
    const t = Math.min(1, (now - start) / duration);
    const phase = t < 0.62 ? t / 0.62 : (1 - t) / 0.38;
    const eased = phase * phase * (3 - 2 * phase);          // smoothstep
    const x = node.x + (GEOMETRY.cx - node.x) * eased;
    const y = node.y + (GEOMETRY.cy - node.y) * eased;
    dot.setAttribute('cx', x.toFixed(1));
    dot.setAttribute('cy', y.toFixed(1));
    ring.setAttribute('cx', x.toFixed(1));
    ring.setAttribute('cy', y.toFixed(1));
    ring.setAttribute('r', (12 + 7 * Math.sin(t * Math.PI)).toFixed(1));
    ring.setAttribute('opacity', (0.9 * (1 - t)).toFixed(2));
    if (t < 1) requestAnimationFrame(frame);
    else { dot.remove(); ring.remove(); }
  }
  requestAnimationFrame(frame);
  window.setTimeout(() => flashCore(color), 420);
}

0.62 / 0.38 这个不对称的折返点是调出来的:去程要冲得快才有"发射"的感觉,回程稍慢一点才像是"内核处理完把结果送回来"。flashCore 延迟 420 ms 触发,正好落在脉冲抵达内核的时间点上,内核圆盘的 drop-shadow 会跟着亮一下,视觉上形成"星体 → 内核 → 星体"的因果链。这段动画没有任何 setTimeout 堆叠,全部挂在 requestAnimationFrame 上,窗口最小化或系统降频时 now 的步长会自动变大,不会积压回调。

背景那 96 颗星点用了固定种子的线性同余发生器,而不是 Math.random():

js 复制代码
let seed = 20261118;
const random = () => {
  seed = (seed * 1664525 + 1013904223) % 4294967296;
  return seed / 4294967296;
};

原因很直白------星图会随着点亮、筛选、重置反复重绘背景层,用真随机的话每次重绘星点都会跳位置,看起来像屏幕在抖。固定种子让背景成为一张稳定的底图,重绘多少次都是同一张脸。

七、遥测:把"成功率"变成一个能读的等级

右侧面板的三块读数------健康度圆环、平均响应、轨道活跃度------全部由同一个汇总函数产出:

js 复制代码
export function summarize(nodes, traces) {
  const total = traces.length;
  const success = traces.filter((item) => item.ok).length;
  const avgLatency = total === 0 ? 0
    : Math.round(traces.reduce((sum, item) => sum + item.latency, 0) / total);
  const activeIds = new Set(traces.map((item) => item.id));
  const byCategory = { file: 0, peripheral: 0, system: 0 };
  for (const node of nodes) {
    if (activeIds.has(node.id)) byCategory[node.category] += 1;
  }
  return { total, success, failed: total - success,
    successRate: total === 0 ? 1 : success / total, avgLatency, active: activeIds.size, byCategory };
}

export function gradeOf(rate) {
  const value = Math.min(1, Math.max(0, Number(rate) || 0));
  if (value >= 0.98) return 'S';
  if (value >= 0.9) return 'A';
  if (value >= 0.75) return 'B';
  if (value >= 0.5) return 'C';
  return 'D';
}

两个细节。第一,total === 0 时成功率记 1,所以应用刚起来、一次都没调用时圆环是满的、等级是 S------这是有意为之,空状态不该显示成"健康度 0"吓人。第二,环形仪表用 strokeDashoffset 驱动,周长是 2π × 78,进度直接映射成偏移量,切等级时只改两个色值,不重绘 DOM。

byCategory 那一列则回答了另一个问题:这套能力到底偏科不偏科。截图里先后出现了"文件 1 / 外设 0 / 系统 3"和"文件 2 / 外设 2 / 系统 3"两种分布,外设轨从 0 涨到 2 的那一轮,恰好是相册与相机被点亮------轨道活跃度条本身就是一条时间线。

图:DevEco 顶部工具栏与项目结构面板。业务、引擎与界面分文件组织,改动范围清晰可控。

八、上屏流水线:从签名到 hdc install 的五个坑

图:关于本机页面可见 MateBook 14、HarmonyOS 7.0.0.115 SP11 与 API 26。复现时把设备信息与截图一并记录。

hap/ 是官方交付物,app/ 是业务,中间由四步串起来。工程把这四步做成了 npm 脚本,在鸿蒙 PC 的终端里按顺序跑:

sh 复制代码
npm run hap:sign -- --prefix <材料前缀>   # 写入签名材料,回写包名
npm run hap:sync                          # 业务代码注入 resfile/resources/app
npm run hap:build                         # ohpm install(缺依赖时)+ hvigor 构建
npm run hap:install && npm run hap:start  # 装机 + 拉起

hap:build 内部没有调 hvigorw 包装脚本,而是直接用 node 跑 hvigorw.js:

sh 复制代码
HVIGORW_JS="$HMOS_CLT_HOME/hvigor/bin/hvigorw.js"
cd hap
node "$HVIGORW_JS" assembleHap --mode module \
  -p "product=$PRODUCT" -p "module=$MODULE@$PRODUCT" --no-daemon

HMOS_CLT_HOME 指向 /data/service/hnp/hmos-clt.org/hmos-clt_1.0.0,也就是鸿蒙 PC 上的命令行工具集,里面自带 node、ohpm、hvigor 和 SDK。用 node 直跑而不是调包装脚本,是为了绕开 shell 层对工具链路径的假设------这套工具集装在系统分区,PATH 里未必有 hvigor,但 node 绝对路径/hvigorw.js 一定成立。--no-daemon 也别去掉:构建守护进程在 HAP 工程搬迁后会缓存旧的绝对路径,症状是莫名其妙的 00308018。

下面五个坑按"遇到概率"排序:

现象 原因 处理
窗口顶部出现两层菜单栏 鸿蒙 PC 窗口自带系统菜单区,Electron 默认还要塞一个应用菜单 Menu.setApplicationMenu(null),并写进 check.mjs 硬断言
遥测退回降级状态但明明在真机 process.platform 可能返回 ohos 也可能返回 openharmony 双值同时识别,源码断言两个字符串都在
构建报 00308018 Unknown Error / OhmUrl 解析失败 HAP 工程搬迁后 oh_modules 符号链接、.bitfun 元数据仍指向旧绝对路径 npm run hap:relink 重定向链接 + 清掉 .hvigor 与 build 中间产物
安装成功但应用启动白屏 装的是另一套签名材料签出来的旧包,bundleName 相同、versionCode 更低被系统拒绝替换 先 hdc uninstall 再装;包名一律以 p7b 内 bundle-name 为准
签名口令进了仓库 build-profile.json5 的 signingConfigs 是整段材料 hap:sign 生成、工程基线里剥掉该段,hap:init 检测到源工程带签名材料直接拒绝初始化

第四个坑最隐蔽。hdc install 返回成功,aa start 也拉起来了,但界面上什么都没有------大概率是包里带着上一轮签名材料的旧 HAP,系统按 versionCode 判了新包"更旧",实际运行的还是老版本。工程的 hap-sign.mjs 会从 .p7b 的二进制里抠出 bundle-name 回写 hap.config.json,就是为了消除"配置里的包名和签名里的包名不是一回事"这条隐性不一致。装机脚本还会检查 hdc install 输出里是否真出现 install bundle successfully,而不是只看退出码。

versionCode 也踩过:同机装了多个鸿蒙 PC 工程时,它们共用调试签名的 bundleName,后装的那个 versionCode 必须更大,否则 install -r 直接拒绝。把版本号写成 3400000 这种带段位的六位数,比起从 1 递增,后续插入其他构建更不容易撞车。

九、鸿蒙 PC 真机上的实际读数

空状态是这样的:三条轨道环安静地转,中心内核亮着,左侧星表停在"显示 5 / 16",遥测圆环满格 S、平均响应 0 ms。这个状态很关键------它证明业务层已经把 16 路能力全量装载完成,只是还没点亮任何一颗。

点亮办公链路里的四步(文档选择器、系统剪贴板、通知发布、窗口管理)之后,星图上出现四条连线与四枚星体,遥测跳到"累计调用 4、活跃星体 4、平均响应 36 ms",轨道活跃度条给出"文件 1 / 外设 0 / 系统 3"的分布,下方调用链 Trace 逐条列出 窗口管理 #004、通知发布 #003 的响应耗时------就是文章开头那张图的状态。

继续点相册选择器与音频输出,外设轨从 0 变成 2,活跃星体到 7,平均响应抬到 53 ms。这 17 ms 的涨幅几乎全部来自相机采集那一档 138 ms 的基准耗时被拉进均值,和 summarize 里那条算术完全对得上。

开发时的真实工作区是这样的:左侧 DevEco Studio 打开 hap/ 工程,electron 模块下能看到 web_engine、AppScope、oh_modules 的完整结构,右侧是已经装好的星枢窗口在跑。这套跨平台框架的工作流有个好处------ArkTS 那侧几乎不用动,改完 app/ 里的 JS,hap:sync + hap:build 走一遍就能看到新界面,DevEco 里那一大堆 .ets 文件基本只在适配系统行为时才碰。

右上角那行运行时读数还暴露了一个真实问题:截图里显示 Electron v40.0.1-release / Chromium 144.0.7559.76 / Node 24.11.1 · undefined。最后那个 undefined 是系统版本字段------getSystemVersion 在当前运行时版本存在但返回空,而代码里只做了"函数是否存在"的判断:

js 复制代码
const systemVersion = typeof runtimeProcess.getSystemVersion === 'function'
  ? runtimeProcess.getSystemVersion()
  : 'unknown';

正确写法得再兜一层空值:

js 复制代码
const version = typeof runtimeProcess.getSystemVersion === 'function'
  ? runtimeProcess.getSystemVersion()
  : '';
const systemVersion = typeof version === 'string' && version.length > 0 ? version : 'unknown';

这类"字段在、值是空"的情况在跨平台框架里特别多,凡是跨进程读到的元信息,都该按"可能缺失"来写,而不是按"可能不存在方法"来写。同一段代码里 runtime.electron / chromium / node 全都做了 || 'unknown',唯独系统版本漏了,就成了截图里那截尾巴。

十、Electron 在鸿蒙 PC 上的边界与取舍

用下来,这条路线的优势和代价都很清楚。

优势有三条。第一,前端资产零损耗------这个应用 90% 的代码是 HTML/CSS/SVG 加一个纯函数引擎,改一行 CSS 就能改观感,换成纯 ArkTS 重写,星图这层至少多花三倍时间。第二,Node 生态可用------主进程能直接 require('node:path')、node:url,构建脚本、测试脚本都能用 node --test,18 个用例(15 组引擎 + 3 组主进程工具)在 Windows 上跑完再上真机,不需要设备在环。第三,Chromium 版本统一------144.0.7559.76 意味着不用为鸿蒙 PC 单独排查浏览器兼容性,和团队的 Web 端产物行为一致。

代价也得说清。第一是体积:libelectron.so 把 Node 和 Chromium 一起带进 HAP,安装包不再是几 MB 的量级,对"轻量工具"这类定位要慎重。第二是启动:Chromium 初始化 + V8 快照 + 首帧合成,冷启动比同等功能的 ArkTS 应用慢一截,所以窗口里那个 show: false + ready-to-show 不是可选优化而是必需。第三是系统能力仍然要靠 ArkTS 桥------Electron 拿不到 @ohos.* 的完整能力面,需要外设、相机、通知这类能力时,还是得在 web_engine 里加 JS 绑定,或者走"IPC → 主进程 → ArkTS 侧"的转接。星枢的做法是把能力目录做成数据:ArkTS 侧提供哪些绑定,星表里就有哪些星体,两侧对不上的项按 restricted 显式标出,而不是让它点了没反应。

所以判断标准可以简化成一句话:界面复杂度高、团队前端积累厚、不需要深度绑死系统私有能力的鸿蒙 PC 应用,Electron 这条跨平台框架路线是效率最高的;反过来,如果应用的核心价值就在系统能力本身(外设管理、系统设置、性能工具),ArkTS 原生更合适。

十一、结语

星枢 AstroHub 这个工程最后跑起来的样子,其实就是一句话的落地:把"这个应用能调用哪些系统能力"从文档里的表格,变成一个能点、能看、能追溯的拓扑。Electron 在这个过程里承担的是"不打断开发者已有习惯"的角色------主进程、预加载、渲染进程三件套照旧,IPC 安全基线照旧,纯函数引擎照旧可以在 Node 里跑测试;变化的只有壳:从 Windows 的 exe 换成了鸿蒙 PC 的 HAP,从系统的窗口管理器换成了 ArkUI 的 XComponent 表面。

真正需要重新学习的东西并不多,但每一条都很具体:platform 的两个返回值、系统菜单区的双份菜单、resfile 里的资源路径、符号链接残留导致的 00308018、以及签名材料对包名的锁定。把这些坑写进 check.mjs 和 doctor.mjs,让它们在构建时喊出来,比写进文档有用得多------文档会被跳过,构建不会。

后续我打算在这套骨架上继续做两件事:一是把调用链 Trace 落成 JSONL,用 hdc 拉回本机做时序分析;二是给星表加一层"能力可达性"探测,启动时先和 ArkTS 侧对一遍绑定清单,把不可达的星体直接标灰。这两件事都不需要改动 Electron 运行时,改的仍然是 app/ 里的 JavaScript------这大概就是跨平台框架最实在的价值。

相关推荐
向哆哆24 分钟前
在鸿蒙PC上用ArkUI开发跨平台缓存可视化应用:CacheLoom实战
缓存·华为·harmonyos
向哆哆1 小时前
在鸿蒙PC上用Electron跨平台框架开发桌面应用:动量台 Momentum 的窗口动力学引擎与 HAP 交付实践
华为·electron·harmonyos
时光慢煮2 小时前
在鸿蒙 PC 上用 Electron 跨平台框架写鸿蒙 PC 应用:信交所 SignalBourse 的能力行情撮合与 HAP 上屏实战
华为·electron·harmonyos
程序猿追2 小时前
返库看板最小化后还会刷新吗?HarmonyOS 7 窗口状态实测
android·开发语言·kotlin·harmonyos
向哆哆4 小时前
Electron 跨平台框架落地鸿蒙 PC:用 OrbitKey 构建“授权闸门 + 本地审计链“桌面应用
缓存·华为·harmonyos
传奇开心果编程4 小时前
【华为仓颉独特优势】第11课:回到主场——HarmonyOS 上的仓颉:ArkTS 互操作与“宿主问题”的终极答卷
开发语言·华为·harmonyos·编程语言理论·仓颉·cangjie·通用编程语言
NJPJI_Yang4 小时前
鸿蒙操作系统使用 RichEditor 实现图文混排富文本编辑实战(本文已在AtomGit仓库开源)
华为·开源·harmonyos
渣哥搞AI4 小时前
鸿蒙 PC 上用 Electron 开发桌面级应用:曜轮 AuraWheel 的 MRU 环轨、IPC 分层与 HAP 交付流水线
华为·electron·harmonyos