import { AnyStyledComponent, CodeleapStyleRegistry, ICSS, StylePersistor } from '@codeleap/styles' import { StyleSheet } from 'react-native' import { MMKV } from 'react-native-mmkv' const mmkvStorage = new MMKV() const persistor = new StylePersistor({ set(key, value) { return mmkvStorage?.set(key, value) }, get(key) { return mmkvStorage?.getString(key) }, del(key) { return mmkvStorage?.delete(key) }, }) let instance: MobileStyleRegistry const components: CodeleapStyleRegistry['components'][string][] = [] /** * Singleton — the constructor enforces a single instance and returns it on every `new` call, so any module that imports this class and instantiates it will always get the same registry. Components registered via the static `registerComponent` before the first instantiation are buffered in `components[]` and replayed on construction; registrations after instantiation go straight to the live instance. * * `createStyle` passes every style object through `StyleSheet.create` so React Native can intern it on the native side; skipping this would cause equality checks in layout diffing to always fail. */ export class MobileStyleRegistry extends CodeleapStyleRegistry { constructor() { super(persistor) components.forEach((component) => { this.registerComponent(component) }) if (!instance) { instance = this } return instance } createStyle(css: ICSS): ICSS { return StyleSheet.create({ s: css }).s } static get current() { return instance } static registerComponent(component: AnyStyledComponent) { components.push(component) if (instance) { instance.registerComponent(component) } } }