@plasmicapp/react-web 0.2.137 → 0.2.138

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.
@@ -14,8 +14,7 @@ import ReactDOM__default from 'react-dom';
14
14
  import { useFocusRing } from '@react-aria/focus';
15
15
  import clone from 'clone';
16
16
  import deepEqual from 'fast-deep-equal';
17
- import { proxy, ref, useSnapshot } from 'valtio';
18
- import { subscribeKey } from 'valtio/utils';
17
+ import { proxy, useSnapshot, ref } from 'valtio';
19
18
  export { PlasmicDataSourceContextProvider, useCurrentUser } from '@plasmicapp/data-sources-context';
20
19
  import '@react-aria/ssr';
21
20
 
@@ -674,6 +673,31 @@ function generateStateValueProp($state, path // ["parent", 0, 1, "counter"]
674
673
  ) {
675
674
  return get($state, path);
676
675
  }
676
+ var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
677
+ function shallowEqual(a1, a2) {
678
+ if (a1.length !== a2.length) {
679
+ return false;
680
+ }
681
+ for (var i = 0; i < a1.length; i++) {
682
+ if (a1[i] !== a2[i]) {
683
+ return false;
684
+ }
685
+ }
686
+ return true;
687
+ }
688
+ function isNum$1(value) {
689
+ return typeof value === "symbol" ? false : !isNaN(+value);
690
+ }
691
+ function assert(cond, msg) {
692
+ if (msg === void 0) { msg = "Assertion failed"; }
693
+ if (!cond) {
694
+ // We always generate an non empty message so that it doesn't get swallowed
695
+ // by the async library.
696
+ msg = (typeof msg === "string" ? msg : msg()) || "Assertion failed";
697
+ debugger;
698
+ throw new Error(msg);
699
+ }
700
+ }
677
701
  /**
678
702
  * Forked from https://github.com/lukeed/dset
679
703
  * Changes: fixed setting a deep value to a proxy object
@@ -685,47 +709,52 @@ function set(obj, keys, val) {
685
709
  k = keys[i++];
686
710
  if (k === "__proto__" || k === "constructor" || k === "prototype")
687
711
  break;
688
- if (i === l) {
689
- t[k] = val;
690
- t = t[k];
691
- }
692
- else {
693
- if (typeof (x = t[k]) === typeof keys) {
694
- t = t[k] = x;
695
- }
696
- else if (keys[i] * 0 !== 0 || !!~("" + keys[i]).indexOf(".")) {
697
- t[k] = {};
698
- t = t[k];
699
- }
700
- else {
701
- t[k] = [];
702
- t = t[k];
703
- }
704
- }
712
+ var newValue = i === l
713
+ ? val
714
+ : typeof (x = t[k]) === typeof keys
715
+ ? x
716
+ : keys[i] * 0 !== 0 || !!~("" + keys[i]).indexOf(".")
717
+ ? {}
718
+ : [];
719
+ assignValue(t, k, newValue);
720
+ t = t[k];
705
721
  }
706
722
  }
707
- var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
708
- function shallowEqual$1(a1, a2) {
709
- if (a1.length !== a2.length) {
710
- return false;
723
+ /**
724
+ * Forked from lodash
725
+ */
726
+ function baseAssignValue(object, key, value) {
727
+ if (key == "__proto__") {
728
+ Object.defineProperty(object, key, {
729
+ configurable: true,
730
+ enumerable: true,
731
+ value: value,
732
+ writable: true
733
+ });
711
734
  }
712
- for (var i = 0; i < a1.length; i++) {
713
- if (a1[i] !== a2[i]) {
714
- return false;
715
- }
735
+ else {
736
+ object[key] = value;
716
737
  }
717
- return true;
718
738
  }
719
- function isNum$1(value) {
720
- return typeof value === "symbol" ? false : !isNaN(+value);
739
+ function eq(value, other) {
740
+ return value === other || (value !== value && other !== other);
741
+ }
742
+ function assignValue(object, key, value) {
743
+ var objValue = object[key];
744
+ if (!(Object.prototype.hasOwnProperty.call(object, key) && eq(objValue, value)) ||
745
+ (value === undefined && !(key in object))) {
746
+ baseAssignValue(object, key, value);
747
+ }
721
748
  }
722
749
 
723
750
  var ARRAY_SYMBOL = Symbol("[]");
724
751
 
752
+ var UNINITIALIZED = Symbol("plasmic.unitialized");
725
753
  var StateSpecNode = /** @class */ (function () {
726
754
  function StateSpecNode(specs) {
727
755
  this.specs = specs;
728
756
  this.edges = new Map();
757
+ this.state = {};
729
758
  }
730
759
  StateSpecNode.prototype.hasEdge = function (key) {
731
760
  return this.edges.has(key);
@@ -733,6 +762,9 @@ var StateSpecNode = /** @class */ (function () {
733
762
  StateSpecNode.prototype.addEdge = function (key, node) {
734
763
  this.edges.set(key, node);
735
764
  };
765
+ StateSpecNode.prototype.children = function () {
766
+ return this.edges.values();
767
+ };
736
768
  StateSpecNode.prototype.makeTransition = function (key) {
737
769
  key = isNum$1(key) ? ARRAY_SYMBOL : key;
738
770
  return this.edges.get(key);
@@ -749,6 +781,40 @@ var StateSpecNode = /** @class */ (function () {
749
781
  StateSpecNode.prototype.getAllSpecs = function () {
750
782
  return this.specs;
751
783
  };
784
+ StateSpecNode.prototype.getState = function (path) {
785
+ return this.state[JSON.stringify(path)];
786
+ };
787
+ StateSpecNode.prototype.clearStates = function () {
788
+ this.state = {};
789
+ };
790
+ StateSpecNode.prototype.states = function () {
791
+ return Object.values(this.state);
792
+ };
793
+ StateSpecNode.prototype.hasState = function (path) {
794
+ var key = JSON.stringify(path);
795
+ return key in this.state;
796
+ };
797
+ StateSpecNode.prototype.createStateCell = function (path) {
798
+ var key = JSON.stringify(path);
799
+ this.state[key] = {
800
+ listeners: [],
801
+ initialValue: UNINITIALIZED,
802
+ registeredInitFunc: this.getSpec().initFunc,
803
+ path: path
804
+ };
805
+ };
806
+ StateSpecNode.prototype.setInitialValue = function (path, value) {
807
+ var key = JSON.stringify(path);
808
+ this.state[key].initialValue = value;
809
+ };
810
+ StateSpecNode.prototype.getInitialValue = function (path) {
811
+ var key = JSON.stringify(path);
812
+ return this.state[key].initialValue;
813
+ };
814
+ StateSpecNode.prototype.addListener = function (path, f) {
815
+ var key = JSON.stringify(path);
816
+ this.state[key].listeners.push(f);
817
+ };
752
818
  return StateSpecNode;
753
819
  }());
754
820
  var transformPathStringToObj = function (str) {
@@ -758,13 +824,13 @@ var transformPathStringToObj = function (str) {
758
824
  };
759
825
  return str.split(".").flatMap(splitStatePathPart);
760
826
  };
761
- function buildGraph(specs) {
827
+ function buildTree(specs) {
762
828
  var internalSpec = specs.map(function (spec) {
763
829
  return (__assign(__assign({}, spec), { pathObj: transformPathStringToObj(spec.path), isRepeated: spec.path.split(".").some(function (part) { return part.endsWith("[]"); }) }));
764
830
  });
765
831
  var rec = function (currentPath) {
766
832
  var node = new StateSpecNode(internalSpec.filter(function (spec) {
767
- return shallowEqual$1(currentPath, spec.pathObj.slice(0, currentPath.length));
833
+ return shallowEqual(currentPath, spec.pathObj.slice(0, currentPath.length));
768
834
  }));
769
835
  node.getAllSpecs().forEach(function (spec) {
770
836
  if (spec.pathObj.length > currentPath.length) {
@@ -777,349 +843,334 @@ function buildGraph(specs) {
777
843
  return node;
778
844
  };
779
845
  return rec([]);
780
- }
781
-
782
- var mkUntrackedValue = function (o) {
783
- return o != null && typeof o === "object" ? ref(o) : o;
784
- };
785
- function shallowEqual(a1, a2) {
786
- if (a1.length !== a2.length) {
787
- return false;
846
+ }
847
+ function getLeaves(root) {
848
+ var leaves = [];
849
+ var rec = function (node) {
850
+ var e_1, _a;
851
+ try {
852
+ for (var _b = __values(node.children()), _c = _b.next(); !_c.done; _c = _b.next()) {
853
+ var child = _c.value;
854
+ rec(child);
855
+ }
856
+ }
857
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
858
+ finally {
859
+ try {
860
+ if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
861
+ }
862
+ finally { if (e_1) throw e_1.error; }
863
+ }
864
+ if (node.isLeaf()) {
865
+ leaves.push(node);
866
+ }
867
+ };
868
+ rec(root);
869
+ return leaves;
870
+ }
871
+ function findStateCell(root, pathStr, repetitionIndex) {
872
+ var e_2, _a;
873
+ var realPath = [];
874
+ var pathObj = transformPathStringToObj(pathStr);
875
+ var currRepIndex = 0;
876
+ try {
877
+ for (var pathObj_1 = __values(pathObj), pathObj_1_1 = pathObj_1.next(); !pathObj_1_1.done; pathObj_1_1 = pathObj_1.next()) {
878
+ var part = pathObj_1_1.value;
879
+ if (typeof part === "symbol") {
880
+ if (!root.hasArrayTransition() ||
881
+ !repetitionIndex ||
882
+ currRepIndex > repetitionIndex.length) {
883
+ console.log(root);
884
+ throw new Error("transition not found: pathStr ".concat(pathStr, " part ").concat(typeof part === "symbol" ? "[]" : part));
885
+ }
886
+ realPath.push(repetitionIndex[currRepIndex++]);
887
+ root = root.makeTransition(ARRAY_SYMBOL);
888
+ }
889
+ else {
890
+ if (!root.hasEdge(part)) {
891
+ throw new Error("transition not found: pathStr ".concat(pathStr, " part ").concat(typeof part === "symbol" ? "[]" : part));
892
+ }
893
+ realPath.push(part);
894
+ root = root.makeTransition(part);
895
+ }
896
+ }
788
897
  }
789
- for (var i = 0; i < a1.length; i++) {
790
- if (a1[i] !== a2[i]) {
791
- return false;
898
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
899
+ finally {
900
+ try {
901
+ if (pathObj_1_1 && !pathObj_1_1.done && (_a = pathObj_1["return"])) _a.call(pathObj_1);
792
902
  }
903
+ finally { if (e_2) throw e_2.error; }
793
904
  }
794
- return true;
795
- }
905
+ return {
906
+ node: root,
907
+ realPath: realPath
908
+ };
909
+ }
910
+
796
911
  function isNum(value) {
797
912
  return typeof value === "symbol" ? false : !isNaN(+value);
798
913
  }
799
- function saveNewState($$state, path, spec) {
800
- var key = JSON.stringify(path);
801
- $$state.existingStates.set(key, { path: path, specKey: spec.path });
802
- if (!$$state.statesInstanceBySpec.has(spec.path)) {
803
- $$state.statesInstanceBySpec.set(spec.path, []);
804
- }
805
- $$state.statesInstanceBySpec
806
- .get(spec.path)
807
- .push({ path: path, specKey: spec.path });
914
+ function canProxy(value) {
915
+ return typeof value === "object" && value != null;
916
+ }
917
+ function initializeStateValue($$state, initialSpecNode, initialStatePath, proxyRoot) {
918
+ var _a, _b;
919
+ var stateAccess = new Set();
920
+ var $state = create$StateProxy($$state, function (node, path) { return ({
921
+ get: function () {
922
+ stateAccess.add({ path: path, node: node });
923
+ var spec = node.getSpec();
924
+ if (spec.valueProp) {
925
+ return $$state.props[spec.valueProp];
926
+ }
927
+ else if (!node.hasState(path) && spec.initFunc) {
928
+ return initializeStateValue($$state, node, path, proxyRoot);
929
+ }
930
+ return get(proxyRoot, path);
931
+ },
932
+ set: function () {
933
+ throw new Error("Cannot update state values during initialization");
934
+ }
935
+ }); });
936
+ stateAccess.forEach(function (_a) {
937
+ var node = _a.node, path = _a.path;
938
+ node.addListener(path, function () {
939
+ var newValue = initialSpecNode.getSpec().initFunc($$state.props, $state, $$state.ctx);
940
+ set(proxyRoot, initialStatePath, newValue);
941
+ });
942
+ });
943
+ var initialValue = initialSpecNode.getState(initialStatePath)
944
+ .registeredInitFunc($$state.props, $state, $$state.ctx);
945
+ initialSpecNode.setInitialValue(initialStatePath, clone(initialValue));
946
+ var initialSpec = initialSpecNode.getSpec();
947
+ var value = initialSpec.isImmutable
948
+ ? mkUntrackedValue(initialValue)
949
+ : clone(initialValue);
950
+ set(proxyRoot, initialStatePath, value);
951
+ //immediately fire onChange
952
+ if (initialSpec.onChangeProp) {
953
+ (_b = (_a = $$state.props)[initialSpec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, initialValue);
954
+ }
955
+ return initialValue;
808
956
  }
809
- function create$StateProxy($$state, handlers) {
810
- var rec = function (currPath, currNode) {
957
+ function create$StateProxy($$state, leafHandlers) {
958
+ var rec = function (currPath, currNode, isOutside, proxyRoot, initialObject) {
811
959
  var getNextPath = function (property) { return __spreadArray(__spreadArray([], __read(currPath), false), [
812
960
  isNum(property) ? +property : property,
813
961
  ], false); };
814
- return new Proxy(currNode.hasArrayTransition() ? [] : {}, {
962
+ var spec = currNode.getSpec();
963
+ var handlers = {
815
964
  deleteProperty: function (target, property) {
816
- var prefixPath = getNextPath(property);
817
- var specKeysToUpdate = new Set();
818
- $$state.existingStates.forEach(function (_a) {
819
- var path = _a.path, specKey = _a.specKey;
820
- if (path.length >= prefixPath.length &&
821
- shallowEqual(path.slice(0, prefixPath.length), prefixPath)) {
822
- deleteState($$state, path);
823
- specKeysToUpdate.add(specKey);
824
- }
825
- });
826
- specKeysToUpdate.forEach(function (specKey) {
827
- var _a, _b;
828
- var spec = $$state.specsByKey[specKey];
829
- if (spec.onChangeProp) {
830
- (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, get($$state.stateValues, currPath), currPath);
831
- }
832
- });
965
+ var _a, _b;
966
+ if (!isOutside &&
967
+ !currNode.isLeaf() &&
968
+ !currNode.hasArrayTransition() &&
969
+ !isNum(property)) {
970
+ throw new Error("Can't delete a property in the middle of the state spec");
971
+ }
972
+ delete get($$state.stateValues, currPath)[property];
973
+ if (spec.onChangeProp) {
974
+ //we are always in a leaf, since we only have two cases:
975
+ // 1 - delete properties outside the state tree
976
+ // 2 - delete indices in repeated implicit states, but these can't be exposed, so they don't have onChangeProp
977
+ (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, get($$state.stateValues, currPath.slice(spec.pathObj.length)));
978
+ }
833
979
  return Reflect.deleteProperty(target, property);
834
980
  },
835
981
  get: function (target, property, receiver) {
836
982
  var _a, _b;
983
+ proxyRoot = proxyRoot == null ? receiver : proxyRoot;
837
984
  var nextPath = getNextPath(property);
985
+ if (isOutside || currNode.isLeaf()) {
986
+ return Reflect.get(target, property, receiver);
987
+ }
838
988
  var nextNode = currNode.makeTransition(property);
839
- if (nextNode) {
840
- if (nextNode.isLeaf()) {
841
- target[property] = (_b = (_a = handlers(nextPath, nextNode.getSpec())).get) === null || _b === void 0 ? void 0 : _b.call(_a, target, property, receiver);
842
- }
843
- else if (!(property in target)) {
844
- target[property] = rec(nextPath, nextNode);
845
- }
989
+ if (nextNode === null || nextNode === void 0 ? void 0 : nextNode.isLeaf()) {
990
+ return (_b = (_a = leafHandlers(nextNode, nextPath, proxyRoot)).get) === null || _b === void 0 ? void 0 : _b.call(_a, target, property, receiver);
991
+ }
992
+ else if (nextNode && !(property in target)) {
993
+ target[property] = rec(nextPath, nextNode, false, proxyRoot, undefined);
846
994
  }
847
995
  return Reflect.get(target, property, receiver);
848
996
  },
849
997
  set: function (target, property, value, receiver) {
850
- var e_1, _a;
851
- var _b, _c, _d, _e;
998
+ var _a, _b;
999
+ proxyRoot = proxyRoot == null ? receiver : proxyRoot;
852
1000
  var nextPath = getNextPath(property);
853
1001
  var nextNode = currNode.makeTransition(property);
854
- if (nextNode && typeof property !== "symbol") {
855
- if (nextNode.isLeaf()) {
856
- // reached the end of the spec
857
- target[property] = (_c = (_b = handlers(nextPath, nextNode.getSpec())).set) === null || _c === void 0 ? void 0 : _c.call(_b, target, property, value, receiver);
858
- return Reflect.set(target, property, value, receiver);
859
- }
860
- else if (typeof value === "object") {
861
- target[property] = rec(nextPath, nextNode);
862
- try {
863
- for (var _f = __values(Object.keys(value)), _g = _f.next(); !_g.done; _g = _f.next()) {
864
- var key = _g.value;
865
- target[property][key] = value[key];
866
- }
867
- }
868
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
869
- finally {
870
- try {
871
- if (_g && !_g.done && (_a = _f["return"])) _a.call(_f);
872
- }
873
- finally { if (e_1) throw e_1.error; }
874
- }
875
- return true;
876
- }
877
- }
878
1002
  if (property === "registerInitFunc" && currPath.length === 0) {
879
1003
  return Reflect.set(target, property, value, receiver);
880
1004
  }
881
- if (currNode.hasArrayTransition()) {
1005
+ if (!nextNode && currNode.hasArrayTransition()) {
882
1006
  set($$state.stateValues, nextPath, value);
883
- (_e = (_d = currNode
884
- .makeTransition(ARRAY_SYMBOL)) === null || _d === void 0 ? void 0 : _d.getAllSpecs()) === null || _e === void 0 ? void 0 : _e.forEach(function (spec) {
885
- var _a, _b;
886
- if (spec.onChangeProp) {
887
- (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, value, nextPath);
888
- }
889
- });
1007
+ //array can set his own properties such as length, map, ...
890
1008
  return Reflect.set(target, property, value, receiver);
891
1009
  }
892
- // invalid setting a value that doesn't make part of the spec
893
- return false;
1010
+ if (nextNode === null || nextNode === void 0 ? void 0 : nextNode.isLeaf()) {
1011
+ (_b = (_a = leafHandlers(nextNode, nextPath, proxyRoot)).set) === null || _b === void 0 ? void 0 : _b.call(_a, target, property, value, receiver);
1012
+ }
1013
+ if (!isOutside && !currNode.isLeaf() && !nextNode) {
1014
+ // can't set an unknown field in $state
1015
+ return false;
1016
+ }
1017
+ // we keep pointing to the leaf
1018
+ if (!nextNode) {
1019
+ assert(isOutside || currNode.isLeaf, "unexpected update in nextNode");
1020
+ nextNode = currNode;
1021
+ }
1022
+ if (canProxy(value)) {
1023
+ target[property] = rec(nextPath, nextNode, isOutside || currNode.isLeaf(), proxyRoot, value);
1024
+ }
1025
+ else if (!isOutside && !currNode.isLeaf() && !(nextNode === null || nextNode === void 0 ? void 0 : nextNode.isLeaf())) {
1026
+ throw new Error("inserting a primitive value into a non-leaf");
1027
+ }
1028
+ else {
1029
+ Reflect.set(target, property, value, receiver);
1030
+ }
1031
+ nextNode.getAllSpecs().forEach(function (spec) {
1032
+ var _a, _b;
1033
+ if (spec.onChangeProp) {
1034
+ (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1035
+ }
1036
+ });
1037
+ var newValue = (isOutside || currNode.isLeaf()) && currNode.getSpec().isImmutable
1038
+ ? mkUntrackedValue(value)
1039
+ : value;
1040
+ set($$state.stateValues, nextPath, newValue);
1041
+ return true;
894
1042
  }
895
- });
1043
+ };
1044
+ var baseObject = !isOutside && !currNode.isLeaf()
1045
+ ? currNode.hasArrayTransition()
1046
+ ? []
1047
+ : {}
1048
+ : Array.isArray(initialObject)
1049
+ ? []
1050
+ : Object.create(Object.getPrototypeOf(initialObject));
1051
+ var proxyObj = new Proxy(baseObject, handlers);
1052
+ if (initialObject) {
1053
+ Reflect.ownKeys(initialObject).forEach(function (key) {
1054
+ var desc = Object.getOwnPropertyDescriptor(initialObject, key);
1055
+ if (desc.get || desc.set) {
1056
+ Object.defineProperty(baseObject, key, desc);
1057
+ }
1058
+ else {
1059
+ proxyObj[key] = initialObject[key];
1060
+ }
1061
+ });
1062
+ }
1063
+ return proxyObj;
896
1064
  };
897
- return rec([], $$state.rootStateSpec);
1065
+ return rec([], $$state.rootSpecTree, false, undefined, undefined);
898
1066
  }
899
- var deleteState = function ($$state, path) {
900
- var _a;
901
- var key = JSON.stringify(path);
902
- (_a = $$state.unsubscriptionsByState[key]) === null || _a === void 0 ? void 0 : _a.forEach(function (f) { return f(); });
903
- delete $$state.unsubscriptionsByState[key];
904
- $$state.existingStates["delete"](key);
905
- // delete get($$state.stateValues, path.slice(-1))[path.slice(-1)[0]];
906
- // delete get($$state.initStateValues, path.slice(-1))[path.slice(-1)[0]];
907
- };
908
- var getIndexes = function (path, spec) {
909
- var indexes = [];
910
- if (path.length !== spec.pathObj.length) {
911
- throw new Error("Unexpected error: state path and spec path have different lengths");
912
- }
913
- for (var i = 0; i < spec.pathObj.length; i++) {
914
- if (spec.pathObj[i] === "[]") {
915
- indexes.push(path[i]);
916
- }
917
- }
918
- return indexes;
1067
+ var mkUntrackedValue = function (o) {
1068
+ return o != null && typeof o === "object" ? ref(o) : o;
919
1069
  };
920
- function initializeStateValue($$state, initialStatePath, initialSpec) {
921
- var _a;
922
- var initialStateKey = JSON.stringify(initialStatePath);
923
- var stateAccess = new Set();
924
- var $state = create$StateProxy($$state, function (path, spec) { return ({
925
- get: function () {
926
- var key = JSON.stringify(path);
927
- stateAccess.add({ path: path, spec: spec });
928
- if (spec.valueProp) {
929
- return !spec.isRepeated
930
- ? $$state.props[spec.valueProp]
931
- : get($$state.props[spec.valueProp], path.slice(1));
932
- }
933
- if ($$state.existingStates.has(key)) {
934
- // is already initialized
935
- return get($$state.stateValues, path);
936
- }
937
- else if (spec.initFunc) {
938
- initializeStateValue($$state, path, spec);
939
- }
940
- return get($$state.stateValues, path);
941
- },
942
- set: function () {
943
- throw new Error("Cannot update state values during initialization");
944
- }
945
- }); });
946
- (_a = $$state.unsubscriptionsByState[initialStateKey]) === null || _a === void 0 ? void 0 : _a.forEach(function (f) { return f(); });
947
- $$state.unsubscriptionsByState[initialStateKey] = [];
948
- stateAccess.forEach(function (_a) {
949
- var path = _a.path, spec = _a.spec;
950
- var unsubscribe = subscribeKey(get($$state.stateValues, path.slice(-1)), path.slice(-1)[0], function () {
951
- return saveValue($$state, initialStatePath, initialSpec, initialSpec.initFunc($$state.props, $state, $$state.ctx, getIndexes(path, spec)));
952
- });
953
- $$state.unsubscriptionsByState[initialStateKey].push(unsubscribe);
954
- });
955
- var initialValue = initialSpec.initFunc($$state.props, $state, $$state.ctx, getIndexes(initialStatePath, initialSpec));
956
- saveStateInitialValue($$state, initialStatePath, initialSpec, initialValue);
957
- return initialValue;
958
- }
959
- function saveValue($$state, path, spec, value) {
960
- if (spec.isImmutable) {
961
- set($$state.stateValues, path, mkUntrackedValue(value));
962
- }
963
- else {
964
- set($$state.stateValues, path, value);
965
- }
966
- }
967
- function saveStateInitialValue($$state, path, spec, initialValue) {
968
- if (spec.isImmutable) {
969
- var untrackedValue = mkUntrackedValue(initialValue);
970
- set($$state.stateValues, path, untrackedValue);
971
- set($$state.initStateValues, path, clone(untrackedValue));
972
- }
973
- else {
974
- set($$state.stateValues, path, clone(initialValue));
975
- set($$state.initStateValues, path, clone(initialValue));
976
- }
977
- }
978
1070
  function useDollarState(specs, props, $ctx) {
979
- var $$state = React__default.useRef(proxy({
980
- stateValues: {},
981
- initStateValues: {},
982
- specsByKey: Object.fromEntries(specs.map(function (spec) { return [
983
- spec.path,
984
- __assign(__assign({}, spec), { pathObj: transformPathStringToObj(spec.path), isRepeated: spec.path
985
- .split(".")
986
- .some(function (part) { return part.endsWith("[]"); }) }),
987
- ]; })),
988
- statesInstanceBySpec: new Map(),
989
- existingStates: new Map(),
990
- unsubscriptionsByState: {},
991
- props: {},
992
- ctx: {},
993
- registrationsQueue: [],
994
- rootStateSpec: buildGraph(specs)
995
- })).current;
996
- $$state.props = mkUntrackedValue(props);
997
- $$state.ctx = mkUntrackedValue($ctx !== null && $ctx !== void 0 ? $ctx : {});
998
- var $state = React__default.useRef(Object.assign(create$StateProxy($$state, function (path, spec) {
999
- var _a;
1000
- var key = JSON.stringify(path);
1001
- if (!$$state.existingStates.has(key)) {
1002
- saveNewState($$state, path, spec);
1003
- var initialValue = !spec.initFunc
1004
- ? (_a = spec.initVal) !== null && _a !== void 0 ? _a : undefined
1005
- : initializeStateValue($$state, path, spec);
1006
- saveStateInitialValue($$state, path, spec, initialValue);
1007
- }
1071
+ var $$state = React__default.useRef((function () {
1072
+ var rootSpecTree = buildTree(specs);
1008
1073
  return {
1009
- get: function () {
1010
- if (spec.valueProp) {
1011
- var value = !spec.isRepeated
1012
- ? $$state.props[spec.valueProp]
1013
- : get($$state.props[spec.valueProp], path.slice(1));
1014
- return value;
1074
+ rootSpecTree: rootSpecTree,
1075
+ specTreeLeaves: getLeaves(rootSpecTree),
1076
+ stateValues: proxy({}),
1077
+ props: {},
1078
+ ctx: {},
1079
+ registrationsQueue: []
1080
+ };
1081
+ })()).current;
1082
+ $$state.props = props;
1083
+ $$state.ctx = $ctx !== null && $ctx !== void 0 ? $ctx : {};
1084
+ var $state = React__default.useRef((function () {
1085
+ var useRef$state = Object.assign(create$StateProxy($$state, function (node, path, proxyRoot) {
1086
+ if (!node.hasState(path)) {
1087
+ node.createStateCell(path);
1088
+ var spec = node.getSpec();
1089
+ if (spec.initFunc) {
1090
+ initializeStateValue($$state, node, path, proxyRoot);
1015
1091
  }
1016
- else {
1017
- return get($$state.stateValues, path);
1092
+ else if (!spec.valueProp) {
1093
+ set(proxyRoot, path, spec.initVal);
1018
1094
  }
1019
- },
1020
- set: function (_t, _p, value) {
1021
- var _a, _b;
1022
- saveValue($$state, path, spec, value);
1023
- if (spec.onChangeProp) {
1024
- (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, value, path);
1025
- }
1026
- return true;
1027
1095
  }
1028
- };
1029
- }), {
1030
- registerInitFunc: function (pathStr, f) {
1031
- var _a;
1032
- if ((_a = $$state.statesInstanceBySpec
1033
- .get(pathStr)) === null || _a === void 0 ? void 0 : _a.some(function (_a) {
1034
- var path = _a.path, specKey = _a.specKey;
1035
- return !deepEqual(get($$state.initStateValues, path), f(props, $state, $ctx !== null && $ctx !== void 0 ? $ctx : {}, getIndexes(path, $$state.specsByKey[specKey])));
1036
- })) {
1037
- $$state.registrationsQueue.push({ pathStr: pathStr, f: f });
1096
+ return {
1097
+ get: function (target, property, receiver) {
1098
+ var spec = node.getSpec();
1099
+ if (spec.valueProp) {
1100
+ return $$state.props[spec.valueProp];
1101
+ }
1102
+ else {
1103
+ return Reflect.get(target, property, receiver);
1104
+ }
1105
+ }
1106
+ };
1107
+ }), {
1108
+ registerInitFunc: function (pathStr, f, repetitionIndex) {
1109
+ var _a = findStateCell($$state.rootSpecTree, pathStr, repetitionIndex), node = _a.node, realPath = _a.realPath;
1110
+ if (!node.hasState(realPath)) {
1111
+ node.createStateCell(realPath);
1112
+ }
1113
+ if (!deepEqual(node.getState(realPath).initialValue, f($$state.props, useRef$state, $$state.ctx))) {
1114
+ $$state.registrationsQueue.push({ node: node, path: realPath, f: f });
1115
+ }
1038
1116
  }
1039
- }
1040
- })).current;
1117
+ });
1118
+ return useRef$state;
1119
+ })()).current;
1041
1120
  // For each spec with an initFunc, evaluate it and see if
1042
1121
  // the init value has changed. If so, reset its state.
1043
1122
  var resetSpecs = [];
1044
- $$state.existingStates.forEach(function (_a) {
1045
- var path = _a.path, specKey = _a.specKey;
1046
- var spec = $$state.specsByKey[specKey];
1047
- if (spec.initFunc) {
1048
- var newInit = spec.initFunc(props, $state, $ctx !== null && $ctx !== void 0 ? $ctx : {}, getIndexes(path, spec));
1049
- if (!deepEqual(newInit, get($$state.initStateValues, path))) {
1050
- resetSpecs.push({ path: path, spec: spec });
1123
+ $$state.specTreeLeaves
1124
+ .flatMap(function (node) { return node.states().map(function (stateCell) { return ({ stateCell: stateCell, node: node }); }); })
1125
+ .forEach(function (_a) {
1126
+ var stateCell = _a.stateCell, node = _a.node;
1127
+ if (stateCell.registeredInitFunc) {
1128
+ var newInit = stateCell.registeredInitFunc(props, $state, $ctx !== null && $ctx !== void 0 ? $ctx : {});
1129
+ if (!deepEqual(newInit, stateCell.initialValue)) {
1130
+ resetSpecs.push({ stateCell: stateCell, node: node });
1051
1131
  }
1052
1132
  }
1053
1133
  });
1134
+ var reInitializeState = function (node, stateCell) {
1135
+ var _a, _b;
1136
+ var newInit = initializeStateValue($$state, node, stateCell.path, $state);
1137
+ var spec = node.getSpec();
1138
+ if (spec.onChangeProp) {
1139
+ (_b = (_a = $$state.props)[spec.onChangeProp]) === null || _b === void 0 ? void 0 : _b.call(_a, newInit);
1140
+ }
1141
+ };
1054
1142
  useIsomorphicLayoutEffect(function () {
1055
1143
  resetSpecs.forEach(function (_a) {
1056
- var _b, _c;
1057
- var path = _a.path, spec = _a.spec;
1058
- var newInit = initializeStateValue($$state, path, spec);
1059
- if (spec.onChangeProp) {
1060
- (_c = (_b = $$state.props)[spec.onChangeProp]) === null || _c === void 0 ? void 0 : _c.call(_b, newInit, path);
1061
- }
1144
+ var stateCell = _a.stateCell, node = _a.node;
1145
+ reInitializeState(node, stateCell);
1062
1146
  });
1063
1147
  }, [props, resetSpecs]);
1064
1148
  useIsomorphicLayoutEffect(function () {
1065
1149
  $$state.registrationsQueue.forEach(function (_a) {
1066
- var f = _a.f, pathStr = _a.pathStr;
1067
- $$state.specsByKey[pathStr].initFunc = f;
1150
+ var node = _a.node, path = _a.path, f = _a.f;
1151
+ var stateCell = node.getState(path);
1152
+ stateCell.registeredInitFunc = f;
1153
+ reInitializeState(node, stateCell);
1068
1154
  });
1069
1155
  $$state.registrationsQueue = [];
1070
1156
  }, [$$state.registrationsQueue]);
1157
+ // immediately initialize exposed non-private states
1158
+ useIsomorphicLayoutEffect(function () {
1159
+ $$state.specTreeLeaves.forEach(function (node) {
1160
+ var spec = node.getSpec();
1161
+ if (!spec.isRepeated && spec.type !== "private" && spec.initFunc) {
1162
+ node.createStateCell(spec.pathObj);
1163
+ initializeStateValue($$state, node, spec.pathObj, $state);
1164
+ }
1165
+ });
1166
+ }, []);
1071
1167
  // Re-render if any value changed in one of these objects
1072
1168
  useSnapshot($$state.stateValues, { sync: true });
1073
- useSnapshot($$state.specsByKey, { sync: true });
1074
- return $state;
1075
- }
1076
- // Simple version of $state useDollarState for read-only
1077
- function useCanvasDollarState(specs, props, $ctx) {
1078
- var e_2, _a;
1079
- var $$state = proxy({
1080
- stateValues: {},
1081
- initStateValues: {},
1082
- specsByKey: Object.fromEntries(specs.map(function (spec) { return [
1083
- spec.path,
1084
- __assign(__assign({}, spec), { pathObj: transformPathStringToObj(spec.path), isRepeated: spec.path.split(".").some(function (part) { return part.endsWith("[]"); }) }),
1085
- ]; })),
1086
- statesInstanceBySpec: new Map(),
1087
- existingStates: new Map(),
1088
- unsubscriptionsByState: {},
1089
- props: {},
1090
- ctx: {},
1091
- registrationsQueue: [],
1092
- rootStateSpec: buildGraph(specs)
1093
- });
1094
- $$state.props = mkUntrackedValue(props);
1095
- $$state.ctx = mkUntrackedValue($ctx);
1096
- var $state = {};
1097
- try {
1098
- for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
1099
- var spec = specs_1_1.value;
1100
- var path = transformPathStringToObj(spec.path);
1101
- var init = spec.valueProp
1102
- ? $$state.props[spec.valueProp]
1103
- : spec.initVal
1104
- ? spec.initVal
1105
- : spec.initFunc
1106
- ? initializeStateValue($$state, path, $$state.specsByKey[spec.path])
1107
- : undefined;
1108
- set($state, path, init);
1109
- }
1110
- }
1111
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1112
- finally {
1113
- try {
1114
- if (specs_1_1 && !specs_1_1.done && (_a = specs_1["return"])) _a.call(specs_1);
1115
- }
1116
- finally { if (e_2) throw e_2.error; }
1117
- }
1118
1169
  return $state;
1119
1170
  }
1120
1171
 
1121
1172
  // Utilities used by generated code
1122
1173
  var classNames = classNames$1;
1123
1174
 
1124
- export { PlasmicIcon, PlasmicLink, PlasmicPageGuard, PlasmicSlot, Stack, classNames, createPlasmicElementProxy, createUseScreenVariants, deriveRenderOpts, ensureGlobalVariants, generateStateOnChangeProp, generateStateValueProp, hasVariant, isNum$1 as isNum, makeFragment, mergeVariantsWithStates, renderPlasmicSlot, set, shallowEqual$1 as shallowEqual, useCanvasDollarState, useDollarState, useIsomorphicLayoutEffect, useTrigger, wrapWithClassName };
1175
+ export { PlasmicIcon, PlasmicLink, PlasmicPageGuard, PlasmicSlot, Stack, classNames, createPlasmicElementProxy, createUseScreenVariants, deriveRenderOpts, ensureGlobalVariants, generateStateOnChangeProp, generateStateValueProp, hasVariant, makeFragment, mergeVariantsWithStates, renderPlasmicSlot, set, useDollarState, useTrigger, wrapWithClassName };
1125
1176
  //# sourceMappingURL=index.js.map