Electron 上游没有 HarmonyOS PC 发行版,"旋转窗口"这件事却跟平台没多大关系。这篇记录 tablet-adaptive-electron 的做法:把旋转几何写成纯函数,主进程和 renderer 共用一份断点,鸿蒙侧再用一份 ArkTS HAR 对齐同一套契约。

仓库地址:https://atomgit.com/lqjmac/tablet-adaptive-electron
版本地址:https://atomgit.com/CPF-Electron
三方库框架:https://atomgit.com/oh-tpc

0. 环境与验证范围

三方库适配信息:

三方库Electron 版本鸿蒙化版本仓库地址社区社区地址
tablet-adaptive-electronv40.1.06.0.0(20)https://atomgit.com/oh-tpcCPF-Electron 鸿蒙社区https://atomgit.com/CPF-Electron

验证环境:

项版本/型号
Electron40.1.0(peer >= 28;本机未下载 Electron 运行时,demo 页由 Chrome + 只读 bridge stub 截图)
Node / 构建24.12.0;TypeScript 5.9 → CJS + d.ts;esbuild 产出 ESM/IIFE renderer
DevEco Studio6.x(内置 hvigor 6.26.4、ohpm);SDK API 26
ohos 工程HAR tablet-adaptive-ohos + 演示 HAP;compatibleSdkVersion 5.0.0(12) · targetSdkVersion 5.0.5(17)
测试Vitest 7 个文件 70 项全过(断点向量、旋转几何、IPC 白名单、preload、jsdom 行为)
demo 页读数Chrome + 只读 bridge stub:1280×768(横屏 large/12 栏/rail+split)→ rotate() → 768×853(竖屏 medium/8 栏/bottom+single),全程 page errors: [](非 Electron 主进程实跑)

这一版没有启动 Electron 主进程 demo:本机未下载 Electron 运行时,截图由 macOS 的 Chrome 打开 demo/index.html、注入只读 window.tabletAdaptive stub 后生成;鸿蒙侧只做到编译、打包。文中的构建输出和测试数字来自验证记录,页面读数来自这份 stub,不是 Electron 主进程的实跑结果。

1. 先看窗口转起来

demo 页按 1280×800 的窗口、1280×768 的内容区打开。顶栏三枚按钮:旋转窗口、竖屏、横屏,右侧一条状态栏实时汇报尺寸和布局。

横屏初始态

状态栏读数是 1280×768 · 横屏 · large · 12 栏。左侧 88px 侧轨,主体双栏:左列笔记列表固定在 300–400px,右列是选中笔记的正文。demo 页的只读 bridge stub 报告的 navigation / paneMode 是 rail / split,bridge: ready,page errors: []。

点"旋转窗口":

旋转后的竖屏态

状态栏变成 768×853。这里不是笔误:按直觉,1280×768 旋转后应该是 768×1280,但完整窗口(含标题栏)已经超出 screen.workArea,纯函数按工作区夹取后,高度压到了 853。布局同时切到 medium · 8 栏,侧轨换成底部导航,主体单栏、卡片两列。

再点"横屏":

竖屏单栏

重排逻辑会保留列表滚动位置、选中笔记和键盘焦点,page errors 仍是空数组。demo/main.js 里的 webPreferences 是 sandbox: true、contextIsolation: true,preload 只暴露四个方法;本轮没有启动主进程,这几项由单元测试覆盖。

2. 交换宽高之后,窗口为什么会跑

最初我以为旋转就是交换宽高,代码也确实只有三行:

const bounds = win.getBounds();
win.setBounds({
  x: bounds.x,
  y: bounds.y,
  width: bounds.height,
  height: bounds.width,
});

跑起来就发现不对。窗口的左上角没动,中心跑到右下方去了;多转几次,标题栏就滑出屏幕,鼠标够不着。原因不复杂:setBounds 以左上角为锚点,宽高一换,中心自然漂移。旋转应该以原中心为锚点;如果按左上角交换宽高,窗口会一路往右下跑。

