1.2 自定义窗口、菜单与快捷键
扩展需要三个入口:自己的窗口、主菜单里的一项、以及一个快捷键。菜单是树,路径一次补全中间节点;快捷键是全局资源,跨扩展冲突必须当场拒绝,而不是等用户按下组合键时才发现两个命令同时触发。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 命令与快捷键 | 《架构内核》 的命令系统 | 内核负责命令执行;本节处理扩展占用快捷键的冲突 |
| 编辑器 UI | 《架构内核》 的 docking 布局 | 布局管窗口位置;本节管扩展如何登记自己的窗口与菜单项 |
| 全卷脉络 | 本卷目录 | 本节把扩展能力接到用户可见的入口 |
从零实现:自定义窗口、菜单与快捷键
快捷键先解析成规范形式:修饰键固定顺序、按键统一大写,再作为比较键。注册时若同一组合已绑定到别的命令,返回冲突信息且不覆盖;同一命令重复注册则幂等。菜单用路径 File/Export/PNG 建树,中间节点自动创建,叶子按深度优先遍历。
对标扩展机制
Cocos Creator 在扩展清单中分别声明菜单和快捷键贡献。快捷键可通过消息连接到扩展行为。helio 示例将菜单树生成和快捷键冲突检查分开,冲突规则属于本节注册表。 Cocos 扩展贡献点
可运行产物:6 条用例
下面是 src/shortcut-menu.ts,层级 L1,完整可编译。运行命令 node --test test/01-2-custom-window-menu-shortcut.test.ts:
// file: src/shortcut-menu.ts
// tier: L1
// verify: node --test test/01-2-custom-window-menu-shortcut.test.ts
//
// 卷四(第一章):自定义窗口、菜单与快捷键。
// 扩展在清单之外还要交两样东西:它往菜单树里插的项,以及它占用的
// 快捷键。快捷键是全局资源,注册表必须检测跨扩展冲突;菜单是树,
// 由「File/Export/PNG」这样的路径一次补全中间节点。
export interface Chord {
ctrl: boolean;
shift: boolean;
alt: boolean;
key: string;
}
export function parseChord(text: string): Chord {
const chord: Chord = { ctrl: false, shift: false, alt: false, key: '' };
for (const part of text.split('+')) {
const low = part.trim().toLowerCase();
if (low === 'ctrl' || low === 'cmd' || low === 'meta') chord.ctrl = true;
else if (low === 'shift') chord.shift = true;
else if (low === 'alt' || low === 'option') chord.alt = true;
else if (low) chord.key = low;
}
if (!chord.key) throw new Error(`快捷键缺少按键:${text}`);
return chord;
}
/** 规范化:修饰键固定顺序、按键小写转大写,便于比较与展示。 */
export function formatChord(c: Chord): string {
const parts: string[] = [];
if (c.ctrl) parts.push('Ctrl');
if (c.shift) parts.push('Shift');
if (c.alt) parts.push('Alt');
parts.push(c.key.toUpperCase());
return parts.join('+');
}
export class ShortcutRegistry {
#bindings = new Map<string, { command: string; extensionId: string }>();
/** 注册快捷键;同键不同命令返回冲突,且不写入。 */
register(
extensionId: string,
command: string,
chord: string,
): { ok: boolean; conflict?: string } {
const key = formatChord(parseChord(chord));
const existing = this.#bindings.get(key);
if (existing && existing.command !== command) {
return { ok: false, conflict: existing.command };
}
this.#bindings.set(key, { command, extensionId });
return { ok: true };
}
resolve(text: string): string | undefined {
return this.#bindings.get(formatChord(parseChord(text)))?.command;
}
count(): number {
return this.#bindings.size;
}
}
export interface MenuNode {
label: string;
children: Map<string, MenuNode>;
command?: string;
}
/** 由「菜单/子菜单/项」路径构建菜单树,中间节点自动补全。 */
export function buildMenu(items: { path: string; command: string }[]): MenuNode {
const root: MenuNode = { label: '', children: new Map() };
for (const item of items) {
const segs = item.path.split('/').filter((s) => s.length > 0);
let node = root;
segs.forEach((seg, i) => {
let child = node.children.get(seg);
if (!child) {
child = { label: seg, children: new Map() };
node.children.set(seg, child);
}
if (i === segs.length - 1) child.command = item.command;
node = child;
});
}
return root;
}
/** 按深度优先顺序取出所有叶子命令,用来断言菜单内容与顺序。 */
export function menuLeaves(node: MenuNode): string[] {
const out: string[] = [];
for (const child of node.children.values()) {
if (child.children.size === 0) {
if (child.command) out.push(child.command);
} else {
out.push(...menuLeaves(child));
}
}
return out;
}
parseChord 与 formatChord 构成一对规范化函数,是所有比较的唯一入口;register 只认规范化后的键,因此 shift+ctrl+k 与 Ctrl+Shift+K 被视为同一绑定。buildMenu 不排序,保留声明顺序,让扩展作者能控制菜单项先后。
下面是 test/01-2-custom-window-menu-shortcut.test.ts,层级 L1:
// file: test/01-2-custom-window-menu-shortcut.test.ts
// tier: L1
// verify: node --test test/01-2-custom-window-menu-shortcut.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parseChord,
formatChord,
ShortcutRegistry,
buildMenu,
menuLeaves,
} from '../src/shortcut-menu.ts';
test('解析快捷键与修饰键顺序无关', () => {
const c = parseChord('shift+ctrl+k');
assert.equal(c.ctrl, true);
assert.equal(c.shift, true);
assert.equal(c.alt, false);
assert.equal(c.key, 'k');
});
test('格式化往返保持规范形式', () => {
assert.equal(formatChord(parseChord('shift+ctrl+k')), 'Ctrl+Shift+K');
assert.equal(formatChord(parseChord('Ctrl+Shift+K')), 'Ctrl+Shift+K');
});
test('跨扩展快捷键冲突被拒绝', () => {
const r = new ShortcutRegistry();
assert.deepEqual(r.register('ext-a', 'file.save', 'Ctrl+K'), { ok: true });
const second = r.register('ext-b', 'file.format', 'ctrl+k');
assert.equal(second.ok, false);
assert.equal(second.conflict, 'file.save');
assert.equal(r.resolve('Ctrl+K'), 'file.save');
});
test('同一命令重复注册幂等', () => {
const r = new ShortcutRegistry();
r.register('ext-a', 'file.save', 'Ctrl+K');
assert.deepEqual(r.register('ext-a', 'file.save', 'Ctrl+K'), { ok: true });
assert.equal(r.count(), 1);
});
test('菜单路径自动补全中间节点', () => {
const root = buildMenu([
{ path: 'File/Export/PNG', command: 'file.export.png' },
{ path: 'File/Export/WebP', command: 'file.export.webp' },
{ path: 'File/Close', command: 'file.close' },
]);
const file = root.children.get('File');
assert.ok(file);
assert.deepEqual([...file.children.keys()], ['Export', 'Close']);
const exp = file.children.get('Export');
assert.ok(exp);
assert.deepEqual([...exp.children.keys()], ['PNG', 'WebP']);
});
test('叶子命令按深度优先输出', () => {
const root = buildMenu([
{ path: 'A/x', command: 'a.x' },
{ path: 'A/B/y', command: 'a.b.y' },
{ path: 'C/z', command: 'c.z' },
]);
assert.deepEqual(menuLeaves(root), ['a.x', 'a.b.y', 'c.z']);
});
本机实测(Node v26.5.0,node --test test/01-2-custom-window-menu-shortcut.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。
前两条钉快捷键解析与规范化往返;第三条钉跨扩展冲突;第四条钉幂等;第五、六条钉菜单中间节点与叶子顺序。
小结
- 快捷键必须先规范化再比较,否则大小写与修饰键顺序会造成假冲突。
- 冲突要返回已有命令,扩展作者才能提示用户改键。
- 菜单树由路径生成,中间节点不需要扩展重复声明。
- 叶子遍历顺序即显示顺序,不要在构建时隐式排序。
阅读导航:上一节:1.1 扩展清单、注册与生命周期 · 下一节:1.3 扩展的安全与隔离 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。