Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
fantasticsoul committed Dec 15, 2023
1 parent 07ced69 commit 895ecee
Show file tree
Hide file tree
Showing 37 changed files with 231 additions and 226 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

# helux 简介

[helux](https://github.com/heluxjs/helux) 是一个集`atom``signal``依赖收集``派生``观察`为一体,支持细粒度响应式更新的 react 状态库,支持所有类react框架(包括react 18)
[helux](https://github.com/heluxjs/helux) 是一个集`atom``signal``依赖收集``派生``观察`为一体,支持细粒度响应式更新的 react 状态库,支持所有类 react 框架(包括 react 18)

特性简介:

- 基于最快的不可变 js 库[limu](https://github.com/tnfe/limu)开发,拥有超强性能
- atom 支持依赖收集,意味着 atom 不用拆分的很细,atom 就可以等同于 model,天然对 `DDD` 领域驱动设计友好
- 内置 signal 响应机制,可实现 0 hook 编码 + dom 粒度的更新
Expand Down
20 changes: 16 additions & 4 deletions packages/helux-core/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,26 @@ import { mutate, mutateDict, runMutate, runMutateTask } from './factory/createMu
import { atom, atomx, share, sharex } from './factory/createShared';
import { sync, syncer } from './factory/createSync';
import { watch } from './factory/createWatch';
import { flush, reactiveDesc } from './factory/creator/reactive';
import { currentDraftRoot, setAtomVal } from './factory/creator/current';
import { flush, reactiveDesc } from './factory/creator/reactive';
import { getDeriveLoading, runDerive, runDeriveTask } from './helpers/fnRunner';
import { getRawState, getSnap } from './helpers/state';
import {
useAtom, useAtomForceUpdate, useDerived, useGlobalId, useLocalForceUpdate,
getActionLoading, getMutateLoading, useActionLoading, useMutateLoading,
useMutable, useOnEvent, useReactive, useService, storeSrv, useWatch,
getActionLoading,
getMutateLoading,
storeSrv,
useActionLoading,
useAtom,
useAtomForceUpdate,
useDerived,
useGlobalId,
useLocalForceUpdate,
useMutable,
useMutateLoading,
useOnEvent,
useReactive,
useService,
useWatch,
} from './hooks';
import { block, dynamicBlock, signal } from './signal';

Expand Down
11 changes: 5 additions & 6 deletions packages/helux-core/src/consts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const FROM = {
* 来自 top setState(draft)、ins setState(draft) 的读写
* ```ts
* const [, setState] = atom({a:1});
*
*
* const [, setState] = useAtom();
* ```
*/
Expand Down Expand Up @@ -120,11 +120,11 @@ export const FROM = {
* mutate({
* task: async({ draft }){ },
* });
*
*
* action(async ({ draft })=>{ });
*
*
* const [,,{ reactive }] = atom({a:1});
*
*
* const [ reactive ] = useReactive(someAtom);
* ```
*/
Expand All @@ -138,11 +138,10 @@ export const FROM = {
* ```ts
* import { sync } from 'helux';
* sync(someState)(to=>to.a.b);
*
*
* const [,,{ sync }] = atom({a:1});
* sync(to=>to.a.b);
* ```
*/
SYNC: 'Sync',
} as const;

2 changes: 1 addition & 1 deletion packages/helux-core/src/factory/common/check.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { tryAlert } from '@helux/utils';
import { getInternal, getInternalByKey } from '../../helpers/state';
import { REACTIVE_META_KEY } from '../../consts';
import { getInternal, getInternalByKey } from '../../helpers/state';
import type { SharedState } from '../../types/base';
import type { IReactiveMeta } from '../../types/inner';
import type { TInternal } from '../creator/buildInternal';
Expand Down
2 changes: 1 addition & 1 deletion packages/helux-core/src/factory/common/derived.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { limuUtils } from 'limu';
import { dedupList, enureReturnArr, isFn, isObj, isPromise, nodupPush, noop, tryAlert, warn } from '@helux/utils';
import { limuUtils } from 'limu';
import { ASYNC_TYPE, DERIVE, IS_DERIVED_ATOM, SCOPE_TYPE } from '../../consts';
import { recordBlockDepKey } from '../../helpers/blockDep';
import { markFnEnd, markFnStart, registerFn, shouldShowComputing } from '../../helpers/fnCtx';
Expand Down
2 changes: 1 addition & 1 deletion packages/helux-core/src/factory/common/key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,6 @@ export function genFnKey(keyType: ScopeType | 'Mutate' | 'Reactive') {
return `${prefix}${keySeed}`;
}

export function getReactiveKey(){
export function getReactiveKey() {
return genFnKey('Reactive');
}
6 changes: 3 additions & 3 deletions packages/helux-core/src/factory/common/util.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { getVal, isDebug, isFn, isMap, isObj, isProxyAvailable, noop, prefixValKey } from '@helux/utils';
import { immut, IOperateParams, limuUtils } from 'limu';
import { ARR, KEY_SPLITER, MAP, STATE_TYPE, FROM } from '../../consts';
import { ARR, FROM, KEY_SPLITER, MAP, STATE_TYPE } from '../../consts';
import { createOb } from '../../helpers/obj';
import type { IMutateCtx, Dict, IInnerSetStateOptions } from '../../types/base';
import type { Dict, IInnerSetStateOptions, IMutateCtx } from '../../types/base';
import { DepKeyInfo } from '../../types/inner';
import type { TInternal } from '../creator/buildInternal';

Expand Down Expand Up @@ -53,7 +53,7 @@ export function newMutateCtx(options: IInnerSetStateOptions): IMutateCtx {
export function newOpParams(
key: string,
value: any,
options: { isChanged?: boolean, parentKeyPath: string[], op?: any, parentType?: any }
options: { isChanged?: boolean; parentKeyPath: string[]; op?: any; parentType?: any },
): IOperateParams {
const { isChanged = true, parentKeyPath = [], op = 'set', parentType = 'Object' } = options;
const fullKeyPath = parentKeyPath.slice();
Expand Down
12 changes: 6 additions & 6 deletions packages/helux-core/src/factory/createShared.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { noop } from '@helux/utils';
import { FROM, STATE_TYPE } from '../consts';
import { runDerive, runDeriveTask } from '../helpers/fnRunner';
import { useAtom, useDerived, useReactive, useMutable, useAtomForceUpdate, useLocalForceUpdate } from '../hooks';
import { useAtom, useAtomForceUpdate, useDerived, useLocalForceUpdate, useMutable, useReactive } from '../hooks';
import type { CoreApiCtx } from '../types/api-ctx';
import type { Dict, Fn, IAtomCtx, ICreateOptions, IRunMutateOptions, ISharedCtx } from '../types/base';
import { action } from './createAction';
import { derive } from './createDerived';
import { mutate, mutateDict, runMutate, runMutateTask } from './createMutate';
import { buildSharedObject } from './creator';
import type { TInternal } from './creator/buildInternal';
import { flush, reactiveDesc } from './creator/reactive';
import { setAtomVal } from './creator/current';
import { getGlobalEmpty, initGlobalEmpty } from './creator/globalId';
import { getLoadingInfo, initGlobalLoading, initLoadingCtx } from './creator/loading';
import type { IInnerOptions } from './creator/parse';
import { flush, reactiveDesc } from './creator/reactive';

const { USER_STATE } = STATE_TYPE;
const { MUTATE, ACTION } = FROM;
Expand Down Expand Up @@ -44,7 +44,7 @@ function defineActions(
};
}

function defineMutate(options: { state: any, ldMutate: Dict; mutateFnDict: Dict }) {
function defineMutate(options: { state: any; ldMutate: Dict; mutateFnDict: Dict }) {
const { state, ldMutate, mutateFnDict } = options;
const witnessDict = mutateDict(state)(mutateFnDict);
return {
Expand Down Expand Up @@ -98,10 +98,11 @@ export function createSharedLogic(innerOptions: IInnerOptions, createOptions?: a
const common = { createFn, internal, apiCtx };

return {
state, // 指向 root
state, // 指向 root
stateVal, // atom 的话 stateVal 是拆箱后的值,share 对象的话,stateVal 指向 root 自身
setState,
defineActions: (throwErr?: boolean) => (actionDict: Dict) => defineActions({ ...common, ldAction, actionCreator, actionDict }, throwErr),
defineActions: (throwErr?: boolean) => (actionDict: Dict) =>
defineActions({ ...common, ldAction, actionCreator, actionDict }, throwErr),
defineMutateDerive: (inital: Dict, mutateFnDict: Dict) => defineMutateDerive({ ...common, ldMutate, inital, mutateFnDict }),
defineMutateSelf: (mutateFnDict: Dict) => defineMutate({ ldMutate, state, mutateFnDict }),
defineFullDerive: (throwErr?: boolean) => (deriveFnDict: Dict) => defineFullDerive({ apiCtx, deriveFnDict, throwErr }),
Expand Down Expand Up @@ -134,7 +135,6 @@ export function createSharedLogic(innerOptions: IInnerOptions, createOptions?: a
};
}


/** expose share ctx as tuple */
export function share<T = Dict, O extends ICreateOptions<T> = ICreateOptions<T>>(apiCtx: CoreApiCtx, rawState: T | (() => T), options?: O) {
const ctx = createSharedLogic({ apiCtx, rawState }, options) as ISharedCtx<T>;
Expand Down
2 changes: 1 addition & 1 deletion packages/helux-core/src/factory/creator/buildInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import type {
Dict,
Ext,
IInsCtx,
SetStateFactory,
InnerSetState,
IRuleConf,
KeyInsKeysDict,
NumStrSymbol,
SetState,
SetStateFactory,
SharedState,
} from '../../types/base';
import type { Level1ArrKeys } from '../../types/inner';
Expand Down
61 changes: 32 additions & 29 deletions packages/helux-core/src/factory/creator/buildShared.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { canUseDeep, prefixValKey, warn } from '@helux/utils';
import { canUseDeep, warn } from '@helux/utils';
import type { IOperateParams } from 'limu';
import { immut } from 'limu';
import { IS_ATOM, KEY_SPLITER, SHARED_KEY, OP_KEYS } from '../../consts';
import { IS_ATOM, OP_KEYS, SHARED_KEY } from '../../consts';
import { recordBlockDepKey } from '../../helpers/blockDep';
import { recordFnDepKeys } from '../../helpers/fnDep';
import { createOb } from '../../helpers/obj';
import { mapSharedState } from '../../helpers/state';
import type { Dict } from '../../types/base';
import { recordLastest } from '../common/blockScope';
import { callOnRead, newOpParams, isDict, getDepKeyByPath } from '../common/util';
import { callOnRead, getDepKeyByPath, isDict, newOpParams } from '../common/util';
import type { ParsedOptions } from './parse';

function cannotSet() {
Expand Down Expand Up @@ -64,39 +64,42 @@ export function buildSharedState(options: ParsedOptions) {
});
} else {
// TODO 这段逻辑迁移到 helux-mini
const toShallowProxy = (obj: any, keyLevel: number, parentKeyPath: string[]): any => createOb(obj, {
set: cannotSet,
get: (target: Dict, key: any) => {
const value = target[key];
if (OP_KEYS.includes(key)) {
return handleHeluxKey(keyLevel === 1, forAtom, sharedKey, key, value);
}
const opParams = newOpParams(key, value, { isChanged: false, parentKeyPath });
// 为 {} 字典的 atom.val 再包一层监听
if (keyLevel < stopDepth && isDict(value)) {
return toShallowProxy(value, keyLevel + 1, opParams.fullKeyPath);
}
const toShallowProxy = (obj: any, keyLevel: number, parentKeyPath: string[]): any =>
createOb(obj, {
set: cannotSet,
get: (target: Dict, key: any) => {
const value = target[key];
if (OP_KEYS.includes(key)) {
return handleHeluxKey(keyLevel === 1, forAtom, sharedKey, key, value);
}
const opParams = newOpParams(key, value, { isChanged: false, parentKeyPath });
// 为 {} 字典的 atom.val 再包一层监听
if (keyLevel < stopDepth && isDict(value)) {
return toShallowProxy(value, keyLevel + 1, opParams.fullKeyPath);
}

const rawVal = callOnRead(opParams, onRead);
collectDep(opParams.fullKeyPath, rawVal);
return rawVal;
},
});
const rawVal = callOnRead(opParams, onRead);
collectDep(opParams.fullKeyPath, rawVal);
return rawVal;
},
});

sharedRoot = toShallowProxy(rawState, 1, []);
}

let sharedState = sharedRoot;
if (forAtom) {
sharedState = isPrimitive ? rawState.val : new Proxy(rawState, {
set: cannotSet,
get: (t: any, k: any) => {
// TODO FIXME 修复 k 传递 val 的问题
// 从 sharedRoot 去获取
const v = sharedRoot.val[k];
return v;
},
});
sharedState = isPrimitive
? rawState.val
: new Proxy(rawState, {
set: cannotSet,
get: (t: any, k: any) => {
// TODO FIXME 修复 k 传递 val 的问题
// 从 sharedRoot 去获取
const v = sharedRoot.val[k];
return v;
},
});
}

mapSharedState(sharedKey, sharedRoot);
Expand Down
2 changes: 1 addition & 1 deletion packages/helux-core/src/factory/creator/commitState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Dict, IMutateCtx, IInnerSetStateOptions } from '../../types/base';
import type { Dict, IInnerSetStateOptions, IMutateCtx } from '../../types/base';
import type { TInternal } from './buildInternal';
import { execDepFns } from './notify';

Expand Down
15 changes: 7 additions & 8 deletions packages/helux-core/src/factory/creator/current.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { noop } from '@helux/utils';
import type { InsCtxDef } from '../../factory/creator/buildInternal';
import type { IReactiveMeta } from '../../types/inner';
import type { Fn } from '../../types/base';
import { fakeReativeMeta, fakeMutateCtx, fakeDraftRoot } from './fake';
import type { IReactiveMeta } from '../../types/inner';
import { fakeDraftRoot, fakeMutateCtx, fakeReativeMeta } from './fake';

/** 正在执行中的 rootDrft */
let CURRENT_DRAFT_ROOT = fakeDraftRoot;
Expand Down Expand Up @@ -38,8 +38,8 @@ export function currentDraftRoot() {

export const DEPS_CB = {
current: () => CURRENT_DEPS_CB,
set: (cb: Fn) => CURRENT_DEPS_CB = cb,
del: () => CURRENT_DEPS_CB = noop,
set: (cb: Fn) => (CURRENT_DEPS_CB = cb),
del: () => (CURRENT_DEPS_CB = noop),
};

export const REACTIVE_DESC = {
Expand All @@ -48,18 +48,17 @@ export const REACTIVE_DESC = {
del: (key: number) => CURRENT_REACTIVE_DESC.delete(key),
};


/** 记录、删除、读取 mutate fn 收集到的依赖,watchAndCallMutateDict 逻辑里需要读取 */
export const FN_DEP_KEYS = {
current: () => CURRENT_FN_DEPS,
set: (val: string[]) => CURRENT_FN_DEPS = val,
del: () => CURRENT_FN_DEPS = [],
set: (val: string[]) => (CURRENT_FN_DEPS = val),
del: () => (CURRENT_FN_DEPS = []),
};

/** 记录、获取执行写操作的 draft 对象元数据 */
export const REACTIVE_META = {
current: () => CURRENT_REACTIVE_META.get(CURRENT_CB_REACTIVE_KEY) || fakeReativeMeta,
markUsing: (key: string) => CURRENT_CB_REACTIVE_KEY = key,
markUsing: (key: string) => (CURRENT_CB_REACTIVE_KEY = key),
set: (key: string, obj: IReactiveMeta) => CURRENT_REACTIVE_META.set(key, obj),
del: (key: string) => CURRENT_REACTIVE_META.delete(key),
};
Expand Down
19 changes: 12 additions & 7 deletions packages/helux-core/src/factory/creator/deadCycle.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/**
* 本模块用于辅助处理 mutate 函数可能遇到的死循环问题
*/
import { nodupPush, safeMapGet, tryAlert, includeOne, noop } from '@helux/utils';
import { includeOne, nodupPush, noop, safeMapGet, tryAlert } from '@helux/utils';
import { fmtDepKeys } from '../../helpers/debug';
import type { IFnCtx } from '../../types/base';
import { TInternal } from './buildInternal';
import { fmtDepKeys } from '../../helpers/debug';

type Log = { sn: number; descs: string[]; timer: any; errs: any[]; cycle: string[] };
const logMap = new Map<string, Log>();
Expand All @@ -16,7 +16,7 @@ const cbTips = {
[cbTypes.WATCH]: 'watch',
[cbTypes.MUTATE]: 'mutate fn or task',
};
type CbType = typeof cbTypes[keyof typeof cbTypes];
type CbType = (typeof cbTypes)[keyof typeof cbTypes];

function newLog(sn = 0): Log {
return { sn, descs: [], errs: [], timer: null, cycle: [] };
Expand All @@ -41,9 +41,10 @@ export function depKeyDcError(internal: TInternal, fnCtx: IFnCtx, depKeys: strin
const tip = cbTips[cbType];
const { desc, task, fn } = fnCtx.subFnInfo;
const descStr = desc ? `(${desc})` : '';
const dcInfo = `DEAD_CYCLE: found reactive object in ${tip}${descStr} cb`
const dcInfo =
`DEAD_CYCLE: found reactive object in ${tip}${descStr} cb`
+ ` is changing module(${internal.usefulName})'s keys(${fmtDepKeys(depKeys, false, '.')}) by its self, `
+ 'but some of these keys are also the watched dep keys, it will cause a infinity loop call!'
+ 'but some of these keys are also the watched dep keys, it will cause a infinity loop call!';

const mutateFn = task || fn;
const targetFn = mutateFn === noop ? fnCtx.fn : mutateFn;
Expand Down Expand Up @@ -80,7 +81,7 @@ export function probeFnDeadCycle(internal: TInternal, sn: number, desc: string)
}

/**
* 发现类似
* 发现类似
* 1 watch(()=>{ reactive.a = 1 }, ()=>[reactive.a])
* 2 matate(draft=>draft+=1)
* 等场景的死循环
Expand All @@ -97,7 +98,11 @@ export function probeDepKeyDeadCycle(internal: TInternal, fnCtx: IFnCtx, changed
const foundDc = includeOne(shortArr, longArr);
if (foundDc) {
const cbType: CbType = subFnInfo.desc ? cbTypes.MUTATE : cbTypes.WATCH;
tryAlert(depKeyDcError(internal, fnCtx, changedDepKeys, cbType), { logErr: false, throwErr: false, alertErr: internal.alertDeadCycleErr });
tryAlert(depKeyDcError(internal, fnCtx, changedDepKeys, cbType), {
logErr: false,
throwErr: false,
alertErr: internal.alertDeadCycleErr,
});
}
return foundDc;
}
Expand Down
Loading

0 comments on commit 895ecee

Please sign in to comment.