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

@@ -1,8 +1,11 @@
"""Color strip source routes: CRUD, calibration test, preview, and API input push.""" """Color strip source routes: CRUD, calibration test, preview, and API input push."""
import asyncio import asyncio
import io as _io
import json as _json import json as _json
import secrets import secrets
import time as _time
import uuid as _uuid
import numpy as np import numpy as np
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
@@ -706,7 +709,6 @@ async def test_color_strip_ws(
return return
# Acquire stream unique consumer ID per WS to avoid release races # Acquire stream unique consumer ID per WS to avoid release races
import uuid as _uuid
manager: ProcessorManager = get_processor_manager() manager: ProcessorManager = get_processor_manager()
csm = manager.color_strip_stream_manager csm = manager.color_strip_stream_manager
consumer_id = f"__test_{_uuid.uuid4().hex[:8]}__" consumer_id = f"__test_{_uuid.uuid4().hex[:8]}__"
@@ -733,6 +735,7 @@ async def test_color_strip_ws(
meta: dict = { meta: dict = {
"type": "meta", "type": "meta",
"source_type": source.source_type, "source_type": source.source_type,
"source_name": source.name,
"led_count": stream.led_count, "led_count": stream.led_count,
} }
if is_picture and stream.calibration: if is_picture and stream.calibration:
@@ -752,9 +755,10 @@ async def test_color_strip_ws(
if is_composite and hasattr(source, "layers"): if is_composite and hasattr(source, "layers"):
# Send layer info for composite preview # Send layer info for composite preview
enabled_layers = [l for l in source.layers if l.get("enabled", True)] enabled_layers = [l for l in source.layers if l.get("enabled", True)]
layer_infos = [] # [{name, id, is_notification}, ...] layer_infos = [] # [{name, id, is_notification, has_brightness}, ...]
for layer in enabled_layers: for layer in enabled_layers:
info = {"id": layer["source_id"], "name": layer.get("source_id", "?"), "is_notification": False} info = {"id": layer["source_id"], "name": layer.get("source_id", "?"),
"is_notification": False, "has_brightness": bool(layer.get("brightness_source_id"))}
try: try:
layer_src = store.get_source(layer["source_id"]) layer_src = store.get_source(layer["source_id"])
info["name"] = layer_src.name info["name"] = layer_src.name
@@ -766,6 +770,13 @@ async def test_color_strip_ws(
meta["layer_infos"] = layer_infos meta["layer_infos"] = layer_infos
await websocket.send_text(_json.dumps(meta)) await websocket.send_text(_json.dumps(meta))
# For picture sources, grab the live stream for frame preview
_frame_live = None
if is_picture and hasattr(stream, '_live_stream'):
_frame_live = stream._live_stream
_last_aux_time = 0.0
_AUX_INTERVAL = 0.5 # send JPEG preview / brightness updates every 0.5s
# Stream binary RGB frames at ~20 Hz # Stream binary RGB frames at ~20 Hz
while True: while True:
# For composite sources, send per-layer data like target preview does # For composite sources, send per-layer data like target preview does
@@ -791,6 +802,50 @@ async def test_color_strip_ws(
colors = stream.get_latest_colors() colors = stream.get_latest_colors()
if colors is not None: if colors is not None:
await websocket.send_bytes(colors.tobytes()) await websocket.send_bytes(colors.tobytes())
# Periodically send auxiliary data (frame preview, brightness)
now = _time.monotonic()
if now - _last_aux_time >= _AUX_INTERVAL:
_last_aux_time = now
# Send brightness values for composite layers
if is_composite and isinstance(stream, CompositeColorStripStream):
try:
bri_values = stream.get_layer_brightness()
if any(v is not None for v in bri_values):
bri_msg = {"type": "brightness", "values": [
round(v * 100) if v is not None else None for v in bri_values
]}
await websocket.send_text(_json.dumps(bri_msg))
except Exception:
pass
# Send JPEG frame preview for picture sources
if _frame_live:
try:
frame = _frame_live.get_latest_frame()
if frame is not None and frame.image is not None:
from PIL import Image as _PIL_Image
img = frame.image
# Ensure 3-channel RGB (some engines may produce BGRA)
if img.ndim == 3 and img.shape[2] == 4:
img = img[:, :, :3]
# Downscale for bandwidth
h, w = img.shape[:2]
scale = min(480 / w, 360 / h, 1.0)
if scale < 1.0:
new_w = max(1, int(w * scale))
new_h = max(1, int(h * scale))
pil = _PIL_Image.fromarray(img).resize((new_w, new_h), _PIL_Image.LANCZOS)
else:
pil = _PIL_Image.fromarray(img)
buf = _io.BytesIO()
pil.save(buf, format='JPEG', quality=70)
# Wire format: [0xFD] [jpeg_bytes]
await websocket.send_bytes(b'\xfd' + buf.getvalue())
except Exception as e:
logger.warning(f"JPEG frame preview error: {e}")
await asyncio.sleep(0.05) await asyncio.sleep(0.05)
except WebSocketDisconnect: except WebSocketDisconnect:
pass pass

View File

@@ -110,6 +110,22 @@ class CompositeColorStripStream(ColorStripStream):
with self._colors_lock: with self._colors_lock:
return self._latest_layer_colors return self._latest_layer_colors
def get_layer_brightness(self) -> List[Optional[float]]:
"""Return per-layer brightness values (0.0-1.0) from value sources, or None if no source."""
enabled = [l for l in self._layers if l.get("enabled", True)]
result: List[Optional[float]] = []
with self._sub_lock:
for i in range(len(enabled)):
if i in self._brightness_streams:
_vs_id, vs = self._brightness_streams[i]
try:
result.append(vs.get_value())
except Exception:
result.append(None)
else:
result.append(None)
return result
def configure(self, device_led_count: int) -> None: def configure(self, device_led_count: int) -> None:
if self._auto_size and device_led_count > 0 and device_led_count != self._led_count: if self._auto_size and device_led_count > 0 and device_led_count != self._led_count:
self._led_count = device_led_count self._led_count = device_led_count

View File

@@ -354,14 +354,14 @@
background: var(--card-bg); background: var(--card-bg);
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: 6px; border-radius: 6px;
padding: 10px 12px; padding: 10px 0 0;
min-width: 0; min-width: 0;
overflow: hidden;
} }
.perf-chart-wrap { .perf-chart-wrap {
position: relative; position: relative;
height: 100px; height: 100px;
overflow: hidden;
} }
.perf-chart-header { .perf-chart-header {
@@ -369,6 +369,7 @@
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 0; margin-bottom: 0;
padding: 0 12px;
} }
.perf-chart-label { .perf-chart-label {
@@ -382,7 +383,7 @@
.perf-chart-subtitle { .perf-chart-subtitle {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 12px;
font-size: 0.6rem; font-size: 0.6rem;
font-weight: 400; font-weight: 400;
color: var(--text-muted); color: var(--text-muted);

View File

@@ -156,6 +156,20 @@
background: rgba(255, 255, 255, 0.25); background: rgba(255, 255, 255, 0.25);
} }
.css-test-rect-outer {
position: relative;
padding: 22px 30px;
}
.css-test-rect-ticks {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 2;
}
.css-test-rect { .css-test-rect {
display: grid; display: grid;
grid-template-columns: 14px 1fr 14px; grid-template-columns: 14px 1fr 14px;
@@ -170,8 +184,36 @@
} }
.css-test-rect-screen { .css-test-rect-screen {
background: #111; background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
background-size: cover;
background-position: center;
border-radius: 2px; border-radius: 2px;
outline: 1px solid rgba(255, 255, 255, 0.15);
outline-offset: -1px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
overflow: hidden;
}
.css-test-rect-label {
color: rgba(255, 255, 255, 0.85);
font-size: 0.8rem;
font-weight: 600;
text-align: center;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 90%;
}
.css-test-rect-leds {
font-size: 0.7rem;
font-weight: 400;
opacity: 0.75;
} }
.css-test-edge-wrap { .css-test-edge-wrap {
@@ -190,15 +232,6 @@
display: block; display: block;
} }
.css-test-info {
display: flex;
gap: 16px;
padding: 8px 0 0;
font-family: monospace;
font-size: 0.85em;
color: var(--text-muted, #888);
}
.css-test-status { .css-test-status {
text-align: center; text-align: center;
padding: 8px 0; padding: 8px 0;
@@ -245,6 +278,23 @@
opacity: 1; opacity: 1;
} }
.css-test-layer-brightness {
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
font-size: 0.6rem;
font-family: var(--font-mono, monospace);
color: #fff;
text-shadow: 0 0 3px rgba(0,0,0,0.9), 0 0 6px rgba(0,0,0,0.6);
pointer-events: none;
white-space: nowrap;
display: flex;
align-items: center;
gap: 2px;
}
.css-test-layer-brightness svg { width: 12px; height: 12px; }
/* LED count control */ /* LED count control */
.css-test-led-control { .css-test-led-control {
display: flex; display: flex;

View File

@@ -6,6 +6,16 @@ import { kcTestAutoRefresh, setKcTestAutoRefresh, setKcTestTargetId, confirmReso
import { t } from './i18n.js'; import { t } from './i18n.js';
import { ICON_PAUSE, ICON_START } from './icons.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) { export function toggleHint(btn) {
const hint = btn.closest('.label-row').nextElementSibling; const hint = btn.closest('.label-row').nextElementSibling;
if (hint && hint.classList.contains('input-hint')) { if (hint && hint.classList.contains('input-hint')) {

View File

@@ -5,7 +5,7 @@
import { fetchWithAuth, escapeHtml } from '../core/api.js'; import { fetchWithAuth, escapeHtml } from '../core/api.js';
import { _cachedSyncClocks, _cachedValueSources, audioSourcesCache, streamsCache, colorStripSourcesCache, valueSourcesCache } from '../core/state.js'; import { _cachedSyncClocks, _cachedValueSources, audioSourcesCache, streamsCache, colorStripSourcesCache, valueSourcesCache } from '../core/state.js';
import { t } from '../core/i18n.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 { Modal } from '../core/modal.js';
import { import {
getColorStripIcon, getPictureSourceIcon, getAudioSourceIcon, getValueSourceIcon, getColorStripIcon, getPictureSourceIcon, getAudioSourceIcon, getValueSourceIcon,
@@ -13,6 +13,7 @@ import {
ICON_LED, ICON_PALETTE, ICON_FPS, ICON_MAP_PIN, ICON_MUSIC, ICON_LED, ICON_PALETTE, ICON_FPS, ICON_MAP_PIN, ICON_MUSIC,
ICON_AUDIO_LOOPBACK, ICON_TIMER, ICON_LINK_SOURCE, ICON_FILM, ICON_AUDIO_LOOPBACK, ICON_TIMER, ICON_LINK_SOURCE, ICON_FILM,
ICON_LINK, ICON_SPARKLES, ICON_ACTIVITY, ICON_CLOCK, ICON_BELL, ICON_EYE, ICON_LINK, ICON_SPARKLES, ICON_ACTIVITY, ICON_CLOCK, ICON_BELL, ICON_EYE,
ICON_SUN_DIM,
} from '../core/icons.js'; } from '../core/icons.js';
import * as P from '../core/icon-paths.js'; import * as P from '../core/icon-paths.js';
import { wrapCard } from '../core/card-colors.js'; import { wrapCard } from '../core/card-colors.js';
@@ -1553,7 +1554,7 @@ export async function showCSSEditor(cssId = null, cloneData = null) {
cssEditorModal.snapshot(); cssEditorModal.snapshot();
cssEditorModal.open(); cssEditorModal.open();
setTimeout(() => document.getElementById('css-editor-name').focus(), 100); setTimeout(() => desktopFocus(document.getElementById('css-editor-name')), 100);
} catch (error) { } catch (error) {
if (error.isAuth) return; if (error.isAuth) return;
console.error('Failed to open CSS editor:', error); console.error('Failed to open CSS editor:', error);
@@ -1924,7 +1925,6 @@ export function testColorStrip(sourceId) {
if (layersContainer) layersContainer.innerHTML = ''; if (layersContainer) layersContainer.innerHTML = '';
document.getElementById('css-test-status').style.display = ''; document.getElementById('css-test-status').style.display = '';
document.getElementById('css-test-status').textContent = t('color_strip.test.connecting'); document.getElementById('css-test-status').textContent = t('color_strip.test.connecting');
document.getElementById('css-test-led-count').textContent = '';
// Restore LED count + Enter key handler // Restore LED count + Enter key handler
const ledCount = _getCssTestLedCount(); const ledCount = _getCssTestLedCount();
@@ -1954,8 +1954,16 @@ function _cssTestConnect(sourceId, ledCount) {
if (gen !== _cssTestGeneration) return; if (gen !== _cssTestGeneration) return;
if (typeof event.data === 'string') { if (typeof event.data === 'string') {
// JSON metadata const msg = JSON.parse(event.data);
_cssTestMeta = 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; const isPicture = _cssTestMeta.edges && _cssTestMeta.edges.length > 0;
_cssTestIsComposite = _cssTestMeta.layers && _cssTestMeta.layers.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'); const fireBtn = document.getElementById('css-test-fire-btn');
if (fireBtn) fireBtn.style.display = (isNotify && !_cssTestIsComposite) ? '' : 'none'; 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 // Build composite layer canvases
if (_cssTestIsComposite) { if (_cssTestIsComposite) {
@@ -1985,6 +2001,27 @@ function _cssTestConnect(sourceId, ledCount) {
} }
} else { } else {
const raw = new Uint8Array(event.data); 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...] // Check composite wire format: [0xFE] [layer_count] [led_count_hi] [led_count_lo] [layers...] [composite...]
if (raw.length > 3 && raw[0] === 0xFE && _cssTestIsComposite) { if (raw.length > 3 && raw[0] === 0xFE && _cssTestIsComposite) {
const layerCount = raw[1]; const layerCount = raw[1];
@@ -2032,18 +2069,40 @@ function _cssTestBuildLayers(layerNames, sourceType, layerInfos) {
for (let i = 0; i < layerNames.length; i++) { for (let i = 0; i < layerNames.length; i++) {
const info = layerInfos && layerInfos[i]; const info = layerInfos && layerInfos[i];
const isNotify = info && info.is_notification; const isNotify = info && info.is_notification;
const hasBri = info && info.has_brightness;
const fireBtn = isNotify const fireBtn = isNotify
? `<button class="css-test-fire-btn" onclick="event.stopPropagation(); fireCssTestNotificationLayer('${info.id}')" title="${t('color_strip.notification.test')}">${_BELL_SVG}</button>` ? `<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">` + html += `<div class="css-test-layer css-test-strip-wrap">` +
`<canvas class="css-test-layer-canvas" data-layer-idx="${i}"></canvas>` + `<canvas class="css-test-layer-canvas" data-layer-idx="${i}"></canvas>` +
`<span class="css-test-layer-label">${escapeHtml(layerNames[i])}</span>` + `<span class="css-test-layer-label">${escapeHtml(layerNames[i])}</span>` +
briLabel +
fireBtn + fireBtn +
`</div>`; `</div>`;
} }
container.innerHTML = html; 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() { export function applyCssTestLedCount() {
const input = document.getElementById('css-test-led-input'); const input = document.getElementById('css-test-led-input');
if (!input || !_cssTestSourceId) return; 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() { export function fireCssTestNotification() {
for (const id of _cssTestNotificationIds) { for (const id of _cssTestNotificationIds) {
testNotification(id); testNotification(id);
@@ -2183,6 +2353,9 @@ export function closeTestCssSourceModal() {
_cssTestIsComposite = false; _cssTestIsComposite = false;
_cssTestLayerData = null; _cssTestLayerData = null;
_cssTestNotificationIds = []; _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'); const modal = document.getElementById('test-css-source-modal');
if (modal) { modal.style.display = 'none'; } 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 { API_BASE, fetchWithAuth, isSerialDevice, isMockDevice, isMqttDevice, isWsDevice, isOpenrgbDevice, escapeHtml } from '../core/api.js';
import { devicesCache } from '../core/state.js'; import { devicesCache } from '../core/state.js';
import { t } from '../core/i18n.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 { Modal } from '../core/modal.js';
import { _computeMaxFps, _renderFpsHint } from './devices.js'; import { _computeMaxFps, _renderFpsHint } from './devices.js';
import { getDeviceTypeIcon } from '../core/icons.js'; import { getDeviceTypeIcon } from '../core/icons.js';
@@ -302,7 +302,7 @@ export function showAddDevice() {
addDeviceModal.open(); addDeviceModal.open();
onDeviceTypeChanged(); onDeviceTypeChanged();
setTimeout(() => { setTimeout(() => {
document.getElementById('device-name').focus(); desktopFocus(document.getElementById('device-name'));
addDeviceModal.snapshot(); addDeviceModal.snapshot();
}, 100); }, 100);
} }

View File

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

View File

@@ -13,7 +13,7 @@ import {
} from '../core/state.js'; } from '../core/state.js';
import { API_BASE, getHeaders, fetchWithAuth, escapeHtml } from '../core/api.js'; import { API_BASE, getHeaders, fetchWithAuth, escapeHtml } from '../core/api.js';
import { t } from '../core/i18n.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 { Modal } from '../core/modal.js';
import { import {
getValueSourceIcon, getPictureSourceIcon, getValueSourceIcon, getPictureSourceIcon,
@@ -612,7 +612,7 @@ export async function showKCEditor(targetId = null, cloneData = null) {
kcEditorModal.open(); kcEditorModal.open();
document.getElementById('kc-editor-error').style.display = 'none'; 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) { } catch (error) {
console.error('Failed to open KC editor:', error); console.error('Failed to open KC editor:', error);
showToast(t('kc_target.error.editor_open_failed'), '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 { API_BASE, getHeaders, fetchWithAuth, escapeHtml } from '../core/api.js';
import { patternTemplatesCache } from '../core/state.js'; import { patternTemplatesCache } from '../core/state.js';
import { t } from '../core/i18n.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 { Modal } from '../core/modal.js';
import { getPictureSourceIcon, ICON_PATTERN_TEMPLATE, ICON_CLONE, ICON_EDIT } from '../core/icons.js'; import { getPictureSourceIcon, ICON_PATTERN_TEMPLATE, ICON_CLONE, ICON_EDIT } from '../core/icons.js';
import { wrapCard } from '../core/card-colors.js'; import { wrapCard } from '../core/card-colors.js';
@@ -157,7 +157,7 @@ export async function showPatternTemplateEditor(templateId = null, cloneData = n
patternModal.open(); patternModal.open();
document.getElementById('pattern-template-error').style.display = 'none'; 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) { } catch (error) {
console.error('Failed to open pattern template editor:', error); console.error('Failed to open pattern template editor:', error);
showToast(t('pattern.error.editor_open_failed'), 'error'); showToast(t('pattern.error.editor_open_failed'), 'error');

View File

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

View File

@@ -16,18 +16,24 @@
<!-- Rectangle view (for picture sources) --> <!-- Rectangle view (for picture sources) -->
<div id="css-test-rect-view" style="display:none"> <div id="css-test-rect-view" style="display:none">
<div class="css-test-rect" id="css-test-rect"> <div class="css-test-rect-outer">
<div class="css-test-rect-corner"></div> <canvas id="css-test-rect-ticks" class="css-test-rect-ticks"></canvas>
<div class="css-test-edge-wrap"><canvas id="css-test-edge-top" class="css-test-edge"></canvas></div> <div class="css-test-rect" id="css-test-rect">
<div class="css-test-rect-corner"></div> <div class="css-test-rect-corner"></div>
<div class="css-test-edge-wrap"><canvas id="css-test-edge-top" class="css-test-edge"></canvas></div>
<div class="css-test-rect-corner"></div>
<div class="css-test-edge-wrap"><canvas id="css-test-edge-left" class="css-test-edge"></canvas></div> <div class="css-test-edge-wrap"><canvas id="css-test-edge-left" class="css-test-edge"></canvas></div>
<div class="css-test-rect-screen"></div> <div id="css-test-rect-screen" class="css-test-rect-screen">
<div class="css-test-edge-wrap"><canvas id="css-test-edge-right" class="css-test-edge"></canvas></div> <span id="css-test-rect-name" class="css-test-rect-label"></span>
<span id="css-test-rect-leds" class="css-test-rect-label css-test-rect-leds"></span>
</div>
<div class="css-test-edge-wrap"><canvas id="css-test-edge-right" class="css-test-edge"></canvas></div>
<div class="css-test-rect-corner"></div> <div class="css-test-rect-corner"></div>
<div class="css-test-edge-wrap"><canvas id="css-test-edge-bottom" class="css-test-edge"></canvas></div> <div class="css-test-edge-wrap"><canvas id="css-test-edge-bottom" class="css-test-edge"></canvas></div>
<div class="css-test-rect-corner"></div> <div class="css-test-rect-corner"></div>
</div>
</div> </div>
</div> </div>
@@ -36,10 +42,6 @@
<div id="css-test-layers" class="css-test-layers"></div> <div id="css-test-layers" class="css-test-layers"></div>
</div> </div>
<div class="css-test-info">
<span id="css-test-led-count" class="css-test-stat"></span>
</div>
<!-- LED count control --> <!-- LED count control -->
<div class="css-test-led-control" id="css-test-led-control"> <div class="css-test-led-control" id="css-test-led-control">
<label for="css-test-led-input" data-i18n="color_strip.test.led_count">LEDs:</label> <label for="css-test-led-input" data-i18n="color_strip.test.led_count">LEDs:</label>