Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion bin/sonic.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
verifyLogin
} from '../lib/spotify.js';
import { UI } from '../lib/ui.js';
import { queryTerminalBackground } from '../lib/themes.js';
import {
CHANNELS, ACTIVITIES,
getSuggestedChannel, getSuggestedActivity,
Expand Down Expand Up @@ -811,7 +812,11 @@ function promptSearch(notice = '') {
});
}

process.stdin.on('data', async (key) => {
process.stdin.on('data', async (input) => {
const key = String(input);
// A late reply to the background-color query is not a keypress.
if (key.startsWith('\x1b]')) return;

if (key === '\x03') {
cleanup(0);
return;
Expand Down Expand Up @@ -1144,6 +1149,9 @@ async function main() {
process.exit(1);
}

// Learn light vs dark before the first frame, so text never lands white on white.
if (store.config.colorMode === 'auto') await queryTerminalBackground();

ui.hideCursor();

if (connectMode) {
Expand Down
31 changes: 31 additions & 0 deletions lib/themes.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,37 @@ export function cycleTheme(themeId, direction = 1) {

let _detectedMode = null;

// Ask the terminal for its background color (OSC 11). Most terminals answer
// within a few ms; Terminal.app sets no COLORFGBG, so this is the reliable path.
export function queryTerminalBackground(timeoutMs = 250) {
return new Promise((resolve) => {
if (!process.stdin.isTTY || !process.stdout.isTTY) return resolve(null);
const wasRaw = process.stdin.isRaw;
let buffer = '';
const finish = (mode) => {
clearTimeout(timer);
process.stdin.off('data', onData);
if (!wasRaw) process.stdin.setRawMode(false);
process.stdin.pause();
if (mode) _detectedMode = mode;
resolve(mode);
};
const onData = (chunk) => {
buffer += chunk.toString();
const match = buffer.match(/rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);
if (!match) return;
const [r, g, b] = match.slice(1).map((hex) => parseInt(hex, 16) / (16 ** hex.length - 1));
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
finish(luminance > 0.5 ? 'light' : 'dark');
};
const timer = setTimeout(() => finish(null), timeoutMs);
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', onData);
process.stdout.write('\x1b]11;?\x07');
});
}

export function detectColorMode() {
if (_detectedMode) return _detectedMode;
const colorfgbg = process.env.COLORFGBG;
Expand Down
Loading