docs: 逐模块细化中文逻辑注释并覆盖测试与示例
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
//! 托管事件与订阅的传播实现。Connection 持有回调引用,Event 保存目标、阶段与停止传播状态。
|
||||
//! 分发沿出现关系执行 capture → target → bubble,并处理默认行为;只有同一 VM 中的回调可以接触托管对象。
|
||||
//! 分发沿出现关系执行 capture → target → bubble,记录默认行为阻止状态;只有同一 VM 中的回调可以接触托管对象。
|
||||
//!
|
||||
//! Managed subscriptions and occurrence-specific propagation. A validated VM
|
||||
//! function sequences calls, so all handlers share one execution budget.
|
||||
@@ -9,6 +9,7 @@ use endor_core::{
|
||||
Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
|
||||
// 一次分发最多安排 10000 个处理器,另由共享 VM 驱动约束全部回调的总执行预算。
|
||||
const MAX_DELIVERIES: usize = 10_000;
|
||||
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
@@ -26,6 +27,7 @@ pub fn validate_handler(
|
||||
let arity = store
|
||||
.call_arity(function)?
|
||||
.ok_or(invalid("event handler requires positional metadata"))?;
|
||||
// 允许无参便捷回调或单 Event 回调;实际递送时优先传 Event(若接受一参),否则零参调用。
|
||||
if !arity.accepts(0) && !arity.accepts(1) {
|
||||
return Err(invalid(
|
||||
"event handler must accept zero arguments or one Event",
|
||||
@@ -37,10 +39,15 @@ pub fn validate_handler(
|
||||
#[derive(Debug, Clone, Default)]
|
||||
/// 本次传播的托管事件状态,包含目标、当前阶段和阻止默认/停止传播控制。
|
||||
pub struct Event {
|
||||
// 弱引用本轮 guard,检测同一 Event 是否正在分发;驱动释放后 guard 消失,事件可再次使用。
|
||||
dispatch: Option<WeakObjectRef>,
|
||||
// 当前传播组,一般对应路径中的一个出现/阶段;目标捕获与目标非捕获共用一组。
|
||||
group: usize,
|
||||
// stopPropagation 记下当前组,只阻止后续其他组;同组余下处理器仍执行。
|
||||
stopped_at: Option<usize>,
|
||||
// stopImmediatePropagation 全局跳过后续 Delivery,连当前组剩余处理器也停止。
|
||||
immediate: bool,
|
||||
// preventDefault 仅记录默认行为是否被阻止;本模块不在这里实现具体的系统默认动作。
|
||||
prevented: bool,
|
||||
}
|
||||
impl ObjectPayload for Event {
|
||||
@@ -122,12 +129,12 @@ enum Method {
|
||||
Connected,
|
||||
}
|
||||
impl NativeCallable for Method {
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 事件与订阅查询/控制方法无显式参数,只接受隐式 Event 或 Subscription 接收者。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 按操作读取或修改连接/传播状态;断开清除真实 handler/compute,停止标志写回同一 Event。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Object(owner)] = args else {
|
||||
return Err(invalid("event method receiver"));
|
||||
@@ -139,6 +146,7 @@ impl NativeCallable for Method {
|
||||
.payload::<Subscription>(*owner, "Subscription")?
|
||||
.connection;
|
||||
let connection = cx.upgrade(weak)?;
|
||||
// Subscription 同时包装事件 Connection 和属性 Binding;按 payload 类型清 handler 或 compute。
|
||||
let connected = if let Some(connection) = connection {
|
||||
if cx
|
||||
.store()
|
||||
@@ -152,6 +160,7 @@ impl NativeCallable for Method {
|
||||
.payload::<crate::binding::Binding>(connection, "Binding")?
|
||||
.clone();
|
||||
let connected = data.compute.is_some();
|
||||
// 取消切断真实强拥有边,外部仍可保留 token,但 token 弱引用本身不保活回调或目标。
|
||||
if matches!(self, Self::Disconnect) {
|
||||
data.compute = None;
|
||||
cx.replace_payload(connection, data)?;
|
||||
@@ -210,16 +219,17 @@ impl NativeCallable for Constructor {
|
||||
fn signature(&self) -> Option<endor_core::CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 至少接收隐式请求 Type 和事件 kind,额外参数留给源子类声明字段。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::range(2, usize::MAX))
|
||||
}
|
||||
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 先验证事件子类字段数量与注解,再创建原生 Event 并填充声明字段,错误不得留下部分实例。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Object(definition), Value::Text(kind), values @ ..] = args else {
|
||||
return Err(invalid("Event requires an event kind"));
|
||||
};
|
||||
// 事件子类构造先验证额外字段参数数量与注解,再创建默认事件并逐字段初始化。
|
||||
let fields = cx
|
||||
.store()
|
||||
.payload::<endor_core::EndorTypeObject>(*definition, "Type")?
|
||||
@@ -250,6 +260,7 @@ pub fn new_event(
|
||||
let event = cx.allocate(Event::default())?;
|
||||
cx.attach_type(event, definition)?;
|
||||
cx.set_attr(event, "kind", Value::Text(kind.into()))?;
|
||||
// 新事件尚未递送,目标、出现与 hit 都为空;kind 保留输入种类,phase 初始 none。
|
||||
for name in ["target", "mount", "currentTarget", "currentMount", "hit"] {
|
||||
cx.set_attr(event, name, Value::Nil)?;
|
||||
}
|
||||
@@ -268,7 +279,7 @@ impl NativeCallable for TypedMethod {
|
||||
fn signature(&self) -> Option<endor_core::CallSignature> {
|
||||
Some(self.signature.clone())
|
||||
}
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 把已声明签名的调用交给内部 Method,复用事件/订阅控制实现,不创建第二套状态。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
self.method.invoke(cx, args)
|
||||
}
|
||||
@@ -294,6 +305,7 @@ pub fn install(
|
||||
(token_type, "disconnect", Method::Disconnect),
|
||||
(token_type, "isConnected", Method::Connected),
|
||||
] {
|
||||
// isDefaultPrevented/isConnected 返回 Bool 且只读;控制传播和取消方法返回 Unit 并声明 Mutating。
|
||||
let query = matches!(method, Method::Prevented | Method::Connected);
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
@@ -340,18 +352,20 @@ struct Delivery {
|
||||
handler: Handler,
|
||||
}
|
||||
impl NativeCallable for Delivery {
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 单次递送步骤的 Event/handler/阶段已保存在适配器中,执行时不再接收参数。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 轮到该处理器时重查传播状态和连接是否仍有效,更新当前阶段/目标,再按真实回调 arity 发出 VM 调用。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mut event = cx.store().payload::<Event>(self.event, "Event")?.clone();
|
||||
// 真正轮到处理器时重新读取传播状态,之前回调的 stop 操作立即影响后续项,无需重建序列。
|
||||
if event.immediate || event.stopped_at.is_some_and(|group| group != self.group) {
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
let (function, mut arguments) = match self.handler {
|
||||
// 序列只捕获 Connection,不快照 handler;前面处理器取消它后,这里看到 None 并跳过。
|
||||
Handler::Token(token) => {
|
||||
let Some(handler) = cx
|
||||
.store()
|
||||
@@ -363,6 +377,7 @@ impl NativeCallable for Delivery {
|
||||
(handler, vec![])
|
||||
}
|
||||
Handler::Legacy(function) => (function, vec![]),
|
||||
// 对象协议在执行到该项时解析实际类型的 onEvent;显式 receiver 先放入实参向量。
|
||||
Handler::ObjectMethod => {
|
||||
let Some(definition) = cx.store().type_of(self.owner)? else {
|
||||
return Err(invalid("untyped event target"));
|
||||
@@ -374,6 +389,7 @@ impl NativeCallable for Delivery {
|
||||
(function, vec![Value::Object(self.owner)])
|
||||
}
|
||||
};
|
||||
// 调用前更新 currentTarget/currentMount/phase,处理器观察到的是当前路径项,不会误用最终目标。
|
||||
event.group = self.group;
|
||||
cx.replace_payload(self.event, event)?;
|
||||
cx.set_attr(self.event, "phase", Value::Text(self.phase.into()))?;
|
||||
@@ -383,6 +399,7 @@ impl NativeCallable for Delivery {
|
||||
"currentMount",
|
||||
self.mount.map(Value::Object).unwrap_or(Value::Nil),
|
||||
)?;
|
||||
// 对象方法总是携带 Event;显式订阅/旧式回调按 arity 决定是否传 Event。
|
||||
if matches!(self.handler, Handler::ObjectMethod)
|
||||
|| cx
|
||||
.store()
|
||||
@@ -398,17 +415,18 @@ impl NativeCallable for Delivery {
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 传播结束后的默认行为收尾步骤。
|
||||
/// 正常传播结束后清理当前目标、阶段和 guard 标记,返回仍保留最终控制状态的 Event。
|
||||
struct Finish(ObjectRef);
|
||||
impl NativeCallable for Finish {
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 派发结束步骤已持有 Event 引用,无需显式输入。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 正常序列结束时清除活跃派发守卫与当前上下文,保留 target/prevented 并返回实际 Event,允许后续重用。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mut event = cx.store().payload::<Event>(self.0, "Event")?.clone();
|
||||
// 正常序列结束清递送标记与当前上下文,保留原始 target/mount 和 prevented 供调用方读取。
|
||||
event.dispatch = None;
|
||||
cx.replace_payload(self.0, event)?;
|
||||
cx.set_attr(self.0, "phase", Value::Text("none".into()))?;
|
||||
@@ -421,7 +439,7 @@ impl NativeCallable for Finish {
|
||||
/// Snapshot the selected occurrence's route and listener order. Disconnection
|
||||
/// before a listener's turn skips it; newly registered listeners wait for the
|
||||
/// next dispatch. A code event without a Mount visits only its target object.
|
||||
/// 按 Mount 祖先路径执行捕获、目标与冒泡阶段,再处理对应默认行为。
|
||||
/// 快照 Mount 路径和订阅顺序,构造共享预算的 capture/target/bubble 驱动并返回 VM 续调。
|
||||
pub fn dispatch(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
@@ -430,6 +448,7 @@ pub fn dispatch(
|
||||
desktop: ObjectRef,
|
||||
) -> Result<NativeResult, VmError> {
|
||||
let mut event = cx.store().payload::<Event>(event_ref, "Event")?.clone();
|
||||
// 只有 guard 仍存活才禁止重入;此前分发失败但 guard 已释放时,不让旧弱身份永久锁住 Event。
|
||||
if let Some(weak) = event.dispatch
|
||||
&& cx.upgrade(weak)?.is_some()
|
||||
{
|
||||
@@ -441,13 +460,16 @@ pub fn dispatch(
|
||||
if kind.is_empty() || kind.len() > 128 {
|
||||
return Err(invalid("invalid event kind"));
|
||||
}
|
||||
// 路线由目标向外保存。无 Mount 的代码事件只访问目标对象,不猜测共享 Block 属于哪个出现。
|
||||
let mut route = vec![(owner, mount)];
|
||||
if let Some(mount) = mount {
|
||||
let target = cx.store().payload::<Mount>(mount, "Mount")?.clone();
|
||||
// 传入 Mount 必须仍挂接且确实展示 owner;同一 Block 的另一个出现不能替代该上下文。
|
||||
if !target.mounted || target.block != owner {
|
||||
return Err(invalid("event context does not belong to this Block"));
|
||||
}
|
||||
let mut parent = target.parent;
|
||||
// 沿弱 parent 链构建本轮路径快照,检查死亡祖先、脱离与环;不通过 Block 业务孩子关系反推祖先。
|
||||
let mut seen = std::collections::HashSet::from([mount]);
|
||||
while let Some(weak) = parent {
|
||||
let ancestor = cx
|
||||
@@ -463,15 +485,18 @@ pub fn dispatch(
|
||||
route.push((data.block, Some(ancestor)));
|
||||
parent = data.parent;
|
||||
}
|
||||
// 出现祖先之外再加入 Page 上下文,页面本身无 currentMount;弱页已失效则拒绝该旧路线。
|
||||
if let Some(weak) = target.page {
|
||||
let page = cx.upgrade(weak)?.ok_or(invalid("event Page has expired"))?;
|
||||
route.push((page, None));
|
||||
}
|
||||
}
|
||||
// 所有递送和 Finish 显式捕获 guard,Event 只弱引用它;驱动完成/失败释放后 guard 自动结束本轮资格。
|
||||
let guard = cx.new_object()?;
|
||||
let mut calls = Vec::new();
|
||||
let mut group = 0;
|
||||
// Each occurrence is its own propagation group, even for shared Blocks.
|
||||
// 先从最外层向目标递送捕获,再从目标向外递送非捕获;目标两次遍历都标记 phase=target。
|
||||
let traversal = route
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -486,6 +511,7 @@ pub fn dispatch(
|
||||
for (index, &(block, current_mount), capture) in traversal {
|
||||
let (_, data) = block::resolve(cx.store(), block)?;
|
||||
let mut handlers = Vec::new();
|
||||
// 本轮先快照符合事件 kind 与 capture 的订阅顺序;回调期间新注册的连接不进入当前分发。
|
||||
for token in &data.subscriptions {
|
||||
let token_data = cx.store().payload::<Connection>(*token, "Connection")?;
|
||||
if token_data.handler.is_some()
|
||||
@@ -496,6 +522,7 @@ pub fn dispatch(
|
||||
}
|
||||
}
|
||||
if !capture {
|
||||
// 非捕获阶段 onEvent 先执行,再按订阅顺序,最后兼容旧 click 回调。
|
||||
handlers.insert(0, Handler::ObjectMethod);
|
||||
if kind == "click"
|
||||
&& let Some(handler) = data.click
|
||||
@@ -507,6 +534,7 @@ pub fn dispatch(
|
||||
if calls.len() >= MAX_DELIVERIES {
|
||||
return Err(invalid("event delivery budget exceeded"));
|
||||
}
|
||||
// 每一项显式保活本轮 Event、guard、目标和可选 Mount/连接;不能仅靠 Rust ObjectRef 值当 GC 根。
|
||||
let mut captures = vec![event_ref, guard, block];
|
||||
if let Some(mount) = current_mount {
|
||||
captures.push(mount);
|
||||
@@ -538,6 +566,7 @@ pub fn dispatch(
|
||||
}
|
||||
// Capture and bubble at the target are one group: stopPropagation at
|
||||
// target capture still permits other target listeners.
|
||||
// 目标捕获后不递增 group,使 stopPropagation 仍允许目标非捕获处理器;其他路径/阶段则隔离为新组。
|
||||
if index != 0 || !capture {
|
||||
group += 1;
|
||||
}
|
||||
@@ -547,10 +576,12 @@ pub fn dispatch(
|
||||
Finish(event_ref),
|
||||
vec![event_ref, guard],
|
||||
))?;
|
||||
// 无论传播是否被停止,Finish 都作为序列最后一项执行,它不受 Delivery 的 stopped 判定影响。
|
||||
calls.push(finish);
|
||||
let driver = crate::vm_sequence::build(cx, calls, "<event dispatch>", desktop)?;
|
||||
event.dispatch = Some(cx.store().downgrade(guard)?);
|
||||
event.group = 0;
|
||||
// 再次使用 Event 时清上一轮停止和默认阻止标志;目标与 Mount 属性也被本轮参数覆盖。
|
||||
event.stopped_at = None;
|
||||
event.immediate = false;
|
||||
event.prevented = false;
|
||||
|
||||
Reference in New Issue
Block a user