fansunited-frontend-core
v1.1.1
Published
Core types, components, providers and constants for Fans United widgets
Keywords
Readme
Fans United Frontend Core
Core utilities, types, and shared functionality for Fans United widget packages.
Installation
npm install fansunited-frontend-coreyarn add fansunited-frontend-corePeer dependencies
{
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}Emotion and i18next are regular dependencies and are not bundled, so the host app and
fansunited-frontend-components share one copy of each.
Subpath imports
import { WidgetTemplate } from "fansunited-frontend-core/enums";
import type { LanguageType } from "fansunited-frontend-core/types";Available entries: fansunited-frontend-core (everything), /enums, /constants, plus type-only
/interfaces and /types. The package declares "sideEffects": false and ships one file per
source module, so a root import costs only the modules you use, in every bundler. Translations are
loaded lazily, one chunk per language. Because the package uses exports, deep file paths such as
fansunited-frontend-core/index.es.js are not importable.
Static artwork (default backgrounds, placeholder avatars, score icons) is served from
https://uploads.fansunitedassets.com; the URLs are exported as cdnAssets. Every asset has a
small inline SVG fallback (cdnAssetFallbacks): onImageError() swaps a plain <img> to it when
the CDN image fails to load, and backgroundImageUrl() stacks it under a CSS background, so a
missing CDN object never leaves a broken image.
Features
- Complete TypeScript definitions for all Fans United components
- Theme management with light/dark mode support
- Internationalization (i18n) with 16 supported languages, including right-to-left Arabic
- Shared utilities and helper functions
- React providers and hooks
- Component primitives
- Typed analytics events for tag-manager and analytics integrations
Core Exports
Types and Interfaces
import {
// Component Props
ClassicQuizPlayProps,
BaseClassicQuizPlayProps,
ClassicQuizAwarenessProps,
PollVoteProps,
BasePollVoteProps,
PersonalityQuizPlayProps,
BasePersonalityQuizPlayProps,
CollectLeadProps,
BaseCollectLeadProps,
CollectLeadFormProps,
CollectLeadMainProps,
MainProps,
// Configuration Interfaces
Configuration,
ClassicQuizAwarenessConfiguration,
ClassicQuizPlayConfiguration,
// Theme and Styling
CustomThemeOptions,
EnhancedCustomThemeOptions,
InternalCustomThemeOptions,
CustomColors,
InternalCustomColors,
CustomSpacingScale,
CustomBorderRadius,
CustomBorderSize,
CustomBreakpoints,
ImageBackgroundGradient,
FontConfig,
ThemeMode,
// Lead Management
LeadsOptions,
LeadCustomField,
LeadConsent,
LeadLabels,
FormLeadLabels,
// Consents
ConsentDef,
ConsentsConfig,
ConsentsLabels,
ConsentPosition,
// Content and Branding
ContentInfo,
CampaignInfo,
BrandingInfo,
BrandingImages,
FormBrandingInfo,
FormBrandingImages,
BrandingColors,
BrandingUrls,
// CTA and User Interaction
CTADetails,
SignInCTADetails,
OnSuccessCTADetails,
AdditionalCTADetails,
// Analytics and Events
AnalyticsEvent,
UserState,
// Enums
WidgetTemplate,
ClassicQuizTemplate,
// Betslip
BetslipParticipant,
BetslipCompetition,
BetslipAthlete,
BetslipSelectionInput,
BetslipOutcomeLabels,
BetslipLabels,
BetslipProps,
BetslipState,
PredictorBetslipConfig,
PredictorCallbacks,
ComponentEvent,
} from "fansunited-frontend-core";Type Definitions
import {
// Journey and Analytics Types
JourneyType,
StageType,
ActionType,
CTAType,
StagesType,
WidgetType,
// UI and Layout Types
LinkTargetType,
ContentViewType,
OptionsLayout,
// Internationalization
LanguageType,
// Lead Collection
LeadField,
LeadPosition,
CountryType,
ContentType,
// Hook Types
UseLeadFormParams,
UseLeadFormReturn,
LeadFormData,
// Betslip
BetslipPosition,
SelectionStatus,
OddsFormat,
PredictorBetslipTrigger,
// Component analytics events
ComponentEvent,
ComponentEventParams,
PredictorComponentEvent,
PredictorCallbacks,
PredictorAnalyticsContext,
PredictorAnalyticsEventName,
} from "fansunited-frontend-core";Theme Utilities
import {
useSpacingScale,
useFontFamily,
useCornerRadius,
useColors,
useBorderSize,
useInternalTheme,
useImageBackgroundGradient,
} from "fansunited-frontend-core";Helper Functions
import {
stripHtmlTags,
hexToRgb,
isAndroid,
useIsMobile,
getDefaultCountryByCode,
getDefaultCountryByLanguage,
useBrandingProperties,
sanitizeBackgroundUrl,
mapContentTypeToConsentEntityType,
} from "fansunited-frontend-core";React Hooks
import {
useImageUrl,
useConstantContext,
useImageVariant,
useLeadForm,
} from "fansunited-frontend-core";
// Example: Lead form hook usage
const leadForm = useLeadForm({
sdk: sdkInstance,
fields: ["fullName", "email"],
campaignId: "campaign-123",
contentType: "quiz",
contentId: "quiz-456",
syncWithProfile: true, // Optional: sync form data to user profile
});React Providers
import { ConstantsProvider, ConstantsContext } from "fansunited-frontend-core";
<ConstantsProvider
shadowRootElement={shadowRoot}
leadPhoneCountryCode="US"
language="en"
optionsLayout="twoByTwo"
>
<YourApp />
</ConstantsProvider>;Constants
import {
validWidgetTypes,
validWidgetTemplates,
countries,
languageToCountryCode,
} from "fansunited-frontend-core";
// Access predefined country list
const countryOptions = countries;
// Get country code by language
const countryCode = languageToCountryCode["en"]; // "GB"Internationalization
import { initializeI18n } from "fansunited-frontend-core";
// Initialize with preferred language
initializeI18n("en");Betslip Command Bus
betslipApi is a singleton command bus that lets any code — including code that runs before the <Betslip /> widget mounts — add or remove selections programmatically. Pre-mount calls are queued and replayed automatically once the widget registers.
Important: Always import
betslipApifromfansunited-frontend-components, not fromfansunited-frontend-core. The Betslip widget bundles its own copy of the command bus; importing from the components package guarantees you use the same singleton instance the widget is listening on.
import { betslipApi } from "fansunited-frontend-components";
// Add a selection. If the same eventId + market already exists, the outcome is replaced.
betslipApi.setSelection("fb:m:451678:FT_1X2:1");
// Remove a selection by its exact id. No-op if not present or widget is not mounted.
betslipApi.removeSelection("fb:m:451678:FT_1X2:1");Selection ID format: "{eventId}:{market}:{outcome}", for example "fb:m:451678:FT_1X2:1".
Reading betslip state
betslipApi also exposes the current betslip state through a snapshot accessor and a reactive subscription:
import { betslipApi } from "fansunited-frontend-components";
import type { BetslipState } from "fansunited-frontend-components";
// One-shot snapshot — returns the last known state immediately
const { selections, stake, totalOdds } = betslipApi.getState();
// Reactive subscription — fires whenever selections, stake, or odds change
const unsubscribe = betslipApi.subscribe((state: BetslipState) => {
console.log("selections:", state.selections.length);
console.log("stake:", state.stake);
console.log("totalOdds:", state.totalOdds);
});
// Call unsubscribe() to stop receiving updates
unsubscribe();BetslipState shape:
interface BetslipState {
selections: BetslipSelectionInput[]; // current raw selections
stake: number; // parsed numeric stake (0 when empty)
totalOdds: number; // product of all selection decimal odds (0 when no selections)
}The typical integration pattern is:
// 1. Render the Betslip widget once at app root level
<Betslip sdk={sdk} language="en" />;
// 2. From anywhere in your app — e.g. a match card — call betslipApi
import { betslipApi } from "fansunited-frontend-components";
function MatchCard({ eventId, market, outcome }) {
const selectionId = `${eventId}:${market}:${outcome}`;
return (
<button onClick={() => betslipApi.setSelection(selectionId)}>
Add to Betslip
</button>
);
}Component Events Bus
componentEvents is a singleton bus carrying analytics events emitted by the components —
widget_view, prediction_submitted, private_league_joined and the rest. Use it when you cannot
reach the component's JSX: a tag manager, a separately-bundled script, anything loading after mount.
Important: import
componentEventsfromfansunited-frontend-components, not fromfansunited-frontend-core— same reason asbetslipApi. The components package bundles its own copy of the bus, so importing from there guarantees you get the singleton the components emit on. The types below come from core.
import { componentEvents } from "fansunited-frontend-components";
import type { ComponentEvent } from "fansunited-frontend-core";
const unsubscribe = componentEvents.subscribe((event: ComponentEvent) => {
if (event.component !== "predictor") return;
console.log(event.name, event.params, event.context);
});subscribe returns an unsubscribe function. It replays recent events to a new subscriber (the
last 50, within the last 5 minutes), so a listener that attaches after the component mounted still
sees widget_view and anything else it missed.
The bus is subscribe-only: there is no public emit, so nothing else on the page can forge events
into your analytics. ComponentEvent is discriminated on component — narrow it before reading
name / context, and code keeps compiling when more components start emitting.
Payloads are flat primitives and carry no personal data — no profile id, email, display name or
token; only context.userIsLoggedIn. Identifiers in the payloads (match_id, home_team_id, …) are
canonical and provider-agnostic, so they are the fields to join on; team names are localised by the
language prop and are for display only.
Emitting components: Predictor today. See the Predictor section of the
fansunited-frontend-components README
for the full event catalogue and the tag-manager setup.
Call-to-Action (CTA) Interfaces
The package provides several CTA interfaces for different use cases:
AdditionalCTADetails
Configure additional call-to-action buttons for widget completion screens.
import { AdditionalCTADetails } from "fansunited-frontend-core";
// Custom component
const additionalCTA: AdditionalCTADetails = {
component: <CustomCTAButton />,
};
// Basic CTA with onClick handler
const additionalCTA: AdditionalCTADetails = {
defaultLabel: "Learn More",
onClick: () => {
console.log("Additional CTA clicked");
},
};
// CTA with URL navigation
const additionalCTA: AdditionalCTADetails = {
defaultLabel: "Visit Website",
url: "https://your-website.com",
target: "_blank", // or "_self"
};Interface Definition:
interface AdditionalCTADetails {
defaultLabel?: string; // Not required when component is provided
onClick?: () => void; // Required when only defaultLabel is provided
url?: string | null;
target?: LinkTargetType; // "_blank" | "_self" | "_parent" | "_top"
component?: React.ReactElement | null;
}Priority Order:
- Custom Component - If
componentis provided, it will be rendered - Click Handler - If
onClickis provided, a button with the handler will be rendered - URL Navigation - If
urlis provided, a button will be rendered and clicking will navigate to the URL
Usage:
- ClassicQuizPlay: Displayed after "Play Again" and "Share Result" buttons (Standard), after "Play Again" (Split), after "Play Again" and "Share Result" (Overlay)
- PollVote: Displayed before "Vote Again" (Standard), same container as "Vote Again" (Split), after "Vote Again" (Overlay)
- PersonalityQuizPlay: Displayed before "Play Again" (Standard), in thank you container after "Play Again" (Split), after "Play Again" if available (Overlay)
- MatchQuizPlay: Displayed same line as branding logo (Standard), centered after main content (Split), same line as branding logo (Overlay)
SignInCTADetails
Configure sign-in call-to-action buttons for authentication-required widgets.
import { SignInCTADetails } from "fansunited-frontend-core";
// Custom component
const signInCTA: SignInCTADetails = {
component: <CustomSignInButton />,
};
// Basic sign-in with onClick handler
const signInCTA: SignInCTADetails = {
defaultLabel: "Sign In",
onClick: () => {
console.log("Sign in clicked");
},
};
// Sign-in with URL navigation
const signInCTA: SignInCTADetails = {
defaultLabel: "Login",
url: "https://your-auth-provider.com/login",
target: "_blank",
};Interface Definition:
interface SignInCTADetails {
defaultLabel?: string; // Not required when component is provided
onClick?: () => void; // Required when only defaultLabel is provided
url?: string | null;
target?: LinkTargetType; // "_blank" | "_self" | "_parent" | "_top"
component?: React.ReactElement | null;
}Supported Languages
- English (en)
- Arabic (ar) — right-to-left
- Bulgarian (bg)
- German (de)
- Greek (el)
- Spanish (es)
- French (fr)
- Belgian French (fr-be)
- Italian (it)
- Polish (pl)
- Portuguese (pt)
- Brazilian Portuguese (pt-br)
- Romanian (ro)
- Serbian (sr)
- Slovak (sk)
- Turkish (tr)
Usage Examples
Basic Widget Setup
This package is designed to work with fansunited-frontend-components:
import { ClassicQuizPlay } from "fansunited-frontend-components";
import {
ClassicQuizTemplate,
CustomThemeOptions,
} from "fansunited-frontend-core";
const customTheme: CustomThemeOptions = {
mode: "light",
colorSchemes: {
light: {
textPrimary: "#333333",
textBody: "#555555",
surface: "#ffffff",
},
},
};
<ClassicQuizPlay
entityId="quiz-123"
sdk={sdkInstance}
template={ClassicQuizTemplate.STANDARD}
language="en"
themeOptions={customTheme}
imagePosition="left"
/>;Lead Collection Setup
import { CollectLead } from "fansunited-frontend-components";
import {
WidgetTemplate,
LeadField,
LeadCustomField,
LeadConsent,
} from "fansunited-frontend-core";
const leadFields: LeadField[] = ["fullName", "email", "phoneNumber"];
const customFields: LeadCustomField[] = [
{
key: "company",
label: "Company Name",
type: "input",
required: true,
placeholder: "Enter your company name",
},
];
const consents: LeadConsent[] = [
{
id: "marketing",
label: "I agree to receive marketing communications",
},
];
<CollectLead
entityId="lead-form-123"
sdk={sdkInstance}
template={WidgetTemplate.OVERLAY}
language="en"
fields={leadFields}
customFields={customFields}
consents={consents}
syncWithProfile={true} // Sync form data to user profile
labels={{
title: "Get Exclusive Updates",
submitButtonLabel: "Subscribe Now",
}}
/>;Profile Consents
ConsentDef is the consent shape shared by Predictor, TopX and ClassicQuizPlay. CollectLead's older LeadConsent (id / label) is still accepted everywhere consents are read.
import { ConsentDef, ConsentsConfig } from "fansunited-frontend-core";
const items: ConsentDef[] = [
{
consentId: "terms",
// HTML and the {{privacyPolicyUrl}} / {{termsAndConditionsUrl}} tokens are supported.
// Tokens link to the entity's branding.urls.
body: "I accept the {{privacyPolicyUrl}} and the {{termsAndConditionsUrl}}",
required: true, // optional, defaults to false — blocks the gate's CTA
position: "before", // ClassicQuizPlay only: "before" (start screen) | "after" (before submit)
},
{
consentId: "marketing",
body: "Send me news and offers by email",
defaultChecked: true, // optional, defaults to false
},
];
// Predictor / TopX take the array directly
<Predictor {...otherProps} consents={items} />;
// ClassicQuizPlay wraps it, so the surface copy travels with it
const consents: ConsentsConfig = {
items,
labels: {
title: "Before we save your score",
ctaLabel: "Continue",
requiredError: "Please accept the required consents to continue.",
},
};
<ClassicQuizPlay {...otherProps} consents={consents} />;Theme Customization
Every component takes these options as its themeOptions prop.
import { CustomThemeOptions, FontConfig } from "fansunited-frontend-core";
const customFont: FontConfig = {
family: "Inter",
url: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",
weights: [400, 500, 600, 700],
display: "swap",
};
const themeOptions: CustomThemeOptions = {
mode: "dark",
customFontFamily: {
light: {
primary: customFont,
secondary: "Arial, sans-serif",
},
dark: {
primary: customFont,
secondary: "Arial, sans-serif",
},
},
spacingScale: {
xs: "6px",
sm: "12px",
md: "18px",
lg: "24px",
},
colorSchemes: {
dark: {
textPrimary: "#ffffff",
surface: "#1a1a1a",
palette: {
primary: {
plainColor: "#3b82f6",
primaryContainer: "#1e40af",
},
},
},
},
};
<Predictor {...otherProps} themeOptions={themeOptions} />;Using Hooks
import {
useLeadForm,
useColors,
UseLeadFormParams,
} from "fansunited-frontend-core";
function MyComponent() {
// Theme utilities
const colors = useColors();
// Lead form management
const leadFormParams: UseLeadFormParams = {
sdk: sdkInstance,
fields: ["fullName", "email"],
campaignId: "newsletter-2024",
contentType: "quiz",
contentId: "quiz-123",
};
const { formData, updateField, submitForm, isSubmitting, isSuccess, error } =
useLeadForm(leadFormParams);
return (
<div style={{ backgroundColor: colors.surface }}>
{/* Your form UI */}
</div>
);
}Country and Language Utilities
import {
countries,
languageToCountryCode,
getDefaultCountryByLanguage,
getDefaultCountryByCode,
} from "fansunited-frontend-core";
// Get all available countries
const allCountries = countries;
// Get suggested countries only
const suggestedCountries = countries.filter((country) => country.suggested);
// Get default country by language
const defaultCountry = getDefaultCountryByLanguage("fr"); // Returns France
// Get country by code
const usCountry = getDefaultCountryByCode("US");Widget Templates
Most components share WidgetTemplate, which has three members:
WidgetTemplate.STANDARD- Traditional card layout with optional image positioningWidgetTemplate.OVERLAY- Full-screen overlay presentationWidgetTemplate.SPLIT- Split-screen layout with content and media sections
Components offering a layout the others do not have their own template type.
ClassicQuizPlay uses ClassicQuizTemplate, which extends WidgetTemplate with a
fourth member:
ClassicQuizTemplate.DECK- Casino-style table where each question is a face-down card the player turns over in any order. Tuned with thedeckprop —entrance, andopenIconwhich takes a preset name or the URL of your own mark (SVG, rendered in a 36 × 36 px box) — and themed throughimageBackgroundGradient.{light,dark}.deck.
PickThePair and the chance games use PickThePairTemplate and ChanceGameTemplate,
which are separate sets rather than extensions.
TypeScript Support
This package is built with TypeScript and provides comprehensive type definitions for all exports. The types ensure type safety when working with widget configurations, theme options, and component props.
License
© Fans United Media. All rights reserved.
