From 8c0ae86c0760aa0389c813a384400da685962e95 Mon Sep 17 00:00:00 2001 From: egdev6 <18334564+egdev6@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:39:02 +0100 Subject: [PATCH 1/2] test(widgets): wait for the panel save to finish before leaving the page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The router blocks navigation while a save is in flight (confirmLeave returns false during isSaving), and both save-bar buttons are disabled while saving, so waiting for them was racy under full-suite load. Wait for the save-bar status «Todo guardado» instead. --- test/latest-ticker-panel-browser.test.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/latest-ticker-panel-browser.test.mjs b/test/latest-ticker-panel-browser.test.mjs index 01fa394..3f1918b 100644 --- a/test/latest-ticker-panel-browser.test.mjs +++ b/test/latest-ticker-panel-browser.test.mjs @@ -39,7 +39,9 @@ test('the ticker is its own widget and «Últimos» shows its own label', { time await waitDom(c, `!!(${save})`, { timeoutMs: 5000 }); await ev(`${save}.click(); true`); await until(async () => JSON.stringify((await widgets()).ticker?.items) === JSON.stringify(['follow', 'sub', 'cheer']), 'the ticker types were not saved'); - await waitDom(c, `!(${save})`, { timeoutMs: 8000 }); // the panel has no pending changes before leaving the page + // The router blocks leaving while a save is in flight: wait until the panel itself finished saving. + // (both buttons are disabled while saving too, so wait for the save bar status itself) + await waitDom(c, `document.querySelector('.lv-dirty')?.textContent === 'Todo guardado'`, { timeoutMs: 8000 }); assert.deepEqual((await widgets()).latest.items, ['follow', 'sub'], '«Últimos» keeps its own types'); // «Últimos» page: its own label field. From bcd3c3825f6d81f0d9ab7ba68f2790dcdd03b295 Mon Sep 17 00:00:00 2001 From: egdev6 <18334564+egdev6@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:39:02 +0100 Subject: [PATCH 2/2] feat(widgets): add a social bar widget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New built-in widget «Redes sociales» (/widget/socials): an ordered list of up to 12 profiles shown as brand icon + nick, with an optional label and custom CSS. Platforms: Twitch, YouTube, X, Instagram, TikTok, GitHub, Discord, Kick, LinkedIn and Web. Icons come from Simple Icons 16.38.1 (CC0-1.0); Twitch and YouTube reuse platform-icons.js. Nicks are rendered as text through the DOM. The widget is listed as a browser source, usable as a custom overlay slot and editable through MCP. --- README.es.md | 7 +- README.md | 14 +++- app/src/lib/types.ts | 4 ++ app/src/panel/Sidebar.tsx | 2 +- app/src/panel/views/Widgets.tsx | 35 +++++++++- docs/estado.md | 1 + public/custom/sdk.js | 2 +- public/social-icons.js | 51 +++++++++++++++ public/widgets/socials.html | 53 +++++++++++++++ src/config-schema.mjs | 7 ++ src/custom-overlays.mjs | 2 +- src/mcp.mjs | 8 +-- src/routes/shortcuts.mjs | 1 + src/routes/widgets.mjs | 4 ++ src/server.mjs | 2 +- src/store.mjs | 1 + test/chat-variants.test.mjs | 2 +- test/core.test.mjs | 2 +- test/groups.json | 2 + test/interview-dock-catalog-browser.test.mjs | 8 +-- test/routes-shortcuts.test.mjs | 2 +- test/sidebar-widgets-browser.test.mjs | 4 +- test/socials-widget-browser.test.mjs | 68 ++++++++++++++++++++ test/socials-widget.test.mjs | 68 ++++++++++++++++++++ test/theme.test.mjs | 2 +- 25 files changed, 328 insertions(+), 24 deletions(-) create mode 100644 public/social-icons.js create mode 100644 public/widgets/socials.html create mode 100644 test/socials-widget-browser.test.mjs create mode 100644 test/socials-widget.test.mjs diff --git a/README.es.md b/README.es.md index cecabd4..222cc3f 100644 --- a/README.es.md +++ b/README.es.md @@ -35,7 +35,7 @@ antena se queda entera en tu PC y le da a tu directo una capa completa de alerta - **Comandos de chat** (`!engram`, `!web`…) que lanzan sus propias alertas, con permisos y esperas. - **Mensajes programados:** textos que se publican solos en el chat cada X minutos (también como anuncio destacado) y, si quieres, salen además como alerta en pantalla. - **Interactivos:** cola de preguntas del chat, tier list que vota el chat y sorteos con ruleta en pantalla. -- **Widgets:** chat en pantalla (Twitch + YouTube), objetivos, últimos apoyos, ticker, espectadores en directo, agradecimientos a seguidores sin conexión y créditos finales. +- **Widgets:** chat en pantalla (Twitch + YouTube), objetivos, últimos apoyos, ticker, espectadores en directo, agradecimientos a seguidores sin conexión, barra de redes sociales y créditos finales. - **Overlays propios:** capas de HTML, CSS y JavaScript para una escena o para enmarcar la cámara, escritas por ti o por Claude por MCP, con datos en vivo y acciones que apruebas tú. - **Resumen del directo:** totales, a quién dar las gracias y la cronología con el minuto de cada evento, en Markdown. - **Seguidores sin conexión:** registra los seguidores de Twitch ganados mientras antena estaba cerrada y, en YouTube, las suscripciones públicas y un recuento anónimo; YouTube requiere conectar la cuenta. @@ -167,9 +167,12 @@ En el panel, la página «Fuentes del programa de emisión» lista todas con su | Espectadores | `http://127.0.0.1:4500/widget/viewers` | 900×160 | | Agradecimientos | `http://127.0.0.1:4500/widget/thanks` | 900×200 | | Entrevista | `http://127.0.0.1:4500/widget/interview` | 1920×1080 | +| Redes sociales | `http://127.0.0.1:4500/widget/socials` | 1600×80 | **Últimos y ticker.** Son dos widgets separados en **Widgets**. «Últimos» muestra el último apoyo de cada tipo marcado (seguidor, sub, bits, raid, Super Chat, miembro o cualquier evento), con una etiqueta opcional (`widgets.latest.label`; vacía no se muestra, clase `.label`). El ticker, en cambio, recorre los eventos más recientes de sus tipos, así que pueden salir varias subs seguidas. Usa los tipos de «Últimos» hasta que eliges los suyos (`widgets.ticker.items`, mismos valores). +**Redes sociales.** En **Widgets › Redes sociales** (`/widget/socials`, 1600×80) añades, editas, quitas y ordenas hasta 12 redes (Twitch, YouTube, X, Instagram, TikTok, GitHub, Discord, Kick, LinkedIn y Web); cada una sale con el icono de su plataforma y tu nick, como texto. Las redes sin nick no se muestran y, sin redes, la capa queda vacía. Etiqueta opcional (por ejemplo «Sígueme») y CSS propio con las clases `.root`, `.label`, `.item`, `.item-`, `.ico` y `.handle`. Los iconos de marca vienen de Simple Icons (CC0); X, TikTok y GitHub van en blanco para verse sobre fondo oscuro. Los perfiles viven en `widgets.socials` y, como el resto de ajustes de widgets, viajan con los temas guardados. Se puede incrustar como hueco `socials` en overlays propios; por MCP, `editar_widget` con `widget: "socials"` (la lista se sustituye entera). + **Entrevista.** Capa a pantalla completa para el ítem activo y aprobado de la entrevista activa (ver `docs/entrevista-formato.md`): la pregunta en una tarjeta inferior sobre su imagen, vídeo local, reproductor de YouTube (desde el minuto guardado) o tarjeta de post, con la fuente en cada ítem que lleve media. Sin ítem activo la capa queda vacía. En **Widgets › Se manejan en directo › Entrevista** creas o importas entrevistas, editas y ordenas rondas y preguntas y pulsas **Guardar** para aplicar el borrador. La cabecera del detalle elige o para la entrevista activa y controla la capa; el dock también permite pararla sin borrarla. `POST /api/interviews/stop` hace lo mismo y se puede repetir sin riesgo. En **Capa** están la URL y la vista previa de ejemplo. Las notas privadas nunca salen en la capa. Pruébala con `?demo`. **Agradecimientos sin conexión.** Esta capa muestra un seguidor pendiente cada vez y puede terminar con el recuento anónimo de YouTube. En Widgets › Agradecimientos eliges plataformas, todo el tiempo / desde el último directo archivado / un número de días, máximo de nombres e intervalo. Las fechas desconocidas se incluyen; si no hay directos archivados, la ventana desde el último no tiene corte. Sin pendientes la capa queda transparente. Las acciones individuales y en bloque con confirmación se aplican al momento; el bloque marca solo los nombres y registros anónimos seleccionados con los ajustes guardados, no los demás pendientes. @@ -326,7 +329,7 @@ antena.slots.clear('chat'); // clear() borra todos sin animación Solo cambian los huecos nombrados; los demás conservan su estado. Nombres `a-z0-9_-` (hasta 32 caracteres). Cada hueco admite `widget`, `params` opcional, `rect` (píxeles del lienzo `[x,y,w,h]` o `null`), `enter`/`exit` (`none`, `fade`, `left`, `right`, `up`, `down`; por defecto `fade`), `layer` (`above` por defecto o `below`), `fit` (`slot` por defecto o `canvas`) y `css` adicional tras el CSS propio del widget. `slot` hace que `.root` llene el rectángulo; `canvas` llena el lienzo y conserva posición y animaciones propias. Cambiar widget o parámetros recarga su página. No devuelven nada; los datos inválidos se ignoran y se avisan una vez en la consola del overlay. Por seguridad, el CSS del hueco rechaza tokens de carga de recursos (`url`, `image-set`, `image(`, `src(`, `@import`, `@namespace`, `@font-face`), escapes y comentarios: se ejecuta en una página de confianza y no debe hacer peticiones en nombre del marco aislado. -Permitidos: `chat` (`variant`), `viewers` (`layout: 'column'`), `goal` (`id`), `latest` (`items`, `layout: 'column'`), `ticker`, `thanks`, `giveaway`, `question` (`nocount`), `tierlist` (`id`, `nopool`), `interview` (`item`), `credits` (`loop`, `transparent`), `alerts` y `custom` (`id` de otro overlay). Sin URLs arbitrarias, autoinclusión ni overlays propios dentro de otro incrustado. Máximo 12 huecos; rects finitos, ancho/alto 1–4320 y x/y dentro de ±2 dimensiones del lienzo. Las actualizaciones se agrupan por frame y limitan a 20/s. La shell incrusta estas páginas públicas sin permisos de acción y mantiene aislado el marco del usuario. +Permitidos: `chat` (`variant`), `viewers` (`layout: 'column'`), `goal` (`id`), `latest` (`items`, `layout: 'column'`), `ticker`, `thanks`, `giveaway`, `question` (`nocount`), `tierlist` (`id`, `nopool`), `interview` (`item`), `credits` (`loop`, `transparent`), `socials`, `alerts` y `custom` (`id` de otro overlay). Sin URLs arbitrarias, autoinclusión ni overlays propios dentro de otro incrustado. Máximo 12 huecos; rects finitos, ancho/alto 1–4320 y x/y dentro de ±2 dimensiones del lienzo. Las actualizaciones se agrupan por frame y limitan a 20/s. La shell incrusta estas páginas públicas sin permisos de acción y mantiene aislado el marco del usuario. Las alertas y entrevistas incrustadas silencian audio cuando Page Visibility indica que el overlay está oculto; el vídeo YouTube de entrevista se reinicia al volver a verse. **No se ha comprobado la visibilidad fuera de escena en Meld**: usa una sola fuente de navegador y capas Duplicator en las demás escenas para evitar audio duplicado aunque Meld no marque ocultas las fuentes. diff --git a/README.md b/README.md index e19f8d8..030c0df 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ antena runs entirely on your PC and gives your stream a full alert and interacti - **Chat commands** (`!engram`, `!web`…) that trigger their own alerts, with permissions and cooldowns. - **Scheduled messages:** texts that post themselves to chat every X minutes (also as a highlighted announcement) and, if you want, also appear on screen as an alert. - **Interactives:** chat question queue, a tier list the chat votes on, and giveaways with an on-screen roulette. -- **Widgets:** on-screen chat (Twitch + YouTube), goals, latest supporters, ticker, live concurrent viewers, offline follower thank-yous, rotating on-screen messages and end credits. +- **Widgets:** on-screen chat (Twitch + YouTube), goals, latest supporters, ticker, live concurrent viewers, offline follower thank-yous, rotating on-screen messages, a social bar and end credits. - **Custom overlays:** HTML, CSS and JavaScript layers for a scene or to frame the camera, written by you or by Claude via MCP, with live data and actions you approve. - **Stream recap:** totals, who to thank and a timeline with the minute of each event, in Markdown. - **Offline followers:** records Twitch followers gained while antena was closed, and YouTube's public subscribers plus an anonymous count; YouTube requires a connected account. @@ -168,6 +168,7 @@ In the panel, the «Fuentes del programa de emisión» page lists all of them wi | Thank-yous | `http://127.0.0.1:4500/widget/thanks` | 900×200 | | Interview | `http://127.0.0.1:4500/widget/interview` | 1920×1080 | | On-screen messages | `http://127.0.0.1:4500/widget/rotator` | 1200×120 | +| Social bar | `http://127.0.0.1:4500/widget/socials` | 1600×80 | **Latest and ticker.** They are separate widgets in **Widgets**. «Latest» shows the last supporter of each selected type (follower, sub, bits, raid, Super Chat, member or any event), with an optional label (`widgets.latest.label`; empty shows none, class `.label`). The ticker scrolls the most recent events of its types instead, so several subs can appear at once. It uses the «Latest» types until you pick its own (`widgets.ticker.items`, same values). @@ -329,7 +330,7 @@ antena.slots.clear('chat'); // clear() removes all without animation Only named slots change; unmentioned slots keep their state. Names use `a-z0-9_-` (up to 32 characters). Each slot has `widget`, optional `params`, `rect` (canvas pixels `[x,y,w,h]` or `null`), `enter`/`exit` (`none`, `fade`, `left`, `right`, `up`, `down`; default `fade`), `layer` (`above` by default or `below`), `fit` (`slot` by default or `canvas`) and optional extra `css` applied after the widget's own CSS. `slot` makes `.root` fill the rectangle; `canvas` fills the canvas and preserves the page's own positioning and animations. A changed widget or parameters reload its page. Calls return nothing; invalid input is ignored and reported once in the overlay console. For safety, slot CSS rejects resource-loading tokens (`url`, `image-set`, `image(`, `src(`, `@import`, `@namespace`, `@font-face`), CSS escapes and comments: it runs on a trusted same-origin page and must not make requests on the sandbox's behalf. -Allowed: `chat` (`variant`), `viewers` (`layout: 'column'`), `goal` (`id`), `latest` (`items`, `layout: 'column'`), `ticker`, `thanks`, `giveaway`, `question` (`nocount`), `tierlist` (`id`, `nopool`), `interview` (`item`), `credits` (`loop`, `transparent`), `rotator`, `alerts` and `custom` (`id` of another overlay). No arbitrary URLs, self-embedding or custom overlays nested inside another embedded overlay. Maximum 12 slots; finite rects, width/height 1–4320 and x/y within ±2 canvas dimensions. Updates are coalesced per animation frame and limited to 20/s. The shell embeds these public pages, so no action permission is needed; it keeps the user frame sandboxed. +Allowed: `chat` (`variant`), `viewers` (`layout: 'column'`), `goal` (`id`), `latest` (`items`, `layout: 'column'`), `ticker`, `thanks`, `giveaway`, `question` (`nocount`), `tierlist` (`id`, `nopool`), `interview` (`item`), `credits` (`loop`, `transparent`), `rotator`, `socials`, `alerts` and `custom` (`id` of another overlay). No arbitrary URLs, self-embedding or custom overlays nested inside another embedded overlay. Maximum 12 slots; finite rects, width/height 1–4320 and x/y within ±2 canvas dimensions. Updates are coalesced per animation frame and limited to 20/s. The shell embeds these public pages, so no action permission is needed; it keeps the user frame sandboxed. Embedded alerts and interviews suppress audio while Page Visibility reports the overlay hidden; hidden YouTube interview media restarts when visible. **Meld's off-air visibility has not been verified**: use one browser source and Duplicator layers in other scenes to prevent duplicated audio even if Meld does not mark sources hidden. @@ -384,6 +385,15 @@ The pause button also stops scheduled messages, automatic ones and «Send now». The preview rotates every 5 s with your messages so you can check all of them. Custom overlays can embed it as the `rotator` slot. Via MCP: `editar_widget` with `widget: "rotator"`; the message list is replaced as a whole. +### Social bar + +**Widgets › Redes sociales** (`/widget/socials`, 1600×80) shows your social profiles in a row: each platform's icon with your nick. + +- **Networks:** add, edit, remove and reorder up to 12. Platforms: Twitch, YouTube, X, Instagram, TikTok, GitHub, Discord, Kick, LinkedIn and Web. A network without a nick is not shown; with no networks the layer stays empty. +- **Label** (for example «Sígueme»; empty hides it) and **custom CSS** with the classes `.root`, `.label`, `.item`, `.item-`, `.ico` and `.handle`. + +Nicks are shown as text, never as markup. The brand icons come from Simple Icons (CC0); X, TikTok and GitHub use a white glyph so they stay visible on dark backgrounds (`.item-x .ico path { fill: … }` changes it). The profiles live in `widgets.socials`, so, like the other widget settings, they travel with saved themes. Custom overlays can embed it as the `socials` slot. Via MCP: `editar_widget` with `widget: "socials"`; the list is replaced as a whole. + ### Questions, tier list and giveaway They live in **Widgets** and each one has its browser layer. Their state (questions, votes, participants) is saved in `data/interactive.json` and survives a restart. diff --git a/app/src/lib/types.ts b/app/src/lib/types.ts index d21b72a..4eb7719 100644 --- a/app/src/lib/types.ts +++ b/app/src/lib/types.ts @@ -186,6 +186,9 @@ export interface FollowersList extends FollowerSelection { shown: FollowerSelect export interface ThanksSnapshot { names: { name: string; platform: Platform }[]; anonymous: number } /** Chat preview in the real sources (GET/POST /api/chat/preview, SSE chatPreview). */ export interface ChatPreviewState { on: boolean; until: string | null } +/** Social bar profile (widgets.socials.items). */ +export interface SocialProfile { id: string; platform: string; handle: string } +export interface SocialsConfig { label?: string; items?: SocialProfile[]; css?: string } export interface WidgetsConfig { goals?: GoalConfig[]; chat?: WidgetSection; @@ -195,6 +198,7 @@ export interface WidgetsConfig { credits?: WidgetSection; thanks?: ThanksConfig; rotator?: RotatorConfig; + socials?: SocialsConfig; [k: string]: unknown; } /** Estado que consumen los widgets (engine.widgetState()). */ diff --git a/app/src/panel/Sidebar.tsx b/app/src/panel/Sidebar.tsx index 431ce01..fb2e6de 100644 --- a/app/src/panel/Sidebar.tsx +++ b/app/src/panel/Sidebar.tsx @@ -42,7 +42,7 @@ export function Sidebar({ current }: { current: string }) { const live = (t: string, label?: string) => {t}; const warns = alertWarnings(s).length; const widgetTail = I.vote && I.giveaway?.open ? live('2 activos', 'votación en curso y sorteo abierto') - : I.vote ? live('votando', 'votación en curso') : I.giveaway?.open ? live('sorteo', 'sorteo abierto') : num(13); + : I.vote ? live('votando', 'votación en curso') : I.giveaway?.open ? live('sorteo', 'sorteo abierto') : num(14); const groups: [string, string, Item[]][] = [ ['directo', 'En directo', [ { href: '#/directo', label: 'Directo', tail: s.status?.meld?.streaming ? live('●', 'en directo') : null }, diff --git a/app/src/panel/views/Widgets.tsx b/app/src/panel/views/Widgets.tsx index 801f2bf..9f4b916 100644 --- a/app/src/panel/views/Widgets.tsx +++ b/app/src/panel/views/Widgets.tsx @@ -11,8 +11,9 @@ import { useManualSave } from '../../lib/draft'; import { Box, Card, CardGroup, Dot, ListPanel, NameCell, PageHead, SaveBar, Slide, Tags } from '../../lib/layout'; import { go } from '../router'; import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; -import type { FollowerEntry, FollowersList, GoalBar, GoalConfig, GoalValue, RotatorMessage, WidgetSection } from '../../lib/types'; +import type { FollowerEntry, FollowersList, GoalBar, GoalConfig, GoalValue, RotatorMessage, SocialProfile, WidgetSection } from '../../lib/types'; import { CHAT_ANIMS, type ChatAnim } from '../../../../public/widgets/chat-anims.js'; +import { SOCIAL_NAMES } from '../../../../public/social-icons.js'; import { ChatWidget } from './ChatWidget'; import { InterviewSettings } from './InterviewWidget'; @@ -23,6 +24,7 @@ const INFO: RecordParámetros: ?platforms=twitch · ?layout=column · ?total=0 · ?peak=1. La cifra se refresca cada «pollSec» de la alerta de récord.

; if (name === 'thanks') form = ; if (name === 'rotator') form = ; + if (name === 'socials') form = ; if (name === 'interview') form = ; if (name === 'credits') form = <>
@@ -134,6 +137,32 @@ function RotatorSettings() { ; } +/** Social bar: ordered list of profiles (platform + nick), optional label. */ +function SocialsSettings() { + const items = useLive(s => (s.config.widgets.socials?.items || []) as SocialProfile[]); + const setItems = (next: SocialProfile[]) => patchWidgets({ socials: { items: next } }); + const edit = (i: number, change: Partial) => setItems(items.map((x, j) => (j === i ? { ...x, ...change } : x))); + const move = (i: number, d: number) => { const next = [...items]; const [x] = next.splice(i, 1); next.splice(i + d, 0, x); setItems(next); }; + return <> + +

Redes

+ {!items.length &&

Añade al menos una red para que el widget muestre algo.

} + {items.map((x, i) =>
+ + edit(i, { handle: e.target.value })} /> + move(i, -1)} /> + move(i, 1)} /> + setItems(items.filter((_, j) => j !== i))} /> +
)} +
+ +

