@plasmicapp/react-web 0.2.137 → 0.2.139

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