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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ In the panel, the «Fuentes del programa de emisión» page lists all of them wi
| Interview | `http://127.0.0.1:4500/widget/interview` | 1920×1080 |
| On-screen messages | `http://127.0.0.1:4500/widget/rotator` | 1200×120 |

The ticker shows the same event types you tick for «Latest» in **Widgets › Latest and ticker** (follower, sub, bits, raid, Super Chat, member or any event), up to its «Events» count; with nothing matching it shows the placeholder text.
**Preview in your broadcast program:** in **Widgets › Chat**, «Simular mensajes en Meld» makes every real chat source (the default chat, its variants and custom overlay slots) play the same sample messages as the panel preview for 2 minutes, then return to the real chat. A source loaded during the simulation joins it. Nothing is added to the chat, the history or the metrics. API: `POST /api/chat/preview` with `{ "on": true }` (optional `"seconds"`, 1–600) or `{ "on": false }`; `GET /api/chat/preview` returns `{ on, until }`. MCP: `vista_previa_chat`.

**Interview.** Fullscreen layer for the active, approved item of the active interview (see `docs/entrevista-formato.md`): the question on a card at the bottom over its image, local video, YouTube player (starting at the saved minute) or social post card, with the source shown on every item that has media. Without an active item the layer is empty. In **Widgets › Se manejan en directo › Entrevista**, create or import interviews, edit and reorder rounds and questions, and press **Guardar** to save the draft. The detail header selects or stops the active interview and controls the live layer; the dock can also stop it without deleting it. `POST /api/interviews/stop` does the same and is safe to repeat. **Capa** has its URL and demo preview. Private notes never appear on the layer. Try it with `?demo`.