第二次尝试用了 setSize,以为它只改尺寸不改位置。setSize 确实不接收 x/y,但它同样以窗口左上角为锚点,中心还是会漂。真正要拿的是 getContentBounds() 和 getBounds() 两组值:前者是页面能用的内容区,后者是包含标题栏和边框的完整窗口。macOS 上两者的原点还可能不一样,windowBounds.x - contentBounds.x 甚至是负数。把这些差值单独算出来之后,"原地转"才有可操作的坐标。

改成先算中心、再算新位置,又撞上第二个问题:屏幕工作区。一个 1280×800 的窗口在 1280 宽的屏幕上转成 800×1280,高度根本放不下。这时不能只顾中心;窗口得先缩到工作区里,再谈位置。Electron 的 setBounds 还作用于完整窗口,而布局算的是内容区,中间差着标题栏和边框的厚度。

这三件事最后被收进一个纯函数 planContentResize:

// src/geometry.ts
export function planContentResize(input: PlanContentResizeInput): WindowGeometryPlan {
  const frame = readFrameInsets(input.windowBounds, input.contentBounds);
  const workArea = safeWorkArea(input.workArea);

  const width = Math.min(
    safeDimension(input.targetWidth),
    Math.max(0, workArea.width - frame.extraWidth),
  );
  const height = Math.min(
    safeDimension(input.targetHeight),
    Math.max(0, workArea.height - frame.extraHeight),
  );

  const centerX = input.contentBounds.x + input.contentBounds.width / 2;
  const centerY = input.contentBounds.y + input.contentBounds.height / 2;

  const windowWidth = width + frame.extraWidth;
  const windowHeight = height + frame.extraHeight;

  const desiredX = Math.round(centerX - width / 2 - frame.offsetX);
  const desiredY = Math.round(centerY - height / 2 - frame.offsetY);

  const x = Math.round(clamp(
    desiredX,
    workArea.x,
    workArea.x + workArea.width - windowWidth,
  ));
  const y = Math.round(clamp(
    desiredY,
    workArea.y,
    workArea.y + workArea.height - windowHeight,
  ));

  const windowBounds: Rectangle = { x, y, width: windowWidth, height: windowHeight };
  const contentBounds: Rectangle = {
    x: x + frame.offsetX,
    y: y + frame.offsetY,
    width,
    height,
  };
  return { windowBounds, contentBounds };
}

顺序很重要:先按工作区收缩,再以原中心求位置,最后把完整窗口夹进工作区。readFrameInsets 负责把"完整窗口 - 内容区"的差值算出来,safeWorkArea 则把取不到屏幕时的非法值兜住,避免夹取运算算出 NaN。

旋转本身只是这个函数的一次调用,把目标宽高对调:

// src/geometry.ts
export function rotateWindowGeometry(input: RotationInput): WindowGeometryPlan {
  return planContentResize({
    contentBounds: input.contentBounds,
    windowBounds: input.windowBounds,
    workArea: input.workArea,
    targetWidth: input.contentBounds.height,
    targetHeight: input.contentBounds.width,
  });
}

demo 页显示的 768×853 就是这段纯函数算出来的。demo 页注入的工作区放不下 1280 的内容区,减去标题栏后只剩 853;Math.min 把高度压下来,后面的夹取再把窗口挪回工作区内。它看起来像"没转满",实际是工作区约束优先于中心保持。

正方形窗口是另一个边界。交换宽高等于没转,setOrientation('landscape') 会"成功"但方向没变。现在的约定是:正方形归竖屏,要横屏就把高度减 1px:

// src/geometry.ts
const square = input.contentBounds.width === input.contentBounds.height;
if (square && target === 'landscape') {
  if (input.contentBounds.width <= 0) return null;
  return planContentResize({
    contentBounds: input.contentBounds,
    windowBounds: input.windowBounds,
    workArea: input.workArea,
    targetWidth: input.contentBounds.width,
    targetHeight: Math.max(0, input.contentBounds.width - 1),
  });
}

1px 当然不是视觉上的横屏,但它让"方向"这个派生值有了确定的定义,也避免了调用方拿到一个自相矛盾的状态。边界条件写进契约,比在 UI 层逐个处理省事。

3. 断点只留一份

布局规则本身不复杂,难的是只在库里有这一份。这个库的断点有三条,尺寸分四档:

宽度sizeClasscolumnscardColumnsmargin / gutter
<600compact4116 / 8
600–839medium82(横屏 3)24 / 16
840–1199expanded12332 / 24
>=1200large12440 / 32

