跳到主要内容

Touch Bar 支持

·3 分钟阅读

Electron 1.6.3 beta 版本包含了对 macOS Touch Bar 的初始支持。


新的 Touch Bar API 允许您添加按钮、标签、弹出框、颜色选择器、滑块和间隔。这些元素可以动态更新,并在与之交互时发出事件。

这是此 API 的第一个版本,因此它将在接下来的几个 Electron 版本中不断发展。请查看发行说明以获取更多更新,如有任何问题或缺少功能,请提交 issue。

您可以通过 npm install electron@beta 安装此版本,并在 TouchBarBrowserWindow Electron 文档中了解更多信息。

非常感谢 @MarshallOfSound 为 Electron 贡献了此功能。🎉

Touch Bar 示例

Touch Bar Gif

下面是一个在 Touch Bar 中创建简单老虎机游戏的示例。它演示了如何创建 Touch Bar、设置项目样式、将其与窗口关联、处理按钮点击事件以及动态更新标签。

const { app, BrowserWindow, TouchBar } = require('electron');

const { TouchBarButton, TouchBarLabel, TouchBarSpacer } = TouchBar;

let spinning = false;

// Reel labels
const reel1 = new TouchBarLabel();
const reel2 = new TouchBarLabel();
const reel3 = new TouchBarLabel();

// Spin result label
const result = new TouchBarLabel();

// Spin button
const spin = new TouchBarButton({
label: '🎰 Spin',
backgroundColor: '#7851A9',
click: () => {
// Ignore clicks if already spinning
if (spinning) {
return;
}

spinning = true;
result.label = '';

let timeout = 10;
const spinLength = 4 * 1000; // 4 seconds
const startTime = Date.now();

const spinReels = () => {
updateReels();

if (Date.now() - startTime >= spinLength) {
finishSpin();
} else {
// Slow down a bit on each spin
timeout *= 1.1;
setTimeout(spinReels, timeout);
}
};

spinReels();
},
});

const getRandomValue = () => {
const values = ['🍒', '💎', '7️⃣', '🍊', '🔔', '⭐', '🍇', '🍀'];
return values[Math.floor(Math.random() * values.length)];
};

const updateReels = () => {
reel1.label = getRandomValue();
reel2.label = getRandomValue();
reel3.label = getRandomValue();
};

const finishSpin = () => {
const uniqueValues = new Set([reel1.label, reel2.label, reel3.label]).size;
if (uniqueValues === 1) {
// All 3 values are the same
result.label = '💰 Jackpot!';
result.textColor = '#FDFF00';
} else if (uniqueValues === 2) {
// 2 values are the same
result.label = '😍 Winner!';
result.textColor = '#FDFF00';
} else {
// No values are the same
result.label = '🙁 Spin Again';
result.textColor = null;
}
spinning = false;
};

const touchBar = new TouchBar([
spin,
new TouchBarSpacer({ size: 'large' }),
reel1,
new TouchBarSpacer({ size: 'small' }),
reel2,
new TouchBarSpacer({ size: 'small' }),
reel3,
new TouchBarSpacer({ size: 'large' }),
result,
]);

let window;

app.once('ready', () => {
window = new BrowserWindow({
frame: false,
titleBarStyle: 'hidden-inset',
width: 200,
height: 200,
backgroundColor: '#000',
});
window.loadURL('about:blank');
window.setTouchBar(touchBar);
});