Youll
Modules

Core

The foundation layer of the Youll platform. Contains infrastructure (settings, feature flags, theming, deeplinking, services, storage) and screens for all core product modules (Home, Explore, Search, Library, Journeys, Events, Activity, Meals, Quiz).

Why Core

Core is the largest module in the Youll platform (~672 Swift files). It serves a dual purpose: it provides the infrastructure that every other Bricks module depends on, and it is the home of screens for 11 content-based product modules. Every Bricks module except YoullNetwork and TimerShared depends on Core.

Core provides:

  • Settings actor with 57 persistent properties controlling app behavior
  • Feature flags with 23 remotely configurable flags
  • Deeplink routing with 34 destination types
  • 19 API services for fetching and mutating backend data
  • Screen implementations for Home, Explore, Search, Library, Journeys, Events, Activity, Meals, Quiz, and more
  • Theming system with ~180 design token constants and 20 cell theme configurations
  • Storage property wrappers for UserDefaults and file-based persistence
  • Reusable UI components in both UIKit and SwiftUI
  • Module interface protocols that optional modules (Timer, Tuya, Biometrics, Community) implement

Many of these subsystems are explained at the pattern level in the Architecture section. This page provides the Core-specific details: complete enumerations, file paths, and implementation details that the architecture docs summarize.

Cross-Reference with Architecture Docs

Core SubsystemArchitecture PageWhat This Page Adds
Coordinator protocolCoordinator PatternFile paths, base view controller details
Module interfacesModule InterfacesFile paths per protocol
Settings actorBootstrap Sequence, Communication PatternsComplete property table (57 properties)
Feature flags(brief mentions)Complete flag enum (23 cases), FlaggingManager internals
Design tokens / themingDesign Token SystemThemeTokens paths, cell config types list
Deeplink routingCoordinator PatternComplete DeeplinkDestination enum (34 cases), URL parsing
Bootstrap (Core.setup)Bootstrap SequenceCoreKeysType / ClientKeysType protocol details

Package Definition

Swift tools version: 5.9, Platform: iOS 15+

Dependencies:

DependencyTypePurpose
YoullNetworkLocal packageGraphQL + REST networking, API response types
LNPopupControllerRemote (v4.0.0+)Mini player popup UI
SDWebImageBinary xcframeworkImage downloading and caching
SDWebImageSwiftUIBinary xcframeworkSwiftUI image loading
SDWebImageWebPCoderBinary xcframeworkWebP format support
SnapKitBinary xcframeworkAuto Layout DSL
LottieBinary xcframeworkAnimation rendering
libwebpBinary xcframeworkWebP codec

File: Bricks/modules/Core/Package.swift

Directory Structure

Core/Core/
├── App/                    # Application singletons, keys, module interface protocols
│   ├── Module Interface/   # TimerModuleInterface, TuyaModuleInterface,
│   │                       # BiometricsModuleInterface, CommunityModuleInterface
│   ├── Settings.swift      # Settings actor (57 @UserDefault properties)
│   ├── Keys.swift          # CoreKeysType, ClientKeysType protocols + setup()
│   ├── DownloaderManager   # Background URLSession download manager
│   ├── LocationManager     # CLLocationManager wrapper
│   ├── AppleHealthDelegate # Health authorization protocol
│   ├── CustomSubscriptionsManager  # Custom subscription presentation protocol
│   └── AppLogger           # Logging utility

├── Content/                # Infrastructure layer (not about "content items")
│   ├── Coordinator/        # Base Coordinator protocol
│   ├── Data/               # ContentToConsume, ContentDetailsJourney (player handoff)
│   ├── Deeplinking/        # DeeplinkManager, DeeplinkDestination (34 cases)
│   ├── Flagging/           # Flag enum (23 cases), FlaggingManager, FlagProvider
│   ├── Internal Classes/   # Form components: InputField, YoullTextField, etc.
│   ├── Public Interface/   # UIConfig, ButtonConfig, TextLabelConfig, Toast, etc.
│   ├── Theming/            # ThemeTokens, CellThemeConfigs, CellsThemingLayoutManager
│   └── Views/              # Content-specific views (collection view cells)

├── Data/                   # Data layer
│   ├── API Service/        # 19 API services
│   ├── BNModel/            # 28 mapper extensions (API response -> domain type)
│   ├── CoreModel/          # Domain types (ContentSession, Playlist, etc.)
│   ├── ProfileModel/       # Badge, AppProduct, StoreProduct, SuperPaywall types
│   ├── YNModel/            # Profile utility extensions
│   ├── PlayerPublic/       # Types shared with Player (Asset, PlayerAnalytics)
│   ├── Store/              # StoreKit integration (StoreManager, Subscription)
│   ├── Reminders Service/  # Local notifications, reminders infrastructure
│   ├── Tuya/               # TuyaControllerProtocol, device protocols
│   ├── Onboarding/         # AuthError, AuthProvider, AuthUserData
│   └── Protocols/          # TabSelectionProtocol, RemoteBackgroundImageListenerProtocol