导航和分栏是两条派生规则:w >= 840,或 w >= 600 且横屏,走侧轨;w >= 840,或 w >= 720 且横屏,走双栏。列表宽度用 clamp(round(w × 0.34), 300, 400):列表要的是可读宽度,纯比例在宽屏上会把列表拉得过宽。

600 / 840 / 1200 是按这个工作台的内容反推出来的。600 以下列表只放得下一列卡片,导航只能沉到底部;840 以上侧轨(88px)加列表(300–400px)之后还剩得下正文,才值得分栏;1200 以上卡片能排到四列,再宽也只是留白。中间 600–839 这一档最尴尬:宽度够放侧轨,但正文会被挤成一条,所以只有横屏才切 rail。写成规则就是两个"或",但每个"或"背后都是一次"放不下"的布局验证。

resolveTabletLayout 是唯一实现:

// src/layout.ts
export function resolveTabletLayout(
  width: number,
  height: number,
  config: TabletLayoutConfig = {},
): TabletLayout {
  const safeWidth = normalizeDimension(width);
  const safeHeight = normalizeDimension(height);
  const orientation: Orientation = safeWidth > safeHeight ? 'landscape' : 'portrait';
  const sizeClass = resolveSizeClass(safeWidth);
  const density: Density = safeHeight < 500 ? 'compact' : 'comfortable';
  const resolvedConfig = config ?? {};

  return {
    width: safeWidth,
    height: safeHeight,
    orientation,
    sizeClass,
    columns: resolveColumns(sizeClass),
    cardColumns: resolveCardColumns(safeWidth, orientation),
    margin: resolveMargin(sizeClass),
    gutter: resolveGutter(sizeClass),
    navigation: resolveNavigation(safeWidth, orientation),
    paneMode: resolvePaneMode(safeWidth, orientation),
    listWidth: Math.min(
      TABLET_LAYOUT_DEFAULTS.listWidthMax,
      Math.max(
        TABLET_LAYOUT_DEFAULTS.listWidthMin,
        Math.round(safeWidth * 0.34),
      ),
    ),
    railWidth: readConfigNumber(resolvedConfig.railWidth, TABLET_LAYOUT_DEFAULTS.railWidth),
    bottomBarHeight: readConfigNumber(
      resolvedConfig.bottomBarHeight,
      TABLET_LAYOUT_DEFAULTS.bottomBarHeight,
    ),
    headerHeight: readHeaderHeight(resolvedConfig.headerHeight, density),
    density,
    isTablet: Math.min(safeWidth, safeHeight) >= TABLET_LAYOUT_DEFAULTS.tabletMinDimension,
  };
}

两个容易想岔的地方。第一,sizeClass 只看宽度,isTablet 只看短边是否到 600,两者互不封顶。844×390 的手机横屏会拿到 expanded / 12 栏 / rail / split,同时 isTablet == false、density == compact。宽度够宽就用宽布局,跟设备形态无关。第二,非法宽高先归零,0×0 返回 compact 默认值,不抛异常。窗口初始化、屏幕拔插、容器还没挂载,都会短暂量到 0,这里抛异常只会把问题推给调用方。

主进程和 renderer 都 import 这个文件。主进程拿它做窗口决策和日志,renderer 用它渲染工作台,但两边不互相转发尺寸,各自量自己的容器。这样既没有"两份断点",也没有"两份状态"。

观察容器用的是 ResizeObserver,window.resize 只作兜底:

// src/observer.ts:测量与两条订阅路径
const measure = (): TabletLayout => {
  const size = readElementSize(target);
  return resolveTabletLayout(size.width, size.height, layoutConfig);
};

if (typeof ResizeObserver === 'function') {
  usingResizeObserver = true;
  resizeObserver = new ResizeObserver(() => {
    const next = measure();
    if (next.width !== current.width || next.height !== current.height) {
      current = next;
      callback(current);
    }
  });
  resizeObserver.observe(target);
}

const onWindowResize = (): void => {
  const next = measure();
  if (next.width !== current.width || next.height !== current.height) {
    current = next;
    callback(current);
  }
};
window.addEventListener('resize', onWindowResize);

