Skip to content
Open
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
1 change: 1 addition & 0 deletions src/generators/jsx-ast/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default {

defaultConfiguration: {
ref: 'main',
remoteConfig: 'https://nodejs.org/site.json',
},

/**
Expand Down
11 changes: 9 additions & 2 deletions src/generators/jsx-ast/utils/buildContent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,14 @@ export const createDocumentLayout = (
sideBarProps,
metaBarProps,
remark
) =>
createTree('root', [
) => {
const config = getConfig('jsx-ast');

return createTree('root', [
createJSXElement(JSX_IMPORTS.AnnouncementBanner.name, {
remoteConfig: config.remoteConfig,
versionMajor: config.version?.major ?? null,
}),
createJSXElement(JSX_IMPORTS.NavBar.name),
createJSXElement(JSX_IMPORTS.Article.name, {
children: [
Expand All @@ -308,6 +314,7 @@ export const createDocumentLayout = (
],
}),
]);
};

/**
* @typedef {import('estree').Node & { data: ApiDocMetadataEntry }} JSXContent
Expand Down
4 changes: 4 additions & 0 deletions src/generators/web/constants.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export const ROOT = dirname(fileURLToPath(import.meta.url));
* An object containing mappings for various JSX components to their import paths.
*/
export const JSX_IMPORTS = {
AnnouncementBanner: {
name: 'AnnouncementBanner',
source: resolve(ROOT, './ui/components/AnnouncementBanner'),
},
NavBar: {
name: 'NavBar',
source: resolve(ROOT, './ui/components/NavBar'),
Expand Down
1 change: 1 addition & 0 deletions src/generators/web/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type Generator = GeneratorMetadata<
templatePath: string;
title: string;
imports: Record<string, string>;
remoteConfig: string;
},
Generate<Array<JSXContent>, AsyncGenerator<{ html: string; css: string }>>
>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { fetchBanners } from '../fetchBanners.mjs';

const PAST = new Date(Date.now() - 86_400_000).toISOString(); // yesterday
const FUTURE = new Date(Date.now() + 86_400_000).toISOString(); // tomorrow

const makeResponse = (banners, ok = true) => ({
ok,
json: async () => ({ websiteBanners: banners }),
});

describe('fetchBanners', () => {
describe('fetch behavior', () => {
it('fetches from the given URL', async t => {
t.mock.method(global, 'fetch', () => Promise.resolve(makeResponse({})));

await fetchBanners('https://example.com/site.json', null);

assert.equal(global.fetch.mock.calls.length, 1);
assert.equal(
global.fetch.mock.calls[0].arguments[0],
'https://example.com/site.json'
);
});

it('returns an empty array on non-ok response', async t => {
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({}, false))
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, []);
});

it('propagates fetch errors to the caller', async t => {
t.mock.method(global, 'fetch', () =>
Promise.reject(new Error('Network error'))
);

await assert.rejects(
() => fetchBanners('https://example.com/site.json', null),
{ message: 'Network error' }
);
});
});

describe('banner selection', () => {
it('returns the active global (index) banner', async t => {
const banner = { text: 'Global banner', type: 'warning' };
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({ index: banner }))
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, [banner]);
});

it('returns the active version-specific banner', async t => {
const banner = { text: 'v20 banner', type: 'warning' };
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({ v20: banner }))
);

const result = await fetchBanners('https://example.com/site.json', 20);

assert.deepEqual(result, [banner]);
});

it('returns both global and version banners when both are active', async t => {
const globalBanner = { text: 'Global banner', type: 'warning' };
const versionBanner = { text: 'v20 banner', type: 'error' };
t.mock.method(global, 'fetch', () =>
Promise.resolve(
makeResponse({ index: globalBanner, v20: versionBanner })
)
);

const result = await fetchBanners('https://example.com/site.json', 20);

assert.deepEqual(result, [globalBanner, versionBanner]);
});

it('returns global banner first, version banner second', async t => {
const globalBanner = { text: 'Global', type: 'warning' };
const versionBanner = { text: 'v22', type: 'error' };
t.mock.method(global, 'fetch', () =>
Promise.resolve(
makeResponse({ index: globalBanner, v22: versionBanner })
)
);

const result = await fetchBanners('https://example.com/site.json', 22);

assert.equal(result[0], globalBanner);
assert.equal(result[1], versionBanner);
});

it('does not include the version banner when versionMajor is null', async t => {
const globalBanner = { text: 'Global banner', type: 'warning' };
const versionBanner = { text: 'v20 banner', type: 'error' };
t.mock.method(global, 'fetch', () =>
Promise.resolve(
makeResponse({ index: globalBanner, v20: versionBanner })
)
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, [globalBanner]);
});

it('returns an empty array when websiteBanners is absent', async t => {
t.mock.method(global, 'fetch', () =>
Promise.resolve({ ok: true, json: async () => ({}) })
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, []);
});
});

describe('date filtering', () => {
it('excludes a banner whose endDate has passed', async t => {
const banner = { text: 'Expired', type: 'warning', endDate: PAST };
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({ index: banner }))
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, []);
});