├── Screens/                # 30 directories, organized by product module
│   ├── Home/               # Feed, Cells, DataProvider, DataSource, TagFeed
│   ├── Explore/            # Category Details, Facilitators, Feed, Subcategory Details
│   ├── Search/             # Search + Search Filter (filter subdirectories)
│   ├── Library/            # (+ 7 related directories below)
│   ├── Journeys Feed/      # Regular journeys listing
│   ├── Journey Details/    # Regular journey detail screen
│   ├── Linear Journeys Feed/  # Timeline-based journeys
│   ├── Linear Journey Details/ # Timeline journey detail screen
│   ├── Events/             # EventsList, EventsDetails
│   ├── Activity/           # Workouts, session stats
│   ├── MealPlan/           # MealsPage, MealDetails
│   ├── Quiz/               # Intro, Quiz View, Results
│   ├── Showcase/           # Home screen v2 (SwiftUI + GraphQL)
│   └── ...                 # Shared screens (Welcome, DailyQuote, SkeletonView, etc.)

├── Utils/                  # Extensions and support utilities
│   ├── Categories/         # 38 extension files (UIColor+hex, Date+Utils, etc.)
│   ├── Support/            # Property wrappers, Device, HapticFeedback, etc.
│   ├── Popups/             # LottieView, PopupView, PopupViewConfig
│   └── OptionPicker/       # Generic option picker UI

└── View/                   # Standalone reusable UI components
    ├── UIKit/              # ActivityIndicator, YoullTextButton, etc.
    ├── SwiftUI/            # BottomSheet, ProgressBar, NavigationBar, etc.
    ├── SwiftUI Styles/     # YoullButtonStyles, YoullTextFieldStyles
    └── Review Widget/      # Star rating/review UI (9 files)

Naming Clarifications

Content/ is not about content items. Despite its name, this directory contains infrastructure: the coordinator protocol, deeplinking, flagging, theming, and public interface types. The name is historical.

Two Data/ directories exist. Content/Data/ holds just two types (ContentToConsume and ContentDetailsJourney) used for player handoff. The top-level Data/ directory is the full data layer with services, models, and storage.

Three reusable UI component directories serve different purposes:

  • Content/Internal Classes/: Form input components (text fields, pickers, validators, gradient views)
  • Content/Views/: Content-specific views (collection view cells used in feeds)
  • View/: Standalone reusable components usable anywhere (navigation bars, buttons, empty states, bottom sheets)

Settings

The Settings actor provides 57 static properties persisted via the @UserDefault property wrapper. All properties are public static and thread-safe through actor isolation.

File: Bricks/modules/Core/Core/App/Settings.swift

App Identity

PropertyTypeDefaultPurpose
appIdString?nilApplication identifier
appNameString?nilApplication display name
deeplinkPrefixString?nilPrimary deeplink URL scheme
uniqueDeviceIdentifierString""Unique device ID

Auth State

PropertyTypeDefaultPurpose
cachedIDTokenKeyString?nilCached authentication token
loginTypeString?nilLogin method used (email, Apple, Google, anonymous)

Onboarding

PropertyTypeDefaultPurpose
appFirstTimeOpenedBooltrueWhether app has been opened before
onboardingVideoDisplayedBoolfalseVideo onboarding shown
onboardingSliderDisplayedBoolfalseSlider onboarding shown
onboardingContentDisplayedBoolfalseContent onboarding shown
onboardingTypeOnboardingType.regularOnboarding flow variant (.regular, .dissmissable, .none)
ignoreQuizInOnboardingBoolfalseSkip quiz during onboarding
showWelcomeSessionScreenBoolfalseShow welcome session after onboarding
displayedWelcomeMessageBoolfalseWhether welcome message has been shown

Subscription

PropertyTypeDefaultPurpose
presentSubscriptionScreenAfterLoginBoolfalseShow paywall after login
presentSubscriptionScreenAlwaysOnAppStartBoolfalseShow paywall every app launch
enablePromoOffersBoolfalseEnable promotional offer codes
offerIdsToHide[String][]Offer IDs to exclude from display

Content Behavior

PropertyTypeDefaultPurpose
contentItemOptionsContentItemOptions.defaultOptionsAvailable actions on content items
contentHasLockedStateBooltrueWhether content can be locked/gated
contentPlayedCountInt0Number of content items played
contentItemLongPressGestureEnabledBoolfalseEnable long press on content items
useDefaultSubcategoryTitleFieldInSubcategoryDetailsBooltrueSubcategory title field behavior