getBoundingClientRect() 在嵌入 WebView 和 jsdom 里可能返回 0,所以 readElementSize 还会退到 clientWidth/clientHeight。这么做有原因:工作台放在一个还没完成布局的容器里时,第一帧确实会量到 0。

4. 代码放在哪

Electron 侧按进程分文件,鸿蒙侧是独立的 DevEco 工程:

tablet-adaptive-electron/
├─ src/
│  ├─ layout.ts         # 唯一布局契约(主进程与 renderer 共用)
│  ├─ controller.ts     # TabletWindowController / attachTabletWindow
│  ├─ geometry.ts       # 旋转与工作区几何(纯函数)
│  ├─ ipc.ts            # registerTabletIpc(三个命令通道)
│  ├─ preload.ts        # exposeTabletBridge(自带安全校验)
│  ├─ observer.ts       # observeTabletLayout(RO + window.resize 回退)
│  ├─ workspace.ts      # <tablet-adaptive-workspace>
│  ├─ styles.ts / renderer.ts / index.ts / types.ts
├─ __tests__/           # 70 个单元测试
├─ demo/                # 真实 Electron demo(main / preload / index.html)
├─ ohos/
│  ├─ library/          # tablet-adaptive-ohos 三方库(HAR)
│  │   └─ src/main/ets/
│  │     ├─ components/TabletWorkspace.ets   # list-detail 工作台
│  │     ├─ layout.ets                       # resolveTabletLayout 与断点
│  │     └─ theme.ets                        # LIGHT/DARK_THEME
│  └─ example/          # 演示 HAP(file:../library 依赖)
├─ docs/                # 布局契约、验证记录、demo 截图
└─ package.json / tsconfig*.json

工程结构

geometry.ts、layout.ts 这类纯函数文件不 import Electron,测试可以直接在 Node 里跑。controller.ts 是薄壳:挂事件、调几何、推状态。真正跟 Electron 绑定的只有 controller、ipc、preload 和 observer 这几个文件。

5. 三层各管什么

5.1 resize 和 will-resize 不是一回事

controller 同时监听 resize 和 will-resize,但两者待遇不同。resize 是已经生效的尺寸,算出来的布局会推给 renderer 和 onState;will-resize 只是拖动过程中的预览,算出来的状态只给 onPreview,不进入 getState()。

// src/controller.ts:resize 与 will-resize
private readonly handleResize = (): void => {
  this.refresh(true);
};

private readonly handleWillResize = (
  _event: unknown,
  newBounds: Partial<Rectangle>,
): void => {
  if (this.disposed) return;
  const bounds = toRectangle(newBounds);
  const content = this.readContentBounds();
  const windowBounds = this.readWindowBounds();
  const frame: FrameInsets = readFrameInsets(windowBounds, content);
  const preview = this.makeState(
    Math.max(0, bounds.width - frame.extraWidth),
    Math.max(0, bounds.height - frame.extraHeight),
  );
  this.previewState = preview;
  this.options.onPreview?.(preview);
};

拖动窗口边缘时 will-resize 每帧都触发,把预览值当事实推给 renderer,页面会收到一串"从未真正存在过"的布局。预览归预览,状态归状态,两个 getter 分开:getState() 和 getPreviewState()。

这两个事件的触发顺序也要记一下。拖动过程中 will-resize 先来,resize 后到;如果页面在 will-resize 里就把预览值写进全局 store,等 resize 落地时再写一次,中间会有一帧布局和窗口尺寸对不上。demo 里把预览只喂给状态条的淡色数字,正式布局仍然等 resize,所以拖动时看起来有一点延迟,但不会闪。

旋转接口最后落在三个动作上:

// src/controller.ts:旋转与方向切换
rotate(): TabletWindowState {
  this.assertActive();
  const geometry = this.readGeometry();
  const plan = rotateWindowGeometry({
    contentBounds: geometry.content,
    windowBounds: geometry.window,
    workArea: this.resolveWorkArea(geometry.window),
  });
  return this.applyPlan(plan);
}

