v0.1首个版本化设计基线查看版本范围
Developer

构建自绘文本编辑器

自绘编辑器不能只监听键盘。按键控制用 input,真正文本合成用 ime,复制粘贴用 clipboard,持久化由 store 完成。

1. 聚焦并打开 IME

await host.input.focus('editor');
const ime = await host.ime.openSession('editor', {
  text: document.text,
  selection: document.selection,
  inputMode: 'text',
  multiline: true,
});

2. 应用编辑操作

host.events.on('ime.textUpdate', async ({ update, baseRevision }) => {
  if (baseRevision !== document.revision) return;
  document.replace(update.range, update.text);
  await host.ime.updateState(ime, document.snapshot());
  scheduleSave();
});

文档模型在 guest 中是权威状态。IME 事件是编辑请求,应用后再回传新 revision。

3. 同步几何

await host.ime.updateGeometry(ime, {
  revision: document.revision,
  editorBounds: layout.editor,
  caretBounds: layout.caret,
});

在选择、滚动、字体或 canvas 尺寸变化后更新,不要无变化地逐帧发送。

4. 复制与粘贴

async function copy() {
  await host.clipboard.writeText(document.selectedText());
}

async function paste() {
  const text = await host.clipboard.readText();
  if (text !== null) document.replaceSelection(text);
}

两个函数都要从可信用户操作直接进入。一次授权不得转成后台剪贴板读取。

5. 持久化

const previous = await host.store.get('documents/current');
await host.store.put(
  'documents/current',
  encodeDocument(document),
  previous?.version,
);

处理 conflict,不要静默覆盖另一窗口的更新。

6. 关闭

await host.ime.closeSession(ime);

失焦、文档关闭和视图销毁都要清理会话。

相关参考

imeinput.keyclipboardstore.put()

Host API 版本与分层概览Host API v0.1版本非正式提议提议canvas API呈现canvas.getInfo()方法canvas.draw()方法canvas.present()方法canvas.measureText()方法canvas.frame event事件canvas.resize event事件asset API呈现asset.read()方法asset.loadFont()方法playback API呈现playback.open()方法playback.write()方法playback.stop()方法playback.ready event事件playback.ended event事件input API输入input.focus()方法input.pointer event事件input.key event事件input.wheel event事件ime API输入ime.openSession()方法ime.updateState()方法ime.updateGeometry()方法ime.closeSession()方法ime.textUpdate event事件ime.composition event事件ime.formatUpdate event事件ime.characterBoundsRequest event事件capture API输入capture.requestCamera()方法capture.requestMic()方法capture.frame()方法capture.readAudio()方法capture.stop()方法capture.ended event事件store API数据store.get()方法store.put()方法store.delete()方法store.list()方法store.deletePrefix()方法clipboard API数据clipboard.readText()方法clipboard.writeText()方法clipboard.readImage()方法clipboard.writeImage()方法net API网络net.fetch()方法identity API身份identity.status()方法identity.login()方法identity.logout()方法env API平台集成env.snapshot()方法env.change event事件print API平台集成print.open()方法开始调用 Host API指南构建交互式绘图应用指南构建自绘文本编辑器指南管理媒体采集与播放指南组织本地数据与同步指南