diff --git a/README.es.md b/README.es.md index 62133a5..2b8cb32 100644 --- a/README.es.md +++ b/README.es.md @@ -28,7 +28,7 @@ Alertas, chat y widgets de directo para tu **programa de emisión (Meld u OBS)** antena se queda entera en tu PC y le da a tu directo una capa completa de alertas e interacción: - **Alertas** de Twitch (seguidores, subs, resubs, subs regaladas, bits y Power-ups, raids, recompensas) y YouTube (suscriptores nuevos, Super Chats, Super Stickers, miembros, hitos y membresías regaladas), más una bienvenida editable al primer mensaje y alertas de racha (oficial de Twitch; local de YouTube). Tabla evento → alerta: [docs/eventos.md](docs/eventos.md). -- **Tres diseños por alerta:** la tarjeta 3D EGDEV; tu vídeo o imagen (webm con transparencia) con el mensaje encima, colocado donde quieras; o **vídeo + tarjeta**: tu vídeo o imagen de fondo a pantalla completa y encima la tarjeta 3D, con retraso de entrada y ajuste de posición. Todos con CSS propio. +- **Tres diseños por alerta:** la tarjeta 3D EGDEV; tu vídeo o imagen (webm con transparencia) con el mensaje encima, colocado donde quieras; o **vídeo + tarjeta**: tu vídeo o imagen de fondo a pantalla completa y encima la tarjeta 3D, con retraso de entrada y posiciones independientes para fondo y tarjeta. En **Diseño › Posición del fondo**, X/Y desplazan la imagen o el vídeo en píxeles (X −1920…1920, Y −1080…1080); 0/0 mantiene el fondo centrado y los valores positivos mueven a la derecha/abajo. La tarjeta no se mueve. Todos con CSS propio. - **Variaciones:** otra versión de la alerta según la cantidad, el tier, el usuario, el mensaje o una probabilidad. - **Voz (TTS)** de los mensajes, **filtro** de palabras, enlaces y usuarios, y **pausa** con cola. - **Acciones en el programa de emisión** al salir una alerta: cambiar de escena (y volver), mostrar u ocultar capas, efectos, escribir en el chat, hablar… diff --git a/README.md b/README.md index 38de229..9e96584 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Stream alerts, chat and widgets for your **broadcast program (Meld or OBS)** — antena runs entirely on your PC and gives your stream a full alert and interaction layer: - **Alerts** from Twitch (followers, subs, resubs, gifted subs, bits and Power-ups, raids, rewards) and YouTube (new subscribers, Super Chats, Super Stickers, members, milestones and gifted memberships), plus an editable first-message welcome and watch-streak alerts (official Twitch; local YouTube). Event → alert table: [docs/eventos.md](docs/eventos.md). -- **Three designs per alert:** the EGDEV 3D card; your own video or image (webm with transparency) with the message on top, placed wherever you want; or **video + card**: your video or image as a full-screen background with the 3D card on top, with an entry delay and position offset. All with your own CSS. +- **Three designs per alert:** the EGDEV 3D card; your own video or image (webm with transparency) with the message on top, placed wherever you want; or **video + card**: your video or image as a full-screen background with the 3D card on top, with an entry delay and independent background/card position offsets. In **Design › Background position**, X/Y move either image or video in pixels (X −1920…1920, Y −1080…1080); 0/0 keeps the background centered, positive values move right/down. Card position is unchanged. All with your own CSS. - **Variations:** another version of the alert depending on the amount, the tier, the user, the message or a probability. - **Voice (TTS)** for messages, **filtering** of words, links and users, and **pause** with queue. - **Actions in the broadcast program** when an alert fires: change scene (and switch back), show or hide layers, effects, write in chat, speak… diff --git a/app/src/lib/types.ts b/app/src/lib/types.ts index d8aa147..d32f2a7 100644 --- a/app/src/lib/types.ts +++ b/app/src/lib/types.ts @@ -73,6 +73,7 @@ export interface AlertConfig { enabled?: boolean; layout?: 'card' | 'media' | 'mixed'; cardX?: number; cardY?: number; + bgX?: number; bgY?: number; media?: string; sound?: string; soundVolume?: number; diff --git a/app/src/panel/views/Editor.tsx b/app/src/panel/views/Editor.tsx index e6cc9ee..a8dde60 100644 --- a/app/src/panel/views/Editor.tsx +++ b/app/src/panel/views/Editor.tsx @@ -133,7 +133,7 @@ const FIELD_TAB: Record = { actions: 'actions', css: 'css', name: 'head', enabled: 'head', }; export const fieldTab = (f: string) => FIELD_TAB[f] || 'design'; -const FIELD_LABEL: Record = { media: 'vídeo o imagen', layout: 'diseño', sound: 'sonido', soundVolume: 'volumen', title: 'antetítulo', text: 'texto', sub: 'línea de apoyo', actions: 'acciones', css: 'CSS', ttsEnabled: 'voz', ttsTemplate: 'voz', durationMs: 'duración', accentColor: 'color', textColor: 'color', cardX: 'posición', cardY: 'posición', textDelayMs: 'retraso' }; +const FIELD_LABEL: Record = { media: 'vídeo o imagen', layout: 'diseño', sound: 'sonido', soundVolume: 'volumen', title: 'antetítulo', text: 'texto', sub: 'línea de apoyo', actions: 'acciones', css: 'CSS', ttsEnabled: 'voz', ttsTemplate: 'voz', durationMs: 'duración', accentColor: 'color', textColor: 'color', cardX: 'posición', cardY: 'posición', bgX: 'posición del fondo', bgY: 'posición del fondo', textDelayMs: 'retraso' }; function replaceTarget(s: any, t: Target, value: any) { const cfg = { ...s.config }; const mapList = (list: any[], id: string) => list.map(x => (x.id === id ? value : x)); @@ -478,9 +478,13 @@ export function Editor({ target }: { target: Target }) { {when.mixed && R('textDelayMs', 'Retraso de la tarjeta', 0, 6, 0.1, 's', true)} {when.card &&

La tarjeta 3D de la marca: icono, antetítulo, nombre y línea de apoyo. Cambia su aspecto en la pestaña CSS.

} + {when.mixed && box('Posición del fondo', <> +
{R('bgX', 'Horizontal (X)', -1920, 1920, 10, 'px')}{R('bgY', 'Vertical (Y)', -1080, 1080, 10, 'px')}
+

Mueve solo el vídeo o la imagen, sin desplazar la tarjeta. 0/0 = fondo centrado; valores positivos hacia la derecha y abajo, negativos hacia la izquierda y arriba.

+ )} {when.mixed && box('Posición de la tarjeta', <>
{R('cardX', 'Ajuste horizontal', -900, 900, 10, 'px')}{R('cardY', 'Ajuste vertical', -500, 500, 10, 'px')}
-

Parte de la posición del tema (Apariencia › Forma y posición) y la mueve sobre el fondo. 0/0 = donde sale la tarjeta normal. El fondo ocupa toda la capa de 1920×1080: un webm con transparencia deja ver la escena.

+

Parte de la posición del tema (Apariencia › Forma y posición) y la mueve sobre el fondo. 0/0 = donde sale la tarjeta normal. El tamaño y la posición del fondo se ajustan por separado; un webm con transparencia deja ver la escena.

)} {when.media && box('Posición y estilo del texto', <>
{R('textX', 'X', 0, 100, 1, '%')}{R('textY', 'Y', 0, 100, 1, '%')}{R('textWidth', 'Ancho', 20, 140, 1, '%')}
diff --git a/docs/estado.md b/docs/estado.md index 5a74f66..626e6af 100644 --- a/docs/estado.md +++ b/docs/estado.md @@ -27,7 +27,7 @@ sigue sin dependencias (Node ≥ 24); React, esbuild y Tauri son solo de compila - **Mensajes en pantalla:** `/widget/rotator` (1200×120) rota una lista ordenada de mensajes propios, distinta de los mensajes programados del chat: `widgets.rotator` con `label`, `messages` ([{ id, text }], máx. 50), `intervalSec` (5–3600, de un inicio al siguiente), `durationSec` (visible, recortado al intervalo) y `order` (`sequential` o `random`: cada ronda muestra todos una vez y nunca repite el mismo dos veces seguidas). Lógica pura en `public/widgets/rotator-core.js`; la vista previa rota cada 5 s. Se puede incrustar como hueco `rotator` en overlays propios. - **Alertas de Twitch y YouTube:** tipos normalizados (follow, sub, resub, giftsub, cheer, raid, redemption; ytsub, superchat, supersticker, member, milestone, giftmember, jewels) con - tres diseños (tarjeta, vídeo con texto y vídeo de fondo + tarjeta), variaciones, voz y acciones en el programa de emisión. + tres diseños (tarjeta, vídeo con texto y vídeo de fondo + tarjeta), variaciones, voz y acciones en el programa de emisión. En el diseño mixto, el fondo de imagen o vídeo tiene posición X/Y independiente de la tarjeta (0/0 centrado). Los regalos Jewels se agrupan por combo; cuentan como eventos, no como euros de Super Chat. - **Suscriptores de YouTube (#134):** alerta `ytsub` para suscripciones públicas detectadas durante la escucha, con intervalo configurable y parada por cuota. - **Bienvenida (#289):** alerta pequeña y editable en el primer mensaje por persona y plataforma, con variación para quien ya habló en directos archivados. Activada de serie, sin mensajes propios ni usuarios bloqueados; el máximo de cinco alertas pendientes evita inundar la cola. diff --git a/public/overlay.html b/public/overlay.html index ac6cedc..7e6a2ff 100644 --- a/public/overlay.html +++ b/public/overlay.html @@ -123,7 +123,7 @@ /* animaciones de entrada y salida del diseño 2 */ /* diseño 3: mixta (vídeo o imagen de fondo + tarjeta EGDEV encima) */ -.alert-bg{position:fixed;inset:0;display:grid;place-items:center;pointer-events:none;opacity:0;transition:opacity .35s ease-out} +.alert-bg{position:fixed;inset:0;display:grid;place-items:center;translate:var(--bg-x,0px) var(--bg-y,0px);pointer-events:none;opacity:0;transition:opacity .35s ease-out} .alert-bg.on{opacity:1} .alert-bg.out{opacity:0;transition-duration:.45s} .alert-bg .alert-media{width:calc(100vw * var(--bg-size,1));height:calc(100vh * var(--bg-size,1));object-fit:contain} @@ -424,6 +424,8 @@ const bg = document.createElement('div'); bg.className = 'alert-bg type-' + a.type; bg.style.setProperty('--bg-size', Math.max(0.05, L.mediaSize / 100)); + bg.style.setProperty('--bg-x', (L.bgX ?? 0) + 'px'); + bg.style.setProperty('--bg-y', (L.bgY ?? 0) + 'px'); const src = '/media/' + encodeURIComponent(L.media); let el; if (L.mediaKind === 'video') { diff --git a/src/alerts.mjs b/src/alerts.mjs index 632c5ad..b7e7e61 100644 --- a/src/alerts.mjs +++ b/src/alerts.mjs @@ -63,6 +63,7 @@ export const LOOK_DEFAULTS = { animIn: 'pop', // pop | fade | slide | zoom | none animOut: 'fade', // fade | slide | zoom | none cardX: 0, cardY: 0, // mixta: ajuste de la tarjeta sobre el fondo (px, desde la posición del tema) + bgX: 0, bgY: 0, // mixta: ajuste independiente del fondo desde el centro del lienzo (px) css: '', }; @@ -80,7 +81,7 @@ export const ALERT_FIELDS = { layout: ['card', 'media', 'mixed'], media: 'string', mediaSize: 'number', mediaVolume: 'number', sound: 'string', soundVolume: 'number', durationMode: ['fixed', 'media'], textDelayMs: 'number', textX: 'number', textY: 'number', textWidth: 'number', textAlign: ['left', 'center', 'right'], fontSize: 'number', - textColor: 'string', accentColor: 'string', cardX: 'number', cardY: 'number', animIn: ['pop', 'fade', 'slide', 'zoom', 'none'], animOut: ['fade', 'slide', 'zoom', 'none'], + textColor: 'string', accentColor: 'string', cardX: 'number', cardY: 'number', bgX: 'number', bgY: 'number', animIn: ['pop', 'fade', 'slide', 'zoom', 'none'], animOut: ['fade', 'slide', 'zoom', 'none'], css: 'string', ttsEnabled: 'boolean', ttsTemplate: 'string', ttsMinAmount: 'number', actions: 'array', }; @@ -287,7 +288,7 @@ function pickLook(cfg) { // sin archivo, «vídeo» y «mixta» caen a la tarjeta out.layout = ['media', 'mixed'].includes(out.layout) && out.media ? out.layout : 'card'; out.mediaKind = out.media ? mediaKind(out.media) : null; - for (const k of ['mediaSize', 'mediaVolume', 'soundVolume', 'textDelayMs', 'textX', 'textY', 'textWidth', 'fontSize', 'cardX', 'cardY']) out[k] = Number(out[k]) || 0; + for (const k of ['mediaSize', 'mediaVolume', 'soundVolume', 'textDelayMs', 'textX', 'textY', 'textWidth', 'fontSize', 'cardX', 'cardY', 'bgX', 'bgY']) out[k] = Number(out[k]) || 0; return out; } diff --git a/src/config-schema.mjs b/src/config-schema.mjs index 4303583..8603e5d 100644 --- a/src/config-schema.mjs +++ b/src/config-schema.mjs @@ -118,6 +118,7 @@ const condiciones = { const hojasAlerta = { enabled: bool, title: str, text: str, sub: str, durationMs: num({ min: 0 }), minAmount: num({ min: 0 }), + bgX: num({ min: -1920, max: 1920, def: 0 }), bgY: num({ min: -1080, max: 1080, def: 0 }), layout: en(['card', 'media', 'mixed']), cardX: num({ min: -1920, max: 1920 }), cardY: num({ min: -1080, max: 1080 }), media: str, mediaSize: num({ min: 0 }), mediaVolume: num({ min: 0, max: 100 }), sound: str, soundVolume: num({ min: 0, max: 100 }), durationMode: en(['fixed', 'media']), textDelayMs: num({ min: 0 }), textX: num({ min: 0, max: 100 }), textY: num({ min: 0, max: 100 }), textWidth: num({ min: 0 }), // textX/Y: porcentajes reales diff --git a/src/mcp.mjs b/src/mcp.mjs index 8e5f297..379168d 100644 --- a/src/mcp.mjs +++ b/src/mcp.mjs @@ -74,7 +74,7 @@ const TYPES = ['follow', 'sub', 'resub', 'giftsub', 'cheer', 'raid', 'redemption const tipo = S.enum('Tipo de alerta. Twitch: follow, sub, resub, giftsub, cheer (bits), raid, redemption (recompensas). YouTube: superchat, supersticker, member, milestone, giftmember, jewels (regalo de YouTube). Récord de espectadores a la vez: viewers (Twitch) y ytviewers (YouTube), variables {amount} y {previous}. Bienvenida: welcome, variables {user}, {returning} y {platform}. Racha: streak, variables {user}, {platform}, {count}; en Twitch también {message} y {channelPointsAwarded}.', TYPES); const ALERT_HELP = `Campos de una alerta (todos opcionales): - enabled (bool), title/text/sub (plantillas con {user} {amount} {message} {months} {tier} {reward} {input} {amountText} {level} {platform} {count} {channelPointsAwarded}; en Jewels también {giftName}), durationMs, minAmount -- layout: "card" (tarjeta EGDEV) | "media" (vídeo o imagen con el texto encima) | "mixed" (vídeo o imagen de fondo a pantalla completa y encima la tarjeta EGDEV; textDelayMs = retraso de la tarjeta, cardX/cardY = ajuste en px); media (archivo de media/), mediaSize %, mediaVolume % +- layout: "card" (tarjeta EGDEV) | "media" (vídeo o imagen con el texto encima) | "mixed" (vídeo o imagen de fondo a pantalla completa y encima la tarjeta EGDEV; textDelayMs = retraso de la tarjeta, cardX/cardY = ajuste de la tarjeta en px, bgX/bgY = ajuste independiente del fondo desde el centro en px, 0/0 centrado, X entre -1920 y 1920, Y entre -1080 y 1080); media (archivo de media/), mediaSize %, mediaVolume % - sound ("default" | "none" | archivo de audio), soundVolume %, durationMode ("fixed" | "media" = lo que dure el vídeo), textDelayMs - textX/textY/textWidth (% dentro del recurso), textAlign (left|center|right), fontSize px, textColor, accentColor, animIn (pop|fade|slide|zoom|none), animOut (fade|slide|zoom|none) - css: CSS propio de la alerta. Gana siempre a los estilos de serie (no hace falta !important). Clases: .alert (raíz, con .type-, .alert-card o .alert-media-layout; .on mientras se ve, .out al salir), .alert-box, .alert-text, .alert-title, .alert-name, .alert-sub (y .alert-sub b), tarjeta: .card, .alert-icon, .alert-platform, .alert-timer, .alert-glow, .alert-dots, .alert-cube; vídeo: .alert-media; mixta: .alert-bg (fondo, con .alert-media dentro) y la tarjeta como .alert-card.alert-mixed. Variables de la tarjeta en .alert { }: --accent, --title-color, --name-color, --sub-color, --hl-color, --card-width, --card-radius, --card-padding, --card-bg, --border-width, --border-color, --tile-size, --icon-size, --icon-color, --title-size, --name-size, --sub-size, --font-title, --font-name, --font-sub, --tilt, --reflection. Ej.: ".alert { --accent: #00E0FF; --tilt: none; }" diff --git a/test/alert-background-position-browser.test.mjs b/test/alert-background-position-browser.test.mjs new file mode 100644 index 0000000..447a396 --- /dev/null +++ b/test/alert-background-position-browser.test.mjs @@ -0,0 +1,97 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createApp } from '../src/server.mjs'; +import { closeChrome, openChromePage, skipIfNoBrowserOrUi, waitDom } from './helpers/react-browser.mjs'; +import { evaluateChrome } from './helpers/chrome-dom.mjs'; + +const q = JSON.stringify; +const input = field => `document.querySelector('[data-field="${field}"] input')`; +const save = `[...document.querySelectorAll('.lv-sfoot button')].find(b=>b.textContent.trim()==='Guardar')`; +const designTab = `[...document.querySelectorAll('.lv-stabs [role="tab"]')].find(b=>b.textContent.trim().startsWith('Diseño'))`; +const closeTo = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1, `${actual} ≈ ${expected}`); + +test('image/video backgrounds move independently; panel saves and reloads both offsets', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); if (!bin) return; + const root = await mkdtemp(path.join(tmpdir(), 'antena-background-browser-')); + const app = await createApp({ dataDir: root, mediaDir: path.join(root, 'media'), log: () => {} }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${app.server.address().port}`; + const api = async (method, url, body) => { + const r = await fetch(base + url, { method, headers: { 'content-type': 'application/json' }, body: body && JSON.stringify(body) }); + assert.equal(r.status, 200, url); return r.json(); + }; + let chrome; + try { + await api('PUT', '/api/config', { panel: { onboardingDone: true } }); + await api('PUT', '/api/theme', { animation: 'none', tilt: false, sound: 'none', decorations: false }); + chrome = await openChromePage(bin, base + '/overlay?still=follow'); + const c = chrome.cdp, ev = expr => evaluateChrome(c, expr); + await c.send('Emulation.setDeviceMetricsOverride', { width: 1920, height: 1080, deviceScaleFactor: 1, mobile: false }); + await waitDom(c, `location.href===${q(base + '/overlay?still=follow')} && document.readyState==='complete'`); + async function navigate(url, ready, reload = false) { + // CDP can acknowledge navigation while selectors still match the old document. + await ev(`document.__backgroundPreviousDocument = true`); + await c.send(reload ? 'Page.reload' : 'Page.navigate', reload ? {} : { url }); + await waitDom(c, `location.href===${q(url)} && !document.__backgroundPreviousDocument && (${ready})`); + } + // Real decodable image and VP8 video, uploaded only to this isolated test app. + const uploads = await ev(`(async()=>{ + const canvas=document.createElement('canvas');canvas.width=160;canvas.height=90; + const ctx=canvas.getContext('2d');ctx.fillStyle='red';ctx.fillRect(0,0,160,90); + const png=await new Promise(r=>canvas.toBlob(r,'image/png')); + const a=await fetch('/api/media/upload?name=background.png',{method:'POST',body:png}); + const stream=canvas.captureStream(15),chunks=[],rec=new MediaRecorder(stream,{mimeType:'video/webm;codecs=vp8'}); + const done=new Promise((resolve,reject)=>{rec.ondataavailable=e=>{if(e.data.size)chunks.push(e.data)};rec.onerror=reject;rec.onstop=()=>resolve(new Blob(chunks,{type:'video/webm'}))}); + rec.start();await new Promise(r=>{let n=0;const timer=setInterval(()=>{ctx.fillStyle=n%2?'red':'blue';ctx.fillRect(0,0,160,90);if(++n===8){clearInterval(timer);rec.stop();r()}},75)}); + const clip=await done;stream.getTracks().forEach(t=>t.stop()); + const b=await fetch('/api/media/upload?name=background.webm',{method:'POST',body:clip});return [a.status,b.status]; + })()`); + assert.deepEqual(uploads, [200, 200]); + let revision = 0; + async function render(patch) { + await api('PUT', '/api/alerts/follow', patch); + await navigate(base + '/overlay?still=follow&case=' + ++revision, + `!!document.querySelector('#stage .alert-mixed.on') && (()=>{const m=document.querySelector('#bg .alert-media');return m && (m.naturalWidth>0 || m.videoWidth>0)})()`); + await ev(`document.fonts.ready.then(()=>true)`); + return ev(`(()=>{const rect=s=>{const r=document.querySelector(s).getBoundingClientRect();return {x:r.x,y:r.y,w:r.width,h:r.height}};return {bg:rect('#bg .alert-media'),card:rect('#stage .card')}})()`); + } + for (const media of ['background.png', 'background.webm']) { + const initial = await render({ layout: 'mixed', media, mediaSize: 50, bgX: 0, bgY: 0, cardX: 0, cardY: 0, textDelayMs: 0 }); + closeTo(initial.bg.x, 480); closeTo(initial.bg.y, 270); + const moved = await render({ bgX: 120, bgY: -70 }); + closeTo(moved.bg.x - initial.bg.x, 120); closeTo(moved.bg.y - initial.bg.y, -70); + closeTo(moved.card.x, initial.card.x); closeTo(moved.card.y, initial.card.y); + const cardMoved = await render({ cardX: -40, cardY: 30 }); + assert.deepEqual(cardMoved.bg, moved.bg); + closeTo(cardMoved.card.x - moved.card.x, -40); closeTo(cardMoved.card.y - moved.card.y, 30); + // Actual editor controls, not a direct API substitute for saving the UI. + await navigate(base + '/#/alertas/follow', `!!(${designTab})`); + await ev(`(${designTab}).click()`); + await waitDom(c, `!!${input('bgX')} && !!${input('bgY')}`); + for (const [field, value] of [['bgX', -160], ['bgY', 90]]) { + await ev(`(()=>{const i=${input(field)};Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(i,${value});i.dispatchEvent(new Event('input',{bubbles:true}));i.dispatchEvent(new Event('change',{bubbles:true}));return true})()`); + await waitDom(c, `${input(field)}?.value===${q(String(value))}`); + } + await ev(`(${save}).click()`); + await waitDom(c, `document.querySelector('.lv-sfoot .lv-dirty')?.textContent.trim()==='Todo guardado'`); + const look = (await api('GET', '/api/alerts/follow/sample')).alert.look; + assert.deepEqual([look.bgX, look.bgY, look.cardX, look.cardY], [-160, 90, -40, 30]); + await navigate(base + '/#/alertas/follow', `!!(${designTab})`, true); + await ev(`(${designTab}).click()`); + await waitDom(c, `${input('bgX')}?.value==='-160' && ${input('bgY')}?.value==='90'`); + } + // Other layouts do not gain or move a separate background layer. + for (const layout of ['card', 'media']) { + await api('PUT', '/api/alerts/follow', { layout }); + await navigate(base + '/overlay?still=follow&case=' + ++revision, `!!document.querySelector('#stage .alert.on')`); + assert.equal(await ev(`!!document.querySelector('#bg .alert-media')`), false); + } + } finally { + if (chrome) await closeChrome(chrome); + app.timers.stop(); app.viewers.stop(); app.meld.stop(); await app.closeHttp(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/test/alert-background-position.test.mjs b/test/alert-background-position.test.mjs new file mode 100644 index 0000000..154874c --- /dev/null +++ b/test/alert-background-position.test.mjs @@ -0,0 +1,55 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createApp } from '../src/server.mjs'; +import { buildCommandAlert, buildCustomAlert } from '../src/alerts.mjs'; + +const xy = look => [look.bgX, look.bgY, look.cardX, look.cardY]; + +test('mixed background offsets round-trip independently through alert APIs', async t => { + const root = await mkdtemp(path.join(tmpdir(), 'antena-background-api-')); + const app = await createApp({ dataDir: root, mediaDir: path.join(root, 'media'), log: () => {} }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + t.after(async () => { app.timers.stop(); app.viewers.stop(); app.meld.stop(); await app.closeHttp(); await rm(root, { recursive: true, force: true }); }); + const base = `http://127.0.0.1:${app.server.address().port}`; + const api = async (method, url, body, status = 200) => { + const r = await fetch(base + url, { method, headers: { 'content-type': 'application/json' }, body: body && JSON.stringify(body) }); + assert.equal(r.status, status, url); return r.json(); + }; + const sample = async () => (await api('GET', '/api/alerts/follow/sample')).alert.look; + assert.deepEqual(xy(await sample()), [0, 0, 0, 0], 'old configurations remain centered'); + const state = await api('GET', '/api/state'); + assert.equal(state.fields.bgX, 'number'); assert.equal(state.fields.bgY, 'number'); + for (const media of ['background.png', 'background.webm']) { + await api('PUT', '/api/alerts/follow', { layout: 'mixed', media, bgX: -120, bgY: 70, cardX: 40, cardY: -90 }); + assert.deepEqual(xy(await sample()), [-120, 70, 40, -90]); + assert.deepEqual(xy((await api('GET', '/api/alerts/follow')).config), [-120, 70, 40, -90]); + } + for (const [bgX, bgY] of [[-1920, -1080], [1920, 1080], [0, 0]]) { + await api('PUT', '/api/config', { alerts: { follow: { bgX, bgY } } }); + assert.deepEqual(xy(await sample()), [bgX, bgY, 40, -90]); + } + const before = await api('GET', '/api/alerts/follow'); + for (const [field, value, message] of [ + ['bgX', -1921, 'el valor mínimo es -1920'], ['bgX', 1921, 'el valor máximo es 1920'], + ['bgY', -1081, 'el valor mínimo es -1080'], ['bgY', 1081, 'el valor máximo es 1080'], + ]) { + const result = await api('PUT', '/api/config', { alerts: { follow: { [field]: value } } }, 400); + assert.equal(result.error, `alerts.follow.${field}: ${message}`); + assert.deepEqual(await api('GET', '/api/alerts/follow'), before, 'rejected input must not change stored settings'); + } + const { variation } = await api('POST', '/api/alerts/follow/variations', { name: 'Offset', overrides: { bgX: 80, bgY: -60 } }); + assert.deepEqual(variation.overrides, { bgX: 80, bgY: -60 }); + const reset = await api('PUT', `/api/alerts/follow/variations/${variation.id}`, { overrides: { bgX: null, bgY: null } }); + assert.deepEqual(reset.variation.overrides, {}, 'reset restores inheritance'); +}); + +test('shared command/custom appearance keeps card offsets and accepts independent background offsets', () => { + for (const build of [fields => buildCommandAlert({ id: 'fixture', ...fields }, { user: 'Ana' }, {}), fields => buildCustomAlert(fields, { user: 'Ana' }, {})]) { + assert.deepEqual(xy(build({ layout: 'mixed', media: 'bg.webm', cardX: 30, cardY: -20 }).look), [0, 0, 30, -20]); + assert.deepEqual(xy(build({ layout: 'mixed', media: 'bg.png', bgX: '120', bgY: -70, cardX: 30, cardY: -20 }).look), [120, -70, 30, -20]); + assert.equal(build({ layout: 'mixed', media: '' }).look.layout, 'card', 'missing media still falls back to card'); + } +}); diff --git a/test/groups.json b/test/groups.json index ca3509b..d2ee697 100644 --- a/test/groups.json +++ b/test/groups.json @@ -1,6 +1,7 @@ { "unit": [ "test/actions-shared.test.mjs", + "test/alert-background-position.test.mjs", "test/alerts.test.mjs", "test/bus-clock.test.mjs", "test/channel-totals.test.mjs", @@ -154,6 +155,7 @@ ], "browser": [ "test/acerca-browser.test.mjs", + "test/alert-background-position-browser.test.mjs", "test/alert-thumbs-browser.test.mjs", "test/apariencia-browser.test.mjs", "test/apariencia-save.test.mjs",