setOrientation(orientation: Orientation): TabletWindowState {
  this.assertActive();
  if (!isOrientation(orientation)) {
    throw new TypeError(`[tablet-adaptive] unsupported orientation: ${String(orientation)}`);
  }
  const geometry = this.readGeometry();
  const plan = orientationWindowGeometry({
    contentBounds: geometry.content,
    windowBounds: geometry.window,
    workArea: this.resolveWorkArea(geometry.window),
  }, orientation);
  if (!plan) {
    return this.refresh(false);
  }
  return this.applyPlan(plan);
}

private applyPlan(plan: WindowGeometryPlan): TabletWindowState {
  this.window.setBounds(plan.windowBounds);
  return this.updateState(plan.contentBounds.width, plan.contentBounds.height, true);
}

setBounds 之后重新 updateState 一次,没有直接拿 plan 里的宽高当状态。原因很实际:某些平台会对窗口尺寸做取整或最小尺寸限制,setBounds 传入的值不一定就是落地值。以最终内容尺寸为准,状态才不会跟窗口对不上。

5.2 IPC 只有三个命令通道

registerTabletIpc 只注册 rotate、set-orientation、get-state 三个通道,没有通用的 invoke(channel, ...)。每个请求通过 event.sender 找到对应窗口的 controller:

// src/ipc.ts:sender 绑定与方向校验
function resolveController(event: IpcMainInvokeEvent): TabletWindowController {
  const controller = lookupTabletControllerBySender(event.sender);
  if (!controller) {
    throw new Error(
      '[tablet-adaptive] IPC request came from a window that was not attached with attachTabletWindow()',
    );
  }
  return controller;
}

host.handle(
  TABLET_IPC_CHANNELS.setOrientation,
  (event: IpcMainInvokeEvent, orientation: unknown): TabletWindowState => {
    if (!isOrientation(orientation)) {
      throw new TypeError(
        `[tablet-adaptive] orientation must be "portrait" or "landscape", got ${String(orientation)}`,
      );
    }
    return resolveController(event).setOrientation(orientation);
  },
);

方向字符串在主进程和 preload 各校验一次。多窗口场景下,A 窗口的页面不能拿 B 窗口的 controller,因为查的是 event.sender,所以多窗口各管各的。注册是幂等的:同一个 ipcMain 重复调用会返回已有注册,避免 handle 抛 “second handler” 错误。

这里没有做通用的 invoke(channel, ...),也没有把 controller 暴露给渲染进程。三个通道各有一个明确的入参和返回值,新增能力必须改类型和测试。看起来笨,但排查问题时不用猜页面到底能调什么;安全审计也只需要看一个文件。

5.3 preload 在 contextIsolation 关掉时直接抛

安全默认值是 contextIsolation: true、nodeIntegration: false、sandbox: true。如果宿主忘了开隔离,exposeTabletBridge() 不会退化成直接挂 Node API,而是抛 TabletBridgeSecurityError:

// src/preload.ts:隔离检查与四个方法
function contextIsolationIsDisabled(): boolean {
  const processLike = typeof process === 'undefined'
    ? undefined
    : (process as unknown as { contextIsolated?: boolean });
  return processLike?.contextIsolated === false;
}

export function exposeTabletBridge(
  options: ExposeTabletBridgeOptions = {},
): TabletAdaptiveBridge {
  if (contextIsolationIsDisabled()) {
    throw new TabletBridgeSecurityError(
      '[tablet-adaptive] contextIsolation is disabled. Enable webPreferences.contextIsolation, '
      + 'set nodeIntegration:false, and reload the window before exposing the tablet bridge.',
    );
  }
  if (!contextBridge || typeof contextBridge.exposeInMainWorld !== 'function') {
    throw new TabletBridgeSecurityError(
      '[tablet-adaptive] contextBridge is unavailable. Run exposeTabletBridge() from a preload '
      + 'script with contextIsolation enabled.',
    );
  }

  const bridge: TabletAdaptiveBridge = Object.freeze({
    rotate(): Promise<TabletWindowState> {
      return ipcRenderer.invoke(CHANNELS.rotate);
    },
    setOrientation(orientation: Orientation): Promise<TabletWindowState> {
      if (!isOrientation(orientation)) {
        return Promise.reject(new TypeError(
          `[tablet-adaptive] orientation must be "portrait" or "landscape", got ${String(orientation)}`,
        ));
      }
      return ipcRenderer.invoke(CHANNELS.setOrientation, orientation);
    },
    getState(): Promise<TabletWindowState> {
      return ipcRenderer.invoke(CHANNELS.getState);
    },
    onState(listener: (state: TabletWindowState) => void): () => void {
      if (typeof listener !== 'function') {
        throw new TypeError('[tablet-adaptive] onState expects a function');
      }
      const wrapped = (_event: unknown, state: unknown): void => {
        if (isTabletWindowState(state)) listener(state);
      };
      ipcRenderer.on(CHANNELS.state, wrapped);
      return () => {
        ipcRenderer.removeListener(CHANNELS.state, wrapped);
      };
    },
  });

  contextBridge.exposeInMainWorld(options.globalName ?? 'tabletAdaptive', bridge);
  return bridge;
}