Clases: .root .label .item .item-{''} .ico .handle

+

Las redes sin nick no se muestran. Los cambios se aplican al guardarlos.

+ ; +} + function ThanksSettings() { const window = useLive(s => s.config.widgets.thanks?.window || 'lastStream'); return <> @@ -221,7 +250,7 @@ export function Widgets({ parts }: { parts: string[] }) {
- + {fixed('chat',
, [...((w.chat?.platforms || ['twitch', 'youtube']) as string[]).map(p => ({ t: p === 'youtube' ? 'YouTube' : 'Twitch' })), ...css(w.chat?.css)])} 1 capa por objetivo} @@ -240,6 +269,8 @@ export function Widgets({ parts }: { parts: string[] }) { {fixed('rotator',
, [{ t: (w.rotator?.messages || []).length ? `${(w.rotator.messages as unknown[]).length} mensajes` : 'Sin mensajes todavía', on: !!(w.rotator?.messages || []).length }, { t: w.rotator?.order === 'random' ? 'Aleatorio' : 'En orden' }, ...css(w.rotator?.css)])} + {fixed('socials',
, + [{ t: (w.socials?.items || []).length ? `${(w.socials.items as unknown[]).length} redes` : 'Sin redes todavía', on: !!(w.socials?.items || []).length }, ...css(w.socials?.css)])} {fixed('credits',
GRACIAS
, [{ t: w.credits?.title || 'Créditos del directo' }, ...css(w.credits?.css)], )}
diff --git a/docs/estado.md b/docs/estado.md index c4eca6c..a07f13c 100644 --- a/docs/estado.md +++ b/docs/estado.md @@ -25,6 +25,7 @@ sigue sin dependencias (Node ≥ 24); React, esbuild y Tauri son solo de compila - **Seguidores sin conexión (#128):** registro local de Twitch y de suscripciones públicas de YouTube con recuento anónimo; requiere cuenta de YouTube conectada y no dispara alertas recuperadas. - **Agradecimientos (#129):** `/widget/thanks` (900×200) rota un nombre pendiente sin conexión cada vez y puede mostrar al final el recuento anónimo de YouTube. Configura plataformas, ventana y máximo desde Widgets; las fechas desconocidas se incluyen y sin archivo previo no hay corte «desde el último directo». El panel marca al momento cada entrada o, con confirmación, exactamente la selección visible. La capa solo recibe nombres, plataformas y recuento anónimo. - **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. +- **Redes sociales:** `/widget/socials` (1600×80) muestra una fila de perfiles con icono de plataforma y nick: `widgets.socials` con `label`, `items` ([{ id, platform, handle }], máx. 12; plataformas en `public/social-icons.js`, que también fija el enum del esquema) y `css`. Iconos de Simple Icons 16.38.1 (CC0) salvo Twitch/YouTube, que reutilizan `public/platform-icons.js`. Nicks como texto (DOM). Se puede incrustar como hueco `socials` en overlays propios. - **Vista previa del chat en las fuentes:** `POST /api/chat/preview` `{ on, seconds? }` (1–600, 120 por defecto) activa un estado efímero (`src/chat-preview.mjs`, sin persistir) que se emite como evento `chatPreview` `{ on, until }` a widgets y panel, también al conectar. `chat.html` reproduce entonces la demo de la vista previa y guarda los mensajes reales para volver a mostrarlos al terminar. No escribe en el chat ni en las métricas. - **Alertas de Twitch y YouTube:** tipos normalizados (follow, sub, resub, giftsub, cheer, raid, redemption; ytsub, superchat, supersticker, member, milestone, giftmember, jewels) con diff --git a/public/custom/sdk.js b/public/custom/sdk.js index 43a95e9..a9a6e3b 100644 --- a/public/custom/sdk.js +++ b/public/custom/sdk.js @@ -22,7 +22,7 @@ * Options: {duration, easing, delay} in ms/CSS easing. Directions: none, fade (default), * left, right, up, down; layer: above (default) or below; fit: slot (default) or canvas. * Allowed widgets/params: chat(variant), viewers(layout=column), goal(id), latest(items, - * layout=column), ticker, thanks, rotator, giveaway, question(nocount), tierlist(id,nopool), + * layout=column), ticker, thanks, rotator, socials, giveaway, question(nocount), tierlist(id,nopool), * interview(item), credits(loop,transparent), alerts, custom(id). No URLs, self-embedding * or nested custom overlays. 12 slots; 20 updates/s; invalid requests warn once. Slot CSS * rejects resource loads, escapes and comments to prevent untrusted CSS making same-origin requests. diff --git a/public/social-icons.js b/public/social-icons.js new file mode 100644 index 0000000..3ec7a0c --- /dev/null +++ b/public/social-icons.js @@ -0,0 +1,51 @@ +// Brand logos for the social bar widget. Twitch and YouTube reuse platform-icons.js; X, Instagram, +// TikTok, GitHub, Discord, Kick and LinkedIn come from Simple Icons 16.38.1 (CC0-1.0, +// https://simpleicons.org) with their brand colour, except black brands (X, TikTok, GitHub), drawn +// white so they stay visible on dark bands. «Web» is an own globe glyph. Built by DOM with fixed +// paths: configurable text never becomes markup. +import { LOGOS } from './platform-icons.js'; + +/** + * @typedef {{ viewBox: string, paths: [string, string][], stroke?: number }} SocialLogo + */ + +/** @type {Record} */ +export const SOCIAL_NAMES = { + twitch: 'Twitch', youtube: 'YouTube', x: 'X', instagram: 'Instagram', tiktok: 'TikTok', + github: 'GitHub', discord: 'Discord', kick: 'Kick', linkedin: 'LinkedIn', web: 'Web', +}; + +/** Platforms in panel order; the config schema accepts exactly these keys. @type {Record} */ +export const SOCIAL_LOGOS = { + twitch: LOGOS.twitch, + youtube: LOGOS.youtube, + x: { viewBox: '0 0 24 24', paths: [['#fff', 'M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z']] }, + instagram: { viewBox: '0 0 24 24', paths: [['#FF0069', 'M7.0301.084c-1.2768.0602-2.1487.264-2.911.5634-.7888.3075-1.4575.72-2.1228 1.3877-.6652.6677-1.075 1.3368-1.3802 2.127-.2954.7638-.4956 1.6365-.552 2.914-.0564 1.2775-.0689 1.6882-.0626 4.947.0062 3.2586.0206 3.6671.0825 4.9473.061 1.2765.264 2.1482.5635 2.9107.308.7889.72 1.4573 1.388 2.1228.6679.6655 1.3365 1.0743 2.1285 1.38.7632.295 1.6361.4961 2.9134.552 1.2773.056 1.6884.069 4.9462.0627 3.2578-.0062 3.668-.0207 4.9478-.0814 1.28-.0607 2.147-.2652 2.9098-.5633.7889-.3086 1.4578-.72 2.1228-1.3881.665-.6682 1.0745-1.3378 1.3795-2.1284.2957-.7632.4966-1.636.552-2.9124.056-1.2809.0692-1.6898.063-4.948-.0063-3.2583-.021-3.6668-.0817-4.9465-.0607-1.2797-.264-2.1487-.5633-2.9117-.3084-.7889-.72-1.4568-1.3876-2.1228C21.2982 1.33 20.628.9208 19.8378.6165 19.074.321 18.2017.1197 16.9244.0645 15.6471.0093 15.236-.005 11.977.0014 8.718.0076 8.31.0215 7.0301.0839m.1402 21.6932c-1.17-.0509-1.8053-.2453-2.2287-.408-.5606-.216-.96-.4771-1.3819-.895-.422-.4178-.6811-.8186-.9-1.378-.1644-.4234-.3624-1.058-.4171-2.228-.0595-1.2645-.072-1.6442-.079-4.848-.007-3.2037.0053-3.583.0607-4.848.05-1.169.2456-1.805.408-2.2282.216-.5613.4762-.96.895-1.3816.4188-.4217.8184-.6814 1.3783-.9003.423-.1651 1.0575-.3614 2.227-.4171 1.2655-.06 1.6447-.072 4.848-.079 3.2033-.007 3.5835.005 4.8495.0608 1.169.0508 1.8053.2445 2.228.408.5608.216.96.4754 1.3816.895.4217.4194.6816.8176.9005 1.3787.1653.4217.3617 1.056.4169 2.2263.0602 1.2655.0739 1.645.0796 4.848.0058 3.203-.0055 3.5834-.061 4.848-.051 1.17-.245 1.8055-.408 2.2294-.216.5604-.4763.96-.8954 1.3814-.419.4215-.8181.6811-1.3783.9-.4224.1649-1.0577.3617-2.2262.4174-1.2656.0595-1.6448.072-4.8493.079-3.2045.007-3.5825-.006-4.848-.0608M16.953 5.5864A1.44 1.44 0 1 0 18.39 4.144a1.44 1.44 0 0 0-1.437 1.4424M5.8385 12.012c.0067 3.4032 2.7706 6.1557 6.173 6.1493 3.4026-.0065 6.157-2.7701 6.1506-6.1733-.0065-3.4032-2.771-6.1565-6.174-6.1498-3.403.0067-6.156 2.771-6.1496 6.1738M8 12.0077a4 4 0 1 1 4.008 3.9921A3.9996 3.9996 0 0 1 8 12.0077']] }, + tiktok: { viewBox: '0 0 24 24', paths: [['#fff', 'M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z']] }, + github: { viewBox: '0 0 24 24', paths: [['#fff', 'M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12']] }, + discord: { viewBox: '0 0 24 24', paths: [['#5865F2', 'M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z']] }, + kick: { viewBox: '0 0 24 24', paths: [['#53FC19', 'M1.333 0h8v5.333H12V2.667h2.667V0h8v8H20v2.667h-2.667v2.666H20V16h2.667v8h-8v-2.667H12v-2.666H9.333V24h-8Z']] }, + linkedin: { viewBox: '0 0 24 24', paths: [['#0A66C2', 'M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z']] }, + web: { viewBox: '0 0 24 24', stroke: 2, paths: [['#fff', 'M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20ZM2 12h20M12 2c2.5 2.7 4 6.2 4 10s-1.5 7.3-4 10c-2.5-2.7-4-6.2-4-10s1.5-7.3 4-10Z']] }, +}; + +/** of a social platform logo, built by DOM; unknown platform → null. */ +export function socialSvg(platform, cls = 'ico') { + const logo = SOCIAL_LOGOS[platform]; + if (!logo) return null; + const NS = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(NS, 'svg'); + svg.setAttribute('viewBox', logo.viewBox); + svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); + svg.setAttribute('role', 'img'); + svg.setAttribute('aria-label', SOCIAL_NAMES[platform]); + svg.setAttribute('class', cls); + for (const [color, d] of logo.paths) { + const path = document.createElementNS(NS, 'path'); + path.setAttribute('d', d); + if (logo.stroke) { path.setAttribute('fill', 'none'); path.setAttribute('stroke', color); path.setAttribute('stroke-width', String(logo.stroke)); } + else path.setAttribute('fill', color); + svg.appendChild(path); + } + return svg; +} diff --git a/public/widgets/socials.html b/public/widgets/socials.html new file mode 100644 index 0000000..efe48cd --- /dev/null +++ b/public/widgets/socials.html @@ -0,0 +1,53 @@ + +antena · redes sociales + + + +
+ diff --git a/src/config-schema.mjs b/src/config-schema.mjs index f987e60..a81133d 100644 --- a/src/config-schema.mjs +++ b/src/config-schema.mjs @@ -27,6 +27,7 @@ import { validScheduleCalendarUrl, SCHEDULE_CALENDAR_URL_ERROR } from './schedul // #130: animaciones de los mensajes del chat en pantalla, las mismas para entrar y para salir; // fuente única compartida con el widget y el panel. import { CHAT_ANIMS } from '../public/widgets/chat-anims.js'; +import { SOCIAL_LOGOS } from '../public/social-icons.js'; // ---------- constructores de nodos ---------- const num = o => ({ kind: 'num', ...o }); @@ -79,6 +80,11 @@ const THANKS_FIELDS = { intervalSec: num({ int: true, min: 1, max: 3600 }), showAnonymous: bool, css: str, }; +// Social bar: ordered profiles (brand icon + nick), optional label. Platforms = the logo set. +const SOCIALS_FIELDS = { + label: str, items: list({ id: str, platform: en(Object.keys(SOCIAL_LOGOS)), handle: str }, { maxItems: 12 }), css: str, +}; + // Rotating on-screen messages: ordered list, cadence (start to start) and visible time. const ROTATOR_FIELDS = { label: str, messages: list({ id: str, text: str }, { maxItems: 50 }), @@ -310,6 +316,7 @@ export const CONFIG_SCHEMA = { viewers: { platforms: arrStr(['twitch', 'youtube']), showTotal: bool, showPeak: bool, css: str }, thanks: THANKS_FIELDS, rotator: ROTATOR_FIELDS, + socials: SOCIALS_FIELDS, }, }; diff --git a/src/custom-overlays.mjs b/src/custom-overlays.mjs index 07722f0..10bd8b1 100644 --- a/src/custom-overlays.mjs +++ b/src/custom-overlays.mjs @@ -386,7 +386,7 @@ export function shellHtml(overlay) { const widgetParams = { chat: ['variant'], viewers: ['layout'], goal: ['id'], latest: ['items', 'layout'], ticker: [], thanks: [], giveaway: [], question: ['nocount'], tierlist: ['id', 'nopool'], - interview: ['item'], credits: ['loop', 'transparent'], rotator: [], alerts: [], custom: ['id'], + interview: ['item'], credits: ['loop', 'transparent'], rotator: [], socials: [], alerts: [], custom: ['id'], }; const directions = ['none', 'fade', 'left', 'right', 'up', 'down']; const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k); diff --git a/src/mcp.mjs b/src/mcp.mjs index c14a869..028b1d3 100644 --- a/src/mcp.mjs +++ b/src/mcp.mjs @@ -306,10 +306,10 @@ tool('ver_widgets', 'Configuración y datos de los widgets (chat y sus variantes const [w, st] = await Promise.all([get('/api/widgets'), get('/api/config?path=port', { global: true })]); const b = `http://127.0.0.1:${st.value || 4500}`; const chatVariantes = (w.widgets.chatVariants || []).map(v => ({ id: v.id, nombre: v.name, url: b + '/widget/chat?variant=' + enc(v.id) })); - return { urls: { chat: b + '/widget/chat', objetivo: b + '/widget/goal?id=', ultimos: b + '/widget/latest', ticker: b + '/widget/ticker', creditos: b + '/widget/credits', espectadores: b + '/widget/viewers', agradecimientos: b + '/widget/thanks', mensajesEnPantalla: b + '/widget/rotator', chatVariantes }, config: w.widgets, objetivos: w.goals, totales: w.totals, ultimos: w.latest }; + return { urls: { chat: b + '/widget/chat', objetivo: b + '/widget/goal?id=', ultimos: b + '/widget/latest', ticker: b + '/widget/ticker', creditos: b + '/widget/credits', espectadores: b + '/widget/viewers', agradecimientos: b + '/widget/thanks', mensajesEnPantalla: b + '/widget/rotator', redesSociales: b + '/widget/socials', chatVariantes }, config: w.widgets, objetivos: w.goals, totales: w.totals, ultimos: w.latest }; }); -tool('editar_widget', 'Edita un widget. chat: platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css · latest: items (follow, sub, cheer, raid, superchat, member, any), label (vacía = sin etiqueta), css · ticker: label, items (follow, sub, cheer, raid, superchat, member, any; sin items usa los de latest), count, speed, css · credits: title, subtitle, speed, css · viewers: platforms (twitch, youtube), showTotal, showPeak, css · thanks: title, platforms (twitch, youtube), window (all|lastStream|days), days, maxNames, intervalSec, showAnonymous, css · rotator (mensajes en pantalla, distintos de los mensajes programados del chat): label, messages ([{ id, text }] en orden; la lista se reemplaza entera), intervalSec (5–3600, de un mensaje al siguiente), durationSec (segundos visibles, como mucho el intervalo), order (sequential|random: aleatorio sin repetir el mismo dos veces seguidas), css.', - { widget: S.enum('Widget', ['chat', 'latest', 'ticker', 'credits', 'viewers', 'thanks', 'rotator']), cambios: S.obj('Campos a cambiar') }, ({ widget, cambios }) => put('/api/widgets', { [widget]: cambios }), ['widget', 'cambios']); +tool('editar_widget', 'Edita un widget. chat: platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css · latest: items (follow, sub, cheer, raid, superchat, member, any), label (vacía = sin etiqueta), css · ticker: label, items (follow, sub, cheer, raid, superchat, member, any; sin items usa los de latest), count, speed, css · credits: title, subtitle, speed, css · viewers: platforms (twitch, youtube), showTotal, showPeak, css · thanks: title, platforms (twitch, youtube), window (all|lastStream|days), days, maxNames, intervalSec, showAnonymous, css · rotator (mensajes en pantalla, distintos de los mensajes programados del chat): label, messages ([{ id, text }] en orden; la lista se reemplaza entera), intervalSec (5–3600, de un mensaje al siguiente), durationSec (segundos visibles, como mucho el intervalo), order (sequential|random: aleatorio sin repetir el mismo dos veces seguidas), css · socials (barra de redes sociales): label, items ([{ id, platform, handle }] en orden, máximo 12; platform: twitch, youtube, x, instagram, tiktok, github, discord, kick, linkedin, web; la lista se reemplaza entera), css.', + { widget: S.enum('Widget', ['chat', 'latest', 'ticker', 'credits', 'viewers', 'thanks', 'rotator', 'socials']), cambios: S.obj('Campos a cambiar') }, ({ widget, cambios }) => put('/api/widgets', { [widget]: cambios }), ['widget', 'cambios']); tool('editar_variante_chat', 'Edita una variante del chat (ids en ver_widgets › chatVariantes; el chat predeterminado se edita con editar_widget). Cambia solo lo que pases: name, platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css. El id no cambia. Con layout horizontal, el css no debe fijar tamaño, posición, padding ni máscara de .root, ni flex, tamaño o letra de .msg: el widget ajusta la fila solo.', { id: S.str('Id de la variante'), cambios: S.obj('Campos a cambiar') }, ({ id, cambios }) => put('/api/widgets/chat/variants/' + enc(id), cambios), ['id', 'cambios']); const METRIC = S.enum('Qué cuenta', ['follows', 'subs', 'bits', 'raids', 'subscribers', 'superchats', 'members', 'events']); @@ -337,7 +337,7 @@ const OVERLAY_HELP = `Cómo se escribe un overlay (con unas líneas basta): - Datos en vivo por el SDK (window.antena): antena.on('alert'|'chat'|'viewers'|'widgets'|'interactive'|'theme'|'scene', fn), antena.state y antena.ready (espera a tener datos). 'scene' da las escenas al aire como [{ id, name }] (vacía sin programa; Meld la confirma al terminar su transición): sirve para un overlay único que cambia de layout según la escena. 'sceneSwitch' da { id, name } de la escena que Antena acaba de ordenar, antes de esa confirmación, para animar a la vez que el programa. Ej.: antena.on('alert', a => { nombre.textContent = a.text; nombre.animate([{opacity:0},{opacity:1}], 300); }); - Huecos sin permisos: antena.slots.place({chat:{widget:'chat',rect:[1500,82,400,488],enter:'right',exit:'right'}},{duration:600,easing:'ease',delay:0}); rect:null oculta; clear('chat') o clear() borra. Huecos no mencionados se conservan. Máx. 12; nombres a-z0-9_- (32); rect finito, w/h 1–4320, x/y ±2 lienzos; 20 actualizaciones/s agrupadas por frame. - Campos: widget, params, rect, enter/exit (none|fade|left|right|up|down), layer (above|below), fit (slot|canvas), css. slot llena el hueco; canvas conserva la posición/animación de la página. Widgets y params: chat(variant), viewers(layout:column), goal(id), latest(items,layout:column), ticker, thanks, giveaway, question(nocount), tierlist(id,nopool), interview(item), credits(loop,transparent), rotator, alerts, custom(id). No URLs; custom no puede incluirse a sí mismo ni anidar otro custom. + Campos: widget, params, rect, enter/exit (none|fade|left|right|up|down), layer (above|below), fit (slot|canvas), css. slot llena el hueco; canvas conserva la posición/animación de la página. Widgets y params: chat(variant), viewers(layout:column), goal(id), latest(items,layout:column), ticker, thanks, giveaway, question(nocount), tierlist(id,nopool), interview(item), credits(loop,transparent), rotator, socials, alerts, custom(id). No URLs; custom no puede incluirse a sí mismo ni anidar otro custom. Por seguridad, el css de hueco rechaza recursos (url, image-set, image(, src(, @import, @namespace, @font-face), escapes y comentarios. Alertas y entrevista incrustadas silencian audio si Page Visibility marca oculta la capa; no se ha comprobado que Meld oculte fuentes fuera de escena. Usa una única fuente en Meld y Duplicator en las otras escenas para evitar audio duplicado. - Acciones (S11): antena.run(kind, params) devuelve una promesa: resuelve si la acción se ejecutó y se rechaza con el error del servidor si no. diff --git a/src/routes/shortcuts.mjs b/src/routes/shortcuts.mjs index 5eace6f..0529160 100644 --- a/src/routes/shortcuts.mjs +++ b/src/routes/shortcuts.mjs @@ -32,6 +32,7 @@ const BROWSER_SOURCES = [ { id: 'thanks', name: 'Agradecimientos', path: '/widget/thanks', width: 900, height: 200 }, { id: 'interview', name: 'Entrevista', path: '/widget/interview', width: 1920, height: 1080 }, { id: 'rotator', name: 'Mensajes en pantalla', path: '/widget/rotator', width: 1200, height: 120 }, + { id: 'socials', name: 'Redes sociales', path: '/widget/socials', width: 1600, height: 80 }, ]; // S10: pestañas del prompter retiradas. La API ya no las ofrece (prompterTabs y la lista de // acciones solo tienen las vigentes), pero un atajo guardado con ellas sigue siendo válido y se diff --git a/src/routes/widgets.mjs b/src/routes/widgets.mjs index 0d264ef..6201e9f 100644 --- a/src/routes/widgets.mjs +++ b/src/routes/widgets.mjs @@ -22,6 +22,10 @@ export function registerWidgetRoutes({ route, store, engine }) { const [error] = validatePath('widgets.thanks', patch.thanks); if (error) throw httpError(400, error.message); } + if (Object.hasOwn(patch, 'socials')) { + const [error] = validatePath('widgets.socials', patch.socials); + if (error) throw httpError(400, error.message); + } if (Object.hasOwn(patch, 'rotator')) { const [error] = validatePath('widgets.rotator', patch.rotator); if (error) throw httpError(400, error.message); diff --git a/src/server.mjs b/src/server.mjs index 85f69ec..0f40391 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -95,7 +95,7 @@ const MIME = { '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.webm': 'video/webm', '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime', }; -export const WIDGETS = ['chat', 'goal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'teleprompter', 'viewers', 'thanks', 'interview', 'rotator']; +export const WIDGETS = ['chat', 'goal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'teleprompter', 'viewers', 'thanks', 'interview', 'rotator', 'socials']; /** Viewer counts for on-screen widgets: only what the widget shows, never settings or errors. */ export function publicViewers(snap) { diff --git a/src/store.mjs b/src/store.mjs index 209f0ea..197f037 100644 --- a/src/store.mjs +++ b/src/store.mjs @@ -65,6 +65,7 @@ export const DEFAULT_CONFIG = { viewers: { platforms: ['twitch', 'youtube'], showTotal: true, showPeak: false, css: '' }, // espectadores a la vez por plataforma thanks: { title: 'Gracias por seguir', platforms: ['twitch', 'youtube'], window: 'lastStream', days: 30, maxNames: 20, intervalSec: 5, showAnonymous: true, css: '' }, rotator: { label: 'Mensaje', messages: [], intervalSec: 240, durationSec: 12, order: 'sequential', css: '' }, // mensajes en pantalla que rotan (independientes de los mensajes programados del chat) + socials: { label: '', items: [], css: '' }, // barra de redes sociales: icono de plataforma + nick credits: { title: 'Gracias por estar', subtitle: 'egdev.es · directos los miércoles a las 19:00', speed: 60, css: '' }, }, }; diff --git a/test/chat-variants.test.mjs b/test/chat-variants.test.mjs index 617c4d9..f0e99da 100644 --- a/test/chat-variants.test.mjs +++ b/test/chat-variants.test.mjs @@ -782,7 +782,7 @@ test('MCP ver_widgets conserva las URLs anteriores y expone las de cada variante const data = JSON.parse(result.content[0].text); assert.deepEqual({ ...data.urls, chatVariantes: undefined }, { chat: `${f.base}/widget/chat`, objetivo: `${f.base}/widget/goal?id=`, ultimos: `${f.base}/widget/latest`, - ticker: `${f.base}/widget/ticker`, creditos: `${f.base}/widget/credits`, espectadores: `${f.base}/widget/viewers`, agradecimientos: `${f.base}/widget/thanks`, mensajesEnPantalla: `${f.base}/widget/rotator`, chatVariantes: undefined, + ticker: `${f.base}/widget/ticker`, creditos: `${f.base}/widget/credits`, espectadores: `${f.base}/widget/viewers`, agradecimientos: `${f.base}/widget/thanks`, mensajesEnPantalla: `${f.base}/widget/rotator`, redesSociales: `${f.base}/widget/socials`, chatVariantes: undefined, }); assert.deepEqual(data.urls.chatVariantes, variants.map(v => ({ id: v.id, nombre: v.name, url: `${f.base}/widget/chat?variant=${v.id}` }))); } diff --git a/test/core.test.mjs b/test/core.test.mjs index e4e2698..572e8e9 100644 --- a/test/core.test.mjs +++ b/test/core.test.mjs @@ -154,7 +154,7 @@ test('CSS: los estilos de serie van en una capa y el CSS común viaja con cada a const a = buildAlert('raid', { user: 'x', amount: 5 }, { overlay: { css: '.alert{--accent:#0ff}' }, alerts: { raid: { css: '.alert-name{color:red}' } } }); assert.equal(a.globalCss, '.alert{--accent:#0ff}'); assert.equal(a.look.css, '.alert-name{color:red}'); - for (const f of ['chat', 'goal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'rotator']) { + for (const f of ['chat', 'goal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'rotator', 'socials']) { assert.match(await readFile(new URL(`../public/widgets/${f}.html`, import.meta.url), 'utf8'), /@layer egdev \{/, f); } }); diff --git a/test/groups.json b/test/groups.json index 21851db..730373e 100644 --- a/test/groups.json +++ b/test/groups.json @@ -106,6 +106,7 @@ "test/session-retention.test.mjs", "test/session-save-cost.test.mjs", "test/shortcuts-neutral-texts.test.mjs", + "test/socials-widget.test.mjs", "test/sse-budget-characterization.test.mjs", "test/sse-budget-socket.test.mjs", "test/sse-compaction-replacement.test.mjs", @@ -233,6 +234,7 @@ "test/security-247-browser.test.mjs", "test/sidebar-widgets-browser.test.mjs", "test/slide-scroll-browser.test.mjs", + "test/socials-widget-browser.test.mjs", "test/stream-client-proxy.test.mjs", "test/teleprompter-widget-browser.test.mjs", "test/thanks-129-regression.test.mjs", diff --git a/test/interview-dock-catalog-browser.test.mjs b/test/interview-dock-catalog-browser.test.mjs index 5061b78..e5d69b5 100644 --- a/test/interview-dock-catalog-browser.test.mjs +++ b/test/interview-dock-catalog-browser.test.mjs @@ -90,12 +90,12 @@ test('interview card is a live-managed widget with accurate counts and live stat const card = `${liveGroup}.querySelector('a.lv-hit[href="#/entrevista"]')?.closest('.lv-card')`; assert.ok(await dom(c, `!!(${card})`), 'the live-managed interview card links to its own page'); assert.equal(await dom(c, `${layerGroup}.querySelectorAll('a.lv-hit[href="#/widgets/interview"]').length`), 0); - assert.equal(await dom(c, `${layerGroup}.querySelectorAll('.lv-card').length`), 8); - assert.equal(await dom(c, `${layerGroup}.querySelector('.lv-group-h .n').textContent`), '8'); + assert.equal(await dom(c, `${layerGroup}.querySelectorAll('.lv-card').length`), 9); + assert.equal(await dom(c, `${layerGroup}.querySelector('.lv-group-h .n').textContent`), '9'); assert.equal(await dom(c, `${liveGroup}.querySelectorAll('.lv-card').length`), 5); assert.equal(await dom(c, `${liveGroup}.querySelector('.lv-group-h .n').textContent`), '5'); - assert.match(await dom(c, `document.querySelector('main .view-head .crumb').textContent`), /13 widgets/); - assert.equal(await dom(c, `document.querySelector('#nav a[href="#/widgets"] .nav-n').textContent`), '13'); + assert.match(await dom(c, `document.querySelector('main .view-head .crumb').textContent`), /14 widgets/); + assert.equal(await dom(c, `document.querySelector('#nav a[href="#/widgets"] .nav-n').textContent`), '14'); await waitDom(c, `(${card})?.querySelector('.lv-dot')?.textContent.includes('Sin entrevista activa')`, { timeoutMs: 9000 }); assert.ok(await dom(c, `!!${liveGroup}.querySelector('a.lv-hit[href="#/preguntas"]')`), 'existing live cards remain'); await ctx.call('POST', '/api/interviews/import', PACK); diff --git a/test/routes-shortcuts.test.mjs b/test/routes-shortcuts.test.mjs index 82c02ef..4357dc0 100644 --- a/test/routes-shortcuts.test.mjs +++ b/test/routes-shortcuts.test.mjs @@ -64,7 +64,7 @@ test('GET /api/sources: capas con URL, objetivos intercalados y paneles', async assert.equal(out.base, 'http://127.0.0.1:4500'); const ids = out.sources.map(x => x.id); // los objetivos van entre chat y latest, como en el original - assert.deepEqual(ids, ['overlay', 'chat', 'goal-principal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'viewers', 'thanks', 'interview', 'rotator']); + assert.deepEqual(ids, ['overlay', 'chat', 'goal-principal', 'latest', 'ticker', 'credits', 'question', 'tierlist', 'giveaway', 'viewers', 'thanks', 'interview', 'rotator', 'socials']); const ov = out.sources.find(x => x.id === 'overlay'); assert.deepEqual([ov.url, ov.width, ov.height], ['http://127.0.0.1:4500/overlay', 1920, 1080]); const goal = out.sources.find(x => x.id === 'goal-principal'); diff --git a/test/sidebar-widgets-browser.test.mjs b/test/sidebar-widgets-browser.test.mjs index 253dbc6..dcc8855 100644 --- a/test/sidebar-widgets-browser.test.mjs +++ b/test/sidebar-widgets-browser.test.mjs @@ -139,7 +139,7 @@ test('Widgets cards retain live states and the sidebar warns about votes and giv assert.equal(await evaluateChrome(c, `${widgetsTail}.getAttribute('aria-label')`), 'sorteo abierto'); assert.equal(await evaluateChrome(c, `${widgetsTail}.classList.contains('is-live')`), true); await call('POST', '/api/giveaway/close'); - await waitDom(c, `${widgetsTail}?.textContent === '13' && ${card('#/sorteo')}?.textContent.includes('Cerrado')`, { timeoutMs: 12000 }); + await waitDom(c, `${widgetsTail}?.textContent === '14' && ${card('#/sorteo')}?.textContent.includes('Cerrado')`, { timeoutMs: 12000 }); assert.equal(await evaluateChrome(c, `${widgetsTail}.classList.contains('is-live')`), false); await call('POST', `/api/tierlists/${tierlist.id}/vote`, { item: 'One' }); await waitDom(c, `${widgetsTail}?.textContent === 'votando' && ${card('#/tierlist')}?.textContent.includes('Votando')`, { timeoutMs: 12000 }); @@ -148,6 +148,6 @@ test('Widgets cards retain live states and the sidebar warns about votes and giv await call('POST', '/api/vote/cancel'); await call('POST', '/api/questions/clear', { all: true }); await call('POST', '/api/teleprompter/control', { action: 'pause' }); - await waitDom(c, `${widgetsTail}?.textContent === '13' && ${card('#/preguntas')}?.textContent.includes('Cola vacía') && !${card('#/teleprompter')}?.textContent.includes('Leyendo')`, { timeoutMs: 12000 }); + await waitDom(c, `${widgetsTail}?.textContent === '14' && ${card('#/preguntas')}?.textContent.includes('Cola vacía') && !${card('#/teleprompter')}?.textContent.includes('Leyendo')`, { timeoutMs: 12000 }); assert.equal(await evaluateChrome(c, `${card('#/teleprompter')}.textContent.includes('Solo lo ves tú')`), true); }); diff --git a/test/socials-widget-browser.test.mjs b/test/socials-widget-browser.test.mjs new file mode 100644 index 0000000..961ae92 --- /dev/null +++ b/test/socials-widget-browser.test.mjs @@ -0,0 +1,68 @@ +// Social bar in Chrome: the widget renders icon + nick as text, and the panel adds a profile. +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 { closeAll, closeChrome, openChromePage, skipIfNoBrowserOrUi, waitDom } from './helpers/react-browser.mjs'; +import { evaluateChrome } from './helpers/chrome-dom.mjs'; + +test('the social bar shows icon and nick per profile and the panel adds one', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const dataDir = await mkdtemp(path.join(tmpdir(), 'antena-socials-browser-')); + t.after(() => rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })); + const app = await createApp({ dataDir, mediaDir: path.join(dataDir, '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 call = async (method, url, body) => { const r = await fetch(base + url, { method, headers: { 'content-type': 'application/json' }, body: body && JSON.stringify(body) }); assert.equal(r.ok, true, url); return r.json(); }; + let chrome; + try { + await call('PUT', '/api/config', { panel: { onboardingDone: true } }); + await call('PUT', '/api/widgets', { socials: { label: 'Sígueme', items: [ + { id: 's1', platform: 'x', handle: '@egdev6' }, { id: 's2', platform: 'github', handle: 'egdev6' }, { id: 's3', platform: 'web', handle: 'egdev.es' }] } }); + chrome = await openChromePage(bin, base + '/widget/socials'); + const c = chrome.cdp, ev = s => evaluateChrome(c, s); + await waitDom(c, `document.querySelectorAll('#root .item').length === 3`, { timeoutMs: 10000 }); + const shown = await ev(`({ label: document.querySelector('#root .label')?.textContent, + items: [...document.querySelectorAll('#root .item')].map(e => ({ cls: e.className, icon: e.querySelector('svg.ico')?.getAttribute('aria-label'), handle: e.querySelector('.handle').textContent })), + injected: document.querySelectorAll('#root .handle b').length })`); + assert.equal(shown.label, 'Sígueme'); + assert.deepEqual(shown.items, [ + { cls: 'item item-x', icon: 'X', handle: '@egdev6' }, + { cls: 'item item-github', icon: 'GitHub', handle: 'egdev6' }, + { cls: 'item item-web', icon: 'Web', handle: 'egdev.es' }]); + assert.equal(shown.injected, 0, 'nicks are text, never markup'); + + // Empty list: nothing on screen; the label alone is not shown. + await call('PUT', '/api/widgets', { socials: { items: [] } }); + await waitDom(c, `document.querySelectorAll('#root .item').length === 0 && !document.querySelector('#root .label')`, { timeoutMs: 8000 }); + await closeChrome(chrome); chrome = null; + + // Panel: add a profile and save it. + chrome = await openChromePage(bin, base + '/#/widgets/socials'); + const p = chrome.cdp, pev = s => evaluateChrome(p, s); + const button = text => `[...document.querySelectorAll('main button')].find(b => b.textContent.trim() === ${JSON.stringify(text)})`; + await waitDom(p, `!!(${button('Añadir red')})`, { timeoutMs: 15000 }); + await pev(`${button('Añadir red')}.click(); true`); + await waitDom(p, `!!document.querySelector('main select[aria-label="Red 1"]') && !!document.querySelector('main input[aria-label="Nick 1"]')`, { timeoutMs: 5000 }); + await pev(`(() => { + const s = document.querySelector('main select[aria-label="Red 1"]'); + Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set.call(s, 'instagram'); s.dispatchEvent(new Event('change', { bubbles: true })); + const i = document.querySelector('main input[aria-label="Nick 1"]'); + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(i, '@egdev6'); i.dispatchEvent(new Event('input', { bubbles: true })); + return true; })()`); + const save = `[...document.querySelectorAll('button')].find(b => /^Guardar/.test(b.textContent.trim()) && !b.disabled)`; + await waitDom(p, `!!(${save})`, { timeoutMs: 5000 }); + await pev(`${save}.click(); true`); + for (let i = 0; i < 60; i++) { + const items = (await (await fetch(base + '/api/widgets')).json()).widgets.socials.items; + if (items.length === 1) { assert.deepEqual(items.map(x => [x.platform, x.handle]), [['instagram', '@egdev6']]); return; } + await new Promise(r => setTimeout(r, 100)); + } + assert.fail('the panel did not save the new profile'); + } finally { + await closeAll(() => chrome && closeChrome(chrome), () => { app.viewers.stop(); app.meld.stop(); app.server.closeAllConnections(); app.server.close(); }); + } +}); diff --git a/test/socials-widget.test.mjs b/test/socials-widget.test.mjs new file mode 100644 index 0000000..e4761bd --- /dev/null +++ b/test/socials-widget.test.mjs @@ -0,0 +1,68 @@ +// Social bar widget: config contract, registration and the brand icon set. +import { after, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { SOCIAL_LOGOS, SOCIAL_NAMES } from '../public/social-icons.js'; +import { schemaAt } from '../src/config-schema.mjs'; + +const root = await mkdtemp(path.join(tmpdir(), 'antena-socials-')); +process.env.ANTENA_DATA = path.join(root, 'default-data'); +process.env.ANTENA_MEDIA = path.join(root, 'default-media'); +const { createApp } = await import('../src/server.mjs'); +after(() => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })); + +const PLATFORMS = ['twitch', 'youtube', 'x', 'instagram', 'tiktok', 'github', 'discord', 'kick', 'linkedin', 'web']; + +async function start(t) { + const dir = await mkdtemp(path.join(root, 'case-')); + const app = await createApp({ dataDir: dir, mediaDir: path.join(dir, 'media'), log: () => {} }); + await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve)); + t.after(() => { app.viewers.stop(); app.meld.stop(); app.server.closeAllConnections(); app.server.close(); }); + const base = `http://127.0.0.1:${app.server.address().port}`; + const put = body => fetch(base + '/api/widgets', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const get = async () => (await (await fetch(base + '/api/widgets')).json()).widgets.socials; + return { base, put, get }; +} + +test('every social platform has a name and a logo, and the config accepts exactly those platforms', () => { + assert.deepEqual(Object.keys(SOCIAL_LOGOS), PLATFORMS); + for (const p of PLATFORMS) { + assert.equal(typeof SOCIAL_NAMES[p], 'string', p); + assert.match(SOCIAL_LOGOS[p].viewBox, /^\d+ \d+ \d+ \d+$/, p); + assert.ok(SOCIAL_LOGOS[p].paths.length > 0, p); + } + assert.deepEqual(schemaAt('widgets.socials.items').item.platform.values, PLATFORMS); +}); + +test('the social bar config has defaults, saves valid changes and rejects invalid ones unchanged', async t => { + const { put, get } = await start(t); + assert.deepEqual(await get(), { label: '', items: [], css: '' }); + + const items = [{ id: 's1', platform: 'x', handle: '@egdev6' }, { id: 's2', platform: 'github', handle: 'egdev6' }]; + const saved = await put({ socials: { label: 'Sígueme', items } }); + assert.equal(saved.status, 200); + assert.deepEqual((await saved.json()).widgets.socials, { label: 'Sígueme', items, css: '' }); + assert.deepEqual((await (await put({ socials: { items: [items[1]] } })).json()).widgets.socials.items, [items[1]], 'the list is replaced, not merged'); + + const before = await get(); + for (const bad of [{ items: [{ id: 'a', platform: 'myspace', handle: 'x' }] }, { items: [{ id: 'a', platform: 'x', handle: 5 }] }, + { label: 3 }, { items: Array.from({ length: 13 }, (_, i) => ({ id: 's' + i, platform: 'web', handle: 'h' })) }]) { + const r = await put({ socials: bad }); + assert.equal(r.status, 400, JSON.stringify(bad)); + assert.match((await r.json()).error, /widgets\.socials/); + } + assert.deepEqual(await get(), before, 'rejected changes leave the config unchanged'); +}); + +test('the social bar is served, listed as a browser source and usable as a slot', async t => { + const { base } = await start(t); + const page = await fetch(base + '/widget/socials'); + assert.equal(page.status, 200); + assert.match(await page.text(), /@layer egdev[\s\S]*social-icons\.js/); + const { sources } = await (await fetch(base + '/api/sources')).json(); + assert.ok(sources.some(s => s.id === 'socials' && s.url === base + '/widget/socials'), 'listed in the browser sources'); + const overlaySource = await readFile(new URL('../src/custom-overlays.mjs', import.meta.url), 'utf8'); + assert.match(overlaySource, /socials: \[\]/, 'custom overlays can embed the social bar as a slot'); +}); diff --git a/test/theme.test.mjs b/test/theme.test.mjs index 9729771..35867be 100644 --- a/test/theme.test.mjs +++ b/test/theme.test.mjs @@ -51,7 +51,7 @@ test('todas las capas del directo cargan /theme.css; el teleprompter no', async } assert.match(await readFile(path.join(ROOT, 'public/overlay.html'), 'utf8'), /id="eg-theme"/); // sin rojos de marca fijos en las capas: todo sale de las variables del tema - for (const f of ['overlay.html', 'widgets/widget.css', 'widgets/chat.html', 'widgets/goal.html', 'widgets/ticker.html', 'widgets/question.html', 'widgets/giveaway.html', 'widgets/tierlist.html', 'widgets/credits.html', 'widgets/latest.html', 'widgets/rotator.html']) { + for (const f of ['overlay.html', 'widgets/widget.css', 'widgets/chat.html', 'widgets/goal.html', 'widgets/ticker.html', 'widgets/question.html', 'widgets/giveaway.html', 'widgets/tierlist.html', 'widgets/credits.html', 'widgets/latest.html', 'widgets/rotator.html', 'widgets/socials.html']) { const src = await readFile(path.join(ROOT, 'public', f), 'utf8'); assert.doesNotMatch(src, /rgba\(255, ?0, ?54/, f); }