Skip to main content

Touch Bar 지원

· 4 min read

Electron 1.6.3 베타 버전이 macOS Touch Bar에 대한 초기 지원을 포함하고 있다.

새로운 Touch Bar API를 통해 버튼, 라벨, 팝오버, 색상 선택기, 슬라이더, 그리고 간격 조절기를 추가할 수 있다. 이러한 엘리먼트들은 동적으로 업데이트할 수 있으며, 사용자와 상호작용할 때 이벤트를 발생시킨다.

이 API는 첫 번째 릴리스이기 때문에 향후 몇 번의 Electron 릴리스에 걸쳐 발전할 예정이다. 추가 업데이트는 릴리스 노트를 확인하고, 문제나 누락된 기능이 있다면 이슈를 열어보길 바란다.

이 버전은 npm install electron@beta를 통해 설치할 수 있으며, TouchBarBrowserWindow Electron 문서에서 더 자세한 내용을 확인할 수 있다.

이 기능을 Electron에 기여한 @MarshallOfSound에게 큰 감사를 표한다. 🎉

터치 바 예제

터치 바 Gif

아래는 터치 바를 활용해 간단한 슬롯 머신 게임을 만드는 예제이다. 이 예제는 터치 바를 생성하고 아이템을 스타일링하며, 윈도우와 연결하고 버튼 클릭 이벤트를 처리하며, 레이블을 동적으로 업데이트하는 방법을 보여준다.

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

const { TouchBarButton, TouchBarLabel, TouchBarSpacer } = TouchBar;

let spinning = false;

// 릴 레이블
const reel1 = new TouchBarLabel();
const reel2 = new TouchBarLabel();
const reel3 = new TouchBarLabel();

// 스핀 결과 레이블
const result = new TouchBarLabel();

// 스핀 버튼
const spin = new TouchBarButton({
label: '🎰 Spin',
backgroundColor: '#7851A9',
click: () => {
// 이미 스핀 중이면 클릭 무시
if (spinning) {
return;
}

spinning = true;
result.label = '';

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

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

if (Date.now() - startTime >= spinLength) {
finishSpin();
} else {
// 각 스핀마다 속도를 조금씩 늦춤
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) {
// 3개 모두 같은 경우
result.label = '💰 Jackpot!';
result.textColor = '#FDFF00';
} else if (uniqueValues === 2) {
// 2개가 같은 경우
result.label = '😍 Winner!';
result.textColor = '#FDFF00';
} else {
// 모두 다른 경우
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);
});