Touch Bar サポート
·3 分で読めます
Electron 1.6.3 ベータリリースには、macOS の Touch Bar の初期サポートが含まれています。
新しい Touch Bar API では、ボタン、ラベル、ポップオーバー、カラーピッカー、スライダー、およびスペーサーを追加できます。これらの要素は動的に更新でき、操作されたときにイベントを発行することもできます。
これはこの API の最初のリリースであるため、次のいくつかの Electron リリースで進化していきます。今後のアップデートについてはリリースノートを確認し、問題や欠落している機能については issues をオープンしてください。
このバージョンは npm install electron@beta
でインストールでき、詳細については、TouchBar および BrowserWindow の Electron ドキュメントを参照してください。
Electron への貢献に感謝します @MarshallOfSound🎉
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);
});