Source code
Revision control
Copy as Markdown
Other Tools
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
import {
hasContentAreaWidgets,
isWidgetEnabled,
isWidgetInSidebar,
isWidgetsContainerVisible,
parsePinnedWidgetIds,
WIDGET_REGISTRY,
} from "./WidgetsRegistry.mjs";
/**
* Newtab page layout variants. "Page layout" is the arrangement of the whole
* newtab page, not a DiscoveryStream layout (see SectionsLayoutFeed and
* selectLayoutRender, which are unrelated).
*
* The pref holds the layout's name rather than a set of feature booleans, so a
* new layout is a new value here instead of a new pref, class prefix and metric.
* The value is what newtab.page_layout_variant reports.
*/
export const PAGE_LAYOUT_VARIANTS = {
NOVA_FULL_WIDTH: "nova-full-width",
SIDE_BY_SIDE_CONTENT_LEAD: "side-by-side-content-lead",
SIDE_BY_SIDE_WIDGETS_LEAD: "side-by-side-widgets-lead",
SIDE_BY_SIDE_CONTENT_LEAD_FIVE: "side-by-side-content-lead-five",
SIDE_BY_SIDE_WIDGETS_LEAD_FIVE: "side-by-side-widgets-lead-five",
SPACES_BUTTONS_TOP: "spaces-buttons-top",
SPACES_BUTTONS_BOTTOM: "spaces-buttons-bottom",
SPACES_THEMATIC_V1: "spaces-thematic-v1",
SPACES_FLOATING_ARROWS: "spaces-floating-arrows",
SPACES_PREVIEW_KIT: "spaces-preview-kit",
SPACES_PREVIEW_ILLUSTRATED: "spaces-preview-illustrated",
SPACES_PREVIEW_CARDS: "spaces-preview-cards",
SPACES_PEEK: "spaces-peek",
AUTO_MINIMIZE_WIDGETS: "auto-minimize-widgets",
WIDGETS_AD_LARGE: "widgets-ad-large",
WIDGET_FIRST_CONTENT_SLOT: "widget-first-content-slot",
};
export const DEFAULT_PAGE_LAYOUT_VARIANT = PAGE_LAYOUT_VARIANTS.NOVA_FULL_WIDTH;
/**
* Band classes per side-by-side variant, keyed by variant name.
*
* Two orthogonal classes rather than the variant name itself, because CSS
* matches classes per token: `.side-by-side-content-lead` would not match an
* element classed `side-by-side-content-lead-five`, so every rule would need a
* duplicate selector. The lead class carries the column order and every
* side-by-side rule keys off it, so a variant and its -five counterpart share
* one; side-by-side-five is what unlocks the fourth content card.
*
* "lead" is inline-start, so these stay correct in RTL.
*/
const SIDE_BY_SIDE_CLASSES = {
[PAGE_LAYOUT_VARIANTS.SIDE_BY_SIDE_CONTENT_LEAD]: [
"side-by-side-content-lead",
],
[PAGE_LAYOUT_VARIANTS.SIDE_BY_SIDE_WIDGETS_LEAD]: [
"side-by-side-widgets-lead",
],
[PAGE_LAYOUT_VARIANTS.SIDE_BY_SIDE_CONTENT_LEAD_FIVE]: [
"side-by-side-content-lead",
"side-by-side-five",
],
[PAGE_LAYOUT_VARIANTS.SIDE_BY_SIDE_WIDGETS_LEAD_FIVE]: [
"side-by-side-widgets-lead",
"side-by-side-five",
],
};
export const SIDE_BY_SIDE_PAGE_LAYOUTS = Object.keys(SIDE_BY_SIDE_CLASSES);
export const PREF_PAGE_LAYOUT_VARIANT = "pageLayouts.variant";
export const PREF_AUTO_MINIMIZE_DELAY_MS = "pageLayouts.autoMinimizeDelayMs";
const DEFAULT_AUTO_MINIMIZE_DELAY_MS = 3000;
/**
* Returns the assigned page layout variant, whether or not it can currently
* render. This is the value telemetry reports.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string}
*/
export function resolvePageLayoutVariant(prefs) {
const trainhop = prefs?.trainhopConfig?.pageLayouts?.variant;
if (typeof trainhop === "string" && trainhop) {
return trainhop;
}
return prefs?.[PREF_PAGE_LAYOUT_VARIANT] || DEFAULT_PAGE_LAYOUT_VARIANT;
}
/**
* Returns true if the auto-minimize-widgets variant is assigned.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isAutoMinimizeWidgetsAssigned(prefs) {
return (
resolvePageLayoutVariant(prefs) ===
PAGE_LAYOUT_VARIANTS.AUTO_MINIMIZE_WIDGETS
);
}
/**
* How long the widgets section stays expanded before it auto-collapses.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {number} delay in milliseconds
*/
export function resolveAutoMinimizeDelayMs(prefs) {
const trainhop = prefs?.trainhopConfig?.pageLayouts?.autoMinimizeDelayMs;
if (typeof trainhop === "number" && trainhop >= 0) {
return trainhop;
}
const pref = prefs?.[PREF_AUTO_MINIMIZE_DELAY_MS];
return typeof pref === "number" && pref >= 0
? pref
: DEFAULT_AUTO_MINIMIZE_DELAY_MS;
}
/**
* Returns the classes the content band needs for the assigned variant, or an
* empty array outside the experiment.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string[]}
*/
export function sideBySideBandClasses(prefs) {
return SIDE_BY_SIDE_CLASSES[resolvePageLayoutVariant(prefs)] ?? [];
}
/**
* Returns true if a side-by-side variant is assigned, whether or not the page
* can lay it out. The section panels key off this rather than isSideBySideActive,
* so a lone section still gets its panel while in the experiment.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSideBySideAssigned(prefs) {
return SIDE_BY_SIDE_PAGE_LAYOUTS.includes(resolvePageLayoutVariant(prefs));
}
// Orthogonal classes, for the same reason side-by-side uses them.
const SPACES_CLASSES = {
[PAGE_LAYOUT_VARIANTS.SPACES_BUTTONS_TOP]: ["spaces", "spaces-buttons-top"],
[PAGE_LAYOUT_VARIANTS.SPACES_BUTTONS_BOTTOM]: [
"spaces",
"spaces-buttons-bottom",
],
// Reuses the buttons-bottom control, which is where the comps put it. Not the
// side-by-side lead class: those band rules would fire on the band itself, and
// here the pair is inside a panel.
[PAGE_LAYOUT_VARIANTS.SPACES_THEMATIC_V1]: [
"spaces",
"spaces-buttons-bottom",
"spaces-thematic",
],
[PAGE_LAYOUT_VARIANTS.SPACES_FLOATING_ARROWS]: [
"spaces",
"spaces-floating-arrows",
],
// The buttons-bottom control, whose tabs preview their space with an image,
// or with its first card in spaces-preview-cards.
[PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_KIT]: [
"spaces",
"spaces-buttons-bottom",
],
[PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_ILLUSTRATED]: [
"spaces",
"spaces-buttons-bottom",
],
[PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_CARDS]: [
"spaces",
"spaces-buttons-bottom",
],
[PAGE_LAYOUT_VARIANTS.SPACES_PEEK]: [
"spaces",
"spaces-buttons-bottom",
"spaces-peek",
],
};
export const SPACES_PAGE_LAYOUTS = Object.keys(SPACES_CLASSES);
// Default order. Stories leads so an unaware user lands where they expect.
export const SPACE_IDS = {
STORIES: "stories",
WIDGETS: "widgets",
// Backed by feeds.section.highlights, despite the name.
ACTIVITY: "activity",
};
export const PREF_SPACES_CONFIG = "pageLayouts.spacesConfig";
export const PREF_SPACES_ORDER = "pageLayouts.spacesOrder";
// Each preview variant's image set, as a filename prefix. Each image is 2x and
// centred on its illustration, so anything that breaks out of it, like Kit,
// overhangs evenly into the preview's padding.
const SPACES_PREVIEW_IMAGE_SETS = {
[PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_KIT]: "spaces-preview-kit-",
[PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_ILLUSTRATED]: "spaces-preview-",
};
/**
* The preview images for the assigned preview variant, by space id, or empty
* outside those variants.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {object} space id to chrome:// URL
*/
export function resolveFeatureSpacePreviewImages(prefs) {
const prefix = SPACES_PREVIEW_IMAGE_SETS[resolvePageLayoutVariant(prefs)];
if (!prefix) {
return {};
}
return Object.fromEntries(
Object.values(SPACE_IDS).map(id => [
id,
`${PREVIEW_ASSETS_PATH}${prefix}${id}.png`,
])
);
}
/**
* The V1 spaces' order: trainhopConfig as an array of ids, else the pref as
* comma-separated ids, else SPACE_IDS order. Unknown ids are dropped, and a
* space the order leaves out is not shown.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string[]}
*/
export function resolveFeatureSpacesOrder(prefs) {
const trainhop = prefs?.trainhopConfig?.pageLayouts?.spacesOrder;
const pref = prefs?.[PREF_SPACES_ORDER];
let raw = [];
if (Array.isArray(trainhop)) {
raw = trainhop;
} else if (typeof pref === "string") {
raw = pref.split(",").map(id => id.trim());
}
const ids = Object.values(SPACE_IDS);
const order = [...new Set(raw)].filter(id => ids.includes(id));
return order.length ? order : ids;
}
// Where the Firefox Profiles avatar icons live. Those are a filled background
// circle plus a knocked-out glyph, so they need the opposite fill and stroke
// treatment to an ordinary toolbar glyph; the path is what tells them apart.
/**
* A config-supplied icon URL, or undefined for anything that is not a chrome
* URL. Not a safety check against markup -- an <img> cannot execute -- but
* about:newtab makes no third-party requests, and an https URL in a recipe
* would have it fetch one. A rejected or broken URL leaves the tab with just
* its label.
*
* @param {string} url - a chrome:// URL from the config
* @returns {string|undefined}
*/
export function resolveThematicSpaceIcon(url) {
return typeof url === "string" && url.startsWith("chrome://")
? url
: undefined;
}
/**
* Which icon family a URL belongs to, so the stylesheet can paint it. "avatar"
* for the Profiles set, "glyph" for everything else.
*
* @param {string|undefined} url - a resolved icon URL
* @returns {string|undefined}
*/
function resolveThematicIconFamily(url) {
if (!url) {
return undefined;
}
return url.startsWith(PROFILE_AVATAR_ICON_PATH) ? "avatar" : "glyph";
}
function asStringArray(value) {
return Array.isArray(value) ? value.filter(v => typeof v === "string") : [];
}
/**
* Says why a config was thrown out, so whoever wrote the recipe or the pref
* finds out rather than watching a layout quietly not appear. Reported here
* because this is where the shape is understood; callers just get null.
*
* @param {*} raw - the config that was rejected
* @returns {null}
*/
function rejectSpacesConfig(raw) {
console.error(
"Thematic spaces config rejected, so the layout will not render. It needs " +
"an `order` array of ids and a `spaces` object giving each of them a " +
"label.",
raw
);
return null;
}
/**
* Normalises a raw config into what the resolvers below expect, or null when it
* cannot render. Nothing is merged with the default: a config either stands on
* its own or is discarded, so a recipe is never half-applied. A space that is
* unusable is dropped and the rest still render; only a missing order, missing
* spaces, or nothing left after dropping kills the layout.
*
* @param {object} raw - a spaces config from trainhopConfig or the pref
* @returns {object|null} { order, default, widgetLibrary, widgetCatchAll,
* arrows, preview, spaces } or null
*/
export function normalizeSpacesConfig(raw) {
const order = asStringArray(raw?.order);
const rawSpaces = raw?.spaces;
if (!order.length || !rawSpaces || typeof rawSpaces !== "object") {
return rejectSpacesConfig(raw);
}
const spaces = {};
const slotted = new Set();
const kept = order.filter(id => {
const space = rawSpaces[id];
// A tab with no label is unusable: nothing tells the user what is behind it.
if (!space || typeof space.label !== "string" || !space.label) {
return false;
}
// A widget is shown once, so the first space to name it keeps it.
const firstSlotWidget =
WIDGET_REGISTRY.some(w => w.id === space.firstSlotWidget) &&
!slotted.has(space.firstSlotWidget)
? space.firstSlotWidget
: null;
if (firstSlotWidget) {
slotted.add(firstSlotWidget);
}
const icon = resolveThematicSpaceIcon(space.icon);
spaces[id] = {
label: space.label,
icon,
iconFamily: resolveThematicIconFamily(icon),
// Chrome-only for the same reason as the icon.
previewImage: resolveThematicSpaceIcon(space.previewImage),
sections: asStringArray(space.sections),
widgets: asStringArray(space.widgets),
// Shows Recent activity.
activity: space.activity === true,
// Shown in the first card of the space's first section.
firstSlotWidget,
};
return true;
});
if (!kept.length) {
return rejectSpacesConfig(raw);
}
// The named default has to have survived; otherwise the leftmost space takes
// both roles, including the sections catch-all.
const defaultId = kept.includes(raw.default) ? raw.default : kept[0];
// Shows every widget, and turns the default space's widgets into the user's
// own Home list. Unset leaves widgets placed by config alone.
const widgetLibrary =
kept.includes(raw.widgetLibrary) && raw.widgetLibrary !== defaultId
? raw.widgetLibrary
: null;
return {
order: kept,
default: defaultId,
widgetLibrary,
// Takes the widgets no space names. The default space unless one is named.
widgetCatchAll: kept.includes(raw.widgetCatchAll)
? raw.widgetCatchAll
: (widgetLibrary ?? defaultId),
// Edge arrows alongside the tablist.
arrows: raw.arrows === true,
preview: raw.preview === true,
spaces,
};
}
// Every space, in tablist order. The experiment turns a space on unless
// optOutPref says the user switched it off while enrolled; PrefsFeed mirrors
// !userPref into it on change, so enrollment itself leaves it alone. userPref
// is never written. feedGated means userPref also starts a feed, so PrefsFeed
// has to write its default too.
export const SPACE_CONFIG = {
[SPACE_IDS.STORIES]: {
trainhopKey: "stories",
userPref: "feeds.section.topstories",
optOutPref: "spaces.storiesOptOut",
},
[SPACE_IDS.WIDGETS]: {
trainhopKey: "widgets",
userPref: "widgets.enabled",
optOutPref: "spaces.widgetsOptOut",
},
[SPACE_IDS.ACTIVITY]: {
trainhopKey: "highlights",
userPref: "feeds.section.highlights",
optOutPref: "spaces.activityOptOut",
feedGated: true,
},
};
/**
* Whether a spaces variant is assigned, populated or not.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpacesAssigned(prefs) {
return SPACES_PAGE_LAYOUTS.includes(resolvePageLayoutVariant(prefs));
}
/**
* Whether the thematic spaces variant is assigned, populated or not. Its spaces
* come from its own config rather than SPACE_IDS, so callers that branch on
* the id set need this and not isSpacesAssigned.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpacesThematicAssigned(prefs) {
return (
resolvePageLayoutVariant(prefs) === PAGE_LAYOUT_VARIANTS.SPACES_THEMATIC_V1
);
}
/**
* Whether the floating arrows variant is assigned, populated or not. That
* variant's arrows replace the tablist.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpacesArrowsAssigned(prefs) {
return (
resolvePageLayoutVariant(prefs) ===
PAGE_LAYOUT_VARIANTS.SPACES_FLOATING_ARROWS
);
}
/**
* Whether the peek variant is assigned, populated or not.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpacesPeekAssigned(prefs) {
return resolvePageLayoutVariant(prefs) === PAGE_LAYOUT_VARIANTS.SPACES_PEEK;
}
/**
* Whether the experiment is currently forcing this space on, which it does for
* a profile that had it switched off. Only ever true while enrolled, and never
* a reason to ignore a choice made since.
*
* OR this with the pref a caller already reads, rather than replacing it:
* `prefs[PREF_X] || isSpaceOverridden(...)` keeps the user's value visible at
* the call site. Callers that read one of these prefs need it, or the space
* renders empty and its customize-menu toggle contradicts the page.
*
* @param {string} id - a SPACE_IDS value
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpaceOverridden(id, prefs) {
const { trainhopKey, optOutPref } = SPACE_CONFIG[id];
return Boolean(
isSpacesAssigned(prefs) &&
prefs?.trainhopConfig?.[trainhopKey]?.enabled &&
!prefs?.[optOutPref]
);
}
/**
* Whether the page has stories, ignoring which variant is assigned.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
function hasStories(prefs) {
return Boolean(
// The override, like Base.jsx does for V1: the experiment turns stories back
// on for a profile that had them off, unless it has since opted out.
// isSpaceOverridden is false outside a spaces variant, so the side-by-side
// layouts read the plain pref. feeds.system.topstories stays raw -- region
// and locale are not a user choice.
(prefs?.["feeds.section.topstories"] ||
isSpaceOverridden(SPACE_IDS.STORIES, prefs)) &&
prefs?.["feeds.system.topstories"]
);
}
/**
* Whether the page has both halves of the side-by-side pair, ignoring which
* variant is assigned.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
function hasSideBySidePair(prefs) {
return Boolean(
hasStories(prefs) &&
isWidgetsContainerVisible(prefs) &&
hasContentAreaWidgets(
prefs,
prefs?.["widgets.enabled"] || isSpaceOverridden(SPACE_IDS.WIDGETS, prefs)
)
);
}
/**
* Returns true if a side-by-side variant is assigned and the page has both
* things to put side by side. Without stories, or without a content-area widget,
* the band falls back to its full-width single column.
*
* Use this rather than testing the variant directly, so the widgets gate stays
* consistent with the rest of the page.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSideBySideActive(prefs) {
return Boolean(
SIDE_BY_SIDE_PAGE_LAYOUTS.includes(resolvePageLayoutVariant(prefs)) &&
hasSideBySidePair(prefs)
);
}
function isSpaceEnabled(id, prefs) {
return (
Boolean(prefs?.[SPACE_CONFIG[id].userPref]) || isSpaceOverridden(id, prefs)
);
}
/**
* Which space the page opens on, given the spaces that survived the populated
* check. Falls back to the first of them, so dropping the config's default still
* opens somewhere.
*
* @param {object} config - from resolveThematicSpacesConfig
* @param {string[]} populatedSpaces - ids from resolvePopulatedSpaces
* @returns {string|undefined}
*/
export function resolveThematicDefaultSpace(config, populatedSpaces = []) {
return populatedSpaces.includes(config?.default)
? config.default
: populatedSpaces[0];
}
/**
* The config a profile should use: a train-hop payload when enrolled, otherwise
* the pref, a JSON string whose shipped default is DEFAULT_SPACES_CONFIG in
* ActivityStream.sys.mjs and which devtools edits. Null when neither yields a
* usable config, which is what stops the layout rendering.
*
* @param {object} [trainhopConfig] - the merged train-hop config
* @param {string} [prefValue] - the pageLayouts.spacesConfig pref
* @returns {object|null}
*/
export function resolveSpacesConfigFrom(trainhopConfig, prefValue) {
if (trainhopConfig?.spaces) {
return normalizeSpacesConfig(trainhopConfig.spaces);
}
if (!prefValue) {
return null;
}
try {
return normalizeSpacesConfig(JSON.parse(prefValue));
} catch {
return rejectSpacesConfig(prefValue);
}
}
/**
* The thematic spaces config in force, resolved and normalised here rather than
* in a feed, since only PREFS_INITIAL_VALUES has arrived before the first paint.
* Null means the variant cannot render and the band falls back to its ordinary
* layout, which is what a config with a mistake in it does: a broken config is
* rejected outright, never patched up from the pref's shipped default.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {object|null}
*/
let lastResolved = { trainhop: undefined, pref: undefined, value: null };
export function resolveThematicSpacesConfig(prefs) {
const trainhop = prefs?.trainhopConfig?.spaces;
const pref = prefs?.[PREF_SPACES_CONFIG];
// Memoised on the inputs, not for speed alone: it also keeps a rejected
// config from complaining once per render. Both are stable between changes --
// trainhopConfig is replaced wholesale, and the pref is a string.
if (lastResolved.trainhop === trainhop && lastResolved.pref === pref) {
return lastResolved.value;
}
const value = resolveSpacesConfigFrom(prefs?.trainhopConfig, pref);
lastResolved = { trainhop, pref, value };
return value;
}
const SPACES_PREVIEW_PAGE_LAYOUTS = [
PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_KIT,
PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_ILLUSTRATED,
PAGE_LAYOUT_VARIANTS.SPACES_PREVIEW_CARDS,
];
/**
* Whether the tabs preview the space they lead to: always in the preview
* variants, and in thematic spaces when their config's `preview` flag is set.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isSpacesPreviewEnabled(prefs) {
if (isSpacesThematicAssigned(prefs)) {
return Boolean(resolveThematicSpacesConfig(prefs)?.preview);
}
return SPACES_PREVIEW_PAGE_LAYOUTS.includes(resolvePageLayoutVariant(prefs));
}
/**
* Whether spaces navigate with edge arrows: always for the floating arrows
* variant, and for the thematic one when its config asks for them.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function hasSpacesArrows(prefs) {
return (
isSpacesArrowsAssigned(prefs) ||
(isSpacesThematicAssigned(prefs) &&
!!resolveThematicSpacesConfig(prefs)?.arrows)
);
}
/**
* Band classes for the assigned variant, empty outside the experiment.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string[]}
*/
export function spacesBandClasses(prefs) {
const classes = SPACES_CLASSES[resolvePageLayoutVariant(prefs)] ?? [];
return hasSpacesArrows(prefs) ? [...classes, "spaces-arrows"] : classes;
}
/**
* The space Recent activity renders in: the first one the config marks for it,
* otherwise the default space, where it rendered before spaces could be marked.
*
* @param {object} config - from resolveThematicSpacesConfig
* @returns {string|undefined}
*/
export function resolveThematicActivitySpace(config) {
return (
config?.order.find(id => config.spaces[id].activity) ?? config?.default
);
}
/**
* Which of the delivered sectionKeys belong to a space, in delivery order. The
* default space is the catch-all, so it also takes every key no other space
* claims and an unrecognised section still renders somewhere.
*
* @param {object} config - from resolveThematicSpacesConfig
* @param {string} spaceId - a config space id
* @param {string[]} sectionKeys - sectionKeys the feed delivered, in order
* @returns {string[]}
*/
export function resolveThematicSpaceSections(
config,
spaceId,
sectionKeys = []
) {
const assigned = new Set(config?.spaces?.[spaceId]?.sections ?? []);
const isCatchAll = spaceId === config?.default;
const claimedElsewhere = new Set(
Object.entries(config?.spaces ?? {})
.filter(([id]) => id !== spaceId && id !== config?.default)
.flatMap(([, space]) => space.sections)
);
// Delivery order is the feed's ranking, so filter rather than reorder.
return sectionKeys.filter(
key => assigned.has(key) || (isCatchAll && !claimedElsewhere.has(key))
);
}
/**
* The sectionKeys the feed has delivered, in order. Empty before the feed
* arrives, which is why a space with nothing to show is dropped rather than
* rendered blank: the next refresh can bring it back.
*
* @param {object} discoveryStream - state.DiscoveryStream
* @returns {string[]}
*/
export function resolveFeedSectionKeys(discoveryStream) {
const sections = Object.values(discoveryStream?.feeds?.data ?? {}).find(
feed => feed?.data?.sections?.length
)?.data?.sections;
return sections?.map(section => section.sectionKey).filter(Boolean) ?? [];
}
// Keep for spaces-thematic-v1, which falls back to it.
export const PREF_WIDGET_FIRST_WIDGET =
"pageLayouts.widgetFirstContentSlot.widget";
/**
* Whether a widget can take a first story card: stories are on and the widget
* is enabled, counting the space overrides, which are false outside a spaces
* variant.
*
* @param {object|undefined} widget - a WIDGET_REGISTRY entry, if one matched
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
function canShowFirstSlotWidget(widget, prefs) {
return Boolean(
widget &&
prefs["nova.enabled"] &&
hasStories(prefs) &&
isWidgetEnabled(
widget,
prefs,
prefs["widgets.enabled"] || isSpaceOverridden(SPACE_IDS.WIDGETS, prefs)
)
);
}
// Keep for spaces-thematic-v1, and drop the widget-first-content-slot check.
/**
* The id of the widget the global setting puts in the first card of the top
* stories section, or null when there is none. The widget must already be
* enabled. Under the thematic spaces variant a space can name its own instead;
* see resolveFirstSlotWidgets.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string|null} a widget registry id
*/
export const selectFirstSlotWidget = prefs => {
const variant = resolvePageLayoutVariant(prefs);
if (
variant !== PAGE_LAYOUT_VARIANTS.WIDGET_FIRST_CONTENT_SLOT &&
variant !== PAGE_LAYOUT_VARIANTS.SPACES_THEMATIC_V1
) {
return null;
}
const id =
prefs.trainhopConfig?.pageLayouts?.widgetFirstContentSlot?.widget ??
prefs[PREF_WIDGET_FIRST_WIDGET];
return canShowFirstSlotWidget(
WIDGET_REGISTRY.find(w => w.id === id),
prefs
)
? id
: null;
};
/**
* The widgets shown in a first story card, in config order. Under the thematic
* spaces variant each space can name its own `firstSlotWidget`. When none does,
* the global setting applies, to the feed's top section.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {Array<{spaceId: string|null, widgetId: string}>} spaceId is null
* for the global setting
*/
export function resolveFirstSlotWidgets(prefs) {
const config = isSpacesThematicAssigned(prefs)
? resolveThematicSpacesConfig(prefs)
: null;
const named =
config?.order.filter(id => config.spaces[id].firstSlotWidget) ?? [];
if (named.length) {
return named
.map(id => ({ spaceId: id, widgetId: config.spaces[id].firstSlotWidget }))
.filter(({ widgetId }) =>
canShowFirstSlotWidget(
WIDGET_REGISTRY.find(w => w.id === widgetId),
prefs
)
);
}
const widgetId = selectFirstSlotWidget(prefs);
return widgetId ? [{ spaceId: null, widgetId }] : [];
}
/**
* The ids of the widgets shown in a first story card, which no widgets column
* shows as well.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {Set<string>}
*/
export function selectFirstSlotWidgetIds(prefs) {
return new Set(resolveFirstSlotWidgets(prefs).map(slot => slot.widgetId));
}
/**
* Which section each first-slot widget leads, by sectionKey: the first of its
* space's sections, or the top section for the global setting. A widget whose
* space has no section in the feed is not shown.
*
* @param {object} prefs - current pref values from the Redux store
* @param {string[]} sectionKeys - sectionKeys in display order
* @returns {object} sectionKey to widget id
*/
export function resolveFirstSlotWidgetsBySection(prefs, sectionKeys) {
const config = resolveThematicSpacesConfig(prefs);
const bySection = {};
for (const { spaceId, widgetId } of resolveFirstSlotWidgets(prefs)) {
const sectionKey = spaceId
? resolveThematicSpaceSections(config, spaceId, sectionKeys)[0]
: sectionKeys[0];
// Two spaces can list the same section; the first one keeps it.
if (sectionKey && !(sectionKey in bySection)) {
bySection[sectionKey] = widgetId;
}
}
return bySection;
}
export const WIDGET_PLACEMENTS = {
HOME: "home",
LIBRARY: "library",
};
/**
* The thematic config when it names a widget library, else null. Only then can
* the user move widgets on and off Home.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {object|null}
*/
function resolveWidgetPlacementConfig(prefs) {
if (!isSpacesThematicAssigned(prefs)) {
return null;
}
const config = resolveThematicSpacesConfig(prefs);
return config?.widgetLibrary ? config : null;
}
/**
* Whether the user places widgets on Home themselves, which changes what hiding
* a widget and the Manage widgets toggles do.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export function isWidgetPlacementActive(prefs) {
return !!resolveWidgetPlacementConfig(prefs);
}
/**
* Which placement role a space plays: Home, the widget library, or neither.
*
* @param {object} config - from resolveThematicSpacesConfig
* @param {string} spaceId - a config space id
* @returns {string|null} a WIDGET_PLACEMENTS value
*/
export function resolveWidgetPlacement(config, spaceId) {
if (!config?.widgetLibrary) {
return null;
}
if (spaceId === config.default) {
return WIDGET_PLACEMENTS.HOME;
}
return spaceId === config.widgetLibrary ? WIDGET_PLACEMENTS.LIBRARY : null;
}
/**
* The ids the user has pinned to Home, in pin order (newest first), else the
* config's widgets for the default space until they first change it.
*
* @param {object} prefs - current pref values from the Redux store
* @param {object} [config] - from resolveThematicSpacesConfig
* @returns {string[]}
*/
export function resolveHomeWidgetIds(
prefs,
config = resolveThematicSpacesConfig(prefs)
) {
return (
parsePinnedWidgetIds(prefs) ??
config?.spaces?.[config.default]?.widgets ??
[]
);
}
/**
* Whether a widget can render in a space's widget column at all: enabled, and
* not in the sidebar or a first story card instead.
*
* @param {object} widget - a WIDGET_REGISTRY entry
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
function canShowInSpaceColumn(widget, prefs) {
const widgetsEnabled =
prefs?.["widgets.enabled"] || isSpaceOverridden(SPACE_IDS.WIDGETS, prefs);
return (
!selectFirstSlotWidgetIds(prefs).has(widget.id) &&
!isWidgetInSidebar(widget, prefs, widgetsEnabled) &&
isWidgetEnabled(widget, prefs, widgetsEnabled)
);
}
/**
* The pinned widgets Home actually shows: those in the Home list that can
* render. How many start there is up to the spaces config.
*
* @param {object} prefs - current pref values from the Redux store
* @param {object} [config] - from resolveThematicSpacesConfig
* @returns {string[]} widget ids, in pin order
*/
export function resolvePinnedWidgetIds(
prefs,
config = resolveThematicSpacesConfig(prefs)
) {
return resolveHomeWidgetIds(prefs, config)
.map(id => WIDGET_REGISTRY.find(w => w.id === id))
.filter(w => w && canShowInSpaceColumn(w, prefs))
.map(w => w.id);
}
/**
* The widgets a space should show, in registry order, filtered to the ones
* actually enabled. The config's widgetCatchAll space also takes every widget no
* space names, so one is never invisible everywhere. Empty means the space shows
* its feed alone, which is all of them while the widgets container is hidden.
*
* When the config names a widgetLibrary, each widget is in exactly one place:
* pinned to Home (the default space), or in the library.
*
* Some widgets are in no space's column: Weather at its small size, which
* renders in the page's inline-end sidebar as it does in the side-by-side
* layouts, and those in the first card of a story section.
*
* @param {object} config - from resolveThematicSpacesConfig
* @param {string} spaceId - a config space id
* @param {object} prefs - current pref values from the Redux store
* @returns {string[]} widget ids
*/
export function resolveThematicSpaceWidgets(config, spaceId, prefs) {
if (!isWidgetsContainerVisible(prefs)) {
return [];
}
const placement = resolveWidgetPlacement(config, spaceId);
if (placement) {
const pinned = resolvePinnedWidgetIds(prefs, config);
const onHome = placement === WIDGET_PLACEMENTS.HOME;
return WIDGET_REGISTRY.filter(
w => pinned.includes(w.id) === onHome && canShowInSpaceColumn(w, prefs)
).map(w => w.id);
}
const assigned = new Set(config?.spaces?.[spaceId]?.widgets ?? []);
const isCatchAll = spaceId === (config?.widgetCatchAll ?? config?.default);
const claimed = new Set(
Object.values(config?.spaces ?? {}).flatMap(space => space.widgets)
);
return WIDGET_REGISTRY.filter(
w =>
(assigned.has(w.id) || (isCatchAll && !claimed.has(w.id))) &&
canShowInSpaceColumn(w, prefs)
).map(w => w.id);
}
/**
* The thematic spaces that have something to show, in the config's order: a
* section in the feed, an enabled widget, or Recent activity. A space with none
* is dropped
* rather than rendered empty -- the next refresh can bring it back. Widgets
* being off only empties the spaces that relied on them; stories being off
* turns the layout off, as the page is built around them.
*
* Nothing renders before the feed arrives either. The default space takes every
* section no other space claims, so until then it would be dropped and the page
* would open on whichever space happened to have widgets.
*
* @param {object} prefs - current pref values from the Redux store
* @param {string[]|null} sectionKeys - sectionKeys the feed delivered, or null
* from a caller that only has prefs, which skips the per-space check
* @returns {string[]}
*/
function resolvePopulatedThematicSpaces(prefs, sectionKeys) {
const config = resolveThematicSpacesConfig(prefs);
if (!config || !hasStories(prefs) || sectionKeys?.length === 0) {
return [];
}
if (!sectionKeys) {
return config.order;
}
const activityId = resolveThematicActivitySpace(config);
const activityEnabled = isSpaceEnabled(SPACE_IDS.ACTIVITY, prefs);
return config.order.filter(
id =>
resolveThematicSpaceSections(config, id, sectionKeys).length ||
resolveThematicSpaceWidgets(config, id, prefs).length ||
(id === activityId && activityEnabled)
);
}
/**
* The V1 spaces that have something to show, in the resolved order. Being
* enabled is not enough for two of them, and no override crosses that floor --
* an empty space is worse than a missing one.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {string[]}
*/
function resolvePopulatedFeatureSpaces(prefs) {
return resolveFeatureSpacesOrder(prefs).filter(id => {
if (!isSpaceEnabled(id, prefs)) {
return false;
}
if (id === SPACE_IDS.STORIES) {
// Region and locale decide whether stories exist at all.
return Boolean(prefs["feeds.system.topstories"]);
}
if (id === SPACE_IDS.WIDGETS) {
// Ignoring the master toggle, which isSpaceEnabled already covered: is
// any widget on that renders in the content area? Weather moves to the
// sidebar at its small size, so a weather-only profile has nothing here.
return hasContentAreaWidgets(prefs, true);
}
return true;
});
}
/**
* Each space's enabled widgets, keyed by space id. Folded once because it
* answers two questions at the call site: whether a space gets a widget column
* at all, and what goes in it.
*
* @param {object} config - from resolveThematicSpacesConfig
* @param {string[]} spaceIds - ids from resolvePopulatedSpaces
* @param {object} prefs - current pref values from the Redux store
* @returns {object} space id to widget ids
*/
export function resolveThematicWidgetsBySpace(config, spaceIds, prefs) {
return Object.fromEntries(
spaceIds.map(id => [id, resolveThematicSpaceWidgets(config, id, prefs)])
);
}
/**
* Ids of the spaces that have content, in tablist order. The two variants
* answer this differently enough to keep apart: V1 asks per feature pref,
* thematic asks the config and the feed.
*
* @param {object} prefs - current pref values from the Redux store
* @param {string[]} [sectionKeys] - sectionKeys the feed delivered. Thematic
* only; V1 spaces are not built from sections.
* @returns {string[]}
*/
export function resolvePopulatedSpaces(prefs = {}, sectionKeys = null) {
return isSpacesThematicAssigned(prefs)
? resolvePopulatedThematicSpaces(prefs, sectionKeys)
: resolvePopulatedFeatureSpaces(prefs);
}
/**
* Everything the thematic layout needs, or null when it is not assigned or has
* no usable config. One call so the component composing the page reads the
* layout's shape in one place rather than assembling it from six resolvers.
*
* @param {object} prefs - current pref values from the Redux store
* @param {object} discoveryStream - state.DiscoveryStream
* @returns {object|null} { order, defaultId, activityId, preview, spaces }
* where each space carries its label, icon, iconFamily, previewImage,
* sectionKeys, widgetIds and widgetPlacement
*/
export function resolveThematicSpaces(prefs, discoveryStream) {
if (!isSpacesThematicAssigned(prefs)) {
return null;
}
const config = resolveThematicSpacesConfig(prefs);
const sectionKeys = resolveFeedSectionKeys(discoveryStream);
const order = resolvePopulatedSpaces(prefs, sectionKeys);
if (!config || !order.length) {
return null;
}
return {
order,
defaultId: resolveThematicDefaultSpace(config, order),
activityId: resolveThematicActivitySpace(config),
preview: config.preview,
spaces: Object.fromEntries(
order.map(id => [
id,
{
...config.spaces[id],
sectionKeys: resolveThematicSpaceSections(config, id, sectionKeys),
widgetIds: resolveThematicSpaceWidgets(config, id, prefs),
widgetPlacement: resolveWidgetPlacement(config, id),
},
])
),
};
}
/**
* Whether spaces is assigned and has somewhere to navigate to. Below two spaces
* the band falls back to stacking its sections.
*
* Takes the DiscoveryStream state rather than section keys so the keys are only
* derived once the cheap checks have passed: the default page is not built from
* sections and should not pay to look at them.
*
* @param {object} prefs - current pref values from the Redux store
* @param {object} [discoveryStream] - state.DiscoveryStream. Only the thematic
* variant uses it, and omitting it asks whether the layout is assigned rather
* than whether its spaces have content
* @returns {boolean}
*/
export function isSpacesActive(prefs, discoveryStream) {
// Every spaces style is scoped under .nova-enabled.
if (!prefs?.["nova.enabled"] || !isSpacesAssigned(prefs)) {
return false;
}
// No feed state given means the caller only wants to know which layout is
// assigned, so the per-space section check is skipped. Deriving keys from
// undefined would come back empty and read as "no space has content".
const sectionKeys =
discoveryStream && isSpacesThematicAssigned(prefs)
? resolveFeedSectionKeys(discoveryStream)
: null;
return resolvePopulatedSpaces(prefs, sectionKeys).length > 1;
}
// Banner formats are placed by row rather than in a card slot, so the row can't
// use one. Rectangle is out too: DSCard swaps its title and excerpt for generic
// copy and drops the attribution footer. Deliberately duplicates the list in
// selectLayoutRender, since sharing it would make common/ depend on
// content-src/, which is the wrong direction.
const WIDGETS_AD_EXCLUDED_FORMATS = ["billboard", "leaderboard", "rectangle"];
/**
* Whether the widgets-row ad variant is assigned and the page can lay it out.
* The row is a Nova-only grid, and an ad on its own under a heading that says
* Widgets is worse than no ad, so this needs a content-area widget too.
*
* @param {object} prefs - current pref values from the Redux store
* @returns {boolean}
*/
export const isWidgetsAdActive = prefs =>
Boolean(
prefs?.["nova.enabled"] &&
resolvePageLayoutVariant(prefs) === PAGE_LAYOUT_VARIANTS.WIDGETS_AD_LARGE &&
// Both gates, as selectLayoutRender and DiscoveryStreamFeed use. A stale
// spoc in the store must not outlive the user turning sponsored off.
prefs.showSponsored &&
prefs["system.showSponsored"] &&
isWidgetsContainerVisible(prefs) &&
hasContentAreaWidgets(prefs)
);
/**
* The sponsored card the widgets row shows, or null when it shows none.
*
* The row takes the first eligible ad and the stories fill skips whichever one
* this returns, so both call this rather than deciding separately. Two gates
* that can disagree would drop an ad nobody renders.
*
* @param {object} prefs - current pref values from the Redux store
* @param {object} spocs - state.DiscoveryStream.spocs
* @returns {object|null} a normalized spoc, in the same shape a story card gets
*/
export const selectWidgetsRowAd = (prefs, spocs) => {
if (!isWidgetsAdActive(prefs)) {
return null;
}
// The first eligible ad, and nothing once it is blocked. Advancing to the
// next would take a second ad out of the Stories inventory.
const first = spocs?.data?.newtab_spocs?.items?.find(
item => !WIDGETS_AD_EXCLUDED_FORMATS.includes(item.format)
);
const blocked = spocs?.blocked ?? [];
return first && !blocked.includes(first.url) ? first : null;
};