Hold Cockpit regional news to the last 24 hours, and tell its states apart

Regional News showed "REGIONAL NEWS UNAVAILABLE" above populated rows and a
static "RECENT" footer over months-old articles. The status banner kept
`display: grid` when hidden, every non-empty answer carried the unavailable
text, and nothing limited or sorted articles by age.

- One window (regionalNewsWindow.js, 24 h): the local proxy asks Google News
  with `when:1d` and GDELT for 24 h, drops undated, older or future-dated
  articles, sorts newest first, and reports newsWindowHours/newsFetchedAt.
- The Cockpit labels four states: fresh (banner hidden, "LAST 24 H"),
  kept after a failed refresh ("CACHED · REFRESH FAILED"), no news in the
  window, and unavailable. The footer lives in the news state, so it
  survives page and tab changes, and the client drops out-of-window rows.
- `.cockpit-brief-status[hidden]` now hides the banner.
This commit is contained in:
Denis Groshev committed 2026-11-06 00:45:19 +01:00
1 parent 2470b39f88
commit dd83812a21
24 files changed
+637 -85

No files matched your search

+23 -3
View File
@@ -1,9 +1,29 @@
/**
* The Cockpit briefing's pages and the state it starts in. It needs only the
* i18n module, so the controller and the view can both read it.
* i18n module and the regional-news window, so the controller and the view
* can both read it.
*/
import { REGIONAL_NEWS_WINDOW_HOURS } from '../data/regionalNewsWindow.js';
import { msg, t } from '../i18n/index.js';
// i18n-ignore: provider name
/** The news feed named before any briefing has answered. */
export const DEFAULT_NEWS_SOURCE = 'GOOGLE NEWS RSS';
/**
* The Regional News footer for a fresh, empty or unavailable list: the feed
* and the window its articles are held to.
* @param {string} [source]
* @param {number} [hours]
* @returns {string}
*/
export function newsWindowFooter(
source = DEFAULT_NEWS_SOURCE,
hours = REGIONAL_NEWS_WINDOW_HOURS,
) {
return t('{source} · LAST {hours} H', { source, hours });
}
export const COCKPIT_BRIEF_PAGES = [
{
id: 'signals',
@@ -15,8 +35,7 @@ export const COCKPIT_BRIEF_PAGES = [
id: 'news',
kickerKey: msg('REGIONAL NEWS'),
subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'),
sourceKey: msg('{source} · LOCATION QUERY · RECENT'),
sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name
// The news footer comes from the news state (`news.footer`), not here.
},
{
id: 'local',
@@ -60,6 +79,7 @@ export function createBriefState() {
statusHidden: false,
state: null,
status: t('ACQUIRING REGIONAL NEWS'),
footer: newsWindowFooter(),
articles: [],
},
local: {
+101 -20
View File
@@ -12,7 +12,14 @@ import {
COCKPIT_BRIEF_PAGES,
CYCLE_HELP_KEYS,
createBriefState,
newsWindowFooter,
} from './cockpitBriefPages.js';
import {
recentRegionalArticles,
regionalNewsWindowHours,
} from '../data/regionalNewsWindow.js';
const NEWS_ROWS = 4;
// regionalModel.weatherCodeLabel is shared with node code and returns
// English; translate it here.
@@ -52,9 +59,13 @@ export function showBriefPage(index, { manual = false } = {}) {
kicker: t(page.kickerKey),
subtitle: t(page.subtitleKey),
position: `${this.briefPageIndex + 1} / ${count}`,
source: page.sourceKey
? t(page.sourceKey, { source: page.sourceName })
: page.source,
// The news footer follows the news state, so it survives page changes.
source:
page.id === 'news'
? this.brief.news.footer
: page.sourceKey
? t(page.sourceKey)
: page.source,
});
this.publishBriefView();
if (manual && this.briefAutoRotateEnabled)
@@ -196,8 +207,8 @@ export function maybeRefreshRegionalBrief(info) {
subjectId !== this.regionalBriefSubjectId
)
return;
this.regionalBrief = payload;
this.renderRegionalBrief(payload, info);
this.regionalBrief = withCachedNews(payload, this.regionalBrief);
this.renderRegionalBrief(this.regionalBrief, info);
})
.catch((error) => {
if (
@@ -206,7 +217,11 @@ export function maybeRefreshRegionalBrief(info) {
requestToken === this.regionalBriefRequestToken &&
subjectId === this.regionalBriefSubjectId
) {
this.renderRegionalBriefStatus('unavailable', info);
if (this.regionalBrief) {
const previous = this.regionalBrief;
this.regionalBrief = cachedNews(previous, previous);
this.renderRegionalBrief(this.regionalBrief, info);
} else this.renderRegionalBriefStatus('unavailable', info);
}
})
.finally(() => {
@@ -215,6 +230,75 @@ export function maybeRefreshRegionalBrief(info) {
});
}
/**
* A brief whose news comes from `previous` after a refresh that brought none:
* the earlier articles stay, marked `cached` so they are labelled as such.
* @param {object} payload The brief to keep everything else from.
* @param {object} previous The last brief rendered for this subject.
*/
function cachedNews(payload, previous) {
return {
...payload,
newsStatus: 'cached',
newsSource: previous.newsSource,
newsWindowHours: previous.newsWindowHours,
newsFetchedAt: previous.newsFetchedAt ?? previous.retrievedAt ?? null,
articles: previous.articles,
};
}
// A refresh whose news read failed keeps the articles from before it.
function withCachedNews(payload, previous) {
return previous && payload?.newsStatus === 'unavailable'
? cachedNews(payload, previous)
: payload;
}
/**
* The Regional News state a brief presents. `ready` and `cached` have rows
* inside the window; `cached` is a refresh that failed (a client-side failure,
* or the local proxy's `stale` answer). `empty` is a source that answered with
* nothing in the window; anything else is `unavailable`.
* @returns {{state: string, status: string, footer: string, articles: object[]}}
*/
function regionalNewsView(payload) {
const hours = regionalNewsWindowHours(payload?.newsWindowHours);
// Old caches and the local path are held to the window here too.
const articles = recentRegionalArticles(payload?.articles, {
windowHours: hours,
limit: NEWS_ROWS,
});
const source = String(
payload?.newsSource || t('REGIONAL NEWS'),
).toUpperCase();
const refreshFailed =
payload?.newsStatus === 'cached' || payload?.status === 'stale';
if (articles.length && refreshFailed)
return {
state: 'cached',
status: t('CACHED · REFRESH FAILED'),
footer: t('{source} · CACHED {age}', {
source,
age: formatCockpitBriefAge(
payload?.newsFetchedAt ?? payload?.retrievedAt,
),
}),
articles,
};
const answered =
!refreshFailed && ['ready', 'empty'].includes(payload?.newsStatus);
return {
state: articles.length ? 'ready' : answered ? 'empty' : 'unavailable',
status: articles.length
? ''
: answered
? t('NO NEWS IN THE LAST {hours} H', { hours })
: t('REGIONAL NEWS UNAVAILABLE'),
footer: newsWindowFooter(source, hours),
articles,
};
}
export function renderRegionalBriefStatus(status, info) {
const { news, local } = this.brief;
news.statusHidden = false;
@@ -223,7 +307,10 @@ export function renderRegionalBriefStatus(status, info) {
status === 'loading'
? t('ACQUIRING REGIONAL NEWS')
: t('REGIONAL NEWS UNAVAILABLE');
if (status === 'unavailable') news.articles = [];
news.footer = newsWindowFooter();
// Only called with no brief for this subject: any rows are another's.
news.articles = [];
if (this.briefPageIndex === 1) this.brief.source = news.footer;
if (status === 'loading') local.place = t('RESOLVING REGION');
if (status === 'unavailable') local.place = t('REGION UNAVAILABLE');
local.coordinates = localCoordinates(info);
@@ -231,7 +318,7 @@ export function renderRegionalBriefStatus(status, info) {
}
export function renderRegionalBrief(payload, info) {
const articles = Array.isArray(payload?.articles) ? payload.articles : [];
const { state, status, footer, articles } = regionalNewsView(payload);
const seen = new Map();
const storyKey = (url) => {
const count = seen.get(url) ?? 0;
@@ -244,13 +331,11 @@ export function renderRegionalBrief(payload, info) {
const placeLabel =
payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE');
this.brief.news = {
statusHidden: articles.length > 0,
state: payload?.newsStatus || 'unavailable',
status:
payload?.newsStatus === 'empty'
? t('NO RECENT LOCATION MATCHES')
: t('REGIONAL NEWS UNAVAILABLE'),
articles: articles.slice(0, 4).map((article) => ({
statusHidden: state === 'ready',
state,
status,
footer,
articles: articles.map((article) => ({
// A row keeps its node, and so its focus, only for the same story.
key: storyKey(article.url),
url: article.url,
@@ -284,11 +369,7 @@ export function renderRegionalBrief(payload, info) {
: '—',
};
this.brief.regionalStatus = payload?.status || 'partial';
if (this.briefPageIndex === 1) {
this.brief.source = t('{source} · LOCATION QUERY', {
source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(),
});
}
if (this.briefPageIndex === 1) this.brief.source = footer;
this.publishBriefView();
this.scheduleContextLayout();
}
+235 -14
View File
@@ -3,11 +3,14 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createPinia } from 'pinia';
import { createApp, nextTick } from 'vue';
import { setLocale } from '../i18n/index.js';
import { createBriefState } from './cockpitBriefPages.js';
import {
maybeRefreshRegionalBrief,
publishBriefView,
renderRegionalBrief,
renderRegionalBriefStatus,
@@ -88,10 +91,7 @@ test('pages, the cycle toggle and the source follow the controller', async (t) =
await nextTick();
assert.equal(text('#cockpit-brief-kicker'), 'REGIONAL NEWS');
assert.equal(text('#cockpit-brief-position'), '2 / 3');
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
assert.deepEqual(visiblePages(), ['news']);
assert.deepEqual(current(), ['false', 'true', 'false']);
assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'news');
@@ -129,7 +129,8 @@ test('regional news and local conditions render what the region returned', async
url: `https://example.com/${index}`,
title: `Story ${index}`,
domain: 'example.com',
publishedAt: new Date().toISOString(),
// Newest first is the shown order, so Story 0 is the newest.
publishedAt: new Date(Date.now() - index * 60_000).toISOString(),
})),
weather: {
temperatureC: 21.6,
@@ -159,7 +160,7 @@ test('regional news and local conditions render what the region returned', async
assert.equal(text('#cockpit-local-condition'), 'RAIN');
assert.equal(text('#cockpit-local-cloud'), 'CLOUD 40%');
assert.equal(text('#cockpit-local-precipitation'), '1.3');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
assert.equal($('#cockpit-signal-stream').dataset.regionalStatus, 'ok');
renderRegionalBriefStatus.call(owner, 'unavailable', {});
await nextTick();
@@ -210,26 +211,246 @@ test('a refreshed news list keeps a focused story on its own link', async (t) =>
assert.equal($('#cockpit-news-list').textContent.includes('Story y'), true);
});
test('the news source names the feed only while it is current on page 2', async (t) => {
// This contract changed on purpose: the footer used to fall back to a
// static "· RECENT" on every page change, which promised nothing. It now
// follows the news state and names the window it holds articles to.
test('the news footer follows the news state across page changes, not a static RECENT', async (t) => {
const { text, owner } = fixture(t);
showBriefPage.call(owner, 1);
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
renderRegionalBrief.call(
owner,
{ newsStatus: 'ready', newsSource: 'wire', newsWindowHours: 24, articles: [story('a')] },
INFO,
);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
showBriefPage.call(owner, 2);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(
text('#cockpit-brief-source'),
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
);
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
showBriefPage.call(owner, 0);
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
renderRegionalBrief.call(
owner,
{ newsStatus: 'ready', newsSource: 'wire', newsWindowHours: 12, articles: [story('a')] },
INFO,
);
await nextTick();
// Off page 2 the footer is the current page's.
assert.equal(
text('#cockpit-brief-source'),
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 12 H');
});
test('the news banner is hidden by the stylesheet, not only by the attribute', async (t) => {
// happy-dom applies no author CSS by itself, so `hidden` alone proves
// nothing: `.cockpit-brief-status { display: grid }` used to beat it.
const css = readFileSync(
fileURLToPath(new URL('./styles/cockpit.css', import.meta.url)),
'utf8',
);
assert.match(css, /\.cockpit-brief-status\[hidden\]\s*\{\s*display:\s*none;?\s*\}/);
const { $, owner } = fixture(t);
const style = document.head.appendChild(document.createElement('style'));
t.after(() => style.remove());
style.textContent = css;
showBriefPage.call(owner, 1);
renderRegionalBrief.call(owner, { newsStatus: 'ready', articles: [story('a')] }, INFO);
await nextTick();
const banner = $('#cockpit-news-status');
assert.equal(banner.hidden, true);
assert.equal(getComputedStyle(banner).display, 'none');
renderRegionalBrief.call(owner, { newsStatus: 'empty', articles: [] }, INFO);
await nextTick();
assert.equal(getComputedStyle(banner).display, 'grid');
});
const hoursAgo = (hours) => new Date(Date.now() - hours * 3_600_000).toISOString();
test('ready, cached, empty and unavailable each label the news differently', async (t) => {
const { $, text, owner } = fixture(t);
showBriefPage.call(owner, 1);
const rows = () =>
[...document.querySelectorAll('#cockpit-news-list strong')].map((row) => row.textContent);
const banner = () => ({
hidden: $('#cockpit-news-status').hidden,
state: $('#cockpit-news-status').dataset.state,
text: text('#cockpit-news-status'),
});
const ready = {
status: 'ready',
newsStatus: 'ready',
newsSource: 'Google News RSS',
newsWindowHours: 24,
newsFetchedAt: hoursAgo(0.5),
articles: [story('a'), story('b')],
};
renderRegionalBrief.call(owner, ready, INFO);
await nextTick();
assert.equal(banner().hidden, true);
assert.equal(banner().state, 'ready');
assert.deepEqual(rows(), ['Story a', 'Story b']);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
// The local proxy's stale answer is a refresh that failed.
renderRegionalBrief.call(owner, { ...ready, status: 'stale' }, INFO);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'cached',
text: 'CACHED · REFRESH FAILED',
});
assert.deepEqual(rows(), ['Story a', 'Story b']);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 30M AGO');
renderRegionalBrief.call(
owner,
{ ...ready, newsStatus: 'empty', newsSource: 'Google News RSS', articles: [] },
INFO,
);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'empty',
text: 'NO NEWS IN THE LAST 24 H',
});
assert.deepEqual(rows(), []);
renderRegionalBrief.call(
owner,
{ ...ready, newsStatus: 'unavailable', newsSource: null, articles: [] },
INFO,
);
await nextTick();
assert.deepEqual(banner(), {
hidden: false,
state: 'unavailable',
text: 'REGIONAL NEWS UNAVAILABLE',
});
assert.deepEqual(rows(), []);
});
test('articles outside the window are dropped even when a server sends them', async (t) => {
const { $, text, owner } = fixture(t);
showBriefPage.call(owner, 1);
const dated = (id, publishedAt) => ({ ...story(id), publishedAt });
// The reported case: 4, 104, 215 and 165 days old under "RECENT".
renderRegionalBrief.call(
owner,
{
newsStatus: 'ready',
articles: [
dated('old', hoursAgo(4 * 24)),
dated('older', hoursAgo(104 * 24)),
dated('undated', null),
dated('one', hoursAgo(20)),
dated('two', hoursAgo(2)),
],
},
INFO,
);
await nextTick();
assert.deepEqual(
[...document.querySelectorAll('#cockpit-news-list strong')].map((row) => row.textContent),
['Story two', 'Story one'],
);
assert.equal($('#cockpit-news-status').hidden, true);
renderRegionalBrief.call(
owner,
{ newsStatus: 'ready', articles: [dated('old', hoursAgo(25))] },
INFO,
);
await nextTick();
assert.equal(document.querySelectorAll('#cockpit-news-list li').length, 0);
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
});
test('a failed refresh keeps the earlier articles as cached, and clears only when there are none', async (t) => {
const { $, text, owner } = fixture(t);
const answers = [];
Object.assign(owner, {
active: true,
regionalBriefSubjectId: null,
regionalBriefAbort: null,
regionalBriefRequestToken: 0,
regionalBriefFetchedAt: 0,
regionalBrief: null,
renderRegionalBrief,
renderRegionalBriefStatus,
});
owner.services = {
...owner.services,
regionalDistanceM: () => 0,
fetchRegionalBrief: () => answers.shift()(),
};
const refresh = async (answer, info = { ...INFO, icao24: 'abc123' }) => {
answers.push(answer);
owner.regionalBriefFetchedAt = 0;
maybeRefreshRegionalBrief.call(owner, info);
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
};
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
showBriefPage.call(owner, 1);
// No earlier brief: an error clears and says unavailable.
await refresh(() => Promise.reject(new Error('503')));
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
assert.equal(rows(), 0);
const fetchedAt = hoursAgo(1);
await refresh(() =>
Promise.resolve({
status: 'ready',
newsStatus: 'ready',
newsSource: 'Google News RSS',
newsWindowHours: 24,
newsFetchedAt: fetchedAt,
articles: [story('a'), story('b')],
}),
);
assert.equal($('#cockpit-news-status').hidden, true);
assert.equal(rows(), 2);
// A network failure keeps the rows and says so, with their age.
await refresh(() => Promise.reject(new TypeError('Failed to fetch')));
assert.equal($('#cockpit-news-status').hidden, false);
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
assert.equal(rows(), 2);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 1H AGO');
showBriefPage.call(owner, 2);
showBriefPage.call(owner, 1);
await nextTick();
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · CACHED 1H AGO');
// So does a brief whose news read failed while weather answered.
await refresh(() =>
Promise.resolve({ status: 'partial', newsStatus: 'unavailable', articles: [] }),
);
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
assert.equal(rows(), 2);
// A successful refresh clears the cached label; a true empty clears rows.
await refresh(() =>
Promise.resolve({ status: 'ready', newsStatus: 'empty', newsSource: 'Google News RSS', articles: [] }),
);
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
assert.equal(rows(), 0);
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
// Another aircraft never inherits the last one's rows.
await refresh(() => Promise.resolve({ newsStatus: 'ready', articles: [story('c')] }));
assert.equal(rows(), 1);
await refresh(
() => Promise.reject(new Error('503')),
{ ...INFO, icao24: 'def456' },
);
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
assert.equal(rows(), 0);
});
test('an unchanged position publishes nothing new', (t) => {
+7 -1
View File
@@ -1818,7 +1818,13 @@ html:not([lang='en']) #cockpit-brief-auto {
letter-spacing: 0.13em;
text-align: center;
}
.cockpit-brief-status[data-state='unavailable'] {
/* `display: grid` above would otherwise beat the UA [hidden] rule and keep a
stale banner over a populated list. */
.cockpit-brief-status[hidden] {
display: none;
}
.cockpit-brief-status[data-state='unavailable'],
.cockpit-brief-status[data-state='cached'] {
color: #d5a863;
}
.cockpit-local-place {