@blac/react 0.0.17 → 0.0.19

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.
@@ -1,31 +1,28 @@
1
- import { Blac, BlocBase, ValueType, BlocConstructor } from 'blac';
2
- import React, { FC, ReactNode } from 'react';
1
+ import { BlocBase, BlocConstructor, ValueType, CubitPropsType } from 'blac/src';
3
2
 
4
- declare const BlacApp: FC<{
5
- children: ReactNode;
6
- blac?: Blac<any>;
7
- }>;
8
-
9
- declare class BlacReact {
10
- static pluginKey: string;
11
- blac: Blac<any>;
12
- blacContext: React.Context<Blac<any>>;
13
- constructor(blac: Blac<any>, blacContext: React.Context<Blac<any>>);
14
- static getInstance(throwError?: boolean): BlacReact;
15
- setup(): void;
16
- }
17
-
18
- interface ExternalStore<B extends BlocBase<any>> {
3
+ interface ExternalStore<B extends BlocBase<S>, S> {
19
4
  subscribe: (onStoreChange: () => void) => () => void;
20
- getSnapshot: () => ValueType<B>;
21
- getServerSnapshot?: () => ValueType<B>;
5
+ getSnapshot: () => S;
6
+ getServerSnapshot?: () => S;
22
7
  }
23
- declare const externalBlocStore: <B extends BlocBase<any>>(bloc: B) => ExternalStore<B>;
8
+ declare const externalBlocStore: <B extends BlocBase<S, {}>, S>(bloc: B, dependencySelector: (state: S) => unknown) => ExternalStore<B, S>;
24
9
 
25
10
  type BlocHookData<B extends BlocBase<S>, S> = [
26
11
  value: ValueType<B>,
27
12
  instance: B
28
13
  ];
29
- declare const useBloc: <B extends BlocBase<S>, S>(bloc: BlocConstructor<B>) => BlocHookData<B, S>;
14
+ interface BlocHookOptions<B extends BlocBase<S>, S> {
15
+ id?: string;
16
+ dependencySelector?: (state: ValueType<B>) => unknown;
17
+ props?: CubitPropsType<B>;
18
+ }
19
+ type BlocHookDependencySelector<B extends BlocBase<S>, S> = (state: ValueType<B>) => unknown;
20
+ declare class UseBlocClass {
21
+ static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B): BlocHookData<InstanceType<B>, S>;
22
+ static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, options: BlocHookOptions<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
23
+ static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, depsSelector: BlocHookDependencySelector<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
24
+ static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, instanceId: string): BlocHookData<InstanceType<B>, S>;
25
+ }
26
+ declare const useBloc: typeof UseBlocClass.useBloc;
30
27
 
31
- export { BlacApp, BlacReact, ExternalStore, externalBlocStore, useBloc };
28
+ export { externalBlocStore, useBloc };
@@ -1,112 +1,482 @@
1
- import { Blac } from 'blac';
2
- import React, { createContext, useMemo, useContext, useSyncExternalStore } from 'react';
1
+ import { useMemo, useSyncExternalStore, useEffect } from 'react';
3
2
 
