From 06e73eb13170bcf2b5ef60dd107c4affeaaa4ab0 Mon Sep 17 00:00:00 2001 From: * <8> Date: Tue, 25 Oct 2022 17:51:56 +0800 Subject: [PATCH 1/2] Match-id-293b5d8b9c2678e17d9ccda1aeae0b5e13d2396e --- libs/horizon/src/dom/valueHandler/SelectValueHandler.ts | 2 +- libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts | 2 +- libs/horizon/src/horizonx/adapters/reduxReact.ts | 2 +- libs/horizon/src/horizonx/proxy/Observer.ts | 2 +- .../horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts | 4 ++-- libs/horizon/src/renderer/ErrorHandler.ts | 2 +- libs/horizon/src/renderer/components/CreatePortal.ts | 2 +- libs/horizon/src/renderer/components/context/Context.ts | 2 +- libs/horizon/src/renderer/hooks/HookExternal.ts | 2 +- libs/horizon/src/renderer/hooks/UseEffectHook.ts | 2 +- libs/horizon/src/renderer/hooks/UseMemoHook.ts | 2 +- libs/horizon/src/renderer/hooks/UseReducerHook.ts | 2 +- libs/horizon/src/renderer/submit/HookEffectHandler.ts | 2 +- libs/horizon/src/renderer/submit/LifeCycleHandler.ts | 2 +- libs/horizon/src/renderer/submit/Submit.ts | 2 +- libs/horizon/src/renderer/vnode/VNodeCreator.ts | 2 +- package.json | 3 ++- 17 files changed, 19 insertions(+), 18 deletions(-) diff --git a/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts b/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts index ed78b5c9..ba9a4716 100644 --- a/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts @@ -61,7 +61,7 @@ export function getSelectPropsWithoutValue(dom: HorizonSelect, properties: Objec }; } -export function updateSelectValue(dom: HorizonSelect, props: Props, isInit: boolean = false) { +export function updateSelectValue(dom: HorizonSelect, props: Props, isInit = false) { const {value, defaultValue, multiple} = props; const oldMultiple = dom._multiple !== undefined ? dom._multiple : dom.multiple; diff --git a/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts b/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts index 595fd663..ea344f23 100644 --- a/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts @@ -45,7 +45,7 @@ export function getTextareaPropsWithoutValue(dom: HTMLTextAreaElement, propertie }; } -export function updateTextareaValue(dom: HTMLTextAreaElement, props: Props, isInit: boolean = false) { +export function updateTextareaValue(dom: HTMLTextAreaElement, props: Props, isInit = false) { if (isInit) { const initValue = getInitValue(props); if (initValue !== '') { diff --git a/libs/horizon/src/horizonx/adapters/reduxReact.ts b/libs/horizon/src/horizonx/adapters/reduxReact.ts index 4b1ff6e6..58321399 100644 --- a/libs/horizon/src/horizonx/adapters/reduxReact.ts +++ b/libs/horizon/src/horizonx/adapters/reduxReact.ts @@ -19,7 +19,7 @@ import { createContext } from '../../renderer/components/context/CreateContext'; import { createElement } from '../../external/JSXElement'; import { BoundActionCreator } from './redux'; import { ReduxAction } from './redux'; -import { ReduxStoreHandler } from '../store/StoreHandler' +import { ReduxStoreHandler } from '../store/StoreHandler'; const DefaultContext = createContext(null); type Context = typeof DefaultContext; diff --git a/libs/horizon/src/horizonx/proxy/Observer.ts b/libs/horizon/src/horizonx/proxy/Observer.ts index 6a2216db..950c16c6 100644 --- a/libs/horizon/src/horizonx/proxy/Observer.ts +++ b/libs/horizon/src/horizonx/proxy/Observer.ts @@ -109,7 +109,7 @@ export class Observer implements IObserver { } allChange(): void { - let keyIt = this.keyVNodes.keys(); + const keyIt = this.keyVNodes.keys(); let keyItem = keyIt.next(); while (!keyItem.done) { this.setProp(keyItem.value); diff --git a/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts b/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts index ac871e90..6074b28b 100644 --- a/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts +++ b/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts @@ -42,8 +42,8 @@ export function get(rawObj: object, key: string | symbol, receiver: any, singleL observer.watchers[prop].push(handler); return ()=>{ observer.watchers[prop]=observer.watchers[prop].filter(cb=>cb!==handler); - } - } + }; + }; } if (key === 'addListener') { diff --git a/libs/horizon/src/renderer/ErrorHandler.ts b/libs/horizon/src/renderer/ErrorHandler.ts index 34461b14..10ec83f3 100644 --- a/libs/horizon/src/renderer/ErrorHandler.ts +++ b/libs/horizon/src/renderer/ErrorHandler.ts @@ -78,7 +78,7 @@ function createClassErrorUpdate( return update; } function isPromise(error: any): error is PromiseType { - return error !== null && typeof error === 'object' && typeof error.then === 'function' + return error !== null && typeof error === 'object' && typeof error.then === 'function'; } // 处理capture和bubble阶段抛出的错误 export function handleRenderThrowError( diff --git a/libs/horizon/src/renderer/components/CreatePortal.ts b/libs/horizon/src/renderer/components/CreatePortal.ts index 767bb21e..f477d528 100644 --- a/libs/horizon/src/renderer/components/CreatePortal.ts +++ b/libs/horizon/src/renderer/components/CreatePortal.ts @@ -19,7 +19,7 @@ import type {PortalType} from '../Types'; export function createPortal( children: any, realNode: any, - key: string = '', + key = '', ): PortalType { return { vtype: TYPE_PORTAL, diff --git a/libs/horizon/src/renderer/components/context/Context.ts b/libs/horizon/src/renderer/components/context/Context.ts index 4c1242af..c1899b9c 100644 --- a/libs/horizon/src/renderer/components/context/Context.ts +++ b/libs/horizon/src/renderer/components/context/Context.ts @@ -35,7 +35,7 @@ function collectDeps(vNode: VNode, context: ContextType) { } } -export function getNewContext(vNode: VNode, ctx: ContextType, isUseContext: boolean = false): T { +export function getNewContext(vNode: VNode, ctx: ContextType, isUseContext = false): T { // 如果来自于useContext,则需要在函数组件中调用 if (isUseContext && getHookStage() === null) { throwNotInFuncError(); diff --git a/libs/horizon/src/renderer/hooks/HookExternal.ts b/libs/horizon/src/renderer/hooks/HookExternal.ts index 45e87ef2..d869aae8 100644 --- a/libs/horizon/src/renderer/hooks/HookExternal.ts +++ b/libs/horizon/src/renderer/hooks/HookExternal.ts @@ -37,7 +37,7 @@ export function useContext( return getNewContext(processingVNode!, Context, true); } -export function useState(initialState: (() => S) | S,): [S, Dispatch>] { +export function useState(initialState: (() => S) | S): [S, Dispatch>] { return useStateImpl(initialState); } diff --git a/libs/horizon/src/renderer/hooks/UseEffectHook.ts b/libs/horizon/src/renderer/hooks/UseEffectHook.ts index 7e57a5cf..e44f0f6c 100644 --- a/libs/horizon/src/renderer/hooks/UseEffectHook.ts +++ b/libs/horizon/src/renderer/hooks/UseEffectHook.ts @@ -26,7 +26,7 @@ import {getHookStage, HookStage} from './HookStage'; import {isArrayEqual} from '../utils/compare'; import {getProcessingVNode} from '../GlobalVar'; -export function useEffectImpl(effectFunc: () => (() => void) | void, deps?: Array | null,): void { +export function useEffectImpl(effectFunc: () => (() => void) | void, deps?: Array | null): void { // 异步触发的effect useEffect(effectFunc, deps, EffectConstant.Effect); } diff --git a/libs/horizon/src/renderer/hooks/UseMemoHook.ts b/libs/horizon/src/renderer/hooks/UseMemoHook.ts index 9a4a8a19..db12d545 100644 --- a/libs/horizon/src/renderer/hooks/UseMemoHook.ts +++ b/libs/horizon/src/renderer/hooks/UseMemoHook.ts @@ -21,7 +21,7 @@ import { import {getHookStage, HookStage} from './HookStage'; import {isArrayEqual} from '../utils/compare'; -export function useMemoImpl(fun: () => V, deps?: Array | null,): V { +export function useMemoImpl(fun: () => V, deps?: Array | null): V { const stage = getHookStage(); if (stage === null) { throwNotInFuncError(); diff --git a/libs/horizon/src/renderer/hooks/UseReducerHook.ts b/libs/horizon/src/renderer/hooks/UseReducerHook.ts index 39d227e1..3637f775 100644 --- a/libs/horizon/src/renderer/hooks/UseReducerHook.ts +++ b/libs/horizon/src/renderer/hooks/UseReducerHook.ts @@ -137,7 +137,7 @@ function updateReducerHookState(currentHookUpdates, currentHook, reducer): // 计算stateValue值 function calculateNewState(currentHookUpdates: Array>, currentHook, reducer: (S, A) => S) { - let reducerObj = currentHook.state; + const reducerObj = currentHook.state; let state = reducerObj.stateValue; // 循环遍历更新数组,计算新的状态值 diff --git a/libs/horizon/src/renderer/submit/HookEffectHandler.ts b/libs/horizon/src/renderer/submit/HookEffectHandler.ts index c0c31f21..88e4b1fc 100644 --- a/libs/horizon/src/renderer/submit/HookEffectHandler.ts +++ b/libs/horizon/src/renderer/submit/HookEffectHandler.ts @@ -31,7 +31,7 @@ import {EffectConstant} from '../hooks/EffectConstant'; let hookEffects: Array = []; let hookRemoveEffects: Array = []; // 是否正在异步调度effects -let isScheduling: boolean = false; +let isScheduling = false; export function setSchedulingEffects(value) { isScheduling = value; diff --git a/libs/horizon/src/renderer/submit/LifeCycleHandler.ts b/libs/horizon/src/renderer/submit/LifeCycleHandler.ts index 5a639aa7..f844b3de 100644 --- a/libs/horizon/src/renderer/submit/LifeCycleHandler.ts +++ b/libs/horizon/src/renderer/submit/LifeCycleHandler.ts @@ -172,7 +172,7 @@ function attachRef(vNode: VNode) { } function detachRef(vNode: VNode, isOldRef?: boolean) { - let ref = (isOldRef ? vNode.oldRef : vNode.ref); + const ref = (isOldRef ? vNode.oldRef : vNode.ref); handleRef(vNode, ref, null); } diff --git a/libs/horizon/src/renderer/submit/Submit.ts b/libs/horizon/src/renderer/submit/Submit.ts index ecdab322..30ec1bf9 100644 --- a/libs/horizon/src/renderer/submit/Submit.ts +++ b/libs/horizon/src/renderer/submit/Submit.ts @@ -41,7 +41,7 @@ let rootThrowError = null; // 防止死循环调用update const LOOPING_UPDATE_LIMIT = 50; -let loopingUpdateCount: number = 0; +let loopingUpdateCount = 0; let lastRoot: VNode | null = null; export function submitToRender(treeRoot) { diff --git a/libs/horizon/src/renderer/vnode/VNodeCreator.ts b/libs/horizon/src/renderer/vnode/VNodeCreator.ts index 6b96e49e..cc596c03 100644 --- a/libs/horizon/src/renderer/vnode/VNodeCreator.ts +++ b/libs/horizon/src/renderer/vnode/VNodeCreator.ts @@ -74,7 +74,7 @@ export function getLazyVNodeTag(lazyComp: any): string { } else if (lazyComp !== undefined && lazyComp !== null && typeLazyMap[lazyComp.vtype]) { return typeLazyMap[lazyComp.vtype]; } - throw Error("Horizon can't resolve the content of lazy"); + throw Error('Horizon can\'t resolve the content of lazy'); } // 创建processing diff --git a/package.json b/package.json index c939f970..c8b44fb3 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,8 @@ "libs/*" ], "scripts": { - "lint": "eslint . --ext .ts", + "lint": "eslint . --ext .ts --fix", + "prettier": "prettier -w libs/**/*.ts", "build": "rollup --config ./scripts/rollup/rollup.config.js", "build:watch": "rollup --watch --config ./scripts/rollup/rollup.config.js", "build:3rdLib": "node ./scripts/gen3rdLib.js build:3rdLib", From f645bd74307f107072486247ed284375e83309d8 Mon Sep 17 00:00:00 2001 From: * <8> Date: Tue, 25 Oct 2022 17:52:19 +0800 Subject: [PATCH 2/2] Match-id-b0371a69193797c3022489b625f16bc8b1e7669e --- libs/horizon/index.ts | 4 +- libs/horizon/src/dom/DOMInternalKeys.ts | 26 +--- libs/horizon/src/dom/DOMOperator.ts | 55 ++----- .../DOMPropertiesHandler.ts | 6 +- .../dom/DOMPropertiesHandler/StyleHandler.ts | 40 +++-- .../DOMPropertiesHandler/UpdateCommonProp.ts | 99 +++++++++--- libs/horizon/src/dom/SelectionRangeHandler.ts | 12 +- libs/horizon/src/dom/utils/Common.ts | 13 +- libs/horizon/src/dom/utils/DomCreator.ts | 6 +- .../src/dom/validators/ValidateProps.ts | 19 +-- .../src/dom/valueHandler/InputValueHandler.ts | 11 +- .../dom/valueHandler/OptionValueHandler.ts | 2 +- .../dom/valueHandler/SelectValueHandler.ts | 12 +- .../dom/valueHandler/TextareaValueHandler.ts | 8 +- .../dom/valueHandler/ValueChangeHandler.ts | 2 +- libs/horizon/src/dom/valueHandler/index.ts | 28 +--- libs/horizon/src/event/EventBinding.ts | 13 +- libs/horizon/src/event/EventWrapper.ts | 6 +- libs/horizon/src/event/FormValueController.ts | 3 +- libs/horizon/src/event/HorizonEventMain.ts | 35 +---- libs/horizon/src/event/utils.ts | 4 +- libs/horizon/src/external/JSXElement.ts | 4 +- libs/horizon/src/external/devtools.ts | 2 +- libs/horizon/src/horizonx/adapters/redux.ts | 2 +- .../src/horizonx/adapters/reduxReact.ts | 12 +- .../src/horizonx/adapters/reduxThunk.ts | 28 ++-- .../src/horizonx/proxy/HooklessObserver.ts | 17 +-- .../src/horizonx/proxy/ProxyHandler.ts | 2 +- .../proxy/handlers/ObjectProxyHandler.ts | 14 +- .../src/horizonx/proxy/readonlyProxy.ts | 2 +- libs/horizon/src/horizonx/types.d.ts | 99 ++++++------ libs/horizon/src/renderer/ErrorHandler.ts | 53 +++---- libs/horizon/src/renderer/ExecuteMode.ts | 3 +- libs/horizon/src/renderer/GlobalVar.ts | 2 +- libs/horizon/src/renderer/Renderer.ts | 22 +-- libs/horizon/src/renderer/TreeBuilder.ts | 34 ++--- libs/horizon/src/renderer/UpdateHandler.ts | 13 +- .../src/renderer/components/CreatePortal.ts | 10 +- .../src/renderer/components/CreateRef.ts | 2 +- .../src/renderer/components/ForwardRef.ts | 2 +- libs/horizon/src/renderer/components/Lazy.ts | 10 +- libs/horizon/src/renderer/components/Memo.ts | 2 +- .../renderer/components/context/Context.ts | 6 +- .../components/context/CreateContext.ts | 4 +- libs/horizon/src/renderer/diff/DiffTools.ts | 2 +- .../src/renderer/diff/nodeDiffComparator.ts | 54 +++---- libs/horizon/src/renderer/hooks/BaseHook.ts | 11 +- .../src/renderer/hooks/HookExternal.ts | 57 +++---- libs/horizon/src/renderer/hooks/HookMain.ts | 13 +- libs/horizon/src/renderer/hooks/HookType.ts | 2 +- .../src/renderer/hooks/UseCallbackHook.ts | 14 +- .../src/renderer/hooks/UseEffectHook.ts | 25 +-- .../src/renderer/hooks/UseImperativeHook.ts | 15 +- .../horizon/src/renderer/hooks/UseMemoHook.ts | 12 +- libs/horizon/src/renderer/hooks/UseRefHook.ts | 8 +- .../src/renderer/hooks/UseStateHook.ts | 4 +- .../src/renderer/render/ClassComponent.ts | 19 +-- .../src/renderer/render/ContextConsumer.ts | 5 +- .../src/renderer/render/ContextProvider.ts | 29 ++-- .../src/renderer/render/DomComponent.ts | 60 +++----- libs/horizon/src/renderer/render/DomText.ts | 21 ++- .../horizon/src/renderer/render/ForwardRef.ts | 5 +- libs/horizon/src/renderer/render/Fragment.ts | 2 +- .../src/renderer/render/FunctionComponent.ts | 27 +--- .../src/renderer/render/LazyComponent.ts | 19 +-- .../src/renderer/render/SuspenseComponent.ts | 19 +-- libs/horizon/src/renderer/render/TreeRoot.ts | 14 +- .../render/class/ClassLifeCycleProcessor.ts | 16 +- libs/horizon/src/renderer/render/index.ts | 4 +- .../src/renderer/submit/HookEffectHandler.ts | 29 ++-- .../src/renderer/submit/LifeCycleHandler.ts | 144 +++++++++--------- libs/horizon/src/renderer/submit/Submit.ts | 39 +++-- .../src/renderer/taskExecutor/BrowserAsync.ts | 5 +- .../src/renderer/taskExecutor/RenderQueue.ts | 4 +- .../src/renderer/taskExecutor/TaskExecutor.ts | 19 +-- libs/horizon/src/renderer/utils/compare.ts | 6 +- .../horizon/src/renderer/utils/throwIfTrue.ts | 2 +- libs/horizon/src/renderer/vnode/VNode.ts | 8 +- .../src/renderer/vnode/VNodeCreator.ts | 2 +- libs/horizon/src/renderer/vnode/VNodeFlags.ts | 33 ++-- .../src/renderer/vnode/VNodeShouldUpdate.ts | 7 +- libs/horizon/src/renderer/vnode/VNodeUtils.ts | 32 ++-- 82 files changed, 655 insertions(+), 881 deletions(-) diff --git a/libs/horizon/index.ts b/libs/horizon/index.ts index e715cf13..59045fbb 100644 --- a/libs/horizon/index.ts +++ b/libs/horizon/index.ts @@ -120,7 +120,7 @@ const Horizon = { isMemo, isPortal, isContextProvider, - isContextConsumer + isContextConsumer, }; export const version = __VERSION__; @@ -171,7 +171,7 @@ export { isMemo, isPortal, isContextProvider, - isContextConsumer + isContextConsumer, }; export default Horizon; diff --git a/libs/horizon/src/dom/DOMInternalKeys.ts b/libs/horizon/src/dom/DOMInternalKeys.ts index 056793ca..f3ac8089 100644 --- a/libs/horizon/src/dom/DOMInternalKeys.ts +++ b/libs/horizon/src/dom/DOMInternalKeys.ts @@ -17,17 +17,10 @@ * 文件整体功能:给dom节点赋 VNode 的结构体和事件初始化标记 */ -import type {VNode} from '../renderer/Types'; -import type { - Container, - Props, -} from './DOMOperator'; +import type { VNode } from '../renderer/Types'; +import type { Container, Props } from './DOMOperator'; -import { - DomComponent, - DomText, - TreeRoot, -} from '../renderer/vnode/VNodeTags'; +import { DomComponent, DomText, TreeRoot } from '../renderer/vnode/VNodeTags'; const INTERNAL_VNODE = '_horizon_VNode'; const INTERNAL_PROPS = '_horizon_Props'; @@ -35,7 +28,7 @@ const INTERNAL_NONDELEGATEEVENTS = '_horizon_NonDelegatedEvents'; // 通过 VNode 实例获取 DOM 节点 export function getDom(vNode: VNode): Element | Text | null { - const {tag} = vNode; + const { tag } = vNode; if (tag === DomComponent || tag === DomText) { return vNode.realNode; } @@ -43,18 +36,15 @@ export function getDom(vNode: VNode): Element | Text | null { } // 将 VNode 属性相关信息挂到 DOM 对象的特定属性上 -export function saveVNode( - vNode: VNode, - dom: Element | Text | Container, -): void { +export function saveVNode(vNode: VNode, dom: Element | Text | Container): void { dom[INTERNAL_VNODE] = vNode; } // 用 DOM 节点,来找其对应的 VNode 实例 -export function getVNode(dom: Node|Container): VNode | null { +export function getVNode(dom: Node | Container): VNode | null { const vNode = dom[INTERNAL_VNODE] || (dom as Container)._treeRoot; if (vNode) { - const {tag} = vNode; + const { tag } = vNode; if (tag === DomComponent || tag === DomText || tag === TreeRoot) { return vNode; } @@ -78,7 +68,7 @@ export function getNearestVNode(dom: Node): null | VNode { } // 获取 vNode 上的属性相关信息 -export function getVNodeProps(dom: Element | Text): Props | null{ +export function getVNodeProps(dom: Element | Text): Props | null { return dom[INTERNAL_PROPS] || null; } diff --git a/libs/horizon/src/dom/DOMOperator.ts b/libs/horizon/src/dom/DOMOperator.ts index 8e944175..ed3047b8 100644 --- a/libs/horizon/src/dom/DOMOperator.ts +++ b/libs/horizon/src/dom/DOMOperator.ts @@ -13,27 +13,15 @@ * See the Mulan PSL v2 for more details. */ -import { - saveVNode, - updateVNodeProps, -} from './DOMInternalKeys'; -import { - createDom, -} from './utils/DomCreator'; +import { saveVNode, updateVNodeProps } from './DOMInternalKeys'; +import { createDom } from './utils/DomCreator'; import { getSelectionInfo, resetSelectionRange, SelectionData } from './SelectionRangeHandler'; import { shouldAutoFocus } from './utils/Common'; import { NSS } from './utils/DomCreator'; import { adjustStyleValue } from './DOMPropertiesHandler/StyleHandler'; import type { VNode } from '../renderer/Types'; -import { - setInitValue, - getPropsWithoutValue, - updateValue, -} from './valueHandler'; -import { - compareProps, - setDomProps, -} from './DOMPropertiesHandler/DOMPropertiesHandler'; +import { setInitValue, getPropsWithoutValue, updateValue } from './valueHandler'; +import { compareProps, setDomProps } from './DOMPropertiesHandler/DOMPropertiesHandler'; import { isNativeElement, validateProps } from './validators/ValidateProps'; import { watchValueChange } from './valueHandler/ValueChangeHandler'; import { DomComponent, DomText } from '../renderer/vnode/VNodeTags'; @@ -81,12 +69,7 @@ export function resetAfterSubmit(): void { } // 创建 DOM 对象 -export function newDom( - tagName: string, - props: Props, - parentNamespace: string, - vNode: VNode, -): Element { +export function newDom(tagName: string, props: Props, parentNamespace: string, vNode: VNode): Element { const dom: Element = createDom(tagName, parentNamespace); // 将 vNode 节点挂到 DOM 对象上 saveVNode(vNode, dom); @@ -119,12 +102,7 @@ export function initDomProps(dom: Element, tagName: string, rawProps: Props): bo } // 准备更新之前进行一系列校验 DOM,寻找属性差异等准备工作 -export function getPropChangeList( - dom: Element, - type: string, - lastRawProps: Props, - nextRawProps: Props, -): Object { +export function getPropChangeList(dom: Element, type: string, lastRawProps: Props, nextRawProps: Props): Object { // 校验两个对象的不同 validateProps(type, nextRawProps); @@ -151,10 +129,7 @@ export function isTextChild(type: string, props: Props): boolean { } } -export function newTextDom( - text: string, - processing: VNode, -): Text { +export function newTextDom(text: string, processing: VNode): Text { const textNode: Text = document.createTextNode(text); saveVNode(processing, textNode); return textNode; @@ -198,26 +173,16 @@ export function clearText(dom: Element): void { } // 添加child元素 -export function appendChildElement( - parent: Element | Container, - child: Element | Text -): void { +export function appendChildElement(parent: Element | Container, child: Element | Text): void { parent.appendChild(child); } // 插入dom元素 -export function insertDomBefore( - parent: Element | Container, - child: Element | Text, - beforeChild: Element | Text, -) { +export function insertDomBefore(parent: Element | Container, child: Element | Text, beforeChild: Element | Text) { parent.insertBefore(child, beforeChild); } -export function removeChildDom( - parent: Element | Container, - child: Element | Text -) { +export function removeChildDom(parent: Element | Container, child: Element | Text) { parent.removeChild(child); } diff --git a/libs/horizon/src/dom/DOMPropertiesHandler/DOMPropertiesHandler.ts b/libs/horizon/src/dom/DOMPropertiesHandler/DOMPropertiesHandler.ts index d8e64743..a0ab84b3 100644 --- a/libs/horizon/src/dom/DOMPropertiesHandler/DOMPropertiesHandler.ts +++ b/libs/horizon/src/dom/DOMPropertiesHandler/DOMPropertiesHandler.ts @@ -81,11 +81,7 @@ export function compareProps(oldProps: Object, newProps: Object): Object { styleProp = styleProps[j]; updatesForStyle[styleProp] = ''; } - } else if ( - propName === 'autoFocus' || - propName === 'children' || - propName === 'dangerouslySetInnerHTML' - ) { + } else if (propName === 'autoFocus' || propName === 'children' || propName === 'dangerouslySetInnerHTML') { continue; } else if (isEventProp(propName)) { if (!allDelegatedHorizonEvents.has(propName)) { diff --git a/libs/horizon/src/dom/DOMPropertiesHandler/StyleHandler.ts b/libs/horizon/src/dom/DOMPropertiesHandler/StyleHandler.ts index fea7e9d2..012f438f 100644 --- a/libs/horizon/src/dom/DOMPropertiesHandler/StyleHandler.ts +++ b/libs/horizon/src/dom/DOMPropertiesHandler/StyleHandler.ts @@ -14,14 +14,16 @@ */ function isNeedUnitCSS(styleName: string) { - return !(noUnitCSS.includes(styleName) - || styleName.startsWith('borderImage') - || styleName.startsWith('flex') - || styleName.startsWith('gridRow') - || styleName.startsWith('gridColumn') - || styleName.startsWith('stroke') - || styleName.startsWith('box') - || styleName.endsWith('Opacity')); + return !( + noUnitCSS.includes(styleName) || + styleName.startsWith('borderImage') || + styleName.startsWith('flex') || + styleName.startsWith('gridRow') || + styleName.startsWith('gridColumn') || + styleName.startsWith('stroke') || + styleName.startsWith('box') || + styleName.endsWith('Opacity') + ); } /** @@ -29,7 +31,7 @@ function isNeedUnitCSS(styleName: string) { * 对空值或布尔值进行适配,转为空字符串 * 去掉多余空字符 */ - export function adjustStyleValue(name, value) { +export function adjustStyleValue(name, value) { let validValue = value; if (typeof value === 'number' && value !== 0 && isNeedUnitCSS(name)) { @@ -50,7 +52,7 @@ export function setStyles(dom, styles) { } const style = dom.style; - Object.keys(styles).forEach((name) => { + Object.keys(styles).forEach(name => { const styleVal = styles[name]; style[name] = adjustStyleValue(name, styleVal); @@ -60,5 +62,19 @@ export function setStyles(dom, styles) { /** * 不需要加长度单位的 css 属性 */ -const noUnitCSS = ['animationIterationCount', 'columnCount', 'columns', 'gridArea', 'fontWeight', 'lineClamp', - 'lineHeight', 'opacity', 'order', 'orphans', 'tabSize', 'widows', 'zIndex', 'zoom']; +const noUnitCSS = [ + 'animationIterationCount', + 'columnCount', + 'columns', + 'gridArea', + 'fontWeight', + 'lineClamp', + 'lineHeight', + 'opacity', + 'order', + 'orphans', + 'tabSize', + 'widows', + 'zIndex', + 'zoom', +]; diff --git a/libs/horizon/src/dom/DOMPropertiesHandler/UpdateCommonProp.ts b/libs/horizon/src/dom/DOMPropertiesHandler/UpdateCommonProp.ts index 7800addf..fb92ddbe 100644 --- a/libs/horizon/src/dom/DOMPropertiesHandler/UpdateCommonProp.ts +++ b/libs/horizon/src/dom/DOMPropertiesHandler/UpdateCommonProp.ts @@ -13,25 +13,77 @@ * See the Mulan PSL v2 for more details. */ -import { - getPropDetails, - PROPERTY_TYPE, -} from '../validators/PropertiesData'; -import {isInvalidValue} from '../validators/ValidateProps'; -import {getNamespaceCtx} from '../../renderer/ContextSaver'; -import {NSS} from '../utils/DomCreator'; -import {getDomTag} from '../utils/Common'; +import { getPropDetails, PROPERTY_TYPE } from '../validators/PropertiesData'; +import { isInvalidValue } from '../validators/ValidateProps'; +import { getNamespaceCtx } from '../../renderer/ContextSaver'; +import { NSS } from '../utils/DomCreator'; +import { getDomTag } from '../utils/Common'; -const svgHumpAttr = new Set(['allowReorder', 'autoReverse', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', - 'contentScriptType', 'contentStyleType', 'diffuseConstant', 'edgeMode', 'externalResourcesRequired', 'filterRes', - 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', - 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', - 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform,', - 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', - 'referrerPolicy', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', - 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', - 'stitchTiles', 'surfaceScale','systemLanguage', 'tableValues', 'targetX', 'targetY', - 'textLength','viewBox', 'viewTarget', 'xChannelSelector','yChannelSelector', 'zoomAndPan']); +const svgHumpAttr = new Set([ + 'allowReorder', + 'autoReverse', + 'baseFrequency', + 'baseProfile', + 'calcMode', + 'clipPathUnits', + 'contentScriptType', + 'contentStyleType', + 'diffuseConstant', + 'edgeMode', + 'externalResourcesRequired', + 'filterRes', + 'filterUnits', + 'glyphRef', + 'gradientTransform', + 'gradientUnits', + 'kernelMatrix', + 'kernelUnitLength', + 'keyPoints', + 'keySplines', + 'keyTimes', + 'lengthAdjust', + 'limitingConeAngle', + 'markerHeight', + 'markerUnits', + 'markerWidth', + 'maskContentUnits', + 'maskUnits', + 'numOctaves', + 'pathLength', + 'patternContentUnits', + 'patternTransform,', + 'patternUnits', + 'pointsAtX', + 'pointsAtY', + 'pointsAtZ', + 'preserveAlpha', + 'preserveAspectRatio', + 'primitiveUnits', + 'referrerPolicy', + 'refX', + 'refY', + 'repeatCount', + 'repeatDur', + 'requiredExtensions', + 'requiredFeatures', + 'specularConstant', + 'specularExponent', + 'spreadMethod', + 'startOffset', + 'stdDeviation', + 'stitchTiles', + 'surfaceScale', + 'systemLanguage', + 'tableValues', + 'targetX', + 'targetY', + 'textLength', + 'viewBox', + 'viewTarget', + 'xChannelSelector', + 'yChannelSelector', + 'zoomAndPan', +]); // 驼峰 变 “-” function convertToLowerCase(str) { @@ -65,19 +117,22 @@ export function updateCommonProp(dom: Element, attrName: string, value: any, isN dom.setAttribute(attrName, String(value)); } } else if (['checked', 'multiple', 'muted', 'selected'].includes(propDetails.attrName)) { - if (value === null) { // 必填属性设置默认值 + if (value === null) { + // 必填属性设置默认值 dom[propDetails.attrName] = false; } else { dom[propDetails.attrName] = value; } - } else { // 处理其他普通属性 + } else { + // 处理其他普通属性 if (value === null) { dom.removeAttribute(propDetails.attrName); } else { - const {type, attrNS} = propDetails; // 数据类型、固有属性命名空间 + const { type, attrNS } = propDetails; // 数据类型、固有属性命名空间 const attributeName = propDetails.attrName; // 固有属性名 let attributeValue; - if (type === PROPERTY_TYPE.BOOLEAN) { // 即可以用作标志又可以是属性值的属性 + if (type === PROPERTY_TYPE.BOOLEAN) { + // 即可以用作标志又可以是属性值的属性 attributeValue = ''; } else { attributeValue = String(value); diff --git a/libs/horizon/src/dom/SelectionRangeHandler.ts b/libs/horizon/src/dom/SelectionRangeHandler.ts index 8ed611f8..e09e0dad 100644 --- a/libs/horizon/src/dom/SelectionRangeHandler.ts +++ b/libs/horizon/src/dom/SelectionRangeHandler.ts @@ -17,9 +17,9 @@ * 处理文本框、输入框中框选范围内的数据 */ -import {getIFrameFocusedDom, isText} from './utils/Common'; +import { getIFrameFocusedDom, isText } from './utils/Common'; -import {isElement} from './utils/Common'; +import { isElement } from './utils/Common'; /** * 设置聚焦的 textarea 或 input 节点的选择范围 @@ -76,7 +76,8 @@ function isNodeContainsByTargetNode(targetNode, node) { if (typeof targetNode.contains === 'function') { return targetNode.contains(node); // 该的节点是否为目标节点的后代节点 } - if (typeof targetNode.compareDocumentPosition === 'function') { // compareDocumentPosition 数值,表示两个节点彼此做比较的位置 + if (typeof targetNode.compareDocumentPosition === 'function') { + // compareDocumentPosition 数值,表示两个节点彼此做比较的位置 const CONTAINS_CODE = 16; // 返回 16 代表 第二节点在第一节点内部 return targetNode.compareDocumentPosition(node) === CONTAINS_CODE; @@ -153,9 +154,10 @@ export function resetSelectionRange(preSelectionRangeData: SelectionData) { let ancestor = preFocusedDom.parentNode; // 查找先前的 focus 节点的先祖 while (ancestor) { - if (isElement(ancestor)) { // 是元素节点,就把先祖信息放到先祖数组中 + if (isElement(ancestor)) { + // 是元素节点,就把先祖信息放到先祖数组中 // @ts-ignore - const {scrollLeft, scrollTop} = ancestor; + const { scrollLeft, scrollTop } = ancestor; ancestors.push({ dom: ancestor, scrollLeft, diff --git a/libs/horizon/src/dom/utils/Common.ts b/libs/horizon/src/dom/utils/Common.ts index 1926f185..30c172cf 100644 --- a/libs/horizon/src/dom/utils/Common.ts +++ b/libs/horizon/src/dom/utils/Common.ts @@ -13,8 +13,8 @@ * See the Mulan PSL v2 for more details. */ -import {HorizonDom} from './Interface'; -import {Props} from '../DOMOperator'; +import { HorizonDom } from './Interface'; +import { Props } from '../DOMOperator'; /** * 获取当前聚焦的 input 或者 textarea 元素 @@ -35,12 +35,15 @@ export function getIFrameFocusedDom() { while (focusedDom instanceof currentWindow.HTMLIFrameElement) { try { // 访问 HTMLIframeElement 的 contentDocument 可能会导致浏览器抛出错误 - if (typeof focusedDom.contentWindow.location.href === 'string') { // iframe 的内容为同源 + if (typeof focusedDom.contentWindow.location.href === 'string') { + // iframe 的内容为同源 focusedDom = getFocusedDom(focusedDom.contentWindow.document); - } else { // 非同源 iframe 因为安全性原因无法获取其中的具体元素 + } else { + // 非同源 iframe 因为安全性原因无法获取其中的具体元素 break; } - } catch (e) { // 非同源 iframe 因为安全性原因无法获取其中的具体元素 + } catch (e) { + // 非同源 iframe 因为安全性原因无法获取其中的具体元素 break; } } diff --git a/libs/horizon/src/dom/utils/DomCreator.ts b/libs/horizon/src/dom/utils/DomCreator.ts index 31f30544..3eb2d1ca 100644 --- a/libs/horizon/src/dom/utils/DomCreator.ts +++ b/libs/horizon/src/dom/utils/DomCreator.ts @@ -1,4 +1,3 @@ - /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * @@ -21,10 +20,7 @@ export const NSS = { }; // 创建DOM元素 -export function createDom( - tagName: string, - parentNamespace: string, -): Element { +export function createDom(tagName: string, parentNamespace: string): Element { let dom: Element; const selfNamespace = NSS[tagName] || NSS.html; const ns = parentNamespace !== NSS.html ? parentNamespace : selfNamespace; diff --git a/libs/horizon/src/dom/validators/ValidateProps.ts b/libs/horizon/src/dom/validators/ValidateProps.ts index 48de7df2..d6629b29 100644 --- a/libs/horizon/src/dom/validators/ValidateProps.ts +++ b/libs/horizon/src/dom/validators/ValidateProps.ts @@ -13,23 +13,16 @@ * See the Mulan PSL v2 for more details. */ -import { - getPropDetails, PROPERTY_TYPE, PropDetails, -} from './PropertiesData'; +import { getPropDetails, PROPERTY_TYPE, PropDetails } from './PropertiesData'; const INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; - // 是内置元素 export function isNativeElement(tagName: string, props: Record) { return !tagName.includes('-') && props.is === undefined; } -function isInvalidBoolean( - attributeName: string, - value: any, - propDetails: PropDetails, -): boolean { +function isInvalidBoolean(attributeName: string, value: any, propDetails: PropDetails): boolean { if (propDetails.type === PROPERTY_TYPE.SPECIAL) { return false; } @@ -78,7 +71,7 @@ export function isInvalidValue( name: string, value: any, propDetails: PropDetails | null, - isNativeTag: boolean, + isNativeTag: boolean ): boolean { if (value == null) { return true; @@ -122,11 +115,7 @@ export function validateProps(type, props) { const propString = invalidProps.map(prop => '`' + prop + '`').join(', '); if (invalidProps.length >= 1) { - console.error( - 'Invalid value for prop %s on <%s> tag.', - propString, - type, - ); + console.error('Invalid value for prop %s on <%s> tag.', propString, type); } } } diff --git a/libs/horizon/src/dom/valueHandler/InputValueHandler.ts b/libs/horizon/src/dom/valueHandler/InputValueHandler.ts index ee374e43..824d57dd 100644 --- a/libs/horizon/src/dom/valueHandler/InputValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/InputValueHandler.ts @@ -28,7 +28,7 @@ function getInitValue(dom: HTMLInputElement, props: Props) { export function getInputPropsWithoutValue(dom: HTMLInputElement, props: Props) { // checked属于必填属性,无法置 - let {checked} = props; + let { checked } = props; if (checked == null) { checked = getInitValue(dom, props).initChecked; } @@ -43,9 +43,10 @@ export function getInputPropsWithoutValue(dom: HTMLInputElement, props: Props) { } export function updateInputValue(dom: HTMLInputElement, props: Props) { - const {value, checked} = props; + const { value, checked } = props; - if (value != null) { // 处理 dom.value 逻辑 + if (value != null) { + // 处理 dom.value 逻辑 if (dom.value !== String(value)) { dom.value = String(value); } @@ -56,8 +57,8 @@ export function updateInputValue(dom: HTMLInputElement, props: Props) { // 设置input的初始值 export function setInitInputValue(dom: HTMLInputElement, props: Props) { - const {value, defaultValue} = props; - const {initValue, initChecked} = getInitValue(dom, props); + const { value, defaultValue } = props; + const { initValue, initChecked } = getInitValue(dom, props); if (value != null || defaultValue != null) { // value 的使用优先级 value 属性 > defaultValue 属性 > 空字符串 diff --git a/libs/horizon/src/dom/valueHandler/OptionValueHandler.ts b/libs/horizon/src/dom/valueHandler/OptionValueHandler.ts index 89f33bc7..d1c8022a 100644 --- a/libs/horizon/src/dom/valueHandler/OptionValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/OptionValueHandler.ts @@ -19,7 +19,7 @@ import { Props } from '../utils/Interface'; // 把 const a = 'a'; 转成 giraffe function concatChildren(children) { let content = ''; - Children.forEach(children, function(child) { + Children.forEach(children, function (child) { content += child; }); diff --git a/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts b/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts index ba9a4716..fb9f859e 100644 --- a/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/SelectValueHandler.ts @@ -13,12 +13,12 @@ * See the Mulan PSL v2 for more details. */ -import {HorizonSelect, Props} from '../utils/Interface'; +import { HorizonSelect, Props } from '../utils/Interface'; function updateMultipleValue(options, newValues) { const newValueSet = new Set(); - newValues.forEach((val) => { + newValues.forEach(val => { newValueSet.add(String(val)); }); @@ -62,7 +62,7 @@ export function getSelectPropsWithoutValue(dom: HorizonSelect, properties: Objec } export function updateSelectValue(dom: HorizonSelect, props: Props, isInit = false) { - const {value, defaultValue, multiple} = props; + const { value, defaultValue, multiple } = props; const oldMultiple = dom._multiple !== undefined ? dom._multiple : dom.multiple; const newMultiple = Boolean(multiple); @@ -71,7 +71,8 @@ export function updateSelectValue(dom: HorizonSelect, props: Props, isInit = fal // 设置了 value 属性 if (value != null) { updateValue(dom.options, value, newMultiple); - } else if (oldMultiple !== newMultiple) { // 修改了 multiple 属性 + } else if (oldMultiple !== newMultiple) { + // 修改了 multiple 属性 // 切换 multiple 之后,如果设置了 defaultValue 需要重新应用 if (defaultValue != null) { updateValue(dom.options, defaultValue, newMultiple); @@ -79,7 +80,8 @@ export function updateSelectValue(dom: HorizonSelect, props: Props, isInit = fal // 恢复到未选定状态 updateValue(dom.options, newMultiple ? [] : '', newMultiple); } - } else if (isInit && defaultValue != null) { // 设置了 defaultValue 属性 + } else if (isInit && defaultValue != null) { + // 设置了 defaultValue 属性 updateValue(dom.options, defaultValue, newMultiple); } } diff --git a/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts b/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts index ea344f23..82b2203e 100644 --- a/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts +++ b/libs/horizon/src/dom/valueHandler/TextareaValueHandler.ts @@ -13,15 +13,14 @@ * See the Mulan PSL v2 for more details. */ -import {Props} from '../utils/Interface'; - +import { Props } from '../utils/Interface'; // 值的优先级 value > children > defaultValue function getInitValue(props: Props) { - const {value} = props; + const { value } = props; if (value == null) { - const {defaultValue, children} = props; + const { defaultValue, children } = props; let initValue = defaultValue; // children content存在时,会覆盖defaultValue @@ -63,4 +62,3 @@ export function updateTextareaValue(dom: HTMLTextAreaElement, props: Props, isIn } } } - diff --git a/libs/horizon/src/dom/valueHandler/ValueChangeHandler.ts b/libs/horizon/src/dom/valueHandler/ValueChangeHandler.ts index d95c2be5..d1c39fd8 100644 --- a/libs/horizon/src/dom/valueHandler/ValueChangeHandler.ts +++ b/libs/horizon/src/dom/valueHandler/ValueChangeHandler.ts @@ -52,7 +52,7 @@ export function watchValueChange(dom) { const setFunc = descriptor?.set; Object.defineProperty(dom, keyForValue, { ...descriptor, - set: function(value) { + set: function (value) { currentVal = String(value); setFunc?.apply(this, [value]); }, diff --git a/libs/horizon/src/dom/valueHandler/index.ts b/libs/horizon/src/dom/valueHandler/index.ts index 828190e0..6e96281a 100644 --- a/libs/horizon/src/dom/valueHandler/index.ts +++ b/libs/horizon/src/dom/valueHandler/index.ts @@ -18,23 +18,11 @@ * 处理组件被代理和不被代理情况下的不同逻辑 */ -import {HorizonDom, HorizonSelect, Props} from '../utils/Interface'; -import { - getInputPropsWithoutValue, - setInitInputValue, - updateInputValue, -} from './InputValueHandler'; -import { - getOptionPropsWithoutValue, -} from './OptionValueHandler'; -import { - getSelectPropsWithoutValue, - updateSelectValue, -} from './SelectValueHandler'; -import { - getTextareaPropsWithoutValue, - updateTextareaValue, -} from './TextareaValueHandler'; +import { HorizonDom, HorizonSelect, Props } from '../utils/Interface'; +import { getInputPropsWithoutValue, setInitInputValue, updateInputValue } from './InputValueHandler'; +import { getOptionPropsWithoutValue } from './OptionValueHandler'; +import { getSelectPropsWithoutValue, updateSelectValue } from './SelectValueHandler'; +import { getTextareaPropsWithoutValue, updateTextareaValue } from './TextareaValueHandler'; // 获取元素除了被代理的值以外的属性 function getPropsWithoutValue(type: string, dom: HorizonDom, props: Props) { @@ -86,8 +74,4 @@ function updateValue(type: string, dom: HorizonDom, props: Props) { } } -export { - getPropsWithoutValue, - setInitValue, - updateValue, -}; +export { getPropsWithoutValue, setInitValue, updateValue }; diff --git a/libs/horizon/src/event/EventBinding.ts b/libs/horizon/src/event/EventBinding.ts index 3a6819ac..e9d88308 100644 --- a/libs/horizon/src/event/EventBinding.ts +++ b/libs/horizon/src/event/EventBinding.ts @@ -16,10 +16,7 @@ /** * 事件绑定实现,分为绑定委托事件和非委托事件 */ -import { - allDelegatedHorizonEvents, - allDelegatedNativeEvents, -} from './EventHub'; +import { allDelegatedHorizonEvents, allDelegatedNativeEvents } from './EventHub'; import { isDocument } from '../dom/utils/Common'; import { getNearestVNode, getNonDelegatedListenerMap } from '../dom/DOMInternalKeys'; import { asyncUpdates, runDiscreteUpdates } from '../renderer/TreeBuilder'; @@ -27,11 +24,7 @@ import { handleEventMain } from './HorizonEventMain'; import { decorateNativeEvent } from './EventWrapper'; import { VNode } from '../renderer/vnode/VNode'; -const listeningMarker = - '_horizonListening' + - Math.random() - .toString(36) - .slice(4); +const listeningMarker = '_horizonListening' + Math.random().toString(36).slice(4); // 触发委托事件 function triggerDelegatedEvent( @@ -71,7 +64,7 @@ export function lazyDelegateOnRoot(currentRoot: VNode, eventName: string) { const nativeEvents = allDelegatedHorizonEvents.get(eventName); nativeEvents.forEach(nativeEvent => { - const nativeFullName = isCapture ? nativeEvent + 'capture' : nativeEvent; + const nativeFullName = isCapture ? nativeEvent + 'capture' : nativeEvent; // 事件存储在DOM节点属性,避免多个VNode(root和portal)对应同一个DOM, 造成事件重复监听 let events = currentRoot.realNode.$EV; diff --git a/libs/horizon/src/event/EventWrapper.ts b/libs/horizon/src/event/EventWrapper.ts index 6e922129..6ed15a19 100644 --- a/libs/horizon/src/event/EventWrapper.ts +++ b/libs/horizon/src/event/EventWrapper.ts @@ -40,7 +40,7 @@ export class WrappedEvent { stopPropagation: () => void; preventDefault: () => void; - propagationStopped = false + propagationStopped = false; isPropagationStopped = (): boolean => this.propagationStopped; // 适配Keyboard键盘事件该函数不能由合成事件调用 @@ -51,9 +51,9 @@ export class WrappedEvent { constructor(customEventName: string, nativeEvtName: string, nativeEvent: AnyNativeEvent) { for (const name in nativeEvent) { this[name] = nativeEvent[name]; - if(name === 'getModifierState') { + if (name === 'getModifierState') { const keyBoardEvent = nativeEvent as KeyboardEvent; - this.getModifierState = (keyArg) => keyBoardEvent.getModifierState(keyArg); + this.getModifierState = keyArg => keyBoardEvent.getModifierState(keyArg); } } // stopPropagation和preventDefault 必须通过Event实例调用 diff --git a/libs/horizon/src/event/FormValueController.ts b/libs/horizon/src/event/FormValueController.ts index a8a5b514..ac0603e8 100644 --- a/libs/horizon/src/event/FormValueController.ts +++ b/libs/horizon/src/event/FormValueController.ts @@ -15,7 +15,7 @@ import { getVNodeProps } from '../dom/DOMInternalKeys'; import { getDomTag } from '../dom/utils/Common'; -import { Props } from '../dom/utils/Interface'; +import { Props } from '../dom/utils/Interface'; import { updateTextareaValue } from '../dom/valueHandler/TextareaValueHandler'; import { updateInputHandlerIfChanged } from '../dom/valueHandler/ValueChangeHandler'; import { updateInputValue } from '../dom/valueHandler/InputValueHandler'; @@ -87,4 +87,3 @@ function controlInputValue(inputDom: HTMLInputElement, props: Props) { updateInputValue(inputDom, props); } } - diff --git a/libs/horizon/src/event/HorizonEventMain.ts b/libs/horizon/src/event/HorizonEventMain.ts index ea5fb202..5c0ae747 100644 --- a/libs/horizon/src/event/HorizonEventMain.ts +++ b/libs/horizon/src/event/HorizonEventMain.ts @@ -78,11 +78,7 @@ function getChangeListeners( if (shouldTriggerChangeEvent(targetDom, nativeEvtName)) { recordChangeEventTargets(target); - const event = decorateNativeEvent( - 'onChange', - 'change', - nativeEvt, - ); + const event = decorateNativeEvent('onChange', 'change', nativeEvt); return getListenersFromTree(vNode, 'onChange', event, EVENT_TYPE_ALL); } @@ -95,7 +91,7 @@ function getCommonListeners( vNode: null | VNode, nativeEvent: AnyNativeEvent, target: null | EventTarget, - isCapture: boolean, + isCapture: boolean ): ListenerUnitList { const horizonEvtName = transformToHorizonEvent(nativeEvtName); @@ -117,12 +113,7 @@ function getCommonListeners( } const horizonEvent = decorateNativeEvent(horizonEvtName, nativeEvtName, nativeEvent); - return getListenersFromTree( - vNode, - horizonEvtName, - horizonEvent, - isCapture ? EVENT_TYPE_CAPTURE : EVENT_TYPE_BUBBLE, - ); + return getListenersFromTree(vNode, horizonEvtName, horizonEvent, isCapture ? EVENT_TYPE_CAPTURE : EVENT_TYPE_BUBBLE); } // 按顺序执行事件队列 @@ -145,27 +136,16 @@ function triggerHorizonEvents( nativeEvtName: string, isCapture: boolean, nativeEvent: AnyNativeEvent, - vNode: VNode | null, + vNode: VNode | null ) { const target = nativeEvent.target || nativeEvent.srcElement!; // 触发普通委托事件 - let listenerList: ListenerUnitList = getCommonListeners( - nativeEvtName, - vNode, - nativeEvent, - target, - isCapture, - ); + let listenerList: ListenerUnitList = getCommonListeners(nativeEvtName, vNode, nativeEvent, target, isCapture); // 触发特殊handler委托事件 if (!isCapture && horizonEventToNativeMap.get('onChange')!.includes(nativeEvtName)) { - const changeListeners = getChangeListeners( - nativeEvtName, - nativeEvent, - vNode, - target - ); + const changeListeners = getChangeListeners(nativeEvtName, nativeEvent, vNode, target); if (changeListeners.length) { listenerList = listenerList.concat(changeListeners); } @@ -175,7 +155,6 @@ function triggerHorizonEvents( processListeners(listenerList); } - // 其他事件正在执行中标记 let isInEventsExecution = false; @@ -185,7 +164,7 @@ export function handleEventMain( isCapture: boolean, nativeEvent: AnyNativeEvent, vNode: null | VNode, - targetDom: EventTarget, + targetDom: EventTarget ): void { let startVNode = vNode; if (startVNode !== null) { diff --git a/libs/horizon/src/event/utils.ts b/libs/horizon/src/event/utils.ts index ad8b119c..6f21e52e 100644 --- a/libs/horizon/src/event/utils.ts +++ b/libs/horizon/src/event/utils.ts @@ -1,4 +1,3 @@ - /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * @@ -16,12 +15,11 @@ export function isInputElement(dom?: HTMLElement): boolean { return dom instanceof HTMLInputElement || dom instanceof HTMLTextAreaElement; - } export function setPropertyWritable(obj, propName) { const desc = Object.getOwnPropertyDescriptor(obj, propName); if (!desc || !desc.writable) { - Object.defineProperty(obj, propName, { writable : true }); + Object.defineProperty(obj, propName, { writable: true }); } } diff --git a/libs/horizon/src/external/JSXElement.ts b/libs/horizon/src/external/JSXElement.ts index fee74176..ebb43d18 100644 --- a/libs/horizon/src/external/JSXElement.ts +++ b/libs/horizon/src/external/JSXElement.ts @@ -56,8 +56,8 @@ function mergeDefault(sourceObj, defaultObj) { function buildElement(isClone, type, setting, children) { // setting中的值优先级最高,clone情况下从 type 中取值,创建情况下直接赋值为 null - const key = (setting && setting.key !== undefined) ? String(setting.key) : (isClone ? type.key : null); - const ref = (setting && setting.ref !== undefined) ? setting.ref : (isClone ? type.ref : null); + const key = setting && setting.key !== undefined ? String(setting.key) : isClone ? type.key : null; + const ref = setting && setting.ref !== undefined ? setting.ref : isClone ? type.ref : null; const props = isClone ? { ...type.props } : {}; let vNode = isClone ? type.belongClassVNode : getProcessingClassVNode(); diff --git a/libs/horizon/src/external/devtools.ts b/libs/horizon/src/external/devtools.ts index 633827fb..ba9922e3 100644 --- a/libs/horizon/src/external/devtools.ts +++ b/libs/horizon/src/external/devtools.ts @@ -54,7 +54,7 @@ export const helper = { return { name: HookName.RefHook, hIndex, value: (state as Ref).current }; } else if (isEffectHook(state)) { const name = - state.effectConstant == EffectConstant.LayoutEffect || (EffectConstant.LayoutEffect | EffectConstant.DepsChange) + state.effectConstant == EffectConstant.LayoutEffect || EffectConstant.LayoutEffect | EffectConstant.DepsChange ? HookName.LayoutEffectHook : HookName.EffectHook; return { name, hIndex, value: (state as Effect).effect }; diff --git a/libs/horizon/src/horizonx/adapters/redux.ts b/libs/horizon/src/horizonx/adapters/redux.ts index fe71cf34..359981ef 100644 --- a/libs/horizon/src/horizonx/adapters/redux.ts +++ b/libs/horizon/src/horizonx/adapters/redux.ts @@ -73,7 +73,7 @@ export function createStore(reducer: Reducer, preloadedState?: any, enhancers?): const result = { reducer, - getState: function() { + getState: function () { return store.$s.stateWrapper; }, subscribe: listener => { diff --git a/libs/horizon/src/horizonx/adapters/reduxReact.ts b/libs/horizon/src/horizonx/adapters/reduxReact.ts index 58321399..615c5d9b 100644 --- a/libs/horizon/src/horizonx/adapters/reduxReact.ts +++ b/libs/horizon/src/horizonx/adapters/reduxReact.ts @@ -44,8 +44,8 @@ export function createStoreHook(context: Context) { } export function createSelectorHook(context: Context): (selector?: (any) => any) => any { - const store = (createStoreHook(context)() as unknown) as ReduxStoreHandler; - return function(selector = state => state) { + const store = createStoreHook(context)() as unknown as ReduxStoreHandler; + return function (selector = state => state) { const [b, fr] = useState(false); useEffect(() => { @@ -59,9 +59,9 @@ export function createSelectorHook(context: Context): (selector?: (any) => any) }; } -export function createDispatchHook(context: Context): ()=>BoundActionCreator { - const store = (createStoreHook(context)() as unknown) as ReduxStoreHandler; - return function() { +export function createDispatchHook(context: Context): () => BoundActionCreator { + const store = createStoreHook(context)() as unknown as ReduxStoreHandler; + return function () { return action => { store.dispatch(action); }; @@ -120,7 +120,7 @@ export function connect( function Wrapper(props) { const [f, forceReload] = useState(true); - const store = (useStore() as unknown) as ReduxStoreHandler; + const store = useStore() as unknown as ReduxStoreHandler; useEffect(() => { const unsubscribe = store.subscribe(() => forceReload(!f)); diff --git a/libs/horizon/src/horizonx/adapters/reduxThunk.ts b/libs/horizon/src/horizonx/adapters/reduxThunk.ts index 3fab9b2d..70dfe622 100644 --- a/libs/horizon/src/horizonx/adapters/reduxThunk.ts +++ b/libs/horizon/src/horizonx/adapters/reduxThunk.ts @@ -17,20 +17,22 @@ import { ReduxAction, ReduxMiddleware } from './redux'; import { ReduxStoreHandler } from '../store/StoreHandler'; function createThunkMiddleware(extraArgument?: any): ReduxMiddleware { - return (store: ReduxStoreHandler) => (next: (action: ReduxAction) => any) => ( - action: - | ReduxAction - | ((dispatch: (action: ReduxAction) => void, store: ReduxStoreHandler, extraArgument?: any) => any) - ) => { - // This gets called for every action you dispatch. - // If it's a function, call it. - if (typeof action === 'function') { - return action(store.dispatch, store.getState.bind(store), extraArgument); - } + return (store: ReduxStoreHandler) => + (next: (action: ReduxAction) => any) => + ( + action: + | ReduxAction + | ((dispatch: (action: ReduxAction) => void, store: ReduxStoreHandler, extraArgument?: any) => any) + ) => { + // This gets called for every action you dispatch. + // If it's a function, call it. + if (typeof action === 'function') { + return action(store.dispatch, store.getState.bind(store), extraArgument); + } - // Otherwise, just continue processing this action as usual - return next(action); - }; + // Otherwise, just continue processing this action as usual + return next(action); + }; } export const thunk = createThunkMiddleware(); diff --git a/libs/horizon/src/horizonx/proxy/HooklessObserver.ts b/libs/horizon/src/horizonx/proxy/HooklessObserver.ts index 42e7da21..bc1dbda0 100644 --- a/libs/horizon/src/horizonx/proxy/HooklessObserver.ts +++ b/libs/horizon/src/horizonx/proxy/HooklessObserver.ts @@ -15,18 +15,16 @@ // TODO: implement vNode type -import {IObserver} from './Observer'; +import { IObserver } from './Observer'; /** * 一个对象(对象、数组、集合)对应一个Observer * */ export class HooklessObserver implements IObserver { + listeners: (() => void)[] = []; - listeners:(() => void)[] = []; - - useProp(key: string | symbol): void { - } + useProp(key: string | symbol): void {} addListener(listener: () => void) { this.listeners.push(listener); @@ -49,12 +47,9 @@ export class HooklessObserver implements IObserver { }); } - triggerUpdate(vNode): void { - } + triggerUpdate(vNode): void {} - allChange(): void { - } + allChange(): void {} - clearByVNode(vNode): void { - } + clearByVNode(vNode): void {} } diff --git a/libs/horizon/src/horizonx/proxy/ProxyHandler.ts b/libs/horizon/src/horizonx/proxy/ProxyHandler.ts index 1f17dd74..0004aae9 100644 --- a/libs/horizon/src/horizonx/proxy/ProxyHandler.ts +++ b/libs/horizon/src/horizonx/proxy/ProxyHandler.ts @@ -54,7 +54,7 @@ export function createProxy(rawObj: any, hookObserver = true): any { // 创建Proxy let proxyObj; if (!hookObserver) { - proxyObj = createObjectProxy(rawObj,true); + proxyObj = createObjectProxy(rawObj, true); } else if (isArray(rawObj)) { // 数组 proxyObj = createArrayProxy(rawObj as []); diff --git a/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts b/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts index 6074b28b..a231988e 100644 --- a/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts +++ b/libs/horizon/src/horizonx/proxy/handlers/ObjectProxyHandler.ts @@ -34,14 +34,14 @@ export function get(rawObj: object, key: string | symbol, receiver: any, singleL const observer = getObserver(rawObj); - if (key === 'watch'){ - return (prop, handler:(key:string, oldValue:any, newValue:any)=>void)=>{ - if(!observer.watchers[prop]){ - observer.watchers[prop]=[] as ((key:string, oldValue:any, newValue:any)=>void)[]; + if (key === 'watch') { + return (prop, handler: (key: string, oldValue: any, newValue: any) => void) => { + if (!observer.watchers[prop]) { + observer.watchers[prop] = [] as ((key: string, oldValue: any, newValue: any) => void)[]; } observer.watchers[prop].push(handler); - return ()=>{ - observer.watchers[prop]=observer.watchers[prop].filter(cb=>cb!==handler); + return () => { + observer.watchers[prop] = observer.watchers[prop].filter(cb => cb !== handler); }; }; } @@ -81,7 +81,7 @@ export function set(rawObj: object, key: string, value: any, receiver: any): boo const ret = Reflect.set(rawObj, key, newValue, receiver); if (!isSame(newValue, oldValue)) { - if(observer.watchers?.[key]){ + if (observer.watchers?.[key]) { observer.watchers[key].forEach(cb => { cb(key, oldValue, newValue); }); diff --git a/libs/horizon/src/horizonx/proxy/readonlyProxy.ts b/libs/horizon/src/horizonx/proxy/readonlyProxy.ts index 72fc776a..f2853fed 100644 --- a/libs/horizon/src/horizonx/proxy/readonlyProxy.ts +++ b/libs/horizon/src/horizonx/proxy/readonlyProxy.ts @@ -23,7 +23,7 @@ export function readonlyProxy(target: T): ProxyHandler { if (isObject(result)) { return readonlyProxy(result); } - } catch(err) { + } catch (err) { // 不处理 } return result; diff --git a/libs/horizon/src/horizonx/types.d.ts b/libs/horizon/src/horizonx/types.d.ts index 8c93e132..243d6f8a 100644 --- a/libs/horizon/src/horizonx/types.d.ts +++ b/libs/horizon/src/horizonx/types.d.ts @@ -14,7 +14,6 @@ */ export interface IObserver { - useProp: (key: string | symbol) => void; addListener: (listener: () => void) => void; @@ -32,65 +31,65 @@ export interface IObserver { clearByVNode: (vNode: any) => void; } -type RemoveFirstFromTuple = - T['length'] extends 0 ? [] : - (((...b: T) => void) extends (a, ...b: infer I) => void ? I : []) +type RemoveFirstFromTuple = T['length'] extends 0 + ? [] + : ((...b: T) => void) extends (a, ...b: infer I) => void + ? I + : []; - -type UserActions = { [K:string]: ActionFunction }; -type UserComputedValues = { [K:string]: ComputedFunction }; +type UserActions = { [K: string]: ActionFunction }; +type UserComputedValues = { [K: string]: ComputedFunction }; type ActionFunction = (state: S, ...args: any[]) => any; type ComputedFunction = (state: S) => any; -type Action> = (...args:RemoveFirstFromTuple>)=>ReturnType -type AsyncAction> = (...args:RemoveFirstFromTuple>)=>Promise> +type Action> = (...args: RemoveFirstFromTuple>) => ReturnType; +type AsyncAction> = (...args: RemoveFirstFromTuple>) => Promise>; -type StoreActions> = { [K in keyof A]: Action }; -type QueuedStoreActions> = { [K in keyof A]: AsyncAction }; -type ComputedValues> = { [K in keyof C]: ReturnType }; +type StoreActions> = { [K in keyof A]: Action }; +type QueuedStoreActions> = { [K in keyof A]: AsyncAction }; +type ComputedValues> = { [K in keyof C]: ReturnType }; type PostponedAction = (state: object, ...args: any[]) => Promise; -type PostponedActions = { [key:string]: PostponedAction } +type PostponedActions = { [key: string]: PostponedAction }; -export type StoreHandler,C extends UserComputedValues> = - {$subscribe: ((listener: () => void) => void), - $unsubscribe: ((listener: () => void) => void), - $state: S, - $config: StoreConfig, - $queue: QueuedStoreActions, - $actions: StoreActions, - $computed: ComputedValues, - reduxHandler?:ReduxStoreHandler} - & - {[K in keyof S]: S[K]} - & - {[K in keyof A]: Action} - & - {[K in keyof C]: ReturnType} +export type StoreHandler, C extends UserComputedValues> = { + $subscribe: (listener: () => void) => void; + $unsubscribe: (listener: () => void) => void; + $state: S; + $config: StoreConfig; + $queue: QueuedStoreActions; + $actions: StoreActions; + $computed: ComputedValues; + reduxHandler?: ReduxStoreHandler; +} & { [K in keyof S]: S[K] } & { [K in keyof A]: Action } & { [K in keyof C]: ReturnType }; -export type StoreConfig,C extends UserComputedValues> = { - state?: S, - options?:{suppressHooks?: boolean}, - actions?: A, - id?: string, - computed?: C -} +export type StoreConfig, C extends UserComputedValues> = { + state?: S; + options?: { suppressHooks?: boolean }; + actions?: A; + id?: string; + computed?: C; +}; type ReduxStoreHandler = { - reducer:(state:any,action:{type:string})=>any, - dispatch:(action:{type:string})=>void, - getState:()=>any, - subscribe:(listener:()=>void)=>((listener:()=>void)=>void) - replaceReducer: (reducer: (state:any,action:{type:string})=>any)=>void - _horizonXstore: StoreHandler -} + reducer: (state: any, action: { type: string }) => any; + dispatch: (action: { type: string }) => void; + getState: () => any; + subscribe: (listener: () => void) => (listener: () => void) => void; + replaceReducer: (reducer: (state: any, action: { type: string }) => any) => void; + _horizonXstore: StoreHandler; +}; type ReduxAction = { - type:string -} + type: string; +}; -type ReduxMiddleware = (store:ReduxStoreHandler, extraArgument?:any) => - (next:((action:ReduxAction)=>any)) => - (action:( - ReduxAction| - ((dispatch:(action:ReduxAction)=>void,store:ReduxStoreHandler,extraArgument?:any)=>any) - )) => ReduxStoreHandler +type ReduxMiddleware = ( + store: ReduxStoreHandler, + extraArgument?: any +) => ( + next: (action: ReduxAction) => any +) => ( + action: + | ReduxAction + | ((dispatch: (action: ReduxAction) => void, store: ReduxStoreHandler, extraArgument?: any) => any) +) => ReduxStoreHandler; diff --git a/libs/horizon/src/renderer/ErrorHandler.ts b/libs/horizon/src/renderer/ErrorHandler.ts index 10ec83f3..af115325 100644 --- a/libs/horizon/src/renderer/ErrorHandler.ts +++ b/libs/horizon/src/renderer/ErrorHandler.ts @@ -18,16 +18,16 @@ */ import type { PromiseType, VNode } from './Types'; -import type {Update} from './UpdateHandler'; +import type { Update } from './UpdateHandler'; -import {ClassComponent, TreeRoot} from './vnode/VNodeTags'; -import {FlagUtils, Interrupted, DidCapture, InitFlag} from './vnode/VNodeFlags'; -import {newUpdate, UpdateState, pushUpdate} from './UpdateHandler'; -import {launchUpdateFromVNode, tryRenderFromRoot} from './TreeBuilder'; -import {setRootThrowError} from './submit/Submit'; -import {handleSuspenseChildThrowError} from './render/SuspenseComponent'; -import {updateShouldUpdateOfTree} from './vnode/VNodeShouldUpdate'; -import {BuildErrored, setBuildResult} from './GlobalVar'; +import { ClassComponent, TreeRoot } from './vnode/VNodeTags'; +import { FlagUtils, Interrupted, DidCapture, InitFlag } from './vnode/VNodeFlags'; +import { newUpdate, UpdateState, pushUpdate } from './UpdateHandler'; +import { launchUpdateFromVNode, tryRenderFromRoot } from './TreeBuilder'; +import { setRootThrowError } from './submit/Submit'; +import { handleSuspenseChildThrowError } from './render/SuspenseComponent'; +import { updateShouldUpdateOfTree } from './vnode/VNodeShouldUpdate'; +import { BuildErrored, setBuildResult } from './GlobalVar'; function consoleError(error: any): void { if (isTest) { @@ -38,18 +38,13 @@ function consoleError(error: any): void { } } -function handleRootError( - error: any, -) { +function handleRootError(error: any) { // 注意:如果根节点抛出错误,不会销毁整棵树,只打印日志,抛出异常。 setRootThrowError(error); consoleError(error); } -function createClassErrorUpdate( - vNode: VNode, - error: any, -): Update { +function createClassErrorUpdate(vNode: VNode, error: any): Update { const update = newUpdate(); update.type = UpdateState.Error; @@ -81,10 +76,7 @@ function isPromise(error: any): error is PromiseType { return error !== null && typeof error === 'object' && typeof error.then === 'function'; } // 处理capture和bubble阶段抛出的错误 -export function handleRenderThrowError( - sourceVNode: VNode, - error: any, -) { +export function handleRenderThrowError(sourceVNode: VNode, error: any) { // vNode抛出了异常,标记Interrupted中断 FlagUtils.markInterrupted(sourceVNode); // dirtyNodes 不再有效 @@ -117,10 +109,8 @@ export function handleRenderThrowError( const instance = vNode.realNode; if ( (vNode.flags & DidCapture) === InitFlag && - ( - typeof ctor.getDerivedStateFromError === 'function' || - (instance !== null && typeof instance.componentDidCatch === 'function') - ) + (typeof ctor.getDerivedStateFromError === 'function' || + (instance !== null && typeof instance.componentDidCatch === 'function')) ) { FlagUtils.markShouldCapture(vNode); @@ -155,7 +145,6 @@ function triggerUpdate(vNode, state) { } } - // 处理submit阶段的异常 export function handleSubmitError(vNode: VNode, error: any) { if (vNode.tag === TreeRoot) { @@ -169,20 +158,19 @@ export function handleSubmitError(vNode: VNode, error: any) { if (node.tag === TreeRoot) { handleRootError(error); return; - } else if (node.tag === ClassComponent) { // 只有 class 组件才可以成为错误边界组件 + } else if (node.tag === ClassComponent) { + // 只有 class 组件才可以成为错误边界组件 const ctor = node.type; const instance = node.realNode; - if ( - typeof ctor.getDerivedStateFromError === 'function' || - typeof instance.componentDidCatch === 'function' - ) { + if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function') { const getDerivedStateFromError = node.type.getDerivedStateFromError; if (typeof getDerivedStateFromError === 'function') { // 打印错误 consoleError(error); const retState = getDerivedStateFromError(error); - if (retState) { // 有返回值 + if (retState) { + // 有返回值 // 触发更新 triggerUpdate(node, retState); } @@ -190,7 +178,8 @@ export function handleSubmitError(vNode: VNode, error: any) { // 处理componentDidCatch if (instance !== null && typeof instance.componentDidCatch === 'function') { - if (typeof getDerivedStateFromError !== 'function') { // 没有getDerivedStateFromError + if (typeof getDerivedStateFromError !== 'function') { + // 没有getDerivedStateFromError // 打印错误 consoleError(error); } diff --git a/libs/horizon/src/renderer/ExecuteMode.ts b/libs/horizon/src/renderer/ExecuteMode.ts index f7071936..e0ddf54d 100644 --- a/libs/horizon/src/renderer/ExecuteMode.ts +++ b/libs/horizon/src/renderer/ExecuteMode.ts @@ -1,4 +1,3 @@ - /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * @@ -42,7 +41,7 @@ export function isExecuting() { } export function copyExecuteMode() { - return {...executeMode}; + return { ...executeMode }; } export function setExecuteMode(mode: typeof executeMode) { diff --git a/libs/horizon/src/renderer/GlobalVar.ts b/libs/horizon/src/renderer/GlobalVar.ts index 272cad79..fac2f8aa 100644 --- a/libs/horizon/src/renderer/GlobalVar.ts +++ b/libs/horizon/src/renderer/GlobalVar.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from './Types'; +import type { VNode } from './Types'; // 当前处理的classVNode,用于设置inst.refs let processingClassVNode: VNode | null = null; diff --git a/libs/horizon/src/renderer/Renderer.ts b/libs/horizon/src/renderer/Renderer.ts index a58a953f..37f77f92 100644 --- a/libs/horizon/src/renderer/Renderer.ts +++ b/libs/horizon/src/renderer/Renderer.ts @@ -16,30 +16,15 @@ import type { VNode } from './Types'; import type { Update } from './UpdateHandler'; -import { - asyncUpdates, - syncUpdates, - runDiscreteUpdates, - launchUpdateFromVNode, -} from './TreeBuilder'; +import { asyncUpdates, syncUpdates, runDiscreteUpdates, launchUpdateFromVNode } from './TreeBuilder'; import { runAsyncEffects } from './submit/HookEffectHandler'; import { Callback, newUpdate, pushUpdate } from './UpdateHandler'; - export { createVNode, createTreeRootVNode } from './vnode/VNodeCreator'; export { createPortal } from './components/CreatePortal'; -export { - asyncUpdates, - syncUpdates, - runDiscreteUpdates, - runAsyncEffects, -}; +export { asyncUpdates, syncUpdates, runDiscreteUpdates, runAsyncEffects }; -export function startUpdate( - element: any, - treeRoot: VNode, - callback?: Callback, -) { +export function startUpdate(element: any, treeRoot: VNode, callback?: Callback) { const update: Update = newUpdate(); update.content = { element }; @@ -58,4 +43,3 @@ export function getFirstCustomDom(treeRoot?: VNode | null): Element | Text | nul } return null; } - diff --git a/libs/horizon/src/renderer/TreeBuilder.ts b/libs/horizon/src/renderer/TreeBuilder.ts index 71dd01e0..2abace80 100644 --- a/libs/horizon/src/renderer/TreeBuilder.ts +++ b/libs/horizon/src/renderer/TreeBuilder.ts @@ -45,12 +45,7 @@ import { isExecuting, setExecuteMode, } from './ExecuteMode'; -import { - resetContext, - resetNamespaceCtx, - setContext, - setNamespaceCtx, -} from './ContextSaver'; +import { resetContext, resetNamespaceCtx, setContext, setNamespaceCtx } from './ContextSaver'; import { updateChildShouldUpdate, updateParentsChildShouldUpdate, @@ -110,7 +105,8 @@ function bubbleVNode(vNode: VNode): void { do { const parent = node.parent; - if ((node.flags & Interrupted) === InitFlag) { // vNode没有抛出异常 + if ((node.flags & Interrupted) === InitFlag) { + // vNode没有抛出异常 componentRenders[node.tag].bubbleRender(node); // 设置node的childShouldUpdate属性 @@ -133,7 +129,8 @@ function bubbleVNode(vNode: VNode): void { } const siblingVNode = node.next; - if (siblingVNode !== null) { // 有兄弟vNode + if (siblingVNode !== null) { + // 有兄弟vNode processing = siblingVNode; return; } @@ -244,7 +241,8 @@ function buildVNodeTree(treeRoot: VNode) { // 清空toUpdateNodes treeRoot.toUpdateNodes.clear(); - if (startVNode.tag !== TreeRoot) { // 不是根节点 + if (startVNode.tag !== TreeRoot) { + // 不是根节点 // 设置namespace,用于createElement let parent = startVNode.parent; while (parent !== null) { @@ -290,7 +288,8 @@ function buildVNodeTree(treeRoot: VNode) { handleError(treeRoot, thrownValue); } } - if (startVNode.tag !== TreeRoot) { // 不是根节点 + if (startVNode.tag !== TreeRoot) { + // 不是根节点 // 恢复父节点的context resetTreeContext(startVNode); } @@ -308,7 +307,7 @@ function recoverTreeContext(vNode: VNode) { if (parent.tag === ContextProvider) { contextProviders.unshift(parent); } - if(parent.tag === DomPortal){ + if (parent.tag === DomPortal) { pushCurrentRoot(parent); } parent = parent.parent; @@ -326,7 +325,7 @@ function resetTreeContext(vNode: VNode) { if (parent.tag === ContextProvider) { resetContext(parent); } - if(parent.tag === DomPortal){ + if (parent.tag === DomPortal) { popCurrentRoot(); } parent = parent.parent; @@ -365,9 +364,7 @@ function renderFromRoot(treeRoot) { export function tryRenderFromRoot(treeRoot: VNode) { if (treeRoot.shouldUpdate && treeRoot.task === null) { // 任务放进queue,但是调度开始还是异步的 - treeRoot.task = pushRenderCallback( - renderFromRoot.bind(null, treeRoot), - ); + treeRoot.task = pushRenderCallback(renderFromRoot.bind(null, treeRoot)); } } @@ -387,8 +384,11 @@ export function launchUpdateFromVNode(vNode: VNode) { // 保存待刷新的节点 treeRoot.toUpdateNodes?.add(vNode); - if (checkMode(BySync) && // 非批量 - !checkMode(InRender)) { // 不是渲染阶段触发 + if ( + checkMode(BySync) && // 非批量 + !checkMode(InRender) + ) { + // 不是渲染阶段触发 // 业务直接调用Horizon.render的时候会进入这个分支,同步渲染。 // 不能改成下面的异步,否则会有时序问题,因为业务可能会依赖这个渲染的完成。 diff --git a/libs/horizon/src/renderer/UpdateHandler.ts b/libs/horizon/src/renderer/UpdateHandler.ts index acb9c71e..c906bd1c 100644 --- a/libs/horizon/src/renderer/UpdateHandler.ts +++ b/libs/horizon/src/renderer/UpdateHandler.ts @@ -53,13 +53,7 @@ export function pushUpdate(vNode: VNode, update: Update) { } // 根据update获取新的state -function calcState( - vNode: VNode, - update: Update, - inst: any, - oldState: any, - props: any, -): any { +function calcState(vNode: VNode, update: Update, inst: any, oldState: any, props: any): any { switch (update.type) { case UpdateState.Override: const content = update.content; @@ -73,9 +67,7 @@ function calcState( case UpdateState.Update: const updateContent = update.content; const newState = typeof updateContent === 'function' ? updateContent.call(inst, oldState, props) : updateContent; - return (newState === null || newState === undefined) - ? oldState - : { ...oldState, ...newState }; + return newState === null || newState === undefined ? oldState : { ...oldState, ...newState }; default: return oldState; } @@ -118,7 +110,6 @@ export function processUpdates(vNode: VNode, inst: any, props: any): void { calcUpdates(vNode, props, inst, toProcessUpdates); } } - } export function pushForceUpdate(vNode: VNode) { diff --git a/libs/horizon/src/renderer/components/CreatePortal.ts b/libs/horizon/src/renderer/components/CreatePortal.ts index f477d528..1c9cbc67 100644 --- a/libs/horizon/src/renderer/components/CreatePortal.ts +++ b/libs/horizon/src/renderer/components/CreatePortal.ts @@ -13,14 +13,10 @@ * See the Mulan PSL v2 for more details. */ -import {TYPE_PORTAL} from '../../external/JSXElementType'; -import type {PortalType} from '../Types'; +import { TYPE_PORTAL } from '../../external/JSXElementType'; +import type { PortalType } from '../Types'; -export function createPortal( - children: any, - realNode: any, - key = '', -): PortalType { +export function createPortal(children: any, realNode: any, key = ''): PortalType { return { vtype: TYPE_PORTAL, key: key == '' ? '' : '' + key, diff --git a/libs/horizon/src/renderer/components/CreateRef.ts b/libs/horizon/src/renderer/components/CreateRef.ts index cc1c65af..9abbcb27 100644 --- a/libs/horizon/src/renderer/components/CreateRef.ts +++ b/libs/horizon/src/renderer/components/CreateRef.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import type {RefType} from '../Types'; +import type { RefType } from '../Types'; export function createRef(): RefType { return { diff --git a/libs/horizon/src/renderer/components/ForwardRef.ts b/libs/horizon/src/renderer/components/ForwardRef.ts index a2c9dac3..80270175 100644 --- a/libs/horizon/src/renderer/components/ForwardRef.ts +++ b/libs/horizon/src/renderer/components/ForwardRef.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import {TYPE_FORWARD_REF} from '../../external/JSXElementType'; +import { TYPE_FORWARD_REF } from '../../external/JSXElementType'; export function forwardRef(render: Function) { return { diff --git a/libs/horizon/src/renderer/components/Lazy.ts b/libs/horizon/src/renderer/components/Lazy.ts index e04e3ff6..9359ca1f 100644 --- a/libs/horizon/src/renderer/components/Lazy.ts +++ b/libs/horizon/src/renderer/components/Lazy.ts @@ -13,9 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import type {PromiseType} from '../Types'; +import type { PromiseType } from '../Types'; -import {TYPE_LAZY} from '../../external/JSXElementType'; +import { TYPE_LAZY } from '../../external/JSXElementType'; enum LayStatus { UnProcessed = 'UnProcessed', @@ -26,7 +26,7 @@ enum LayStatus { type LazyContent = { _status: string; - _value: () => PromiseType<{default: T}> | PromiseType | T | any; + _value: () => PromiseType<{ default: T }> | PromiseType | T | any; }; export type LazyComponent = { @@ -59,7 +59,7 @@ function lazyLoader(lazyContent: LazyContent): any { lazyContent._status = LayStatus.Rejected; lazyContent._value = error; } - }, + } ); } if (lazyContent._status === LayStatus.Fulfilled) { @@ -69,7 +69,7 @@ function lazyLoader(lazyContent: LazyContent): any { } } -export function lazy(promiseCtor: () => PromiseType<{default: T}>): LazyComponent> { +export function lazy(promiseCtor: () => PromiseType<{ default: T }>): LazyComponent> { return { vtype: TYPE_LAZY, _content: { diff --git a/libs/horizon/src/renderer/components/Memo.ts b/libs/horizon/src/renderer/components/Memo.ts index c3c18f07..f8889dd2 100644 --- a/libs/horizon/src/renderer/components/Memo.ts +++ b/libs/horizon/src/renderer/components/Memo.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import {TYPE_MEMO} from '../../external/JSXElementType'; +import { TYPE_MEMO } from '../../external/JSXElementType'; export function memo(type, compare?: (oldProps: Props, newProps: Props) => boolean) { return { diff --git a/libs/horizon/src/renderer/components/context/Context.ts b/libs/horizon/src/renderer/components/context/Context.ts index c1899b9c..3fc5d681 100644 --- a/libs/horizon/src/renderer/components/context/Context.ts +++ b/libs/horizon/src/renderer/components/context/Context.ts @@ -13,9 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode, ContextType} from '../../Types'; -import {getHookStage} from '../../hooks/HookStage'; -import {throwNotInFuncError} from '../../hooks/BaseHook'; +import type { VNode, ContextType } from '../../Types'; +import { getHookStage } from '../../hooks/HookStage'; +import { throwNotInFuncError } from '../../hooks/BaseHook'; // 重置依赖 export function resetDepContexts(vNode: VNode): void { diff --git a/libs/horizon/src/renderer/components/context/CreateContext.ts b/libs/horizon/src/renderer/components/context/CreateContext.ts index 8c654726..db4b0e02 100644 --- a/libs/horizon/src/renderer/components/context/CreateContext.ts +++ b/libs/horizon/src/renderer/components/context/CreateContext.ts @@ -13,8 +13,8 @@ * See the Mulan PSL v2 for more details. */ -import type {ContextType} from '../../Types'; -import {TYPE_PROVIDER, TYPE_CONTEXT} from '../../../external/JSXElementType'; +import type { ContextType } from '../../Types'; +import { TYPE_PROVIDER, TYPE_CONTEXT } from '../../../external/JSXElementType'; export function createContext(val: T): ContextType { const context: ContextType = { diff --git a/libs/horizon/src/renderer/diff/DiffTools.ts b/libs/horizon/src/renderer/diff/DiffTools.ts index 49e2a79d..46c92c5c 100644 --- a/libs/horizon/src/renderer/diff/DiffTools.ts +++ b/libs/horizon/src/renderer/diff/DiffTools.ts @@ -18,7 +18,7 @@ import type { VNode, JSXElement } from '../Types'; // 当前vNode和element是同样的类型 // LazyComponent 会修改type的类型,所以特殊处理这种类型 export const isSameType = (vNode: VNode, ele: JSXElement) => - vNode.type === ele.type || (vNode.isLazyComponent && vNode.lazyType === ele.type); + vNode.type === ele.type || (vNode.isLazyComponent && vNode.lazyType === ele.type); export function isTextType(newChild: any) { return typeof newChild === 'string' || typeof newChild === 'number'; diff --git a/libs/horizon/src/renderer/diff/nodeDiffComparator.ts b/libs/horizon/src/renderer/diff/nodeDiffComparator.ts index 3899dae9..56753063 100644 --- a/libs/horizon/src/renderer/diff/nodeDiffComparator.ts +++ b/libs/horizon/src/renderer/diff/nodeDiffComparator.ts @@ -24,13 +24,7 @@ import { createPortalVNode, createDomTextVNode, } from '../vnode/VNodeCreator'; -import { - isSameType, - getIteratorFn, - isTextType, - isIteratorType, - isObjectType, -} from './DiffTools'; +import { isSameType, getIteratorFn, isTextType, isIteratorType, isObjectType } from './DiffTools'; import { travelChildren } from '../vnode/VNodeUtils'; import { markVNodePath } from '../utils/vNodePath'; @@ -120,10 +114,12 @@ function getNodeType(newChild: any): string | null { function setVNodeAdditionFlag(newNode: VNode, lastPosition: number): number { let position = lastPosition; - if (newNode.isCreated || newNode.eIndex < lastPosition) { // 位置 小于 上一个复用的位置 + if (newNode.isCreated || newNode.eIndex < lastPosition) { + // 位置 小于 上一个复用的位置 // 标记为新增 FlagUtils.setAddition(newNode); - } else { // 复用 + } else { + // 复用 position = newNode.eIndex; } @@ -206,15 +202,16 @@ function transRightChildrenToArray(child) { return rightChildrenArray; } -function transLeftChildrenToMap( - startChild: VNode, - rightEndVNode: VNode | null, -): Map { +function transLeftChildrenToMap(startChild: VNode, rightEndVNode: VNode | null): Map { const leftChildrenMap: Map = new Map(); - travelChildren(startChild, node => { - leftChildrenMap.set(node.key !== null ? node.key : node.eIndex, node); - }, node => node === rightEndVNode); + travelChildren( + startChild, + node => { + leftChildrenMap.set(node.key !== null ? node.key : node.eIndex, node); + }, + node => node === rightEndVNode + ); return leftChildrenMap; } @@ -235,11 +232,7 @@ function getOldNodeFromMap(nodeMap: Map, newIdx: number, } // diff数组类型的节点,核心算法 -function diffArrayNodesHandler( - parentNode: VNode, - firstChild: VNode | null, - newChildren: Array, -): VNode | null { +function diffArrayNodesHandler(parentNode: VNode, firstChild: VNode | null, newChildren: Array): VNode | null { let resultingFirstChild: VNode | null = null; let prevNewNode: VNode | null = null; @@ -366,13 +359,14 @@ function diffArrayNodesHandler( // 4. 新节点还有一部分,但是老节点已经没有了 if (oldNode === null) { - let isDirectAdd = false; // TODO: 是否可以扩大至非dom类型节点 // 如果dom节点在上次添加前没有节点,说明本次添加时,可以直接添加到最后,不需要通过 getSiblingDom 函数找到 before 节点 - if (parentNode.tag === DomComponent && + if ( + parentNode.tag === DomComponent && parentNode.oldProps?.children?.length === 0 && - rightIdx - leftIdx === newChildren.length) { + rightIdx - leftIdx === newChildren.length + ) { isDirectAdd = true; } const isAddition = parentNode.tag === DomPortal || !parentNode.isCreated; @@ -424,7 +418,8 @@ function diffArrayNodesHandler( const eIndex = newNode.eIndex; eIndexes.push(eIndex); last = eIndexes[result[result.length - 1]]; - if (eIndex > last || last === undefined) { // 大的 eIndex直接放在最后 + if (eIndex > last || last === undefined) { + // 大的 eIndex直接放在最后 preIndex[i] = result[result.length - 1]; result.push(i); } else { @@ -500,7 +495,7 @@ function setVNodesCIndex(startChild: VNode | null, startIdx: number) { function diffIteratorNodesHandler( parentNode: VNode, firstChild: VNode | null, - newChildrenIterable: Iterable, + newChildrenIterable: Iterable ): VNode | null { const iteratorFn = getIteratorFn(newChildrenIterable); const iteratorObj = iteratorFn.call(newChildrenIterable); @@ -517,12 +512,7 @@ function diffIteratorNodesHandler( } // 新节点是字符串类型 -function diffStringNodeHandler( - parentNode: VNode, - newChild: any, - firstChildVNode: VNode, - isComparing: boolean -) { +function diffStringNodeHandler(parentNode: VNode, newChild: any, firstChildVNode: VNode, isComparing: boolean) { let newTextNode: VNode | null = null; // 第一个vNode是Text,则复用 diff --git a/libs/horizon/src/renderer/hooks/BaseHook.ts b/libs/horizon/src/renderer/hooks/BaseHook.ts index d34f4c1f..3ffcaf62 100644 --- a/libs/horizon/src/renderer/hooks/BaseHook.ts +++ b/libs/horizon/src/renderer/hooks/BaseHook.ts @@ -14,7 +14,7 @@ */ import type { Hook } from './HookType'; -import {getProcessingVNode} from '../GlobalVar'; +import { getProcessingVNode } from '../GlobalVar'; // lastTimeHook是上一次执行func时产生的hooks中,与currentHook对应的hook let lastTimeHook: Hook | null = null; @@ -35,9 +35,7 @@ export function setCurrentHook(hook: Hook | null) { } export function throwNotInFuncError() { - throw Error( - 'Hooks should be used inside function component.', - ); + throw Error('Hooks should be used inside function component.'); } // 新建一个hook,并放到vNode.hooks中 @@ -63,9 +61,8 @@ export function getNextHook(hook: Hook, hooks: Array>) // 原因:1.比对hook的数量有没有变化(非必要);2.从上一次执行中的hook获取removeEffect export function getCurrentHook(): Hook { const processingVNode = getProcessingVNode(); - currentHook = currentHook !== null ? - getNextHook(currentHook, processingVNode.hooks) : - (processingVNode.hooks[0] || null); + currentHook = + currentHook !== null ? getNextHook(currentHook, processingVNode.hooks) : processingVNode.hooks[0] || null; if (lastTimeHook !== null) { lastTimeHook = getNextHook(lastTimeHook, processingVNode.oldHooks); diff --git a/libs/horizon/src/renderer/hooks/HookExternal.ts b/libs/horizon/src/renderer/hooks/HookExternal.ts index d869aae8..60adc0bd 100644 --- a/libs/horizon/src/renderer/hooks/HookExternal.ts +++ b/libs/horizon/src/renderer/hooks/HookExternal.ts @@ -13,26 +13,23 @@ * See the Mulan PSL v2 for more details. */ -import type {ContextType} from '../Types'; +import type { ContextType } from '../Types'; -import {useRefImpl} from './UseRefHook'; -import {useEffectImpl, useLayoutEffectImpl} from './UseEffectHook'; -import {useCallbackImpl} from './UseCallbackHook'; -import {useMemoImpl} from './UseMemoHook'; -import {useImperativeHandleImpl} from './UseImperativeHook'; -import {useReducerImpl} from './UseReducerHook'; -import {useStateImpl} from './UseStateHook'; -import {getNewContext} from '../components/context/Context'; -import {getProcessingVNode} from '../GlobalVar'; -import {Ref, Trigger} from './HookType'; +import { useRefImpl } from './UseRefHook'; +import { useEffectImpl, useLayoutEffectImpl } from './UseEffectHook'; +import { useCallbackImpl } from './UseCallbackHook'; +import { useMemoImpl } from './UseMemoHook'; +import { useImperativeHandleImpl } from './UseImperativeHook'; +import { useReducerImpl } from './UseReducerHook'; +import { useStateImpl } from './UseStateHook'; +import { getNewContext } from '../components/context/Context'; +import { getProcessingVNode } from '../GlobalVar'; +import { Ref, Trigger } from './HookType'; type BasicStateAction = ((S) => S) | S; type Dispatch = (A) => void; - -export function useContext( - Context: ContextType, -): T { +export function useContext(Context: ContextType): T { const processingVNode = getProcessingVNode(); return getNewContext(processingVNode!, Context, true); } @@ -41,11 +38,7 @@ export function useState(initialState: (() => S) | S): [S, Dispatch( - reducer: (S, A) => S, - initialArg: I, - init?: (I) => S, -): [S, Trigger] | void { +export function useReducer(reducer: (S, A) => S, initialArg: I, init?: (I) => S): [S, Trigger] | void { return useReducerImpl(reducer, initialArg, init); } @@ -53,38 +46,26 @@ export function useRef(initialValue: T): Ref { return useRefImpl(initialValue); } -export function useEffect( - create: () => (() => void) | void, - deps?: Array | null, -): void { +export function useEffect(create: () => (() => void) | void, deps?: Array | null): void { return useEffectImpl(create, deps); } -export function useLayoutEffect( - create: () => (() => void) | void, - deps?: Array | null, -): void { +export function useLayoutEffect(create: () => (() => void) | void, deps?: Array | null): void { return useLayoutEffectImpl(create, deps); } -export function useCallback( - callback: T, - deps?: Array | null, -): T { +export function useCallback(callback: T, deps?: Array | null): T { return useCallbackImpl(callback, deps); } -export function useMemo( - create: () => T, - deps?: Array | null, -): T { +export function useMemo(create: () => T, deps?: Array | null): T { return useMemoImpl(create, deps); } export function useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => any) | null | void, + ref: { current: T | null } | ((inst: T | null) => any) | null | void, create: () => T, - deps?: Array | null, + deps?: Array | null ): void { return useImperativeHandleImpl(ref, create, deps); } diff --git a/libs/horizon/src/renderer/hooks/HookMain.ts b/libs/horizon/src/renderer/hooks/HookMain.ts index b51b366d..31a5be53 100644 --- a/libs/horizon/src/renderer/hooks/HookMain.ts +++ b/libs/horizon/src/renderer/hooks/HookMain.ts @@ -13,21 +13,17 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from '../Types'; +import type { VNode } from '../Types'; -import { - getLastTimeHook, - setLastTimeHook, - setCurrentHook, getNextHook -} from './BaseHook'; -import {HookStage, setHookStage} from './HookStage'; +import { getLastTimeHook, setLastTimeHook, setCurrentHook, getNextHook } from './BaseHook'; +import { HookStage, setHookStage } from './HookStage'; // hook对外入口 export function runFunctionWithHooks, Arg>( funcComp: (props: Props, arg: Arg) => any, props: Props, arg: Arg, - processing: VNode, + processing: VNode ) { // 重置全局变量 resetGlobalVariable(); @@ -67,4 +63,3 @@ function resetGlobalVariable() { setLastTimeHook(null); setCurrentHook(null); } - diff --git a/libs/horizon/src/renderer/hooks/HookType.ts b/libs/horizon/src/renderer/hooks/HookType.ts index bdfdbab9..9377c456 100644 --- a/libs/horizon/src/renderer/hooks/HookType.ts +++ b/libs/horizon/src/renderer/hooks/HookType.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import {EffectConstant} from './EffectConstant'; +import { EffectConstant } from './EffectConstant'; type ValueOf = T[keyof T]; export interface Hook { state: Reducer | Effect | Memo | CallBack | Ref; diff --git a/libs/horizon/src/renderer/hooks/UseCallbackHook.ts b/libs/horizon/src/renderer/hooks/UseCallbackHook.ts index c9cb74a9..7316939d 100644 --- a/libs/horizon/src/renderer/hooks/UseCallbackHook.ts +++ b/libs/horizon/src/renderer/hooks/UseCallbackHook.ts @@ -13,13 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import { - createHook, - getCurrentHook, - throwNotInFuncError -} from './BaseHook'; -import {getHookStage, HookStage} from './HookStage'; -import {isArrayEqual} from '../utils/compare'; +import { createHook, getCurrentHook, throwNotInFuncError } from './BaseHook'; +import { getHookStage, HookStage } from './HookStage'; +import { isArrayEqual } from '../utils/compare'; export function useCallbackImpl(func: F, dependencies?: Array | null): F { const stage = getHookStage(); @@ -31,7 +27,7 @@ export function useCallbackImpl(func: F, dependencies?: Array | null): F const deps = dependencies !== undefined ? dependencies : null; if (stage === HookStage.Init) { hook = createHook(); - hook.state = {func, dependencies: deps}; + hook.state = { func, dependencies: deps }; } else if (stage === HookStage.Update) { hook = getCurrentHook(); @@ -40,7 +36,7 @@ export function useCallbackImpl(func: F, dependencies?: Array | null): F if (lastState !== null && deps !== null && isArrayEqual(deps, lastState.dependencies)) { return lastState.func; } - hook.state = {func, dependencies: deps}; + hook.state = { func, dependencies: deps }; } return func; diff --git a/libs/horizon/src/renderer/hooks/UseEffectHook.ts b/libs/horizon/src/renderer/hooks/UseEffectHook.ts index e44f0f6c..cd8e4313 100644 --- a/libs/horizon/src/renderer/hooks/UseEffectHook.ts +++ b/libs/horizon/src/renderer/hooks/UseEffectHook.ts @@ -13,18 +13,13 @@ * See the Mulan PSL v2 for more details. */ -import { - createHook, - getCurrentHook, - getLastTimeHook, - throwNotInFuncError -} from './BaseHook'; -import {FlagUtils} from '../vnode/VNodeFlags'; -import {EffectConstant} from './EffectConstant'; -import type {Effect, EffectList} from './HookType'; -import {getHookStage, HookStage} from './HookStage'; -import {isArrayEqual} from '../utils/compare'; -import {getProcessingVNode} from '../GlobalVar'; +import { createHook, getCurrentHook, getLastTimeHook, throwNotInFuncError } from './BaseHook'; +import { FlagUtils } from '../vnode/VNodeFlags'; +import { EffectConstant } from './EffectConstant'; +import type { Effect, EffectList } from './HookType'; +import { getHookStage, HookStage } from './HookStage'; +import { isArrayEqual } from '../utils/compare'; +import { getProcessingVNode } from '../GlobalVar'; export function useEffectImpl(effectFunc: () => (() => void) | void, deps?: Array | null): void { // 异步触发的effect @@ -36,11 +31,7 @@ export function useLayoutEffectImpl(effectFunc: () => (() => void) | void, deps? useEffect(effectFunc, deps, EffectConstant.LayoutEffect); } -function useEffect( - effectFunc: () => (() => void) | void, - deps: Array | void | null, - effectType: number -): void { +function useEffect(effectFunc: () => (() => void) | void, deps: Array | void | null, effectType: number): void { const stage = getHookStage(); if (stage === null) { throwNotInFuncError(); diff --git a/libs/horizon/src/renderer/hooks/UseImperativeHook.ts b/libs/horizon/src/renderer/hooks/UseImperativeHook.ts index 19c466a4..b9f6d581 100644 --- a/libs/horizon/src/renderer/hooks/UseImperativeHook.ts +++ b/libs/horizon/src/renderer/hooks/UseImperativeHook.ts @@ -13,15 +13,15 @@ * See the Mulan PSL v2 for more details. */ -import {useLayoutEffectImpl} from './UseEffectHook'; -import {getHookStage} from './HookStage'; -import {throwNotInFuncError} from './BaseHook'; -import type {Ref} from './HookType'; +import { useLayoutEffectImpl } from './UseEffectHook'; +import { getHookStage } from './HookStage'; +import { throwNotInFuncError } from './BaseHook'; +import type { Ref } from './HookType'; export function useImperativeHandleImpl( ref: { current: R | null } | ((any) => any) | null | void, func: () => R, - dependencies?: Array | null, + dependencies?: Array | null ): void { const stage = getHookStage(); if (stage === null) { @@ -36,10 +36,7 @@ function isNotNull(object: any): boolean { return object !== null && object !== undefined; } -function effectFunc( - func: () => R, - ref: Ref | ((any) => any) | null, -): (() => void) | void { +function effectFunc(func: () => R, ref: Ref | ((any) => any) | null): (() => void) | void { if (typeof ref === 'function') { const value = func(); ref(value); diff --git a/libs/horizon/src/renderer/hooks/UseMemoHook.ts b/libs/horizon/src/renderer/hooks/UseMemoHook.ts index db12d545..5b72a055 100644 --- a/libs/horizon/src/renderer/hooks/UseMemoHook.ts +++ b/libs/horizon/src/renderer/hooks/UseMemoHook.ts @@ -13,13 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import { - createHook, - getCurrentHook, - throwNotInFuncError -} from './BaseHook'; -import {getHookStage, HookStage} from './HookStage'; -import {isArrayEqual} from '../utils/compare'; +import { createHook, getCurrentHook, throwNotInFuncError } from './BaseHook'; +import { getHookStage, HookStage } from './HookStage'; +import { isArrayEqual } from '../utils/compare'; export function useMemoImpl(fun: () => V, deps?: Array | null): V { const stage = getHookStage(); @@ -45,6 +41,6 @@ export function useMemoImpl(fun: () => V, deps?: Array | null): V { result = fun(); } - hook.state = {result, dependencies: nextDeps}; + hook.state = { result, dependencies: nextDeps }; return hook.state.result; } diff --git a/libs/horizon/src/renderer/hooks/UseRefHook.ts b/libs/horizon/src/renderer/hooks/UseRefHook.ts index e09cb3db..a9e597fb 100644 --- a/libs/horizon/src/renderer/hooks/UseRefHook.ts +++ b/libs/horizon/src/renderer/hooks/UseRefHook.ts @@ -13,9 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import {createHook, getCurrentHook, throwNotInFuncError} from './BaseHook'; -import {getHookStage, HookStage} from './HookStage'; -import type {Ref} from './HookType'; +import { createHook, getCurrentHook, throwNotInFuncError } from './BaseHook'; +import { getHookStage, HookStage } from './HookStage'; +import type { Ref } from './HookType'; export function useRefImpl(value: V): Ref { const stage = getHookStage(); @@ -26,7 +26,7 @@ export function useRefImpl(value: V): Ref { let hook; if (stage === HookStage.Init) { hook = createHook(); - hook.state = {current: value}; + hook.state = { current: value }; } else if (stage === HookStage.Update) { hook = getCurrentHook(); } diff --git a/libs/horizon/src/renderer/hooks/UseStateHook.ts b/libs/horizon/src/renderer/hooks/UseStateHook.ts index 942f7d20..e7d10eb0 100644 --- a/libs/horizon/src/renderer/hooks/UseStateHook.ts +++ b/libs/horizon/src/renderer/hooks/UseStateHook.ts @@ -13,8 +13,8 @@ * See the Mulan PSL v2 for more details. */ -import type {Trigger} from './HookType'; -import {useReducerImpl} from './UseReducerHook'; +import type { Trigger } from './HookType'; +import { useReducerImpl } from './UseReducerHook'; function defaultReducer(state: S, action: ((S) => S) | S): S { // @ts-ignore diff --git a/libs/horizon/src/renderer/render/ClassComponent.ts b/libs/horizon/src/renderer/render/ClassComponent.ts index a90370ea..f486b6b4 100644 --- a/libs/horizon/src/renderer/render/ClassComponent.ts +++ b/libs/horizon/src/renderer/render/ClassComponent.ts @@ -30,9 +30,7 @@ import { } from './class/ClassLifeCycleProcessor'; import { FlagUtils, DidCapture } from '../vnode/VNodeFlags'; import { markRef } from './BaseComponent'; -import { - processUpdates, -} from '../UpdateHandler'; +import { processUpdates } from '../UpdateHandler'; import { setProcessingClassVNode } from '../GlobalVar'; import { onlyUpdateChildVNodes } from '../vnode/VNodeCreator'; import { createChildrenByDiff } from '../diff/nodeDiffComparator'; @@ -41,9 +39,7 @@ const emptyContextObj = {}; // 获取当前节点的context export function getCurrentContext(clazz, processing: VNode) { const context = clazz.contextType; - return typeof context === 'object' && context !== null - ? getNewContext(processing, context) - : emptyContextObj; + return typeof context === 'object' && context !== null ? getNewContext(processing, context) : emptyContextObj; } // 挂载实例 @@ -84,9 +80,7 @@ function createChildren(clazz: any, processing: VNode) { const isCatchError = (processing.flags & DidCapture) === DidCapture; // 按照已有规格,如果捕获了错误却没有定义getDerivedStateFromError函数,返回的child为null - const newElements = isCatchError && typeof clazz.getDerivedStateFromError !== 'function' - ? null - : inst.render(); + const newElements = isCatchError && typeof clazz.getDerivedStateFromError !== 'function' ? null : inst.render(); processing.child = createChildrenByDiff(processing, processing.child, newElements, !processing.isCreated); return processing.child; @@ -136,7 +130,8 @@ export function captureRender(processing: VNode): VNode | null { // 挂载新组件,一定会更新 mountInstance(ctor, processing, nextProps); shouldUpdate = true; - } else { // 更新 + } else { + // 更新 const newContext = getCurrentContext(ctor, processing); // 子节点抛出异常时,如果本class是个捕获异常的处理节点,这时候oldProps是null,所以需要使用props @@ -150,9 +145,7 @@ export function captureRender(processing: VNode): VNode | null { processUpdates(processing, inst, nextProps); // 如果 props, state, context 都没有变化且 isForceUpdate 为 false则不需要更新 - shouldUpdate = oldProps !== processing.props || - inst.state !== processing.state || - processing.isForceUpdate; + shouldUpdate = oldProps !== processing.props || inst.state !== processing.state || processing.isForceUpdate; if (shouldUpdate) { // derivedStateFromProps会修改nextState,因此需要调用 diff --git a/libs/horizon/src/renderer/render/ContextConsumer.ts b/libs/horizon/src/renderer/render/ContextConsumer.ts index c072d536..7c945816 100644 --- a/libs/horizon/src/renderer/render/ContextConsumer.ts +++ b/libs/horizon/src/renderer/render/ContextConsumer.ts @@ -13,9 +13,9 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode, ContextType} from '../Types'; +import type { VNode, ContextType } from '../Types'; -import {resetDepContexts, getNewContext} from '../components/context/Context'; +import { resetDepContexts, getNewContext } from '../components/context/Context'; import { createChildrenByDiff } from '../diff/nodeDiffComparator'; function captureContextConsumer(processing: VNode) { @@ -36,4 +36,3 @@ export function captureRender(processing: VNode): VNode | null { } export function bubbleRender() {} - diff --git a/libs/horizon/src/renderer/render/ContextProvider.ts b/libs/horizon/src/renderer/render/ContextProvider.ts index 103a302e..1eadd6cc 100644 --- a/libs/horizon/src/renderer/render/ContextProvider.ts +++ b/libs/horizon/src/renderer/render/ContextProvider.ts @@ -18,10 +18,7 @@ import type { VNode, ContextType, ProviderType } from '../Types'; import { isSame } from '../utils/compare'; import { ClassComponent, ContextProvider } from '../vnode/VNodeTags'; import { pushForceUpdate } from '../UpdateHandler'; -import { - resetContext, - setContext, -} from '../ContextSaver'; +import { resetContext, setContext } from '../ContextSaver'; import { travelVNodeTree } from '../vnode/VNodeUtils'; import { launchUpdateFromVNode } from '../TreeBuilder'; import { onlyUpdateChildVNodes } from '../vnode/VNodeCreator'; @@ -62,15 +59,20 @@ function handleContextChange(processing: VNode, context: ContextType): void let isMatch = false; // 从vNode开始遍历 - travelVNodeTree(vNode, node => { - const depContexts = node.depContexts; - if (depContexts && depContexts.length) { - isMatch = matchDependencies(depContexts, context, node) ?? isMatch; - } - }, node => - // 如果这是匹配的provider,则不要更深入地扫描 - node.tag === ContextProvider && node.type === processing.type - , processing, null); + travelVNodeTree( + vNode, + node => { + const depContexts = node.depContexts; + if (depContexts && depContexts.length) { + isMatch = matchDependencies(depContexts, context, node) ?? isMatch; + } + }, + node => + // 如果这是匹配的provider,则不要更深入地扫描 + node.tag === ContextProvider && node.type === processing.type, + processing, + null + ); // 找到了依赖context的子节点,触发一次更新 if (isMatch) { @@ -117,4 +119,3 @@ export function captureRender(processing: VNode): VNode | null { export function bubbleRender(processing: VNode) { resetContext(processing); } - diff --git a/libs/horizon/src/renderer/render/DomComponent.ts b/libs/horizon/src/renderer/render/DomComponent.ts index 0419878e..2eaef98b 100644 --- a/libs/horizon/src/renderer/render/DomComponent.ts +++ b/libs/horizon/src/renderer/render/DomComponent.ts @@ -16,28 +16,15 @@ import type { VNode } from '../Types'; import type { Props } from '../../dom/DOMOperator'; -import { - getNamespaceCtx, - setNamespaceCtx, - resetNamespaceCtx, -} from '../ContextSaver'; -import { - appendChildElement, - newDom, - initDomProps, getPropChangeList, - isTextChild, -} from '../../dom/DOMOperator'; +import { getNamespaceCtx, setNamespaceCtx, resetNamespaceCtx } from '../ContextSaver'; +import { appendChildElement, newDom, initDomProps, getPropChangeList, isTextChild } from '../../dom/DOMOperator'; import { FlagUtils } from '../vnode/VNodeFlags'; import { markRef } from './BaseComponent'; import { DomComponent, DomPortal, DomText } from '../vnode/VNodeTags'; import { travelVNodeTree } from '../vnode/VNodeUtils'; import { createChildrenByDiff } from '../diff/nodeDiffComparator'; -function updateDom( - processing: VNode, - type: any, - newProps: Props, -) { +function updateDom(processing: VNode, type: any, newProps: Props) { // 如果oldProps !== newProps,意味着存在更新,并且需要处理其相关的副作用 const oldProps = processing.oldProps; if (oldProps === newProps) { @@ -47,12 +34,7 @@ function updateDom( const dom: Element = processing.realNode; - const changeList = getPropChangeList( - dom, - type, - oldProps, - newProps, - ); + const changeList = getPropChangeList(dom, type, oldProps, newProps); // 输入类型的直接标记更新 if (type === 'input' || type === 'textarea' || type === 'select' || type === 'option') { @@ -74,11 +56,7 @@ export function bubbleRender(processing: VNode) { const newProps = processing.props; if (!processing.isCreated && processing.realNode != null) { // 更新dom属性 - updateDom( - processing, - type, - newProps, - ); + updateDom(processing, type, newProps); if (processing.oldRef !== processing.ref) { FlagUtils.markRef(processing); @@ -87,25 +65,25 @@ export function bubbleRender(processing: VNode) { const parentNamespace = getNamespaceCtx(); // 创建dom - const dom = newDom( - type, - newProps, - parentNamespace, - processing, - ); + const dom = newDom(type, newProps, parentNamespace, processing); // 把dom类型的子节点append到parent dom中 const vNode = processing.child; if (vNode !== null) { // 向下递归它的子节点,查找所有终端节点。 - travelVNodeTree(vNode, node => { - if (node.tag === DomComponent || node.tag === DomText) { - appendChildElement(dom, node.realNode); - } - }, node => - // 已经append到父节点,或者是DomPortal都不需要处理child了 - node.tag === DomComponent || node.tag === DomText || node.tag === DomPortal - , processing, null); + travelVNodeTree( + vNode, + node => { + if (node.tag === DomComponent || node.tag === DomText) { + appendChildElement(dom, node.realNode); + } + }, + node => + // 已经append到父节点,或者是DomPortal都不需要处理child了 + node.tag === DomComponent || node.tag === DomText || node.tag === DomPortal, + processing, + null + ); } processing.realNode = dom; diff --git a/libs/horizon/src/renderer/render/DomText.ts b/libs/horizon/src/renderer/render/DomText.ts index 6ed00173..6f46901c 100644 --- a/libs/horizon/src/renderer/render/DomText.ts +++ b/libs/horizon/src/renderer/render/DomText.ts @@ -13,11 +13,11 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from '../Types'; +import type { VNode } from '../Types'; -import {throwIfTrue} from '../utils/throwIfTrue'; -import {newTextDom} from '../../dom/DOMOperator'; -import {FlagUtils} from '../vnode/VNodeFlags'; +import { throwIfTrue } from '../utils/throwIfTrue'; +import { newTextDom } from '../../dom/DOMOperator'; +import { FlagUtils } from '../vnode/VNodeFlags'; export function captureRender(): VNode | null { return null; @@ -26,25 +26,24 @@ export function captureRender(): VNode | null { export function bubbleRender(processing: VNode) { const newText = processing.props; - if (!processing.isCreated && processing.realNode != null) { // 更新 + if (!processing.isCreated && processing.realNode != null) { + // 更新 const oldText = processing.oldProps; // 如果文本不同,将其标记为更新 if (oldText !== newText) { FlagUtils.markUpdate(processing); } - } else { // 初始化 + } else { + // 初始化 if (typeof newText !== 'string') { // 如果存在bug,可能出现这种情况 throwIfTrue( processing.realNode === null, 'We must have new text for new mounted node. This error is likely ' + - 'caused by a bug in Horizon. Please file an issue.', + 'caused by a bug in Horizon. Please file an issue.' ); } // 获得对应节点 - processing.realNode = newTextDom( - newText, - processing, - ); + processing.realNode = newTextDom(newText, processing); } } diff --git a/libs/horizon/src/renderer/render/ForwardRef.ts b/libs/horizon/src/renderer/render/ForwardRef.ts index 67e21370..960a4763 100644 --- a/libs/horizon/src/renderer/render/ForwardRef.ts +++ b/libs/horizon/src/renderer/render/ForwardRef.ts @@ -13,12 +13,11 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from '../Types'; -import {captureRender as funCaptureRender} from './FunctionComponent'; +import type { VNode } from '../Types'; +import { captureRender as funCaptureRender } from './FunctionComponent'; export function captureRender(processing: VNode): VNode | null { return funCaptureRender(processing); } export function bubbleRender() {} - diff --git a/libs/horizon/src/renderer/render/Fragment.ts b/libs/horizon/src/renderer/render/Fragment.ts index 6a80ff23..8947c27d 100644 --- a/libs/horizon/src/renderer/render/Fragment.ts +++ b/libs/horizon/src/renderer/render/Fragment.ts @@ -13,7 +13,7 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from '../Types'; +import type { VNode } from '../Types'; import { createChildrenByDiff } from '../diff/nodeDiffComparator'; export function bubbleRender() {} diff --git a/libs/horizon/src/renderer/render/FunctionComponent.ts b/libs/horizon/src/renderer/render/FunctionComponent.ts index 4638c2d7..c9ddcc8c 100644 --- a/libs/horizon/src/renderer/render/FunctionComponent.ts +++ b/libs/horizon/src/renderer/render/FunctionComponent.ts @@ -26,14 +26,11 @@ import { createChildrenByDiff } from '../diff/nodeDiffComparator'; // 在useState, useReducer的时候,会触发state变化 let stateChange = false; -export function bubbleRender() { -} +export function bubbleRender() {} // 判断children是否可以复用 function checkIfCanReuseChildren(processing: VNode) { - return !processing.isCreated && - processing.oldProps === processing.props && - !processing.isDepContextChange; + return !processing.isCreated && processing.oldProps === processing.props && !processing.isDepContextChange; } export function setStateChange(isUpdate) { @@ -44,11 +41,7 @@ export function isStateChange() { return stateChange; } -export function captureFunctionComponent( - processing: VNode, - funcComp: any, - nextProps: any, -) { +export function captureFunctionComponent(processing: VNode, funcComp: any, nextProps: any) { // 函数组件内已完成异步动作 if (processing.isSuspended) { // 由于首次被打断,应仍为首次渲染 @@ -67,7 +60,7 @@ export function captureFunctionComponent( processing.tag === ForwardRef ? funcComp.render : funcComp, nextProps, processing.tag === ForwardRef ? processing.ref : undefined, - processing, + processing ); // 这里需要判断是否可以复用,因为函数组件比起其他组件,多了context、stateChange、或者store改变了 三个因素 @@ -86,15 +79,7 @@ export function captureFunctionComponent( export function captureRender(processing: VNode): VNode | null { const Component = processing.type; const unresolvedProps = processing.props; - const resolvedProps = - processing.isLazyComponent - ? mergeDefaultProps(Component, unresolvedProps) - : unresolvedProps; + const resolvedProps = processing.isLazyComponent ? mergeDefaultProps(Component, unresolvedProps) : unresolvedProps; - return captureFunctionComponent( - processing, - Component, - resolvedProps, - ); + return captureFunctionComponent(processing, Component, resolvedProps); } - diff --git a/libs/horizon/src/renderer/render/LazyComponent.ts b/libs/horizon/src/renderer/render/LazyComponent.ts index 152e541e..a385aa3d 100644 --- a/libs/horizon/src/renderer/render/LazyComponent.ts +++ b/libs/horizon/src/renderer/render/LazyComponent.ts @@ -17,18 +17,13 @@ import type { VNode } from '../Types'; import { FlagUtils } from '../vnode/VNodeFlags'; import { getLazyVNodeTag } from '../vnode/VNodeCreator'; -import { - ClassComponent, - ForwardRef, - FunctionComponent, - MemoComponent, -} from '../vnode/VNodeTags'; +import { ClassComponent, ForwardRef, FunctionComponent, MemoComponent } from '../vnode/VNodeTags'; import { throwIfTrue } from '../utils/throwIfTrue'; import { captureFunctionComponent } from './FunctionComponent'; import { captureRender as captureClassComponent } from './ClassComponent'; import { captureMemoComponent } from './MemoComponent'; -export function bubbleRender() { } +export function bubbleRender() {} const LazyRendererMap = { [FunctionComponent]: captureFunctionComponent, @@ -51,11 +46,7 @@ export function mergeDefaultProps(Component: any, props: object): object { return props; } -function captureLazyComponent( - processing, - lazyComponent, - shouldUpdate, -) { +function captureLazyComponent(processing, lazyComponent, shouldUpdate) { if (!processing.isCreated) { // 每次加载lazy都当作mount来处理 processing.isCreated = true; @@ -87,9 +78,9 @@ function captureLazyComponent( throwIfTrue( true, 'Element type is invalid. Received a promise that resolves to: %s. ' + - 'Lazy element type must resolve to a class or function.%s', + 'Lazy element type must resolve to a class or function.%s', Component, - '', + '' ); return null; } diff --git a/libs/horizon/src/renderer/render/SuspenseComponent.ts b/libs/horizon/src/renderer/render/SuspenseComponent.ts index 0b7b3d2e..82c04dee 100644 --- a/libs/horizon/src/renderer/render/SuspenseComponent.ts +++ b/libs/horizon/src/renderer/render/SuspenseComponent.ts @@ -17,12 +17,7 @@ import type { VNode, PromiseType } from '../Types'; import { FlagUtils, Interrupted } from '../vnode/VNodeFlags'; import { onlyUpdateChildVNodes, updateVNode, createFragmentVNode } from '../vnode/VNodeCreator'; -import { - ClassComponent, - ForwardRef, - FunctionComponent, - SuspenseComponent, -} from '../vnode/VNodeTags'; +import { ClassComponent, ForwardRef, FunctionComponent, SuspenseComponent } from '../vnode/VNodeTags'; import { pushForceUpdate } from '../UpdateHandler'; import { launchUpdateFromVNode, tryRenderFromRoot } from '../TreeBuilder'; import { updateShouldUpdateOfTree } from '../vnode/VNodeShouldUpdate'; @@ -141,11 +136,7 @@ function updateFallback(processing: VNode): Array | VNode | null { } export function captureRender(processing: VNode, shouldUpdate: boolean): Array | VNode | null { - if ( - !processing.isCreated && - processing.oldProps === processing.props && - !shouldUpdate - ) { + if (!processing.isCreated && processing.oldProps === processing.props && !shouldUpdate) { if (processing.suspenseState.childStatus === SuspenseChildStatus.ShowFallback) { // 当显示fallback时,suspense的子组件要更新 return updateFallback(processing); @@ -158,8 +149,9 @@ export function captureRender(processing: VNode, shouldUpdate: boolean): Array object, - nextProps: object, + nextProps: object ) { if (getDerivedStateFromProps) { const oldState = processing.state; @@ -40,9 +35,7 @@ export function callDerivedStateFromProps( const newState = getDerivedStateFromProps(nextProps, oldState); // 组件未返回state,需要返回旧的preState - processing.state = newState === null || newState === undefined - ? oldState - : { ...oldState, ...newState }; + processing.state = newState === null || newState === undefined ? oldState : { ...oldState, ...newState }; } } @@ -68,7 +61,7 @@ export function callShouldComponentUpdate( oldProps: object, newProps: object, newState: object, - newContext: object, + newContext: object ) { const inst = processing.realNode; @@ -169,4 +162,3 @@ export function markComponentDidUpdate(processing: VNode) { FlagUtils.markUpdate(processing); } } - diff --git a/libs/horizon/src/renderer/render/index.ts b/libs/horizon/src/renderer/render/index.ts index dda8e9c0..d11c4191 100644 --- a/libs/horizon/src/renderer/render/index.ts +++ b/libs/horizon/src/renderer/render/index.ts @@ -44,9 +44,7 @@ import { SuspenseComponent, } from '../vnode/VNodeTags'; -export { - BaseComponentRender, -}; +export { BaseComponentRender }; export default { [ClassComponent]: ClassComponentRender, diff --git a/libs/horizon/src/renderer/submit/HookEffectHandler.ts b/libs/horizon/src/renderer/submit/HookEffectHandler.ts index 88e4b1fc..140eceef 100644 --- a/libs/horizon/src/renderer/submit/HookEffectHandler.ts +++ b/libs/horizon/src/renderer/submit/HookEffectHandler.ts @@ -17,16 +17,11 @@ * useEffect 和 useLayoutEffect的执行逻辑 */ -import type {VNode} from '../Types'; -import type { - Effect as HookEffect, - EffectList, -} from '../hooks/HookType'; -import {runAsync} from '../taskExecutor/TaskExecutor'; -import { - copyExecuteMode, InRender, setExecuteMode,changeMode -} from '../ExecuteMode'; -import {EffectConstant} from '../hooks/EffectConstant'; +import type { VNode } from '../Types'; +import type { Effect as HookEffect, EffectList } from '../hooks/HookType'; +import { runAsync } from '../taskExecutor/TaskExecutor'; +import { copyExecuteMode, InRender, setExecuteMode, changeMode } from '../ExecuteMode'; +import { EffectConstant } from '../hooks/EffectConstant'; let hookEffects: Array = []; let hookRemoveEffects: Array = []; @@ -44,7 +39,7 @@ export function callUseEffects(vNode: VNode) { const effectList: EffectList = vNode.effectList; if (effectList !== null) { effectList.forEach(effect => { - const {effectConstant} = effect; + const { effectConstant } = effect; if ( (effectConstant & EffectConstant.Effect) !== EffectConstant.NoEffect && (effectConstant & EffectConstant.DepsChange) !== EffectConstant.NoEffect @@ -69,7 +64,7 @@ export function runAsyncEffects() { // 调用effect destroy const removeEffects = hookRemoveEffects; hookRemoveEffects = []; - removeEffects.forEach((effect) => { + removeEffects.forEach(effect => { const destroy = effect.removeEffect; effect.removeEffect = undefined; @@ -85,7 +80,7 @@ export function runAsyncEffects() { // 调用effect create const createEffects = hookEffects; hookEffects = []; - createEffects.forEach((effect) => { + createEffects.forEach(effect => { try { const create = effect.effect; @@ -103,17 +98,19 @@ export function callEffectRemove(vNode: VNode) { const effectList: EffectList = vNode.effectList; if (effectList !== null) { effectList.forEach(effect => { - const {removeEffect, effectConstant} = effect; + const { removeEffect, effectConstant } = effect; if (removeEffect !== undefined) { - if ((effectConstant & EffectConstant.Effect) !== EffectConstant.NoEffect) { // 如果是useEffect,就异步调用 + if ((effectConstant & EffectConstant.Effect) !== EffectConstant.NoEffect) { + // 如果是useEffect,就异步调用 hookRemoveEffects.push(effect); if (!isScheduling) { isScheduling = true; runAsync(runAsyncEffects); } - } else { // 是useLayoutEffect,直接执行 + } else { + // 是useLayoutEffect,直接执行 removeEffect(); } } diff --git a/libs/horizon/src/renderer/submit/LifeCycleHandler.ts b/libs/horizon/src/renderer/submit/LifeCycleHandler.ts index f844b3de..cd3461b2 100644 --- a/libs/horizon/src/renderer/submit/LifeCycleHandler.ts +++ b/libs/horizon/src/renderer/submit/LifeCycleHandler.ts @@ -50,12 +50,7 @@ import { callUseLayoutEffectRemove, } from './HookEffectHandler'; import { handleSubmitError } from '../ErrorHandler'; -import { - travelVNodeTree, - clearVNode, - isDomVNode, - getSiblingDom, -} from '../vnode/VNodeUtils'; +import { travelVNodeTree, clearVNode, isDomVNode, getSiblingDom } from '../vnode/VNodeUtils'; import { shouldAutoFocus } from '../../dom/utils/Common'; function callComponentWillUnmount(vNode: VNode, instance: any) { @@ -67,13 +62,10 @@ function callComponentWillUnmount(vNode: VNode, instance: any) { } // 调用界面变化前的生命周期 -function callBeforeSubmitLifeCycles( - vNode: VNode, -): void { - if (vNode.tag === ClassComponent && !vNode.isCreated) { // 调用instance.getSnapshotBeforeUpdate - const prevProps = vNode.isLazyComponent - ? mergeDefaultProps(vNode.type, vNode.oldProps) - : vNode.oldProps; +function callBeforeSubmitLifeCycles(vNode: VNode): void { + if (vNode.tag === ClassComponent && !vNode.isCreated) { + // 调用instance.getSnapshotBeforeUpdate + const prevProps = vNode.isLazyComponent ? mergeDefaultProps(vNode.type, vNode.oldProps) : vNode.oldProps; const prevState = vNode.oldState; const instance = vNode.realNode; @@ -98,9 +90,7 @@ function callStateCallback(vNode: VNode, obj: any): void { } // 调用界面变化后的生命周期 -function callAfterSubmitLifeCycles( - vNode: VNode, -): void { +function callAfterSubmitLifeCycles(vNode: VNode): void { switch (vNode.tag) { case FunctionComponent: case ForwardRef: { @@ -116,17 +106,10 @@ function callAfterSubmitLifeCycles( if (vNode.isCreated) { instance.componentDidMount(); } else { - const prevProps = - vNode.isLazyComponent - ? mergeDefaultProps(vNode.type, vNode.oldProps) - : vNode.oldProps; + const prevProps = vNode.isLazyComponent ? mergeDefaultProps(vNode.type, vNode.oldProps) : vNode.oldProps; const prevState = vNode.oldState; - instance.componentDidUpdate( - prevProps, - prevState, - instance.__snapshotResult, - ); + instance.componentDidUpdate(prevProps, prevState, instance.__snapshotResult); } } @@ -152,17 +135,23 @@ function callAfterSubmitLifeCycles( } function hideOrUnhideAllChildren(vNode, isHidden) { - travelVNodeTree(vNode, (node: VNode) => { - const instance = node.realNode; + travelVNodeTree( + vNode, + (node: VNode) => { + const instance = node.realNode; - if (node.tag === DomComponent || node.tag === DomText) { - if (isHidden) { - hideDom(node.tag, instance); - } else { - unHideDom(node.tag, instance, node.props); + if (node.tag === DomComponent || node.tag === DomText) { + if (isHidden) { + hideDom(node.tag, instance); + } else { + unHideDom(node.tag, instance, node.props); + } } - } - }, null, vNode, null); + }, + null, + vNode, + null + ); } function attachRef(vNode: VNode) { @@ -172,7 +161,7 @@ function attachRef(vNode: VNode) { } function detachRef(vNode: VNode, isOldRef?: boolean) { - const ref = (isOldRef ? vNode.oldRef : vNode.ref); + const ref = isOldRef ? vNode.oldRef : vNode.ref; handleRef(vNode, ref, null); } @@ -233,12 +222,17 @@ function unmountVNode(vNode: VNode): void { // 卸载vNode,递归遍历子vNode function unmountNestedVNodes(vNode: VNode): void { - travelVNodeTree(vNode, (node) => { + travelVNodeTree( + vNode, + node => { unmountVNode(node); - }, node => + }, + node => // 如果是DomPortal,不需要遍历child - node.tag === DomPortal - , vNode, null); + node.tag === DomPortal, + vNode, + null + ); } function submitAddition(vNode: VNode): void { @@ -269,11 +263,7 @@ function submitAddition(vNode: VNode): void { insertOrAppendPlacementNode(vNode, before, parentDom); } -function insertOrAppendPlacementNode( - node: VNode, - beforeDom: Element | null, - parent: Element | Container, -): void { +function insertOrAppendPlacementNode(node: VNode, beforeDom: Element | null, parent: Element | Container): void { const { tag, realNode } = node; if (isDomVNode(node)) { @@ -305,42 +295,48 @@ function unmountDomComponents(vNode: VNode): void { // 这两个变量要一起更新 let currentParent; - travelVNodeTree(vNode, (node) => { - if (!currentParentIsValid) { - let parent = node.parent; - let tag; - while (parent !== null) { - tag = parent.tag; - if (tag === DomComponent || tag === TreeRoot || tag === DomPortal) { - currentParent = parent.realNode; - break; + travelVNodeTree( + vNode, + node => { + if (!currentParentIsValid) { + let parent = node.parent; + let tag; + while (parent !== null) { + tag = parent.tag; + if (tag === DomComponent || tag === TreeRoot || tag === DomPortal) { + currentParent = parent.realNode; + break; + } + parent = parent.parent; } - parent = parent.parent; + currentParentIsValid = true; } - currentParentIsValid = true; - } - if (node.tag === DomComponent || node.tag === DomText) { - // 卸载vNode,递归遍历子vNode - unmountNestedVNodes(node); + if (node.tag === DomComponent || node.tag === DomText) { + // 卸载vNode,递归遍历子vNode + unmountNestedVNodes(node); - // 在所有子项都卸载后,删除dom树中的节点 - removeChildDom(currentParent, node.realNode); - } else if (node.tag === DomPortal) { - if (node.child !== null) { - currentParent = node.realNode; + // 在所有子项都卸载后,删除dom树中的节点 + removeChildDom(currentParent, node.realNode); + } else if (node.tag === DomPortal) { + if (node.child !== null) { + currentParent = node.realNode; + } + } else { + unmountVNode(node); + } + }, + node => + // 如果是dom不用再遍历child + node.tag === DomComponent || node.tag === DomText, + vNode, + node => { + if (node.tag === DomPortal) { + // 当离开portal,需要重新设置parent + currentParentIsValid = false; } - } else { - unmountVNode(node); } - }, node => - // 如果是dom不用再遍历child - node.tag === DomComponent || node.tag === DomText, vNode, (node) => { - if (node.tag === DomPortal) { - // 当离开portal,需要重新设置parent - currentParentIsValid = false; - } - }); + ); } function submitClear(vNode: VNode): void { diff --git a/libs/horizon/src/renderer/submit/Submit.ts b/libs/horizon/src/renderer/submit/Submit.ts index 30ec1bf9..4ea6d47c 100644 --- a/libs/horizon/src/renderer/submit/Submit.ts +++ b/libs/horizon/src/renderer/submit/Submit.ts @@ -13,29 +13,26 @@ * See the Mulan PSL v2 for more details. */ -import type {VNode} from '../Types'; +import type { VNode } from '../Types'; -import {FlagUtils, Addition, Snapshot, ResetText, Ref, Update, Deletion, Clear, Callback} from '../vnode/VNodeFlags'; -import {prepareForSubmit, resetAfterSubmit} from '../../dom/DOMOperator'; -import {handleSubmitError} from '../ErrorHandler'; +import { FlagUtils, Addition, Snapshot, ResetText, Ref, Update, Deletion, Clear, Callback } from '../vnode/VNodeFlags'; +import { prepareForSubmit, resetAfterSubmit } from '../../dom/DOMOperator'; +import { handleSubmitError } from '../ErrorHandler'; import { attachRef, callAfterSubmitLifeCycles, - callBeforeSubmitLifeCycles, submitDeletion, submitAddition, - submitResetTextContent, submitUpdate, detachRef, submitClear, + callBeforeSubmitLifeCycles, + submitDeletion, + submitAddition, + submitResetTextContent, + submitUpdate, + detachRef, + submitClear, } from './LifeCycleHandler'; -import {tryRenderFromRoot} from '../TreeBuilder'; -import { - InRender, - copyExecuteMode, - setExecuteMode, - changeMode, -} from '../ExecuteMode'; -import { - isSchedulingEffects, - setSchedulingEffects, -} from './HookEffectHandler'; -import {getStartVNode} from '../GlobalVar'; +import { tryRenderFromRoot } from '../TreeBuilder'; +import { InRender, copyExecuteMode, setExecuteMode, changeMode } from '../ExecuteMode'; +import { isSchedulingEffects, setSchedulingEffects } from './HookEffectHandler'; +import { getStartVNode } from '../GlobalVar'; let rootThrowError = null; @@ -104,7 +101,7 @@ export function submitToRender(treeRoot) { function beforeSubmit(dirtyNodes: Array) { let node; const nodesLength = dirtyNodes.length; - for(let i = 0; i < nodesLength; i++) { + for (let i = 0; i < nodesLength; i++) { node = dirtyNodes[i]; try { if ((node.flags & Snapshot) === Snapshot) { @@ -123,7 +120,7 @@ function submit(dirtyNodes: Array) { let isUpdate; let isDeletion; let isClear; - for(let i = 0; i < nodesLength; i++) { + for (let i = 0; i < nodesLength; i++) { node = dirtyNodes[i]; try { if ((node.flags & ResetText) === ResetText) { @@ -170,7 +167,7 @@ function submit(dirtyNodes: Array) { function afterSubmit(dirtyNodes: Array) { let node; const nodesLength = dirtyNodes.length; - for(let i = 0; i < nodesLength; i++) { + for (let i = 0; i < nodesLength; i++) { node = dirtyNodes[i]; try { if ((node.flags & Update) === Update || (node.flags & Callback) === Callback) { diff --git a/libs/horizon/src/renderer/taskExecutor/BrowserAsync.ts b/libs/horizon/src/renderer/taskExecutor/BrowserAsync.ts index b9672e3d..28e17a84 100644 --- a/libs/horizon/src/renderer/taskExecutor/BrowserAsync.ts +++ b/libs/horizon/src/renderer/taskExecutor/BrowserAsync.ts @@ -21,7 +21,6 @@ let isMessageLoopRunning = false; let browserCallback = null; const { port1, port2 } = new MessageChannel(); - export function isOverTime() { return false; } @@ -36,7 +35,8 @@ const callRenderTasks = () => { // 执行callback const hasMoreTask = browserCallback(); - if (!hasMoreTask) { // 没有更多task + if (!hasMoreTask) { + // 没有更多task isMessageLoopRunning = false; browserCallback = null; } else { @@ -49,7 +49,6 @@ const callRenderTasks = () => { } }; - port1.onmessage = callRenderTasks; export function requestBrowserCallback(callback) { diff --git a/libs/horizon/src/renderer/taskExecutor/RenderQueue.ts b/libs/horizon/src/renderer/taskExecutor/RenderQueue.ts index 71fbfee5..0fe3e533 100644 --- a/libs/horizon/src/renderer/taskExecutor/RenderQueue.ts +++ b/libs/horizon/src/renderer/taskExecutor/RenderQueue.ts @@ -17,7 +17,7 @@ * 利用TaskExecutor的异步任务,封装一个renderQueue来执行同步的渲染callback */ -import {runAsync, cancelTask, ImmediatePriority} from './TaskExecutor'; +import { runAsync, cancelTask, ImmediatePriority } from './TaskExecutor'; type RenderCallback = () => RenderCallback | null; @@ -45,7 +45,7 @@ function callRenderQueue() { try { let callback; - while (callback = renderQueue.shift()) { + while ((callback = renderQueue.shift())) { callback(); } diff --git a/libs/horizon/src/renderer/taskExecutor/TaskExecutor.ts b/libs/horizon/src/renderer/taskExecutor/TaskExecutor.ts index 4345a461..8613cfca 100644 --- a/libs/horizon/src/renderer/taskExecutor/TaskExecutor.ts +++ b/libs/horizon/src/renderer/taskExecutor/TaskExecutor.ts @@ -18,10 +18,7 @@ */ import { Node } from '../taskExecutor/TaskQueue'; -import { - requestBrowserCallback, - isOverTime, -} from './BrowserAsync'; +import { requestBrowserCallback, isOverTime } from './BrowserAsync'; import { add, shift, first, remove } from './TaskQueue'; @@ -41,7 +38,7 @@ function callTasks() { isWaiting = false; isProcessing = true; - let task: Node | null= null; + let task: Node | null = null; try { task = first(); @@ -60,7 +57,8 @@ function callTasks() { if (task === first()) { shift(); - } else { // 执行任务中可能插入了新任务 + } else { + // 执行任务中可能插入了新任务 remove(task); } } else { @@ -77,7 +75,7 @@ function callTasks() { } } -function runAsync(callback, priorityLevel= NormalPriority) { +function runAsync(callback, priorityLevel = NormalPriority) { let increment; switch (priorityLevel) { case ImmediatePriority: @@ -109,9 +107,4 @@ function cancelTask(task) { task.callback = null; } -export { - ImmediatePriority, - NormalPriority, - runAsync, - cancelTask, -}; +export { ImmediatePriority, NormalPriority, runAsync, cancelTask }; diff --git a/libs/horizon/src/renderer/utils/compare.ts b/libs/horizon/src/renderer/utils/compare.ts index b7c039b3..eb04a627 100644 --- a/libs/horizon/src/renderer/utils/compare.ts +++ b/libs/horizon/src/renderer/utils/compare.ts @@ -57,10 +57,10 @@ export function shallowCompare(paramX: any, paramY: any): boolean { return false; } - return keysX.every((key, i) => - Object.prototype.hasOwnProperty.call(paramY, key) && isSame(paramX[key], paramY[keysX[i]]) + return keysX.every( + (key, i) => Object.prototype.hasOwnProperty.call(paramY, key) && isSame(paramX[key], paramY[keysX[i]]) ); } - return false; + return false; } diff --git a/libs/horizon/src/renderer/utils/throwIfTrue.ts b/libs/horizon/src/renderer/utils/throwIfTrue.ts index c5c326b9..79c792a0 100644 --- a/libs/horizon/src/renderer/utils/throwIfTrue.ts +++ b/libs/horizon/src/renderer/utils/throwIfTrue.ts @@ -20,7 +20,7 @@ export function throwIfTrue(condition: boolean, errTemplate: string, ...errExpre // 将%s 替换成对应的变量 const msg = errTemplate.split('%s').reduce((prevSentence: string, part: string, idx: number) => { // %s对应的变量 - const expression = idx < errExpressions.length ? errExpressions[idx] : '' ; + const expression = idx < errExpressions.length ? errExpressions[idx] : ''; return prevSentence + part + expression; }, ''); throw Error(msg); diff --git a/libs/horizon/src/renderer/vnode/VNode.ts b/libs/horizon/src/renderer/vnode/VNode.ts index 1bf707f7..1cea3243 100644 --- a/libs/horizon/src/renderer/vnode/VNode.ts +++ b/libs/horizon/src/renderer/vnode/VNode.ts @@ -32,10 +32,10 @@ import { Profiler, MemoComponent, } from './VNodeTags'; -import type {VNodeTag} from './VNodeTags'; -import type {RefType, ContextType, SuspenseState, Source} from '../Types'; -import type {Hook} from '../hooks/HookType'; -import {InitFlag} from './VNodeFlags'; +import type { VNodeTag } from './VNodeTags'; +import type { RefType, ContextType, SuspenseState, Source } from '../Types'; +import type { Hook } from '../hooks/HookType'; +import { InitFlag } from './VNodeFlags'; export class VNode { tag: VNodeTag; diff --git a/libs/horizon/src/renderer/vnode/VNodeCreator.ts b/libs/horizon/src/renderer/vnode/VNodeCreator.ts index cc596c03..6b96e49e 100644 --- a/libs/horizon/src/renderer/vnode/VNodeCreator.ts +++ b/libs/horizon/src/renderer/vnode/VNodeCreator.ts @@ -74,7 +74,7 @@ export function getLazyVNodeTag(lazyComp: any): string { } else if (lazyComp !== undefined && lazyComp !== null && typeLazyMap[lazyComp.vtype]) { return typeLazyMap[lazyComp.vtype]; } - throw Error('Horizon can\'t resolve the content of lazy'); + throw Error("Horizon can't resolve the content of lazy"); } // 创建processing diff --git a/libs/horizon/src/renderer/vnode/VNodeFlags.ts b/libs/horizon/src/renderer/vnode/VNodeFlags.ts index 95bb92e2..d1971106 100644 --- a/libs/horizon/src/renderer/vnode/VNodeFlags.ts +++ b/libs/horizon/src/renderer/vnode/VNodeFlags.ts @@ -19,22 +19,21 @@ import type { VNode } from './VNode'; - -export const InitFlag = /** */ 0; +export const InitFlag = /** */ 0; // vNode节点的flags -export const DirectAddition = /** */ 1 << 0; // 在本次更新前入股父dom没有子节点,说明本次可以直接添加至父节点,不需要通过 getSiblingDom 找到 before 节点 -export const Addition = /** */ 1 << 1; -export const Update = /** */ 1 << 2; -export const Deletion = /** */ 1 << 3; -export const ResetText =/** */ 1 << 4; -export const Callback = /** */ 1 << 5; -export const DidCapture =/** */ 1 << 6; -export const Ref = /** */ 1 << 7; -export const Snapshot = /** */ 1 << 8; -export const Interrupted = /** */ 1 << 9; // 被中断了,抛出错误的vNode以及它的父vNode -export const ShouldCapture =/** */ 1 << 11; -export const ForceUpdate = /** */ 1 << 12; // For suspense -export const Clear = /** */ 1 << 13; +export const DirectAddition = /** */ 1 << 0; // 在本次更新前入股父dom没有子节点,说明本次可以直接添加至父节点,不需要通过 getSiblingDom 找到 before 节点 +export const Addition = /** */ 1 << 1; +export const Update = /** */ 1 << 2; +export const Deletion = /** */ 1 << 3; +export const ResetText = /** */ 1 << 4; +export const Callback = /** */ 1 << 5; +export const DidCapture = /** */ 1 << 6; +export const Ref = /** */ 1 << 7; +export const Snapshot = /** */ 1 << 8; +export const Interrupted = /** */ 1 << 9; // 被中断了,抛出错误的vNode以及它的父vNode +export const ShouldCapture = /** */ 1 << 11; +export const ForceUpdate = /** */ 1 << 12; // For suspense +export const Clear = /** */ 1 << 13; const LifecycleEffectArr = Update | Callback | Ref | Snapshot; export class FlagUtils { @@ -44,7 +43,8 @@ export class FlagUtils { static removeLifecycleEffectFlags(node) { node.flags &= ~LifecycleEffectArr; } - static hasAnyFlag(node: VNode) { // 有标志位 + static hasAnyFlag(node: VNode) { + // 有标志位 return node.flags !== InitFlag; } @@ -97,4 +97,3 @@ export class FlagUtils { node.flags |= Clear; } } - diff --git a/libs/horizon/src/renderer/vnode/VNodeShouldUpdate.ts b/libs/horizon/src/renderer/vnode/VNodeShouldUpdate.ts index 9d9cb958..7530db0f 100644 --- a/libs/horizon/src/renderer/vnode/VNodeShouldUpdate.ts +++ b/libs/horizon/src/renderer/vnode/VNodeShouldUpdate.ts @@ -14,8 +14,8 @@ */ // 从当前节点向上遍历,更新shouldUpdate和childShouldUpdate -import {VNode} from './VNode'; -import {TreeRoot} from './VNodeTags'; +import { VNode } from './VNode'; +import { TreeRoot } from './VNodeTags'; export function updateShouldUpdateOfTree(vNode: VNode): VNode | null { vNode.shouldUpdate = true; @@ -70,7 +70,8 @@ export function updateParentsChildShouldUpdate(vNode: VNode) { let node = vNode.parent; const isShouldUpdate = vNode.shouldUpdate || vNode.childShouldUpdate; - if (isShouldUpdate) { // 开始节点是shouldUpdate或childShouldUpdate + if (isShouldUpdate) { + // 开始节点是shouldUpdate或childShouldUpdate // 更新从当前节点到根节点的childShouldUpdate为true setParentsChildShouldUpdate(node); } else { diff --git a/libs/horizon/src/renderer/vnode/VNodeUtils.ts b/libs/horizon/src/renderer/vnode/VNodeUtils.ts index 529ca3c4..6616d4c5 100644 --- a/libs/horizon/src/renderer/vnode/VNodeUtils.ts +++ b/libs/horizon/src/renderer/vnode/VNodeUtils.ts @@ -17,11 +17,11 @@ * 提供:vNode的“遍历”,“查找”,“判断”的相关工具方法 */ -import type {VNode} from '../Types'; +import type { VNode } from '../Types'; -import {DomComponent, DomPortal, DomText, TreeRoot} from './VNodeTags'; -import {isComment} from '../../dom/utils/Common'; -import {getNearestVNode} from '../../dom/DOMInternalKeys'; +import { DomComponent, DomPortal, DomText, TreeRoot } from './VNodeTags'; +import { isComment } from '../../dom/utils/Common'; +import { getNearestVNode } from '../../dom/DOMInternalKeys'; import { Addition, InitFlag } from './VNodeFlags'; export function travelChildren(beginVNode: VNode, handleVNode: Function, isFinish?: Function) { @@ -125,20 +125,22 @@ export function isDomVNode(node: VNode) { // 是容器类型的vNode function isDomContainer(vNode: VNode): boolean { - return ( - vNode.tag === DomComponent || - vNode.tag === TreeRoot || - vNode.tag === DomPortal - ); + return vNode.tag === DomComponent || vNode.tag === TreeRoot || vNode.tag === DomPortal; } export function findDomVNode(vNode: VNode): VNode | null { - return travelVNodeTree(vNode, (node) => { - if (node.tag === DomComponent || node.tag === DomText) { - return node; - } - return null; - }, null, vNode, null); + return travelVNodeTree( + vNode, + node => { + if (node.tag === DomComponent || node.tag === DomText) { + return node; + } + return null; + }, + null, + vNode, + null + ); } export function findDOMByClassInst(inst) {