it('excludes a banner whose startDate is in the future', async t => {
const banner = { text: 'Upcoming', type: 'warning', startDate: FUTURE };
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({ index: banner }))
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, []);
});

it('includes a banner within its active date range', async t => {
const banner = {
text: 'Active',
type: 'warning',
startDate: PAST,
endDate: FUTURE,
};
t.mock.method(global, 'fetch', () =>
Promise.resolve(makeResponse({ index: banner }))
);

const result = await fetchBanners('https://example.com/site.json', null);

assert.deepEqual(result, [banner]);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/** @import { BannerEntry, RemoteConfig } from './types.d.ts' */

import { isBannerActive } from '../../utils/banner.mjs';

/**
* Fetches and returns active banners for the given version from the remote config.
* Returns an empty array on any fetch or parse failure.
*
* @param {string} remoteConfig
* @param {number | null} versionMajor
* @returns {Promise<BannerEntry[]>}
*/
export const fetchBanners = async (remoteConfig, versionMajor) => {
const res = await fetch(remoteConfig, { signal: AbortSignal.timeout(2500) });

if (!res.ok) {
return [];
}

/** @type {RemoteConfig} */
const config = await res.json();

const active = [];

const globalBanner = config.websiteBanners?.index;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can have config.websiteBanners?.index and config.websiteBanners?.all, not sure which one to use here

if (globalBanner && isBannerActive(globalBanner)) {
active.push(globalBanner);
}

if (versionMajor != null) {
const versionBanner = config.websiteBanners?.[`v${versionMajor}`];
if (versionBanner && isBannerActive(versionBanner)) {
active.push(versionBanner);
}
}

return active;
};
49 changes: 49 additions & 0 deletions src/generators/web/ui/components/AnnouncementBanner/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ArrowUpRightIcon } from '@heroicons/react/24/outline';
import Banner from '@node-core/ui-components/Common/Banner';
import { useEffect, useState } from 'preact/hooks';

import { fetchBanners } from './fetchBanners.mjs';

/** @import { BannerEntry } from './types.d.ts' */

/**
* Asynchronously fetches and displays announcement banners from the remote config.
* Global banners are rendered above version-specific ones.
* Non-blocking: silently ignores fetch/parse failures.
*
* @param {{ remoteConfig: string, versionMajor: number | null }} props
*/
export default ({ remoteConfig, versionMajor }) => {
const [banners, setBanners] = useState(/** @type {BannerEntry[]} */ ([]));

useEffect(() => {
if (!remoteConfig) {
return;
}

fetchBanners(remoteConfig, versionMajor)
.then(setBanners)
.catch(console.error);
}, []);

if (!banners.length) {
return null;
}

return (
<div role="region" aria-label="Announcements">
{banners.map(banner => (
<Banner key={banner.text ?? banner.text} type={banner.type}>
{banner.link ? (
<a href={banner.link} target="_blank" rel="noopener noreferrer">
{banner.text}
</a>
) : (
banner.text
)}
{banner.link && <ArrowUpRightIcon />}
</Banner>
))}
</div>
);
};
13 changes: 13 additions & 0 deletions src/generators/web/ui/components/AnnouncementBanner/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { BannerProps } from '@node-core/ui-components/Common/Banner';

export type BannerEntry = {
startDate?: string;
endDate?: string;
text: string;
link?: string;
type?: BannerProps['type'];
};

export type RemoteConfig = {
websiteBanners?: Record<string, BannerEntry | undefined>;
};
63 changes: 63 additions & 0 deletions src/generators/web/ui/utils/__tests__/banner.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { isBannerActive } from '../banner.mjs';

const PAST = new Date(Date.now() - 86_400_000).toISOString(); // yesterday
const FUTURE = new Date(Date.now() + 86_400_000).toISOString(); // tomorrow

const banner = (overrides = {}) => ({
text: 'Test banner',
...overrides,
});

describe('isBannerActive', () => {
describe('no startDate, no endDate', () => {
it('is always active', () => {
assert.equal(isBannerActive(banner()), true);
});
});

describe('startDate only', () => {
it('is active when startDate is in the past', () => {
assert.equal(isBannerActive(banner({ startDate: PAST })), true);
});

it('is not active when startDate is in the future', () => {
assert.equal(isBannerActive(banner({ startDate: FUTURE })), false);
});
});

describe('endDate only', () => {
it('is active when endDate is in the future', () => {
assert.equal(isBannerActive(banner({ endDate: FUTURE })), true);
});

it('is not active when endDate is in the past', () => {
assert.equal(isBannerActive(banner({ endDate: PAST })), false);
});
});

describe('startDate and endDate', () => {
it('is active when now is within the range', () => {
assert.equal(
isBannerActive(banner({ startDate: PAST, endDate: FUTURE })),
true
);
});

it('is not active when now is before the range', () => {
assert.equal(
isBannerActive(banner({ startDate: FUTURE, endDate: FUTURE })),
false
);
});

it('is not active when now is after the range', () => {
assert.equal(
isBannerActive(banner({ startDate: PAST, endDate: PAST })),
false
);
});
});
});
Loading
Loading