Enhance CSS test preview with live capture, brightness display, and UX fixes

- Stream live JPEG frames from picture sources into the test preview rectangle
- Add composite layer brightness display via value source streaming
- Fix missing id on css-test-rect-screen element that prevented frame display
- Preload images before swapping to eliminate flicker on frame updates
- Increase preview resolution to 480x360 and add subtle outline
- Prevent auto-focus on name field in modals on touch devices (desktopFocus)
- Fix performance chart padding, color picker clipping, and subtitle offset
- Add calibration-style ticks and source name/LED count to rectangle preview

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-13 01:31:37 +03:00
parent 9b5686ac0a
commit 568a992a4e
12 changed files with 353 additions and 48 deletions

View File

@@ -6,6 +6,16 @@ import { kcTestAutoRefresh, setKcTestAutoRefresh, setKcTestTargetId, confirmReso
import { t } from './i18n.js';
import { ICON_PAUSE, ICON_START } from './icons.js';
/** Returns true on touch devices where auto-focus would pop up the virtual keyboard */
export function isTouchDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
/** Focus element only on non-touch devices (avoids virtual keyboard popup on mobile) */
export function desktopFocus(el) {
if (el && !isTouchDevice()) el.focus();
}
export function toggleHint(btn) {
const hint = btn.closest('.label-row').nextElementSibling;
if (hint && hint.classList.contains('input-hint')) {

View File

@@ -5,7 +5,7 @@
import { fetchWithAuth, escapeHtml } from '../core/api.js';
import { _cachedSyncClocks, _cachedValueSources, audioSourcesCache, streamsCache, colorStripSourcesCache, valueSourcesCache } from '../core/state.js';
import { t } from '../core/i18n.js';
import { showToast, showConfirm } from '../core/ui.js';
import { showToast, showConfirm, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import {
getColorStripIcon, getPictureSourceIcon, getAudioSourceIcon, getValueSourceIcon,
@@ -13,6 +13,7 @@ import {
ICON_LED, ICON_PALETTE, ICON_FPS, ICON_MAP_PIN, ICON_MUSIC,
ICON_AUDIO_LOOPBACK, ICON_TIMER, ICON_LINK_SOURCE, ICON_FILM,
ICON_LINK, ICON_SPARKLES, ICON_ACTIVITY, ICON_CLOCK, ICON_BELL, ICON_EYE,
ICON_SUN_DIM,
} from '../core/icons.js';
import * as P from '../core/icon-paths.js';
import { wrapCard } from '../core/card-colors.js';
@@ -1553,7 +1554,7 @@ export async function showCSSEditor(cssId = null, cloneData = null) {
cssEditorModal.snapshot();
cssEditorModal.open();
setTimeout(() => document.getElementById('css-editor-name').focus(), 100);
setTimeout(() => desktopFocus(document.getElementById('css-editor-name')), 100);
} catch (error) {
if (error.isAuth) return;
console.error('Failed to open CSS editor:', error);
@@ -1924,7 +1925,6 @@ export function testColorStrip(sourceId) {
if (layersContainer) layersContainer.innerHTML = '';
document.getElementById('css-test-status').style.display = '';
document.getElementById('css-test-status').textContent = t('color_strip.test.connecting');
document.getElementById('css-test-led-count').textContent = '';
// Restore LED count + Enter key handler
const ledCount = _getCssTestLedCount();
@@ -1954,8 +1954,16 @@ function _cssTestConnect(sourceId, ledCount) {
if (gen !== _cssTestGeneration) return;
if (typeof event.data === 'string') {
// JSON metadata
_cssTestMeta = JSON.parse(event.data);
const msg = JSON.parse(event.data);
// Handle brightness updates for composite layers
if (msg.type === 'brightness') {
_cssTestUpdateBrightness(msg.values);
return;
}
// Initial metadata
_cssTestMeta = msg;
const isPicture = _cssTestMeta.edges && _cssTestMeta.edges.length > 0;
_cssTestIsComposite = _cssTestMeta.layers && _cssTestMeta.layers.length > 0;
@@ -1977,7 +1985,15 @@ function _cssTestConnect(sourceId, ledCount) {
const fireBtn = document.getElementById('css-test-fire-btn');
if (fireBtn) fireBtn.style.display = (isNotify && !_cssTestIsComposite) ? '' : 'none';
document.getElementById('css-test-led-count').textContent = `${_cssTestMeta.led_count} LEDs`;
// Populate rect screen labels for picture sources
if (isPicture) {
const nameEl = document.getElementById('css-test-rect-name');
const ledsEl = document.getElementById('css-test-rect-leds');
if (nameEl) nameEl.textContent = _cssTestMeta.source_name || '';
if (ledsEl) ledsEl.textContent = `${_cssTestMeta.led_count} LEDs`;
// Render tick marks after layout settles
requestAnimationFrame(() => _cssTestRenderTicks(_cssTestMeta.edges));
}
// Build composite layer canvases
if (_cssTestIsComposite) {
@@ -1985,6 +2001,27 @@ function _cssTestConnect(sourceId, ledCount) {
}
} else {
const raw = new Uint8Array(event.data);
// Check JPEG frame preview: [0xFD] [jpeg_bytes]
if (raw.length > 1 && raw[0] === 0xFD) {
const jpegBlob = new Blob([raw.subarray(1)], { type: 'image/jpeg' });
const url = URL.createObjectURL(jpegBlob);
const screen = document.getElementById('css-test-rect-screen');
if (screen) {
// Preload image to avoid flicker on swap
const img = new Image();
img.onload = () => {
const oldUrl = screen._blobUrl;
screen._blobUrl = url;
screen.style.backgroundImage = `url(${url})`;
screen.style.backgroundSize = 'cover';
screen.style.backgroundPosition = 'center';
if (oldUrl) URL.revokeObjectURL(oldUrl);
};
img.onerror = () => URL.revokeObjectURL(url);
img.src = url;
}
return;
}
// Check composite wire format: [0xFE] [layer_count] [led_count_hi] [led_count_lo] [layers...] [composite...]
if (raw.length > 3 && raw[0] === 0xFE && _cssTestIsComposite) {
const layerCount = raw[1];
@@ -2032,18 +2069,40 @@ function _cssTestBuildLayers(layerNames, sourceType, layerInfos) {
for (let i = 0; i < layerNames.length; i++) {
const info = layerInfos && layerInfos[i];
const isNotify = info && info.is_notification;
const hasBri = info && info.has_brightness;
const fireBtn = isNotify
? `<button class="css-test-fire-btn" onclick="event.stopPropagation(); fireCssTestNotificationLayer('${info.id}')" title="${t('color_strip.notification.test')}">${_BELL_SVG}</button>`
: '';
const briLabel = hasBri
? `<span class="css-test-layer-brightness" data-layer-idx="${i}" style="display:none"></span>`
: '';
html += `<div class="css-test-layer css-test-strip-wrap">` +
`<canvas class="css-test-layer-canvas" data-layer-idx="${i}"></canvas>` +
`<span class="css-test-layer-label">${escapeHtml(layerNames[i])}</span>` +
briLabel +
fireBtn +
`</div>`;
}
container.innerHTML = html;
}
function _cssTestUpdateBrightness(values) {
if (!values) return;
const container = document.getElementById('css-test-layers');
if (!container) return;
for (let i = 0; i < values.length; i++) {
const el = container.querySelector(`.css-test-layer-brightness[data-layer-idx="${i}"]`);
if (!el) continue;
const v = values[i];
if (v != null) {
el.innerHTML = `${ICON_SUN_DIM} ${v}%`;
el.style.display = '';
} else {
el.style.display = 'none';
}
}
}
export function applyCssTestLedCount() {
const input = document.getElementById('css-test-led-input');
if (!input || !_cssTestSourceId) return;
@@ -2164,6 +2223,117 @@ function _cssTestRenderRect(rgbBytes, edges) {
}
}
function _cssTestRenderTicks(edges) {
const canvas = document.getElementById('css-test-rect-ticks');
const rectEl = document.getElementById('css-test-rect');
if (!canvas || !rectEl) return;
const outer = canvas.parentElement;
const outerRect = outer.getBoundingClientRect();
const gridRect = rectEl.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = outerRect.width * dpr;
canvas.height = outerRect.height * dpr;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, outerRect.width, outerRect.height);
// Grid offset within outer container (the padding area)
const gx = gridRect.left - outerRect.left;
const gy = gridRect.top - outerRect.top;
const gw = gridRect.width;
const gh = gridRect.height;
const edgeThick = 14; // matches CSS grid-template
// Build edge map with indices
const edgeMap = { top: [], right: [], bottom: [], left: [] };
for (const e of edges) {
if (edgeMap[e.edge]) edgeMap[e.edge].push(...e.indices);
}
const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
const tickStroke = isDark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.35)';
const tickFill = isDark ? 'rgba(255, 255, 255, 0.75)' : 'rgba(0, 0, 0, 0.65)';
ctx.strokeStyle = tickStroke;
ctx.fillStyle = tickFill;
ctx.lineWidth = 1;
ctx.font = '10px -apple-system, BlinkMacSystemFont, sans-serif';
const edgeGeom = {
top: { x1: gx + edgeThick, x2: gx + gw - edgeThick, y: gy, dir: -1, horizontal: true },
bottom: { x1: gx + edgeThick, x2: gx + gw - edgeThick, y: gy + gh, dir: 1, horizontal: true },
left: { y1: gy + edgeThick, y2: gy + gh - edgeThick, x: gx, dir: -1, horizontal: false },
right: { y1: gy + edgeThick, y2: gy + gh - edgeThick, x: gx + gw, dir: 1, horizontal: false },
};
for (const [edge, indices] of Object.entries(edgeMap)) {
const count = indices.length;
if (count === 0) continue;
const geo = edgeGeom[edge];
// Determine which ticks to label
const labelsToShow = new Set([0]);
if (count > 1) labelsToShow.add(count - 1);
if (count > 2) {
const edgeLen = geo.horizontal ? (geo.x2 - geo.x1) : (geo.y2 - geo.y1);
const maxDigits = String(Math.max(...indices)).length;
const minSpacing = geo.horizontal ? maxDigits * 7 + 8 : 20;
const niceSteps = [5, 10, 25, 50, 100, 250, 500];
let step = niceSteps[niceSteps.length - 1];
for (const s of niceSteps) {
if (Math.floor(count / s) <= 4) { step = s; break; }
}
const tickPx = i => (i / (count - 1)) * edgeLen;
const placed = [];
// Place boundary ticks first
labelsToShow.forEach(i => placed.push(tickPx(i)));
for (let i = 1; i < count - 1; i++) {
if (indices[i] % step === 0) {
const px = tickPx(i);
if (!placed.some(p => Math.abs(px - p) < minSpacing)) {
labelsToShow.add(i);
placed.push(px);
}
}
}
}
const tickLen = 6;
labelsToShow.forEach(idx => {
const label = String(indices[idx]);
const fraction = count > 1 ? idx / (count - 1) : 0.5;
if (geo.horizontal) {
const tx = geo.x1 + fraction * (geo.x2 - geo.x1);
const ty = geo.y;
const tickDir = geo.dir; // -1 for top (tick goes up), +1 for bottom (tick goes down)
ctx.beginPath();
ctx.moveTo(tx, ty);
ctx.lineTo(tx, ty + tickDir * tickLen);
ctx.stroke();
ctx.textAlign = 'center';
ctx.textBaseline = tickDir < 0 ? 'bottom' : 'top';
ctx.fillText(label, tx, ty + tickDir * (tickLen + 2));
} else {
const ty = geo.y1 + fraction * (geo.y2 - geo.y1);
const tx = geo.x;
const tickDir = geo.dir; // -1 for left (tick goes left), +1 for right (tick goes right)
ctx.beginPath();
ctx.moveTo(tx, ty);
ctx.lineTo(tx + tickDir * tickLen, ty);
ctx.stroke();
ctx.textBaseline = 'middle';
ctx.textAlign = tickDir < 0 ? 'right' : 'left';
ctx.fillText(label, tx + tickDir * (tickLen + 2), ty);
}
});
}
}
export function fireCssTestNotification() {
for (const id of _cssTestNotificationIds) {
testNotification(id);
@@ -2183,6 +2353,9 @@ export function closeTestCssSourceModal() {
_cssTestIsComposite = false;
_cssTestLayerData = null;
_cssTestNotificationIds = [];
// Revoke blob URL for frame preview
const screen = document.getElementById('css-test-rect-screen');
if (screen && screen._blobUrl) { URL.revokeObjectURL(screen._blobUrl); screen._blobUrl = null; screen.style.backgroundImage = ''; }
const modal = document.getElementById('test-css-source-modal');
if (modal) { modal.style.display = 'none'; }
}

View File

@@ -9,7 +9,7 @@ import {
import { API_BASE, fetchWithAuth, isSerialDevice, isMockDevice, isMqttDevice, isWsDevice, isOpenrgbDevice, escapeHtml } from '../core/api.js';
import { devicesCache } from '../core/state.js';
import { t } from '../core/i18n.js';
import { showToast } from '../core/ui.js';
import { showToast, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import { _computeMaxFps, _renderFpsHint } from './devices.js';
import { getDeviceTypeIcon } from '../core/icons.js';
@@ -302,7 +302,7 @@ export function showAddDevice() {
addDeviceModal.open();
onDeviceTypeChanged();
setTimeout(() => {
document.getElementById('device-name').focus();
desktopFocus(document.getElementById('device-name'));
addDeviceModal.snapshot();
}, 100);
}

View File

@@ -9,7 +9,7 @@ import { API_BASE, getHeaders, fetchWithAuth, escapeHtml, isSerialDevice, isMock
import { devicesCache } from '../core/state.js';
import { _fetchOpenrgbZones, _getCheckedZones, _splitOpenrgbZone, _getZoneMode } from './device-discovery.js';
import { t } from '../core/i18n.js';
import { showToast, showConfirm } from '../core/ui.js';
import { showToast, showConfirm, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import { ICON_SETTINGS, ICON_STOP_PLAIN, ICON_LED, ICON_WEB, ICON_PLUG, ICON_REFRESH } from '../core/icons.js';
import { wrapCard } from '../core/card-colors.js';
@@ -369,9 +369,7 @@ export async function showSettings(deviceId) {
settingsModal.snapshot();
settingsModal.open();
setTimeout(() => {
document.getElementById('settings-device-name').focus();
}, 100);
setTimeout(() => desktopFocus(document.getElementById('settings-device-name')), 100);
} catch (error) {
if (error.isAuth) return;

View File

@@ -13,7 +13,7 @@ import {
} from '../core/state.js';
import { API_BASE, getHeaders, fetchWithAuth, escapeHtml } from '../core/api.js';
import { t } from '../core/i18n.js';
import { lockBody, showToast, showConfirm, formatUptime } from '../core/ui.js';
import { lockBody, showToast, showConfirm, formatUptime, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import {
getValueSourceIcon, getPictureSourceIcon,
@@ -612,7 +612,7 @@ export async function showKCEditor(targetId = null, cloneData = null) {
kcEditorModal.open();
document.getElementById('kc-editor-error').style.display = 'none';
setTimeout(() => document.getElementById('kc-editor-name').focus(), 100);
setTimeout(() => desktopFocus(document.getElementById('kc-editor-name')), 100);
} catch (error) {
console.error('Failed to open KC editor:', error);
showToast(t('kc_target.error.editor_open_failed'), 'error');

View File

@@ -18,7 +18,7 @@ import {
import { API_BASE, getHeaders, fetchWithAuth, escapeHtml } from '../core/api.js';
import { patternTemplatesCache } from '../core/state.js';
import { t } from '../core/i18n.js';
import { showToast, showConfirm } from '../core/ui.js';
import { showToast, showConfirm, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import { getPictureSourceIcon, ICON_PATTERN_TEMPLATE, ICON_CLONE, ICON_EDIT } from '../core/icons.js';
import { wrapCard } from '../core/card-colors.js';
@@ -157,7 +157,7 @@ export async function showPatternTemplateEditor(templateId = null, cloneData = n
patternModal.open();
document.getElementById('pattern-template-error').style.display = 'none';
setTimeout(() => document.getElementById('pattern-template-name').focus(), 100);
setTimeout(() => desktopFocus(document.getElementById('pattern-template-name')), 100);
} catch (error) {
console.error('Failed to open pattern template editor:', error);
showToast(t('pattern.error.editor_open_failed'), 'error');

View File

@@ -14,7 +14,7 @@ import {
} from '../core/state.js';
import { API_BASE, getHeaders, fetchWithAuth, escapeHtml, isOpenrgbDevice } from '../core/api.js';
import { t } from '../core/i18n.js';
import { showToast, showConfirm, formatUptime, setTabRefreshing } from '../core/ui.js';
import { showToast, showConfirm, formatUptime, setTabRefreshing, desktopFocus } from '../core/ui.js';
import { Modal } from '../core/modal.js';
import { createDeviceCard, attachDeviceListeners, fetchDeviceBrightness, enrichOpenrgbZoneBadges, _computeMaxFps, getZoneCountCache } from './devices.js';
import { _splitOpenrgbZone } from './device-discovery.js';
@@ -448,7 +448,7 @@ export async function showTargetEditor(targetId = null, cloneData = null) {
targetEditorModal.open();
document.getElementById('target-editor-error').style.display = 'none';
setTimeout(() => document.getElementById('target-editor-name').focus(), 100);
setTimeout(() => desktopFocus(document.getElementById('target-editor-name')), 100);
} catch (error) {
console.error('Failed to open target editor:', error);
showToast(t('target.error.editor_open_failed'), 'error');