Feature Toggles

PropertyTypeDefaultPurpose
isSearchEnabledBooltrueEnable search functionality
isSearchInTabBarBoolfalseShow search as a tab bar item
isLibraryInProfileBoolfalseNest library inside profile instead of its own tab
settingsInProfileBoolfalseShow settings within profile screen
enableVectorSearchBoolfalseUse vector-based search
enableTimerLiveActivityBoolfalseEnable iOS Live Activities for timer
fetchTimerSessionsBoolfalseFetch timer session data from API
hapticksEnabledBoolfalseEnable haptic feedback

UI

PropertyTypeDefaultPurpose
displayHomeScreenGreetingsBooltrueShow greeting messages on home
displaySessionCompleteBooltrueShow session completion screen
showMarketingMediaControllerBoolfalseShow marketing media content
useDynamicFontSizesBoolfalseSupport Dynamic Type
isLiquidGlassEnabledBoolfalseEnable iOS 26 Liquid Glass styling

Downloads / Offline

PropertyTypeDefaultPurpose
downloadedContent[String][]IDs of downloaded content items
offlineMediaProgress[String: BNMediaProgress][:]Offline playback progress per content
offlineQuizAnswers[BNQuizAnswer][]Quiz answers saved while offline

Player

PropertyTypeDefaultPurpose
playerDuckOthersBoolfalseDuck other audio when player is active
resumePlayerOnAppStartBooltrueResume last session on app launch

Misc

PropertyTypeDefaultPurpose
appStartsInt1Number of app launches
minimumAppVersionString""Minimum required app version
exploreTags[Tag][]Cached explore tags
whatsNewPopupHashValueString?nilHash of last shown "what's new"
waitForRemoteConfigValuesRefreshOnFirstAppStartBoolfalseBlock launch until Remote Config refreshes
lastSentFCMTokenString?nilLast Firebase Cloud Messaging token sent
pendingCohortIds[String][]Cohort IDs pending assignment
pendingAppsFlyerDeeplinks[String][]AppsFlyer deeplinks pending processing
eventsNotificationIds[String][]Event notification IDs scheduled
presentedCompletedScreenIDs[String][]Journey completion screens already shown
presentedQuizesIDs[String][]Quizzes already presented
receivedBadgesIDs[String][]Badge IDs already received
allowTrakingBoolfalseUser tracking consent
facebookAppIDString?nilFacebook App ID for Meta SDK
customTimerString?nilCustom timer configuration
didSendFreeTrialEventToMetaBoolfalseWhether free trial event was sent to Meta

Reset

Settings.resetForLogout() clears session-specific properties on logout: appStarts, contentPlayedCount, presentedQuizesIDs, offerIdsToHide.

Feature Flags

Core defines 23 feature flags via the Flag enum. Flags are backed by a remote config service (typically Firebase Remote Config) through the FlagProvider protocol. Customer apps implement FlagProvider and inject it into YouFlaggingManager.

Flag Enum

CaseRaw Value (Remote Config Key)Purpose
remindersreminders_enabledEnable reminders feature
anonymousanonymous_mode_enabledAllow anonymous authentication
healthhealth_enabledEnable Apple Health integration
contentReviewcontent_review_enabledEnable content review/rating
envoyenvoy_enabledEnable content sharing via envoy links
libraryEnabledlibrary_enabledShow Library tab/section
journeysEnabledjourneys_enabledShow Journeys tab/section
superPaywallEnabledsuperpaywall_enabledEnable SuperPaywall feature
downloadsEnableddownloads_enabledAllow content downloads
isLightVersionis_lightLight/free version mode
favouritesEnabledfavourites_enabledEnable favorites
exploreEnabledexplore_enabledShow Explore tab
miniplayerEnabledminiplayer_enabledEnable mini player
quizEnabledquiz_enabledEnable quiz feature
advancedSearchEnabledadvancedsearch_enabledEnable advanced search filters
eventsEnabledevents_enabledEnable events feature
mealsEnabledmeals_enabledEnable meals feature
activityEnabledactivity_enabledEnable activity tracking
paywallConfigIdpaywall_config_idPaywall configuration identifier (string value)
userProfileuser_profileEnable user profile features
poweredBypowered_byShow "powered by" attribution
abOnboardingTypeab_onboarding_typeA/B test onboarding variants (string value)
multilanguageEnabledmultilanguage_enabledEnable multi-language support

FlaggingManager Protocol

