New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@blac/react

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@blac/react - npm Package Compare versions

Comparing version 0.0.18 to 0.0.19

18

dist/blac-react.d.ts

@@ -1,9 +0,9 @@

import { BlocBase, ValueType, BlocConstructor, BlocInstanceId, CubitPropsType } from 'blac';
import { BlocBase, BlocConstructor, ValueType, CubitPropsType } from 'blac/src';
interface ExternalStore<B extends BlocBase<any>> {
interface ExternalStore<B extends BlocBase<S>, S> {
subscribe: (onStoreChange: () => void) => () => void;
getSnapshot: () => ValueType<B>;
getServerSnapshot?: () => ValueType<B>;
getSnapshot: () => S;
getServerSnapshot?: () => S;
}
declare const externalBlocStore: <B extends BlocBase<any>>(bloc: B, dependencySelector: (state: ValueType<B>) => unknown) => ExternalStore<B>;
declare const externalBlocStore: <B extends BlocBase<S, {}>, S>(bloc: B, dependencySelector: (state: S) => unknown) => ExternalStore<B, S>;

@@ -21,6 +21,6 @@ type BlocHookData<B extends BlocBase<S>, S> = [

declare class UseBlocClass {
static useBloc<B extends BlocBase<S>, S>(bloc: BlocConstructor<B>): BlocHookData<B, S>;
static useBloc<B extends BlocBase<S>, S>(bloc: BlocConstructor<B>, options: BlocHookOptions<B, S>): BlocHookData<B, S>;
static useBloc<B extends BlocBase<S>, S>(bloc: BlocConstructor<B>, depsSelector: BlocHookDependencySelector<B, S>): BlocHookData<B, S>;
static useBloc<B extends BlocBase<S>, S>(bloc: BlocConstructor<B>, instanceId: BlocInstanceId): BlocHookData<B, S>;
static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B): BlocHookData<InstanceType<B>, S>;
static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, options: BlocHookOptions<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, depsSelector: BlocHookDependencySelector<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, instanceId: string): BlocHookData<InstanceType<B>, S>;
}

@@ -27,0 +27,0 @@ declare const useBloc: typeof UseBlocClass.useBloc;

import { useMemo, useSyncExternalStore, useEffect } from 'react';
import { Blac } from 'blac';

