觸控列支援
·3 分鐘閱讀
Electron 1.6.3 beta 版本包含對 macOS 觸控列的初步支援。
新的觸控列 API 可讓您新增按鈕、標籤、彈出視窗、顏色選擇器、滑桿和間隔符。這些元素可以動態更新,並且在與其互動時也會發出事件。
這是此 API 的第一個版本,因此它將在接下來的幾個 Electron 版本中不斷發展。請查看版本說明以取得進一步的更新,並針對任何問題或缺少的功能開啟 問題。
您可以透過 npm install electron@beta
安裝此版本,並在 TouchBar 和 BrowserWindow Electron 文件中了解更多資訊。
非常感謝 @MarshallOfSound 為 Electron 貢獻此功能。🎉
觸控列範例
以下是在觸控列中建立簡單拉霸機遊戲的範例。它示範如何建立觸控列、設定項目樣式、將其與視窗關聯、處理按鈕點擊事件以及動態更新標籤。
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);
});