public protocol FlaggingManager {
    var didInitialRefresh: Bool { get }
    func isActive(flag: Flag) -> Bool
    func getStringValue(forFlag flag: Flag) -> String?
    func getStringValue(forKey key: String) -> String?
    func refreshFromProvider()
    var flagRefreshCompletedPublisher: AnyPublisher<Void, Never> { get }
}

YouFlaggingManager is the concrete implementation. It wraps any FlagProvider and forwards flag refresh events via a Combine publisher. Customer apps create a FlagProvider (wrapping Firebase Remote Config), pass it to YouFlaggingManager(provider:), and inject the result into Config.

FlagProvider Protocol

public protocol FlagProvider {
    var didInitialRefresh: Bool { get }
    func getState(forFlag flag: Flag) -> Bool
    func getStringValue(forFlag flag: Flag) -> String?
    func getStringValue(forKey key: String) -> String?
    func refreshAllFlags(completion: (() -> Void)?)
    var flagRefreshCompletedPublisher: AnyPublisher<Void, Never> { get }
}

Core never imports Firebase directly. The FlagProvider protocol abstracts away the remote config backend.

Files: Core/Content/Flagging/Flag.swift, Core/Content/Flagging/FlaggingManager.swift, Core/Content/Flagging/FlagProvider.swift, Core/Content/Flagging/YouFlaggingManager.swift

Core defines 34 deeplink destinations and a singleton DeeplinkManager that parses URLs and publishes navigation events.

DeeplinkDestination Enum

AreaCases
Authlogin, subscription
Homehomescreen
Exploreexplore(tagId:), category(id:), subcategory(id:), tag(id:, sortInfo:)
Journeysjourneys, journey(id:), timelineJourney(id:)
Playerplayer(contentId:)
Profileprofile, changePassword, editProfile, badge(id:)
Quizquiz(skipIntro:, quizID:)
Eventsevents, event(id:)
Activityactivities, activityNext, activityCompleted, activityId(id:)
Mealsmeals, meal(id:)
Librarylibrary, favorites, downloads, history, playlist(id:)
Remindersreminders, remindersPopup
ExternalexternalUrl(url:), joinCohorts(ids:, shouldRedirectHome:)
TuyatuyaMaintenance(type:)

DeeplinkManager

DeeplinkManager.shared is a @MainActor singleton that parses deeplink URLs and publishes DeeplinkDestination events via a PassthroughSubject.

URL format: {scheme}://{destination}?param1=value1&param2=value2

Alternative format: {scheme}://rp?path={destination}&param1=value1 (the rp host triggers path-based routing).

The manager supports multiple URL scheme prefixes per app (configured via CoreKeysType.deeplinkPrefixes). For external URLs, it recursively checks whether the URL uses a recognized scheme before treating it as external.

Key methods:

  • handleDeeplink(stringUrl:prefixes:): Parse a URL string and publish the matching destination
  • handleCohortDeeplinks(stringUrls:prefixes:shouldRedirectHome:): Parse cohort-specific URLs and publish joinCohorts
  • run(deeplink:): Directly publish a destination without parsing

Files: Core/Content/Deeplinking/DeeplinkDestination.swift, Core/Content/Deeplinking/DeeplinkManager.swift

Data Layer

API Services

Core provides 19 API services in Data/API Service/. Most services take a BricksNetwork parameter for making network calls. UserService is special: it is created by Config during bootstrap and shared as a singleton.

ServicePurpose
ContentServiceContent CRUD, likes, playlists, journey content, media progress, tracking, vector search, envoy sharing, downloads
HomeFeedServiceHome feed sections and data
ExploreServiceExplore feed categories
JourneyServiceJourney listings and details
LinearJourneyManagerLinear (timeline) journey state management
SearchServiceSearch queries
SearchFiltersServiceSearch filter configuration
LibraryContentServiceLibrary content (favorites, downloads, history, playlists)
FavoriteContentServiceFavorites-specific operations
DownloadedSessionsServiceDownloaded sessions management
EventsContentServiceEvents listing and details
ActivitiesContentServiceActivity and workout content
MealsContentServiceMeal plans and details
QuizServiceQuiz data fetching and answer submission
TagServiceTag-based content queries
UserServiceUser data operations (created by Config, shared singleton)
NavigationContentServiceNavigation content data
PaymentServicePayment and subscription API calls
SettingsServiceSettings-related API calls

Relationship to YoullNetwork: Services use BricksNetwork.shared (from YoullNetwork) to make GraphQL queries and REST calls. The service layer abstracts this, so screens and view models never call BricksNetwork directly.

Data Model Architecture

Data flows through three tiers:

YoullNetwork API Response (generated GraphQL types, BN*/YN* prefixed)

        ▼ BNModel mapper extensions
Core Domain Types (CoreModel, ProfileModel)

        ▼ Used by ViewModels
Screen Display