ipcRenderer、process、require 都没有暴露。onState 返回取消订阅函数,页面卸载时能把自己摘干净。push 过来的 state 还要过一遍 isTabletWindowState,主进程被攻破也不能把任意对象塞进页面。dist/preload.js 除了 require('electron') 没有本地依赖,这是为了在 sandbox: true 下能和宿主 preload 打成单文件。

5.4 工作台:重排不等于重建

Web Component 的状态放在 DOM 之外:当前导航、选中条目、单双栏面板、两个滚动位置。render() 每帧重建 shadowRoot.innerHTML,但在重建前抓滚动和焦点,重建后放回去:

// src/workspace.ts:重排前后的滚动与焦点
private render(): void {
  const shadow = this.shadowRoot;
  if (!shadow) return;

  const activeList = shadow.querySelector<HTMLElement>('[data-scroll="list"]');
  if (activeList) this._listScrollTop = activeList.scrollTop;
  const activeDetail = shadow.querySelector<HTMLElement>('[data-scroll="detail"]');
  if (activeDetail) this._detailScrollTop = activeDetail.scrollTop;

  if (this._renderedDestinationId !== this._activeDestinationId) {
    this._listScrollTop = 0;
    this._renderedDestinationId = this._activeDestinationId;
  }
  if (this._renderedItemId !== this._selectedItemId) {
    this._detailScrollTop = 0;
    this._renderedItemId = this._selectedItemId;
  }

  const focus = this.captureFocus();
  const layout = this._layout;
  const isSplit = layout.paneMode === 'split';
  const selected = this.filteredItems.some((item) => item.id === this._selectedItemId);
  const activeDestination = this._destinations.find(
    (entry) => entry.id === this._activeDestinationId,
  );
  const showDetail = isSplit || (this._panel === 'detail' && selected);
  const brand = this._brand || activeDestination?.label || FALLBACK_BRAND;
  const eyebrow = this._eyebrow || FALLBACK_EYEBROW;
  const sizeHint = formatSizeHint(layout);

  const content = showDetail && !isSplit
    ? this.renderDetail()
    : `${this.renderList()}${isSplit ? this.renderDetail() : ''}`;

  shadow.innerHTML = `<style>${WORKSPACE_CSS}</style>
    <div class="shell" data-navigation="${layout.navigation}" data-pane-mode="${layout.paneMode}"
      data-orientation="${layout.orientation}" data-size-class="${layout.sizeClass}"
      style="--pad:${layout.margin}px;--gap:${layout.gutter}px;--card-cols:${layout.paneMode === 'split' ? 1 : layout.cardColumns};--list-width:${layout.listWidth}px;--rail-width:${layout.railWidth}px;--bottom-bar-height:${layout.bottomBarHeight}px;--header-height:${layout.headerHeight}px">
      ${layout.navigation === 'rail' ? this.renderRail(activeDestination, layout) : ''}
      <div class="main">
        <header class="header">
          <div class="heading">
            <div class="eyebrow">${escapeHtml(eyebrow)}</div>
            <h1>${escapeHtml(brand)}</h1>
          </div>
          <div class="size-hint" data-size-hint aria-label="当前容器尺寸">${escapeHtml(sizeHint)}</div>
        </header>
        <div class="body">${content}</div>
        ${layout.navigation === 'bottom'
          ? this.renderNavigation('bottom', activeDestination?.id ?? null)
          : ''}
      </div>
    </div>`;

  const listAfter = shadow.querySelector<HTMLElement>('[data-scroll="list"]');
  if (listAfter) listAfter.scrollTop = this._listScrollTop;
  const detailAfter = shadow.querySelector<HTMLElement>('[data-scroll="detail"]');
  if (detailAfter) detailAfter.scrollTop = this._detailScrollTop;
  this.restoreFocus(focus);
}

