import type { ImageStyle, TextStyle, ViewStyle } from 'react-native'; import type { FlexTokens } from '../flex/tokens.types'; import type { ThemeState } from '../flex/themeState.types'; type AnyStyle = ViewStyle | ImageStyle | TextStyle; /** * Ordered hierarchy levels. Each level contains mutually exclusive states in * precedence order. */ export type StateLevels = readonly (readonly string[])[]; /** * Every state declared in a hierarchy. */ export type StateNames = Levels[number][number]; type StateEntries = Levels extends readonly [ infer Head extends readonly string[], ...infer Tail extends StateLevels, ] ? Partial>> & StateEntries : unknown; /** * Every valid ordered state path, including paths that skip hierarchy levels * to provide fallback styles. */ export type StatePath = Levels extends readonly [ infer Head extends readonly string[], ...infer Tail extends StateLevels, ] ? Head[number] | StatePath | `${Head[number]}.${StatePath & string}` : never; /** * A flattened style set containing the base style and every explicitly * defined state path. */ export type BranchedStyles = { base: StyleType; } & Partial, StyleType>>; /** * A hierarchical style definition. A state can contain states from any later * hierarchy level, while later-level states can also appear at the base as * fallbacks. */ export type StyleDefinition = StyleType & StateEntries; /** * Source of active states, either an array of names or an object whose truthy * properties indicate active states. */ export type StateSource = Partial> | readonly States[]; /** * Factory function for generating a style definition from theme tokens. */ export type StyleDefFromTokens = ( tokens: FlexTokens, ) => StyleDefinition; function hasState(source: StateSource, state: string): boolean { if (Array.isArray(source)) { return source.includes(state); } return Boolean((source as Partial>)[state]); } /** * Picks the first active state according to the supplied precedence order. */ export function getActiveState(source: StateSource, states?: readonly States[]): States | undefined { for (const state of states ?? []) { if (hasState(source, state)) { return state; } } return undefined; } interface ActiveState { level: number; name: string; } function getActiveStatePaths(source: StateSource>, stateLevels: Levels): string[] { const activeStates: ActiveState[] = []; for (const [level, states] of stateLevels.entries()) { const name = getActiveState(source, states); if (name) { activeStates.push({ level, name }); } } const combinations: ActiveState[][] = [[]]; for (const activeState of activeStates) { const existingCombinations = [...combinations]; for (const combination of existingCombinations) { combinations.push([...combination, activeState]); } } return combinations .filter((combination) => combination.length > 0) .sort((left, right) => { if (left.length !== right.length) { return right.length - left.length; } for (let index = left.length - 1; index >= 0; index--) { const levelDifference = right[index].level - left[index].level; if (levelDifference !== 0) { return levelDifference; } } return 0; }) .map((combination) => combination.map(({ name }) => name).join('.')); } /** * Selects the most specific defined state path. Paths with more active states * win, followed by paths containing states from deeper hierarchy levels. */ export function pickActiveStyle( state: StateSource>, stateLevels: Levels, styles: BranchedStyles, ): StyleType { for (const path of getActiveStatePaths(state, stateLevels)) { const style = (styles as Partial>)[path]; if (style !== undefined) { return style; } } return styles.base; } function isStyle(value: unknown): value is AnyStyle { return typeof value === 'object' && value !== null && !Array.isArray(value); } /** * Creates a state-to-level lookup and rejects ambiguous hierarchies. */ export function createStateLevelMap(stateLevels: StateLevels): ReadonlyMap { const stateLevelMap = new Map(); for (const [level, states] of stateLevels.entries()) { for (const state of states) { if (stateLevelMap.has(state)) { throw new TypeError(`State "${state}" must belong to only one hierarchy level.`); } stateLevelMap.set(state, level); } } return stateLevelMap; } function flattenStyleDefinition( target: Record, definition: Record, stateLevelMap: ReadonlyMap, nextLevel: number, path: readonly string[], inheritedStyle: StyleType, ): void { const localStyle = {} as StyleType; const childStates: { definition: StyleType; level: number; name: string }[] = []; for (const [key, value] of Object.entries(definition)) { const stateLevel = stateLevelMap.get(key); if (stateLevel === undefined) { Object.assign(localStyle, { [key]: value }); continue; } if (stateLevel < nextLevel) { throw new TypeError(`State "${key}" cannot be nested beneath a state from the same or a later hierarchy level.`); } if (value === undefined) { continue; } if (!isStyle(value)) { throw new TypeError(`State style "${key}" must be an object.`); } childStates.push({ definition: value as StyleType, level: stateLevel, name: key }); } const resolvedStyle = { ...inheritedStyle, ...localStyle }; target[path.length > 0 ? path.join('.') : 'base'] = resolvedStyle; for (const child of childStates) { flattenStyleDefinition( target, child.definition as Record, stateLevelMap, child.level + 1, [...path, child.name], resolvedStyle, ); } } /** * Flattens a hierarchical style definition and applies ancestor inheritance * to every explicitly defined state path. */ export function styleDefinitionToBranchedStyles( styles: StyleDefinition, stateLevels: Levels, ): BranchedStyles { const result: Record = {}; const stateLevelMap = createStateLevelMap(stateLevels); flattenStyleDefinition(result, styles as Record, stateLevelMap, 0, [], {} as StyleType); return result as BranchedStyles; } /** * Creates a state style getter that lazily flattens and caches one definition. */ export function getStateStyleFactory( definition: StyleDefinition, stateLevels: Levels, ): (source: StateSource>) => StyleType { let branchedStyles: BranchedStyles | undefined; return (source) => { branchedStyles ??= styleDefinitionToBranchedStyles(definition, stateLevels); return pickActiveStyle(source, stateLevels, branchedStyles); }; } /** * Creates a state style getter that resolves and caches one definition per * ThemeState. */ export function getThemedStateStyleFactory( name: string, factory: StyleDefFromTokens, stateLevels: Levels, ): (state: ThemeState, source: StateSource>) => StyleType { const cacheKey = Symbol(name); return (state, source) => { const cachedStyles = state.themeStyles[cacheKey] as BranchedStyles | undefined; const branchedStyles = cachedStyles ?? styleDefinitionToBranchedStyles(factory(state.tokens), stateLevels); if (!cachedStyles) { state.themeStyles[cacheKey] = branchedStyles; } return pickActiveStyle(source, stateLevels, branchedStyles); }; }