BNModel (Data/BNModel/, 28 files): Extensions on YoullNetwork response types that convert API data to Core domain types. Naming pattern: BNContent+ContentItem.swift, BNJourney+JourneyItem.swift. These are the translation layer between network responses and the types screens actually use.

CoreModel (Data/CoreModel/): Pure domain types used by screens:

  • ContentSession: A playable content item
  • ContentQuiz: Quiz data and questions
  • JourneyContent: Content within a journey
  • Playlist: User-created playlist
  • HomeNavBarConfig: Home navigation bar configuration
  • LiveUsersInfoConfig: Live user count display
  • OnboardingPage: Onboarding screen configuration
  • SocialProofReview: Social proof review display

ProfileModel (Data/ProfileModel/): Profile-related types: Badge, AppProduct, StoreProduct, UserStats, and SuperPaywall/ types for paywall configuration.

PlayerPublic (Data/PlayerPublic/): Types shared with the Player module: Asset, AssetSource, AssetType, Colors, LabelConfig, PlayerAnalytics.

Content/Data (Content/Data/): Two types for player handoff: ContentToConsume (the struct passed to the player when starting playback) and ContentDetailsJourney.

StoreKit Integration

Data/Store/ contains the StoreKit integration layer:

TypePurpose
StoreManagerManages product fetching and purchase flows
SubscriptionSubscription state and entitlement checking
TransactionObserverObserves StoreKit transaction updates
AppStoreProductStorageCaches fetched App Store product data

StoreManager handles the device-side purchase flow, while PaymentService (in API Services) handles the server-side verification and subscription status. They work together: StoreManager completes the purchase, then PaymentService validates the receipt with the backend.

Reminders Service

Data/Reminders Service/ provides local notification and reminder infrastructure:

TypePurpose
LocalNotificationsManagerSchedule and manage local notifications
NotificationsManagerHigher-level notification coordination
NotificationsPermissionManagerRequest and check notification permissions
RemindersProviderProtocol for reminder data source
RemindersRepositoryReminder persistence
TuyaMaintenanceRemindersServiceTuya device maintenance reminders
UserDefaultsRepositoryUserDefaults-backed persistence for reminders

This subsystem handles local notifications only. Push notification handling lives in the Client module.

Screen Architecture

Screen Pattern

Screens in Core follow a consistent pattern with these file types:

File SuffixPurposeExample
*ScreenConfigFrozen struct with all UI configuration (colors, fonts, spacing, strings). Created by the customer app's ScreenConfigFactory.HomeScreenConfig
*ViewControllerUIViewController (typically subclassing AppearanceCoordinatedViewController). Owns the view and wires up the view model.HomeViewController
*ViewModelObservableObject or class with Combine publishers. Fetches data via services and transforms for display.HomeViewModel
*ViewSwiftUI view or UIKit view. Receives data from the view model and renders UI.HomeView
*DataProvider / *DataSourceData fetching and transformation layer. Provides data to the view model.HomeDataProvider

Not every screen has all five file types. Simpler screens may combine the view and view controller, or omit the data provider.

Screen Directory Catalog

DirectoryProduct ModuleContents
Home/HomeFeed, Cells, DataProvider, DataSource, TagFeed, LiveUsersInfoView
Explore/ExploreCategory Details, Facilitators, Feed, Subcategory Details
Search/, Search Filter/SearchSearch screen + filter subdirectories for each filter type
Library/LibraryLibrary main screen
FavoritesViewController/LibraryFavorites list
HistoryViewController/LibraryPlayback history
PlaylistsViewController/LibraryPlaylists list
PlaylistDetails/LibrarySingle playlist detail
CreatePlaylistViewController/LibraryPlaylist creation
Profile Playlists/LibraryPlaylists shown in profile
Downloaded Sessions/LibraryDownloaded content management
Journeys Feed/Journeys (regular)Standard journey listing
Journey Details/Journeys (regular)Standard journey detail
Linear Journeys Feed/Journeys (linear)Timeline-based journey listing
Linear Journey Details/Journeys (linear)Timeline journey detail
Events/EventsEventsList, EventsDetails, Data, Subviews
Activity/ActivityActivityPage, WorkoutDetails, WorkoutsSeeAll
MealPlan/MealsMealsPage, MealDetails
Quiz/QuizIntro, Quiz View, Results, Answer creation
Showcase/ShowcaseAlternative home screen for hardware-focused apps

Shared screens (not tied to a single product module):

DirectoryPurpose
Welcome/Welcome/onboarding screen
WhatsNewPopup/"What's new" modal
DailyQuoteModal/Daily quote display
InfoBanner/Information banners
SkeletonView/Loading placeholder screens (skeleton UI)
SuggestedContent/Content suggestion displays
TimerSessionsHistory/Timer session history list
Lifetime Access Product/Lifetime access subscription offer
LibraryConfirmationBannerViewController/Library action confirmation banner
SettingsReminderItem/Reminder settings item view