Expand Down Expand Up @@ -556,7 +556,7 @@ Claude Desktop (`claude_desktop_config.json`):
| Giveaway | `estado_sorteo`, `abrir_sorteo`, `cerrar_sorteo`, `sortear`, `anadir_participante`, `quitar_participante`, `reiniciar_sorteo` |
| Interactives | `estado_interactivos`, `configurar_interactivos` |
| Files | `listar_archivos`, `importar_archivo` (from a path on your PC), `borrar_archivo` |
| Chat | `leer_chat`, `escribir_chat` (Twitch, YouTube or both), `simular_chat`, `unir_chat`, `youtube_conectar_cuenta`, `youtube_desconectar_cuenta` |
| Chat | `leer_chat`, `escribir_chat` (Twitch, YouTube or both), `simular_chat`, `vista_previa_chat`, `unir_chat`, `youtube_conectar_cuenta`, `youtube_desconectar_cuenta` |
| Widgets | `ver_widgets`, `editar_widget`, `editar_variante_chat`, `crear_objetivo`, `editar_objetivo`, `borrar_objetivo`, `crear_barra`, `editar_barra`, `borrar_barra`, `sumar_objetivo`, `fijar_objetivo`, `sumar_barra`, `fijar_barra`, `lanzar_creditos`, `parar_creditos` |
| Custom overlays | `listar_overlays`, `ver_overlay`, `crear_overlay`, `editar_overlay`, `borrar_overlay`, `probar_overlay`, `css_overlay_tema` |
| Stream | `resumen_directo`, `metricas_directo`, `nuevo_directo`, `renombrar_directo`, `listar_directos`, `eventos_directo` |
Expand Down
1 change: 1 addition & 0 deletions app/src/lib/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ class Live {
for (const r of this.inflightRemoved) r.ids.add(id);
this.update(s => ({ widgets: { ...s.widgets, chat: (s.widgets?.chat || []).filter(m => m.id !== id) } }));
});
on('chatPreview', () => {}); // views listen with live.on('chatPreview')
on('chatResult', () => {}); // only partial failures arrive; the panel shows them as a toast
on('chatClear', ({ login }) => {
for (const r of this.inflightRemoved) r.logins.add(login || null);
Expand Down
3 changes: 3 additions & 0 deletions app/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ export interface AnonymousFollowers { at: string | null; count: number; thanked:
export interface FollowerSelection { entries: FollowerEntry[]; anonymous: AnonymousFollowers[] }
export interface FollowersList extends FollowerSelection { shown: FollowerSelection }
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 }
export interface WidgetsConfig {
goals?: GoalConfig[];
chat?: WidgetSection;
Expand Down Expand Up @@ -528,6 +530,7 @@ export interface LiveEvents {
chat: ChatMessage;
chatDelete: { id: string };
chatResult: ChatResult;
chatPreview: ChatPreviewState;
chatClear: { login: string };
timeline: Timeline;
prompter: PrompterState;
Expand Down
34 changes: 32 additions & 2 deletions app/src/panel/views/ChatWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { horizontalCssWarnings } from '../../lib/chat-css';
import { live, useLive } from '../../lib/live';
import { ManualDraft } from '../../lib/manual-draft';
import { patchWidgets } from '../../lib/patch';
import type { ChatVariant, WidgetSection } from '../../lib/types';
import type { ChatPreviewState, ChatVariant, WidgetSection } from '../../lib/types';
import { BrowserSource, codeTab, confirmDelete, Panel, Stage, Switch, toast, WidgetLayout } from '../../lib/ui';

const ROUTE = '/api/widgets/chat/variants';
Expand Down Expand Up @@ -210,7 +210,7 @@ export function ChatWidget({ info, anims }: { info: Info; anims: Options }) {
return <Slide crumb={<><a href="#/widgets">Widgets</a> › {info.title}</>} title={info.title} desc={info.desc} back="#/widgets" wide foot={<SaveBar />}>
<WidgetLayout className="chat-variant-editor"
source={<BrowserSource url={location.origin + path} size={dimensions.size} />}
preview={<Stage eyebrow="Vista previa" aside={<span>Datos de ejemplo</span>} src={preview} w={dimensions.w} h={dimensions.h} />}>
preview={<><Stage eyebrow="Vista previa" aside={<span>Datos de ejemplo</span>} src={preview} w={dimensions.w} h={dimensions.h} /><ChatPreviewInSources /></>}>
<Panel>
<div className="chat-variants">
<label>Variante de chat<select value={id} disabled={!loaded || locked || mode !== null} onChange={e => changeSelection(e.target.value)}>
Expand Down Expand Up @@ -243,3 +243,33 @@ export function ChatWidget({ info, anims }: { info: Info; anims: Options }) {
</WidgetLayout>
</Slide>;
}

/** Plays the preview's demo messages in every real chat source (Meld) for two minutes. */
function ChatPreviewInSources() {
const [state, setState] = useState<ChatPreviewState>({ on: false, until: null });
const [now, setNow] = useState(Date.now());
const [busy, setBusy] = useState(false);
useEffect(() => {
let alive = true;
get<ChatPreviewState>('/api/chat/preview').then(s => { if (alive) setState(s); }).catch(() => {});
const off = live.on('chatPreview', s => setState(s));
return () => { alive = false; off(); };
}, []);
useEffect(() => {
if (!state.on) return;
const t = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(t);
}, [state.on]);
const left = state.on && state.until ? Math.max(0, Math.round((Date.parse(state.until) - now) / 1000)) : 0;
const toggle = async () => {
setBusy(true);
try { setState(await post<ChatPreviewState>('/api/chat/preview', { on: !state.on })); setNow(Date.now()); }
catch (e) { toast(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
};
return <div className="chat-preview-sources" style={{ marginTop: 12 }}>
<button type="button" className={`eg-btn eg-btn--sm ${state.on ? 'eg-btn--primary' : 'eg-btn--secondary'}`} disabled={busy} aria-pressed={state.on} onClick={() => void toggle()}>
{state.on ? `Parar simulación en Meld · ${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` : 'Simular mensajes en Meld'}</button>
<p className="hint">Tus fuentes de chat en Meld (también las variantes y los huecos de overlays) reproducen estos mensajes de ejemplo durante 2 minutos y luego vuelven al chat real. No se guardan en el chat ni cuentan en las métricas.</p>
</div>;
}
1 change: 1 addition & 0 deletions docs/estado.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- **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
tres diseños (tarjeta, vídeo con texto y vídeo de fondo + tarjeta), variaciones, voz y acciones en el programa de emisión.
Expand Down
22 changes: 18 additions & 4 deletions public/widgets/chat.html
Original file line number Diff line number Diff line change
Expand Up @@ -267,12 +267,26 @@
// Al cambiar el tamaño de la capa se vuelve a limitar el DOM, sin suscripción adicional.
new ResizeObserver(() => { if (cfg.layout === 'horizontal') trim(); }).observe(root);
let first = true;
// Preview in the real sources (chatPreview): the page plays the demo stream and keeps the real
// messages it receives, so it can show them again when the preview ends.
const real = [];
let preview = false, demoTimer = 0;
const keep = m => { real.push(m); if (real.length > 200) real.shift(); };
function clearRoot() { for (const el of [...root.children]) { clearTimeout(el._fade); el.remove(); } }
function playDemo() { for (let i = 0; i < 6; i++) render(demoChat(demoN++)); demoTimer = setInterval(() => render(demoChat(demoN++)), 2200); }
function setPreview(on) {
if (DEMO || on === preview) return;
preview = on; clearInterval(demoTimer); clearRoot();
if (on) playDemo();
else real.filter(visible).slice(-(Number(cfg.maxMessages) || 12)).forEach(render);
}
// Backlog: the last maxMessages visible messages, so hidden ones (yours, commands, other platforms) do not use up the limit.
connect({
widgets: s => { apply(s.widgets); if (first && !DEMO) (s.chat || []).filter(visible).slice(-(Number(cfg.maxMessages) || 12)).forEach(render); first = false; },
chat: m => { if (!DEMO) render(m); },
chatDelete: ({ id }) => root.querySelector(`[data-id="${CSS.escape(id)}"]`)?.remove(),
chatClear: ({ login }) => [...root.children].forEach(el => { if (!login || el.dataset.login === login) el.remove(); }),
widgets: s => { apply(s.widgets); if (first && !DEMO) { (s.chat || []).forEach(keep); if (!preview) (s.chat || []).filter(visible).slice(-(Number(cfg.maxMessages) || 12)).forEach(render); } first = false; },
chat: m => { if (DEMO) return; keep(m); if (!preview) render(m); },
chatDelete: ({ id }) => { const i = real.findIndex(m => m.id === id); if (i >= 0) real.splice(i, 1); if (!preview) root.querySelector(`[data-id="${CSS.escape(id)}"]`)?.remove(); },
chatClear: ({ login }) => { for (let i = real.length - 1; i >= 0; i--) if (!login || real[i].login === login) real.splice(i, 1); if (!preview) [...root.children].forEach(el => { if (!login || el.dataset.login === login) el.remove(); }); },
chatPreview: p => setPreview(!!p?.on),
});
if (DEMO) { for (; demoN < 6; demoN++) render(demoChat(demoN)); setInterval(() => render(demoChat(demoN++)), 2200); }
</script></body></html>
27 changes: 27 additions & 0 deletions src/chat-preview.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Chat preview in the real sources: while on, every chat widget page plays the demo stream
// instead of the real chat. Ephemeral (never persisted) and stops by itself.

export const CHAT_PREVIEW_DEFAULT_SEC = 120;
export const CHAT_PREVIEW_MAX_SEC = 600;

export function createChatPreview(bus) {
let until = null, timer = null;
const snapshot = () => ({ on: until !== null, until });
const publish = () => bus.send('chatPreview', snapshot(), ['widget', 'panel']);
function stop() {
clearTimeout(timer); timer = null;
const was = until !== null;
until = null;
if (was) publish();
return snapshot();
}
function start(seconds = CHAT_PREVIEW_DEFAULT_SEC) {
clearTimeout(timer);
until = new Date(Date.now() + seconds * 1000).toISOString();
timer = setTimeout(stop, seconds * 1000);
timer.unref?.();
publish();
return snapshot();
}
return { start, stop, snapshot };
}
2 changes: 1 addition & 1 deletion src/events.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const REPLACEABLE_EVENTS = new Set([
// Eventos efímeros: sin persistencia y sin replay prometido.
export const EPHEMERAL_EVENTS = new Set([
'alert', 'publicAlert', 'chat', 'chatDelete', 'chatClear', 'chatResult',
'control', 'credits', 'say', 'gap', 'customOverlayTest', 'sceneSwitch',
'control', 'credits', 'say', 'gap', 'customOverlayTest', 'sceneSwitch', 'chatPreview',
]);

// Todos los eventos declarados: unión de ambos sets, en orden estable.
Expand Down
1 change: 1 addition & 0 deletions src/mcp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ tool('escribir_chat', 'Escribe un mensaje en tu chat con tu cuenta: Twitch, YouT
tool('youtube_conectar_cuenta', 'Devuelve el enlace para dar permiso a antena a escribir en tu chat de YouTube (ábrelo en el navegador del PC).', {}, () => post('/api/youtube/auth'));
tool('youtube_desconectar_cuenta', 'Quita el permiso de tu cuenta de YouTube.', {}, () => post('/api/youtube/logout'));
tool('simular_chat', 'Simula un mensaje de chat (útil para probar comandos y el widget de chat); no cuenta en las métricas. Los comandos pueden enviar respuestas al chat real si la plataforma está conectada.', { usuario: S.str('Nombre'), texto: S.str('Mensaje'), plataforma: S.enum('Plataforma', ['twitch', 'youtube']), mod: S.bool('Es moderador') }, ({ usuario, texto, plataforma, mod }) => post('/api/chat/simulate', { user: usuario, text: texto, platform: plataforma, mod }), ['texto']);
tool('vista_previa_chat', 'Hace que tus fuentes de chat en el programa de emisión (también variantes y huecos de overlays) reproduzcan los mensajes de ejemplo de la vista previa durante unos segundos (120 por defecto, máx. 600) y luego vuelvan al chat real. No se guarda nada en el chat ni en las métricas.', { activar: S.bool('true para empezar, false para parar'), segundos: S.num('Duración en segundos (1–600, opcional)') }, ({ activar, segundos }) => post('/api/chat/preview', segundos === undefined ? { on: activar } : { on: activar, seconds: segundos }), ['activar']);
tool('unir_chat', 'Lee el chat de otro canal de Twitch (vacío = el tuyo).', { canal: S.str('Canal de Twitch') }, ({ canal }) => post('/api/chat/join', { channel: canal }));

// widgets
Expand Down
12 changes: 11 additions & 1 deletion src/routes/chat.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
// chat), el helper id8 y la lista CHAT_TO de destinos. httpError se
// importa de src/http-util.mjs (se acepta por ctx por compatibilidad con los tests).
import { httpError as httpErrorBase, id8 as id8Base } from '../http-util.mjs';
import { CHAT_PREVIEW_MAX_SEC } from '../chat-preview.mjs';

// escribir en Twitch, YouTube o los dos (to: twitch | youtube | both; por defecto chat.sendTo)
const CHAT_TO = ['twitch', 'youtube', 'both'];

export function registerChatRoutes({ route, store, engine, twitch, youtube, chat, id8 = id8Base, httpError = httpErrorBase }) {
export function registerChatRoutes({ route, store, engine, twitch, youtube, chat, chatPreview, id8 = id8Base, httpError = httpErrorBase }) {
route('POST', '/api/chat/announce', async ({ text, color }) => ({ sent: await twitch.sendAnnouncement(text, color) }));

route('GET', '/api/chat', async (_, __, url) => engine.chat.slice(-(Number(url.searchParams.get('limit')) || 50)));
Expand Down Expand Up @@ -43,6 +44,15 @@ export function registerChatRoutes({ route, store, engine, twitch, youtube, chat
engine.handleChat({ id: 'sim:' + id8(), platform, user, login: String(user).toLowerCase(), text, parts: [{ t: text }], mod, owner, member, highlighted: !!highlighted, at: new Date().toISOString() });
return { ok: true };
});
// Preview in the real sources: they play the demo stream for `seconds` (default 120); nothing is stored.
route('GET', '/api/chat/preview', async () => chatPreview.snapshot());
route('POST', '/api/chat/preview', async ({ on, seconds } = {}) => {
if (typeof on !== 'boolean') throw httpError(400, 'vista previa: «on» debe ser true o false');
if (!on) return chatPreview.stop();
if (seconds !== undefined && (!Number.isInteger(seconds) || seconds < 1 || seconds > CHAT_PREVIEW_MAX_SEC))
throw httpError(400, `vista previa: «seconds» debe ser un entero entre 1 y ${CHAT_PREVIEW_MAX_SEC}`);
return chatPreview.start(seconds);
});
route('POST', '/api/chat/clear', async () => { engine.clearChatUser(null); return { ok: true }; });
route('POST', '/api/chat/join', async ({ channel }) => { await store.patchConfig({ chat: { twitchChannel: channel || '' } }); chat.join(channel || twitch.status.user); return chat.status; });
}
6 changes: 5 additions & 1 deletion src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { createScheduleCalendar, validScheduleCalendarToken } from './schedule-c
import { registerMediaRoutes, MAX_UPLOAD } from './routes/media.mjs';
import { registerInteractiveRoutes } from './routes/interactive.mjs';
import { registerChatRoutes } from './routes/chat.mjs';
import { createChatPreview } from './chat-preview.mjs';
import { registerGoalsRoutes } from './routes/goals.mjs';
import { registerFollowersRoutes } from './routes/followers.mjs';
import { registerChatVariantsRoutes } from './routes/chat-variants.mjs';
Expand Down Expand Up @@ -257,6 +258,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA |
};
session._applyRetention().catch(() => {}); // unclassified archives stay protected until reconciliation
const engine = new Engine({ store, bus, session, meld: program, twitch, youtube, log });
const chatPreview = createChatPreview(bus); // demo stream in the real chat sources (ephemeral)
// #132: barras de objetivo con el total real del canal (persisten entre directos)
const channelTotals = await new ChannelTotals({ dir: store.dir, twitch, youtube, log }).load();
const followers = await new FollowerRegistry({ dir: store.dir, twitch, youtube, log }).load();
Expand Down Expand Up @@ -1023,7 +1025,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA |
// estaban sus rutas: los patrones son coincidencia exacta, así que el orden relativo
// del resto de rutas se conserva. /api/chat/announce estaba antes de los interactivos
// y las rutas de Meld después de las de sesión: el orden de resolución no cambia.
registerChatRoutes({ route, store, engine, twitch, youtube, chat, id8 });
registerChatRoutes({ route, store, engine, twitch, youtube, chat, id8, chatPreview });
registerInteractiveRoutes({ route, store, interactive, isProjection });
registerViewersRoutes({ route, store, viewers });
registerTeleprompterRoutes({ route, teleprompter });
Expand Down Expand Up @@ -1326,6 +1328,8 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA |
if (customTheme) res.write(`event: customOverlayTheme\ndata: ${JSON.stringify(customOverlayThemeSnapshot())}\n\n`);
}
if (scene) res.write(`event: scene\ndata: ${JSON.stringify(onAirScenes())}\n\n`);
// A chat source or panel that connects during a chat preview joins it.
if ((kind === 'widget' || kind === 'panel') && chatPreview.snapshot().on) res.write(`event: chatPreview\ndata: ${JSON.stringify(chatPreview.snapshot())}\n\n`);
pushStatus();
};

Expand Down
Loading
Loading