@blac/core 0.1.0 → 2.0.0-rc-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Main Blac class that manages the state management system.
3
+ * Implements a singleton pattern to ensure only one instance exists.
4
+ * Handles bloc lifecycle, plugin management, and instance tracking.
5
+ *
6
+ * Key responsibilities:
7
+ * - Managing bloc instances (creation, disposal, lookup)
8
+ * - Handling isolated and non-isolated blocs
9
+ * - Managing plugins and lifecycle events
10
+ * - Providing logging and debugging capabilities
11
+ */
12
+ export declare class Blac {
13
+ /** The singleton instance of Blac */
14
+ static instance: Blac;
15
+ /** Timestamp when the instance was created */
16
+ createdAt: number;
17
+ static getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
18
+ searchIsolated?: boolean;
19
+ }) => InstanceType<B>[];
20
+ static addPlugin: (plugin: BlacPlugin) => void;
21
+ /** Map storing all registered bloc instances by their class name and ID */
22
+ blocInstanceMap: Map<string, BlocBase<any>>;
23
+ /** Map storing isolated bloc instances grouped by their constructor */
24
+ isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<any>[]>;
25
+ pluginList: BlacPlugin[];
26
+ /** Flag to control whether changes should be posted to document */
27
+ postChangesToDocument: boolean;
28
+ /**
29
+ * Creates a new Blac instance.
30
+ * @param options - Configuration options including singleton control
31
+ */
32
+ constructor(options?: {
33
+ __unsafe_ignore_singleton?: boolean;
34
+ });
35
+ /** Flag to enable/disable logging */
36
+ static enableLog: boolean;
37
+ /**
38
+ * Logs messages to console when logging is enabled
39
+ * @param args - Arguments to log
40
+ */
41
+ log: (...args: unknown[]) => void;
42
+ static log: (...args: unknown[]) => void;
43
+ /**
44
+ * Gets the singleton instance of Blac
45
+ * @returns The Blac instance
46
+ */
47
+ static getInstance(): Blac;
48
+ /**
49
+ * Logs a warning message
50
+ * @param message - Warning message
51
+ * @param args - Additional arguments
52
+ */
53
+ warn: (message: string, ...args: unknown[]) => void;
54
+ static warn: (message: string, ...args: unknown[]) => void;
55
+ /**
56
+ * Logs an error message
57
+ * @param message - Error message
58
+ * @param args - Additional arguments
59
+ */
60
+ error: (message: string, ...args: unknown[]) => void;
61
+ static error: (message: string, ...args: unknown[]) => void;
62
+ /**
63
+ * Resets the Blac instance to a new one, disposing non-keepAlive blocs
64
+ * from the old instance.
65
+ */
66
+ resetInstance: () => void;
67
+ static resetInstance: () => void;
68
+ /**
69
+ * Adds a plugin to the Blac instance
70
+ * @param plugin - The plugin to add
71
+ */
72
+ addPlugin: (plugin: BlacPlugin) => void;
73
+ /**
74
+ * Dispatches a lifecycle event to all registered plugins
75
+ * @param event - The lifecycle event to dispatch
76
+ * @param bloc - The bloc instance involved in the event
77
+ * @param params - Additional parameters for the event
78
+ */
79
+ dispatchEventToPlugins: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
80
+ /**
81
+ * Dispatches a lifecycle event and handles related cleanup actions.
82
+ * This method is responsible for:
83
+ * - Logging the event
84
+ * - Handling bloc disposal when needed
85
+ * - Managing bloc consumer cleanup
86
+ * - Forwarding the event to plugins
87
+ *
88
+ * @param event - The lifecycle event to dispatch
89
+ * @param bloc - The bloc instance involved in the event
90
+ * @param params - Additional parameters for the event
91
+ */
92
+ dispatchEvent: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
93
+ /**
94
+ * Disposes of a bloc instance by removing it from the appropriate registry
95
+ * @param bloc - The bloc instance to dispose
96
+ */
97
+ disposeBloc: (bloc: BlocBase<any>) => void;
98
+ /**
99
+ * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
100
+ * @param blocClassName - The name of the bloc class
101
+ * @param id - The instance ID
102
+ * @returns A unique key string in the format "className:id"
103
+ */
104
+ createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
105
+ /**
106
+ * Unregister a bloc instance from the main registry
107
+ * @param bloc - The bloc instance to unregister
108
+ */
109
+ unregisterBlocInstance(bloc: BlocBase<any>): void;
110
+ /**
111
+ * Registers a bloc instance in the main registry
112
+ * @param bloc - The bloc instance to register
113
+ */
114
+ registerBlocInstance(bloc: BlocBase<any>): void;
115
+ /**
116
+ * Finds a registered bloc instance by its class and ID
117
+ * @param blocClass - The bloc class to search for
118
+ * @param id - The instance ID
119
+ * @returns The found bloc instance or undefined if not found
120
+ */
121
+ findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
122
+ /**
123
+ * Registers an isolated bloc instance in the isolated registry
124
+ * @param bloc - The isolated bloc instance to register
125
+ */
126
+ registerIsolatedBlocInstance(bloc: BlocBase<any>): void;
127
+ /**
128
+ * Unregister an isolated bloc instance from the isolated registry
129
+ * @param bloc - The isolated bloc instance to unregister
130
+ */
131
+ unregisterIsolatedBlocInstance(bloc: BlocBase<any>): void;
132
+ /**
133
+ * Finds an isolated bloc instance by its class and ID
134
+ */
135
+ findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
136
+ /**
137
+ * Creates a new bloc instance and registers it in the appropriate registry
138
+ * @param blocClass - The bloc class to instantiate
139
+ * @param id - The instance ID
140
+ * @param props - Properties to pass to the bloc constructor
141
+ * @param instanceRef - Optional reference string for the instance
142
+ * @returns The newly created bloc instance
143
+ */
144
+ createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
145
+ /**
146
+ * Gets or creates a bloc instance based on the provided class and options.
147
+ * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
148
+ *
149
+ * @param blocClass - The bloc class to get or create
150
+ * @param options - Options including:
151
+ * - id: The instance ID (defaults to class name if not provided)
152
+ * - props: Properties to pass to the bloc constructor
153
+ * - instanceRef: Optional reference string for the instance
154
+ * @returns The bloc instance
155
+ */
156
+ getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
157
+ static getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
158
+ /**
159
+ * Gets a bloc instance or throws an error if it doesn't exist
160
+ * @param blocClass - The bloc class to get
161
+ * @param options - Options including:
162
+ * - id: The instance ID (defaults to class name if not provided)
163
+ * - props: Properties to pass to the bloc constructor
164
+ * - instanceRef: Optional reference string for the instance
165
+ */
166
+ getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
167
+ id?: BlocInstanceId;
168
+ props?: InferPropsFromGeneric<B>;
169
+ instanceRef?: string;
170
+ }) => InstanceType<B>;
171
+ static getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
172
+ id?: BlocInstanceId;
173
+ props?: InferPropsFromGeneric<B> | undefined;
174
+ instanceRef?: string;
175
+ }) => InstanceType<B>;
176
+ /**
177
+ * Gets all instances of a specific bloc class
178
+ * @param blocClass - The bloc class to search for
179
+ * @param options - Options including:
180
+ * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
181
+ * @returns Array of matching bloc instances
182
+ */
183
+ getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
184
+ searchIsolated?: boolean;
185
+ }) => InstanceType<B>[];
186
+ }
187
+
188
+ declare type BlacAddon = {
189
+ name: string;
190
+ onInit?: BlacAddonInit;
191
+ onEmit?: BlacAddonEmit;
192
+ };
193
+
194
+ declare type BlacAddonEmit = (params: {
195
+ oldState: unknown;
196
+ newState: unknown;
197
+ cubit: BlocBase<any>;
198
+ }) => void;
199
+
200
+ declare type BlacAddonInit = (bloc: BlocBase<any>) => void;
201
+
202
+ /**
203
+ * Configuration options for the Blac instance
204
+ */
205
+ export declare interface BlacConfig {
206
+ /** Whether to expose the Blac instance globally */
207
+ exposeBlacInstance?: boolean;
208
+ }
209
+
210
+ /**
211
+ * Enum representing different lifecycle events that can occur in the Blac system.
212
+ * These events are used to track the lifecycle of blocs and their consumers.
213
+ */
214
+ export declare enum BlacLifecycleEvent {
215
+ BLOC_DISPOSED = "BLOC_DISPOSED",
216
+ BLOC_CREATED = "BLOC_CREATED",
217
+ LISTENER_REMOVED = "LISTENER_REMOVED",
218
+ LISTENER_ADDED = "LISTENER_ADDED",
219
+ STATE_CHANGED = "STATE_CHANGED",
220
+ BLOC_CONSUMER_REMOVED = "BLOC_CONSUMER_REMOVED",
221
+ BLOC_CONSUMER_ADDED = "BLOC_CONSUMER_ADDED"
222
+ }
223
+
224
+ /**
225
+ * A class that manages observers for a Bloc's state changes
226
+ * @template S - The type of state being observed
227
+ */
228
+ export declare class BlacObservable<S = unknown> {
229
+ /** The Bloc instance this observable is associated with */
230
+ bloc: BlocBase<S>;
231
+ /**
232
+ * Creates a new BlacObservable instance
233
+ * @param bloc - The Bloc instance to observe
234
+ */
235
+ constructor(bloc: BlocBase<S>);
236
+ private _observers;
237
+ /**
238
+ * Gets the number of active observers
239
+ * @returns The number of observers currently subscribed
240
+ */
241
+ get size(): number;
242
+ /**
243
+ * Gets the set of all observers
244
+ * @returns The Set of all BlacObserver instances
245
+ */
246
+ get observers(): Set<BlacObserver<S>>;
247
+ /**
248
+ * Subscribes an observer to state changes
249
+ * @param observer - The observer to subscribe
250
+ * @returns A function that can be called to unsubscribe the observer
251
+ */
252
+ subscribe(observer: BlacObserver<S>): () => void;
253
+ /**
254
+ * Unsubscribes an observer from state changes
255
+ * @param observer - The observer to unsubscribe
256
+ */
257
+ unsubscribe(observer: BlacObserver<S>): void;
258
+ /**
259
+ * Notifies all observers of a state change
260
+ * @param newState - The new state value
261
+ * @param oldState - The previous state value
262
+ * @param action - Optional action that triggered the state change
263
+ */
264
+ notify(newState: S, oldState: S, action?: unknown): void;
265
+ /**
266
+ * Disposes of all observers and clears the observer set
267
+ */
268
+ dispose(): void;
269
+ }
270
+
271
+ /**
272
+ * Represents an observer that can subscribe to state changes in a Bloc
273
+ * @template S - The type of state being observed
274
+ */
275
+ export declare type BlacObserver<S> = {
276
+ /** Function to be called when state changes */
277
+ fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;
278
+ /** Optional function to determine if the observer should be notified of state changes */
279
+ dependencyArray?: BlocHookDependencyArrayFn<S>;
280
+ /** Dispose function for the observer */
281
+ dispose?: () => void;
282
+ /** Cached state values used for dependency comparison */
283
+ lastState?: unknown[][];
284
+ /** Unique identifier for the observer */
285
+ id: string;
286
+ };
287
+
288
+ export declare interface BlacPlugin {
289
+ name: string;
290
+ onEvent(event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown): void;
291
+ }
292
+
293
+ export declare abstract class Bloc<S, // State type
294
+ A extends object, // Base Action/Event type, constrained to object
295
+ P = unknown> extends BlocBase<S, P> {
296
+ readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
297
+ /**
298
+ * Registers an event handler for a specific event type.
299
+ * This method is typically called in the constructor of a derived Bloc class.
300
+ * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
301
+ * @param handler A function that processes the event and can emit new states.
302
+ * The 'event' parameter in the handler will be typed to the specific eventConstructor.
303
+ */
304
+ protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
305
+ /**
306
+ * Dispatches an action/event to the Bloc.
307
+ * If a handler is registered for this specific event type (via 'on'), it will be invoked.
308
+ * Asynchronous handlers are awaited.
309
+ * @param action The action/event instance to be processed.
310
+ */
311
+ add: (action: A) => Promise<void>;
312
+ }
313
+
314
+ /**
315
+ * Base class for both Blocs and Cubits that provides core state management functionality.
316
+ * Handles state transitions, observer notifications, lifecycle management, and addon integration.
317
+ *
318
+ * @abstract This class should be extended, not instantiated directly
319
+ * @template S The type of state managed by this Bloc
320
+ * @template P The type of props that can be passed during instance creation (optional)
321
+ */
322
+ export declare abstract class BlocBase<S, P = unknown> {
323
+ /**
324
+ * When true, every consumer will receive its own unique instance of this Bloc.
325
+ * Use this when state should not be shared between components.
326
+ * @default false
327
+ */
328
+ static isolated: boolean;
329
+ get isIsolated(): boolean;
330
+ /**
331
+ * When true, the Bloc instance persists even when there are no active consumers.
332
+ * Useful for maintaining state between component unmount/remount cycles.
333
+ * @default false
334
+ */
335
+ static keepAlive: boolean;
336
+ get isKeepAlive(): boolean;
337
+ /**
338
+ * Defines how dependencies are selected from the state for efficient updates.
339
+ * When provided, observers will only be notified when selected dependencies change.
340
+ */
341
+ defaultDependencySelector: DependencySelector<S> | undefined;
342
+ /* Excluded from this release type: _addons */
343
+ /* Excluded from this release type: _isolated */
344
+ /* Excluded from this release type: _observer */
345
+ /* Excluded from this release type: _blac */
346
+ /**
347
+ * The unique identifier for this Bloc instance.
348
+ * Defaults to the class name, but can be customized.
349
+ */
350
+ _id: BlocInstanceId;
351
+ /* Excluded from this release type: _instanceRef */
352
+ /* Excluded from this release type: _keepAlive */
353
+ /**
354
+ * @readonly
355
+ * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.
356
+ */
357
+ readonly _createdAt: number;
358
+ /* Excluded from this release type: _state */
359
+ /* Excluded from this release type: _oldState */
360
+ /**
361
+ * Props passed during Bloc instance creation.
362
+ * Can be used to configure or parameterize the Bloc's behavior.
363
+ */
364
+ props: P | null;
365
+ /**
366
+ * Creates a new BlocBase instance with the given initial state.
367
+ * Sets up the observer, registers with the Blac manager, and initializes addons.
368
+ *
369
+ * @param initialState The initial state value for this Bloc
370
+ */
371
+ constructor(initialState: S);
372
+ /**
373
+ * Returns the current state of the Bloc.
374
+ * Use this getter to access the state in a read-only manner.
375
+ */
376
+ get state(): S;
377
+ /* Excluded from this release type: _name */
378
+ /* Excluded from this release type: _updateId */
379
+ /* Excluded from this release type: _dispose */
380
+ /* Excluded from this release type: onDispose */
381
+ /* Excluded from this release type: _consumers */
382
+ /* Excluded from this release type: _addConsumer */
383
+ /* Excluded from this release type: _removeConsumer */
384
+ /* Excluded from this release type: _connectAddons */
385
+ lastUpdate: number;
386
+ /* Excluded from this release type: _pushState */
387
+ }
388
+
389
+ /**
390
+ * Represents the abstract base types for Bloc and Cubit
391
+ */
392
+ export declare type BlocBaseAbstract = typeof Bloc<any, any, any> | typeof Cubit<any, any>;
393
+
394
+ /**
395
+ * Represents a constructor type for a Bloc that takes no parameters
396
+ * @template B - The type of the Bloc instance
397
+ */
398
+ export declare type BlocClassNoParams<B> = new (args: never[]) => B;
399
+
400
+ /**
401
+ * Represents a constructor type for a Bloc that can take any parameters
402
+ * @template B - The type of the Bloc instance
403
+ */
404
+ export declare type BlocConstructor<B> = new (...args: any) => B;
405
+
406
+ /**
407
+ * Extracts the constructor parameters type from a BlocBase
408
+ * @template B - The BlocBase type to extract the constructor parameters from
409
+ */
410
+ export declare type BlocConstructorParameters<B extends BlocBase<any>> = BlocConstructor<B> extends new (...args: infer P) => B ? P : never;
411
+
412
+ /**
413
+ * Represents a function type for determining hook dependencies based on state changes
414
+ * @template B - The BlocGeneric type
415
+ */
416
+ export declare type BlocHookDependencyArrayFn<S> = (newState: S) => unknown[][];
417
+
418
+ export declare type BlocInstanceId = string | number | undefined;
419
+
420
+ /**
421
+ * Extracts the state type from either a Bloc or Cubit
422
+ * @template T - The Bloc or Cubit type to extract the state from
423
+ */
424
+ export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
425
+
426
+ /**
427
+ * A Cubit is a simpler version of a Bloc that doesn't handle events.
428
+ * It manages state and provides methods to update it.
429
+ * @template S - The type of state this Cubit manages
430
+ * @template P - The type of parameters (optional, defaults to null)
431
+ */
432
+ export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
433
+ /**
434
+ * Updates the current state and notifies all observers of the change.
435
+ * If the new state is identical to the current state (using Object.is),
436
+ * no update will occur.
437
+ * @param state - The new state to set
438
+ */
439
+ emit(state: S): void;
440
+ /**
441
+ * Partially updates the current state by merging it with the provided state patch.
442
+ * This method is only applicable when the state is an object type.
443
+ *
444
+ * @param statePatch - A partial state object containing only the properties to update
445
+ * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
446
+ * @throws {TypeError} If the state is not an object type
447
+ */
448
+ patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
449
+ }
450
+
451
+ declare type DependencySelector<S> = (newState: S) => unknown[][];
452
+
453
+ export declare interface GetBlocOptions<B extends BlocBase<any>> {
454
+ id?: string;
455
+ selector?: BlocHookDependencyArrayFn<BlocState<B>>;
456
+ props?: InferPropsFromGeneric<B>;
457
+ onMount?: (bloc: B) => void;
458
+ instanceRef?: string;
459
+ }
460
+
461
+ /**
462
+ * Extracts the props type from either a Bloc or Cubit
463
+ * @template T - The Bloc or Cubit type to extract the props from
464
+ */
465
+ export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
466
+
467
+ /**
468
+ * Persist addon
469
+ *
470
+ * @param options
471
+ * @returns BlacAddon
472
+ */
473
+ export declare function Persist(options?: {
474
+ /**
475
+ * @default 'blac'
476
+ */
477
+ keyPrefix?: string;
478
+ /**
479
+ * @default the bloc's id
480
+ */
481
+ keyName?: string;
482
+ /**
483
+ * Used when the value is not found in storage
484
+ */
485
+ defaultValue?: unknown;
486
+ /**
487
+ * @default 'localStorage'
488
+ * @see StorageType
489
+ */
490
+ storageType?: StorageType;
491
+ /**
492
+ * @default false
493
+ */
494
+ onError?: (e: unknown) => void;
495
+ }): BlacAddon;
496
+
497
+ declare type StorageType = 'localStorage' | 'sessionStorage';
498
+
499
+ /**
500
+ * Extracts the state type from a BlocBase instance
501
+ * @template B - The BlocBase type to extract the state from
502
+ */
503
+ export declare type ValueType<B extends BlocBase<any>> = B extends BlocBase<infer U> ? U : never;
504
+
505
+ export { }