Dual Journey Systems

Core contains two separate journey implementations:

Regular Journeys (Journeys Feed/, Journey Details/): Structured multi-session programs where users can complete sessions in a flexible order. This is the original implementation.

Linear Journeys (Linear Journeys Feed/, Linear Journey Details/): Timeline-based programs with sequential progression. Sessions unlock in order. This is a newer implementation.

Which system is used depends on the .journeys tab item configuration. The useSwiftUIView property on the tab item controls which journey implementation is rendered.

Home Screen Versions

The platform has three home screen implementations, all fully functional and used across different customer apps:

Home v1 (Home/) is the original UIKit-based home screen built on UICollectionView with compositional layout. Uses Hasura/GraphQL for its backend. Supports 27 feed section types. Activated via the .home tab item. Deprecated: existing customers only, new apps should use Showcase v2 or Slices v3.

Showcase v2 (Showcase/) is a SwiftUI rewrite of the home screen. Also uses Hasura/GraphQL for its backend. Originally designed with a device-centric layout for hardware-focused apps but works for any content-on-demand app. Activated via the .showcase or .exploreShowcase tab item.

Slices v3 is the newest SwiftUI home screen. The key difference from Showcase is that it uses REST APIs instead of Hasura/GraphQL. Activated via the .slices tab item.

Keys Protocols

Customer apps implement CoreKeysType (which extends ClientKeysType and WidgetKeysType) to provide app identity and configuration URLs.

public protocol ClientKeysType: WidgetKeysType {
    var appGroupSuiteName: String { get }
    var deeplinkPrefixes: [String] { get }
    var appStoreAppId: String { get }
    var infoEmail: String { get }
    var termsUrl: URL { get }
    var privacyUrl: URL { get }
    var faqUrl: URL { get }
    var aboutUrl: URL { get }
    var yourPageURL: URL { get }
    var appstoreURL: URL { get }
    var shareContentURLFormat: String? { get }  // optional, defaults to nil
    var subscriptionManagementUrl: URL { get }
    var offlineDownloads: String { get }
    var tryAgainOfflineBannerButton: String { get }
    var didMakeVisibleMainCoordinator: String { get }
    var didUpdateRemoteBackgroundImageNotificationName: String { get }
}

public protocol CoreKeysType: ClientKeysType {
    var deeplinkPrefixes: [String] { get }
}

After calling setup(with: CoreKeysType), the keys are accessible globally via the Keys constant. Calling any Core functionality before setup() triggers a fatal error.

File: Bricks/modules/Core/Core/App/Keys.swift

Theming System

For the full design token pipeline (Figma export to runtime), see Design Token System. This section covers Core-specific theming internals.

ThemeTokens

ThemeTokens is a struct with ~180 static string constants representing design token paths. These constants are used by screens and cell configurations to look up colors, sizes, and styles from the parsed design token JSON.

Two formats are used:

Palette references use curly braces: "{Main.main-300}", "{Accent.accent-400}". These reference the color palette directly.

Semantic token paths use slashes: "theme/general/on-background", "theme/buttons/primary/active/surface". These map to semantic UI concepts.

Token areas covered: general, buttons (primary/secondary/tertiary/circled/small/text), navigation (top/bottom/collapsing toolbar), cards, pills, sheets, inputs (search/text/form/dropdown/select), controls (player-progress/interval-selector/switches/quiz-progress), banners (error/warning/success/info), lists, modals, skeleton, player, miniplayer, paywall, onboarding, profile, settings, quiz, showcase, session-end, hardware, biometrics, community, Apple Health.

File: Core/Content/Theming/Tokens/ThemeTokens.swift

Cell Theme Configurations

20 cell theme config types define theming for different cell layouts:

BannerCellThemeConfig, ClassicCardCellThemeConfig, CustomTimerCellThemeConfig, DailyQuoteCellThemeConfig, FeaturedCellThemeConfig, LargeHorizontalCellThemeConfig, LargeVerticalCellThemeConfig, ProgramCardThemeConfig, ProgressCellThemeConfig, SmallCenteredCellThemeConfig, SmallHorizontalCellThemeConfig, SmallHorizontalContentCellConfig, SmallSquareCellThemeConfig, SmallVerticalCellThemeConfig, TagCellThemeConfig, TextCellThemeConfig, TimerSessionCellThemeConfig, TuyaHardwareConfig

