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
2 changes: 1 addition & 1 deletion README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ En el panel, la página «Fuentes del programa de emisión» lista todas con su
| 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).
**Ú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`). Con **Mostrar** eliges «Este directo» (por defecto; empieza vacío en cada directo) o «Histórico» (`widgets.latest.scope: "all"`): el último apoyo de cada tipo de todos tus directos, guardado aparte de las sesiones; las alertas simuladas no cuentan. 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-<plataforma>`, `.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).

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ In the panel, the «Fuentes del programa de emisión» page lists all of them wi
| 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).
**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`). **Show** picks «This stream» (default; starts empty on every stream) or «All streams» (`widgets.latest.scope: "all"`): the last supporter of each type across all your streams, kept apart from sessions; simulated alerts do not count. 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).

**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`.

Expand Down
11 changes: 11 additions & 0 deletions app/src/panel/views/Widgets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export function Widget({ name }: { name: string }) {
let form: ReactNode = null;
if (name === 'latest') form = <>
<WField w="latest" f="label" label="Etiqueta" placeholder="Últimos (vacía = sin etiqueta)" />
<LatestScope />
<div className="lbl">Tipos de apoyo<div className="row field-ctl"><ListChecks w="latest" f="items" items={SUPPORT_TYPES} /></div></div>
<WField w="latest" f="css" label="CSS de «últimos»" type="css" placeholder=".item .big { font-size: 34px; }" />
<p className="css-help">Clases: <code>.root</code> <code>.root.col</code> <code>.label</code> <code>.item</code> <code>.item-{'<tipo>'}</code> <code>.item.empty</code> <code>.item.flash</code> <code>.kick</code> <code>.big</code> <code>.extra</code></p></>;
Expand Down Expand Up @@ -163,6 +164,16 @@ function SocialsSettings() {
</>;
}

function LatestScope() {
const scope = String(useLive(s => s.config.widgets.latest?.scope) || 'stream');
return <>
<label>Mostrar <select value={scope} onChange={e => patchWidgets({ latest: { scope: e.target.value } })}>
<option value="stream">Este directo</option><option value="all">Histórico</option>
</select></label>
<p className="hint">«Este directo» empieza vacío en cada directo. «Histórico» muestra el último apoyo de cada tipo de todos tus directos; las alertas simuladas no cuentan.</p>
</>;
}

function ThanksSettings() {
const window = useLive(s => s.config.widgets.thanks?.window || 'lastStream');
return <>
Expand Down
6 changes: 4 additions & 2 deletions public/widgets/latest.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,16 @@
function apply(s) {
const cfg = s.widgets?.latest || {};
setCss(cfg.css);
// scope «all» (#357): the last supporters of every stream; otherwise only this stream's.
const latest = cfg.scope === 'all' && s.latestAll ? s.latestAll : s.latest;
const items = (qs.get('items')?.split(',') || cfg.items || ['follow', 'sub', 'cheer', 'superchat']).filter(k => LABELS[k]);
// Optional label (widgets.latest.label): empty shows nothing.
root.innerHTML = (cfg.label ? `<p class="label">${esc(cfg.label)}</p>` : '') + items.map(k => {
const e = s.latest?.[k];
const e = latest?.[k];
const changed = e && prev[k] && prev[k] !== e.user + e.at;
return `<div class="item eg-card soft ${e ? '' : 'empty'} ${changed ? 'flash' : ''} item-${k}"><p class="kick">${LABELS[k]}</p><p class="big">${e ? esc(e.user) : '—'}</p>${e && extra(k, e) ? `<p class="extra">${esc(extra(k, e))}</p>` : ''}</div>`;
}).join('');
prev = Object.fromEntries(items.map(k => [k, s.latest?.[k] ? s.latest[k].user + s.latest[k].at : null]));
prev = Object.fromEntries(items.map(k => [k, latest?.[k] ? latest[k].user + latest[k].at : null]));
}
connect({ widgets: s => apply(DEMO ? { ...demoState(), widgets: s.widgets } : s) });
if (DEMO) apply(demoState());
Expand Down
3 changes: 2 additions & 1 deletion src/config-schema.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,8 @@ export const CONFIG_SCHEMA = {
chat: CHAT_FIELDS,
chatVariants: CHAT_VARIANTS,
goals: list(GOAL_BOX),
latest: { items: arrStr(SUPPORT_TYPES), label: str, css: str },
// scope (#357): «stream» = this stream's last supporters; «all» = the last ones of every stream.
latest: { items: arrStr(SUPPORT_TYPES), label: str, scope: en(['stream', 'all']), css: str },
// items is optional: without it the ticker shows the «Últimos» types.
ticker: { label: str, items: arrStr(SUPPORT_TYPES), count: num({ int: true, min: 1, max: 100 }), speed: num({ int: true, min: 10, max: 500 }), css: str },
credits: { title: str, subtitle: str, speed: num({ int: true, min: 10, max: 500 }), css: str },
Expand Down
5 changes: 3 additions & 2 deletions src/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class Engine extends EventEmitter {
const clean = cleanVars(vars, this.config.filters);
const a = buildAlert(type, clean, this.config);
if (!a) return null;
this.session.record(a);
this.session.record(a, { simulated: String(externalId || '').startsWith('sim:') });
this.log(`[alerta] ${type}${a.variation ? ' (' + a.variation.name + ')' : ''} · ${a.text}`);
return this.deliver(a);
}
Expand Down Expand Up @@ -614,7 +614,8 @@ export class Engine extends EventEmitter {
bars: (g.bars || []).map(b => ({ ...b, value: s.goalValue(b.metric, b.platform), source: isTotalMetric(b.metric, b.platform) ? 'channel' : 'session' })),
}));
return {
totals: s.totals(), latest: s.latest(), goals,
// #357: latestAll = last supporters of every stream; latest stays per stream for every consumer.
totals: s.totals(), latest: s.latest(), latestAll: this.latestHistory ? this.latestHistory.snapshot() : s.latest(), goals,
recent: s.data.events.filter(e => !ALERT_TYPES[e.type]?.system).slice(-30).reverse().map(e => ({ type: e.type, label: ALERT_TYPES[e.type]?.label || e.type, user: e.user, sub: e.sub, at: e.at })),
credits: s.credits(), session: { id: s.data.id, title: s.data.title, startedAt: s.data.startedAt },
thanks: this.thanksState?.() ?? { names: [], anonymous: 0 },
Expand Down
89 changes: 89 additions & 0 deletions src/latest-history.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// #357: the last supporter of each «Últimos» type across all streams, kept apart from sessions.
// One entry per type (bounded size), updated with every real event and never cleared when a
// stream starts. Simulated alerts are tests and never enter it.
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { isSystemType } from './alerts.mjs';
import { writeJson } from './json-file.mjs';

export const LATEST_FILE = 'latest-history.json';
// Same grouping as the per-stream «Últimos» (Session#latest).
export const LATEST_GROUPS = {
follow: ['follow', 'ytsub'], sub: ['sub', 'resub', 'giftsub'], cheer: ['cheer'], raid: ['raid'],
superchat: ['superchat', 'supersticker'], member: ['member', 'milestone', 'giftmember'],
};
export const LATEST_KEYS = [...Object.keys(LATEST_GROUPS), 'any'];

/** «Últimos» keys an event type counts for. */
export const latestKeys = type => [
...Object.keys(LATEST_GROUPS).filter(k => LATEST_GROUPS[k].includes(type)),
...(type && !isSystemType(type) ? ['any'] : []),
];

/** Last event of each «Últimos» type in a list ordered oldest first. */
export function latestOf(events = []) {
const out = Object.fromEntries(LATEST_KEYS.map(k => [k, null]));
for (const e of events) for (const k of latestKeys(e?.type)) out[k] = e;
return out;
}

const validEntry = e => !!e && typeof e === 'object' && typeof e.type === 'string' && typeof e.at === 'string';

export class LatestHistory {
constructor({ dir, write = writeJson, log = () => {} } = {}) {
this.file = path.join(dir, LATEST_FILE);
this.write = write; this.log = log;
this.entries = Object.fromEntries(LATEST_KEYS.map(k => [k, null]));
this.loaded = false;
this.writing = Promise.resolve();
}

async load() {
try {
const data = JSON.parse(await readFile(this.file, 'utf8'));
for (const k of LATEST_KEYS) this.entries[k] = validEntry(data?.entries?.[k]) ? data.entries[k] : null;
this.loaded = true;
} catch (err) {
if (err?.code !== 'ENOENT') this.log(`[últimos] no se pudo leer ${LATEST_FILE}: ${err.message}; se reconstruye`);
this.loaded = false;
}
return this;
}

/** True when there is no saved record yet (first run or unreadable): rebuild it from the archives. */
get needsBackfill() { return !this.loaded; }

#apply(ev) {
if (!validEntry(ev) || ev.simulated) return false;
let changed = false;
for (const k of latestKeys(ev.type)) {
const cur = this.entries[k];
if (!cur || ev.at >= cur.at) { this.entries[k] = { ...ev }; changed = true; }
}
return changed;
}

/** A new real event: keep it when it is the newest of its types. */
observe(ev) {
const changed = this.#apply(ev);
if (changed) this.save();
return changed;
}

/** Several events (backfill, imported streams): newest wins, one write. */
merge(events = []) {
for (const ev of events) this.#apply(ev);
this.loaded = true;
return this.save();
}

snapshot() { return { ...this.entries }; }

save() {
const data = { version: 1, entries: this.entries };
this.writing = this.writing.then(() => this.write(this.file, data)).catch(err => this.log(`[últimos] no se pudo guardar ${LATEST_FILE}: ${err.message}`));
return this.writing;
}

flush() { return this.writing; }
}
2 changes: 1 addition & 1 deletion src/mcp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ tool('ver_widgets', 'Configuración y datos de los widgets (chat y sus variantes
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=<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 · 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.',
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), scope (stream = este directo | all = histórico de todos los directos), 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']);
Expand Down
2 changes: 1 addition & 1 deletion src/routes/widgets.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function registerWidgetRoutes({ route, store, engine }) {
if (error) throw httpError(400, error.message);
}
// Support types and the «Últimos» label are new fields: validate only them, keep the legacy merge for the rest.
for (const [name, field] of [['latest', 'items'], ['latest', 'label'], ['ticker', 'items']]) {
for (const [name, field] of [['latest', 'items'], ['latest', 'label'], ['latest', 'scope'], ['ticker', 'items']]) {
if (!patch[name] || typeof patch[name] !== 'object' || !Object.hasOwn(patch[name], field)) continue;
const [error] = validatePath(`widgets.${name}.${field}`, patch[name][field]);
if (error) throw httpError(400, error.message);
Expand Down
Loading
Loading