4
- class BlacReact {
5
- static pluginKey = "blacReact";
6
- blac;
7
- blacContext;
8
- constructor(blac, blacContext) {
9
- const blacReact = blac.getPluginKey(BlacReact.pluginKey);
10
- // new setup
11
- this.blac = blac;
12
- this.blacContext = blacContext;
13
- this.setup();
14
- if (blacReact) {
15
- return blacReact;
16
- }
17
- }
18
- static getInstance(throwError = true) {
19
- // const blac = (globalThis as any).blac;
20
- const blac = BlacContext._currentValue;
21
- if (!blac) {
22
- throw new Error("BlacReact: blac instance not found, the <BlacApp> provider component might be missing");
23
- }
24
- const blacReact = blac.getPluginKey(BlacReact.pluginKey);
25
- if (!blacReact) {
26
- throw new Error("BlacReact: blacReact instance not found");
27
- }
28
- return blacReact;
29
- }
30
- setup() {
31
- // (globalThis as any).blac = this.blac;
32
- this.blac.addPluginKey(BlacReact.pluginKey, this);
33
- }
34
- }
35
-
36
- const BlacContext = createContext(null);
37
- const BlacApp = (props) => {
38
- const { children, blac } = props;
39
- const blacInstance = useMemo(() => blac ?? new Blac(), [blac]);
40
- const blacApp = useMemo(() => new BlacReact(blacInstance, BlacContext), [blacInstance]);
41
- if (!blacApp) {
42
- throw new Error("BlacReact failed to initialize");
43
- }
44
- return React.createElement(BlacContext.Provider, { value: blacInstance }, children);
45
- };
46
-
47
- const externalBlocStore = (bloc) => {
3
+ var externalBlocStore = function (bloc, dependencySelector) {
4
+ var lastDependencyCheck = dependencySelector(bloc.state);
48
5
  return {
49
- subscribe: (listener) => {
50
- const unSub = bloc.onStateChange(listener);
51
- return () => {
6
+ subscribe: function (listener) {
7
+ var unSub = bloc.addEventListenerStateChange(function (data) {
8
+ var newDependencyCheck = dependencySelector(data);
9
+ if (newDependencyCheck !== lastDependencyCheck) {
10
+ lastDependencyCheck = newDependencyCheck;
11
+ listener();
12
+ }
13
+ });
14
+ return function () {
52
15
  unSub();
53
16
  };
54
17
  },
55
- getSnapshot: () => bloc.state
18
+ getSnapshot: function () { return bloc.state; },
19
+ getServerSnapshot: function () { return bloc.state; },
56
20
  };
57
21
  };
58
22
 
59
- const resolveBloc = ({ bloc, blacInstance, blacReact
60
- // create
61
- }) => {
62
- // check if its a create function or a class
63
- const isFunction = bloc instanceof Function;
64
- const isBloc = isFunction && bloc?.isBlacClass;
65
- const isLiveBloc = !isFunction &&
66
- typeof bloc === "object" &&
67
- bloc?.isBlacLive;
68
- // if it is a create function, call it
69
- if (!isBloc && isFunction) {
70
- return bloc();
23
+ /******************************************************************************
24
+ Copyright (c) Microsoft Corporation.
25
+
26
+ Permission to use, copy, modify, and/or distribute this software for any
27
+ purpose with or without fee is hereby granted.
28
+
29
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
30
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
31
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
32
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
33
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
35
+ PERFORMANCE OF THIS SOFTWARE.
36
+ ***************************************************************************** */
37
+ /* global Reflect, Promise, SuppressedError, Symbol */
38
+
39
+ var extendStatics = function(d, b) {
40
+ extendStatics = Object.setPrototypeOf ||
41
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
43
+ return extendStatics(d, b);
44
+ };
45
+
46
+ function __extends(d, b) {
47
+ if (typeof b !== "function" && b !== null)
48
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
49
+ extendStatics(d, b);
50
+ function __() { this.constructor = d; }
51
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
52
+ }
53
+
54
+ var __assign = function() {
55
+ __assign = Object.assign || function __assign(t) {
56
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
57
+ s = arguments[i];
58
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
59
+ }
60
+ return t;
61
+ };
62
+ return __assign.apply(this, arguments);
63
+ };
64
+
65
+ function __awaiter(thisArg, _arguments, P, generator) {
66
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
67
+ return new (P || (P = Promise))(function (resolve, reject) {
68
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
69
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
70
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
71
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
72
+ });
73
+ }
74
+
75
+ function __generator(thisArg, body) {
76
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
77
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
78
+ function verb(n) { return function (v) { return step([n, v]); }; }
79
+ function step(op) {
80
+ if (f) throw new TypeError("Generator is already executing.");
81
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
82
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
83
+ if (y = 0, t) op = [op[0] & 2, t.value];
84
+ switch (op[0]) {
85
+ case 0: case 1: t = op; break;
86
+ case 4: _.label++; return { value: op[1], done: false };
87
+ case 5: _.label++; y = op[1]; op = [0]; continue;
88
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
89
+ default:
90
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
91
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
92
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
93
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
94
+ if (t[2]) _.ops.pop();
95
+ _.trys.pop(); continue;
96
+ }
97
+ op = body.call(thisArg, _);
98
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
99
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
100
+ }
101
+ }
102
+
103
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
104
+ var e = new Error(message);
105
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
106
+ };
107
+
108
+ var BlacEvent;
109
+ (function (BlacEvent) {
110
+ BlacEvent["BLOC_DISPOSED"] = "BLOC_DISPOSED";
111
+ BlacEvent["LISTENER_REMOVED"] = "LISTENER_REMOVED";
112
+ BlacEvent["LISTENER_ADDED"] = "LISTENER_ADDED";
113
+ BlacEvent["STATE_CHANGED"] = "STATE_CHANGED";
114
+ BlacEvent["BLOC_CREATED"] = "BLOC_CREATED";
115
+ })(BlacEvent || (BlacEvent = {}));
116
+ var Blac = /** @class */ (function () {
117
+ function Blac() {
118
+ var _this = this;
119
+ this.blocInstanceMap = new Map();
120
+ this.isolatedBlocMap = new Map();
121
+ this.pluginList = [];
122
+ this.customPropsMap = new Map();
123
+ this.postChangesToDocument = false;
124
+ this.addPlugin = function (plugin) {
125
+ // check if already added
126
+ var index = _this.pluginList.findIndex(function (p) { return p.name === plugin.name; });
127
+ if (index !== -1)
128
+ return;
129
+ _this.pluginList.push(plugin);
130
+ };
131
+ this.reportToPlugins = function (event, bloc, params) {
132
+ _this.pluginList.forEach(function (plugin) {
133
+ plugin.onEvent(event, bloc, params);
134
+ });
135
+ };
136
+ this.report = function (event, bloc, params) {
137
+ var base = bloc.constructor;
138
+ switch (event) {
139
+ case BlacEvent.BLOC_DISPOSED:
140
+ _this.disposeBloc(bloc);
141
+ break;
142
+ case BlacEvent.LISTENER_REMOVED:
143
+ if (bloc.observer.size === 0 && !base.keepAlive)
144
+ _this.disposeBloc(bloc);
145
+ break;
146
+ }
147
+ _this.reportToPlugins(event, bloc, params);
148
+ };
149
+ this.disposeBloc = function (bloc) {
150
+ var base = bloc.constructor;
151
+ if (!base.isolated) {
152
+ _this.unregisterBlocInstance(bloc);
153
+ }
154
+ else {
155
+ _this.unregisterIsolatedBlocInstance(bloc);
156
+ }
157
+ };
158
+ this.getAllBlocs = function (blocClass, options) {
159
+ if (options === void 0) { options = {}; }
160
+ return __awaiter(_this, void 0, void 0, function () {
161
+ var base, searchIsolated, blocs, blocs;
162
+ var _a;
163
+ return __generator(this, function (_b) {
164
+ base = blocClass;
165
+ searchIsolated = (_a = options.searchIsolated, _a === void 0 ? base.isolated : _a);
166
+ if (searchIsolated) {
167
+ blocs = this.isolatedBlocMap.get(blocClass);
168
+ if (blocs)
169
+ return [2 /*return*/, blocs];
170
+ }
171
+ else {
172
+ blocs = Array.from(this.blocInstanceMap.values());
173
+ return [2 /*return*/, blocs.filter(function (b) { return b instanceof blocClass; })];
174
+ }
175
+ return [2 /*return*/, []];
176
+ });
177
+ });
178
+ };
179
+ this.configure = function (config) {
180
+ if (config.exposeBlacInstance) ;
181
+ };
182
+ if (Blac.instance) {
183
+ return Blac.instance;
184
+ }
185
+ Blac.instance = this;
186
+ console.log('Blac Init');
71
187
  }
72
- if (bloc?.isBlacLive) {
73
- return bloc;
188
+ Blac.getInstance = function () {
189
+ return Blac.instance;
190
+ };
191
+ Blac.prototype.createBlocInstanceMapKey = function (blocClassName, id) {
192
+ return "".concat(blocClassName, ":").concat(id);
193
+ };
194
+ Blac.prototype.unregisterBlocInstance = function (bloc) {
195
+ var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
196
+ this.blocInstanceMap.delete(key);
197
+ };
198
+ Blac.prototype.registerBlocInstance = function (bloc) {
199
+ var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
200
+ this.blocInstanceMap.set(key, bloc);
201
+ };
202
+ Blac.prototype.findRegisteredBlocInstance = function (blocClass, id) {
203
+ var base = blocClass;
204
+ if (base.isolated)
205
+ return undefined;
206
+ var key = this.createBlocInstanceMapKey(blocClass.name, id);
207
+ return this.blocInstanceMap.get(key);
208
+ };
209
+ Blac.prototype.registerIsolatedBlocInstance = function (bloc) {
210
+ var blocClass = bloc.constructor;
211
+ var blocs = this.isolatedBlocMap.get(blocClass);
212
+ if (blocs) {
213
+ blocs.push(bloc);
214
+ }
215
+ else {
216
+ this.isolatedBlocMap.set(blocClass, [bloc]);
217
+ }
218
+ };
219
+ Blac.prototype.unregisterIsolatedBlocInstance = function (bloc) {
220
+ var blocClass = bloc.constructor;
221
+ var blocs = this.isolatedBlocMap.get(blocClass);
222
+ if (blocs) {
223
+ var index = blocs.findIndex(function (b) { return b.id === bloc.id; });
224
+ blocs.splice(index, 1);
225
+ }
226
+ };
227
+ Blac.prototype.setCustomProps = function (blocClass, props) {
228
+ if (!props)
229
+ return;
230
+ this.customPropsMap.set(blocClass, props);
231
+ };
232
+ Blac.prototype.getCustomProps = function (blocClass) {
233
+ var props = this.customPropsMap.get(blocClass);
234
+ this.customPropsMap.delete(blocClass);
235
+ return props;
236
+ };
237
+ Blac.prototype.createNewBlocInstance = function (blocClass, id, props) {
238
+ var base = blocClass;
239
+ var hasCreateMethod = Object.prototype.hasOwnProperty.call(blocClass, 'create');
240
+ this.setCustomProps(base, props);
241
+ var newBloc = hasCreateMethod ? base.create() : new blocClass();
242
+ newBloc.updateId(id);
243
+ if (base.isolated) {
244
+ this.registerIsolatedBlocInstance(newBloc);
245
+ return newBloc;
246
+ }
247
+ this.registerBlocInstance(newBloc);
248
+ return newBloc;
249
+ };
250
+ Blac.prototype.getBloc = function (blocClass, options) {
251
+ if (options === void 0) { options = {}; }
252
+ var id = options.id || blocClass.name;
253
+ var registered = this.findRegisteredBlocInstance(blocClass, id);
254
+ var reconnect = options.reconnect;
255
+ if (registered) {
256
+ if (reconnect) {
257
+ registered.dispose();
258
+ }
259
+ else {
260
+ return registered;
261
+ }
262
+ }
263
+ return this.createNewBlocInstance(blocClass, id, options.props);
264
+ };
265
+ Blac.instance = new Blac();
266
+ Blac.getAllBlocs = Blac.instance.getAllBlocs;
267
+ Blac.addPlugin = Blac.instance.addPlugin;
268
+ Blac.configure = Blac.instance.configure;
269
+ return Blac;
270
+ }());
271
+
272
+ var BlacObservable = /** @class */ (function () {
273
+ function BlacObservable() {
274
+ this._observers = new Set();
74
275
  }
75
- // if it is a class
76
- const blocClass = bloc;
77
- if (isLiveBloc) {
78
- return bloc;
276
+ Object.defineProperty(BlacObservable.prototype, "size", {
277
+ get: function () {
278
+ return this._observers.size;
279
+ },
280
+ enumerable: false,
281
+ configurable: true
282
+ });
283
+ BlacObservable.prototype.subscribe = function (observer) {
284
+ var _this = this;
285
+ this._observers.add(observer);
286
+ return function () { return _this.unsubscribe(observer); };
287
+ };
288
+ BlacObservable.prototype.unsubscribe = function (observer) {
289
+ this._observers.delete(observer);
290
+ };
291
+ BlacObservable.prototype.notify = function (newState, oldState) {
292
+ this._observers.forEach(function (observer) { return observer(newState, oldState); });
293
+ };
294
+ BlacObservable.prototype.dispose = function () {
295
+ this._observers.clear();
296
+ };
297
+ return BlacObservable;
298
+ }());
299
+
300
+ var BlocBase = /** @class */ (function () {
301
+ // onConnect(): void;
302
+ // onDisconnect(): void;
303
+ function BlocBase(initialState) {
304
+ var _this = this;
305
+ this.isolated = false;
306
+ this.isBlacLive = true;
307
+ this.blac = Blac.getInstance();
308
+ this.props = {};
309
+ this.createdAt = Date.now();
310
+ this.updateId = function (id) {
311
+ var originalId = _this.id;
312
+ if (!id || id === originalId)
313
+ return;
314
+ _this.id = id;
315
+ };
316
+ this.addEventListenerStateChange = function (callback) {
317
+ _this.blac.report(BlacEvent.LISTENER_ADDED, _this);
318
+ _this.observer.subscribe(callback);
319
+ return function () { return _this.handleUnsubscribe(callback); };
320
+ };
321
+ this.handleUnsubscribe = function (callback) {
322
+ _this.observer.unsubscribe(callback);
323
+ _this.blac.report(BlacEvent.LISTENER_REMOVED, _this);
324
+ };
325
+ this.observer = new BlacObservable();
326
+ this._state = initialState;
327
+ this.blac.report(BlacEvent.BLOC_CREATED, this);
328
+ this.id = this.constructor.name;
329
+ this.isolated = this.constructor.isolated;
330
+ // this.onConnect?.();
79
331
  }
80
- const registered = blacReact.blac.getBloc(blocClass);
81
- if (registered) {
82
- return registered;
332
+ Object.defineProperty(BlocBase.prototype, "state", {
333
+ get: function () {
334
+ return this._state;
335
+ },
336
+ enumerable: false,
337
+ configurable: true
338
+ });
339
+ Object.defineProperty(BlocBase.prototype, "name", {
340
+ get: function () {
341
+ return this.constructor.name;
342
+ },
343
+ enumerable: false,
344
+ configurable: true
345
+ });
346
+ BlocBase.prototype.dispose = function () {
347
+ this.blac.report(BlacEvent.BLOC_DISPOSED, this);
348
+ this.isBlacLive = false;
349
+ this.observer.dispose();
350
+ // this.onDisconnect?.();
351
+ };
352
+ BlocBase.isolated = false;
353
+ BlocBase.keepAlive = false;
354
+ BlocBase.isBlacClass = true;
355
+ return BlocBase;
356
+ }());
357
+
358
+ /** @class */ ((function (_super) {
359
+ __extends(Cubit, _super);
360
+ function Cubit(initialState) {
361
+ var _this = _super.call(this, initialState) || this;
362
+ _this.props = {};
363
+ var newProps = Blac.getInstance().getCustomProps(_this.constructor);
364
+ _this.props = __assign(__assign({}, _this.props), newProps);
365
+ return _this;
83
366
  }
84
- };
85
- const useResolvedBloc = (bloc) => {
86
- const blacReact = BlacReact.getInstance();
87
- const blacInstance = useContext(BlacContext);
88
- const resolvedBloc = useMemo(() => {
89
- if (!blacReact) {
90
- return undefined;
367
+ /**
368
+ * Update the state then will notify all observers
369
+ * @param state: new state
370
+ **/
371
+ Cubit.prototype.emit = function (state) {
372
+ if (state === this.state) {
373
+ return;
91
374
  }
92
- return resolveBloc({
93
- bloc,
94
- blacInstance,
95
- blacReact
375
+ var oldState = this.state;
376
+ var newState = state;
377
+ this._state = state;
378
+ this.observer.notify(newState, oldState);
379
+ this.blac.report(BlacEvent.STATE_CHANGED, this, {
380
+ newState: newState,
381
+ oldState: oldState,
96
382
  });
97
- }, []);
98
- return resolvedBloc;
99
- };
383
+ };
384
+ /**
385
+ * Merges current state object with the parameter "state" and emits the new state
386
+ * Warning: only works when the state is an object.
387
+ * @param state: Partial state that should change
388
+ **/
389
+ Cubit.prototype.patch = function (statePatch, ignoreChangeCheck) {
390
+ if (ignoreChangeCheck === void 0) { ignoreChangeCheck = false; }
391
+ var changes = false;
392
+ if (!ignoreChangeCheck) {
393
+ for (var key in statePatch) {
394
+ var current = this.state[key];
395
+ if (statePatch[key] !== current) {
396
+ changes = true;
397
+ break;
398
+ }
399
+ }
400
+ }
401
+ if (changes) {
402
+ this.emit(__assign(__assign({}, this.state), statePatch));
403
+ }
404
+ };
405
+ return Cubit;
406
+ })(BlocBase));
100
407
 
101
- const useBloc = (bloc) => {
102
- const resolvedBloc = useResolvedBloc(bloc);
103
- if (!resolvedBloc) {
104
- throw new Error(`useBloc: could not resolve: ${bloc.name || bloc}`);
408
+ /** @class */ ((function (_super) {
409
+ __extends(Bloc, _super);
410
+ function Bloc() {
411
+ var _this = _super !== null && _super.apply(this, arguments) || this;
412
+ /**
413
+ * Emit a new action, the reducer should digest the action and update the state accordingly
414
+ * @param action: action t obe sent to the reducer
415
+ */
416
+ _this.emit = function (action) {
417
+ var oldState = _this.state;
418
+ var newState = _this.reducer(action, _this.state);
419
+ _this._state = newState;
420
+ _this.observer.notify(newState, oldState);
421
+ _this.blac.report(BlacEvent.STATE_CHANGED, _this, {
422
+ newState: newState,
423
+ oldState: oldState,
424
+ });
425
+ };
426
+ return _this;
105
427
  }
106
- const { subscribe, getSnapshot } = useMemo(() => externalBlocStore(resolvedBloc), [resolvedBloc]);
107
- const state = useSyncExternalStore(subscribe, getSnapshot);
108
- return [state, resolvedBloc];
109
- };
428
+ return Bloc;
429
+ })(BlocBase));
430
+
431
+ var UseBlocClass = /** @class */ (function () {
432
+ function UseBlocClass() {
433
+ }
434
+ UseBlocClass.useBloc = function (bloc, options) {
435
+ var _a, _b;
436
+ // default options
437
+ var dependencySelector = function (state) { return state; };
438
+ var blocId;
439
+ var props = {};
440
+ // parse options
441
+ // if options is a function, its a dependencySelector
442
+ if (typeof options === 'function') {
443
+ dependencySelector = options;
444
+ }
445
+ // if options is a string its an ID
446
+ if (typeof options === 'string') {
447
+ blocId = options;
448
+ }
449
+ if (typeof options === 'object') {
450
+ dependencySelector = (_a = options.dependencySelector) !== null && _a !== void 0 ? _a : dependencySelector;
451
+ blocId = options.id;
452
+ props = (_b = options.props) !== null && _b !== void 0 ? _b : props;
453
+ }
454
+ // const now = Date.now();
455
+ // const createdAt = useRef(now);
456
+ // const dateChanged = now !== createdAt;
457
+ // resolve the bloc, get the existing instance of the bloc or create a new one
458
+ // const resolvedBloc = useMemo(
459
+ // () =>
460
+ var resolvedBloc = Blac.getInstance().getBloc(bloc, {
461
+ id: blocId,
462
+ props: props,
463
+ reconnect: false,
464
+ });
465
+ // [renderId.current],
466
+ // );
467
+ if (!resolvedBloc) {
468
+ throw new Error("useBloc: could not resolve: ".concat(bloc.name || bloc));
469
+ }
470
+ var _c = useMemo(function () { return externalBlocStore(resolvedBloc, dependencySelector); }, [resolvedBloc.createdAt]), subscribe = _c.subscribe, getSnapshot = _c.getSnapshot, getServerSnapshot = _c.getServerSnapshot;
471
+ var state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
472
+ useEffect(function () {
473
+ resolvedBloc.props = props;
474
+ }, [props]);
475
+ return [state, resolvedBloc];
476
+ };
477
+ return UseBlocClass;
478
+ }());
479
+ var useBloc = UseBlocClass.useBloc;
110
480
 
111
- export { BlacApp, BlacReact, externalBlocStore, useBloc };
481
+ export { externalBlocStore, useBloc };
112
482
  //# sourceMappingURL=blac-react.esm.js.map