The CellsThemingLayoutManagerProtocol is a factory that produces themed cell views for 18+ cell style types (.smallVertical, .smallCentered, .largeVertical, .featured, .facilitator, .events, .timer, .tuyaHardware, etc.). Both UIKit and SwiftUI layout implementations exist.

Directory: Core/Content/Theming/CollectionViewCellsThemingConfigs/, Core/Content/Theming/CellsThemingLayoutManager/

Public Interface Protocols

The Content/Public Interface/ directory (16 files) defines the contract between Core and customer apps/other modules:

Protocol / TypePurpose
UIConfigButton styles, auth buttons, gradients, navigation/tab bar styling, popup bar styling. Has cellsThemingLayoutManager property.
ButtonStyleProtocolFull button theming contract (background, text, border, shadow, corner radius per state)
TypographyTypeProtocolFont, kern, paragraph style for text rendering
FormValidator / ValidatorTypeInput validation types and rules
ToastController / ToastMessage / ToastDelegateToast notification system contracts
AppToastToast singleton (AppToast.shared)
UIManagerUI utility manager
TextLabelConfigLabel configuration (font, color, alignment)
ButtonConfigButton configuration
AuthOption / AuthButtonConfigAuthentication button configuration for login/signup screens
TermsPrivacyConfigTerms of service and privacy policy URL configuration
TextFieldConfig / YoullTextFieldConfigText field appearance and behavior configuration

UI Infrastructure

Toast System

AppToast.shared provides app-wide toast notifications with five styles:

StyleUse Case
.errorError messages
.infoInformational messages
.warningWarning messages
.successSuccess confirmations
.noConnectionNetwork connectivity issues

Components: AppToast (singleton), ToastController (presentation), ToastView (rendering), ToastMessage (protocol), ToastDelegate (action/dismiss callbacks).

Popups

Utils/Popups/ provides Lottie-based animated popup modals: LottieView (animation rendering), PopupView (popup container), PopupViewConfig (configuration).

Base View Controllers

AppearanceCoordinatedViewController is the base UIViewController subclass used across Core screens. It provides:

  • willAppearHandler / willDisappearHandler / didAppearHandler closures for coordinator lifecycle
  • Custom back button support via addCustomBackButton / addBackButton
  • Theme-aware appearance management

AppNavigationController is a custom UINavigationController subclass.

Reusable UIKit Components (View/UIKit/)

ActivityIndicator, BackgroundImageView, ContentGenericCollectionViewCell, FeedEmptyViewCell, NavigationBarCell, PointerUIControl, ReusableView, ScreenEmptyView, SharedScreenHeaderView, SwipeableCollectionViewCell, TimerUserSpentOnScreen, UIKitNavigationBar, UIKitNegativeView, YoullTextButton

Reusable SwiftUI Components (View/SwiftUI/)

AlwaysPopover, BackgroundSwiftUIImageView, BottomSheetSwiftUIView, ContentBottomSheetTitleImageDescription, ContentSessionsListView, GenericEmptyStateView, ProgressBarView, SUIBasicNavigationBar, SUINavigationBar, SUIViewControllerBaseView

SwiftUI Styles (View/SwiftUI Styles/)

HighlightedButtonStyle, YoullButtonStyles, YoullTextFieldStyles, TextLabelStyles, AccessibilityModifier

Form Components (Content/Internal Classes/)

InputField, YoullTextField, YoullTextFieldViewModel, DateTextField, PickerTextField, Validator, GradientLayerView, GradientOverlayView, HighlightedButton, ImageButton, AppNavigationController

Storage Property Wrappers

Core provides two property wrappers for persistent storage in Utils/Support/:

@UserDefault

@propertyWrapper
public struct UserDefault<T: Codable> {
    let key: String
    let defaultValue: T
    let suiteName: String?  // optional, for App Groups
}

Used by all Settings properties. Stores data in UserDefaults.standard (or a named suite for App Groups). Uses JSON encoding/decoding via Codable for complex types. Falls back to direct casting for primitives. Calls synchronize() after writes.

File: Core/Utils/Support/UserDefaults.swift

@FileManagerDataStorage

@propertyWrapper
public struct FileManagerDataStorage<T: Codable> {
    let key: String
    let defaultValue: T
    let suiteName: String?  // optional, for App Groups
}

Persists data as JSON files in the documents directory (or app group container). Uses atomic writes for safety. Appropriate for larger data that would be inappropriate for UserDefaults.

File: Core/Utils/Support/FileManagerDataStorage.swift

Utilities and Extensions

Extension Library (Utils/Categories/, 38 files)

