npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

fansunited-frontend-core

v1.1.1

Published

Core types, components, providers and constants for Fans United widgets

Readme

Fans United Frontend Core

Core utilities, types, and shared functionality for Fans United widget packages.

Installation

npm install fansunited-frontend-core
yarn add fansunited-frontend-core

Peer 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 betslipApi from fansunited-frontend-components, not from fansunited-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 componentEvents from fansunited-frontend-components, not from fansunited-frontend-core — same reason as betslipApi. 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:

  1. Custom Component - If component is provided, it will be rendered
  2. Click Handler - If onClick is provided, a button with the handler will be rendered
  3. URL Navigation - If url is 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 positioning
  • WidgetTemplate.OVERLAY - Full-screen overlay presentation
  • WidgetTemplate.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 the deck prop — entrance, and openIcon which takes a preset name or the URL of your own mark (SVG, rendered in a 36 × 36 px box) — and themed through imageBackgroundGradient.{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.