wevu 7.1.4 → 7.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -6
- package/dist/dev/index.d.mts +3 -3
- package/dist/dev/index.mjs +3 -2
- package/dist/dev/package.mjs +1 -1
- package/dist/dev/reactivity/computed.d.mts +4 -0
- package/dist/dev/reactivity/computed.mjs +10 -1
- package/dist/dev/reactivity/computed.mjs.map +1 -1
- package/dist/dev/reactivity/reactive.mjs +27 -20
- package/dist/dev/reactivity/reactive.mjs.map +1 -1
- package/dist/dev/router/auto-routes.d.mts +8 -0
- package/dist/dev/router/auto-routes.mjs +11 -0
- package/dist/dev/router/auto-routes.mjs.map +1 -0
- package/dist/dev/router/createRouter.d.mts +2 -1
- package/dist/dev/router/createRouter.mjs +3 -4
- package/dist/dev/router/createRouter.mjs.map +1 -1
- package/dist/dev/router/navigationCore.d.mts +3 -2
- package/dist/dev/router/navigationCore.mjs +7 -7
- package/dist/dev/router/navigationCore.mjs.map +1 -1
- package/dist/dev/router/resolve.d.mts +3 -2
- package/dist/dev/router/resolve.mjs.map +1 -1
- package/dist/dev/router/routeSync.d.mts +1 -0
- package/dist/dev/router/types.d.mts +173 -78
- package/dist/dev/router/types.mjs.map +1 -1
- package/dist/dev/router/useRoute.d.mts +4 -3
- package/dist/dev/router/useRoute.mjs.map +1 -1
- package/dist/dev/router/useRouter.d.mts +2 -1
- package/dist/dev/router/useRouter.mjs.map +1 -1
- package/dist/dev/router.d.mts +19 -3
- package/dist/dev/routerInternal/location.d.mts +2 -0
- package/dist/dev/routerInternal/matching.d.mts +2 -0
- package/dist/dev/routerInternal/matching.mjs +1 -1
- package/dist/dev/routerInternal/matching.mjs.map +1 -1
- package/dist/dev/routerInternal/params.d.mts +2 -0
- package/dist/dev/routerInternal/params.mjs.map +1 -1
- package/dist/dev/routerInternal/records.d.mts +2 -0
- package/dist/dev/routerInternal/recordsWarnings.d.mts +2 -0
- package/dist/dev/routerInternal/shared.d.mts +9 -0
- package/dist/dev/routerInternal/snapshots.d.mts +2 -0
- package/dist/dev/runtime/hooks/base.mjs +5 -5
- package/dist/dev/runtime/hooks/base.mjs.map +1 -1
- package/dist/dev/runtime/platform.mjs +31 -24
- package/dist/dev/runtime/platform.mjs.map +1 -1
- package/dist/dev/runtime/register/component/alipay.mjs +72 -0
- package/dist/dev/runtime/register/component/alipay.mjs.map +1 -0
- package/dist/dev/runtime/register/component/registerNativeDefinition.mjs +5 -2
- package/dist/dev/runtime/register/component/registerNativeDefinition.mjs.map +1 -1
- package/dist/dev/store/actions.mjs +27 -29
- package/dist/dev/store/actions.mjs.map +1 -1
- package/dist/dev/store/base.mjs +152 -36
- package/dist/dev/store/base.mjs.map +1 -1
- package/dist/dev/store/define/create.mjs +92 -0
- package/dist/dev/store/define/create.mjs.map +1 -0
- package/dist/dev/store/define.d.mts +5 -16
- package/dist/dev/store/define.mjs +11 -15
- package/dist/dev/store/define.mjs.map +1 -1
- package/dist/dev/store/manager.d.mts +13 -5
- package/dist/dev/store/manager.mjs +55 -14
- package/dist/dev/store/manager.mjs.map +1 -1
- package/dist/dev/store/storeToRefs.d.mts +5 -7
- package/dist/dev/store/storeToRefs.mjs +10 -18
- package/dist/dev/store/storeToRefs.mjs.map +1 -1
- package/dist/dev/store/subscriptions.mjs +17 -0
- package/dist/dev/store/subscriptions.mjs.map +1 -0
- package/dist/dev/store/types.d.mts +85 -59
- package/dist/dev/store/types.mjs +11 -0
- package/dist/dev/store/types.mjs.map +1 -0
- package/dist/dev/store/utils.mjs +1 -37
- package/dist/dev/store/utils.mjs.map +1 -1
- package/dist/dev/store/view.mjs +56 -0
- package/dist/dev/store/view.mjs.map +1 -0
- package/dist/dev/store.d.mts +3 -3
- package/dist/dev/store.mjs +3 -2
- package/dist/dev/vue-demi.d.mts +3 -3
- package/dist/dev/vue-demi.mjs +3 -2
- package/dist/dev/vue-demi.mjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/reactivity/computed.d.mts +4 -0
- package/dist/reactivity/computed.mjs +1 -1
- package/dist/reactivity/reactive.mjs +1 -1
- package/dist/router/auto-routes.d.mts +7 -0
- package/dist/router/auto-routes.mjs +1 -0
- package/dist/router/createRouter.d.mts +2 -1
- package/dist/router/createRouter.mjs +1 -1
- package/dist/router/navigationCore.d.mts +3 -2
- package/dist/router/navigationCore.mjs +1 -1
- package/dist/router/resolve.d.mts +3 -2
- package/dist/router/routeSync.d.mts +1 -0
- package/dist/router/types.d.mts +173 -78
- package/dist/router/useRoute.d.mts +4 -3
- package/dist/router/useRouter.d.mts +2 -1
- package/dist/router.d.mts +18 -3
- package/dist/routerInternal/location.d.mts +2 -0
- package/dist/routerInternal/matching.d.mts +2 -0
- package/dist/routerInternal/matching.mjs +1 -1
- package/dist/routerInternal/params.d.mts +2 -0
- package/dist/routerInternal/records.d.mts +2 -0
- package/dist/routerInternal/recordsWarnings.d.mts +2 -0
- package/dist/routerInternal/shared.d.mts +9 -0
- package/dist/routerInternal/snapshots.d.mts +2 -0
- package/dist/runtime/hooks/base.mjs +1 -1
- package/dist/runtime/platform.mjs +1 -1
- package/dist/runtime/register/component/alipay.mjs +1 -0
- package/dist/runtime/register/component/registerNativeDefinition.mjs +1 -1
- package/dist/store/actions.mjs +1 -1
- package/dist/store/base.mjs +1 -1
- package/dist/store/define/create.mjs +1 -0
- package/dist/store/define.d.mts +5 -16
- package/dist/store/define.mjs +1 -1
- package/dist/store/manager.d.mts +13 -5
- package/dist/store/manager.mjs +1 -1
- package/dist/store/storeToRefs.d.mts +5 -7
- package/dist/store/storeToRefs.mjs +1 -1
- package/dist/store/subscriptions.mjs +1 -0
- package/dist/store/types.d.mts +85 -59
- package/dist/store/types.mjs +1 -0
- package/dist/store/utils.mjs +1 -1
- package/dist/store/view.mjs +1 -0
- package/dist/store.d.mts +3 -3
- package/dist/store.mjs +1 -1
- package/dist/vue-demi.d.mts +3 -3
- package/dist/vue-demi.mjs +1 -1
- package/package.json +29 -9
- package/dist/dev/store/define/optionsStyle.mjs +0 -117
- package/dist/dev/store/define/optionsStyle.mjs.map +0 -1
- package/dist/dev/store/define/setupStyle.mjs +0 -137
- package/dist/dev/store/define/setupStyle.mjs.map +0 -1
- package/dist/dev/store/define/shared.mjs +0 -81
- package/dist/dev/store/define/shared.mjs.map +0 -1
- package/dist/store/define/optionsStyle.mjs +0 -1
- package/dist/store/define/setupStyle.mjs +0 -1
- package/dist/store/define/shared.mjs +0 -1
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Vue 3 风格的小程序运行时,复用同款响应式与调度器,通过
|
|
|
8
8
|
- `defineComponent` + `setup` 生命周期钩子(onShow/onPageScroll/onShareAppMessage 等)自动注册微信小程序 `Component`(在微信中可用于页面/组件)
|
|
9
9
|
- 快照 diff + 去重调度,最小化 `setData` 体积,支持 `bindModel` / `useBindModel` 的双向绑定语法
|
|
10
10
|
- 插件、`app.config.globalProperties` 及小程序原生选项可自由组合
|
|
11
|
-
- 内置 `defineStore`/`storeToRefs`/`
|
|
11
|
+
- 内置 `defineStore`/`storeToRefs`/`createPinia`,支持 getters、actions、订阅与补丁
|
|
12
12
|
- TypeScript first,输出 ESM/CJS/types
|
|
13
13
|
|
|
14
14
|
## 安装
|
|
@@ -89,10 +89,24 @@ const users = useAsyncDerivation(({ signal }) => fetchUsers({ signal }))
|
|
|
89
89
|
|
|
90
90
|
## 状态管理
|
|
91
91
|
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
旧项目升级前请阅读 [Store 迁移指南](https://vite.weapp.dev/wevu/store-migration)。本次按 minor 发布,初始化、Setup 状态访问、重置和订阅行为仍需按指南迁移。
|
|
93
|
+
|
|
94
|
+
新代码推荐 `createPinia()`;旧名称 `createStore()` 为同一个函数,`StoreManager` 类型继续保留。只创建实例不会激活它。
|
|
95
|
+
|
|
96
|
+
在 `app.vue` 中安装一次 manager:
|
|
97
|
+
|
|
98
|
+
```vue
|
|
99
|
+
<script setup lang="ts">
|
|
100
|
+
import { createPinia, use } from 'wevu'
|
|
94
101
|
|
|
95
|
-
|
|
102
|
+
use(createPinia())
|
|
103
|
+
</script>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
使用 `createApp()` 时调用 `app.use(pinia)`;`use()` 只能在 app setup 中调用。定义 Store 并在安装后的页面/组件中使用:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { defineStore, storeToRefs } from 'wevu'
|
|
96
110
|
|
|
97
111
|
export const useCounter = defineStore('counter', {
|
|
98
112
|
state: () => ({ count: 0 }),
|
|
@@ -106,7 +120,7 @@ export const useCounter = defineStore('counter', {
|
|
|
106
120
|
},
|
|
107
121
|
})
|
|
108
122
|
|
|
109
|
-
//
|
|
123
|
+
// 在已安装 manager 的页面/组件内使用
|
|
110
124
|
const counter = useCounter()
|
|
111
125
|
const { count, doubled } = storeToRefs(counter)
|
|
112
126
|
counter.$subscribe(({ type }) => console.log('mutation', type))
|
|
@@ -115,7 +129,7 @@ counter.inc()
|
|
|
115
129
|
|
|
116
130
|
## 事件派发(emit)
|
|
117
131
|
|
|
118
|
-
在 `setup(props, ctx)` 中可使用 `ctx.emit(eventName, detail?, options?)
|
|
132
|
+
在 `setup(props, ctx)` 中可使用 `ctx.emit(eventName, detail?, options?)`,底层调用宿主事件能力。微信和抖音使用 `triggerEvent`;支付宝通过 `props.onXxx` 回调传递事件,并保留模板监听器需要的 `detail` 和数据集。支付宝回调不提供微信的冒泡、捕获和跨组件传播选项。
|
|
119
133
|
|
|
120
134
|
组件边界遵循 Vue 的大小写约定:camelCase prop 与事件会统一映射为小程序 kebab-case 宿主名称,例如 `maxQuantity` 映射为 `max-quantity`,`emit('quantityChange')` 可由父组件的 `@quantity-change` 监听。`update:modelValue` 等带冒号事件继续沿用既有的 `update-modelvalue` 映射。
|
|
121
135
|
|
package/dist/dev/index.d.mts
CHANGED
|
@@ -62,11 +62,11 @@ import { TemplateRef, useTemplateRef } from "./runtime/vueCompat/templateRef.mjs
|
|
|
62
62
|
import "./runtime/index.mjs";
|
|
63
63
|
import { ComponentTypeEmits, EmitFn, EmitsOptions } from "./macros/shared.mjs";
|
|
64
64
|
import { DefineModelModifiers, DefineModelTransformOptions, ModelRef, PageLayoutMeta, PageMeta, defineEmits, defineExpose, defineModel, defineOptions, definePageMeta, defineProps, defineSlots, withDefaults } from "./macros.mjs";
|
|
65
|
-
import { ActionContext, ActionSubscriber, DefineStoreOptions, MutationType, StoreManager, StoreSubscribeOptions, SubscriptionCallback } from "./store/types.mjs";
|
|
65
|
+
import { ActionContext, ActionSubscriber, DefineStoreOptions, MutationType, Pinia, PiniaCustomProperties, PiniaCustomStateProperties, PiniaPlugin, PiniaPluginContext, StateTree, StoreActions, StoreDefinition, StoreGeneric, StoreManager, StoreState, StoreSubscribeOptions, SubscriptionCallback, SubscriptionCallbackMutation } from "./store/types.mjs";
|
|
66
66
|
import { defineStore } from "./store/define.mjs";
|
|
67
|
-
import { createStore } from "./store/manager.mjs";
|
|
67
|
+
import { createPinia, createStore, disposePinia, getActivePinia, setActivePinia } from "./store/manager.mjs";
|
|
68
68
|
import { StoreToRefsResult, storeToRefs } from "./store/storeToRefs.mjs";
|
|
69
69
|
import "./store.mjs";
|
|
70
70
|
import { version } from "./version.mjs";
|
|
71
71
|
export * from "@wevu/web-apis";
|
|
72
|
-
export { type ActionContext, type ActionSubscriber, type AlipayMiniProgramHostNamespace, type AlipayMiniProgramHostSourceContract, type AllowedComponentProps, type AppConfig, type AsyncDerivation, type AsyncDerivationContext, type AsyncDerivationState, type AsyncDerivationStatus, type ComponentCustomProps, type ComponentDefinition, type ComponentOptionsMixin, type ComponentPropsOptions, type ComponentPublicInstance, type ComponentTypeEmits, type ComputedDefinitions, type ComputedGetter, type ComputedRef, type ComputedSetter, type CreateAppOptions, type CustomRefFactory, type CustomRefOptions, type CustomRefSource, type DataOption, type DefaultMiniProgramHostNamespace, type DefaultMiniProgramHostSourceContract, type DefineAppOptions, type DefineComponent, type DefineComponentOptions, type DefineComponentTypePropsOptions, type DefineComponentWithTypeProps, DefineModelModifiers, DefineModelTransformOptions, type DefineStoreOptions, DisposableBag, DisposableLike, DisposableMethodName, DisposableObject, type DouyinMiniProgramHostNamespace, type DouyinMiniProgramHostSourceContract, type EffectScope, ElementIntersectionObserverCallback, type EmitFn, type EmitsOptions, type ExtractComputed, type ExtractDefaultPropTypes, type ExtractMethods, type ExtractPropTypes, type ExtractPublicPropTypes, GlobalComponents, GlobalDirectives, type HostMiniProgramAddToFavoritesOption, type HostMiniProgramAppOptions, type HostMiniProgramAppTrivialInstance, type HostMiniProgramBehaviorIdentifier, type HostMiniProgramBoundingClientRectResult, type HostMiniProgramComponentAllFullProperty, type HostMiniProgramComponentAllProperty, type HostMiniProgramComponentBehaviorOptions, type HostMiniProgramComponentEmptyArray, type HostMiniProgramComponentInstance, type HostMiniProgramComponentMethodOption, type HostMiniProgramComponentPropertyOption, type HostMiniProgramComponentPropertyValue, type HostMiniProgramComponentShortProperty, type HostMiniProgramComponentTrivialInstance, type HostMiniProgramComponentTrivialOption, type HostMiniProgramIntersectionObserver, type HostMiniProgramIntersectionObserverOptions, type HostMiniProgramLaunchOptions, type HostMiniProgramMemoryWarningResult, type HostMiniProgramNavigateToOption, type HostMiniProgramNodesRef, type HostMiniProgramNodesRefFields, type HostMiniProgramPageLifetime, type HostMiniProgramPageNotFoundOptions, type HostMiniProgramPageResizeOption, type HostMiniProgramPageScrollOption, type HostMiniProgramPageTrivialInstance, type HostMiniProgramReLaunchOption, type HostMiniProgramRedirectToOption, type HostMiniProgramRouter, type HostMiniProgramSaveExitState, type HostMiniProgramScrollOffsetResult, type HostMiniProgramSelectorQuery, type HostMiniProgramShareAppMessageOption, type HostMiniProgramSwitchTabOption, type HostMiniProgramTabItemTapOption, type HostMiniProgramThemeChangeResult, type HostMiniProgramTriggerEventOptions, type HostMiniProgramUnhandledRejectionResult, type InferNativePropType, type InferNativeProps, type InferPropType, type InferProps, type InternalRuntimeState, type InternalRuntimeStateFields, type LayoutBridgeInstance, type LayoutHostBinding, type MapSources, type MaybeRef, type MaybeRefOrGetter, type MaybeUndefined, type MethodDefinitions, type MiniProgramAdapter, type HostMiniProgramAddToFavoritesOption as MiniProgramAddToFavoritesOption, type MiniProgramAppOptions, type MiniProgramBehaviorIdentifier, type HostMiniProgramBoundingClientRectResult as MiniProgramBoundingClientRectResult, type HostMiniProgramComponentAllFullProperty as MiniProgramComponentAllFullProperty, type HostMiniProgramComponentAllProperty as MiniProgramComponentAllProperty, type HostMiniProgramComponentBehaviorOptions as MiniProgramComponentBehaviorOptions, type HostMiniProgramComponentEmptyArray as MiniProgramComponentEmptyArray, type MiniProgramComponentInstance, type HostMiniProgramComponentMethodOption as MiniProgramComponentMethodOption, type MiniProgramComponentOptions, type HostMiniProgramComponentPropertyOption as MiniProgramComponentPropertyOption, type MiniProgramComponentPropertyValue, type MiniProgramComponentRawOptions, type HostMiniProgramComponentShortProperty as MiniProgramComponentShortProperty, type MiniProgramHostNamespace, type MiniProgramHostNamespaceBySource, type MiniProgramHostSourceName, type MiniProgramHostSourceRegistry, type MiniProgramInstance, type HostMiniProgramIntersectionObserver as MiniProgramIntersectionObserver, type HostMiniProgramIntersectionObserverOptions as MiniProgramIntersectionObserverOptions, type HostMiniProgramLaunchOptions as MiniProgramLaunchOptions, type HostMiniProgramMemoryWarningResult as MiniProgramMemoryWarningResult, type HostMiniProgramNavigateToOption as MiniProgramNavigateToOption, type HostMiniProgramNodesRef as MiniProgramNodesRef, type HostMiniProgramNodesRefFields as MiniProgramNodesRefFields, type HostMiniProgramPageLifetime as MiniProgramPageLifetime, type MiniProgramPageLifetimes, type HostMiniProgramPageNotFoundOptions as MiniProgramPageNotFoundOptions, type HostMiniProgramPageResizeOption as MiniProgramPageResizeOption, type HostMiniProgramPageScrollOption as MiniProgramPageScrollOption, type MiniProgramPlatformHostNamespaceBySource, type MiniProgramPlatformHostSourceName, type MiniProgramPlatformHostSourceRegistry, type HostMiniProgramReLaunchOption as MiniProgramReLaunchOption, type HostMiniProgramRedirectToOption as MiniProgramRedirectToOption, type HostMiniProgramRouter as MiniProgramRouter, type MiniProgramRouterNavigateToOption, type MiniProgramRouterReLaunchOption, type MiniProgramRouterRedirectToOption, type MiniProgramRouterSwitchTabOption, type MiniProgramRuntimeHostNamespaceBySource, type MiniProgramRuntimeHostSourceName, type MiniProgramRuntimeHostSourceRegistry, type HostMiniProgramSaveExitState as MiniProgramSaveExitState, type HostMiniProgramScrollOffsetResult as MiniProgramScrollOffsetResult, type HostMiniProgramSelectorQuery as MiniProgramSelectorQuery, type HostMiniProgramShareAppMessageOption as MiniProgramShareAppMessageOption, type HostMiniProgramSwitchTabOption as MiniProgramSwitchTabOption, type HostMiniProgramTabItemTapOption as MiniProgramTabItemTapOption, MiniProgramTemplateRefValue, type HostMiniProgramThemeChangeResult as MiniProgramThemeChangeResult, type HostMiniProgramUnhandledRejectionResult as MiniProgramUnhandledRejectionResult, type ModelBinding, type ModelBindingOptions, type ModelBindingPayload, type ModelModifiers, ModelRef, type MultiWatchSources, type MutationKind, type MutationOp, type MutationRecord, type MutationType, type NativeComponent, type NativePropType, type NativePropsOptions, type NativeTypeHint, type NativeTypedProperty, NavigationBarMetrics, type ObjectDirective, type OnCleanup, type PageFeatures, PageLayoutMeta, type PageLayoutState, PageMeta, PageStackSnapshot, type PrelinkReactiveTreeOptions, type PropConstructor, type PropOptions, type PropType, type PublicProps, PullDownRefreshHandler, type Ref, type RuntimeApp, type RuntimeInstance, type SetDataBindingDiagnostic, type SetDataDebugInfo, type SetDataSnapshotOptions, type SetupContext, type SetupContextIntersectionObserver, type SetupContextIntersectionObserverOptions, type SetupContextNativeInstance, type SetupContextRouter, type SetupContextSelectorQuery, type SetupContextWithTypeProps, type SetupFunction, type SetupFunctionWithTypeProps, type ShallowRef, type ShallowUnwrapRef, type StoreManager, type StoreSubscribeOptions, type StoreToRefsResult, type SubscriptionCallback, type TemplateRef, TemplateRefValue, TemplateRefs, type ToRefs, type HostMiniProgramTriggerEventOptions as TriggerEventOptions, type TtMiniProgramHostNamespace, type TtMiniProgramHostSourceContract, UpdatePerformanceListener, UpdatePerformanceListenerResult, UseAllBoundingClientRectOptions, UseAllScrollOffsetOptions, UseAllSelectorFieldsOptions, type UseAsyncDerivationOptions, UseAsyncPullDownRefreshOptions, UseBoundingClientRectOptions, UseElementIntersectionObserverOptions, UseElementIntersectionObserverReturn, UseIntersectionObserverOptions, UseIntersectionObserverResult, type UseModelOptions, UseNavigationBarMetricsOptions, UsePageScrollThrottleOptions, UsePageScrollThrottleStopHandle, UsePageStackOptions, UseScrollOffsetOptions, UseSelectorFieldsOptions, UseSelectorQueryOptions, UseUpdatePerformanceListenerStopHandle, type VNode, type VNodeProps, type WatchCallback, type WatchEffect, type WatchEffectOptions, type WatchMultiSources, type WatchOptions, type WatchScheduler, type WatchSource, type WatchSourceValue, type WatchSources, type WatchStopHandle, type WechatMiniProgramHostNamespace, type WechatMiniProgramHostSourceContract, type WevuComponentConstructor, type WevuDefaults, type WevuDefinedComponent, WevuGlobalComponents, WevuGlobalDirectives, type WevuPageLayoutMap, type WevuPlugin, type WevuTypedRouterRouteMap, type WritableComputedOptions, type WritableComputedRef, addMutationRecorder, batch, callHookList, callHookReturn, callUpdateHooks, computed, createApp, createStore, createWevuComponent, createWevuScopedSlotComponent, customRef, defineAppSetup, defineComponent, defineEmits, defineExpose, defineModel, defineOptions, definePageMeta, defineProps, defineSlots, defineStore, effect, effectScope, endBatch, getCurrentInstance, getCurrentPageStackSnapshot, getCurrentScope, getCurrentSetupContext, getDeepWatchStrategy, getNavigationBarMetrics, getReactiveVersion, hasInjectionContext, inject, injectGlobal, isNoSetData, isProxy, isRaw, isReactive, isReadonly, isRef, isShallowReactive, isShallowRef, markNoSetData, markRaw, mergeModels, mountRuntimeInstance, nextTick, normalizeClass, normalizeStyle, onActivated, onAddToFavorites, onAttached, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onDetached, onError, onErrorCaptured, onHide, onLaunch, onLoad, onMemoryWarning, onMounted, onMoved, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onResize, onRouteDone, onSaveExitState, onScopeDispose, onServerPrefetch, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, onUnmounted, onUpdated, prelinkReactiveTree, provide, provideGlobal, reactive, readonly, ref, registerApp, registerComponent, registerPageLayoutBridge, registerRuntimeLayoutHosts, removeMutationRecorder, resetWevuDefaults, resolveLayoutBridge, resolveLayoutHost, resolvePropValue, resolveRuntimePageLayoutName, runSetupFunction, setCurrentInstance, setCurrentSetupContext, setDeepWatchStrategy, setGlobalProvidedValue, setPageLayout, setRuntimeSetDataVisibility, setWevuDefaults, shallowReactive, shallowReadonly, shallowRef, startBatch, stop, storeToRefs, syncRuntimePageLayoutState, syncRuntimePageLayoutStateFromRuntime, teardownRuntimeInstance, toRaw, toRef, toRefs, toValue, touchReactive, traverse, triggerRef, unref, unregisterPageLayoutBridge, unregisterRuntimeLayoutHosts, use, useAsyncDerivation, useAsyncPullDownRefresh, useAttrs, useBindModel, useBoundingClientRect, useChangeModel, useCssModule, useDisposables, useElementIntersectionObserver, useIntersectionObserver, useLayoutBridge, useLayoutHosts, useModel, useNativeInstance, useNativePageRouter, useNativeRouter, useNavigationBarMetrics, usePageLayout, usePageScrollThrottle, usePageStack, useScrollOffset, useSelectorFields, useSelectorQuery, useSlots, useTemplateRef, useUpdatePerformanceListener, version, waitForLayoutHost, watch, watchEffect, watchPostEffect, watchSyncEffect, withDefaults };
|
|
72
|
+
export { type ActionContext, type ActionSubscriber, type AlipayMiniProgramHostNamespace, type AlipayMiniProgramHostSourceContract, type AllowedComponentProps, type AppConfig, type AsyncDerivation, type AsyncDerivationContext, type AsyncDerivationState, type AsyncDerivationStatus, type ComponentCustomProps, type ComponentDefinition, type ComponentOptionsMixin, type ComponentPropsOptions, type ComponentPublicInstance, type ComponentTypeEmits, type ComputedDefinitions, type ComputedGetter, type ComputedRef, type ComputedSetter, type CreateAppOptions, type CustomRefFactory, type CustomRefOptions, type CustomRefSource, type DataOption, type DefaultMiniProgramHostNamespace, type DefaultMiniProgramHostSourceContract, type DefineAppOptions, type DefineComponent, type DefineComponentOptions, type DefineComponentTypePropsOptions, type DefineComponentWithTypeProps, DefineModelModifiers, DefineModelTransformOptions, type DefineStoreOptions, DisposableBag, DisposableLike, DisposableMethodName, DisposableObject, type DouyinMiniProgramHostNamespace, type DouyinMiniProgramHostSourceContract, type EffectScope, ElementIntersectionObserverCallback, type EmitFn, type EmitsOptions, type ExtractComputed, type ExtractDefaultPropTypes, type ExtractMethods, type ExtractPropTypes, type ExtractPublicPropTypes, GlobalComponents, GlobalDirectives, type HostMiniProgramAddToFavoritesOption, type HostMiniProgramAppOptions, type HostMiniProgramAppTrivialInstance, type HostMiniProgramBehaviorIdentifier, type HostMiniProgramBoundingClientRectResult, type HostMiniProgramComponentAllFullProperty, type HostMiniProgramComponentAllProperty, type HostMiniProgramComponentBehaviorOptions, type HostMiniProgramComponentEmptyArray, type HostMiniProgramComponentInstance, type HostMiniProgramComponentMethodOption, type HostMiniProgramComponentPropertyOption, type HostMiniProgramComponentPropertyValue, type HostMiniProgramComponentShortProperty, type HostMiniProgramComponentTrivialInstance, type HostMiniProgramComponentTrivialOption, type HostMiniProgramIntersectionObserver, type HostMiniProgramIntersectionObserverOptions, type HostMiniProgramLaunchOptions, type HostMiniProgramMemoryWarningResult, type HostMiniProgramNavigateToOption, type HostMiniProgramNodesRef, type HostMiniProgramNodesRefFields, type HostMiniProgramPageLifetime, type HostMiniProgramPageNotFoundOptions, type HostMiniProgramPageResizeOption, type HostMiniProgramPageScrollOption, type HostMiniProgramPageTrivialInstance, type HostMiniProgramReLaunchOption, type HostMiniProgramRedirectToOption, type HostMiniProgramRouter, type HostMiniProgramSaveExitState, type HostMiniProgramScrollOffsetResult, type HostMiniProgramSelectorQuery, type HostMiniProgramShareAppMessageOption, type HostMiniProgramSwitchTabOption, type HostMiniProgramTabItemTapOption, type HostMiniProgramThemeChangeResult, type HostMiniProgramTriggerEventOptions, type HostMiniProgramUnhandledRejectionResult, type InferNativePropType, type InferNativeProps, type InferPropType, type InferProps, type InternalRuntimeState, type InternalRuntimeStateFields, type LayoutBridgeInstance, type LayoutHostBinding, type MapSources, type MaybeRef, type MaybeRefOrGetter, type MaybeUndefined, type MethodDefinitions, type MiniProgramAdapter, type HostMiniProgramAddToFavoritesOption as MiniProgramAddToFavoritesOption, type MiniProgramAppOptions, type MiniProgramBehaviorIdentifier, type HostMiniProgramBoundingClientRectResult as MiniProgramBoundingClientRectResult, type HostMiniProgramComponentAllFullProperty as MiniProgramComponentAllFullProperty, type HostMiniProgramComponentAllProperty as MiniProgramComponentAllProperty, type HostMiniProgramComponentBehaviorOptions as MiniProgramComponentBehaviorOptions, type HostMiniProgramComponentEmptyArray as MiniProgramComponentEmptyArray, type MiniProgramComponentInstance, type HostMiniProgramComponentMethodOption as MiniProgramComponentMethodOption, type MiniProgramComponentOptions, type HostMiniProgramComponentPropertyOption as MiniProgramComponentPropertyOption, type MiniProgramComponentPropertyValue, type MiniProgramComponentRawOptions, type HostMiniProgramComponentShortProperty as MiniProgramComponentShortProperty, type MiniProgramHostNamespace, type MiniProgramHostNamespaceBySource, type MiniProgramHostSourceName, type MiniProgramHostSourceRegistry, type MiniProgramInstance, type HostMiniProgramIntersectionObserver as MiniProgramIntersectionObserver, type HostMiniProgramIntersectionObserverOptions as MiniProgramIntersectionObserverOptions, type HostMiniProgramLaunchOptions as MiniProgramLaunchOptions, type HostMiniProgramMemoryWarningResult as MiniProgramMemoryWarningResult, type HostMiniProgramNavigateToOption as MiniProgramNavigateToOption, type HostMiniProgramNodesRef as MiniProgramNodesRef, type HostMiniProgramNodesRefFields as MiniProgramNodesRefFields, type HostMiniProgramPageLifetime as MiniProgramPageLifetime, type MiniProgramPageLifetimes, type HostMiniProgramPageNotFoundOptions as MiniProgramPageNotFoundOptions, type HostMiniProgramPageResizeOption as MiniProgramPageResizeOption, type HostMiniProgramPageScrollOption as MiniProgramPageScrollOption, type MiniProgramPlatformHostNamespaceBySource, type MiniProgramPlatformHostSourceName, type MiniProgramPlatformHostSourceRegistry, type HostMiniProgramReLaunchOption as MiniProgramReLaunchOption, type HostMiniProgramRedirectToOption as MiniProgramRedirectToOption, type HostMiniProgramRouter as MiniProgramRouter, type MiniProgramRouterNavigateToOption, type MiniProgramRouterReLaunchOption, type MiniProgramRouterRedirectToOption, type MiniProgramRouterSwitchTabOption, type MiniProgramRuntimeHostNamespaceBySource, type MiniProgramRuntimeHostSourceName, type MiniProgramRuntimeHostSourceRegistry, type HostMiniProgramSaveExitState as MiniProgramSaveExitState, type HostMiniProgramScrollOffsetResult as MiniProgramScrollOffsetResult, type HostMiniProgramSelectorQuery as MiniProgramSelectorQuery, type HostMiniProgramShareAppMessageOption as MiniProgramShareAppMessageOption, type HostMiniProgramSwitchTabOption as MiniProgramSwitchTabOption, type HostMiniProgramTabItemTapOption as MiniProgramTabItemTapOption, MiniProgramTemplateRefValue, type HostMiniProgramThemeChangeResult as MiniProgramThemeChangeResult, type HostMiniProgramUnhandledRejectionResult as MiniProgramUnhandledRejectionResult, type ModelBinding, type ModelBindingOptions, type ModelBindingPayload, type ModelModifiers, ModelRef, type MultiWatchSources, type MutationKind, type MutationOp, type MutationRecord, MutationType, type NativeComponent, type NativePropType, type NativePropsOptions, type NativeTypeHint, type NativeTypedProperty, NavigationBarMetrics, type ObjectDirective, type OnCleanup, type PageFeatures, PageLayoutMeta, type PageLayoutState, PageMeta, PageStackSnapshot, type Pinia, type PiniaCustomProperties, type PiniaCustomStateProperties, type PiniaPlugin, type PiniaPluginContext, type PrelinkReactiveTreeOptions, type PropConstructor, type PropOptions, type PropType, type PublicProps, PullDownRefreshHandler, type Ref, type RuntimeApp, type RuntimeInstance, type SetDataBindingDiagnostic, type SetDataDebugInfo, type SetDataSnapshotOptions, type SetupContext, type SetupContextIntersectionObserver, type SetupContextIntersectionObserverOptions, type SetupContextNativeInstance, type SetupContextRouter, type SetupContextSelectorQuery, type SetupContextWithTypeProps, type SetupFunction, type SetupFunctionWithTypeProps, type ShallowRef, type ShallowUnwrapRef, type StateTree, type StoreActions, type StoreDefinition, type StoreGeneric, type StoreManager, type StoreState, type StoreSubscribeOptions, type StoreToRefsResult, type SubscriptionCallback, type SubscriptionCallbackMutation, type TemplateRef, TemplateRefValue, TemplateRefs, type ToRefs, type HostMiniProgramTriggerEventOptions as TriggerEventOptions, type TtMiniProgramHostNamespace, type TtMiniProgramHostSourceContract, UpdatePerformanceListener, UpdatePerformanceListenerResult, UseAllBoundingClientRectOptions, UseAllScrollOffsetOptions, UseAllSelectorFieldsOptions, type UseAsyncDerivationOptions, UseAsyncPullDownRefreshOptions, UseBoundingClientRectOptions, UseElementIntersectionObserverOptions, UseElementIntersectionObserverReturn, UseIntersectionObserverOptions, UseIntersectionObserverResult, type UseModelOptions, UseNavigationBarMetricsOptions, UsePageScrollThrottleOptions, UsePageScrollThrottleStopHandle, UsePageStackOptions, UseScrollOffsetOptions, UseSelectorFieldsOptions, UseSelectorQueryOptions, UseUpdatePerformanceListenerStopHandle, type VNode, type VNodeProps, type WatchCallback, type WatchEffect, type WatchEffectOptions, type WatchMultiSources, type WatchOptions, type WatchScheduler, type WatchSource, type WatchSourceValue, type WatchSources, type WatchStopHandle, type WechatMiniProgramHostNamespace, type WechatMiniProgramHostSourceContract, type WevuComponentConstructor, type WevuDefaults, type WevuDefinedComponent, WevuGlobalComponents, WevuGlobalDirectives, type WevuPageLayoutMap, type WevuPlugin, type WevuTypedRouterRouteMap, type WritableComputedOptions, type WritableComputedRef, addMutationRecorder, batch, callHookList, callHookReturn, callUpdateHooks, computed, createApp, createPinia, createStore, createWevuComponent, createWevuScopedSlotComponent, customRef, defineAppSetup, defineComponent, defineEmits, defineExpose, defineModel, defineOptions, definePageMeta, defineProps, defineSlots, defineStore, disposePinia, effect, effectScope, endBatch, getActivePinia, getCurrentInstance, getCurrentPageStackSnapshot, getCurrentScope, getCurrentSetupContext, getDeepWatchStrategy, getNavigationBarMetrics, getReactiveVersion, hasInjectionContext, inject, injectGlobal, isNoSetData, isProxy, isRaw, isReactive, isReadonly, isRef, isShallowReactive, isShallowRef, markNoSetData, markRaw, mergeModels, mountRuntimeInstance, nextTick, normalizeClass, normalizeStyle, onActivated, onAddToFavorites, onAttached, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onDetached, onError, onErrorCaptured, onHide, onLaunch, onLoad, onMemoryWarning, onMounted, onMoved, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onResize, onRouteDone, onSaveExitState, onScopeDispose, onServerPrefetch, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, onUnmounted, onUpdated, prelinkReactiveTree, provide, provideGlobal, reactive, readonly, ref, registerApp, registerComponent, registerPageLayoutBridge, registerRuntimeLayoutHosts, removeMutationRecorder, resetWevuDefaults, resolveLayoutBridge, resolveLayoutHost, resolvePropValue, resolveRuntimePageLayoutName, runSetupFunction, setActivePinia, setCurrentInstance, setCurrentSetupContext, setDeepWatchStrategy, setGlobalProvidedValue, setPageLayout, setRuntimeSetDataVisibility, setWevuDefaults, shallowReactive, shallowReadonly, shallowRef, startBatch, stop, storeToRefs, syncRuntimePageLayoutState, syncRuntimePageLayoutStateFromRuntime, teardownRuntimeInstance, toRaw, toRef, toRefs, toValue, touchReactive, traverse, triggerRef, unref, unregisterPageLayoutBridge, unregisterRuntimeLayoutHosts, use, useAsyncDerivation, useAsyncPullDownRefresh, useAttrs, useBindModel, useBoundingClientRect, useChangeModel, useCssModule, useDisposables, useElementIntersectionObserver, useIntersectionObserver, useLayoutBridge, useLayoutHosts, useModel, useNativeInstance, useNativePageRouter, useNativeRouter, useNavigationBarMetrics, usePageLayout, usePageScrollThrottle, usePageStack, useScrollOffset, useSelectorFields, useSelectorQuery, useSlots, useTemplateRef, useUpdatePerformanceListener, version, waitForLayoutHost, watch, watchEffect, watchPostEffect, watchSyncEffect, withDefaults };
|
package/dist/dev/index.mjs
CHANGED
|
@@ -41,10 +41,11 @@ import { useAttrs, useNativeInstance, useSlots } from "./runtime/vueCompat/conte
|
|
|
41
41
|
import { mergeModels, useBindModel, useChangeModel, useModel } from "./runtime/vueCompat/model.mjs";
|
|
42
42
|
import { useNativePageRouter, useNativeRouter } from "./runtime/vueCompat/router.mjs";
|
|
43
43
|
import { useTemplateRef } from "./runtime/vueCompat/templateRef.mjs";
|
|
44
|
-
import { createStore } from "./store/manager.mjs";
|
|
44
|
+
import { createPinia, createStore, disposePinia, getActivePinia, setActivePinia } from "./store/manager.mjs";
|
|
45
|
+
import { MutationType } from "./store/types.mjs";
|
|
45
46
|
import { defineStore } from "./store/define.mjs";
|
|
46
47
|
import { storeToRefs } from "./store/storeToRefs.mjs";
|
|
47
48
|
|
|
48
49
|
export * from "@wevu/web-apis"
|
|
49
50
|
|
|
50
|
-
export { addMutationRecorder, batch, callHookList, callHookReturn, callUpdateHooks, computed, createApp, createStore, createWevuComponent, createWevuScopedSlotComponent, customRef, defineAppSetup, defineComponent, defineStore, effect, effectScope, endBatch, getCurrentInstance, getCurrentPageStackSnapshot, getCurrentScope, getCurrentSetupContext, getDeepWatchStrategy, getNavigationBarMetrics, getReactiveVersion, hasInjectionContext, inject, injectGlobal, isNoSetData, isProxy, isRaw, isReactive, isReadonly, isRef, isShallowReactive, isShallowRef, markNoSetData, markRaw, mergeModels, mountRuntimeInstance, nextTick, normalizeClass, normalizeStyle, onActivated, onAddToFavorites, onAttached, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onDetached, onError, onErrorCaptured, onHide, onLaunch, onLoad, onMemoryWarning, onMounted, onMoved, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onResize, onRouteDone, onSaveExitState, onScopeDispose, onServerPrefetch, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, onUnmounted, onUpdated, prelinkReactiveTree, provide, provideGlobal, reactive, readonly, ref, registerApp, registerComponent, registerPageLayoutBridge, registerRuntimeLayoutHosts, removeMutationRecorder, resetWevuDefaults, resolveLayoutBridge, resolveLayoutHost, resolvePropValue, resolveRuntimePageLayoutName, runSetupFunction, setCurrentInstance, setCurrentSetupContext, setDeepWatchStrategy, setGlobalProvidedValue, setPageLayout, setRuntimeSetDataVisibility, setWevuDefaults, shallowReactive, shallowReadonly, shallowRef, startBatch, stop, storeToRefs, syncRuntimePageLayoutState, syncRuntimePageLayoutStateFromRuntime, teardownRuntimeInstance, toRaw, toRef, toRefs, toValue, touchReactive, traverse, triggerRef, unref, unregisterPageLayoutBridge, unregisterRuntimeLayoutHosts, use, useAsyncDerivation, useAsyncPullDownRefresh, useAttrs, useBindModel, useBoundingClientRect, useChangeModel, useCssModule, useDisposables, useElementIntersectionObserver, useIntersectionObserver, useLayoutBridge, useLayoutHosts, useModel, useNativeInstance, useNativePageRouter, useNativeRouter, useNavigationBarMetrics, usePageLayout, usePageScrollThrottle, usePageStack, useScrollOffset, useSelectorFields, useSelectorQuery, useSlots, useTemplateRef, useUpdatePerformanceListener, version, waitForLayoutHost, watch, watchEffect, watchPostEffect, watchSyncEffect };
|
|
51
|
+
export { MutationType, addMutationRecorder, batch, callHookList, callHookReturn, callUpdateHooks, computed, createApp, createPinia, createStore, createWevuComponent, createWevuScopedSlotComponent, customRef, defineAppSetup, defineComponent, defineStore, disposePinia, effect, effectScope, endBatch, getActivePinia, getCurrentInstance, getCurrentPageStackSnapshot, getCurrentScope, getCurrentSetupContext, getDeepWatchStrategy, getNavigationBarMetrics, getReactiveVersion, hasInjectionContext, inject, injectGlobal, isNoSetData, isProxy, isRaw, isReactive, isReadonly, isRef, isShallowReactive, isShallowRef, markNoSetData, markRaw, mergeModels, mountRuntimeInstance, nextTick, normalizeClass, normalizeStyle, onActivated, onAddToFavorites, onAttached, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onDetached, onError, onErrorCaptured, onHide, onLaunch, onLoad, onMemoryWarning, onMounted, onMoved, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onResize, onRouteDone, onSaveExitState, onScopeDispose, onServerPrefetch, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, onUnmounted, onUpdated, prelinkReactiveTree, provide, provideGlobal, reactive, readonly, ref, registerApp, registerComponent, registerPageLayoutBridge, registerRuntimeLayoutHosts, removeMutationRecorder, resetWevuDefaults, resolveLayoutBridge, resolveLayoutHost, resolvePropValue, resolveRuntimePageLayoutName, runSetupFunction, setActivePinia, setCurrentInstance, setCurrentSetupContext, setDeepWatchStrategy, setGlobalProvidedValue, setPageLayout, setRuntimeSetDataVisibility, setWevuDefaults, shallowReactive, shallowReadonly, shallowRef, startBatch, stop, storeToRefs, syncRuntimePageLayoutState, syncRuntimePageLayoutStateFromRuntime, teardownRuntimeInstance, toRaw, toRef, toRefs, toValue, touchReactive, traverse, triggerRef, unref, unregisterPageLayoutBridge, unregisterRuntimeLayoutHosts, use, useAsyncDerivation, useAsyncPullDownRefresh, useAttrs, useBindModel, useBoundingClientRect, useChangeModel, useCssModule, useDisposables, useElementIntersectionObserver, useIntersectionObserver, useLayoutBridge, useLayoutHosts, useModel, useNativeInstance, useNativePageRouter, useNativeRouter, useNavigationBarMetrics, usePageLayout, usePageScrollThrottle, usePageStack, useScrollOffset, useSelectorFields, useSelectorQuery, useSlots, useTemplateRef, useUpdatePerformanceListener, version, waitForLayoutHost, watch, watchEffect, watchPostEffect, watchSyncEffect };
|
package/dist/dev/package.mjs
CHANGED
|
@@ -2,13 +2,17 @@ import { Ref } from "./ref.mjs";
|
|
|
2
2
|
//#region src/reactivity/computed.d.ts
|
|
3
3
|
export type ComputedGetter<T> = () => T;
|
|
4
4
|
export type ComputedSetter<T> = (value: T) => void;
|
|
5
|
+
declare const computedBrand: unique symbol;
|
|
6
|
+
declare const writableComputedBrand: unique symbol;
|
|
5
7
|
interface BaseComputedRef<T, S = T> extends Ref<T, S> {
|
|
6
8
|
[key: symbol]: any;
|
|
7
9
|
}
|
|
8
10
|
export interface ComputedRef<T = any> extends BaseComputedRef<T> {
|
|
11
|
+
readonly [computedBrand]: true;
|
|
9
12
|
readonly value: T;
|
|
10
13
|
}
|
|
11
14
|
export interface WritableComputedRef<T, S = T> extends BaseComputedRef<T, S> {
|
|
15
|
+
readonly [writableComputedBrand]: true;
|
|
12
16
|
value: T;
|
|
13
17
|
}
|
|
14
18
|
export interface WritableComputedOptions<T> {
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { createComputedEffect, track, trigger } from "./core.mjs";
|
|
2
|
+
import { markRaw } from "./reactive.mjs";
|
|
2
3
|
import { markAsRef } from "./ref.mjs";
|
|
3
4
|
|
|
4
5
|
//#region src/reactivity/computed.ts
|
|
6
|
+
const computedRefs = /* @__PURE__ */ new WeakSet();
|
|
7
|
+
/** 识别计算来源,供 Store 将派生值与可持久化 state 分离。 */
|
|
8
|
+
function isComputedRef(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && computedRefs.has(value);
|
|
10
|
+
}
|
|
5
11
|
function computed(getterOrOptions) {
|
|
6
12
|
let getter;
|
|
7
13
|
let setter;
|
|
@@ -32,6 +38,9 @@ function computed(getterOrOptions) {
|
|
|
32
38
|
}
|
|
33
39
|
};
|
|
34
40
|
markAsRef(obj);
|
|
41
|
+
markRaw(obj);
|
|
42
|
+
computedRefs.add(obj);
|
|
43
|
+
Object.defineProperty(obj, "__r_isReadonly", { value: onlyGetter });
|
|
35
44
|
runner = createComputedEffect(getter, {
|
|
36
45
|
lazy: true,
|
|
37
46
|
scheduler: () => {
|
|
@@ -45,5 +54,5 @@ function computed(getterOrOptions) {
|
|
|
45
54
|
}
|
|
46
55
|
|
|
47
56
|
//#endregion
|
|
48
|
-
export { computed };
|
|
57
|
+
export { computed, isComputedRef };
|
|
49
58
|
//# sourceMappingURL=computed.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"computed.mjs","names":[],"sources":["../../../src/reactivity/computed.ts"],"sourcesContent":["import type { ReactiveEffect } from './core'\nimport type { Ref } from './ref'\nimport { createComputedEffect, track, trigger } from './core'\nimport { markAsRef } from './ref'\n\nexport type ComputedGetter<T> = () => T\nexport type ComputedSetter<T> = (value: T) => void\n\ninterface BaseComputedRef<T, S = T> extends Ref<T, S> {\n [key: symbol]: any\n}\n\nexport interface ComputedRef<T = any> extends BaseComputedRef<T> {\n readonly value: T\n}\n\nexport interface WritableComputedRef<T, S = T> extends BaseComputedRef<T, S> {\n value: T\n}\n\nexport interface WritableComputedOptions<T> {\n get: ComputedGetter<T>\n set: ComputedSetter<T>\n}\n\nexport function computed<T>(getter: ComputedGetter<T>): ComputedRef<T>\nexport function computed<T>(options: WritableComputedOptions<T>): WritableComputedRef<T>\nexport function computed<T>(\n getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T>,\n): ComputedRef<T> | WritableComputedRef<T> {\n let getter: ComputedGetter<T>\n let setter: ComputedSetter<T>\n const onlyGetter = typeof getterOrOptions === 'function'\n if (onlyGetter) {\n getter = getterOrOptions as ComputedGetter<T>\n setter = () => {\n throw new Error('计算属性是只读的')\n }\n }\n else {\n getter = (getterOrOptions as WritableComputedOptions<T>).get\n setter = (getterOrOptions as WritableComputedOptions<T>).set\n }\n let value: T\n let dirty = true\n let runner: ReactiveEffect<T>\n const obj: any = {\n get value() {\n if (dirty) {\n value = runner()\n dirty = false\n }\n track(obj, 'value')\n return value\n },\n set value(newValue: T) {\n setter(newValue)\n },\n }\n markAsRef(obj)\n runner = createComputedEffect(getter, {\n lazy: true,\n scheduler: () => {\n if (!dirty) {\n dirty = true\n trigger(obj, 'value')\n }\n },\n })\n return (onlyGetter ? obj as ComputedRef<T> : obj as WritableComputedRef<T>)\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"computed.mjs","names":[],"sources":["../../../src/reactivity/computed.ts"],"sourcesContent":["import type { ReactiveEffect } from './core'\nimport type { Ref } from './ref'\nimport { createComputedEffect, track, trigger } from './core'\nimport { markRaw } from './reactive'\nimport { ReactiveFlags } from './reactive/shared'\nimport { markAsRef } from './ref'\n\nexport type ComputedGetter<T> = () => T\nexport type ComputedSetter<T> = (value: T) => void\n\ndeclare const computedBrand: unique symbol\ndeclare const writableComputedBrand: unique symbol\n\nconst computedRefs = new WeakSet<object>()\n\n/** 识别计算来源,供 Store 将派生值与可持久化 state 分离。 */\nexport function isComputedRef(value: unknown): value is ComputedRef | WritableComputedRef<any> {\n return typeof value === 'object' && value !== null && computedRefs.has(value)\n}\n\ninterface BaseComputedRef<T, S = T> extends Ref<T, S> {\n [key: symbol]: any\n}\n\nexport interface ComputedRef<T = any> extends BaseComputedRef<T> {\n readonly [computedBrand]: true\n readonly value: T\n}\n\nexport interface WritableComputedRef<T, S = T> extends BaseComputedRef<T, S> {\n readonly [writableComputedBrand]: true\n value: T\n}\n\nexport interface WritableComputedOptions<T> {\n get: ComputedGetter<T>\n set: ComputedSetter<T>\n}\n\nexport function computed<T>(getter: ComputedGetter<T>): ComputedRef<T>\nexport function computed<T>(options: WritableComputedOptions<T>): WritableComputedRef<T>\nexport function computed<T>(\n getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T>,\n): ComputedRef<T> | WritableComputedRef<T> {\n let getter: ComputedGetter<T>\n let setter: ComputedSetter<T>\n const onlyGetter = typeof getterOrOptions === 'function'\n if (onlyGetter) {\n getter = getterOrOptions as ComputedGetter<T>\n setter = () => {\n throw new Error('计算属性是只读的')\n }\n }\n else {\n getter = (getterOrOptions as WritableComputedOptions<T>).get\n setter = (getterOrOptions as WritableComputedOptions<T>).set\n }\n let value: T\n let dirty = true\n let runner: ReactiveEffect<T>\n const obj: any = {\n get value() {\n if (dirty) {\n value = runner()\n dirty = false\n }\n track(obj, 'value')\n return value\n },\n set value(newValue: T) {\n setter(newValue)\n },\n }\n markAsRef(obj)\n markRaw(obj)\n computedRefs.add(obj)\n Object.defineProperty(obj, ReactiveFlags.IS_READONLY, { value: onlyGetter })\n runner = createComputedEffect(getter, {\n lazy: true,\n scheduler: () => {\n if (!dirty) {\n dirty = true\n trigger(obj, 'value')\n }\n },\n })\n return (onlyGetter ? obj as ComputedRef<T> : obj as WritableComputedRef<T>)\n}\n"],"mappings":";;;;;AAaA,MAAM,+BAAe,IAAI,QAAgB;;AAGzC,SAAgB,cAAc,OAAiE;CAC7F,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,IAAI,KAAK;AAC9E;AAuBA,SAAgB,SACd,iBACyC;CACzC,IAAI;CACJ,IAAI;CACJ,MAAM,aAAa,OAAO,oBAAoB;CAC9C,IAAI,YAAY;EACd,SAAS;EACT,eAAe;GACb,MAAM,IAAI,MAAM,UAAU;EAC5B;CACF,OACK;EACH,SAAU,gBAA+C;EACzD,SAAU,gBAA+C;CAC3D;CACA,IAAI;CACJ,IAAI,QAAQ;CACZ,IAAI;CACJ,MAAM,MAAW;EACf,IAAI,QAAQ;GACV,IAAI,OAAO;IACT,QAAQ,OAAO;IACf,QAAQ;GACV;GACA,MAAM,KAAK,OAAO;GAClB,OAAO;EACT;EACA,IAAI,MAAM,UAAa;GACrB,OAAO,QAAQ;EACjB;CACF;CACA,UAAU,GAAG;CACb,QAAQ,GAAG;CACX,aAAa,IAAI,GAAG;CACpB,OAAO,eAAe,uBAAgC,EAAE,OAAO,WAAW,CAAC;CAC3E,SAAS,qBAAqB,QAAQ;EACpC,MAAM;EACN,iBAAiB;GACf,IAAI,CAAC,OAAO;IACV,QAAQ;IACR,QAAQ,KAAK,OAAO;GACtB;EACF;CACF,CAAC;CACD,OAAQ,aAAa,MAAwB;AAC/C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { track, trigger } from "./core.mjs";
|
|
1
|
+
import { batch, track, trigger } from "./core.mjs";
|
|
2
2
|
import { addMutationRecorder, mutationRecorders, removeMutationRecorder } from "./reactive/mutation.mjs";
|
|
3
3
|
import { adoptReactiveRoot, bumpAncestorVersions, bumpRawVersion, getRawVersion, rawMultiParentSet, rawParentsMap, rawPathMap, rawRootMap, rawVersionMap, recordParentLink, removeParentLink, resolvePathToTarget } from "./reactive/patchState.mjs";
|
|
4
4
|
import { VERSION_KEY, getTargetType, hasOwn, isArrayIndexKey, isObject, toRaw } from "./reactive/shared.mjs";
|
|
@@ -89,6 +89,7 @@ const mutableHandlers = {
|
|
|
89
89
|
return res;
|
|
90
90
|
},
|
|
91
91
|
set(target, key, value, receiver) {
|
|
92
|
+
const hadKey = hasOwn(target, key);
|
|
92
93
|
const isArr = Array.isArray(target);
|
|
93
94
|
const oldLength = isArr ? target.length : 0;
|
|
94
95
|
const oldValue = Reflect.get(target, key, receiver);
|
|
@@ -109,16 +110,19 @@ const mutableHandlers = {
|
|
|
109
110
|
rawPathMap.set(childRaw, nextPath);
|
|
110
111
|
}
|
|
111
112
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
113
|
+
batch(() => {
|
|
114
|
+
trigger(target, key);
|
|
115
|
+
if (isArr && typeof key === "string" && isArrayIndexKey(key) && Number(key) >= oldLength) trigger(target, "length");
|
|
116
|
+
trigger(target, VERSION_KEY);
|
|
117
|
+
bumpRawVersion(target);
|
|
118
|
+
bumpAncestorVersions(target);
|
|
119
|
+
const root = rawRootMap.get(target);
|
|
120
|
+
if (root && root !== target) {
|
|
121
|
+
trigger(root, VERSION_KEY);
|
|
122
|
+
bumpRawVersion(root);
|
|
123
|
+
}
|
|
124
|
+
if (!hadKey) trigger(target, Symbol.iterator);
|
|
125
|
+
});
|
|
122
126
|
emitMutation(target, key, "set");
|
|
123
127
|
}
|
|
124
128
|
return result;
|
|
@@ -131,15 +135,18 @@ const mutableHandlers = {
|
|
|
131
135
|
var _ReactiveFlags$RAW2;
|
|
132
136
|
const oldRaw = isObject(oldValue) ? (_ReactiveFlags$RAW2 = oldValue === null || oldValue === void 0 ? void 0 : oldValue["__r_raw"]) !== null && _ReactiveFlags$RAW2 !== void 0 ? _ReactiveFlags$RAW2 : oldValue : void 0;
|
|
133
137
|
if (oldRaw) removeParentLink(oldRaw, target, key);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
138
|
+
batch(() => {
|
|
139
|
+
trigger(target, key);
|
|
140
|
+
trigger(target, VERSION_KEY);
|
|
141
|
+
bumpRawVersion(target);
|
|
142
|
+
bumpAncestorVersions(target);
|
|
143
|
+
const root = rawRootMap.get(target);
|
|
144
|
+
if (root && root !== target) {
|
|
145
|
+
trigger(root, VERSION_KEY);
|
|
146
|
+
bumpRawVersion(root);
|
|
147
|
+
}
|
|
148
|
+
trigger(target, Symbol.iterator);
|
|
149
|
+
});
|
|
143
150
|
emitMutation(target, key, "delete");
|
|
144
151
|
}
|
|
145
152
|
return result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactive.mjs","names":[],"sources":["../../../src/reactivity/reactive.ts"],"sourcesContent":["import type { MutationKind, MutationOp } from './reactive/mutation'\nimport { track, trigger } from './core'\nimport { mutationRecorders } from './reactive/mutation'\nimport {\n adoptReactiveRoot,\n bumpAncestorVersions,\n bumpRawVersion,\n getRawVersion,\n rawMultiParentSet,\n rawParentsMap,\n rawPathMap,\n rawRootMap,\n rawVersionMap,\n recordParentLink,\n removeParentLink,\n resolvePathToTarget,\n} from './reactive/patchState'\nimport { getTargetType, hasOwn, isArrayIndexKey, isObject, ReactiveFlags, TargetType, toRaw, VERSION_KEY } from './reactive/shared'\nimport { rawMap, reactiveMap } from './reactive/state'\n\nexport { addMutationRecorder, removeMutationRecorder } from './reactive/mutation'\nexport type { MutationKind, MutationOp, MutationRecord } from './reactive/mutation'\nexport type { PrelinkReactiveTreeOptions } from './reactive/patch'\nexport { clearPatchIndices, prelinkReactiveTree, touchReactive } from './reactive/patch'\nexport { isShallowReactive, shallowReactive } from './reactive/shallow'\nexport { isObject, ReactiveFlags, toRaw } from './reactive/shared'\n\n/**\n * 读取响应式版本号(框架内部调试能力)。\n * @internal\n */\nexport function getReactiveVersion(target: object) {\n const raw = toRaw(target as any) as object\n return getRawVersion(raw)\n}\n\nfunction emitMutation(target: object, key: PropertyKey, op: MutationOp) {\n if (!mutationRecorders.size) {\n return\n }\n if (typeof key !== 'string') {\n return\n }\n if (key.startsWith('__r_')) {\n return\n }\n const root = rawRootMap.get(target) ?? target\n const isArray = Array.isArray(target)\n const kind: MutationKind = isArray && (key === 'length' || isArrayIndexKey(key)) ? 'array' : 'property'\n\n const baseSegments = resolvePathToTarget(root, target)\n if (!baseSegments) {\n // 路径不唯一/无法解析:尝试从父引用收集可能的顶层 key,供 patch 模式做“局部回退”。\n const fallback = new Set<string>()\n const parents = rawParentsMap.get(target)\n if (parents) {\n for (const [parent, keys] of parents) {\n const parentPath = rawPathMap.get(parent)\n const topFromParentPath = parentPath ? parentPath.split('.', 1)[0] : undefined\n const topFromResolve = !topFromParentPath\n ? (resolvePathToTarget(root, parent)?.[0] as string | undefined)\n : undefined\n for (const k of keys) {\n if (typeof k !== 'string') {\n continue\n }\n fallback.add(topFromParentPath ?? topFromResolve ?? k)\n }\n }\n }\n else {\n // 若目标就是 root 的直接子属性(未记录 parent link),仍可用 key 作为顶层回退\n fallback.add(key)\n }\n for (const recorder of mutationRecorders) {\n recorder({ root, kind, op, path: undefined, fallbackTopKeys: fallback.size ? [...fallback] : undefined })\n }\n return\n }\n\n // 若目标位于数组内部(例如 arr[0].x),直接回退到数组本身的路径,保持“数组整体替换”的策略。\n const arrayIndexPos = baseSegments.findIndex(seg => isArrayIndexKey(seg))\n if (arrayIndexPos !== -1) {\n const arrayPath = baseSegments.slice(0, arrayIndexPos).join('.')\n const path = arrayPath || undefined\n for (const recorder of mutationRecorders) {\n recorder({ root, kind: 'array', op, path })\n }\n return\n }\n\n const basePath = baseSegments.length ? baseSegments.join('.') : ''\n const path = kind === 'array' ? (basePath || undefined) : (basePath ? `${basePath}.${key}` : (key as string))\n\n for (const recorder of mutationRecorders) {\n recorder({\n root,\n kind,\n op,\n path,\n })\n }\n}\n\nconst mutableHandlers: ProxyHandler<any> = {\n get(target, key, receiver) {\n if (key === ReactiveFlags.IS_REACTIVE) {\n return true\n }\n if (key === ReactiveFlags.RAW) {\n return target\n }\n const res = Reflect.get(target, key, receiver)\n track(target, key)\n if (isObject(res)) {\n // 检查返回值是否被 markRaw 标记为跳过响应式\n if ((res as any)[ReactiveFlags.SKIP]) {\n return res\n }\n // 确保子对象的根引用与当前目标一致,便于版本号级联\n const childRaw = ((res as any)?.[ReactiveFlags.RAW] ?? res) as object\n adoptReactiveRoot(childRaw, target)\n recordParentLink(childRaw, target, key)\n const parentPath = rawPathMap.get(target)\n if (mutationRecorders.size && typeof key === 'string' && parentPath != null && !rawMultiParentSet.has(childRaw)) {\n const nextPath = parentPath ? `${parentPath}.${key}` : key\n rawPathMap.set(childRaw, nextPath)\n }\n // eslint-disable-next-line ts/no-use-before-define -- 避免递归调用的顺序警告\n return reactive(res)\n }\n return res\n },\n set(target, key, value, receiver) {\n const isArr = Array.isArray(target)\n const oldLength = isArr ? target.length : 0\n const oldValue = Reflect.get(target, key, receiver)\n const oldRawValue = isObject(oldValue) ? toRaw(oldValue) : oldValue\n const rawValue = isObject(value) ? toRaw(value) : value\n if (Object.is(oldRawValue, rawValue)) {\n return true\n }\n const result = Reflect.set(target, key, value, receiver)\n if (result) {\n const oldRaw = isObject(oldRawValue) ? oldRawValue as object : undefined\n if (oldRaw) {\n removeParentLink(oldRaw, target, key)\n }\n if (isObject(rawValue) && !(rawValue as any)[ReactiveFlags.SKIP]) {\n const childRaw = rawValue as object\n adoptReactiveRoot(childRaw, target)\n recordParentLink(childRaw, target, key)\n const parentPath = rawPathMap.get(target)\n if (mutationRecorders.size && typeof key === 'string' && parentPath != null && !rawMultiParentSet.has(childRaw)) {\n const nextPath = parentPath ? `${parentPath}.${key}` : key\n rawPathMap.set(childRaw, nextPath)\n }\n }\n trigger(target, key)\n if (isArr && typeof key === 'string' && isArrayIndexKey(key) && Number(key) >= oldLength) {\n trigger(target, 'length')\n }\n // 任意写操作都提升通用版本号\n trigger(target, VERSION_KEY)\n bumpRawVersion(target)\n bumpAncestorVersions(target)\n const root = rawRootMap.get(target)\n if (root && root !== target) {\n trigger(root, VERSION_KEY)\n bumpRawVersion(root)\n }\n emitMutation(target, key, 'set')\n }\n return result\n },\n deleteProperty(target, key) {\n const hadKey = hasOwn(target, key)\n const oldValue = hadKey ? (target as any)[key] : undefined\n const result = Reflect.deleteProperty(target, key)\n if (hadKey && result) {\n const oldRaw = isObject(oldValue) ? (((oldValue as any)?.[ReactiveFlags.RAW] ?? oldValue) as object) : undefined\n if (oldRaw) {\n removeParentLink(oldRaw, target, key)\n }\n trigger(target, key)\n // 删除同样提升通用版本号\n trigger(target, VERSION_KEY)\n bumpRawVersion(target)\n bumpAncestorVersions(target)\n const root = rawRootMap.get(target)\n if (root && root !== target) {\n trigger(root, VERSION_KEY)\n bumpRawVersion(root)\n }\n emitMutation(target, key, 'delete')\n }\n return result\n },\n ownKeys(target) {\n track(target, Symbol.iterator)\n // 遍历时也订阅通用版本号,确保新增/删除键可触发\n track(target, VERSION_KEY)\n return Reflect.ownKeys(target)\n },\n}\n\nexport function reactive<T extends object>(target: T): T {\n if (!isObject(target)) {\n return target\n }\n if ((target as any)[ReactiveFlags.IS_REACTIVE]) {\n return target\n }\n const existingProxy = reactiveMap.get(target)\n if (existingProxy) {\n return existingProxy\n }\n if (getTargetType(target) === TargetType.INVALID) {\n return target\n }\n const proxy = new Proxy(target, mutableHandlers)\n reactiveMap.set(target, proxy)\n rawMap.set(proxy, target)\n if (!rawVersionMap.has(target)) {\n rawVersionMap.set(target, 0)\n }\n // 新的原始对象在被观察时初始化根节点映射\n if (!rawRootMap.has(target)) {\n rawRootMap.set(target, target)\n }\n return proxy\n}\n\nexport function isReactive(value: unknown): boolean {\n return Boolean(value && (value as any)[ReactiveFlags.IS_REACTIVE])\n}\n\nexport function convertToReactive<T>(value: T): T {\n return isObject(value) ? reactive(value as any) : value\n}\n\n// ============================================================================\n// 标记对象跳过响应式转换(markRaw)\n// ============================================================================\n\n/**\n * 标记对象为“原始”状态,后续不会被转换为响应式,返回原对象本身。\n *\n * @param value 需要标记的对象\n * @returns 带有跳过标记的原对象\n *\n * @example\n * ```ts\n * const foo = markRaw({\n * nested: {}\n * })\n *\n * const state = reactive({\n * foo\n * })\n *\n * state.foo // 不是响应式对象\n * ```\n */\nexport function markRaw<T extends object>(value: T): T {\n if (!isObject(value)) {\n return value\n }\n Object.defineProperty(value, ReactiveFlags.SKIP, {\n value: true,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n return value\n}\n\n/**\n * 判断某个值是否被标记为原始(即不应转换为响应式)。\n *\n * @param value 待检测的值\n * @returns 若含有跳过标记则返回 true\n */\nexport function isRaw(value: unknown): boolean {\n return isObject(value) && ReactiveFlags.SKIP in (value as object)\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,SAAgB,mBAAmB,QAAgB;CACjD,MAAM,MAAM,MAAM,MAAa;CAC/B,OAAO,cAAc,GAAG;AAC1B;AAEA,SAAS,aAAa,QAAgB,KAAkB,IAAgB;;CACtE,IAAI,CAAC,kBAAkB,MACrB;CAEF,IAAI,OAAO,QAAQ,UACjB;CAEF,IAAI,IAAI,WAAW,MAAM,GACvB;CAEF,MAAM,0BAAO,WAAW,IAAI,MAAM,8DAAK;CAEvC,MAAM,OADU,MAAM,QAAQ,MACG,MAAM,QAAQ,YAAY,gBAAgB,GAAG,KAAK,UAAU;CAE7F,MAAM,eAAe,oBAAoB,MAAM,MAAM;CACrD,IAAI,CAAC,cAAc;EAEjB,MAAM,2BAAW,IAAI,IAAY;EACjC,MAAM,UAAU,cAAc,IAAI,MAAM;EACxC,IAAI,SACF,KAAK,MAAM,CAAC,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,MAAM,GAC3B,cAAc,IAAI,QAAQ,CAAC;CAG7B,IAAI,CAAC,WAAW,IAAI,MAAM,GACxB,WAAW,IAAI,QAAQ,MAAM;CAE/B,OAAO;AACT;AAEA,SAAgB,WAAW,OAAyB;CAClD,OAAO,QAAQ,SAAU,uBAAwC;AACnE;AAEA,SAAgB,kBAAqB,OAAa;CAChD,OAAO,SAAS,KAAK,IAAI,SAAS,KAAY,IAAI;AACpD;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAA0B,OAAa;CACrD,IAAI,CAAC,SAAS,KAAK,GACjB,OAAO;CAET,OAAO,eAAe,mBAA2B;EAC/C,OAAO;EACP,cAAc;EACd,YAAY;EACZ,UAAU;CACZ,CAAC;CACD,OAAO;AACT;;;;;;;AAQA,SAAgB,MAAM,OAAyB;CAC7C,OAAO,SAAS,KAAK,mBAA4B;AACnD"}
|
|
1
|
+
{"version":3,"file":"reactive.mjs","names":[],"sources":["../../../src/reactivity/reactive.ts"],"sourcesContent":["import type { MutationKind, MutationOp } from './reactive/mutation'\nimport { batch, track, trigger } from './core'\nimport { mutationRecorders } from './reactive/mutation'\nimport {\n adoptReactiveRoot,\n bumpAncestorVersions,\n bumpRawVersion,\n getRawVersion,\n rawMultiParentSet,\n rawParentsMap,\n rawPathMap,\n rawRootMap,\n rawVersionMap,\n recordParentLink,\n removeParentLink,\n resolvePathToTarget,\n} from './reactive/patchState'\nimport { getTargetType, hasOwn, isArrayIndexKey, isObject, ReactiveFlags, TargetType, toRaw, VERSION_KEY } from './reactive/shared'\nimport { rawMap, reactiveMap } from './reactive/state'\n\nexport { addMutationRecorder, removeMutationRecorder } from './reactive/mutation'\nexport type { MutationKind, MutationOp, MutationRecord } from './reactive/mutation'\nexport type { PrelinkReactiveTreeOptions } from './reactive/patch'\nexport { clearPatchIndices, prelinkReactiveTree, touchReactive } from './reactive/patch'\nexport { isShallowReactive, shallowReactive } from './reactive/shallow'\nexport { isObject, ReactiveFlags, toRaw } from './reactive/shared'\n\n/**\n * 读取响应式版本号(框架内部调试能力)。\n * @internal\n */\nexport function getReactiveVersion(target: object) {\n const raw = toRaw(target as any) as object\n return getRawVersion(raw)\n}\n\nfunction emitMutation(target: object, key: PropertyKey, op: MutationOp) {\n if (!mutationRecorders.size) {\n return\n }\n if (typeof key !== 'string') {\n return\n }\n if (key.startsWith('__r_')) {\n return\n }\n const root = rawRootMap.get(target) ?? target\n const isArray = Array.isArray(target)\n const kind: MutationKind = isArray && (key === 'length' || isArrayIndexKey(key)) ? 'array' : 'property'\n\n const baseSegments = resolvePathToTarget(root, target)\n if (!baseSegments) {\n // 路径不唯一/无法解析:尝试从父引用收集可能的顶层 key,供 patch 模式做“局部回退”。\n const fallback = new Set<string>()\n const parents = rawParentsMap.get(target)\n if (parents) {\n for (const [parent, keys] of parents) {\n const parentPath = rawPathMap.get(parent)\n const topFromParentPath = parentPath ? parentPath.split('.', 1)[0] : undefined\n const topFromResolve = !topFromParentPath\n ? (resolvePathToTarget(root, parent)?.[0] as string | undefined)\n : undefined\n for (const k of keys) {\n if (typeof k !== 'string') {\n continue\n }\n fallback.add(topFromParentPath ?? topFromResolve ?? k)\n }\n }\n }\n else {\n // 若目标就是 root 的直接子属性(未记录 parent link),仍可用 key 作为顶层回退\n fallback.add(key)\n }\n for (const recorder of mutationRecorders) {\n recorder({ root, kind, op, path: undefined, fallbackTopKeys: fallback.size ? [...fallback] : undefined })\n }\n return\n }\n\n // 若目标位于数组内部(例如 arr[0].x),直接回退到数组本身的路径,保持“数组整体替换”的策略。\n const arrayIndexPos = baseSegments.findIndex(seg => isArrayIndexKey(seg))\n if (arrayIndexPos !== -1) {\n const arrayPath = baseSegments.slice(0, arrayIndexPos).join('.')\n const path = arrayPath || undefined\n for (const recorder of mutationRecorders) {\n recorder({ root, kind: 'array', op, path })\n }\n return\n }\n\n const basePath = baseSegments.length ? baseSegments.join('.') : ''\n const path = kind === 'array' ? (basePath || undefined) : (basePath ? `${basePath}.${key}` : (key as string))\n\n for (const recorder of mutationRecorders) {\n recorder({\n root,\n kind,\n op,\n path,\n })\n }\n}\n\nconst mutableHandlers: ProxyHandler<any> = {\n get(target, key, receiver) {\n if (key === ReactiveFlags.IS_REACTIVE) {\n return true\n }\n if (key === ReactiveFlags.RAW) {\n return target\n }\n const res = Reflect.get(target, key, receiver)\n track(target, key)\n if (isObject(res)) {\n // 检查返回值是否被 markRaw 标记为跳过响应式\n if ((res as any)[ReactiveFlags.SKIP]) {\n return res\n }\n // 确保子对象的根引用与当前目标一致,便于版本号级联\n const childRaw = ((res as any)?.[ReactiveFlags.RAW] ?? res) as object\n adoptReactiveRoot(childRaw, target)\n recordParentLink(childRaw, target, key)\n const parentPath = rawPathMap.get(target)\n if (mutationRecorders.size && typeof key === 'string' && parentPath != null && !rawMultiParentSet.has(childRaw)) {\n const nextPath = parentPath ? `${parentPath}.${key}` : key\n rawPathMap.set(childRaw, nextPath)\n }\n // eslint-disable-next-line ts/no-use-before-define -- 避免递归调用的顺序警告\n return reactive(res)\n }\n return res\n },\n set(target, key, value, receiver) {\n const hadKey = hasOwn(target, key)\n const isArr = Array.isArray(target)\n const oldLength = isArr ? target.length : 0\n const oldValue = Reflect.get(target, key, receiver)\n const oldRawValue = isObject(oldValue) ? toRaw(oldValue) : oldValue\n const rawValue = isObject(value) ? toRaw(value) : value\n if (Object.is(oldRawValue, rawValue)) {\n return true\n }\n const result = Reflect.set(target, key, value, receiver)\n if (result) {\n const oldRaw = isObject(oldRawValue) ? oldRawValue as object : undefined\n if (oldRaw) {\n removeParentLink(oldRaw, target, key)\n }\n if (isObject(rawValue) && !(rawValue as any)[ReactiveFlags.SKIP]) {\n const childRaw = rawValue as object\n adoptReactiveRoot(childRaw, target)\n recordParentLink(childRaw, target, key)\n const parentPath = rawPathMap.get(target)\n if (mutationRecorders.size && typeof key === 'string' && parentPath != null && !rawMultiParentSet.has(childRaw)) {\n const nextPath = parentPath ? `${parentPath}.${key}` : key\n rawPathMap.set(childRaw, nextPath)\n }\n }\n batch(() => {\n trigger(target, key)\n if (isArr && typeof key === 'string' && isArrayIndexKey(key) && Number(key) >= oldLength) {\n trigger(target, 'length')\n }\n // 任意写操作都提升通用版本号\n trigger(target, VERSION_KEY)\n bumpRawVersion(target)\n bumpAncestorVersions(target)\n const root = rawRootMap.get(target)\n if (root && root !== target) {\n trigger(root, VERSION_KEY)\n bumpRawVersion(root)\n }\n if (!hadKey) {\n trigger(target, Symbol.iterator)\n }\n })\n emitMutation(target, key, 'set')\n }\n return result\n },\n deleteProperty(target, key) {\n const hadKey = hasOwn(target, key)\n const oldValue = hadKey ? (target as any)[key] : undefined\n const result = Reflect.deleteProperty(target, key)\n if (hadKey && result) {\n const oldRaw = isObject(oldValue) ? (((oldValue as any)?.[ReactiveFlags.RAW] ?? oldValue) as object) : undefined\n if (oldRaw) {\n removeParentLink(oldRaw, target, key)\n }\n batch(() => {\n trigger(target, key)\n // 删除同样提升通用版本号\n trigger(target, VERSION_KEY)\n bumpRawVersion(target)\n bumpAncestorVersions(target)\n const root = rawRootMap.get(target)\n if (root && root !== target) {\n trigger(root, VERSION_KEY)\n bumpRawVersion(root)\n }\n trigger(target, Symbol.iterator)\n })\n emitMutation(target, key, 'delete')\n }\n return result\n },\n ownKeys(target) {\n track(target, Symbol.iterator)\n // 遍历时也订阅通用版本号,确保新增/删除键可触发\n track(target, VERSION_KEY)\n return Reflect.ownKeys(target)\n },\n}\n\nexport function reactive<T extends object>(target: T): T {\n if (!isObject(target)) {\n return target\n }\n if ((target as any)[ReactiveFlags.IS_REACTIVE]) {\n return target\n }\n const existingProxy = reactiveMap.get(target)\n if (existingProxy) {\n return existingProxy\n }\n if (getTargetType(target) === TargetType.INVALID) {\n return target\n }\n const proxy = new Proxy(target, mutableHandlers)\n reactiveMap.set(target, proxy)\n rawMap.set(proxy, target)\n if (!rawVersionMap.has(target)) {\n rawVersionMap.set(target, 0)\n }\n // 新的原始对象在被观察时初始化根节点映射\n if (!rawRootMap.has(target)) {\n rawRootMap.set(target, target)\n }\n return proxy\n}\n\nexport function isReactive(value: unknown): boolean {\n return Boolean(value && (value as any)[ReactiveFlags.IS_REACTIVE])\n}\n\nexport function convertToReactive<T>(value: T): T {\n return isObject(value) ? reactive(value as any) : value\n}\n\n// ============================================================================\n// 标记对象跳过响应式转换(markRaw)\n// ============================================================================\n\n/**\n * 标记对象为“原始”状态,后续不会被转换为响应式,返回原对象本身。\n *\n * @param value 需要标记的对象\n * @returns 带有跳过标记的原对象\n *\n * @example\n * ```ts\n * const foo = markRaw({\n * nested: {}\n * })\n *\n * const state = reactive({\n * foo\n * })\n *\n * state.foo // 不是响应式对象\n * ```\n */\nexport function markRaw<T extends object>(value: T): T {\n if (!isObject(value)) {\n return value\n }\n Object.defineProperty(value, ReactiveFlags.SKIP, {\n value: true,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n return value\n}\n\n/**\n * 判断某个值是否被标记为原始(即不应转换为响应式)。\n *\n * @param value 待检测的值\n * @returns 若含有跳过标记则返回 true\n */\nexport function isRaw(value: unknown): boolean {\n return isObject(value) && ReactiveFlags.SKIP in (value as object)\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,SAAgB,mBAAmB,QAAgB;CACjD,MAAM,MAAM,MAAM,MAAa;CAC/B,OAAO,cAAc,GAAG;AAC1B;AAEA,SAAS,aAAa,QAAgB,KAAkB,IAAgB;;CACtE,IAAI,CAAC,kBAAkB,MACrB;CAEF,IAAI,OAAO,QAAQ,UACjB;CAEF,IAAI,IAAI,WAAW,MAAM,GACvB;CAEF,MAAM,0BAAO,WAAW,IAAI,MAAM,8DAAK;CAEvC,MAAM,OADU,MAAM,QAAQ,MACG,MAAM,QAAQ,YAAY,gBAAgB,GAAG,KAAK,UAAU;CAE7F,MAAM,eAAe,oBAAoB,MAAM,MAAM;CACrD,IAAI,CAAC,cAAc;EAEjB,MAAM,2BAAW,IAAI,IAAY;EACjC,MAAM,UAAU,cAAc,IAAI,MAAM;EACxC,IAAI,SACF,KAAK,MAAM,CAAC,QAAQ,S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Ac,MAAM,SACtB,OAAO;CAET,MAAM,QAAQ,IAAI,MAAM,QAAQ,eAAe;CAC/C,YAAY,IAAI,QAAQ,KAAK;CAC7B,OAAO,IAAI,OAAO,MAAM;CACxB,IAAI,CAAC,cAAc,IAAI,MAAM,GAC3B,cAAc,IAAI,QAAQ,CAAC;CAG7B,IAAI,CAAC,WAAW,IAAI,MAAM,GACxB,WAAW,IAAI,QAAQ,MAAM;CAE/B,OAAO;AACT;AAEA,SAAgB,WAAW,OAAyB;CAClD,OAAO,QAAQ,SAAU,uBAAwC;AACnE;AAEA,SAAgB,kBAAqB,OAAa;CAChD,OAAO,SAAS,KAAK,IAAI,SAAS,KAAY,IAAI;AACpD;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAA0B,OAAa;CACrD,IAAI,CAAC,SAAS,KAAK,GACjB,OAAO;CAET,OAAO,eAAe,mBAA2B;EAC/C,OAAO;EACP,cAAc;EACd,YAAY;EACZ,UAAU;CACZ,CAAC;CACD,OAAO;AACT;;;;;;;AAQA,SAAgB,MAAM,OAAyB;CAC7C,OAAO,SAAS,KAAK,mBAA4B;AACnD"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { WevuAutoRoute } from "./types.mjs";
|
|
2
|
+
import { WevuNamedRouteMap } from "../router.mjs";
|
|
3
|
+
//#region src/router/auto-routes.d.ts
|
|
4
|
+
export type WevuAutoRoutes<TRouteMap extends object = WevuNamedRouteMap> = readonly WevuAutoRoute<TRouteMap>[];
|
|
5
|
+
export declare const routes: WevuAutoRoutes;
|
|
6
|
+
//#endregion
|
|
7
|
+
export type { WevuAutoRoute };
|
|
8
|
+
//# sourceMappingURL=auto-routes.d.mts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { WEVU_AUTO_ROUTES_MODULE_ID } from "@weapp-core/constants";
|
|
2
|
+
|
|
3
|
+
//#region src/router/auto-routes.ts
|
|
4
|
+
function unavailableOutsideVite() {
|
|
5
|
+
throw new Error(`${WEVU_AUTO_ROUTES_MODULE_ID} is generated by weapp-vite and is unavailable outside a weapp-vite build.`);
|
|
6
|
+
}
|
|
7
|
+
const routes = unavailableOutsideVite();
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
export { routes };
|
|
11
|
+
//# sourceMappingURL=auto-routes.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-routes.mjs","names":[],"sources":["../../../src/router/auto-routes.ts"],"sourcesContent":["import type { WevuNamedRouteMap } from '../router'\nimport type { WevuAutoRoute } from './types'\nimport { WEVU_AUTO_ROUTES_MODULE_ID } from '@weapp-core/constants'\n\nexport type { WevuAutoRoute } from './types'\n\nexport type WevuAutoRoutes<TRouteMap extends object = WevuNamedRouteMap>\n = readonly WevuAutoRoute<TRouteMap>[]\n\nfunction unavailableOutsideVite(): never {\n throw new Error(`${WEVU_AUTO_ROUTES_MODULE_ID} is generated by weapp-vite and is unavailable outside a weapp-vite build.`)\n}\n\nexport const routes: WevuAutoRoutes = unavailableOutsideVite()\n"],"mappings":";;;AASA,SAAS,yBAAgC;CACvC,MAAM,IAAI,MAAM,GAAG,2BAA2B,2EAA2E;AAC3H;AAEA,MAAa,SAAyB,uBAAuB"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { RouterNavigation, UseRouterOptions } from "./types.mjs";
|
|
2
|
+
import { WevuNamedRouteMap } from "../router.mjs";
|
|
2
3
|
//#region src/router/createRouter.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* @description 创建高阶路由导航器(对齐 Vue Router 的 createRouter 心智)
|
|
5
6
|
*/
|
|
6
|
-
export declare function createRouter(
|
|
7
|
+
export declare function createRouter<TRouteMap extends object = WevuNamedRouteMap>(optionsInput?: UseRouterOptions<NoInfer<TRouteMap>>): RouterNavigation<TRouteMap>;
|
|
7
8
|
//#endregion
|
|
8
9
|
//# sourceMappingURL=createRouter.d.mts.map
|
|
@@ -24,8 +24,9 @@ import { createRouteStateController, useNativeRouter } from "./useRoute.mjs";
|
|
|
24
24
|
/**
|
|
25
25
|
* @description 创建高阶路由导航器(对齐 Vue Router 的 createRouter 心智)
|
|
26
26
|
*/
|
|
27
|
-
function createRouter(
|
|
27
|
+
function createRouter(optionsInput = {}) {
|
|
28
28
|
var _options$maxRedirects, _options$initialNavig, _options$paramsMode, _options$rejectOnErro, _options$parseQuery, _options$stringifyQue, _options$tabBarEntrie;
|
|
29
|
+
const options = optionsInput;
|
|
29
30
|
const nativeRouter = useNativeRouter();
|
|
30
31
|
installRouteStateSyncOnNativeRouter(getMiniProgramGlobalObject());
|
|
31
32
|
const beforeEachGuards = /* @__PURE__ */ new Set();
|
|
@@ -107,9 +108,7 @@ function createRouter(options = {}) {
|
|
|
107
108
|
beforeRouteStateSync,
|
|
108
109
|
resolveRoute: enrichRouteRecordState
|
|
109
110
|
}).route;
|
|
110
|
-
|
|
111
|
-
return resolveWithCodec(to, route.path);
|
|
112
|
-
}
|
|
111
|
+
const resolve = (to) => resolveWithCodec(to, route.path);
|
|
113
112
|
const navigationResultController = createNavigationResultController({
|
|
114
113
|
afterEachHooks,
|
|
115
114
|
errorHandlers,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRouter.mjs","names":[],"sources":["../../../src/router/createRouter.ts"],"sourcesContent":["import type { RouteResolveCodec } from '../routerInternal/shared'\nimport type { NavigationRunResult } from './navigationResult'\nimport type { RouteStateSyncPayload } from './routeSync'\nimport type {\n InitialNavigationMode,\n LocationQueryRaw,\n NavigationAfterEach,\n NavigationErrorHandler,\n NavigationGuard,\n RouteLocationNormalizedLoaded,\n RouteLocationRaw,\n RouterNavigation,\n UseRouterOptions,\n} from './types'\nimport {\n cloneRouteMeta,\n cloneRouteParams,\n createNamedRouteLookup,\n createNativeRouteUrl,\n createRouterOptionsSnapshot,\n mergeMatchedRouteMeta,\n normalizeRouteRecordMatched,\n parseQuery,\n resolveCurrentRoute,\n resolveMatchedRouteRecord,\n resolveNamedRouteLocation,\n resolvePath,\n resolveRouteOptionEntries,\n snapshotRouteLocation,\n stringifyQuery,\n warnDuplicateRouteEntries,\n} from '../routerInternal/shared'\nimport { getCurrentMiniProgramTabBarPagePaths, getMiniProgramGlobalObject } from '../runtime/platform'\nimport { resolveBackNavigationTarget, runBackNavigationGuards } from './backNavigation'\nimport { DEFAULT_INITIAL_NAVIGATION_TIMEOUT, registerInitialNavigationRunner } from './initialNavigation'\nimport { setActiveRouter } from './instance'\nimport { createNavigationApi } from './navigationApi'\nimport { createNavigationFailure, executeNavigationMethod } from './navigationCore'\nimport { createNavigationResultController } from './navigationResult'\nimport { navigateWithTarget } from './navigationTarget'\nimport { resolveRouteLocation } from './resolve'\nimport { createRouteRegistry } from './routeRegistry'\nimport { installRouteStateSyncOnNativeRouter, notifyRouteStateSync } from './routeSync'\nimport { NavigationFailureType } from './types'\nimport { createRouteStateController, useNativeRouter } from './useRoute'\n\n/**\n * @description 创建高阶路由导航器(对齐 Vue Router 的 createRouter 心智)\n */\nexport function createRouter(options: UseRouterOptions = {}): RouterNavigation {\n const nativeRouter = useNativeRouter()\n installRouteStateSyncOnNativeRouter(getMiniProgramGlobalObject())\n const beforeEachGuards = new Set<NavigationGuard>()\n const beforeResolveGuards = new Set<NavigationGuard>()\n const afterEachHooks = new Set<NavigationAfterEach>()\n const errorHandlers = new Set<NavigationErrorHandler>()\n const maxRedirects = options.maxRedirects ?? 10\n const initialNavigationMode: InitialNavigationMode = options.initialNavigationMode === 'blocking' ? 'blocking' : 'eager'\n const initialNavigationTimeout = Number.isFinite(options.initialNavigationTimeout) && (options.initialNavigationTimeout ?? 0) > 0\n ? Math.max(1, Math.trunc(options.initialNavigationTimeout!))\n : DEFAULT_INITIAL_NAVIGATION_TIMEOUT\n const paramsMode = options.paramsMode ?? 'loose'\n const rejectOnError = options.rejectOnError ?? true\n const routeResolveCodec: RouteResolveCodec = {\n parseQuery: options.parseQuery ?? parseQuery,\n stringifyQuery: options.stringifyQuery ?? stringifyQuery,\n }\n const readyPromise = Promise.resolve()\n const routeEntries = resolveRouteOptionEntries(options)\n warnDuplicateRouteEntries(routeEntries)\n const namedRouteLookup = createNamedRouteLookup(routeEntries)\n const tabBarEntrySource = options.tabBarEntries ?? getCurrentMiniProgramTabBarPagePaths()\n const normalizedTabBarEntries = tabBarEntrySource\n .map(path => resolvePath(path, ''))\n .filter(Boolean)\n const tabBarPathSet = new Set(normalizedTabBarEntries)\n const routeRegistry = createRouteRegistry(namedRouteLookup)\n let managedNavigationCount = 0\n let activeManagedRoutePath: string | undefined\n let pendingManagedRouteSyncPath: string | undefined\n let pendingExternalRouteSyncPath: string | undefined\n const routerOptions = createRouterOptionsSnapshot(\n normalizedTabBarEntries,\n routeRegistry.getRoutes(),\n paramsMode,\n maxRedirects,\n initialNavigationMode,\n initialNavigationTimeout,\n routeResolveCodec,\n rejectOnError,\n )\n\n function enrichRouteRecordState(routeLocation: RouteLocationNormalizedLoaded): RouteLocationNormalizedLoaded {\n const resolved = { ...routeLocation }\n resolved.href = resolved.fullPath\n const matchedResult = resolveMatchedRouteRecord(resolved, namedRouteLookup)\n if (matchedResult) {\n const matchedRecord = matchedResult.record\n if (resolved.name === undefined) {\n resolved.name = matchedRecord.name\n }\n const mergedRouteMeta = mergeMatchedRouteMeta(matchedResult.matchedRecords)\n if (mergedRouteMeta !== undefined) {\n resolved.meta = cloneRouteMeta(mergedRouteMeta)\n }\n if (matchedResult.params && Object.keys(resolved.params).length === 0) {\n resolved.params = cloneRouteParams(matchedResult.params)\n }\n resolved.matched = matchedResult.matchedRecords.map((record, index, records) => {\n const leafMatchedPath = index === records.length - 1\n ? matchedResult.matchedPath\n : undefined\n return normalizeRouteRecordMatched(record, leafMatchedPath)\n })\n }\n else {\n resolved.matched = []\n }\n return resolved\n }\n\n function resolveWithCodec(to: RouteLocationRaw, currentPath: string): RouteLocationNormalizedLoaded {\n const rawTo = typeof to === 'string'\n ? to\n : resolveNamedRouteLocation(to, namedRouteLookup, paramsMode)\n return enrichRouteRecordState(resolveRouteLocation(rawTo, currentPath, routeResolveCodec))\n }\n\n let route: Readonly<RouteLocationNormalizedLoaded>\n let emitObservedNavigationAfterEach: ((result: NavigationRunResult) => Promise<void>) | undefined\n\n function isExternalBackSync(payload: RouteStateSyncPayload): boolean {\n return payload.source === 'page'\n || (payload.source === 'native' && payload.method === 'navigateBack')\n }\n\n function beforeRouteStateSync(\n nextRoute: RouteLocationNormalizedLoaded,\n payload: RouteStateSyncPayload,\n ) {\n if (managedNavigationCount > 0 || !isExternalBackSync(payload)) {\n return\n }\n\n if (pendingExternalRouteSyncPath !== undefined) {\n return\n }\n\n if (pendingManagedRouteSyncPath !== undefined) {\n const expectedPath = pendingManagedRouteSyncPath\n pendingManagedRouteSyncPath = undefined\n if (nextRoute.fullPath === expectedPath) {\n return\n }\n }\n\n if (nextRoute.fullPath === route.fullPath) {\n return\n }\n\n pendingExternalRouteSyncPath = nextRoute.fullPath\n const from = snapshotRouteLocation(route)\n void runBackNavigationGuards({\n target: nextRoute,\n from,\n nativeRouter,\n beforeEachGuards,\n beforeResolveGuards,\n resolveWithCodec,\n }).then((result) => {\n return emitObservedNavigationAfterEach?.(result)\n }).finally(() => {\n pendingExternalRouteSyncPath = undefined\n })\n }\n\n const routeController = createRouteStateController({\n beforeRouteStateSync,\n resolveRoute: enrichRouteRecordState,\n })\n route = routeController.route\n\n function resolve(to: RouteLocationRaw): RouteLocationNormalizedLoaded {\n return resolveWithCodec(to, route.path)\n }\n\n const navigationResultController = createNavigationResultController({\n afterEachHooks,\n errorHandlers,\n nativeRouter,\n rejectOnError,\n })\n emitObservedNavigationAfterEach = navigationResultController.emitNavigationAfterEach\n\n const navigationApi = createNavigationApi({\n nativeRouter,\n route,\n routeResolveCodec,\n namedRouteLookup,\n beforeEachGuards,\n beforeResolveGuards,\n maxRedirects,\n tabBarPathSet,\n resolveWithCodec,\n settleNavigationResult: navigationResultController.settleNavigationResult,\n })\n\n async function runManagedNavigation<T>(navigation: () => Promise<T>, targetPath?: string): Promise<T> {\n const previousRoutePath = route.fullPath\n if (targetPath) {\n activeManagedRoutePath = targetPath\n }\n managedNavigationCount += 1\n try {\n const result = await navigation()\n if (route.fullPath !== previousRoutePath) {\n pendingManagedRouteSyncPath = route.fullPath\n }\n return result\n }\n finally {\n managedNavigationCount -= 1\n if (managedNavigationCount <= 0) {\n activeManagedRoutePath = undefined\n }\n }\n }\n\n function resolveManagedRoutePath(to: RouteLocationRaw): string | undefined {\n try {\n return resolveWithCodec(to, route.path).fullPath\n }\n catch {\n return undefined\n }\n }\n\n async function runInitialNavigation(\n page: Parameters<typeof resolveCurrentRoute>[1],\n query?: LocationQueryRaw,\n isActive: () => boolean = () => true,\n ) {\n return runManagedNavigation(async () => {\n const from = snapshotRouteLocation(route)\n const target = enrichRouteRecordState(resolveCurrentRoute(query, page))\n if (!target.path) {\n return undefined\n }\n if (activeManagedRoutePath === target.fullPath) {\n notifyRouteStateSync({\n route: target,\n source: 'router',\n })\n return undefined\n }\n const result = await navigateWithTarget({\n mode: 'push',\n target,\n from,\n nativeRouter,\n routeResolveCodec,\n namedRouteLookup,\n beforeEachGuards,\n beforeResolveGuards,\n maxRedirects,\n tabBarPathSet,\n resolveWithCodec,\n executeNative: false,\n allowSameLocation: true,\n })\n if (!isActive()) {\n return undefined\n }\n if (initialNavigationMode === 'blocking' && result.to && result.to.fullPath !== target.fullPath) {\n const redirectedTarget = result.to\n const isTabBarTarget = tabBarPathSet.has(redirectedTarget.path)\n const method = isTabBarTarget ? nativeRouter.switchTab : nativeRouter.redirectTo\n const nativeResult = await executeNavigationMethod(\n method as (options: Record<string, any>) => unknown,\n { url: createNativeRouteUrl(redirectedTarget, routeResolveCodec.stringifyQuery) },\n redirectedTarget,\n from,\n )\n if (nativeResult) {\n return nativeResult\n }\n notifyRouteStateSync({\n route: redirectedTarget,\n source: 'router',\n })\n return createNavigationFailure(NavigationFailureType.cancelled, redirectedTarget, from)\n }\n return navigationResultController.settleNavigationResult(result)\n })\n }\n\n function beforeEach(guard: NavigationGuard): () => void {\n beforeEachGuards.add(guard)\n return () => {\n beforeEachGuards.delete(guard)\n }\n }\n\n function beforeResolve(guard: NavigationGuard): () => void {\n beforeResolveGuards.add(guard)\n return () => {\n beforeResolveGuards.delete(guard)\n }\n }\n\n function afterEach(hook: NavigationAfterEach): () => void {\n afterEachHooks.add(hook)\n return () => {\n afterEachHooks.delete(hook)\n }\n }\n\n function onError(handler: NavigationErrorHandler): () => void {\n errorHandlers.add(handler)\n return () => {\n errorHandlers.delete(handler)\n }\n }\n\n const router: RouterNavigation = {\n nativeRouter,\n options: routerOptions,\n currentRoute: route,\n install(app?: unknown): void {\n setActiveRouter(router)\n const globalProperties = (app as { config?: { globalProperties?: Record<string, unknown> } } | undefined)?.config?.globalProperties\n if (globalProperties) {\n globalProperties.$router = router\n }\n },\n resolve,\n isReady(): Promise<void> {\n return readyPromise\n },\n push: to => runManagedNavigation(() => navigationApi.push(to), resolveManagedRoutePath(to)),\n replace: to => runManagedNavigation(() => navigationApi.replace(to), resolveManagedRoutePath(to)),\n back: delta => runManagedNavigation(\n () => navigationApi.back(delta),\n resolveBackNavigationTarget(delta ?? 1, route, resolveWithCodec)?.fullPath,\n ),\n go: delta => runManagedNavigation(\n () => navigationApi.go(delta),\n delta < 0\n ? resolveBackNavigationTarget(Math.abs(delta), route, resolveWithCodec)?.fullPath\n : undefined,\n ),\n forward: () => runManagedNavigation(() => navigationApi.forward()),\n hasRoute: routeRegistry.hasRoute,\n getRoutes: routeRegistry.getRoutes,\n addRoute: routeRegistry.addRoute,\n removeRoute: routeRegistry.removeRoute,\n clearRoutes: routeRegistry.clearRoutes,\n beforeEach,\n beforeResolve,\n afterEach,\n onError,\n }\n\n setActiveRouter(router)\n registerInitialNavigationRunner(router, runInitialNavigation, initialNavigationTimeout, initialNavigationMode)\n return router\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,aAAa,UAA4B,CAAC,GAAqB;;CAC7E,MAAM,eAAe,gBAAgB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IAAI,KAAK,GAAG,OAAO,gBAAgB,mFAAG,WACvE,MACN;;EACA,eAAe,2BAA2B,cAAc,QAAQ,CAAC;EACjE,UAAU,cAAc;EACxB,WAAW,cAAc;EACzB,UAAU,cAAc;EACxB,aAAa,cAAc;EAC3B,aAAa,cAAc;EAC3B;EACA;EACA;EACA;CACF;CAEA,gBAAgB,MAAM;CACtB,gCAAgC,QAAQ,sBAAsB,0BAA0B,qBAAqB;CAC7G,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"createRouter.mjs","names":["typedRouter"],"sources":["../../../src/router/createRouter.ts"],"sourcesContent":["import type { WevuNamedRouteMap } from '../router'\nimport type { RouteResolveCodec } from '../routerInternal/shared'\nimport type { NavigationRunResult } from './navigationResult'\nimport type { RouteStateSyncPayload } from './routeSync'\nimport type {\n InitialNavigationMode,\n LocationQueryRaw,\n NavigationAfterEach,\n NavigationErrorHandler,\n NavigationGuard,\n RouteLocationNormalizedLoaded,\n RouteLocationRaw,\n RouterNavigation,\n UseRouterOptions,\n} from './types'\nimport {\n cloneRouteMeta,\n cloneRouteParams,\n createNamedRouteLookup,\n createNativeRouteUrl,\n createRouterOptionsSnapshot,\n mergeMatchedRouteMeta,\n normalizeRouteRecordMatched,\n parseQuery,\n resolveCurrentRoute,\n resolveMatchedRouteRecord,\n resolveNamedRouteLocation,\n resolvePath,\n resolveRouteOptionEntries,\n snapshotRouteLocation,\n stringifyQuery,\n warnDuplicateRouteEntries,\n} from '../routerInternal/shared'\nimport { getCurrentMiniProgramTabBarPagePaths, getMiniProgramGlobalObject } from '../runtime/platform'\nimport { resolveBackNavigationTarget, runBackNavigationGuards } from './backNavigation'\nimport { DEFAULT_INITIAL_NAVIGATION_TIMEOUT, registerInitialNavigationRunner } from './initialNavigation'\nimport { setActiveRouter } from './instance'\nimport { createNavigationApi } from './navigationApi'\nimport { createNavigationFailure, executeNavigationMethod } from './navigationCore'\nimport { createNavigationResultController } from './navigationResult'\nimport { navigateWithTarget } from './navigationTarget'\nimport { resolveRouteLocation } from './resolve'\nimport { createRouteRegistry } from './routeRegistry'\nimport { installRouteStateSyncOnNativeRouter, notifyRouteStateSync } from './routeSync'\nimport { NavigationFailureType } from './types'\nimport { createRouteStateController, useNativeRouter } from './useRoute'\n\n/**\n * @description 创建高阶路由导航器(对齐 Vue Router 的 createRouter 心智)\n */\nexport function createRouter<TRouteMap extends object = WevuNamedRouteMap>(\n optionsInput: UseRouterOptions<NoInfer<TRouteMap>> = {},\n): RouterNavigation<TRouteMap> {\n // 路由表泛型只约束公开类型;运行时继续使用同一套名称无关的导航引擎。\n const options = optionsInput as unknown as UseRouterOptions\n const nativeRouter = useNativeRouter()\n installRouteStateSyncOnNativeRouter(getMiniProgramGlobalObject())\n const beforeEachGuards = new Set<NavigationGuard>()\n const beforeResolveGuards = new Set<NavigationGuard>()\n const afterEachHooks = new Set<NavigationAfterEach>()\n const errorHandlers = new Set<NavigationErrorHandler>()\n const maxRedirects = options.maxRedirects ?? 10\n const initialNavigationMode: InitialNavigationMode = options.initialNavigationMode === 'blocking' ? 'blocking' : 'eager'\n const initialNavigationTimeout = Number.isFinite(options.initialNavigationTimeout) && (options.initialNavigationTimeout ?? 0) > 0\n ? Math.max(1, Math.trunc(options.initialNavigationTimeout!))\n : DEFAULT_INITIAL_NAVIGATION_TIMEOUT\n const paramsMode = options.paramsMode ?? 'loose'\n const rejectOnError = options.rejectOnError ?? true\n const routeResolveCodec: RouteResolveCodec = {\n parseQuery: options.parseQuery ?? parseQuery,\n stringifyQuery: options.stringifyQuery ?? stringifyQuery,\n }\n const readyPromise = Promise.resolve()\n const routeEntries = resolveRouteOptionEntries(options)\n warnDuplicateRouteEntries(routeEntries)\n const namedRouteLookup = createNamedRouteLookup(routeEntries)\n const tabBarEntrySource = options.tabBarEntries ?? getCurrentMiniProgramTabBarPagePaths()\n const normalizedTabBarEntries = tabBarEntrySource\n .map(path => resolvePath(path, ''))\n .filter(Boolean)\n const tabBarPathSet = new Set(normalizedTabBarEntries)\n const routeRegistry = createRouteRegistry(namedRouteLookup)\n let managedNavigationCount = 0\n let activeManagedRoutePath: string | undefined\n let pendingManagedRouteSyncPath: string | undefined\n let pendingExternalRouteSyncPath: string | undefined\n const routerOptions = createRouterOptionsSnapshot(\n normalizedTabBarEntries,\n routeRegistry.getRoutes(),\n paramsMode,\n maxRedirects,\n initialNavigationMode,\n initialNavigationTimeout,\n routeResolveCodec,\n rejectOnError,\n )\n\n function enrichRouteRecordState(routeLocation: RouteLocationNormalizedLoaded): RouteLocationNormalizedLoaded {\n const resolved = { ...routeLocation }\n resolved.href = resolved.fullPath\n const matchedResult = resolveMatchedRouteRecord(resolved, namedRouteLookup)\n if (matchedResult) {\n const matchedRecord = matchedResult.record\n if (resolved.name === undefined) {\n resolved.name = matchedRecord.name\n }\n const mergedRouteMeta = mergeMatchedRouteMeta(matchedResult.matchedRecords)\n if (mergedRouteMeta !== undefined) {\n resolved.meta = cloneRouteMeta(mergedRouteMeta)\n }\n if (matchedResult.params && Object.keys(resolved.params).length === 0) {\n resolved.params = cloneRouteParams(matchedResult.params)\n }\n resolved.matched = matchedResult.matchedRecords.map((record, index, records) => {\n const leafMatchedPath = index === records.length - 1\n ? matchedResult.matchedPath\n : undefined\n return normalizeRouteRecordMatched(record, leafMatchedPath)\n })\n }\n else {\n resolved.matched = []\n }\n return resolved\n }\n\n function resolveWithCodec(to: RouteLocationRaw, currentPath: string): RouteLocationNormalizedLoaded {\n const rawTo = typeof to === 'string'\n ? to\n : resolveNamedRouteLocation(to, namedRouteLookup, paramsMode)\n return enrichRouteRecordState(resolveRouteLocation(rawTo, currentPath, routeResolveCodec))\n }\n\n let route: Readonly<RouteLocationNormalizedLoaded>\n let emitObservedNavigationAfterEach: ((result: NavigationRunResult) => Promise<void>) | undefined\n\n function isExternalBackSync(payload: RouteStateSyncPayload): boolean {\n return payload.source === 'page'\n || (payload.source === 'native' && payload.method === 'navigateBack')\n }\n\n function beforeRouteStateSync(\n nextRoute: RouteLocationNormalizedLoaded,\n payload: RouteStateSyncPayload,\n ) {\n if (managedNavigationCount > 0 || !isExternalBackSync(payload)) {\n return\n }\n\n if (pendingExternalRouteSyncPath !== undefined) {\n return\n }\n\n if (pendingManagedRouteSyncPath !== undefined) {\n const expectedPath = pendingManagedRouteSyncPath\n pendingManagedRouteSyncPath = undefined\n if (nextRoute.fullPath === expectedPath) {\n return\n }\n }\n\n if (nextRoute.fullPath === route.fullPath) {\n return\n }\n\n pendingExternalRouteSyncPath = nextRoute.fullPath\n const from = snapshotRouteLocation(route)\n void runBackNavigationGuards({\n target: nextRoute,\n from,\n nativeRouter,\n beforeEachGuards,\n beforeResolveGuards,\n resolveWithCodec,\n }).then((result) => {\n return emitObservedNavigationAfterEach?.(result)\n }).finally(() => {\n pendingExternalRouteSyncPath = undefined\n })\n }\n\n const routeController = createRouteStateController({\n beforeRouteStateSync,\n resolveRoute: enrichRouteRecordState,\n })\n route = routeController.route\n\n const resolve = (to: RouteLocationRaw): RouteLocationNormalizedLoaded =>\n resolveWithCodec(to, route.path)\n\n const navigationResultController = createNavigationResultController({\n afterEachHooks,\n errorHandlers,\n nativeRouter,\n rejectOnError,\n })\n emitObservedNavigationAfterEach = navigationResultController.emitNavigationAfterEach\n\n const navigationApi = createNavigationApi({\n nativeRouter,\n route,\n routeResolveCodec,\n namedRouteLookup,\n beforeEachGuards,\n beforeResolveGuards,\n maxRedirects,\n tabBarPathSet,\n resolveWithCodec,\n settleNavigationResult: navigationResultController.settleNavigationResult,\n })\n\n async function runManagedNavigation<T>(navigation: () => Promise<T>, targetPath?: string): Promise<T> {\n const previousRoutePath = route.fullPath\n if (targetPath) {\n activeManagedRoutePath = targetPath\n }\n managedNavigationCount += 1\n try {\n const result = await navigation()\n if (route.fullPath !== previousRoutePath) {\n pendingManagedRouteSyncPath = route.fullPath\n }\n return result\n }\n finally {\n managedNavigationCount -= 1\n if (managedNavigationCount <= 0) {\n activeManagedRoutePath = undefined\n }\n }\n }\n\n function resolveManagedRoutePath(to: RouteLocationRaw): string | undefined {\n try {\n return resolveWithCodec(to, route.path).fullPath\n }\n catch {\n return undefined\n }\n }\n\n async function runInitialNavigation(\n page: Parameters<typeof resolveCurrentRoute>[1],\n query?: LocationQueryRaw,\n isActive: () => boolean = () => true,\n ) {\n return runManagedNavigation(async () => {\n const from = snapshotRouteLocation(route)\n const target = enrichRouteRecordState(resolveCurrentRoute(query, page))\n if (!target.path) {\n return undefined\n }\n if (activeManagedRoutePath === target.fullPath) {\n notifyRouteStateSync({\n route: target,\n source: 'router',\n })\n return undefined\n }\n const result = await navigateWithTarget({\n mode: 'push',\n target,\n from,\n nativeRouter,\n routeResolveCodec,\n namedRouteLookup,\n beforeEachGuards,\n beforeResolveGuards,\n maxRedirects,\n tabBarPathSet,\n resolveWithCodec,\n executeNative: false,\n allowSameLocation: true,\n })\n if (!isActive()) {\n return undefined\n }\n if (initialNavigationMode === 'blocking' && result.to && result.to.fullPath !== target.fullPath) {\n const redirectedTarget = result.to\n const isTabBarTarget = tabBarPathSet.has(redirectedTarget.path)\n const method = isTabBarTarget ? nativeRouter.switchTab : nativeRouter.redirectTo\n const nativeResult = await executeNavigationMethod(\n method as (options: Record<string, any>) => unknown,\n { url: createNativeRouteUrl(redirectedTarget, routeResolveCodec.stringifyQuery) },\n redirectedTarget,\n from,\n )\n if (nativeResult) {\n return nativeResult\n }\n notifyRouteStateSync({\n route: redirectedTarget,\n source: 'router',\n })\n return createNavigationFailure(NavigationFailureType.cancelled, redirectedTarget, from)\n }\n return navigationResultController.settleNavigationResult(result)\n })\n }\n\n function beforeEach(guard: NavigationGuard): () => void {\n beforeEachGuards.add(guard)\n return () => {\n beforeEachGuards.delete(guard)\n }\n }\n\n function beforeResolve(guard: NavigationGuard): () => void {\n beforeResolveGuards.add(guard)\n return () => {\n beforeResolveGuards.delete(guard)\n }\n }\n\n function afterEach(hook: NavigationAfterEach): () => void {\n afterEachHooks.add(hook)\n return () => {\n afterEachHooks.delete(hook)\n }\n }\n\n function onError(handler: NavigationErrorHandler): () => void {\n errorHandlers.add(handler)\n return () => {\n errorHandlers.delete(handler)\n }\n }\n\n const router: RouterNavigation = {\n nativeRouter,\n options: routerOptions,\n currentRoute: route,\n install(app?: unknown): void {\n setActiveRouter(router)\n const globalProperties = (app as { config?: { globalProperties?: Record<string, unknown> } } | undefined)?.config?.globalProperties\n if (globalProperties) {\n globalProperties.$router = router\n }\n },\n resolve,\n isReady(): Promise<void> {\n return readyPromise\n },\n push: to => runManagedNavigation(() => navigationApi.push(to), resolveManagedRoutePath(to)),\n replace: to => runManagedNavigation(() => navigationApi.replace(to), resolveManagedRoutePath(to)),\n back: delta => runManagedNavigation(\n () => navigationApi.back(delta),\n resolveBackNavigationTarget(delta ?? 1, route, resolveWithCodec)?.fullPath,\n ),\n go: delta => runManagedNavigation(\n () => navigationApi.go(delta),\n delta < 0\n ? resolveBackNavigationTarget(Math.abs(delta), route, resolveWithCodec)?.fullPath\n : undefined,\n ),\n forward: () => runManagedNavigation(() => navigationApi.forward()),\n hasRoute: routeRegistry.hasRoute,\n getRoutes: routeRegistry.getRoutes,\n addRoute: routeRegistry.addRoute,\n removeRoute: routeRegistry.removeRoute,\n clearRoutes: routeRegistry.clearRoutes,\n beforeEach,\n beforeResolve,\n afterEach,\n onError,\n }\n\n setActiveRouter(router)\n registerInitialNavigationRunner(router, runInitialNavigation, initialNavigationTimeout, initialNavigationMode)\n const typedRouter = router as unknown as RouterNavigation<TRouteMap>\n return typedRouter\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,aACd,eAAqD,CAAC,GACzB;;CAE7B,MAAM,UAAU;CAChB,MAAM,eAAe,gBAAgB;CACrC,oCAAoC,2BAA2B,CAAC;CAChE,MAAM,mCAAmB,IAAI,IAAqB;CAClD,MAAM,sCAAsB,IAAI,IAAqB;CACrD,MAAM,iCAAiB,IAAI,IAAyB;CACpD,MAAM,gCAAgB,IAAI,IAA4B;CACtD,MAAM,wCAAe,QAAQ,qFAAgB;CAC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AAM;CACtB,gCAAgC,QAAQ,sBAAsB,0BAA0B,qBAAqB;CAE7G,OAAOA;AACT"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NavigationFailure, NavigationFailureTypeValue, RouteLocationNormalizedLoaded } from "./types.mjs";
|
|
2
|
+
import { WevuNamedRouteMap } from "../router.mjs";
|
|
2
3
|
//#region src/router/navigationCore.d.ts
|
|
3
|
-
export declare function createNavigationFailure(type: NavigationFailureTypeValue, to?: RouteLocationNormalizedLoaded
|
|
4
|
-
export declare function isNavigationFailure(error: unknown, type?: NavigationFailureTypeValue): error is NavigationFailure
|
|
4
|
+
export declare function createNavigationFailure<TRouteMap extends object = WevuNamedRouteMap>(type: NavigationFailureTypeValue, to?: RouteLocationNormalizedLoaded<NoInfer<TRouteMap>>, from?: RouteLocationNormalizedLoaded<NoInfer<TRouteMap>>, cause?: unknown): NavigationFailure<TRouteMap>;
|
|
5
|
+
export declare function isNavigationFailure<TRouteMap extends object = WevuNamedRouteMap>(error: unknown, type?: NavigationFailureTypeValue): error is NavigationFailure<TRouteMap>;
|
|
5
6
|
//#endregion
|
|
6
7
|
//# sourceMappingURL=navigationCore.d.mts.map
|
|
@@ -22,13 +22,13 @@ function resolveNavigationFailureType(error) {
|
|
|
22
22
|
}
|
|
23
23
|
function createNavigationFailure(type, to, from, cause) {
|
|
24
24
|
const message = normalizeNavigationErrorMessage(cause) || "Navigation failed";
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
25
|
+
return Object.assign(new Error(message), {
|
|
26
|
+
__wevuNavigationFailure: true,
|
|
27
|
+
type,
|
|
28
|
+
to,
|
|
29
|
+
from,
|
|
30
|
+
cause
|
|
31
|
+
});
|
|
32
32
|
}
|
|
33
33
|
function isNavigationFailure(error, type) {
|
|
34
34
|
if (!error || typeof error !== "object") return false;
|