ExtensionPurpose
UIColor+hexInitialize UIColor from hex integers
UIView+RoundCornersCorner radius helpers
UIView+ShadowDrop shadow configuration
UIView+ShimmingShimmer/skeleton loading effect
UIImage+CropImage cropping utilities
UIImage+TemplateTemplate rendering helpers
UIImageView+RemoteRemote image loading via SDWebImage
Date+UtilsDate formatting and comparison
String+CryptoHashing utilities (SHA, MD5)
String+UtilsString manipulation helpers
Double+ExtensionsNumber formatting
URL+ExtensionsURL construction helpers
FileManager+DirDocuments directory path helpers
Bundle+ExtensionsBundle info utilities
ProcessInfo+TestingTest environment detection
Text+LabelConfigSwiftUI Text styled with LabelConfig theming

Support Utilities (Utils/Support/)

UtilityPurpose
DeviceDevice model and capability detection
HapticFeedbackHaptic feedback generation
SoundPlayerSound effect playback
AppReviewRequestApp Store review prompt
AppVersionManagerVersion comparison and forced update checks
LocalizedStringLocalization helpers
AlertViewAlert presentation utilities
ClientNavigationBarNavigation bar customization

Module Interface Protocols

Core defines the interface protocols that optional modules implement. For the full pattern explanation, see Module Interfaces.

ProtocolFile
TimerModuleInterfaceCore/App/Module Interface/TimerModuleInterface.swift
TuyaModuleInterfaceCore/App/Module Interface/TuyaModuleInterface.swift
BiometricsModuleInterfaceCore/App/Module Interface/BiometricsModuleInterface.swift
CommunityModuleInterfaceCore/App/Module Interface/CommunityModuleInterface.swift

Other App-Level Types

TypeFilePurpose
DownloaderManagerCore/App/DownloaderManager.swiftBackground URLSession download manager for offline content. Singleton via .instance.
LocationManagerCore/App/LocationManager.swiftCLLocationManager wrapper. Singleton via .shared.
AppleHealthDelegateCore/App/AppleHealthDelegate.swiftProtocol for HealthKit authorization and data saving.
CustomSubscriptionsManagerCore/App/CustomSubscriptionsManager.swiftProtocol for custom subscription presentation logic.
AppLoggerCore/App/AppLogger.swiftLogging utility. Also: DLog() functions throughout Core for debug logging.

Initialization

Core is initialized by calling setup(with: CoreKeysType) in AppDelegate. This stores the keys globally, making them available via the Keys constant to all Core subsystems. Calling Core functionality before setup triggers a fatal error.

For the full initialization sequence, see Bootstrap Sequence.

For Agents

Reading Order

To understand Core, read in this order:

  1. Core/App/Keys.swift - How Core is configured
  2. Core/App/Settings.swift - All persistent app settings
  3. Core/Content/Flagging/Flag.swift - All feature flags
  4. Core/Content/Coordinator/Coordinator.swift - Base navigation protocol
  5. Core/Content/Deeplinking/DeeplinkDestination.swift - All deeplink targets
  6. Core/Content/Public Interface/UIConfig.swift - The theming contract
  7. Core/Content/Theming/Tokens/ThemeTokens.swift - All design token paths
  8. Core/App/Module Interface/ - All four module interface protocols
  9. One screen directory (e.g., Core/Screens/Home/) to understand the screen pattern

Finding a Screen

To find the screen files for a product module:

  1. Check the screen directory catalog above to find the directory name
  2. Look in Core/Screens/{directory}/
  3. The ScreenConfig struct is defined in the screen directory but created in the customer app's ScreenConfigFactory
  4. The coordinator that presents the screen is in the Client module

Adding a New Setting

  1. Add a new @UserDefault property to Settings.swift
  2. Choose an appropriate key string (prefix with k)
  3. Set a sensible defaultValue
  4. If the setting should be cleared on logout, add it to resetForLogout()
  5. Set the value from the customer app's configuration (typically in AppDelegate or the factory)

Adding a New Feature Flag

  1. Add a new case to the Flag enum in Flag.swift
  2. Set the raw value to the Remote Config key string (convention: snake_case_enabled)
  3. Add the flag to the customer app's Firebase Remote Config
  4. Check the flag via Config.flaggingManager.isActive(flag: .yourNewFlag)
  1. Add a new case to DeeplinkDestination in DeeplinkDestination.swift
  2. Add a matching case to DestinationScreen in DeeplinkManager.swift
  3. Add the routing logic in DeeplinkManager.redirect(to:with:url:)
  4. Handle the destination in the appropriate coordinator in Client

Adding a New API Service

  1. Create a new file in Data/API Service/
  2. Follow the naming pattern: {Feature}Service.swift
  3. Take BricksNetwork as a dependency (or use BricksNetwork.shared)
  4. Use GraphQL via ApolloMission for complex queries, REST for simple operations
  5. Return domain types (from CoreModel/ or create new ones)

On this page