} - 返回视图构建函数
*/
export declare function builder(builder: (props: P, location?: CodeLocation) => R, displayName?: string): ViewBuilder
;
/**
* class属性值类型
*
* @remarks
* 该类型支持多种形式的class定义:
* - 字符串:单个或多个以空格分隔的类名
* - 数组:数组的每个字符串元素都会被视为一个类名,会过滤掉==false的元素
* - 对象:键为类名,值为布尔值,表示是否应用该类
*
* @example
* ```ts
* // 字符串形式
* const class1: ClassProperties = 'btn btn-primary'
*
* // 数组形式
* const class2: ClassProperties = ['btn', 'btn-primary']
*
* // 对象形式
* const class3: ClassProperties = {
* btn: true,
* 'btn-primary': true,
* 'btn-large': false
* }
* ```
*/
export declare type ClassProperties = string | any[] | Record;
/**
* 清除指定 loader 的所有缓存
*
* 同时清除已加载缓存和加载中缓存
*
* 注意:谨慎使用,仅应用于测试环境。
*
* @param loader - 懒加载器函数
*
* @example
* ```ts
* const loader = () => import('./MyComponent.js')
*
* // 清除缓存,下次使用时会重新加载
* clearComponentCache(loader)
* ```
*/
export declare function clearComponentCache(loader: LazyLoader): void;
/**
* 代码位置
*
* 用于记录视图的生成位置
*/
export declare interface CodeLocation extends CodeSource {
}
/**
* CommentView 组件化构建器
*
* 用于创建 Comment 视图节点。
*
* @param props - Comment 节点的属性对象
* @param [props.text] - 注释内容,不能动态更新!
* @return {CommentView} CommentView
*/
declare const Comment_2: ViewBuilder;
declare type Comment_2 = ViewBuilder & {
__is_comment: true;
};
export { Comment_2 as Comment }
export declare interface CommentProps {
text: string;
}
/**
* CommentView 类用于表示和渲染注释节点。
*
* 核心功能:
* - 继承自 BaseAtomicView,专门处理注释类型的视图
* - 提供注释渲染的基础功能
*
* 使用示例:
* ```typescript
* const commentView = new CommentView();
* commentView.mount(container);
* ```
*/
export declare class CommentView extends BaseAtomicView {
readonly kind = ViewKind.COMMENT;
protected createNode(renderer: ViewRenderer, text: string): HostComment;
}
export declare type Component = {
/**
* 组件函数。
*
* @param props - 组件属性对象
* @param [location] - 组件位置信息,仅开发模式下存在
*/
(props: P, location?: CodeLocation): RenderChild;
/**
* 定义组件的默认属性。
*
* - 在组件实例创建时,`defaultProps` 会自动注入到 `props` 中。
* - 当外部未传入某个属性时,其默认值通过代理的 `get` 拦截动态返回,
* 因此 **不会直接合并到 `props` 对象本身**。
* - 注意:在组件实例中,`props` 是只读的对象:
*
* @example
* ```ts
* // 函数组件
* function MyComponent(props: { name?: string; age: number }) {
* return
{props.name}
;
* }
* MyComponent.defaultProps = {
* age: 18,
* };
* ```
*/
defaultProps?: AnyProps;
/**
* 属性验证函数。
*
* 用于校验传入的 props 是否符合预期
*
* 校验时机:仅开发模式下节点创建之前进行校验
*
* 校验结果说明:
* - `string`:打印警告日志信息。
* - `false`:打印默认的校验失败信息。
* - throw new Error('自定义异常'):如果不希望继续渲染组件,则可以抛出异常。
* - 其他值/void:校验通过。
*
* 仅在开发模式下进行校验,生产模式下不会进行校验。
*
* @example
* ```ts
* defineValidate(MyComponent, (props) => {
* if (props.age < 0) {
* return 'age cannot be less than 0';
* }
* });
* ```
*
* @param props - 传入的组件属性对象
* @returns {string | false | unknown} 校验结果
*/
validateProps?: ValidateProps;
/**
* 组件展示的名称,仅用于调试。
*/
displayName?: string;
};
/**
* 组件实例类,用于管理和维护组件的运行时状态。
*
* 核心功能:
* - 管理组件的生命周期(初始化、显示、隐藏、销毁)
* - 处理组件的副作用和依赖收集
* - 管理组件的视图渲染和子视图
* - 提供组件间的依赖注入和错误处理机制
*
* @template T - 组件类型,默认为 `Component`
* @constructor
* @param {ComponentView} view - 组件视图对象,包含组件定义、属性、指令等信息
*
* @remarks
* - ⚠️ 该类主要由框架内部使用,不应直接实例化!!!
* - ⚠️ 所有方法皆为框架内部核心使用,开发者请勿随意使用!!!
* - ⚠️ 所有属性面向开发者都是只读的,请勿随意修改!!!
*/
export declare class ComponentInstance {
readonly view: ComponentView;
/** 所属应用应用 */
readonly app: App | null;
/** 所属父组件实例 */
readonly parent: ComponentInstance | null;
/* Excluded from this release type: hooks */
/** 组件的副作用管理作用域 */
readonly scope: EffectScope;
/** 组件公开实例,只读!*/
readonly publicInstance: ComponentPublicInstance;
/* Excluded from this release type: provide */
/* Excluded from this release type: directiveStore */
/* Excluded from this release type: onViewSwitch */
/* Excluded from this release type: errorHandler */
/** 组件的子视图 */
readonly subView: View;
/** 异步初始化 */
initPromise?: Promise;
/** 给子视图继承的上下文 */
readonly subViewContext: ViewContext;
/* Excluded from this release type: _isMounted */
constructor(view: ComponentView);
/**
* 获取组件是否已挂载的状态
* 这是一个getter方法,用于返回组件的挂载状态
*
* @returns {boolean} 返回组件是否已挂载,true表示已挂载,false表示未挂载
*/
get isMounted(): boolean;
/* Excluded from this release type: init */
/* Excluded from this release type: beforeMount */
/* Excluded from this release type: mounted */
/* Excluded from this release type: show */
/* Excluded from this release type: hide */
/* Excluded from this release type: dispose */
/**
* 报告错误的方法
*
* @param error - 发生的错误对象
* @param source - 错误来源
* @param instance - 可选的组件实例,默认为当前实例
*/
reportError(error: unknown, source: ErrorSource, instance?: ComponentInstance): void;
/**
* 调用无返回值的钩子
*
* @param stage - 钩子阶段
* @private
*/
private invokeVoidHook;
/**
* 规范化视图,将各种类型的子节点转换为标准的 View 对象
*
* 处理顺序:
* 1. null/undefined/boolean - 转换为空组件注释
* 2. View 对象 - 直接返回
* 3. Ref 对象 - 包装为 DynamicView
* 4. 字符串/数字 - 转换为 TextView 或空组件注释
* 5. 其他类型 - 记录警告并返回错误注释
*
* @param child - 要规范化的子节点,可以是任意类型
* @returns {View} - 规范化后的 View 对象
* @throws {Error} 当转换过程中发生错误时抛出
*/
private normalizeView;
/**
* 获取暂停计数器
*
* @private
*/
private useSuspenseCounter;
}
/**
* 组件属性类型
*/
export declare type ComponentProps = C extends Component ? WithDefaultProps : {};
/**
* 组件公开实例类型
*/
export declare type ComponentPublicInstance = {
readonly [IS_RAW]: true;
readonly [key: keyof any]: any;
};
/**
* ComponentView 是用于管理和渲染组件实例的视图类。
* 它负责组件的初始化、挂载、更新和销毁等生命周期管理。
*
* 核心功能:
* - 组件实例的创建和管理
* - 组件属性解析和引用处理
* - 组件生命周期控制(初始化、挂载、销毁)
* - 组件子视图的管理
*
* @example
* ```typescript
* const componentView = new ComponentView(MyComponent, { prop1: 'value' }, 'myKey');
* componentView.init();
* componentView.mount(container);
* ```
*
* @template T - 组件类型,默认为 Component
*
* @remarks
* - 组件实例在初始化时创建,在销毁时释放
* - 组件引用(ref)会在挂载时自动设置
* - 组件销毁时会自动清理子视图和实例
*/
export declare class ComponentView extends BaseView {
/** 类型标识 */
readonly kind = ViewKind.COMPONENT;
/* Excluded from this release type: ref */
/** 组件实体函数 */
readonly component: T;
/** 传递给组件的参数 */
readonly props: AnyProps;
/** 组件运行时实例 */
instance: ComponentInstance | null;
/**
* @constructor
*
* @param component - 组件实体函数,定义组件的实现
* @param props - 传递给组件的属性对象,可以为 null
* @param [location] - 可选的代码位置信息,用于调试
*/
constructor(component: T, props?: ComponentProps | null, location?: CodeLocation);
/**
* 获取组件名称的getter方法
* 如果组件有displayName属性则使用displayName,否则使用name属性,如果都没有则使用默认值'anonymous'
*
* 返回格式为"Component<实际名称>"的字符串
*/
get name(): string;
protected get hostNode(): HostNode | null;
get subView(): View | null;
/**
* @inheritDoc
*/
mount(target: HostContainer | HostNode, type?: MountMode): this;
protected doActivate(): void;
protected doDeactivate(): void;
protected doInit(): void;
protected doMount(containerOrAnchor: HostContainer | HostNode, type: MountMode): void;
protected doDispose(root: boolean): void;
}
/**
* 创建注释视图
*
* @param text 注释内容
* @param location 代码位置信息,用于调试
* @returns {CommentView} 注释视图实例
*/
export declare function createCommentView(text: string, location?: CodeLocation): CommentView;
/**
* 创建组件视图
*
* @param component 组件类型
* @param props 组件属性,默认为null
* @param location 代码位置信息,用于调试
* @returns {ComponentView} 组件视图实例
*/
export declare function createComponentView(component: T, props?: InferProps | null, location?: CodeLocation): ComponentView;
/**
* 创建动态视图
*
* 动态视图根据响应式引用的值动态渲染不同的子视图
*
* @param source 响应式引用,用于决定显示哪个子视图
* @param location 代码位置信息,用于调试
* @returns {DynamicView} 切换视图实例
*/
export declare function createDynamicView(source: Ref, location?: CodeLocation): DynamicView;
/**
* 创建元素视图
*
* 元素视图代表一个DOM元素,如div、span等
*
* @param tag HTML标签名
* @param props 元素属性,可以为null
* @param location 代码位置信息,用于调试
* @returns {ElementView} 元素视图实例
*/
export declare function createElementView(tag: T, props: InferProps | null, location?: CodeLocation): ElementView;
/**
* 创建片段视图
* 片段视图用于包装多个子视图而不创建额外的DOM节点
*
* @param children 子视图或子元素
* @param location 代码位置信息,用于调试
* @returns {FragmentView} 片段视图实例
*/
export declare function createFragmentView(children: RenderChildren, location?: CodeLocation): FragmentView;
/**
* 创建并返回一个ListView实例的工厂函数
*
* @param items - 可选参数,用于初始化ListView的视图项数组
* @param location - 可选参数,用于指定代码位置信息
* @returns - 返回一个新的ListView实例
*/
export declare function createListView(items?: Iterable, location?: CodeLocation): ListView;
/**
* 创建文本视图
*
* @param text 要显示的文本内容
* @param location 代码位置信息,用于调试
* @returns {TextView} 文本视图实例
*/
export declare function createTextView(text: string, location?: CodeLocation): TextView;
/**
* 创建视图的工厂函数
*
* @template P - 视图属性的类型,必须扩展自 AnyProps
* @template V - 视图实例的类型,必须扩展自 View
* @param type - 视图构建器函数,用于创建指定类型的视图实例
* @param [props] - 可选的视图属性对象,默认为 null
* @param location - 可选的代码位置信息,用于调试和错误追踪
* @returns 返回创建的视图实例,类型为 B
*/
export declare function createView(type: ViewBuilder
, props?: P | null, location?: CodeLocation): V;
/**
* 创建组件视图实例
* 当传入类型参数为组件时,创建对应的组件视图
*
* @template T 组件类型
* @param type 组件类型
* @param props 组件属性,默认为null
* @param location 代码位置信息,用于调试
* @returns {ComponentView} 组件视图实例
*/
export declare function createView(type: T, props?: InferProps | null, location?: CodeLocation): ComponentView;
/**
* 创建元素视图实例
* 当传入类型参数为HTML标签时,创建对应的元素视图
*
* @template T HTML标签类型
* @param type HTML标签名称
* @param props 元素属性,默认为null
* @param location 代码位置信息,用于调试
* @returns {ElementView} 元素视图实例
*/
export declare function createView(type: T, props?: InferProps | null, location?: CodeLocation): ElementView;
/**
* 创建通用视图实例
* 当传入类型参数为视图标签时,创建对应的视图实例
*
* @template T 视图标签类型
* @param type 视图标签
* @param props 视图属性,默认为null
* @param location 代码位置信息,用于调试
* @returns {View} 视图实例
*/
export declare function createView(type: T, props?: InferProps | null, location?: CodeLocation): View;
/**
* 定义指令
*
* 如果在有状态的组件上下文中定义,则会将指令存储在当前组件的指令缓存中,否则存储在全局指令缓存中
*
* @param name - 指令名称
* @param directive - 指令配置对象或函数
* @returns void
*/
export declare function defineDirective(name: string, directive: Directive): void;
/**
* 暴露函数组件的内部成员,供外部ref使用。
*
* @example
* ```tsx
* import { defineExpose,ref } from 'vitarx'
*
* function Foo() {
* const count = ref(0);
* const add = () => count.value++;
* // 暴露 count 和 add
* defineExpose({ count, add });
* return {count}
;
* }
* ```
*
* @param {Record} exposed - 键值对对象。
*/
export declare function defineExpose(exposed: T): void;
/**
* 定义组件属性验证函数
*
* @param component - 要验证的组件
* @param validator - 验证函数,接收组件属性作为参数,返回值说明:false表示验证失败,字符串表示验证失败的提示信息,返回值视为验证成功
* @returns {void} 无返回值
*/
export declare function defineValidate(component: Component
, validator: ValidateProps): void;
export declare interface Directive {
/** 指令名称,仅用于调试 */
name?: string;
/**
* 元素已经创建时调用
*
* @param el - 宿主元素实例
* @param binding - 指令绑定信息对象
* @param view - 节点实例
*/
created?: DirectiveHook;
/**
* 元素挂载完成后调用
*
* @param el - 宿主元素实例
* @param binding - 指令绑定信息对象
* @param view - 节点实例
*/
mounted?: DirectiveHook;
/**
* 元素即将被销毁
*
* 在此方法中清理副作用,避免造成内存泄漏。
*/
dispose?: DirectiveHook;
/**
* 获取节点的属性对象,用于服务端渲染
*
* 返回的属性对象会和元素的属性对象合并。
*
* @param binding - 指令绑定信息对象
* @param view - 视图节点对象
* @return {object} 属性对象
*/
getSSRProps?(binding: DirectiveBinding, view: ElementView): Record | void;
}
export declare interface DirectiveBinding {
/**
* 指令绑定的值
*/
readonly value: any;
/**
* 指令绑定的参数
*/
readonly arg?: string;
}
export declare type DirectiveHook = (el: HostElement, binding: DirectiveBinding, view: ElementView) => void;
export declare type DirectiveMap = Map;
/**
* 动态视图构建器
*
* 根据传入的 `is` 属性动态渲染组件或元素。
* 支持响应式切换,当 `is` 值变化时自动更新渲染内容。
*
* @example
* ```tsx
* // 基础用法:动态组件
* const App = () => {
* const current = shallowRef(ComponentA)
* return
* }
* ```
*
* @example
* ```tsx
* // 动态元素标签
* const App = () => {
* const tag = ref<'div' | 'span'>('div')
* return Content
* }
* ```
*
* @example
* ```tsx
* // 传递属性
*
* ```
*
* @param props - 属性对象
* @param props.is - 动态渲染的目标(组件/元素标签)
* @param [props.memo=false] - 是否缓存组件视图实例
* @param [props.children] - 子元素插槽
* @returns {View} 动态/静态视图对象(取决于传入的is是否具有响应性)
*/
export declare const Dynamic: ViewBuilder;
export declare type Dynamic = ViewBuilder & {
__is_dynamic: true;
};
/**
* 声明式动态视图,始终创建 DynamicView 实例。
*
* 用于在 JSX 或非编译上下文中声明一个依赖响应式数据的动态子树。
* 无论构建函数是否包含响应式依赖,都会创建 DynamicView 以保证行为一致。
*
* 与 `Dynamic` 组件的区别:`Dynamic` 是结构级动态(根据 is 切换组件类型),
* `dynamic` 是表达式级动态(根据表达式结果重建子树)。
*
* 与 `expr` 的区别:`dynamic` 始终创建 DynamicView(语义明确),
* `expr` 在无依赖时直接返回原值,有依赖时返回 Ref(性能优化)。
*
* @param build 构建子视图的函数,内部访问的响应式数据变化时会重新执行
* @param [location] 代码位置信息,用于调试
* @returns 始终返回 `DynamicView` 实例
* @example
* ```jsx
* function App() {
* const show = ref(true)
*
* // 条件渲染:show 变化时自动切换子视图
* return dynamic(() => (show.value ? : ))
*
* // 派生文本:count 变化时更新文本内容
* // dynamic(() => count.value + 1)
* }
* ```
*/
export declare function dynamic(build: () => T, location?: CodeLocation): DynamicView;
export declare interface DynamicProps {
/**
* 动态渲染的目标
*
* 支持以下类型:
* - **组件函数**:`() => View` 或 `Component` 函数
* - **元素标签**:如 `'div'`、`'span'`、`'button'` 等
* - **响应式引用**:`Ref` 或 `Ref`
*
* @example
* ```tsx
* // 渲染组件
*
*
* // 渲染元素标签
* Content
*
* // 响应式切换
* const current = ref(ComponentA)
*
* ```
*/
is: ViewDescriptor | undefined | null | false;
/**
* 唯一标识
*
* 如需使同一个组件缓存不同的实例,可以传入一个`key`标识,它需和`is`传入的组件保持关联。
* 仅在 `memo` 启用时有效。
*
* @example
* ```tsx
* // 缓存同一组件的不同实例
*
* ```
*/
key?: unknown;
/**
* 组件视图缓存策略
*
* - `false`(默认):不缓存
* - `true`:缓存所有组件视图,不限制数量
* - `number > 0`:缓存指定数量的组件视图,采用 LRU 策略
* - `number <= 0`:等同于 `true`,不限制数量
*
* **注意**:
* - 仅对组件函数有效,元素标签不会被缓存
* - 缓存基于组件函数的引用,相同函数会复用同一视图
* - 如需完整的组件缓存功能(include/exclude),请使用 `Freeze` 组件
*
* @default false
*
* @example
* ```tsx
* // 缓存所有组件视图
*
*
* // 最多缓存 3 个组件视图(LRU 策略)
*
* ```
*/
memo?: boolean | number;
/**
* 子元素插槽内容
*
* 会原样传递给渲染的元素/组件
*/
children?: RenderChildren;
/**
* 其他自定义属性
*
* 会原样传递给渲染的元素/组件
*/
[key: string]: any;
}
/**
* 动态视图类,用于根据响应式数据源的变化动态渲染不同的视图内容。
*
* 核心功能:
* - 监听响应式数据源(source)的变化
* - 根据数据类型自动选择合适的视图类型(文本视图、空视图或自定义视图)
* - 提供视图切换的事务机制,支持自定义切换逻辑
* - 管理视图的生命周期(初始化、激活、停用、挂载、释放)
* - 支持指令(directives)的应用
*
* @example
* ```typescript
* const source = ref('Hello World')
* const dynamicView = new DynamicView(source)
* dynamicView.init(ctx)
*
* // 更新数据源会自动触发视图更新
* source.value = 'New Text' // 更新为文本视图
* source.value = null // 更新为空视图
* source.value = new TextView('Custom') // 更新为自定义视图
* ```
*
* @remarks
* - 视图切换过程是异步的,可以通过 owner.onViewSwitch 管理/配置事务
* - 在视图切换期间,新的更新请求会被标记为脏(dirty)并在当前切换完成后处理
* - 如果视图初始化失败,会自动创建一个错误注释视图
*/
export declare class DynamicView extends BaseView {
#private;
readonly kind = ViewKind.DYNAMIC;
readonly source: Ref;
private cachedView;
private cachedType;
private effect;
/**
* @constructor
*
* @param source - 响应式数据源,视图会根据此数据的变化而更新
* @param [location] - 可选,代码位置信息,用于错误追踪
*/
constructor(source: Ref, location?: CodeLocation);
/**
* 获取当前渲染的子视图
*
* @returns 当前缓存的视图实例,如果没有则为 null
*/
get currentView(): View | null;
/**
* 获取宿主节点
* @returns 当前视图的宿主节点,如果没有则为 null
*/
protected get hostNode(): HostNode | null;
/**
* 初始化视图
*/
protected doInit(): void;
/**
* 释放资源
*/
protected doDispose(root: boolean): void;
/**
* 激活视图
*/
protected doActivate(): void;
/**
* 停用视图
*/
protected doDeactivate(): void;
/**
* 挂载视图
* @param containerOrAnchor - 宿主容器或锚点节点
* @param type - 挂载类型
*/
protected doMount(containerOrAnchor: HostContainer | HostNode, type: MountMode): void;
}
/**
* ElementView 类用于表示和管理 DOM 元素视图,支持属性、子元素、指令和引用等功能。
*
* 核心功能:
* - 创建和管理 DOM 元素节点
* - 处理元素属性和子元素
* - 支持指令(directives)和引用(ref)
* - 管理视图的生命周期(初始化、挂载、激活、停用、销毁)
*
* @example
* ```typescript
* const elementView = new ElementView('div', { class: 'container', children: [new TextView('Hello')] })
* elementView.init(ctx)
* elementView.mount(document.body, 'append')
* ```
*
* @template T - 扩展自 HostElementTag,表示 DOM 元素的标签名
*
* @remarks
* - 内部使用 directives 属性来管理指令映射表
* - effects 属性用于管理视图的副作用,会在视图销毁时自动清理
* - $node 属性在挂载前为 null,挂载后会引用实际的 DOM 节点
*/
export declare class ElementView extends BaseView> {
readonly kind = ViewKind.ELEMENT;
protected hostNode: HostElement | null;
/** 元素标签 */
readonly tag: T;
/** 元素属性 */
readonly props: AnyProps | null;
/** 子视图列表 */
readonly children: ResolvedChildren;
/** 元素引用 */
readonly ref: InstanceRef | undefined;
/** 指令映射表 */
private effects;
/**
* @constructor
*
* @param {T} tag - DOM 元素的标签名(如 'div', 'span' 等)
* @param {IntrinsicElements[T] | null} [props=null] - 元素的属性对象,包括事件处理器、样式、类名等
* @param {CodeLocation} [location] - 可选的代码位置信息,用于调试
*/
constructor(tag: T, props?: IntrinsicElements[T] | null, location?: CodeLocation);
protected doInit(): void;
protected doActivate(): void;
protected doDeactivate(): void;
protected doMount(containerOrAnchor: HostContainer | HostNode, type: MountMode): void;
protected doDispose(root: boolean): void;
private setProps;
}
/**
* 错误处理器类型
*
* 如果返回 false 则终止错误处理流程
*/
export declare type ErrorHandler = (error: unknown, info: ErrorInfo) => boolean | void;
/**
* 错误信息对象接口
*/
export declare interface ErrorInfo {
/**
* 错误来源
*/
source: ErrorSource;
/**
* 抛出异常的实例
*/
instance: ComponentInstance;
}
/**
* 错误来源联合类型
*
* 定义了框架中可能发生错误的各种来源。
*
* - `component:run`:表示在执行函数组件时发生的错误。
* - `effect:${string}`:表示在执行某个 effect 时发生的错误。
* - `hook:${Lifecycle}`:表示在执行某个生命周期钩子时发生的错误。
* - `view:switch`:表示在切换视图时发生的错误,DynamicView 发出。
* - `view:update`:表示在更新视图时发生的错误,ElementView 发出。
* - `view:build`:表示在构建视图时发生的错误,For 组件发出。
*/
export declare type ErrorSource = `component:run` | `effect:${string}` | `hook:${Lifecycle}` | 'view:switch' | 'view:update' | 'view:build';
/**
* 表达式包装器,运行时判断是否需要动态追踪。
*
* 由编译插件将无法静态确定是否包含响应式依赖的表达式
* (函数调用、方法调用、逻辑运算等)转换为此调用。
*
* 核心优化:通过运行时判断 getter
* 是否包含响应式依赖。无依赖时直接返回计算值(零开销),
* 有依赖时返回 Ref 自动追踪更新。
*
* @template T getter 返回值类型
* @returns 静态表达式返回原值,动态表达式返回 `Ref`
* @example
* ```jsx
* // JSX: {count.value + 1}
* // 编译为: createView('div', null, expr(() => count.value + 1))
* // JSX: {foo()}
* // 编译为: createView('span', null, expr(() => foo()))
* // 静态表达式零开销
* expr(() => 'hello') // → 'hello'
* expr(() => 42) // → 42
* expr(() => count.value) // → Ref(包含响应式依赖)
* ```
*/
export declare function expr(getter: () => T): T | Ref;
/**
* 提取视图属性
*
* @template T - 视图标签类型,必须继承自 ViewTag
*/
declare type ExtractProps = T extends Dynamic ? DynamicProps : T extends Fragment ? FragmentProps : T extends HostElementTag ? IntrinsicElements[T] : T extends Component ? ComponentProps : AnyProps;
/**
* For组件函数,用于渲染动态列表视图
*
* @template T - 列表项的数据类型
* @param {ForProps} props - 组件的属性对象
* @returns {ListView} 返回列表视图实例
*
* @example
* ```ts
* // 基本用法
* const items = ["apple", "banana", "cherry"];
*
* function App() {
* return (
* item}
* children={(item, index) => {item}
}
* />
* );
* }
* ```
*/
export declare function For(props: ForProps): ListView;
/**
* 列表组件基础属性接口
*
* 定义了For组件所需的核心属性,用于渲染动态列表。
*
* @template T - 列表项的数据类型
*
* @example
* ```jsx
* // 基本用法
* item}
* children={(item, index) => Item {item} at index {index}
}
* />
*
* // 对象数组用法
* user.id}
* children={(user) => }
* />
* ```
*/
export declare interface ForProps extends ListLifecycleHook {
/**
* 要渲染的列表数据数组
*
* 支持只读数组,当数组内容发生变化时,
* 组件会自动更新对应的DOM元素。
*/
each: readonly T[];
/**
* 列表项渲染函数
*
* 用于定义每个列表项如何渲染,接收当前项和索引作为参数,
* 返回有效的子元素(View、字符串、数字等)。
*/
children: (item: T, index: Ref) => RenderChild;
/**
* 列表项的唯一标识生成器
*
* 用于优化列表渲染性能和保持组件状态。
* 可以是:
* - 函数:接收(item)参数,返回唯一标识
* - 字符串:作为对象属性名直接访问
*
* 虽然非必需,但强烈建议提供以获得更好的性能和状态保持。
*/
key?: keyof T | ((item: T) => any);
}
/**
* FragmentView 构建器
*
* @param props - 属性对象
* @param [props.children] - 子视图列表
* @return {FragmentView} FragmentView 对象
*/
export declare const Fragment: ViewBuilder;
export declare type Fragment = ViewBuilder & {
__is_fragment: true;
};
export declare interface FragmentProps {
children?: RenderChildren;
}
/**
* FragmentView 类用于表示一个片段视图,它是 BaseView 的子类,专门用于管理一组子视图的容器。
* 该类负责子视图的初始化、挂载、激活、停用和销毁等生命周期管理。
*
* 核心功能:
* - 管理子视图的生命周期(初始化、挂载、激活、停用、销毁)
* - 提供对子视图的统一管理接口
*
* 使用示例:
* ```typescript
* const fragment = new FragmentView([childView1, childView2]);
* fragment.init(context);
* fragment.mount(container, 'append');
* ```
*
* 构造函数参数:
* - children: RenderChildren - 子视图数组,可以是单个视图或视图数组
* - location?: CodeLocation - 可选的代码位置信息,用于调试和错误追踪
*
* 特殊说明:
* - 该类会自动创建一个宿主片段节点(HostFragment)用于挂载子视图
* - 子视图的生命周期方法会按照顺序依次调用
* - 不建议直接实例化该类,通常通过视图系统自动创建
*/
export declare class FragmentView extends BaseView {
readonly kind = ViewKind.FRAGMENT;
readonly children: ResolvedChildren;
protected hostNode: HostFragment | null;
constructor(children: RenderChildren, location?: CodeLocation);
protected doInit(): void;
protected doDispose(root: boolean): void;
protected doActivate(): void;
protected doDeactivate(): void;
protected doMount(target: HostContainer | HostNode, type: MountMode): void;
}
/**
* Freeze 组件实现
* 用于缓存和复用组件视图,避免重复创建和销毁,提升性能
*
* 工作原理:
* 1. 监听 `is` 属性的变化
* 2. 当组件切换时,将旧组件冻结(响应式停止)并缓存
* 3. 当新组件需要显示时,优先从缓存中复用(恢复响应式)
* 4. 组件销毁时,清理所有缓存的视图
*
* @example
* ```tsx
* // 基础用法:动态组件缓存
* const current = ref(ComponentA)
*
* ```
* @example
* ```tsx
* // 使用 include 只缓存指定组件
*
* ```
* @example
* ```tsx
* // 使用 exclude 排除不需要缓存的组件
*
* ```
* @example
* ```tsx
* // 限制最大缓存数量
*
* ```
* @example
* ```tsx
* // 传递属性给组件
*
* ```
*
* @param props - Freeze 组件属性
* @returns {View} 返回当前激活的视图
*/
export declare function Freeze(props: FreezeProps): View;
/**
* Freeze 组件属性接口
*/
export declare interface FreezeProps {
/**
* 动态组件类型
*
* 可以是组件函数或响应式引用
*/
is: Component | null | undefined | false;
/**
* 唯一标识
*
* 如需使同一个组件永远不同的实例,可以传入一个`key`标识,它需和`is`传入的组件保持关联。
*/
key?: unknown;
/**
* 传递给组件的属性对象
*
* @example
* ```jsx
* const showComponent = ref(ComponentA)
* // 静态属性对象
*
* // 响应式属性对象
* const someProps = reactive({ message: 'Hello, World!' })
*
* ```
*/
props?: AnyProps | null | undefined;
/**
* 需要缓存的组件类型列表,如果指定则只缓存列表中的组件
*/
include?: Component[];
/**
* 不需要缓存的组件类型列表,优先级高于 include
*/
exclude?: Component[];
/**
* 最大缓存数量,默认为 0 表示不限制
*
* @default 0
*/
max?: number;
}
/**
* 获取应用程序上下文的函数
* 该函数用于从全局上下文中获取App类型的实例
*
* @template T - 应用程序实例的类型,默认为App
* @returns {App | null} 返回App类型的实例,如果不存在则返回null
*/
export declare function getApp(): T | null;
/**
* 获取已缓存的组件
*
* @template T - 组件类型
* @param loader - 懒加载器函数
* @returns {T | undefined} 返回缓存的组件,如果未缓存则返回 undefined
*
* @example
* ```ts
* const loader = () => import('./MyComponent.js')
*
* const cached = getCachedComponent(loader)
* if (cached) {
* // 直接使用缓存的组件
* const view = createView(cached, { children: 'Hello' })
* }
* ```
*/
export declare function getCachedComponent(loader: LazyLoader): T | undefined;
/**
* 获取当前组件对应的视图
*
* @returns {ComponentView} 返回当前活跃的组件视图
* @throws {Error} 如果没有活跃的组件实例则抛出错误
*/
declare function getComponentView(): ComponentView;
/**
* 获取当前组件对应的视图
*
* @param allowEmpty - 是否允许返回空值
* @returns {ComponentView} 返回当前活跃的组件视图
* @throws {Error} 如果没有活跃的组件实例则抛出错误
*/
declare function getComponentView(allowEmpty: false): ComponentView;
/**
* 获取当前组件对应的视图
*
* @param [allowEmpty=false] - 是否允许返回空值
* @returns {ComponentView | null} 返回当前活跃的组件视图,如果没有返回null
*/
declare function getComponentView(allowEmpty: true): ComponentView | null;
export { getComponentView }
export { getComponentView as useView }
/**
* 获取当前组件的运行时实例
*
* @returns {ComponentInstance} 返回当前活跃的小部件实例
* @throws {Error} 如果没有活跃的组件实例则抛出错误
*/
declare function getInstance(): ComponentInstance;
/**
* 获取当前组件的运行时实例
*
* @param allowEmpty - 是否允许返回空值
* @returns {ComponentInstance} 返回当前活跃的组件实例
* @throws {Error} 如果没有活跃的组件实例则抛出错误
*/
declare function getInstance(allowEmpty: false): ComponentInstance;
/**
* 获取当前组件的运行时实例
*
* @param allowEmpty - 是否允许返回空值
* @returns {ComponentInstance | null} 返回当前活跃的组件件实例,如果没有则返回null
*/
declare function getInstance(allowEmpty: true): ComponentInstance | null;
export { getInstance }
export { getInstance as useInstance }
/**
* 获取懒加载组件的加载器
*
* 该函数用于检查一个组件是否是通过 {@link lazy} 函数创建的懒加载组件,
* 如果是则返回其内部的加载器函数,否则返回 null。
*
* @example
* ```ts
* // 基本用法 - 获取懒加载组件的 loader
* const Button = lazy(() => import('./Button.js'))
* const loader = getLazyLoader(Button)
* console.log(loader) // [Function: loader]
*
* // 检查组件是否为懒加载组件
* if (getLazyLoader(SomeComponent)) {
* console.log('这是一个懒加载组件')
* }
*
* // 对非懒加载组件返回 null
* const RegularComponent = () => createView('div', {})
* console.log(getLazyLoader(RegularComponent)) // null
*
* // 用于动态获取 loader 并重新创建懒加载实例
* const originalLoader = getLazyLoader(Button)
* if (originalLoader) {
* // 可以用于缓存预加载等场景
* const loading = getLoadingComponent(originalLoader)
* if (loading) {
* await loading
* console.log('加载完成')
* }
* }
* ```
*
* @param component - 要检查的组件,可以是任意值
* @returns 如果组件是通过 {@link lazy} 创建的懒加载组件,返回其 loader 函数;否则返回 null
* @see {@link lazy} 用于创建懒加载组件
*/
export declare function getLazyLoader(component: any): LazyLoader | null;
/**
* 获取正在加载中的组件 Promise
*
* 用于路由等外部模块等待异步组件加载完成。
* 如果组件正在加载中,返回该 Promise;
* 如果已经加载完成或未开始加载,返回 void。
*
* @param loader - 懒加载器函数
* @returns {Promise | void} 返回加载中的 Promise 或 void
*
* @example
* ```js
* const loader = () => import('./MyComponent.js')
*
* // 在路由跳转后尝试等待
* const loading = getLoadingComponent(loader)
* if (loading) {
* await loading
* // 此时组件 JS 已加载完毕,且已存入 LAZY_LOADED_CACHE
* await nextTick()
* // 如果不是预加载,此时可以安全的获取布局信息
* }
* ```
*/
export declare function getLoadingComponent(loader: LazyLoader): Promise | void;
/**
* 获取注册的 ViewRenderer 实例
* 如果尚未注册,则会抛出错误
*
* @returns {ViewRenderer} 返回已注册的ViewRenderer实例
* @throws {Error} 未注册时抛出错误
*/
export declare function getRenderer(): ViewRenderer;
/**
* 获取注册的 ViewRenderer 实例
* 如果尚未注册,则会抛出错误
*
* @param {boolean} allowEmpty - 不允许返回null
* @returns {ViewRenderer} 返回已注册的ViewRenderer实例
* @throws {Error} 未注册时抛出错误
*/
export declare function getRenderer(allowEmpty: false): ViewRenderer;
/**
* 获取注册的 ViewRenderer 实例
*
* @param {boolean} allowEmpty - 允许返回null
* @returns {ViewRenderer | null } 返回已注册的ViewRenderer实例或null
*/
export declare function getRenderer(allowEmpty: true): ViewRenderer | null;
/**
* 创建View对象的JS编码友好助手函数
*
* 此函数是对 `createView` 进行了二次封装,方便在直接使用js代码创建视图。
*
* @param type - 元素的类型,必须是ViewTag的子类型
* @param propsOrChildren - 元素的属性对象或子元素
* @param children - 元素的子元素
* @returns {View} 返回对应类型的视图对象
*/
export declare function h(type: T, propsOrChildren?: AnyProps | RenderChildren, children?: RenderChildren): InferView;
/**
* 生命周期钩子回调函数类型
*/
export declare type HookCallback = () => HookReturn;
/**
* 生命周期钩子返回值类型
* 根据钩子类型推导返回值类型
*/
declare type HookReturn = T extends Lifecycle.init ? Promise | void : void;
/**
* 生命周期钩子映射表
* 存储各个生命周期对应的回调函数数组
*/
export declare type HookStore = {
[K in Lifecycle]?: AnyCallback[];
};
/**
* 平台宿主注释节点类型
* 表示平台特定的注释节点实例
*/
export declare type HostComment = Vitarx.HostCommentNode;
/**
* 平台宿主容器节点类型
* 表示可以包含其他节点的宿主容器
*/
export declare type HostContainer = HostElement | HostFragment | Vitarx.HostContainerNode;
/**
* 平台宿主元素类型
* 表示平台特定的元素节点实例
*/
export declare type HostElement = (T extends HostTag ? Vitarx.HostElementTagMap[T] : {}) & {
[key: string | symbol | number]: any;
};
/**
* 平台宿主元素标签类型
* 表示所有支持的宿主元素标签的联合类型
*/
export declare type HostElementTag = HostTag extends never ? string : keyof Vitarx.HostElementTagMap;
/**
* 平台宿主片段节点类型
* 表示平台特定的片段节点实例
*/
export declare type HostFragment = Vitarx.HostFragmentNode;
/**
* 平台宿主节点联合类型
* 表示所有可能的宿主节点类型
*/
export declare type HostNode = HostElement | HostText | HostComment | HostFragment;
declare type HostTag = keyof Vitarx.HostElementTagMap;
/**
* 平台宿主文本节点类型
* 表示平台特定的文本节点实例
*/
export declare type HostText = Vitarx.HostTextNode;
/**
* 宿主节点视图
*
* 包括 Element、Fragment、Text、Comment 四种UI可见视图
*/
export declare type HostView = ElementView | FragmentView | TextView | CommentView;
/**
* InferProps类型工具,用于推断 createView 可接受的属性类型
*
* @template T - 视图标签类型,必须继承自 ViewDescriptor
*/
export declare type InferProps = ExtractProps & VitarxIntrinsicAttributes;
/**
* ViewDescriptor 转 View 类型
*/
export declare type InferView = T extends HostElementTag ? ElementView : T extends ViewBuilder ? V : T extends Component ? ComponentView : never;
/**
* 注入依赖数据 - 基本用法
*
* 注意:依赖组件上下文,仅支持在组件初始化阶段使用!!!
*
* @template T - 注入数据的类型
* @param name - 依赖数据的唯一标识符
*/
export declare function inject(name: string | symbol): T | undefined;
/**
* 注入依赖数据 - 带默认值
*
* 注意:依赖组件上下文,仅支持在组件初始化阶段使用!!!
*
* @template T - 注入数据的类型
* @param name - 依赖数据的唯一标识符
* @param defaultValue - 默认值
*/
export declare function inject(name: string | symbol, defaultValue: T): T;
/**
* 注入依赖数据 - 明确指定默认值不作为工厂函数
*
* 注意:依赖组件上下文,仅支持在组件初始化阶段使用!!!
*
* @template T - 注入数据的类型
* @param name - 依赖数据的唯一标识符
* @param defaultValue - 默认值
* @param treatDefaultAsFactory - 是否将默认值作为工厂函数
*/
export declare function inject(name: string | symbol, defaultValue: T, treatDefaultAsFactory: false): T;
/**
* 注入依赖数据 - 默认值作为工厂函数
*
* 注意:依赖组件上下文,仅支持在组件初始化阶段使用!!!
*
* @template T - 函数类型
* @param name - 依赖数据的唯一标识符
* @param defaultValue - 工厂函数
* @param treatDefaultAsFactory - 是否将默认值作为工厂函数
*/
export declare function inject(name: string | symbol, defaultValue: T, treatDefaultAsFactory: true): ReturnType;
/**
* 辅助计算出元素类型
*/
declare type InstanceOf = ShallowRef<(T extends HostElement ? T : T extends HostElementTag ? HostElement : T extends Component ? ComponentPublicInstance : T) | null>;
/**
* 实例引用
*/
export declare type InstanceRef = Ref;
/**
* 固有元素
*/
export declare type IntrinsicElements = Vitarx.IntrinsicElements;
/**
* 为 HTML 固有元素属性添加 MaybeRef 包装
*
* 使所有 HTML 属性支持传入 Ref/Computed 响应式值,
* 运行时会自动解包响应式值并追踪依赖。
*/
export declare type IntrinsicElementsWithRefProps = {
[K in keyof T]: {
[P in keyof T[K]]: MaybeRef;
};
};
export declare const IS_VIEW: unique symbol;
export declare const IS_VIEW_BUILDER: unique symbol;
/**
* 检查给定值是否为CommentView注释视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是CommentView注释视图类型则返回true,否则返回false
*/
export declare const isCommentView: (val: any) => val is CommentView;
/**
* 检查给定值是否为Component组件类型
*
* 主要检查值是否为函数类型,函数即可作为组件使用。
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是Component组件类型则返回true,否则返回false
*/
export declare const isComponent: (val: any) => val is Component;
/**
* 检查给定值是否为ComponentView组件视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是ComponentView组件视图类型则返回true,否则返回false
*/
export declare const isComponentView: (val: any) => val is ComponentView;
/**
* 检查给定值是否为DynamicView条件视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是DynamicView条件视图类型则返回true,否则返回false
*/
export declare const isDynamicView: (val: any) => val is DynamicView;
/**
* 检查给定值是否为ElementView元素视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是ElementView元素视图类型则返回true,否则返回false
*/
export declare const isElementView: (val: any) => val is ElementView;
/**
* 检查给定值是否为FragmentView片段视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是FragmentView片段视图类型则返回true,否则返回false
*/
export declare const isFragmentView: (val: any) => val is FragmentView;
/**
* 检查给定值是否为ListView列表视图类型
*
* @param val - 需要检查的任意值
* @return {boolean} 如果值是ListView列表视图类型则返回true,否则返回false
*/
export declare const isListView: (val: any) => val is ListView;
/**
* 检查给定值是否为TextView文本视图类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是TextView文本视图类型则返回true,否则返回false
*/
export declare const isTextView: (val: any) => val is TextView;
/**
* 检查给定值是否为View对象类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是View对象类型则返回true,否则返回false
*/
export declare const isView: (val: any) => val is View;
/**
* 检查给定值是否为ViewBuilder视图构建器类型
*
* @param val - 需要检查的任意值
* @returns {boolean} 如果值是ViewBuilder视图构建器类型则返回true,否则返回false
*/
export declare const isViewBuilder: (val: any) => val is ViewBuilder;
/**
* Lazy组件,用于延迟加载子组件,
* 提供了延迟加载、超时处理、加载状态显示等功能
*
* @template T - 子组件类型
* @param { LazyProps } props - 惰性加载配置选项
* @returns { View } - 返回一个视图,用于延迟加载子组件
*
* @example
* ```ts
* function App() {
* return (
* import('./MyAsyncComponent')}
* loading={() => Loading...
},
* timeout={5000},
* onError={(e) => Error: {e.message}
}
* />
* )
* }
* ```
*/
export declare function Lazy(props: LazyProps): View;
/**
* 定义一个懒加载组件
*
* @example
* ```ts
* // 基本用法
* const Button = lazy(() => import('./Button.js'))
*
* function App() {
* // color,children都会透传给最终渲染的Button组件
* return
* // 等效于
* // return import('./Button.js')} props={color="red"}>按钮
* }
*
* // 带有loading和错误处理的用法
* const AdvancedComponent = lazy(
* () => import('./AdvancedComponent.js'),
* {
* delay: 300,
* timeout: 5000,
* loading: () => 正在加载...
,
* onError: (error) => 加载失败: {String(error)}
* }
* )
* ```
*
* @param loader - 加载器
* @param [options] - 懒加载组件选项
* @param [options.delay=200] - 延迟显式loading视图的时间,避免视图闪烁
* @param [options.timeout=0] - 加载超时时间
* @param [options.loading] - 加载中显示的节点
* @param [options.onError] - 处理器加载失败/返回备用View
* @returns { ViewBuilder } 懒加载组件的视图构建器
*/
export declare function lazy(loader: () => Promise<{
default: T;
}>, options?: LazyLoadOptions): LazyWrapper;
/**
* ES组件模块懒加载器类型
*/
export declare type LazyLoader = () => Promise<{
default: T;
}>;
/**
* 惰性加载配置选项
*/
export declare interface LazyLoadOptions {
/**
* 加载视图构建函数
*
* 默认向上寻找 `Suspense` 组件,使其呈现 `fallback` (优先级高于loading)。
*/
loading?: () => View;
/**
* 展示加载组件前的延迟时间
*
* @default 200
*/
delay?: number;
/**
* 超时时间
*
* `<=0` 则不限制超时时间。
*
* @default 0
*/
timeout?: number;
/**
* 异常处理钩子
*
* @param error - 捕获到的异常
* @returns { View } - 返回一个视图,用于显示异常信息
*/
onError?: (e: unknown) => View;
}
/**
* Lazy 支持的属性
*/
export declare interface LazyProps extends LazyLoadOptions {
/**
* 接收一个惰性加载器
*
* @example
* ```ts
* // 组件必须使用`export default`导出,否则会报错。
* () => import('./YourWidget.js')
* ```
*/
loader: LazyLoader;
/**
* 绑定给加载组件的属性
*/
props?: WithProps;
/**
* 原样透传给加载完成后的组件
*/
children?: ComponentProps['children'];
}
export declare type LazyWrapper = ViewBuilder, ComponentView>>;
/**
* 生命周期阶段枚举
*
* 定义了组件在生命周期中的各个阶段
*/
declare const enum Lifecycle {
/** 准备数据阶段,发生在首次渲染之前 */
init = "init",
/** 挂载阶段 */
beforeMount = "beforeMount",
/** 显式阶段 */
show = "show",
/** 即将挂载阶段 */
mounted = "mounted",
/** 隐藏阶段 */
hide = "hide",
/** 即将卸载阶段 */
dispose = "dispose"
}
declare type ListItemView = View & {
__parent?: ListView;
__prev?: ListItemView | null;
__next?: ListItemView | null;
};
/**
* 列表组件生命周期钩子接口
*
* 定义了列表项在不同生命周期阶段可以执行的回调函数,
* 用于实现列表项的进入、离开和更新动画效果。
*
* @example
* ```jsx
* item.id}
* onEnter={(view) => {
* // 列表项进入时的动画
* view.node.style.opacity = '0'
* setTimeout(() => {
* view.node.style.transition = 'opacity 0.3s'
* view.node.style.opacity = '1'
* }, 0)
* }}
* onLeave={(view, done) => {
* // 列表项离开时的动画
* view.node.style.transition = 'opacity 0.3s'
* view.node.style.opacity = '0'
* setTimeout(done, 300)
* }}
* children={(item) => {item.name}
}
* />
* ```
*/
declare interface ListLifecycleHook {
/**
* 列表项即将被移除时触发的回调函数
*
* 当列表项需要从DOM中移除时调用,可以用于实现离开动画。
* 必须调用done回调来完成移除操作。
*
* @param view - 即将被移除的视图实例
* @param done - 完成回调函数,调用后才会真正移除DOM元素
*/
onLeave?: (view: View, done: VoidCallback) => void;
/**
* 列表项被添加到DOM后触发的回调函数
*
* 当新的列表项被插入到DOM中后调用,可以用于实现进入动画。
*
* @param view - 新添加的视图实例
*/
onEnter?: (view: View) => void;
/**
* 列表更新前触发的回调函数
*
* 在列表数据发生变化,但在DOM更新之前调用。
* 可以用于执行更新前的准备工作或获取当前状态。
*
* @param children - 当前的所有子视图实例数组
*/
onBeforeUpdate?: (children: IterableIterator) => void;
/**
* 列表更新后触发的回调函数
*
* 在列表数据发生变化且DOM更新完成后调用。
* 可以用于执行更新后的操作,如重新计算布局等。
*
* @param children - 更新后的所有子视图实例数组
*/
onAfterUpdate?: (children: IterableIterator) => void;
}
/**
* ListView 是一个用于管理列表视图的类,继承自 BaseView。
* 它提供了对列表项的增删改查功能,并维护列表项之间的顺序关系。
*
* 核心功能:
* - 添加视图到列表末尾(append)
* - 在指定位置插入视图(insert)
* - 移动视图到新位置(move)
* - 从列表中移除视图(remove)
* - 获取列表的长度、首尾元素和子视图迭代器
*
* 使用示例:
* ```typescript
* const list = new ListView([item1, item2]);
* list.append(item3);
* list.insert(item4, item2);
* list.move(item3, item1);
* list.remove(item2);
* ```
*
* 构造函数参数:
* @param items - 可选参数,初始化时要添加到列表中的视图数组
* @param location - 可选参数,代码位置信息
*
* 特殊说明:
* - 视图之间的顺序关系通过 __prev 和 __next 属性维护
* - 在开发模式下,会对参数类型进行严格检查
* - 所有操作都仅影响链表指针,需自行管理视图生命周期状态和DOM位置
*/
export declare class ListView extends BaseView {
readonly kind = ViewKind.LIST;
protected hostNode: HostFragment | null;
private head?;
private tail?;
private size;
constructor(items?: Iterable, location?: CodeLocation);
get length(): number;
get first(): ListItemView | null;
get last(): ListItemView | null;
get children(): IterableIterator;
/**
* 往列表中追加视图
*
* @param child
*/
append(child: ListItemView): void;
/**
* 插入一个视图到指定锚点之前
*
* @param child - 要插入的视图
* @param anchor - 插入位置
*/
insert(child: ListItemView, anchor: ListItemView | null): void;
/**
* 移动一个视图到指定锚点之前
*
* @param child - 要移动的视图
* @param anchor - 移动位置,传入 null 等同于 append
*/
move(child: ListItemView, anchor: ListItemView | null): void;
/**
* 从列表删除一个视图
*
* @param child
*/
remove(child: ListItemView): void;
protected doInit(): void;
protected doMount(target: HostContainer | HostNode, type: MountMode): void;
protected doActivate(): void;
protected doDeactivate(): void;
protected doDispose(root: boolean): void;
/**
* 获取视图列表迭代器
*
* @returns {IterableIterator}
*/
private safeChildren;
}
/**
* 可能是引用值的类型
*
* 创建一个联合类型,表示值可以是原始类型 T 或其 Ref 包装形式。
* 这对于接受可以是响应式或非响应式值的API非常有用。
*
* @template T - 原始值类型
*
* @example
* ```ts
* // 接受可以是数字或数字的响应式引用
* function setValue(value: MaybeRef) {
* // 函数实现
* }
*
* // 以下两种调用方式都是有效的
* setValue(42); // 直接传入数字
* setValue(ref(42)); // 传入响应式引用
* ```
*/
export declare type MaybeRef = T extends Ref ? U | T : T | Ref;
/**
* 合并Props对象
*
* 合并两个Props对象,如果对象2中存在与对象1相同的属性,则对象2的属性值优先。
*
* @param p1 - 对象1
* @param p2 - 对象2
* @returns {AnyProps} 合并后的新属性对象
*/
export declare function mergeProps(p1: AnyProps, p2: AnyProps): AnyProps;
/**
* ModelRef 类实现了一个双向绑定的属性代理,用于在组件Prop和响应式系统之间建立双向数据绑定。
*
* 核心功能:
* - 提供对组件Prop的响应式访问
* - 自动处理属性更新和依赖通知
*
* 构造函数参数:
* @param props - 目标对象,包含要绑定的属性
* @param propName - 要绑定的属性名,必须是 _props 的键
* @param defaultValue - 可选,当属性不存在时的默认值
*
* 特殊说明:
* - 该类实现了 RefSignal 接口
* - 会自动处理原始值是否为 RefSignal 的情况
* - 当属性值未改变时,不会触发更新
*/
export declare class ModelRef implements Ref> {
readonly [IS_REF] = true;
private readonly _ref;
private readonly _props;
private readonly _eventName;
constructor(props: T, propName: K, defaultValue?: T[K]);
/**
* 获取属性的当前值
*
* @returns {any} 属性的当前值
*/
get value(): V extends void ? T[K] : Exclude;
/**
* 设置属性的新值
*
* 该setter会智能处理不同类型的属性值:
* - 如果原始属性是Ref,则更新该Ref的值
* - 如果原始属性是普通值,则直接更新属性并通知依赖
*
* @param {any} newValue - 要设置的新值
*/
set value(newValue: T[K]);
}
/**
* 挂载类型
*
* 视图挂载到 DOM 的方式:
* - 'append': 追加到容器末尾
* - 'insert': 插入到指定位置
* - 'replace': 替换已有节点
*/
export declare type MountMode = 'append' | 'insert' | 'replace';
declare type NonConfigurationPlugins = (app: App) => void;
/**
* 组件挂载前钩子函数
*
* 在组件即将被挂载到DOM之前调用,此时组件即将开始首次渲染。
*
* @param {HookCallback} cb - 回调函数,在组件挂载前执行
*/
export declare const onBeforeMount: (cb: HookCallback) => void;
/**
* 组件销毁钩子函数
*
* 在组件即将被销毁时调用,用于清理资源和取消订阅。
*
* @param {HookCallback} cb - 回调函数,在组件销毁时执行
*/
export declare const onDispose: (cb: HookCallback) => void;
/**
* 组件异常处理钩子函数
*
* 用于捕获和处理组件内部发生的异常,提供统一的错误处理机制。
*
* @param handler - 异常处理函数
*
* @example
* ```ts
* // 基本用法
* function MyComponent() {
* onError((error) => {
* console.error('组件发生错误:', error);
* return false // 返回false表示错误已被处理,不需要向上抛出
* });
*
* // 可能引发错误的操作
* const riskyOperation = () => {
* throw new Error('模拟错误');
* };
*
* return ;
* }
*
* // Vue类比:类似于Vue 3中的onErrorCaptured
* // Vue 3: onErrorCaptured((error, instance, info) => { ... })
*
* // 高级用法:发送错误报告
* function ErrorBoundary(props) {
* const showView = shallowRef()
* onError((error,info) => {
* // 发送错误报告到服务器
* fetch('/api/error-report', {
* method: 'POST',
* body: JSON.stringify({
* message: error.message,
* stack: error.stack,
* source: info.source,
* component: info.instance.name,
* })
* }).catch(console.error)
*
* showView.value = 组件出现异常,工程师正在紧急修复中...
* return false // 返回false表示错误已被处理,不需要向上抛出
* });
*
* return (<>
* {showView.value ? showView : props.children }
* >)
* }
* ```
*/
export declare const onError: (handler: ErrorHandler) => void;
/**
* 组件隐藏钩子函数
*
* 在组件隐藏时调用,通常用于清理组件显示期间的资源。
*
* @param {HookCallback} cb - 回调函数,在组件隐藏时执行
*/
export declare const onHide: (cb: HookCallback) => void;
/**
* 组件初始化钩子函数
*
* 在组件实例创建后立即调用,此时组件响应式数据已初始化但尚未挂载到DOM
*
* @param {HookCallback} cb - 回调函数,在组件初始化时执行
*/
export declare const onInit: (cb: HookCallback) => void;
/**
* 组件已挂载钩子函数
*
* 在组件挂载到DOM后调用,此时可以访问DOM元素。
*
* @param {HookCallback} cb - 回调函数,在组件挂载完成后执行
*/
export declare const onMounted: (cb: HookCallback) => void;
/**
* 组件显示钩子函数
*
* 在组件显示时调用,通常用于处理组件可见性变化的逻辑。
*
* @param {HookCallback} cb - 回调函数,在组件显示时执行
*/
export declare const onShow: (cb: HookCallback) => void;
/**
* 注册视图切换事务处理器
*
* 当组件的根视图(直接或间接)是 `DynamicView` 时,视图切换会触发此钩子。
* 支持冒泡机制:从内层 DynamicView 向外层组件传播。
*
* 事务会在冒泡完成后自动提交,如需自定义切换时机,可调用 `tx.stopPropagation()` 后手动提交。
*
* @param handler - 视图切换事务处理器函数
*
* @example
* ```tsx
* // 基本用法:监听视图切换
* function MyComponent(props) {
* onViewSwitch((tx) => {
* console.log('视图切换:', tx.prev, '->', tx.next);
* });
*
* return
* }
* ```
*
* @example
* ```tsx
* // 缓存视图:配置 cachePrev 属性
* function CacheView(props) {
* const cache = new Map()
*
* onViewSwitch((tx) => {
* // 配置 prev 视图缓存
* tx.cachePrev = true
* cache.set(tx.prev.component, tx.prev)
* });
*
* return
* }
* ```
*
* @example
* ```tsx
* // 自定义切换:停止冒泡并手动控制
* function Transition(props) {
* onViewSwitch((tx) => {
* // 停止冒泡,阻止自动提交
* tx.stopPropagation()
*
* // 先挂载新视图
* tx.commitNext()
*
* // 执行过渡动画后提交旧视图
* runAnimation(tx.prev.node, () => {
* tx.commitPrev()
* })
* });
*
* return
* }
* ```
*/
export declare const onViewSwitch: (handler: ViewSwitchHandler) => void;
declare type OptionallyConfigurablePlugIns = (app: App, options?: T) => void;
/**
* TextView 组件化解析器
*
* @param props - Text 组件的属性对象
* @param [props.text] - 文本内容
* @return {TextView} TextView对象
*/
export declare const PlainText: ViewBuilder>;
export declare type PlainText = ViewBuilder | CommentView> & {
__is_text: true;
};
export declare interface PlainTextProps {
text: string | number;
}
/**
* 预加载组件并存入缓存
*
* 此函数用于提前加载懒加载组件,避免在实际使用时的延迟。
* 加载成功后组件会被缓存,后续使用时直接从缓存获取。
*
* @template T - 组件类型
* @param loader - 懒加载器函数
* @returns {Promise} 返回加载成功的组件
* @throws {Error} 如果加载失败或模块格式无效
*
* @example
* ```ts
* // 在路由切换前预加载组件
* const loader = () => import('./MyComponent.js')
*
* // 预加载
* preloadComponent(loader)
* .then(() => console.log('组件预加载成功'))
* .catch(err => console.error('预加载失败', err))
* ```
*/
export declare function preloadComponent(loader: LazyLoader): Promise;
/**
* 提供依赖数据,实现组件间的依赖注入
*
* 注意:依赖组件上下文,仅支持在组件构造阶段使用!
*
* @param name - 依赖数据的唯一标识符
* @param value - 要提供的数据值
*
* @example
* ```ts
* // 函数组件中使用
* function Foo() {
* provide('theme', 'dark');
* return ...
* }
* ```
*/
export declare function provide(name: string | symbol, value: unknown): void;
/**
* 渲染组件
*
* @param component - 要渲染的组件
* @param container - 视图将被挂载到的宿主容器
* @param [ctx] - 可选的视图上下文参数
* @param [ctx.app] - 可选的应用实例
* @param [ctx.owner] - 可选的父组件实例
* @returns - 返回渲染后的视图对象
*
* @example
* ```js
* import { ModalComponent } from 'xxxx'
* // 渲染组件到body中
* const view = render(ModalComponent, document.body)
* setTimeout(() => {
* view.dispose() // 销毁
* }, 3000)
* ```
*/
export declare function render(component: Component, container: HostContainer, ctx?: ViewContext): ComponentView;
/**
* 渲染视图
*
* @param view - 要渲染的视图
* @param container - 视图将被挂载到的宿主容器
* @param [ctx] - 可选的视图上下文参数
* @param [ctx.app] - 可选的应用实例
* @param [ctx.owner] - 可选的父组件实例
* @returns - 返回渲染后的视图对象
* @example
* ```jsx
* const view = render(Hello World
, document.body)
* setTimeout(() => {
* view.dispose() // 销毁
* }, 3000)
* ```
*/
export declare function render(view: T, container: HostContainer, ctx?: ViewContext): T;
/**
* 可渲染的类型
*
* 可以是任意视图类型或原始类型(如 string、number 等)
*/
export declare type Renderable = View | AnyPrimitive;
/**
* 可渲染的节点类型
*
* 可以是渲染单元或渲染单元的响应式引用
*/
export declare type RenderChild = Renderable | Ref;
/**
* 可渲染的节点集合类型
*
* 可以是单个有效子节点或可迭代的子节点集合
*/
export declare type RenderChildren = RenderChild | Iterable;
declare type RequiredConfigurationPlugIn = (app: App, options: T) => void;
/**
* 解析后的子节点类型
*
* 子节点被解析后最终得到的视图数组
*/
export declare type ResolvedChildren = readonly View[];
/**
* 解析指令
*
* 根据指令名称查找并返回对应的指令对象。
* 查找顺序遵循优先级:组件局部指令 > 应用级指令 > 全局指令。
*
* @param name - 要查找的指令名称,`v-` 前缀可省略
* @returns { Directive | undefined } 找到的指令对象,如果未找到则返回undefined
*/
export declare function resolveDirective(name: string): Directive | undefined;
/**
* 在组件上下文中执行函数的包装器,
* 确保在函数执行期间可以获取到组件实例。
*
* @template T - 返回值类型
* @param instance - 要设置为活动实例的小部件实例
* @param fn - 要在特定小部件实例上下文中执行的函数
* @returns {T} 返回执行函数的结果
*/
export declare function runComponent(instance: ComponentInstance, fn: () => T): T;
/**
* 设置平台渲染适配器
*
* @param renderer - 要设置的平台渲染适配器实例,用于处理DOM操作
*/
export declare function setRenderer(renderer: ViewRenderer): void;
/**
* style属性值
*/
export declare type StyleProperties = string | Vitarx.HostCSSProperties;
/**
* CSS 样式规则类型
*/
export declare type StyleRules = Vitarx.HostCSSProperties;
/**
* StyleUtils 类是一个用于处理 CSS 类和样式对象的静态工具类。
* 提供了合并、转换 CSS 类和样式的方法,支持多种输入格式(字符串、数组、对象)之间的互相转换。
*
* 核心功能包括:
* - 合并 CSS 类名(mergeCssClass)
* - 合并 CSS 样式(mergeCssStyle)
* - CSS 样式对象与字符串的互相转换(cssStyleValueToString, cssStyleValueToObject)
* - CSS 样式字符串按声明分割(splitCssRules)
* - CSS 类名与数组、字符串的互相转换(cssClassValueToArray, cssClassValueToString)
*
* 示例用法:
* ```typescript
* // 合并类名
* const mergedClasses = StyleUtils.mergeCssClass('class1 class2', { class2: true, class3: true });
* // 合并样式
* const mergedStyles = StyleUtils.mergeCssStyle('color: red;', { fontSize: '14px' });
* // 转换类名为数组
* const classArray = StyleUtils.cssClassValueToArray('class1 class2');
* // 转换样式对象为字符串
* const styleString = StyleUtils.cssStyleValueToString({ color: 'red', fontSize: '14px' });
* ```
*
* 注意事项:
* - 所有方法都是静态方法,可以直接通过类名调用
* - 样式属性的命名会自动在驼峰命名和 kebab-case 之间转换
* - 空值和无效值会被自动过滤
*/
export declare class StyleUtils {
/**
* 将 CSS 样式字符串按声明分割
*
* 跟踪括号和引号状态,避免在 url()、data URI 或引号内的分号处错误分割。
*
* @param style - CSS 样式字符串
* @returns 分割后的声明字符串数组(不含分号分隔符)
*/
static splitCssRules(style: string): string[];
/**
* 合并两个class
*
* @param {ClassProperties} c1 - class1
* @param {ClassProperties} c2 - class2
* @returns {string[]} 合并后的数组,数组元素为类名
*/
static mergeCssClass(c1: ClassProperties | Falsy, c2: ClassProperties | Falsy): string[];
/**
* 合并两个style
*
* @param style1 - 第一个样式对象或字符串
* @param style2 - 第二个样式对象或字符串
* @returns {StyleRules} 合并后的style对象
*/
static mergeCssStyle(style1: StyleProperties | Falsy, style2: StyleProperties | Falsy): StyleRules;
/**
* 将style对象转换为字符串
*
* @param styleObj - style对象
* @returns {string} 转换后的style字符串
*/
static cssStyleValueToString(styleObj: StyleProperties): string;
/**
* 将style字符串转换为style对象
*
* 如果是对象,则会直接返回
*
* @param style - style字符串
* @returns {StyleRules} 转换后的style对象
*/
static cssStyleValueToObject(style: StyleProperties | Falsy): StyleRules;
/**
* 将 class 属性转换为数组
*
* @param classInput - 可以是 string, string[] 或对象类型
* @returns {string[]} 返回一个数组,数组元素为类名
*/
static cssClassValueToArray(classInput: ClassProperties | Falsy): string[];
/**
* 将 class 属性转换为字符串
*
* @param classInput - 可以是 string, string[] 或对象类型
* @returns {string} 返回一个字符串,字符串元素为类名
*/
static cssClassValueToString(classInput: ClassProperties | Falsy): string;
}
/**
* Suspense 组件
*
* 用于处理异步组件加载时的占位显示
*
* @param {SuspenseProps} props - 组件属性
* @param {View} props.children - 实际要渲染的内容
* @param {View} [props.fallback] - 加载中显示的占位视图
* @param {Function} [props.onResolved] - 异步加载完成时的回调函数
* @returns {View} 返回渲染的视图
*
* @example
* ```tsx
* // 基本用法
* Loading...}>
*
*
*
* // 使用 onResolved 回调
* Loading...}
* onResolved={() => console.log('Async content loaded!')}>
*
*
* ```
*/
export declare function Suspense({ fallback, children, onResolved }: SuspenseProps): View;
export declare const SUSPENSE_COUNTER: unique symbol;
/**
* Suspense小部件的配置选项
*
* @property {View} fallback - 回退内容
* @property {View} children - 子节点
* @property {() => void} onResolved - 子节点渲染完成时触发的钩子
*/
export declare interface SuspenseProps {
/**
* 子节点
*/
children: View;
/**
* 回退内容
*
* 在异步子节点加载完成之前会显示该属性传入的节点,
* 加载完成过后会立即切换为子节点内容。
*/
fallback?: View;
/**
* 监听解析完成事件
*
* 该钩子会在子元素全部解析并替换完成后执行。
*/
onResolved?: () => void;
}
/**
* TextView 类用于表示和渲染文本节点。
* 核心功能:
* - 创建和管理文本节点
* - 提供文本渲染的基础功能
*
* @example
* ```typescript
* const textView = new TextView();
* textView.mount(container);
* ```
*/
export declare class TextView extends BaseAtomicView {
readonly kind = ViewKind.TEXT;
protected createNode(renderer: ViewRenderer, text: string): HostText;
}
/**
* 获取当前App实例
*
* @template T - 应用程序实例的类型,默认为App
* @returns {T} 返回当前活动的App实例
* @throws {Error} 如果没有活跃实例则抛出错误
*/
export declare function useApp(): T;
/**
* 格式化组件的 props.children 为类型安全的 View 数组
*
* 当组件需要消费 children 时,使用此函数将 RenderChildren(可能包含 Ref、
* 原始值等)归一化为 ResolvedChildren(readonly View[])。
*
* 解决的问题:
* - 编译辅助函数(branch、expr 等)返回的数据源类型与 View 不兼容
* - 用户声明 children: View 时,运行时实际传入的可能不是 View
* - 此函数在消费端按需归一化,避免生产端预包装的性能浪费
*
* @param children 组件接收到的 props.children,不传则自动从当前组件视图获取
* @returns {ResolvedChildren} 归一化后的子视图数组(ResolvedChildren)
*
* @example
* ```tsx
* // 无参调用:自动获取当前组件的 props.children
* function Test() {
* const children = useChildren()
* // children: readonly View[]
* return {children}
* }
*
* // 显式传参:手动指定 children 来源
* function Test(props: { children: RenderChildren }) {
* const children = useChildren(props.children)
* return {children}
* }
* ```
*/
export declare function useChildren(children?: RenderChildren | undefined): ResolvedChildren;
/**
* 快速归一化单个子视图
*
* 当组件期望 children 是单个 View 时(如 Suspense 的 children: View),
* 使用此函数直接归一化为 `View | null`,跳过 `useChildren` 的数组扁平化开销。
*
* 与 `useChildren` 的区别:
* - `useChildren()` 返回 `View[]`,处理所有子节点(含数组扁平化)
* - `useFastChild()` 返回 `View | null`,仅处理单个子节点(零数组开销)
*
* @param children 组件接收到的 props.children,不传则自动从当前组件视图获取
* @returns {View | null} 归一化后的单个视图,无法解析时返回 null
*
* @example
* ```tsx
* // 无参调用:自动获取当前组件的 props.children
* function Suspense() {
* const child = useFastChild()
* // child: View | null
* if (!child) return new CommentView('empty')
* child.init(context)
* return child
* }
*
* // 显式传参
* function Test(props: { children: RenderChildren }) {
* const child = useFastChild(props.children)
* return child
* }
* ```
*/
export declare function useFastChild(children?: RenderChildren | undefined): View | null;
/**
* 生成应用内唯一的 id
*
* 算法为 `${前缀}-${递增计数器}`
*
* - 组件内:使用 appContext 独立计数
* - 非组件环境:使用全局计数器
*
* @param prefix ID 前缀(优先级最高)
* @returns 唯一 ID 字符串
*/
export declare const useId: (prefix?: string) => string;
/**
* 创建一个支持双向绑定的属性引用
*
* 该函数用于创建一个特殊的 `ModelRef` 对象,它可以与组件的props属性进行双向绑定。
* 当通过该`.value`修改值时,会自动触发 `onUpdate:propName` 事件。
*
* @template T - props对象的类型
* @template K - 属性名的类型
* @template V - 属性值的类型
* @param {T} props - 组件的props对象
* @param {K} propName - 需要进行双向绑定的属性名
* @param {V} [defaultValue] - 可选,当属性不存在时的默认值
* @returns { ModelRef } 返回一个 `ModelRef` 实例
*
* @example
* ```jsx
* import { ref, watch } from 'vitarx'
* import { useModel, type WithModelEvent } from 'vitarx'
*
* interface MyInputProps {
* // modelValue 是 v-model 指令约定的属性名,无需显式声明更新事件
* modelValue: string
* // 自定义属性,需要显式声明更新事件
* customValue: string
* // 为 customValue 属性声明更新事件
* 'onUpdate:customValue': (v: string) => void
* }
*
* // 包装一个支持双向绑定的输入组件
* function MyInput(props: MyInputProps) {
* const valueRef = useModel(props, 'modelValue')
* const customValueRef = useModel(props, 'customValue')
*
* return <>
* valueRef.value = e.target.value} />
* customValueRef.value = e.target.value} />
* >
* }
*
* // 在Props中显式声明更新事件不美观,可以使用 WithModelEvent 类型工具来简化
* export type MyInputProps = WithModelEvent<{
* modelValue: string
* customValue: string
* }, 'customValue'>
* // 或者
* function MyInput(props: WithModelEvent){//...}
*
*
* // 使用组件
* function App() {
* const value = ref('initial')
* const customValue = ref('initial')
* watch(value,(newValue)=>{
* console.log('value changed:', newValue)
* })
* watch(customValue, (newValue) => {
* console.log('customValue changed:', newValue)
* })
* return
* }
*
* // 巧用小妙招
* function Foo(props: {show?: boolean}) {
*
* const visible = useModel(props, 'show', false)
*
* // 通过 useModel 来绕过 props 的只读限制
* return
* {visible.value ? 'visible' : 'hidden'}
*
*
* }
* ```
* @see {@linkcode ModelRef} - 实现双向绑定的属性代理的类
*/
export declare function useModel(props: T, propName: K, defaultValue?: V): ModelRef;
/**
* 引用元素/组件实例
*
* 仅组件/元素支持引用,当引用组件时 `.value` 为组件实例。
*
* @example
* ```tsx
* function App() {
* const refDiv = useRef()
* // 假设 FooPublicInstance 是 Foo 组件暴露的公开实例类型
* const refFoo = useRef()
* onMounted(() => {
* console.log(refDiv.value?.textContent === '测试') // true
* console.log(refFoo.value !== null) // true
* })
* return <>
* 测试
*
* >
* }
* ```
*/
export declare function useRef(): InstanceOf;
/**
* 获取上级 `Suspense` 计数器
*
* @returns {ShallowRef | undefined} 如果存在则返回计数器Ref,不存在则返回undefined
*/
export declare function useSuspense(): ShallowRef | undefined;
/**
* 属性验证函数。
*
* 用于校验传入的 props 是否符合预期
*
* 校验时机:仅开发模式下节点创建之前进行校验
*
* 校验结果说明:
* - `string`:打印警告日志信息。
* - `false`:打印默认的校验失败信息。
* - throw new Error('自定义异常'):如果不希望继续渲染组件,则可以抛出异常。
* - 其他值/void:校验通过。
*
* 仅在开发模式下进行校验,生产模式下不会进行校验。
*
* @example
* ```ts
* defineValidate(MyComponent, (props) => {
* if (props.age < 0) {
* return 'age cannot be less than 0';
* }
* });
* ```
*/
export declare type ValidateProps = (props: AnyProps, location?: CodeLocation) => string | false | unknown;
/**
* 统一视图类型
*/
export declare type View = HostView | ListView | DynamicView | ComponentView;
/**
* 视图构建器
*/
export declare type ViewBuilder = {
(props: P, location?: CodeLocation): R;
[IS_VIEW_BUILDER]: true;
};
/**
* 视图运行时上下文关系
*/
export declare interface ViewContext {
owner?: ComponentInstance | null;
app?: App | null;
}
/**
* 可创建视图类型
*
* 可以被创建为视图的类型,包括:
* - 元素名称(如 'div'、'span' 等)
* - 组件
* - 视图构建器
*/
export declare type ViewDescriptor = HostElementTag | Component | ViewBuilder;
export declare type ViewEffect = {
dispose: () => void;
pause: () => void;
resume: () => void;
};
/**
* 用于执行一个视图副作用函数
*
* 主要服务于视图运行时,如 DOM 更新、`v-show` 指令副作用,业务层谨慎使用!
*
* @warning - ⚠️ 需在合适的时机主动停止副作用,否则可能会造成内存泄漏。
* @param effect - 要执行的副作用函数
* @returns { ViewEffect | null } 副作用存在信号依赖则返回视图副作用控制对象,否则返回 NULL
*/
export declare function viewEffect(effect: () => void): ViewEffect | null;
export declare const enum ViewKind {
/** 文本节点 */
TEXT = 1,
/** 锚点 */
COMMENT = 2,
/** 片段节点,用于包装多个子节点而不创建额外的DOM元素 */
FRAGMENT = 4,
/** 元素,如 `
`、`
` 等 */
ELEMENT = 8,
/** 动态视图 */
DYNAMIC = 16,
/** 列表视图 */
LIST = 32,
/** 组件节点 */
COMPONENT = 64
}
/**
* 平台适配渲染器接口,定义了操作DOM元素基本的方法
* 提供创建、修改、删除DOM元素以及处理事件和样式的能力
*/
export declare interface ViewRenderer {
/**
* 创建元素
*
* @param tag - 元素名称
* @param parent - 即将要挂载的容器,用于继承命名空间!
*/
createElement(tag: T, parent: HostContainer): HostElement;
/**
* 创建文本节点
*
* @param text - 文本内容
*/
createText(text: string): HostText;
/**
* 创建注释节点
*
* 通常用于锚点占位符
*
* @param text - 注释内容
*/
createComment(text: string): HostComment;
/**
* 创建片段
*
* @param view - 视图
*/
createFragment(view: FragmentView | ListView): HostFragment;
/**
* 判断是否为元素
*
* @param node - 节点
*/
isElement(node: HostNode): node is HostElement;
/**
* 判断是否为svg元素
* @param node
*/
isSVGElement(node: HostNode): boolean;
/**
* 判断是否为MathML元素
* @param node
*/
isMathMLElement(node: HostNode): boolean;
/**
* 判断是否为文本节点
*
* @param node - 节点
*/
isFragment(node: HostNode): node is HostFragment;
/**
* 添加子节点到父节点
*
* @param child - 子节点
* @param parent - 父节点
*/
append(child: HostNode, parent: HostContainer): void;
/**
* 插入节点到锚点之前
*
* 如果旧节点不存在于文档中时不执行任何操作
*
* @param child - 节点
* @param anchor - 锚点
*/
insert(child: HostNode, anchor: HostNode): void;
/**
* 替换节点
*
* 如果旧节点不存在于文档中时则不执行任何操作
*
* @param newNode - 新节点
* @param oldNode - 旧节点
*/
replace(newNode: HostNode, oldNode: HostNode): void;
/**
* 删除节点
*
* @param node - 要被删除的节点
*/
remove(node: HostNode): void;
/**
* 设置文本内容
*
* @param node - 节点
* @param text - 文本内容
*/
setText(node: HostNode, text: string): void;
/**
* 设置属性
*
* @param el - 元素
* @param key - 属性名称
* @param nextValue - 属性值
* @param prevValue - 上一次的属性值,兼容卸载旧的事件处理器
*/
setAttribute(el: HostElement, key: string, nextValue: unknown, prevValue: unknown): void;
}
/**
* 节点生命周期状态枚举
*
* - 分离状态 (DETACHED):
* View 对象已创建,但还未进入运行时视图树。
*
* - 初始化完成(INITIALIZED):
* View 已完成初始化,子树结构确定。
*
* - 已挂载(MOUNTED):
* View 已挂载到 DOM 树中。
*/
export declare enum ViewState {
DETACHED = "detached",
INITIALIZED = "initialized",
MOUNTED = "mounted"
}
/**
* 动态视图切换处理器
*
* @param tx - 视图切换事务
*/
export declare type ViewSwitchHandler = (tx: ViewSwitchTransaction) => void;
/**
* 视图切换事务接口
* 负责协调 prev/next 视图、commit 逻辑
*/
export declare interface ViewSwitchTransaction {
readonly prev: View;
readonly next: View;
/**停止冒泡传播*/
readonly propagationStopped: boolean;
/** 标记事务是否已提交 */
readonly committed: boolean;
/**
* 缓存 prev 视图
*
* 配置为 true 时 prev 视图的操作行为: prev.deactivate() + renderer.remove(prev.node)
* 配置为 false 时 prev 视图的操作行为: prev.dispose()
*
* @default `false`
*/
cachePrev?: boolean;
/**
* 停止冒泡传播,并阻止自动提交
*/
stopPropagation(): void;
/**
* 提交下一个视图
*
* 如果将 `forceFlush` 设置为 `true`,则会强制刷新事务,
* 跳过检查 `prev` 是否已提交,强制将当前事务置为完成状态。
*
* 如果在 `commitPrev()` 之前调用 `commitNext(true)`,
* 需在适当时机调用 `commitPrev()` 或自行接管 `prev` 的卸载逻辑,否则可能会造成内存泄漏或其他非预期影响。
*
* 注意:此方法在 `committed=true` 时调用无效。
*
* @param [forceFlush=false] - 是否强制刷新事务
*/
commitNext(forceFlush?: boolean): void;
/**
* 提交上一个视图
*
* 注意:在 `commitNext(true)` 后此方法还可以被调用,仅处理 `prev` 的卸载逻辑。
*/
commitPrev(): void;
/**
* 提交完整的事务
*/
commit(): void;
}
/**
* 支持的全局属性
*/
export declare interface VitarxIntrinsicAttributes {
/**
* 引用组件/元素实例
*/
ref?: InstanceRef;
/**
* 绑定属性
*
* 注意:不能通过 `v-bind` 指令绑定全局属性(ref、children...)。
*
* 可选值:
* - { [key: string]: unknown }:要绑定给元素的属性,`style`|`class`|`className`,会和原有值进行合并。
* - [props: { [key: string]: unknown }, exclude?: string[]]:第一个元素为要绑定给节点的属性对象,
* 第二个元素可以指定哪些属性不需要绑定。
*/
'v-bind'?: BindAttributes | null | undefined;
}
/**
* 组件属性类型拓展
*
* @template C - 组件类型
* @template P - 组件的默认属性类型
*/
export declare type VitarxManagedAttributes = C extends Component ? P extends AnyProps ? WithVModel>> : AnyProps : P;
declare type VModelValue = T extends Ref ? T | S : Ref | T;
/**
* 应用组件默认值类型
*
* @template C - 组件类型
* @template P - 组件的属性类型
*/
export declare type WithDefaultProps = 'defaultProps' extends RequiredKeys ? Omit & {
[K in keyof C['defaultProps'] as K extends keyof P ? K : never]?: K extends keyof P ? P[K] : never;
} : P;
/**
* 为虚拟节点添加指令
*
* 将一个或多个指令添加到虚拟节点的指令集合中。
* 每个指令通过其名称进行标识,并存储在vnode的directives Map中。
* 支持两种指令格式:简单指令对象和包含指令、值和参数的数组形式。
*
* @param view - 要添加指令的虚拟节点
* @param directives - 要添加的指令数组,可以是Directive对象数组或[Directive, value?, arg?]形式的元组数组
*
* @example
* ```typescript
* // 使用简单指令对象形式
* const focusDirective = { mounted: el => el.focus() };
* const tooltipDirective = { mounted: (el, binding) => { //... } };
*
* // 将指令添加到虚拟节点
* withDirectives(createVNode('div'), [focusDirective, tooltipDirective]);
* ```
*
* @example
* ```typescript
* // 使用数组形式,包含指令、值和参数
* const colorDirective = { mounted: (el, binding) => { //... } };
*
* const color = ref('red');
* // 将指令添加到虚拟节点,同时传递值和参数
* withDirectives(createVNode('input'), [
* [colorDirective, {get value(){return color.value}, arg:'theme'}] // 指令、值和参数
* ]);
* ```
*/
export declare function withDirectives(view: T, directives: Array<[name: string | Directive, binding: DirectiveBinding]> | Array): T;
export declare type WithModelEvent = T & {
[key in K extends string ? `onUpdate:${K}` : never]?: (value: T[K]) => void;
};
/**
* 根据视图标签类型推断其对应的属性类型
*
* @example
* ```ts
* // 通过继承 WithProps 可以让组件支持所有div元素的属性,
* interface Props extends WithProps<'div'> {
* // ... 其他自定义属性
* }
* const MyComponent = (props: Props) => {
* return
{props.children}
* }
* export default MyComponent
* ```
*
* @template T - 节点类型,必须继承自 ViewTag
*/
export declare type WithProps
= ExtractProps;
/**
* 属性支持引用值的类型
*
* 将对象类型 T 的所有属性转换为支持 Ref 包装的形式。
* 这对于创建可以是响应式或非响应式的属性对象非常有用,
* 特别是在组件属性定义和状态管理中。
*
* @template T - 原始对象类型
*
* @example
* ```ts
* interface ButtonProps {
* text: string;
* disabled?: boolean;
* onClick: () => void;
* }
*
* // 使用 WithRefProps 使属性支持响应式引用
* function createButton(props: WithRefProps) {
* // 函数实现,可以处理响应式和非响应式属性
* }
*
* // 以下两种参数类型都有效
* createButton({
* text: 'Click me',
* disabled: false,
* onClick: () => console.log('clicked')
* });
*
* createButton({
* text: ref('Click me'),
* disabled: ref(false),
* onClick: () => console.log('clicked')
* });
* ```
*/
export declare type WithRefProps = {
[K in keyof T]: MaybeRef;
};
declare type WithVModel = 'modelValue' extends keyof T ? 'modelValue' extends keyof PickRequired ? T | (Omit & {
/**
* v-model 双向绑定
*
* `v-model` 模仿 Vue 的 `v-model` 双向绑定,具有相同效果,
* 仅支持 `v-model <-> modelValue`,不兼容 `v-model:propName`。
*
* 示例:
* ```tsx
* const modelValue = ref('test')
*
* // 运行时等效于如下语法
* modelValue.value = v }/>
* ```
*/
'v-model': VModelValue;
}) : T | (Omit & {
/**
* v-model 双向绑定
*
* `v-model` 模仿 Vue 的 `v-model` 双向绑定,具有相同效果,
* 仅支持 `v-model <-> modelValue`,不兼容 `v-model:propName`。
*
* 示例:
* ```tsx
* const modelValue = ref('test')
*
* // 运行时等效于如下语法
* modelValue.value = v }/>
* ```
*/
'v-model'?: VModelValue;
}) : T;
export { }
declare global {
namespace Vitarx {
/**
* 宿主平台父节点接口
*
* @example
* ```ts
* declare global {
* namespace Vitarx {
* // 重写 DOM 平台的支持做为父元素的元素类型
* interface HostParentNode extends ParentNode {
*
* }
* }
* }
* ```
*/
interface HostContainerNode {
}
/**
* 允许渲染的元素
*
* 宿主平台包可以重写此接口以支持Tsx类型校验。
*/
interface IntrinsicElements {
[Tag: string]: {
[p: string]: unknown;
};
}
/**
* 宿主平台片段节点
*/
interface HostFragmentNode {
}
/**
* 宿主平台文本节点接口
*
* 用于表示纯文本内容的节点,如 Hello
中的 "Hello"。
* 文本节点只能包含纯文本内容,不能包含其他元素。
*/
interface HostTextNode {
}
/**
* 宿主平台注释节点接口
*
* 用于表示注释内容,如 中的 "This is a comment"。
* 在开发过程中,注释节点可用于显示调试信息,如条件渲染的提示。
*/
interface HostCommentNode {
}
/**
* 宿主平台运行时节点映射
*
* 此类型定义了运行时支持的元素类型标签与其实例的映射关系。
*
* @example
* ```ts
* declare global {
* namespace Vitarx {
* interface HostElementTagMap {
* div: HTMLDivElement,
* span: HTMLSpanElement,
* // 其他映射...
* }
* }
* }
* ```
*/
interface HostElementTagMap {
}
/**
* 元素支持的样式规则
*
* 运行时支持的样式规则映射,runtime-core包中未定义任何规则,需要在各平台渲染包中扩展此类型。
*/
interface HostCSSProperties {
}
/**
* Vitarx 框架内置固有属性
*/
interface IntrinsicAttributes extends VitarxIntrinsicAttributes {
}
/**
* App配置项
*/
interface AppConfig {
/**
* 错误处理函数
*
* @param error - 捕获到的异常
* @param info - 具体的错误信息
*/
errorHandler?: ErrorHandler;
/**
* useId() 返回的 ID 前缀
*
* 默认为 `v-`
*/
idPrefix?: string;
}
}
/**
* JSX 命名空间定义了 JSX 语法在 Vitarx 框架中的类型支持
* 这些类型使 TypeScript 能够正确理解和使用 JSX 语法
*/
namespace JSX {
/**
* 定义 JSX 元素的类型,可以是字符串(原生 HTML 标签)或组件
* 例如:'div'、MyComponent 等
*/
type ElementType = string | keyof IntrinsicElements | Component;
type Element = View;
/**
* JSX 内置属性接口,扩展了 Vitarx 的内置属性
* 包含所有 JSX 元素都可以使用的通用属性
*/
interface IntrinsicAttributes extends Vitarx.IntrinsicAttributes {
}
/**
* JSX 内置元素类型定义
* 将原生 HTML 标签名映射到对应的属性类型,并添加 ref 支持
* 例如:div、span、button 等标签的属性类型
*/
interface IntrinsicElements extends IntrinsicElementsWithRefProps {
}
/**
* 库管理的属性类型
* 用于处理组件属性的类型转换和验证
* C: 组件类型,P: 属性类型
*/
type LibraryManagedAttributes = VitarxManagedAttributes;
interface ElementAttributesProperty {
props: {};
}
interface ElementChildrenAttribute {
children: {};
}
}
}