@@ -20,14 +19,414 @@ var externalBlocStore = function (bloc, dependencySelector) {

getSnapshot: function () { return bloc.state; },
getServerSnapshot: function () { return bloc.state; }
getServerSnapshot: function () { return bloc.state; },
};
};
var useResolvedBloc = function (bloc, options) {
if (options === void 0) { options = {}; }
return useMemo(function () { return Blac.getInstance().getBloc(bloc, {
id: options.id,
props: options.props
}); }, [options.id]);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var BlacEvent;
(function (BlacEvent) {
BlacEvent["BLOC_DISPOSED"] = "BLOC_DISPOSED";
BlacEvent["LISTENER_REMOVED"] = "LISTENER_REMOVED";
BlacEvent["LISTENER_ADDED"] = "LISTENER_ADDED";
BlacEvent["STATE_CHANGED"] = "STATE_CHANGED";
BlacEvent["BLOC_CREATED"] = "BLOC_CREATED";
})(BlacEvent || (BlacEvent = {}));
var Blac = /** @class */ (function () {
function Blac() {
var _this = this;
this.blocInstanceMap = new Map();
this.isolatedBlocMap = new Map();
this.pluginList = [];
this.customPropsMap = new Map();
this.postChangesToDocument = false;
this.addPlugin = function (plugin) {
// check if already added
var index = _this.pluginList.findIndex(function (p) { return p.name === plugin.name; });
if (index !== -1)
return;
_this.pluginList.push(plugin);
};
this.reportToPlugins = function (event, bloc, params) {
_this.pluginList.forEach(function (plugin) {
plugin.onEvent(event, bloc, params);
});
};
this.report = function (event, bloc, params) {
var base = bloc.constructor;
switch (event) {
case BlacEvent.BLOC_DISPOSED:
_this.disposeBloc(bloc);
break;
case BlacEvent.LISTENER_REMOVED:
if (bloc.observer.size === 0 && !base.keepAlive)
_this.disposeBloc(bloc);
break;
}
_this.reportToPlugins(event, bloc, params);
};
this.disposeBloc = function (bloc) {
var base = bloc.constructor;
if (!base.isolated) {
_this.unregisterBlocInstance(bloc);
}
else {
_this.unregisterIsolatedBlocInstance(bloc);
}
};
this.getAllBlocs = function (blocClass, options) {
if (options === void 0) { options = {}; }
return __awaiter(_this, void 0, void 0, function () {
var base, searchIsolated, blocs, blocs;
var _a;
return __generator(this, function (_b) {
base = blocClass;
searchIsolated = (_a = options.searchIsolated, _a === void 0 ? base.isolated : _a);
if (searchIsolated) {
blocs = this.isolatedBlocMap.get(blocClass);
if (blocs)
return [2 /*return*/, blocs];
}
else {
blocs = Array.from(this.blocInstanceMap.values());
return [2 /*return*/, blocs.filter(function (b) { return b instanceof blocClass; })];
}
return [2 /*return*/, []];
});
});
};
this.configure = function (config) {
if (config.exposeBlacInstance) ;
};
if (Blac.instance) {
return Blac.instance;
}
Blac.instance = this;
console.log('Blac Init');
}
Blac.getInstance = function () {
return Blac.instance;
};
Blac.prototype.createBlocInstanceMapKey = function (blocClassName, id) {
return "".concat(blocClassName, ":").concat(id);
};
Blac.prototype.unregisterBlocInstance = function (bloc) {
var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
this.blocInstanceMap.delete(key);
};
Blac.prototype.registerBlocInstance = function (bloc) {
var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
this.blocInstanceMap.set(key, bloc);
};
Blac.prototype.findRegisteredBlocInstance = function (blocClass, id) {
var base = blocClass;
if (base.isolated)
return undefined;
var key = this.createBlocInstanceMapKey(blocClass.name, id);
return this.blocInstanceMap.get(key);
};
Blac.prototype.registerIsolatedBlocInstance = function (bloc) {
var blocClass = bloc.constructor;
var blocs = this.isolatedBlocMap.get(blocClass);
if (blocs) {
blocs.push(bloc);
}
else {
this.isolatedBlocMap.set(blocClass, [bloc]);
}
};
Blac.prototype.unregisterIsolatedBlocInstance = function (bloc) {
var blocClass = bloc.constructor;
var blocs = this.isolatedBlocMap.get(blocClass);
if (blocs) {
var index = blocs.findIndex(function (b) { return b.id === bloc.id; });
blocs.splice(index, 1);
}
};
Blac.prototype.setCustomProps = function (blocClass, props) {
if (!props)
return;
this.customPropsMap.set(blocClass, props);
};
Blac.prototype.getCustomProps = function (blocClass) {
var props = this.customPropsMap.get(blocClass);
this.customPropsMap.delete(blocClass);
return props;
};
Blac.prototype.createNewBlocInstance = function (blocClass, id, props) {
var base = blocClass;
var hasCreateMethod = Object.prototype.hasOwnProperty.call(blocClass, 'create');
this.setCustomProps(base, props);
var newBloc = hasCreateMethod ? base.create() : new blocClass();
newBloc.updateId(id);
if (base.isolated) {
this.registerIsolatedBlocInstance(newBloc);
return newBloc;
}
this.registerBlocInstance(newBloc);
return newBloc;
};
Blac.prototype.getBloc = function (blocClass, options) {
if (options === void 0) { options = {}; }
var id = options.id || blocClass.name;
var registered = this.findRegisteredBlocInstance(blocClass, id);
var reconnect = options.reconnect;
if (registered) {
if (reconnect) {
registered.dispose();
}
else {
return registered;
}
}
return this.createNewBlocInstance(blocClass, id, options.props);
};
Blac.instance = new Blac();
Blac.getAllBlocs = Blac.instance.getAllBlocs;
Blac.addPlugin = Blac.instance.addPlugin;
Blac.configure = Blac.instance.configure;
return Blac;
}());
var BlacObservable = /** @class */ (function () {
function BlacObservable() {
this._observers = new Set();
}
Object.defineProperty(BlacObservable.prototype, "size", {
get: function () {
return this._observers.size;
},
enumerable: false,
configurable: true
});
BlacObservable.prototype.subscribe = function (observer) {
var _this = this;
this._observers.add(observer);
return function () { return _this.unsubscribe(observer); };
};
BlacObservable.prototype.unsubscribe = function (observer) {
this._observers.delete(observer);
};
BlacObservable.prototype.notify = function (newState, oldState) {
this._observers.forEach(function (observer) { return observer(newState, oldState); });
};
BlacObservable.prototype.dispose = function () {
this._observers.clear();
};
return BlacObservable;
}());
var BlocBase = /** @class */ (function () {
// onConnect(): void;
// onDisconnect(): void;
function BlocBase(initialState) {
var _this = this;
this.isolated = false;
this.isBlacLive = true;
this.blac = Blac.getInstance();
this.props = {};
this.createdAt = Date.now();
this.updateId = function (id) {
var originalId = _this.id;
if (!id || id === originalId)
return;
_this.id = id;
};
this.addEventListenerStateChange = function (callback) {
_this.blac.report(BlacEvent.LISTENER_ADDED, _this);
_this.observer.subscribe(callback);
return function () { return _this.handleUnsubscribe(callback); };
};
this.handleUnsubscribe = function (callback) {
_this.observer.unsubscribe(callback);
_this.blac.report(BlacEvent.LISTENER_REMOVED, _this);
};
this.observer = new BlacObservable();
this._state = initialState;
this.blac.report(BlacEvent.BLOC_CREATED, this);
this.id = this.constructor.name;
this.isolated = this.constructor.isolated;
// this.onConnect?.();
}
Object.defineProperty(BlocBase.prototype, "state", {
get: function () {
return this._state;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BlocBase.prototype, "name", {
get: function () {
return this.constructor.name;
},
enumerable: false,
configurable: true
});
BlocBase.prototype.dispose = function () {
this.blac.report(BlacEvent.BLOC_DISPOSED, this);
this.isBlacLive = false;
this.observer.dispose();
// this.onDisconnect?.();
};
BlocBase.isolated = false;
BlocBase.keepAlive = false;
BlocBase.isBlacClass = true;
return BlocBase;
}());
/** @class */ ((function (_super) {
__extends(Cubit, _super);
function Cubit(initialState) {
var _this = _super.call(this, initialState) || this;
_this.props = {};
var newProps = Blac.getInstance().getCustomProps(_this.constructor);
_this.props = __assign(__assign({}, _this.props), newProps);
return _this;
}
/**
* Update the state then will notify all observers
* @param state: new state
**/
Cubit.prototype.emit = function (state) {
if (state === this.state) {
return;
}
var oldState = this.state;
var newState = state;
this._state = state;
this.observer.notify(newState, oldState);
this.blac.report(BlacEvent.STATE_CHANGED, this, {
newState: newState,
oldState: oldState,
});
};
/**
* Merges current state object with the parameter "state" and emits the new state
* Warning: only works when the state is an object.
* @param state: Partial state that should change
**/
Cubit.prototype.patch = function (statePatch, ignoreChangeCheck) {
if (ignoreChangeCheck === void 0) { ignoreChangeCheck = false; }
var changes = false;
if (!ignoreChangeCheck) {
for (var key in statePatch) {
var current = this.state[key];
if (statePatch[key] !== current) {
changes = true;
break;
}
}
}
if (changes) {
this.emit(__assign(__assign({}, this.state), statePatch));
}
};
return Cubit;
})(BlocBase));
/** @class */ ((function (_super) {
__extends(Bloc, _super);
function Bloc() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Emit a new action, the reducer should digest the action and update the state accordingly
* @param action: action t obe sent to the reducer
*/
_this.emit = function (action) {
var oldState = _this.state;
var newState = _this.reducer(action, _this.state);
_this._state = newState;
_this.observer.notify(newState, oldState);
_this.blac.report(BlacEvent.STATE_CHANGED, _this, {
newState: newState,
oldState: oldState,
});
};
return _this;
}
return Bloc;
})(BlocBase));
var UseBlocClass = /** @class */ (function () {

@@ -43,9 +442,11 @@ function UseBlocClass() {

// parse options
if (typeof options === "function") {
// if options is a function, its a dependencySelector
if (typeof options === 'function') {
dependencySelector = options;
}
if (typeof options === "string") {
// if options is a string its an ID
if (typeof options === 'string') {
blocId = options;
}
if (typeof options === "object") {
if (typeof options === 'object') {
dependencySelector = (_a = options.dependencySelector) !== null && _a !== void 0 ? _a : dependencySelector;

@@ -55,7 +456,19 @@ blocId = options.id;

}
var resolvedBloc = useResolvedBloc(bloc, { id: blocId, props: props });
// const now = Date.now();
// const createdAt = useRef(now);
// const dateChanged = now !== createdAt;
// resolve the bloc, get the existing instance of the bloc or create a new one
// const resolvedBloc = useMemo(
// () =>
var resolvedBloc = Blac.getInstance().getBloc(bloc, {
id: blocId,
props: props,
reconnect: false,
});
// [renderId.current],
// );
if (!resolvedBloc) {
throw new Error("useBloc: could not resolve: ".concat(bloc.name || bloc));
}
var _c = useMemo(function () { return externalBlocStore(resolvedBloc, dependencySelector); }, [resolvedBloc]), subscribe = _c.subscribe, getSnapshot = _c.getSnapshot, getServerSnapshot = _c.getServerSnapshot;
var _c = useMemo(function () { return externalBlocStore(resolvedBloc, dependencySelector); }, [resolvedBloc.createdAt]), subscribe = _c.subscribe, getSnapshot = _c.getSnapshot, getServerSnapshot = _c.getServerSnapshot;
var state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);

@@ -62,0 +475,0 @@ useEffect(function () {

'use strict';
var react = require('react');
var blac = require('blac');

@@ -22,14 +21,414 @@ var externalBlocStore = function (bloc, dependencySelector) {

getSnapshot: function () { return bloc.state; },
getServerSnapshot: function () { return bloc.state; }
getServerSnapshot: function () { return bloc.state; },
};
};
var useResolvedBloc = function (bloc, options) {
if (options === void 0) { options = {}; }
return react.useMemo(function () { return blac.Blac.getInstance().getBloc(bloc, {
id: options.id,
props: options.props
}); }, [options.id]);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var BlacEvent;
(function (BlacEvent) {
BlacEvent["BLOC_DISPOSED"] = "BLOC_DISPOSED";
BlacEvent["LISTENER_REMOVED"] = "LISTENER_REMOVED";
BlacEvent["LISTENER_ADDED"] = "LISTENER_ADDED";
BlacEvent["STATE_CHANGED"] = "STATE_CHANGED";
BlacEvent["BLOC_CREATED"] = "BLOC_CREATED";
})(BlacEvent || (BlacEvent = {}));
var Blac = /** @class */ (function () {
function Blac() {
var _this = this;
this.blocInstanceMap = new Map();
this.isolatedBlocMap = new Map();
this.pluginList = [];
this.customPropsMap = new Map();
this.postChangesToDocument = false;
this.addPlugin = function (plugin) {
// check if already added
var index = _this.pluginList.findIndex(function (p) { return p.name === plugin.name; });
if (index !== -1)
return;
_this.pluginList.push(plugin);
};
this.reportToPlugins = function (event, bloc, params) {
_this.pluginList.forEach(function (plugin) {
plugin.onEvent(event, bloc, params);
});
};
this.report = function (event, bloc, params) {
var base = bloc.constructor;
switch (event) {
case BlacEvent.BLOC_DISPOSED:
_this.disposeBloc(bloc);
break;
case BlacEvent.LISTENER_REMOVED:
if (bloc.observer.size === 0 && !base.keepAlive)
_this.disposeBloc(bloc);
break;
}
_this.reportToPlugins(event, bloc, params);
};
this.disposeBloc = function (bloc) {
var base = bloc.constructor;
if (!base.isolated) {
_this.unregisterBlocInstance(bloc);
}
else {
_this.unregisterIsolatedBlocInstance(bloc);
}
};
this.getAllBlocs = function (blocClass, options) {
if (options === void 0) { options = {}; }
return __awaiter(_this, void 0, void 0, function () {
var base, searchIsolated, blocs, blocs;
var _a;
return __generator(this, function (_b) {
base = blocClass;
searchIsolated = (_a = options.searchIsolated, _a === void 0 ? base.isolated : _a);
if (searchIsolated) {
blocs = this.isolatedBlocMap.get(blocClass);
if (blocs)
return [2 /*return*/, blocs];
}
else {
blocs = Array.from(this.blocInstanceMap.values());
return [2 /*return*/, blocs.filter(function (b) { return b instanceof blocClass; })];
}
return [2 /*return*/, []];
});
});
};
this.configure = function (config) {
if (config.exposeBlacInstance) ;
};
if (Blac.instance) {
return Blac.instance;
}
Blac.instance = this;
console.log('Blac Init');
}
Blac.getInstance = function () {
return Blac.instance;
};
Blac.prototype.createBlocInstanceMapKey = function (blocClassName, id) {
return "".concat(blocClassName, ":").concat(id);
};
Blac.prototype.unregisterBlocInstance = function (bloc) {
var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
this.blocInstanceMap.delete(key);
};
Blac.prototype.registerBlocInstance = function (bloc) {
var key = this.createBlocInstanceMapKey(bloc.name, bloc.id);
this.blocInstanceMap.set(key, bloc);
};
Blac.prototype.findRegisteredBlocInstance = function (blocClass, id) {
var base = blocClass;
if (base.isolated)
return undefined;
var key = this.createBlocInstanceMapKey(blocClass.name, id);
return this.blocInstanceMap.get(key);
};
Blac.prototype.registerIsolatedBlocInstance = function (bloc) {
var blocClass = bloc.constructor;
var blocs = this.isolatedBlocMap.get(blocClass);
if (blocs) {
blocs.push(bloc);
}
else {
this.isolatedBlocMap.set(blocClass, [bloc]);
}
};
Blac.prototype.unregisterIsolatedBlocInstance = function (bloc) {
var blocClass = bloc.constructor;
var blocs = this.isolatedBlocMap.get(blocClass);
if (blocs) {
var index = blocs.findIndex(function (b) { return b.id === bloc.id; });
blocs.splice(index, 1);
}
};
Blac.prototype.setCustomProps = function (blocClass, props) {
if (!props)
return;
this.customPropsMap.set(blocClass, props);
};
Blac.prototype.getCustomProps = function (blocClass) {
var props = this.customPropsMap.get(blocClass);
this.customPropsMap.delete(blocClass);
return props;
};
Blac.prototype.createNewBlocInstance = function (blocClass, id, props) {
var base = blocClass;
var hasCreateMethod = Object.prototype.hasOwnProperty.call(blocClass, 'create');
this.setCustomProps(base, props);
var newBloc = hasCreateMethod ? base.create() : new blocClass();
newBloc.updateId(id);
if (base.isolated) {
this.registerIsolatedBlocInstance(newBloc);
return newBloc;
}
this.registerBlocInstance(newBloc);
return newBloc;
};
Blac.prototype.getBloc = function (blocClass, options) {
if (options === void 0) { options = {}; }
var id = options.id || blocClass.name;
var registered = this.findRegisteredBlocInstance(blocClass, id);
var reconnect = options.reconnect;
if (registered) {
if (reconnect) {
registered.dispose();
}
else {
return registered;
}
}
return this.createNewBlocInstance(blocClass, id, options.props);
};
Blac.instance = new Blac();
Blac.getAllBlocs = Blac.instance.getAllBlocs;
Blac.addPlugin = Blac.instance.addPlugin;
Blac.configure = Blac.instance.configure;
return Blac;
}());
var BlacObservable = /** @class */ (function () {
function BlacObservable() {
this._observers = new Set();
}
Object.defineProperty(BlacObservable.prototype, "size", {
get: function () {
return this._observers.size;
},
enumerable: false,
configurable: true
});
BlacObservable.prototype.subscribe = function (observer) {
var _this = this;
this._observers.add(observer);
return function () { return _this.unsubscribe(observer); };
};
BlacObservable.prototype.unsubscribe = function (observer) {
this._observers.delete(observer);
};
BlacObservable.prototype.notify = function (newState, oldState) {
this._observers.forEach(function (observer) { return observer(newState, oldState); });
};
BlacObservable.prototype.dispose = function () {
this._observers.clear();
};
return BlacObservable;
}());
var BlocBase = /** @class */ (function () {
// onConnect(): void;
// onDisconnect(): void;
function BlocBase(initialState) {
var _this = this;
this.isolated = false;
this.isBlacLive = true;
this.blac = Blac.getInstance();
this.props = {};
this.createdAt = Date.now();
this.updateId = function (id) {
var originalId = _this.id;
if (!id || id === originalId)
return;
_this.id = id;
};
this.addEventListenerStateChange = function (callback) {
_this.blac.report(BlacEvent.LISTENER_ADDED, _this);
_this.observer.subscribe(callback);
return function () { return _this.handleUnsubscribe(callback); };
};
this.handleUnsubscribe = function (callback) {
_this.observer.unsubscribe(callback);
_this.blac.report(BlacEvent.LISTENER_REMOVED, _this);
};
this.observer = new BlacObservable();
this._state = initialState;
this.blac.report(BlacEvent.BLOC_CREATED, this);
this.id = this.constructor.name;
this.isolated = this.constructor.isolated;
// this.onConnect?.();
}
Object.defineProperty(BlocBase.prototype, "state", {
get: function () {
return this._state;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BlocBase.prototype, "name", {
get: function () {
return this.constructor.name;
},
enumerable: false,
configurable: true
});
BlocBase.prototype.dispose = function () {
this.blac.report(BlacEvent.BLOC_DISPOSED, this);
this.isBlacLive = false;
this.observer.dispose();
// this.onDisconnect?.();
};
BlocBase.isolated = false;
BlocBase.keepAlive = false;
BlocBase.isBlacClass = true;
return BlocBase;
}());
/** @class */ ((function (_super) {
__extends(Cubit, _super);
function Cubit(initialState) {
var _this = _super.call(this, initialState) || this;
_this.props = {};
var newProps = Blac.getInstance().getCustomProps(_this.constructor);
_this.props = __assign(__assign({}, _this.props), newProps);
return _this;
}
/**
* Update the state then will notify all observers
* @param state: new state
**/
Cubit.prototype.emit = function (state) {
if (state === this.state) {
return;
}
var oldState = this.state;
var newState = state;
this._state = state;
this.observer.notify(newState, oldState);
this.blac.report(BlacEvent.STATE_CHANGED, this, {
newState: newState,
oldState: oldState,
});
};
/**
* Merges current state object with the parameter "state" and emits the new state
* Warning: only works when the state is an object.
* @param state: Partial state that should change
**/
Cubit.prototype.patch = function (statePatch, ignoreChangeCheck) {
if (ignoreChangeCheck === void 0) { ignoreChangeCheck = false; }
var changes = false;
if (!ignoreChangeCheck) {
for (var key in statePatch) {
var current = this.state[key];
if (statePatch[key] !== current) {
changes = true;
break;
}
}
}
if (changes) {
this.emit(__assign(__assign({}, this.state), statePatch));
}
};
return Cubit;
})(BlocBase));
/** @class */ ((function (_super) {
__extends(Bloc, _super);
function Bloc() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Emit a new action, the reducer should digest the action and update the state accordingly
* @param action: action t obe sent to the reducer
*/
_this.emit = function (action) {
var oldState = _this.state;
var newState = _this.reducer(action, _this.state);
_this._state = newState;
_this.observer.notify(newState, oldState);
_this.blac.report(BlacEvent.STATE_CHANGED, _this, {
newState: newState,
oldState: oldState,
});
};
return _this;
}
return Bloc;
})(BlocBase));
var UseBlocClass = /** @class */ (function () {

@@ -45,9 +444,11 @@ function UseBlocClass() {

// parse options
if (typeof options === "function") {
// if options is a function, its a dependencySelector
if (typeof options === 'function') {
dependencySelector = options;
}
if (typeof options === "string") {
// if options is a string its an ID
if (typeof options === 'string') {
blocId = options;
}
if (typeof options === "object") {
if (typeof options === 'object') {
dependencySelector = (_a = options.dependencySelector) !== null && _a !== void 0 ? _a : dependencySelector;

@@ -57,7 +458,19 @@ blocId = options.id;

}
var resolvedBloc = useResolvedBloc(bloc, { id: blocId, props: props });
// const now = Date.now();
// const createdAt = useRef(now);
// const dateChanged = now !== createdAt;
// resolve the bloc, get the existing instance of the bloc or create a new one
// const resolvedBloc = useMemo(
// () =>
var resolvedBloc = Blac.getInstance().getBloc(bloc, {
id: blocId,
props: props,
reconnect: false,
});
// [renderId.current],
// );
if (!resolvedBloc) {
throw new Error("useBloc: could not resolve: ".concat(bloc.name || bloc));
}
var _c = react.useMemo(function () { return externalBlocStore(resolvedBloc, dependencySelector); }, [resolvedBloc]), subscribe = _c.subscribe, getSnapshot = _c.getSnapshot, getServerSnapshot = _c.getServerSnapshot;
var _c = react.useMemo(function () { return externalBlocStore(resolvedBloc, dependencySelector); }, [resolvedBloc.createdAt]), subscribe = _c.subscribe, getSnapshot = _c.getSnapshot, getServerSnapshot = _c.getServerSnapshot;
var state = react.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);

@@ -64,0 +477,0 @@ react.useEffect(function () {

{
"name": "@blac/react",
"version": "0.0.18",
"version": "0.0.19",
"license": "MIT",

@@ -5,0 +5,0 @@ "main": "dist/blac-react.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc