@lark.js/mvc 0.0.5 → 0.0.7

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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/constants.ts
2
2
  var globalCounter = 0;
3
- var SPLITTER = "";
3
+ var SPLITTER = String.fromCharCode(30);
4
4
  var RouterEvents = {
5
5
  CHANGE: "change",
6
6
  CHANGED: "changed",
@@ -305,7 +305,7 @@ function safeguard(data, getter, setter, isRoot) {
305
305
  set(target, property, value) {
306
306
  if (!setter && !prefix) {
307
307
  throw new Error(
308
- "Avoid write back, key: " + prefix + property + " value:" + value + " more: https://github.com/hangtiancheng/h"
308
+ "Avoid write back, key: " + prefix + property + " value:" + value + " more: https://github.com/hangtiancheng/lark"
309
309
  );
310
310
  }
311
311
  Reflect.set(target, property, value);
@@ -767,6 +767,7 @@ var cachedDefaultPath;
767
767
  var cachedRewrite;
768
768
  var defaultTitle;
769
769
  var frameworkConfig;
770
+ var routeMode = "history";
770
771
  var beforeEachGuards = [];
771
772
  function createEmptyLocation() {
772
773
  return {
@@ -792,7 +793,8 @@ function attachViewAndPath(loc) {
792
793
  cachedRewrite = frameworkConfig.rewrite;
793
794
  }
794
795
  if (!loc.view) {
795
- let path = loc.hash["path"] || cachedDefaultPath || "/";
796
+ const rawPath = routeMode === "history" ? loc.query["path"] || loc.hash["path"] : loc.hash["path"];
797
+ let path = rawPath || cachedDefaultPath || "/";
796
798
  if (cachedRewrite) {
797
799
  path = cachedRewrite(
798
800
  path,
@@ -858,7 +860,16 @@ function getChanged(oldLoc, newLoc) {
858
860
  changedCache.set(tKey, finalResult);
859
861
  return finalResult;
860
862
  }
861
- function updateHash(path, replace) {
863
+ function updateBrowserUrl(path, replace) {
864
+ if (routeMode === "history") {
865
+ const url = path || "/";
866
+ if (replace) {
867
+ window.history.replaceState(null, "", url);
868
+ } else {
869
+ window.history.pushState(null, "", url);
870
+ }
871
+ return;
872
+ }
862
873
  const hashbang = frameworkConfig?.hashbang || "#!";
863
874
  const fullPath = path === "" ? "" : hashbang + path;
864
875
  if (replace) {
@@ -869,9 +880,10 @@ function updateHash(path, replace) {
869
880
  }
870
881
  function updateUrl(path, params, loc, replace, silentFlag, lQuery) {
871
882
  path = toUri(path, params, lQuery);
872
- if (path !== loc.srcHash) {
883
+ const currentSrc = routeMode === "history" ? loc.srcQuery : loc.srcHash;
884
+ if (path !== currentSrc) {
873
885
  silent = silentFlag ? 1 : 0;
874
- updateHash(path, replace);
886
+ updateBrowserUrl(path, replace);
875
887
  }
876
888
  }
877
889
  var Router = {
@@ -885,10 +897,29 @@ var Router = {
885
897
  if (cached) {
886
898
  return cached;
887
899
  }
888
- const srcQuery = href.replace(URL_TRIM_HASH_REGEXP, "");
889
- const srcHash = href.replace(URL_TRIM_QUERY_REGEXP, "");
890
- const query = parseUri(srcQuery);
891
- const hash = parseUri(srcHash);
900
+ let srcQuery;
901
+ let srcHash;
902
+ let query;
903
+ let hash;
904
+ if (routeMode === "history") {
905
+ try {
906
+ const urlObj = new URL(href, window.location.origin);
907
+ srcQuery = urlObj.pathname + urlObj.search;
908
+ srcHash = urlObj.hash ? urlObj.hash.replace(/^#!?/, "") : "";
909
+ query = parseUri(srcQuery);
910
+ hash = srcHash ? parseUri(srcHash) : { path: "", params: {} };
911
+ } catch {
912
+ srcQuery = href.replace(URL_TRIM_HASH_REGEXP, "");
913
+ srcHash = href.replace(URL_TRIM_QUERY_REGEXP, "");
914
+ query = parseUri(srcQuery);
915
+ hash = parseUri(srcHash);
916
+ }
917
+ } else {
918
+ srcQuery = href.replace(URL_TRIM_HASH_REGEXP, "");
919
+ srcHash = href.replace(URL_TRIM_QUERY_REGEXP, "");
920
+ query = parseUri(srcQuery);
921
+ hash = parseUri(srcHash);
922
+ }
892
923
  const params = assign({}, query["params"], hash["params"]);
893
924
  const location = {
894
925
  href,
@@ -962,7 +993,7 @@ var Router = {
962
993
  }
963
994
  }
964
995
  if (tPath) {
965
- if (!hasOwnProperty(window, "history")) {
996
+ if (routeMode === "hash" && !hasOwnProperty(window, "history")) {
966
997
  for (const qKey of lQuery) {
967
998
  if (!hasOwnProperty(tParams, qKey)) {
968
999
  tParams[qKey] = "";
@@ -1014,32 +1045,41 @@ var Router = {
1014
1045
  return Router;
1015
1046
  },
1016
1047
  /**
1017
- * Internal: bind hashchange and beforeunload events.
1048
+ * Internal: bind routing events and beforeunload.
1018
1049
  * Called by Framework.boot().
1050
+ * In hash mode, listens to hashchange + popstate.
1051
+ * In history mode, listens to popstate only.
1019
1052
  */
1020
1053
  _bind() {
1021
1054
  defaultTitle = document.title;
1022
- let lastHash = Router.parse().srcHash;
1055
+ const getLocationKey = () => {
1056
+ if (routeMode === "history") {
1057
+ return window.location.pathname + window.location.search;
1058
+ }
1059
+ return Router.parse().srcHash;
1060
+ };
1061
+ let lastKey = getLocationKey();
1023
1062
  let suspend;
1024
1063
  const watchChange = () => {
1025
1064
  if (suspend) {
1026
1065
  return;
1027
1066
  }
1067
+ hrefCache.clear();
1028
1068
  const loc = Router.parse();
1029
- const newHash = loc.srcHash;
1030
- if (newHash !== lastHash) {
1069
+ const newKey = routeMode === "history" ? loc.srcQuery : loc.srcHash;
1070
+ if (newKey !== lastKey) {
1031
1071
  const changeEvent = {
1032
1072
  p: 0,
1033
1073
  reject: () => {
1034
1074
  changeEvent.p = 1;
1035
1075
  suspend = "";
1036
- updateHash(lastHash);
1076
+ updateBrowserUrl(lastKey);
1037
1077
  },
1038
1078
  resolve: () => {
1039
1079
  changeEvent.p = 1;
1040
- lastHash = newHash;
1080
+ lastKey = newKey;
1041
1081
  suspend = "";
1042
- updateHash(newHash);
1082
+ updateBrowserUrl(newKey);
1043
1083
  Router.diff();
1044
1084
  },
1045
1085
  prevent: () => {
@@ -1083,8 +1123,12 @@ var Router = {
1083
1123
  }
1084
1124
  };
1085
1125
  Router.notify = watchChange;
1086
- window.addEventListener("hashchange", watchChange);
1087
- window.addEventListener("popstate", watchChange);
1126
+ if (routeMode === "history") {
1127
+ window.addEventListener("popstate", watchChange);
1128
+ } else {
1129
+ window.addEventListener("hashchange", watchChange);
1130
+ window.addEventListener("popstate", watchChange);
1131
+ }
1088
1132
  window.addEventListener("beforeunload", (domEvent) => {
1089
1133
  const data = {};
1090
1134
  Router.fire(RouterEvents.PAGE_UNLOAD, data);
@@ -1100,11 +1144,15 @@ var Router = {
1100
1144
  */
1101
1145
  _setConfig(cfg) {
1102
1146
  frameworkConfig = cfg;
1147
+ routeMode = cfg.routeMode || "history";
1103
1148
  }
1104
1149
  };
1105
1150
  function markRouterBooted() {
1106
1151
  booted2 = true;
1107
1152
  }
1153
+ function getRouteMode() {
1154
+ return routeMode;
1155
+ }
1108
1156
 
1109
1157
  // src/event-delegator.ts
1110
1158
  var rootEvents = {};
@@ -2443,6 +2491,7 @@ function defineView(props, statics) {
2443
2491
  // src/module-loader.ts
2444
2492
  var config = {
2445
2493
  rootId: "root",
2494
+ routeMode: "history",
2446
2495
  hashbang: "#!",
2447
2496
  error: (error) => {
2448
2497
  throw error;
@@ -3515,6 +3564,7 @@ function serviceSend(service, attrs, done, flag, save) {
3515
3564
  const payloadInfo = service.type.get(attrObj, save);
3516
3565
  const payloadEntity = payloadInfo.entity;
3517
3566
  const cacheKey = payloadEntity.cacheInfo?.key || "";
3567
+ doneArr[requestCount + 1] = payloadEntity;
3518
3568
  const complete = remoteComplete.bind(null, requestCount++);
3519
3569
  if (cacheKey && pendingCacheKeys[cacheKey]) {
3520
3570
  pendingCacheKeys[cacheKey].push(complete);
@@ -3554,6 +3604,23 @@ var FrameVisualBridge = {
3554
3604
  MSG_TREE_DELTA: "LARK_VIS_TREE_DELTA"
3555
3605
  };
3556
3606
  function serializeView(view) {
3607
+ const evtMap = view.eventObjectMap;
3608
+ const eventMethodKeys = evtMap ? Object.keys(evtMap) : [];
3609
+ const resourceKeys = view.resources ? Object.keys(view.resources) : [];
3610
+ const lookup = view;
3611
+ const hasAssign = typeof lookup["assign"] === "function";
3612
+ let updaterData = null;
3613
+ try {
3614
+ const ref = view.updater?.refData;
3615
+ if (ref && typeof ref === "object") {
3616
+ updaterData = {};
3617
+ for (const k of Object.keys(ref)) {
3618
+ const v = ref[k];
3619
+ updaterData[k] = v === null || typeof v !== "object" ? v : `[${typeof v}]`;
3620
+ }
3621
+ }
3622
+ } catch {
3623
+ }
3557
3624
  return {
3558
3625
  id: view.id,
3559
3626
  rendered: !!view.rendered,
@@ -3564,7 +3631,11 @@ function serializeView(view) {
3564
3631
  keys: view.locationObserved.keys,
3565
3632
  observePath: view.locationObserved.observePath
3566
3633
  },
3567
- hasTemplate: !!view.template
3634
+ hasTemplate: !!view.template,
3635
+ eventMethodKeys,
3636
+ resourceKeys,
3637
+ hasAssign,
3638
+ updaterData
3568
3639
  };
3569
3640
  }
3570
3641
  function serializeFrame(frameId) {
@@ -4003,904 +4074,161 @@ if (typeof window !== "undefined") {
4003
4074
  window.__lark_registerViewClass = registerViewClass;
4004
4075
  }
4005
4076
 
4006
- // src/store.ts
4007
- var LARK_GLOBAL = "lark-global";
4008
- var Platform = /* @__PURE__ */ ((Platform2) => {
4009
- Platform2["Lark"] = "lark";
4010
- Platform2["React"] = "react";
4011
- Platform2["Node"] = "node";
4012
- return Platform2;
4013
- })(Platform || {});
4014
- var isFunction = (val) => typeof val === "function";
4015
- var isObject = (val) => val !== null && typeof val === "object";
4016
- var isPromise = (val) => isObject(val) && isFunction(val["then"]);
4017
- var hasOwnProperty2 = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
4018
- var hasStructuredClone = typeof globalThis !== "undefined" && typeof globalThis.structuredClone === "function";
4019
- var deepCloneFallback = (obj) => {
4020
- if (!obj || !isObject(obj)) return {};
4021
- const newData = Array.isArray(obj) ? [] : {};
4022
- for (const key in obj) {
4023
- if (hasOwnProperty2(obj, key)) {
4024
- const value = obj[key];
4025
- newData[key] = isObject(value) ? deepCloneFallback(value) : value;
4026
- }
4027
- }
4028
- return newData;
4029
- };
4030
- var deepClone = (obj) => {
4031
- if (hasStructuredClone) {
4032
- try {
4033
- return structuredClone(obj);
4034
- } catch {
4035
- return deepCloneFallback(obj);
4036
- }
4037
- }
4038
- return deepCloneFallback(obj);
4039
- };
4040
- var cloneData = (data) => isObject(data) ? deepClone(data) : data;
4041
- var getDataByKey = (target, key) => {
4042
- if (!key.includes(".")) {
4043
- return target[key];
4044
- }
4045
- let data = target;
4046
- for (const k of key.split(".")) {
4047
- if (!isObject(data)) return void 0;
4048
- data = data[k];
4049
- }
4050
- return data;
4051
- };
4052
- var Queue = class {
4053
- pendingTasks = /* @__PURE__ */ new Set();
4054
- queue = [];
4055
- flushTasks() {
4056
- const { pendingTasks, queue } = this;
4057
- const flushTickTask = () => {
4058
- while (queue.length > 0) {
4059
- const task2 = queue.shift();
4060
- if (task2) {
4061
- pendingTasks.delete(task2);
4062
- runTask(task2);
4063
- }
4064
- }
4065
- };
4066
- Promise.resolve().then(flushTickTask);
4067
- }
4068
- add(tasks) {
4069
- const isQueueEmpty = this.queue.length === 0;
4070
- for (const { cb, params } of tasks) {
4071
- addParams2Callback(cb, params);
4072
- if (!this.pendingTasks.has(cb)) {
4073
- this.queue.push(cb);
4074
- this.pendingTasks.add(cb);
4075
- }
4076
- }
4077
- if (isQueueEmpty) this.flushTasks();
4078
- }
4079
- delete(tasks) {
4080
- if (this.pendingTasks.size === 0) return;
4081
- for (const { cb } of tasks) {
4082
- if (this.pendingTasks.has(cb)) {
4083
- this.pendingTasks.delete(cb);
4084
- const index = this.queue.findIndex((item) => item === cb);
4085
- if (index !== -1) this.queue.splice(index, 1);
4086
- }
4087
- }
4088
- }
4089
- clear() {
4090
- this.queue = [];
4091
- this.pendingTasks.clear();
4092
- }
4093
- };
4094
- var addParams2Callback = (cb, params) => {
4095
- if (!cb || !params) return;
4096
- const tagged = cb;
4097
- const existing = tagged.params;
4098
- if (isObject(existing)) {
4099
- Object.assign(existing, params);
4100
- } else {
4101
- tagged.params = params;
4102
- }
4103
- };
4104
- var runTask = (cb) => {
4105
- const tagged = cb;
4106
- const params = tagged.params;
4107
- delete tagged.params;
4108
- try {
4109
- cb(params);
4110
- } catch {
4111
- }
4112
- };
4113
- var getDefScheduler = () => new Queue();
4114
- var run = (tasks, scheduler) => {
4115
- if (scheduler) {
4116
- if (isFunction(scheduler)) {
4117
- for (const { cb, params } of tasks) scheduler(cb, params);
4118
- } else {
4119
- scheduler.add(tasks);
4077
+ // src/url-state.ts
4078
+ function useUrlState(view, initialState) {
4079
+ const keys2 = initialState ? Object.keys(initialState) : [];
4080
+ if (keys2.length > 0) {
4081
+ view.observeLocation(keys2);
4082
+ }
4083
+ const getState = () => {
4084
+ const loc = Router.parse();
4085
+ const result = { ...initialState || {} };
4086
+ for (const key of keys2) {
4087
+ const val = loc.get(key);
4088
+ if (val) result[key] = val;
4120
4089
  }
4121
- } else {
4122
- for (const { cb, params } of tasks) cb(params);
4123
- }
4124
- };
4125
- var ArrMethods = {};
4126
- ["indexOf", "lastIndexOf", "includes"].forEach((key) => {
4127
- const rawMethod = Array.prototype[key];
4128
- ArrMethods[key] = function(...args) {
4129
- let res = rawMethod.apply(this, args);
4130
- if (res === -1 || res === false) {
4131
- res = rawMethod.apply(
4132
- this,
4133
- args.map(
4134
- (item) => isObject(item) ? ProxyCache.get(item) ?? item : item
4135
- )
4136
- );
4137
- }
4138
- return res;
4139
- };
4140
- });
4141
- var inArrUpdate = false;
4142
- ["unshift", "shift", "push", "pop", "splice"].forEach((key) => {
4143
- const rawMethod = Array.prototype[key];
4144
- ArrMethods[key] = function(...args) {
4145
- inArrUpdate = true;
4146
- const result = rawMethod.apply(this, args);
4147
- inArrUpdate = false;
4148
4090
  return result;
4149
4091
  };
4150
- });
4151
- function needKeepArrItem(target, newVal, key) {
4152
- if (!Array.isArray(target) || !inArrUpdate) return false;
4153
- if (!isObject(newVal)) return false;
4154
- return getLinkKeys(newVal) === createLinkKeys(target, key);
4155
- }
4156
- var defStateConfig = {
4157
- belong: LARK_GLOBAL,
4158
- linkKeys: "",
4159
- shallow: false
4160
- };
4161
- var StateConfigMap = /* @__PURE__ */ new WeakMap();
4162
- var setStateConfig = (target, config2) => {
4163
- if (target && isObject(config2)) StateConfigMap.set(target, config2);
4164
- };
4165
- function getStateConfig(target, key) {
4166
- if (!StateConfigMap.has(target)) {
4167
- return void 0;
4168
- }
4169
- const config2 = StateConfigMap.get(target);
4170
- return key ? config2?.[key] : config2;
4171
- }
4172
- var isState = (target) => isObject(target) && StateConfigMap.has(target);
4173
- var createLinkKeys = (target, property) => {
4174
- if (!hasLinkKeys(target)) return property;
4175
- if (Array.isArray(target)) return getLinkKeys(target) ?? property;
4176
- return `${getLinkKeys(target)}.${property}`;
4177
- };
4178
- var formatLinkKeys = (target, key) => {
4179
- const originKeysStr = getLinkKeys(target);
4180
- if (!originKeysStr) return null;
4181
- const linkKeys = [];
4182
- const originKeys = originKeysStr.split(".");
4183
- let pre = "";
4184
- for (const k of originKeys) {
4185
- const curr = pre ? `${pre}.${k}` : k;
4186
- linkKeys.push(curr);
4187
- pre = curr;
4188
- }
4189
- linkKeys.push(`${originKeysStr}.${key}`);
4190
- return linkKeys;
4191
- };
4192
- var getLinkKeys = (target) => getStateConfig(target, "linkKeys");
4193
- var hasLinkKeys = (target) => !!getLinkKeys(target);
4194
- var ProxyCache = /* @__PURE__ */ new WeakMap();
4195
- var keepKey = null;
4196
- var keep = (key) => {
4197
- if (keepKey) throw new Error("[lark-store] keepKey is not null");
4198
- keepKey = key;
4199
- };
4200
- var needKeep = (key) => {
4201
- if (keepKey === key) {
4202
- keepKey = null;
4203
- return true;
4204
- }
4205
- return false;
4206
- };
4207
- var canSetNewVal = (params) => {
4208
- const { property, newVal, oldVal } = params;
4209
- if (hasOwnProperty2(params.target, property) && newVal === oldVal)
4210
- return false;
4211
- return true;
4212
- };
4213
- var getNewVal = (params) => {
4214
- const { target, newVal, property, needKeepVal = false } = params;
4215
- const config2 = getStateConfig(target);
4216
- if (!isObject(newVal)) return newVal;
4217
- if (needKeepArrItem(target, newVal, property)) return newVal;
4218
- if (config2?.shallow) return newVal;
4219
- if (needKeepVal) return newVal;
4220
- const linkKeys = createLinkKeys(target, property);
4221
- const newState = createState(newVal, { ...config2, linkKeys });
4222
- if (isPromise(newVal)) handlePromise(newVal, target, property);
4223
- return newState;
4224
- };
4225
- var genPayload = (params) => {
4226
- const { target, property, newVal, oldVal } = params;
4227
- const config2 = getStateConfig(target) ?? defStateConfig;
4228
- return {
4229
- belong: config2.belong || LARK_GLOBAL,
4230
- target,
4231
- keys: formatLinkKeys(target, property) || [property],
4232
- newVal,
4233
- oldVal
4092
+ const setState = (patch) => {
4093
+ const current = getState();
4094
+ const resolved = typeof patch === "function" ? patch(current) : patch;
4095
+ Router.to(resolved);
4234
4096
  };
4235
- };
4236
- var handlePromise = (child, parent, key) => {
4237
- const childObj = child;
4238
- child.then((res) => {
4239
- const parentProxy = ProxyCache.get(parent);
4240
- if (parentProxy) {
4241
- const oldVal = parentProxy[key];
4242
- if (ProxyCache.get(childObj) === oldVal) {
4243
- parentProxy[key] = res;
4244
- }
4245
- }
4246
- }).catch((err) => {
4247
- const parentProxy = ProxyCache.get(parent);
4248
- if (parentProxy) {
4249
- const oldVal = parentProxy[key];
4250
- if (ProxyCache.get(childObj) === oldVal) {
4251
- parentProxy[key] = err;
4252
- }
4253
- }
4254
- });
4255
- };
4256
- var _deleteKey = "_delete";
4257
- var _markObjKey = "_markObj";
4258
- var mark2 = (host, key) => {
4259
- let sign;
4260
- if (!host[_deleteKey]) {
4261
- const markHost = host[_markObjKey] || (host[_markObjKey] = {});
4262
- if (!hasOwnProperty2(markHost, key)) {
4263
- markHost[key] = 0;
4264
- }
4265
- sign = ++markHost[key];
4266
- }
4267
- return () => {
4268
- const temp = host[_markObjKey];
4269
- return !!temp && sign === temp[key];
4270
- };
4271
- };
4272
- var unmark2 = (host) => {
4273
- host[_deleteKey] = 1;
4274
- host[_markObjKey] = 0;
4275
- };
4276
- function createState(initialData, config2) {
4277
- if (!isObject(initialData)) return initialData;
4278
- const mergedConfig = Object.assign({ ...defStateConfig }, config2);
4279
- const data = Array.isArray(initialData) ? [] : Object.create(Object.getPrototypeOf(initialData));
4280
- const handler = {
4281
- get(target, property, _receiver) {
4282
- if (Array.isArray(target) && property in ArrMethods) {
4283
- return ArrMethods[property];
4284
- }
4285
- return Reflect.get(target, property);
4286
- },
4287
- set(target, property, newVal, receiver) {
4288
- const strProp = property;
4289
- const oldVal = Reflect.get(target, property);
4290
- const preventTrigger = isLazySet(strProp);
4291
- const needKeepVal = needKeep(strProp);
4292
- const canSet = canSetNewVal({
4293
- target,
4294
- property: strProp,
4295
- newVal,
4296
- oldVal
4297
- });
4298
- if (!canSet) return true;
4299
- const proxyTarget = isObject(receiver) && receiver !== null ? receiver : state;
4300
- newVal = getNewVal({
4301
- target: proxyTarget,
4302
- property: strProp,
4303
- newVal,
4304
- needKeepVal
4305
- });
4306
- Reflect.set(target, property, newVal, receiver);
4307
- if (preventTrigger) return true;
4308
- const payload = genPayload({
4309
- target: proxyTarget,
4310
- property: strProp,
4311
- newVal,
4312
- oldVal
4313
- });
4314
- trigger(payload);
4315
- return true;
4316
- },
4317
- deleteProperty(target, property) {
4318
- const strProp = property;
4319
- if (!hasOwnProperty2(target, strProp)) return true;
4320
- const oldVal = Reflect.get(target, property);
4321
- Reflect.deleteProperty(target, property);
4322
- const payload = genPayload({
4323
- target: state,
4324
- property: strProp,
4325
- newVal: null,
4326
- oldVal
4327
- });
4328
- trigger(payload);
4329
- return true;
4330
- }
4331
- };
4332
- const state = new Proxy(data, handler);
4333
- ProxyCache.set(initialData, state);
4334
- setStateConfig(state, mergedConfig);
4335
- lazySet(state, initialData);
4336
- return state;
4337
- }
4338
- var curLazySetKey = null;
4339
- function lazySet(target, data) {
4340
- if (isObject(data)) {
4341
- Reflect.ownKeys(data).forEach((key) => {
4342
- const strKey = key;
4343
- if (curLazySetKey) throw new Error("[lark-store] lazy set key conflict");
4344
- curLazySetKey = strKey;
4345
- target[strKey] = data[strKey];
4346
- });
4347
- }
4348
- }
4349
- function isLazySet(property) {
4350
- if (curLazySetKey === property) {
4351
- curLazySetKey = "";
4352
- return true;
4353
- }
4354
- return false;
4355
- }
4356
- function shallowSet(target, key, data) {
4357
- if (!isState(target))
4358
- throw new Error("[lark-store] shallowSet only supports state objects");
4359
- if (!isObject(data)) return target[key] = data;
4360
- keep(key);
4361
- const config2 = getStateConfig(target);
4362
- const linkKeys = createLinkKeys(target, key);
4363
- target[key] = createState(data, { ...config2, linkKeys, shallow: true });
4364
- return target[key];
4097
+ return [getState(), setState];
4365
4098
  }
4366
- var GlobalDeps = /* @__PURE__ */ new Map();
4367
- function track(payload) {
4368
- const { belong, trackList = [] } = payload;
4369
- let deps = GlobalDeps.get(belong);
4370
- if (!deps) GlobalDeps.set(belong, deps = /* @__PURE__ */ new Map());
4371
- for (const { key, cb } of trackList) {
4372
- if (isFunction(cb)) {
4373
- let callbacks = deps.get(key);
4374
- if (!callbacks) deps.set(key, callbacks = /* @__PURE__ */ new Set());
4375
- callbacks.add(cb);
4376
- }
4377
- }
4378
- }
4379
- function trigger(payload) {
4380
- const { belong, keys: keys2 } = payload;
4381
- const store = getStore(belong);
4382
- if (store && store.status !== 2 /* ACTIVE */ && belong !== LARK_GLOBAL)
4383
- return;
4384
- const deps = GlobalDeps.get(belong);
4385
- if (!deps) return;
4386
- const tasks = /* @__PURE__ */ new Set();
4387
- for (const key of keys2) {
4388
- const callbacks = deps.get(key);
4389
- if (callbacks) {
4390
- for (const cb of callbacks) {
4391
- tasks.add({ cb, params: { [key]: true } });
4392
- }
4393
- }
4394
- }
4395
- if (tasks.size === 0) return;
4396
- const scheduler = store?.scheduler;
4397
- run(Array.from(tasks), scheduler);
4099
+
4100
+ // src/store.ts
4101
+ var COMPUTED_BRAND = /* @__PURE__ */ Symbol("lark-store-computed");
4102
+ function isComputedMarker(val) {
4103
+ return val !== null && typeof val === "object" && val[COMPUTED_BRAND] === true;
4398
4104
  }
4399
- function clear(payload) {
4400
- if (!payload) {
4401
- GlobalDeps.clear();
4402
- return;
4403
- }
4404
- const { belong, clearList } = payload;
4405
- const deps = GlobalDeps.get(belong);
4406
- if (!deps) return;
4407
- const store = getStore(belong);
4408
- const scheduler = store?.scheduler;
4409
- if (clearList) {
4410
- for (const { key, cb } of clearList) {
4411
- const callbacks = deps.get(key);
4412
- if (callbacks) {
4413
- if (!cb) {
4414
- deps.delete(key);
4415
- } else if (callbacks.has(cb)) {
4416
- callbacks.delete(cb);
4417
- if (scheduler && !isFunction(scheduler)) {
4418
- scheduler.delete([{ cb }]);
4419
- }
4420
- if (callbacks.size === 0) deps.delete(key);
4105
+ function computed(deps, fn) {
4106
+ return { [COMPUTED_BRAND]: true, deps, fn };
4107
+ }
4108
+ var storeRegistry = /* @__PURE__ */ new Map();
4109
+ function create(name, creator) {
4110
+ const listeners = /* @__PURE__ */ new Set();
4111
+ const computedDefs = /* @__PURE__ */ new Map();
4112
+ const computedKeys = /* @__PURE__ */ new Set();
4113
+ const actionKeys = /* @__PURE__ */ new Set();
4114
+ let state;
4115
+ let destroyed = false;
4116
+ const getState = () => state;
4117
+ const setState = (partial) => {
4118
+ if (destroyed) return;
4119
+ const prevState = state;
4120
+ const resolved = typeof partial === "function" ? partial(prevState) : partial;
4121
+ const nextState = { ...prevState };
4122
+ let changed = false;
4123
+ for (const key in resolved) {
4124
+ if (Object.prototype.hasOwnProperty.call(resolved, key) && !computedKeys.has(key) && !actionKeys.has(key)) {
4125
+ const newVal = resolved[key];
4126
+ if (!Object.is(prevState[key], newVal)) {
4127
+ nextState[key] = newVal;
4128
+ changed = true;
4421
4129
  }
4422
4130
  }
4423
4131
  }
4424
- } else {
4425
- deps.clear();
4426
- GlobalDeps.delete(belong);
4427
- if (scheduler && !isFunction(scheduler)) {
4428
- scheduler.clear();
4132
+ if (!changed) return;
4133
+ state = nextState;
4134
+ recomputeIfNeeded(prevState);
4135
+ for (const listener of listeners) {
4136
+ listener(state, prevState);
4429
4137
  }
4430
- }
4431
- }
4432
- var _storeName = /* @__PURE__ */ Symbol("store-name");
4433
- var _storeStatus = /* @__PURE__ */ Symbol("store-status");
4434
- var _storeScheduler = /* @__PURE__ */ Symbol("store-scheduler");
4435
- var _storeCreate = /* @__PURE__ */ Symbol("fn:store-create");
4436
- var _storeBoot = /* @__PURE__ */ Symbol("fn:store-boot");
4437
- var _storeDestroy = /* @__PURE__ */ Symbol("fn:store-destroy");
4438
- var _innerStore = /* @__PURE__ */ Symbol("inner-store");
4439
- var _outerStore = /* @__PURE__ */ Symbol("outer-store");
4440
- var _originState = /* @__PURE__ */ Symbol("origin-state");
4441
- var _stateKeys = /* @__PURE__ */ Symbol("state-keys");
4442
- var _storeState = /* @__PURE__ */ Symbol("store-state");
4443
- var _storeDefScheduler = /* @__PURE__ */ Symbol("store-def-scheduler");
4444
- var _storeProxy = /* @__PURE__ */ Symbol("fn:store-proxy");
4445
- var _computedKeys = /* @__PURE__ */ Symbol("store-computed-keys");
4446
- var COMPUTED_BRAND = /* @__PURE__ */ Symbol("store-computed-brand");
4447
- function computed(deps, fn) {
4448
- const marker = {
4449
- [COMPUTED_BRAND]: true,
4450
- deps,
4451
- fn
4452
4138
  };
4453
- return marker;
4454
- }
4455
- function isComputedMarker(val) {
4456
- return isObject(val) && val[COMPUTED_BRAND] === true;
4457
- }
4458
- var BaseStore = class {
4459
- [_storeStatus] = 0 /* BEFORE_CREATE */;
4460
- [_computedKeys] = /* @__PURE__ */ new Set();
4461
- [_storeDefScheduler] = getDefScheduler;
4462
- [_storeBoot]() {
4463
- this[_storeStatus] = 2 /* ACTIVE */;
4464
- return this[_storeProxy](true);
4465
- }
4466
- [_storeDestroy]() {
4467
- clear({ belong: this[_storeName] });
4468
- this[_storeState] = createState(this[_originState], {
4469
- belong: this[_storeName]
4470
- });
4471
- this[_storeStatus] = 3 /* DESTROYED */;
4472
- }
4473
- /**
4474
- *
4475
- * @param body - The object returned by the creator function
4476
- * @param excludeFns - Function keys to exclude from handlers (e.g. ['observe'])
4477
- */
4478
- [_storeCreate](body, excludeFns = ["observe"]) {
4479
- this[_storeStatus] = 1 /* CREATED */;
4480
- if (isObject(body)) {
4481
- const state = {};
4482
- const handlers = {};
4483
- const computedDefs = {};
4484
- const computedKeys = this[_computedKeys];
4485
- Reflect.ownKeys(body).forEach((key) => {
4486
- const strKey = key;
4487
- const val = body[strKey];
4488
- if (isComputedMarker(val)) {
4489
- computedDefs[strKey] = val;
4490
- state[strKey] = void 0;
4491
- computedKeys.add(strKey);
4492
- } else if (isFunction(val)) {
4493
- if (!excludeFns.includes(strKey)) handlers[strKey] = val;
4494
- } else {
4495
- state[strKey] = val;
4496
- }
4497
- });
4498
- Object.assign(this, handlers);
4499
- this[_originState] = cloneData(state);
4500
- this[_stateKeys] = Object.keys(state);
4501
- this[_storeState] = createState(state, { belong: this[_storeName] });
4502
- if (Object.keys(computedDefs).length > 0) {
4503
- const belong = this[_storeName];
4504
- const storeState = this[_storeState];
4505
- for (const key of Object.keys(computedDefs)) {
4506
- const def = computedDefs[key];
4507
- const recompute = () => {
4508
- storeState[key] = def.fn();
4509
- };
4510
- recompute();
4511
- const trackList = def.deps.map((depKey) => ({
4512
- key: depKey,
4513
- cb: recompute
4514
- }));
4515
- if (trackList.length > 0) track({ belong, trackList });
4139
+ const recomputeIfNeeded = (prevState) => {
4140
+ if (computedDefs.size === 0) return;
4141
+ const changedKeys2 = /* @__PURE__ */ new Set();
4142
+ for (const key of Object.keys(state)) {
4143
+ if (!Object.is(
4144
+ state[key],
4145
+ prevState[key]
4146
+ )) {
4147
+ changedKeys2.add(key);
4148
+ }
4149
+ }
4150
+ let recomputed = false;
4151
+ for (const [key, def] of computedDefs) {
4152
+ if (def.deps.some((dep) => changedKeys2.has(dep))) {
4153
+ const newVal = def.fn();
4154
+ if (!Object.is(state[key], newVal)) {
4155
+ state[key] = newVal;
4156
+ recomputed = true;
4516
4157
  }
4517
4158
  }
4518
4159
  }
4519
- }
4520
- constructor(name, config2) {
4521
- this[_storeName] = name;
4522
- this[_storeScheduler] = config2?.scheduler || this[_storeDefScheduler]();
4523
- this[_outerStore] = this[_storeProxy](true);
4524
- }
4525
- [_innerStore]() {
4526
- return this[_storeProxy]();
4527
- }
4528
- get status() {
4529
- return this[_storeStatus];
4530
- }
4531
- get storeName() {
4532
- return this[_storeName];
4533
- }
4534
- get scheduler() {
4535
- return this[_storeScheduler];
4536
- }
4537
- [_storeProxy](toOut = false) {
4538
- const self = this;
4539
- const proxy = new Proxy(self, {
4540
- get(target, property) {
4541
- const strProp = property;
4542
- if (self[_stateKeys].includes(strProp)) {
4543
- const val = self[_storeState][strProp];
4544
- return toOut ? cloneData(val) : val;
4545
- }
4546
- return Reflect.get(target, property);
4547
- },
4548
- set(_target, property, val) {
4549
- if (toOut) return true;
4550
- const strProp = property;
4551
- if (self[_computedKeys].has(strProp)) return true;
4552
- if (self[_stateKeys].includes(strProp)) {
4553
- self[_storeState][strProp] = val;
4554
- }
4555
- return true;
4556
- },
4557
- has(target, property) {
4558
- return Reflect.has(target, property) || self[_stateKeys].includes(property);
4559
- }
4560
- });
4561
- return proxy;
4562
- }
4563
- };
4564
- var LarkUtils = {
4565
- isLarkView(instance) {
4566
- if (!isObject(instance)) return false;
4567
- const updater = instance["updater"];
4568
- return isObject(updater) && isFunction(updater["set"]) && isFunction(updater["digest"]);
4569
- },
4570
- getRender(view) {
4571
- return view.updater.digest.bind(view.updater);
4572
- },
4573
- getDataSetter(view) {
4574
- return view.updater.set.bind(view.updater);
4575
- },
4576
- onDestroy(view, cb) {
4577
- view.on("destroy", cb);
4578
- }
4579
- };
4580
- var getLarkAdapter = (storeName) => ({
4581
- Store: LarkStore,
4582
- useStore: ((view) => {
4583
- const store = getStore(storeName);
4584
- if (!(store instanceof LarkStore)) return {};
4585
- return store[_storeBoot](view);
4586
- })
4587
- });
4588
- var _innerObserveFlags = /* @__PURE__ */ Symbol("store-inner-observe-flags");
4589
- var _boundViews = /* @__PURE__ */ Symbol("store-bound-views");
4590
- var LarkStore = class extends BaseStore {
4591
- [_boundViews] = /* @__PURE__ */ new Set();
4592
- [_innerObserveFlags] = /* @__PURE__ */ new Set();
4593
- [_storeBoot](view) {
4594
- if (view && LarkUtils.isLarkView(view) && !this[_boundViews].has(view)) {
4595
- this[_boundViews].add(view);
4596
- LarkUtils.onDestroy(view, () => {
4597
- this[_boundViews].delete(view);
4598
- });
4599
- }
4600
- return super[_storeBoot]();
4601
- }
4602
- [_storeDestroy]() {
4603
- this[_boundViews].clear();
4604
- this[_innerObserveFlags].clear();
4605
- super[_storeDestroy]();
4606
- }
4607
- observe(view, keys2, defCallback) {
4608
- if (this[_storeStatus] !== 2 /* ACTIVE */) return noop;
4609
- let observeKeys = Array.isArray(keys2) ? keys2 : [];
4610
- const _view = view;
4611
- const renderFn = _view ? LarkUtils.getRender(_view) : noop;
4612
- const dateSetterFn = _view ? LarkUtils.getDataSetter(_view) : noop;
4613
- const isInnerObserve = !view;
4614
- const innerFlags = /* @__PURE__ */ new Set();
4615
- const storeInnerObserveFlags = this[_innerObserveFlags];
4616
- if (isFunction(keys2)) {
4617
- const res = keys2();
4618
- if (Array.isArray(res)) observeKeys = res;
4619
- }
4620
- if (keys2 === void 0 && _view && observeKeys.length === 0 && Array.isArray(this[_stateKeys])) {
4621
- observeKeys = this[_stateKeys].slice();
4622
- }
4623
- const defSetter = (immediate, key, alias, transform) => () => {
4624
- const stateVal = getDataByKey(this, key);
4625
- let data = { [alias || key]: stateVal };
4626
- if (transform && isFunction(transform)) {
4627
- const newData = transform(stateVal);
4628
- if (isObject(newData)) data = newData;
4629
- }
4630
- if (immediate) dateSetterFn(data);
4631
- else renderFn(data);
4632
- };
4633
- const getList = (immediate = false) => {
4634
- const list = [];
4635
- for (const item of observeKeys) {
4636
- if (!item) continue;
4637
- const payload = typeof item === "string" ? { key: item } : item;
4638
- const { cb: cbDefault = defCallback, key } = payload;
4639
- let cb = cbDefault;
4640
- const { alias, lazy = true, transform } = payload;
4641
- if (!key) continue;
4642
- const c1 = !immediate;
4643
- const c2 = !cb && !!_view;
4644
- const c3 = !!cb && String(lazy) === "false";
4645
- if (!(c1 || c2 || c3)) continue;
4646
- if (isInnerObserve && cb) {
4647
- const flag = `storeInner_${key}_${observeKeys.join("-")}_${cb.toString()}`;
4648
- if (!storeInnerObserveFlags.has(flag)) {
4649
- storeInnerObserveFlags.add(flag);
4650
- innerFlags.add(flag);
4651
- }
4652
- }
4653
- if (c2) cb = defSetter(immediate, key, alias, transform);
4654
- if (cb) list.push({ key, cb });
4655
- }
4656
- return list;
4657
- };
4658
- const trackList = getList();
4659
- track({ belong: this[_storeName], trackList });
4660
- if (_view) {
4661
- LarkUtils.onDestroy(
4662
- _view,
4663
- () => clear({ belong: this[_storeName], clearList: trackList })
4664
- );
4160
+ if (recomputed) {
4665
4161
  }
4666
- if (!isInnerObserve) run(getList(true));
4162
+ };
4163
+ const subscribe = (listener) => {
4164
+ listeners.add(listener);
4667
4165
  return () => {
4668
- clear({ belong: this[_storeName], clearList: trackList });
4669
- innerFlags.forEach((flag) => storeInnerObserveFlags.delete(flag));
4166
+ listeners.delete(listener);
4670
4167
  };
4671
- }
4672
- };
4673
- var getReactAdapter = (storeName) => ({
4674
- Store: ReactStore,
4675
- useStore: (() => {
4676
- const store = getStore(storeName);
4677
- if (!(store instanceof ReactStore)) return {};
4678
- return store[_storeBoot]();
4679
- })
4680
- });
4681
- var _observe = /* @__PURE__ */ Symbol("store-observe");
4682
- var _getLastState = /* @__PURE__ */ Symbol("store-get-last-state");
4683
- var ReactStore = class extends BaseStore {
4684
- stateChangeCount = 0;
4685
- lastCount = 0;
4686
- lastState = null;
4687
- constructor(name, config2) {
4688
- const effectiveConfig = config2 && !config2.scheduler ? {
4689
- ...config2,
4690
- scheduler: (cb, params) => cb(params)
4691
- } : config2;
4692
- super(name, effectiveConfig);
4693
- }
4694
- [_storeCreate](body) {
4695
- super[_storeCreate](body);
4696
- this[_observe](() => {
4697
- this.stateChangeCount += 1;
4698
- });
4699
- }
4700
- isStateChanged() {
4701
- const currCount = this.stateChangeCount;
4702
- const changed = this.lastCount !== currCount;
4703
- this.lastCount = currCount;
4704
- return changed;
4705
- }
4706
- [_getLastState](handlers) {
4707
- if (this.isStateChanged() || !this.lastState) {
4708
- const state = this[_storeState];
4709
- const immutableState = freezeData(state);
4710
- this.lastState = Object.assign({}, handlers, immutableState);
4711
- }
4712
- return this.lastState;
4713
- }
4714
- [_observe](cb) {
4715
- const tasks = this[_stateKeys].map((key) => ({ key, cb }));
4716
- track({ belong: this[_storeName], trackList: tasks });
4717
- return () => clear({ belong: this[_storeName], clearList: tasks });
4718
- }
4719
- };
4720
- var freezeData = (target) => {
4721
- const data = {};
4722
- const keys2 = Object.keys(target);
4723
- for (const key of keys2) {
4724
- const value = target[key];
4725
- if (Array.isArray(value)) {
4726
- data[key] = value.map(
4727
- (item) => isObject(item) ? freezeData(item) : item
4728
- );
4729
- } else if (isObject(value)) {
4730
- data[key] = freezeData(value);
4168
+ };
4169
+ const destroy = () => {
4170
+ destroyed = true;
4171
+ listeners.clear();
4172
+ storeRegistry.delete(name);
4173
+ };
4174
+ const api = { getState, setState, subscribe, destroy };
4175
+ const body = creator(setState, getState);
4176
+ const initialState = {};
4177
+ const actions = {};
4178
+ for (const key of Object.keys(body)) {
4179
+ const val = body[key];
4180
+ if (isComputedMarker(val)) {
4181
+ computedDefs.set(key, val);
4182
+ computedKeys.add(key);
4183
+ initialState[key] = void 0;
4184
+ } else if (typeof val === "function") {
4185
+ actions[key] = val;
4186
+ actionKeys.add(key);
4731
4187
  } else {
4732
- data[key] = value;
4188
+ initialState[key] = val;
4733
4189
  }
4734
4190
  }
4735
- return data;
4736
- };
4737
- var getNodeAdapter = (storeName) => ({
4738
- Store: NodeStore,
4739
- useStore: (() => {
4740
- const store = getStore(storeName);
4741
- if (!(store instanceof NodeStore)) return {};
4742
- return store[_storeBoot]();
4743
- })
4744
- });
4745
- var NodeStore = class extends BaseStore {
4746
- observe(key, callback, immediate = true) {
4747
- const tasks = [{ key, cb: callback }];
4748
- track({ belong: this[_storeName], trackList: tasks });
4749
- if (immediate) run(tasks);
4750
- return () => clear({ belong: this[_storeName], clearList: tasks });
4191
+ state = { ...initialState, ...actions };
4192
+ for (const [key, def] of computedDefs) {
4193
+ state[key] = def.fn();
4751
4194
  }
4752
- };
4753
- var getAdapter = (platform, storeName) => {
4754
- switch (platform) {
4755
- case "react" /* React */:
4756
- return getReactAdapter(storeName);
4757
- case "node" /* Node */:
4758
- return getNodeAdapter(storeName);
4759
- case "lark" /* Lark */:
4760
- default:
4761
- return getLarkAdapter(storeName);
4762
- }
4763
- };
4764
- var getPlatform = (comp) => {
4765
- if (LarkUtils.isLarkView(comp)) return "lark" /* Lark */;
4766
- return void 0;
4767
- };
4768
- var extendApis = { lazySet, shallowSet, computed };
4769
- var StoreCache = /* @__PURE__ */ new Map();
4770
- function defineStore(name, creator, config2) {
4771
- if (StoreCache.has(name)) {
4772
- name = name + "_copy";
4773
- }
4774
- const { platform = "lark" /* Lark */ } = config2 || {};
4775
- const adapter = getAdapter(platform, name);
4776
- const StoreClass = adapter.Store;
4777
- const useStore = adapter.useStore;
4778
- const store = new StoreClass(name, config2);
4779
- const innerProxy = store[_innerStore]();
4780
- const body = creator(innerProxy, extendApis);
4781
- store[_storeCreate](body);
4782
- Object.defineProperties(useStore, {
4783
- $storeName: { value: name, configurable: true },
4784
- $destroyFn: { value: () => store[_storeDestroy](), configurable: true }
4785
- });
4786
- if (!StoreCache.has(name)) {
4787
- StoreCache.set(name, {
4788
- store,
4789
- creator,
4790
- config: config2,
4791
- useStore
4792
- });
4793
- }
4794
- return useStore;
4195
+ storeRegistry.set(name, api);
4196
+ return api;
4795
4197
  }
4796
- function getStore(name) {
4797
- if (name && StoreCache.has(name)) {
4798
- const entry = StoreCache.get(name);
4799
- return entry ? entry.store : void 0;
4800
- }
4801
- return void 0;
4802
- }
4803
- function delStore(name) {
4804
- if (name && StoreCache.has(name)) StoreCache.delete(name);
4805
- }
4806
- function getUseStore(name) {
4807
- if (name && StoreCache.has(name)) {
4808
- const entry = StoreCache.get(name);
4809
- return entry ? entry.useStore : void 0;
4810
- }
4811
- return void 0;
4812
- }
4813
- function cloneStore(name, useStore, config2) {
4814
- const oldStoreName = useStore.$storeName ?? "";
4815
- const cached = StoreCache.get(oldStoreName);
4816
- const oldStoreCreator = cached?.creator;
4817
- const oldConfig = cached?.config || {};
4818
- if (!name || !oldStoreCreator) return;
4819
- const mergedConfig = { ...oldConfig, ...config2 || {} };
4820
- return defineStore(
4821
- name,
4822
- oldStoreCreator,
4823
- mergedConfig
4824
- );
4198
+ function isLarkView(instance) {
4199
+ if (!instance || typeof instance !== "object") return false;
4200
+ const obj = instance;
4201
+ const updater = obj["updater"];
4202
+ return updater !== null && typeof updater === "object" && typeof updater["set"] === "function" && typeof updater["digest"] === "function";
4825
4203
  }
4826
- function isStoreActive(name) {
4827
- if (name && StoreCache.has(name)) {
4828
- const entry = StoreCache.get(name);
4829
- return entry ? entry.store.status === 2 /* ACTIVE */ : false;
4830
- }
4831
- return false;
4832
- }
4833
- var cellCount = 0;
4834
- function cell(data) {
4835
- const linkKeys = `${LARK_GLOBAL}_${cellCount++}`;
4836
- return createState(data, { belong: LARK_GLOBAL, linkKeys });
4837
- }
4838
- function observeCell(state, cb, immediate = true) {
4839
- const linkKeys = getLinkKeys(state);
4840
- if (!linkKeys) return noop;
4841
- const keys2 = linkKeys.split(".");
4842
- const key = keys2[keys2.length - 1];
4843
- const list = [{ key, cb }];
4844
- track({ belong: LARK_GLOBAL, trackList: list });
4845
- if (immediate) cb();
4846
- return () => clear({ belong: LARK_GLOBAL, clearList: list });
4847
- }
4848
- function multi(useStore) {
4849
- const storeName = useStore.$storeName ?? "";
4850
- const flagSym = `lark-comp-${storeName}`;
4851
- const map = /* @__PURE__ */ new Map();
4852
- let rootViewPath;
4853
- const getFlag = (viewContext) => {
4854
- const owner = viewContext.owner;
4855
- const viewPath = owner?.path ?? "";
4856
- const viewId = owner?.id ?? "";
4857
- let flag;
4858
- if (viewPath === rootViewPath) {
4859
- flag = `${flagSym}-${viewId}`;
4860
- } else {
4861
- const initParams = owner?.viewInitParams;
4862
- const candidate = initParams?.[flagSym];
4863
- flag = typeof candidate === "string" ? candidate : void 0;
4864
- }
4865
- if (owner && isFunction(owner.mountFrame)) {
4866
- const rawMountFrame = owner.mountFrame;
4867
- owner.mountFrame = (frameId, viewPath2, viewInitParams = {}) => rawMountFrame.call(
4868
- owner,
4869
- frameId,
4870
- viewPath2,
4871
- Object.assign(viewInitParams, { [flagSym]: flag })
4872
- );
4873
- }
4874
- return flag ?? "";
4204
+ function bindStore(view, store, selector) {
4205
+ if (!isLarkView(view)) return () => {
4875
4206
  };
4876
- const useFn = ((view) => {
4877
- if (!view)
4878
- throw new Error(
4879
- "[@lark.js/mvc error] multi: cannot find the view instance"
4880
- );
4881
- const viewCtx = view;
4882
- const tag = viewCtx[flagSym];
4883
- const flag = typeof tag === "string" ? tag : "";
4884
- if (map.has(flag)) return map.get(flag);
4885
- const newFn = cloneStore(flag, useStore);
4886
- map.set(flag, newFn);
4887
- return useFn(view);
4888
- });
4889
- const mixinObj = {
4890
- make() {
4891
- if (!rootViewPath) {
4892
- rootViewPath = this.owner?.path ?? "";
4207
+ const extract = (s) => {
4208
+ if (selector) return selector(s);
4209
+ const result = {};
4210
+ for (const key in s) {
4211
+ if (Object.prototype.hasOwnProperty.call(s, key) && typeof s[key] !== "function") {
4212
+ result[key] = s[key];
4893
4213
  }
4894
- this[flagSym] = getFlag(this);
4895
4214
  }
4215
+ return result;
4896
4216
  };
4897
- return [useFn, mixinObj];
4217
+ view.updater.set(extract(store.getState()));
4218
+ view.updater.digest();
4219
+ const off = store.subscribe((state) => {
4220
+ view.updater.set(extract(state));
4221
+ view.updater.digest();
4222
+ });
4223
+ view.on("destroy", off);
4224
+ return off;
4898
4225
  }
4226
+ var defineStore = create;
4899
4227
 
4900
4228
  // src/compiler.ts
4901
4229
  import { parse as babelParse } from "@babel/parser";
4902
- var SPLITTER2 = "";
4903
- var VIEW_ID_PLACEHOLDER = "";
4230
+ var SPLITTER2 = String.fromCharCode(30);
4231
+ var VIEW_ID_PLACEHOLDER = String.fromCharCode(31);
4904
4232
  function jsObjectToUrlParams(paramsStr) {
4905
4233
  const trimmed = paramsStr.trim();
4906
4234
  if (!/^[{[]/.test(trimmed) && /=/.test(trimmed)) {
@@ -4960,7 +4288,7 @@ function addLineMarkers(source) {
4960
4288
  if (parts.length > 1) {
4961
4289
  const reconstructed = parts.map((part, i) => {
4962
4290
  if (i === 0) return part;
4963
- return openTag + SPLITTER2 + ++lineNo;
4291
+ return openTag + SPLITTER2 + ++lineNo + part;
4964
4292
  }).join("");
4965
4293
  result.push(reconstructed);
4966
4294
  } else {
@@ -5353,7 +4681,7 @@ function extractGlobalVars(source) {
5353
4681
  const htmlStore = {};
5354
4682
  let htmlIndex = 0;
5355
4683
  let lastIndex = 0;
5356
- const htmlKey = "";
4684
+ const htmlKey = String.fromCharCode(5);
5357
4685
  template.replace(
5358
4686
  templateCmdRegExp,
5359
4687
  (match, operate, content, offset) => {
@@ -5657,7 +4985,6 @@ export {
5657
4985
  Framework,
5658
4986
  LARK_VIEW,
5659
4987
  Payload,
5660
- Platform,
5661
4988
  RouterEvents as ROUTER_EVENTS,
5662
4989
  Router,
5663
4990
  SPLITTER,
@@ -5671,16 +4998,13 @@ export {
5671
4998
  applyStyle,
5672
4999
  applyVdomOps,
5673
5000
  assign,
5674
- cell,
5675
- cloneData,
5676
- cloneStore,
5001
+ bindStore,
5677
5002
  compileTemplate,
5678
5003
  computed,
5679
- createState,
5004
+ create,
5680
5005
  createVdomRef,
5681
5006
  defineStore,
5682
5007
  defineView,
5683
- delStore,
5684
5008
  encodeHTML,
5685
5009
  encodeQ,
5686
5010
  encodeSafe,
@@ -5692,43 +5016,34 @@ export {
5692
5016
  generateId,
5693
5017
  getAttribute,
5694
5018
  getById,
5695
- getPlatform,
5696
- getStore,
5697
- getUseStore,
5019
+ getRouteMode,
5698
5020
  hasOwnProperty,
5699
5021
  installFrameVisualizerBridge,
5700
5022
  invalidateViewClass,
5701
5023
  isPlainObject,
5702
5024
  isPrimitive,
5703
5025
  isPrimitiveOrFunc,
5704
- isState,
5705
- isStoreActive,
5706
5026
  keys,
5707
- lazySet,
5708
5027
  mark,
5709
5028
  markBooted,
5710
5029
  markRouterBooted,
5711
- multi,
5712
5030
  nextCounter,
5713
5031
  nodeInside,
5714
5032
  noop,
5715
5033
  now,
5716
- observeCell,
5717
5034
  parseUri,
5718
5035
  registerViewClass,
5719
5036
  resetProjectsMap,
5720
5037
  safeguard,
5721
5038
  serializeFrameTree,
5722
5039
  setData,
5723
- shallowSet,
5724
- mark2 as storeMark,
5725
- unmark2 as storeUnmark,
5726
5040
  syncCounter,
5727
5041
  toMap,
5728
5042
  toUri,
5729
5043
  translateData,
5730
5044
  unmark,
5731
5045
  use,
5046
+ useUrlState,
5732
5047
  vdomGetCompareKey,
5733
5048
  vdomGetNode,
5734
5049
  vdomSetAttributes,