split 模式列表栏固定 300–400px,始终单列,这是硬上限;cardColumns 只用于 single 模式的全宽列表。列表超过 400px,扫读路径会变长,剩下的宽度留给正文更划算。从 split 缩回 single 时回到列表,再展开时保留仍然有效的选中项;空列表显示"选择一篇笔记";导航是 <nav aria-label="主导航">,卡片是原生 button,键盘焦点在重排后按 data-action + data-id 找回来。

焦点恢复看起来是小事,实际很容易坏。重排后 DOM 节点全是新的,document.activeElement 会掉回 body;如果只按标签名找,会恢复错卡片。这里用 data-action + data-id 做稳定键,找不到就放弃恢复,不强行聚焦到第一个按钮。导航容器带 aria-label="主导航",卡片是原生 button,Tab 顺序由 DOM 决定,重排后不会因为手写 tabindex 而乱掉。有一个已知缺口:单栏详情标题在隐藏后无法聚焦,重排时如果焦点正好停在那里,会掉回 body;demo 没有为这种情况硬造替代节点,因为造一个假焦点位置比丢焦点更难解释。

6. 鸿蒙侧另写了一份 ArkTS

ohos/library 里的 TabletWorkspace.ets 是一份独立的 ArkTS 实现,不包装 Electron:onAreaChange 观察自身区域,resolveTabletLayout 用同一套断点,主题走 LIGHT_THEME / DARK_THEME。宿主这样接:

import { TabletWorkspace, TabletLayout } from 'tablet-adaptive-ohos';

// 宿主组件里已经有 @State layout / lastOpened
TabletWorkspace({
  data: this.data,                       // 宿主的 TabletWorkspaceData
  onLayoutChange: (layout: TabletLayout) => {
    this.layout = layout;
  },
  onItemOpen: (item) => {
    this.lastOpened = item.title;
  },
})
  .width('100%')
  .layoutWeight(1)

ArkTS 版没有 rotate()。窗口操作用的是宿主自己的 window.resize(),示例提供三档预设;组件只保证"区域变化 → 重新排版 → 状态保留"。这跟 Electron 版的分工正好相反:Electron 主进程能直接改窗口,所以库把几何也包了;ArkUI 宿主本来就能改窗口,库就不该承担这个职责。

两边的 TabletLayout 字段是逐个对齐的,但实现没有共享代码:一个是 TypeScript,一个是 ArkTS,只能靠契约测试保证同输入同输出。这个选择不优雅,却是当时唯一能落地的做法:HAR 要能独立发布,就不能依赖 npm 包,也不能假设宿主一定装 Node。契约漂移的风险靠一份手写的双端向量表兜着,每次改断点两边都要跑同一组尺寸。

HAR 是三方库,不参与应用签名;示例 HAP 要签名,但本机已有的 profile 绑定的是别的 bundleName,直接套会失败。这属于工程配置,改代码解决不了,仓库说明里单独写了一节。

7. 窗口位置、桥和签名上的返工

旋转的第一版就是开头那三行 setBounds。窗口左上角不动、中心漂移,多转几次标题栏出界。把"以原内容中心为新中心"写进 planContentResize 之后,位置对了,但内容区夹进工作区、窗口还是有一截挂在屏幕外:setBounds 作用于完整窗口,而 contentBounds 是内容区,两者差着 frame.insets。readFrameInsets 就是为这个加的:先把边框厚度加回去,再夹完整窗口。768×853 也是在同一轮里对上的:工作区高度不够,Math.min 把 1280 压成了 853,不是旋转少转了一截。

正方形窗口是另一个边界。800×800 转横屏,宽高交换后还是 800×800,setOrientation('landscape') 返回成功但 orientation 仍是 portrait。现在的约定是正方形归竖屏,转横屏时高度减 1px。这个处理不好看,但它让方向有了确定的定义。

安全上的那次返工更典型。宿主为了图省事关掉 contextIsolation,桥"静默可用",页面直接拿到了 require。现在的实现是检测到隔离关闭就抛 TabletBridgeSecurityError,宁可不工作,也不降级暴露。鸿蒙签名则是另一类问题:本机 profile 绑的是 dev.cjgg.immersive_material_example,签不了 dev.cjgg.tablet_adaptive_example,要么为这个 bundleName 重新生成 profile,要么改 AppScope/app.json5 里的包名。签名 profile 和包名绑定,换包名就得换 profile。中间还遇到过一次 npm install 拉 Electron 运行时超时,ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ 之后重试就好,属于网络问题,包本身没坏。

跨屏工作区是最后一个花时间的点。这一版没有在真实 Electron 窗口上跨屏验证;单屏时直接拿窗口中心命中的 display 没问题;如果窗口一半在 A 屏一半在 B 屏,应该看窗口面积重叠最大的那块屏,鼠标在哪并不重要。现在的 resolveWorkArea 用的是 screen.getDisplayMatching(windowBounds),Electron 内部就是按重叠面积算的。这一点文档写得很含糊,我是在源码里翻到的。

8. 现在能跑到哪一步

npm 侧:

git clone https://atomgit.com/lqjmac/tablet-adaptive-electron.git
cd tablet-adaptive-electron
npm install
npm run verify

verify 依次跑 tsc --noEmit、vitest run、tsc -p tsconfig.build.json 和两次 esbuild。最近一次输出:

Test Files  7 passed (7)
     Tests  70 passed (70)

dist/renderer.mjs        41.7 KB
dist/renderer.global.js  44.1 KB

70 项里,旋转几何占 11 项:交换、中心保持、工作区夹取、原生边框、正方形、超大窗口收缩、非零原点工作区。IPC 6 项、preload 8 项、工作台 jsdom 行为 13 项,其余是断点向量和 controller。

这些测试里有一半以上在测边界值。比如 planContentResize 的用例会传一个 1000×700 的工作区去转 1200×800 的窗口,看它是不是先缩到 700 高、再贴到工作区原点;orientationWindowGeometry 会传一个 0×0 的窗口,确认它返回 null,不会算出负宽高。写这些用例的原因很实际:窗口最小化、显示器休眠、页面还没挂载,都会让尺寸短暂变成 0 或负数,线上出的怪状态基本都来自这些瞬间。

demo 页(Chrome + 只读 bridge stub)读到:

bridge: ready
window state: 1280 × 768 · 横屏 · large · 12 栏
workspace size: 1280 × 670 · 横屏 · large · 12 栏
navigation / paneMode: rail / split
rotate() -> 768 × 853 · 竖屏 · medium · 8 栏
navigation / paneMode: bottom / single
page errors: []

鸿蒙侧(末尾 hdc install / aa start 为构建后的可选安装、启动命令,本轮未执行):

cd ohos && ohpm install --all

hvigorw assembleHar --mode module -p module=library@default -p product=default --no-daemon
hvigorw assembleHap --mode module -p module=entry@default -p product=default \
  -p buildMode=debug --no-daemon

hdc install -r example/build/default/outputs/default/entry-default-unsigned.hap
hdc shell aa start -a EntryAbility -b dev.cjgg.tablet_adaptive_example

HAR 8.6 KB,unsigned HAP 237.8 KB,都是 BUILD SUCCESSFUL。没有配置签名,SignHap 按预期跳过。这两个产物能证明代码能过 ArkTS 编译和打包。

仓库里的文档:

  • 三层 API、横竖屏策略、安全模型和设计边界;
  • 断点与行为契约,两个进程共用;
  • 构建、70 项测试与 Chrome + stub 的 demo 截图;
  • demo/:Electron 演示,npm run demo 直接跑。

这个库没有解决"Electron 在 HarmonyOS PC 上有没有官方发行版"的问题;它解决的是窗口几何和布局契约。真要在鸿蒙 PC 上跑,应该直接用 ohos/ 里的 ArkTS 实现;Electron 这层是给 macOS / Windows / Linux 上的同款工作台用的。两边共享断点和行为,运行时各走各的。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