Bind managed Block properties with read-only dependency tracking
Verify Tessera GUI / verify (push) Failing after 7m31s
Verify Tessera GUI / verify (push) Failing after 7m31s
This commit is contained in:
@@ -196,6 +196,12 @@ Native visual methods are now available on Block: `measure(mount, Constraints(mi
|
||||
|
||||
Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects; methods validate their contents when used, and global annotation type checking remains pending.
|
||||
|
||||
`block.bind(property, compute)` binds an existing managed field to a zero-argument function and returns a Subscription with disconnect()/isConnected(). Targets are Block fields, including source-defined fields; arbitrary non-Block objects are not binding targets yet. Native visual fields are now ordinary attributes: TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Direct assignments and native setters feed the same visual snapshot. Text size remains 1..8, geometry must be finite/nonnegative and within the existing limits, and colors use the existing color parser. Legacy textOf still owns its derived text until setText or a text binding replaces it.
|
||||
|
||||
The target's managed content owns its bindings; each binding traces the actual compute function and its captures. Tokens and the host registry hold weak references. Rebinding a field disconnects its previous binding; disconnecting leaves the last value in place. Hidden but still-referenced Blocks update at successful input/event/viewport stabilization boundaries. Functions run read-only against existing objects; they may construct result objects. Dependencies are recorded from actual VM reads, with object-level versions and conservative global-dictionary invalidation. This replaces the earlier candidate API's explicit source list. Binding results are settled before frame publication, including across windows and after lifecycle changes. Values read earlier in the same input precede this batch boundary. Explicit dependencies and property-level dependency precision remain future work.
|
||||
|
||||
One Block can have up to 128 active bindings. Each computation has 100000 instructions/128 frames, and a refresh rejects after 10000 computations if dependencies do not stabilize; it reports an error and preserves the published picture instead of silently truncating propagation. A live binding-computation failure stops that runtime. General type/effect checking remains pending. See [property-bindings.endor](examples/property-bindings.endor) for actual Endor source.
|
||||
|
||||
`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Explicit traits, full type/effect contracts, more precise context dependencies and general container constraint negotiation remain future work.
|
||||
|
||||
A source subclass can override `measure(self, mount, constraints): MeasureResult` and `arrange(self, mount, geometry): Arrangement`. The persistent renderer creates stable Mount identities and parent/child/sibling links before measuring. Measurement proceeds bottom-up with the current logical viewport as the Page constraints (headless callers default to 0..1000000); native parents and explicit native base calls use the current occurrence's measured child sizes, including source overrides. Arrangement proceeds top-down; each child Bounds must be assigned exactly once using its stable slot, with nominal result types and finite geometry checked. Source arrangements can resize or move children; omission, duplicate/foreign slots and invalid geometry reject the frame. See [source-layout.endor](examples/source-layout.endor).
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
class Model {
|
||||
width: Number
|
||||
color: String
|
||||
label: String
|
||||
function getWidth(self: Model): Number { return self.width }
|
||||
function getColor(self: Model): String { return self.color }
|
||||
function getLabel(self: Model): String { return self.label }
|
||||
function expand(self: Model, event: Event): Unit {
|
||||
self.width = 260
|
||||
self.color = "#237A45"
|
||||
self.label = "绑定已更新"
|
||||
}
|
||||
}
|
||||
model = Model(120, "#526AC7", "点击更新共享对象")
|
||||
rect = RectBlock(120, 40, 8, "#526AC7")
|
||||
label = TextBlock("初始化")
|
||||
widthBinding = rect.bind("width", model.getWidth)
|
||||
colorBinding = rect.bind("color", model.getColor)
|
||||
labelBinding = label.bind("text", model.getLabel)
|
||||
button = Button("更新宽度、颜色和文字")
|
||||
clickConnection = button.on("click", model.expand)
|
||||
root = Column(24, 16, label, rect, button)
|
||||
page = Page()
|
||||
page.title = "通用属性绑定"
|
||||
page.render(root)
|
||||
second = Page()
|
||||
second.title = "同一组 Block"
|
||||
second.render(root)
|
||||
page.activate()
|
||||
@@ -8,6 +8,7 @@
|
||||
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
|
||||
| endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot |
|
||||
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, tab registry, Page lifecycle/navigation and immutable frame extraction |
|
||||
| binding.rs | Target-owned managed property bindings, weak Subscription tokens, read-only compute and borrowed dependency/output caches |
|
||||
| block.rs | Aster-managed Block/Cell/data graph, stable child slots, content-owned field storage, shared assignment, cycle validation and explicit text bindings |
|
||||
| snapshot.rs | Property and visual-method identity dependencies across shared field-storage paths, reverse parent links and cached immutable visual derivation |
|
||||
| mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries |
|
||||
@@ -95,3 +96,13 @@ are filtered by their published runtime generation. Native window/surface failur
|
||||
are returned to the host diagnostics rather than panicking the event loop; main
|
||||
window initialization errors propagate to process exit. The stopped-window and
|
||||
cross-generation regression sources are compiled, not locally executed.
|
||||
|
||||
Native visual scalar parameters live in the Block's managed property storage.
|
||||
Snapshot extraction validates and reads those fields, and records exact property
|
||||
invalidation keys. Payload kind values remain constructor defaults; drawing uses
|
||||
the property projection. Binding refresh traverses the weak visual registry and
|
||||
deduplicates forwarded content, including hidden objects. It records object-level
|
||||
read versions and borrowed output values for equality without adding GC roots;
|
||||
cache updates do not mutate the connection's business version. Target content
|
||||
traces the compute function. Subscription tokens are weak and also support bindings.
|
||||
All binding work settles before published frames; compute failure stops the VM.
|
||||
|
||||
@@ -1042,6 +1042,8 @@ Source measure and arrange overrides execute bottom-up and top-down in one read-
|
||||
|
||||
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
|
||||
|
||||
Block.bind(property, compute) binds an existing managed Block field to a zero-argument function and returns Subscription (disconnect/isConnected). This includes source-defined fields and native TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Native fields can also be assigned directly. The target content owns compute/captures; tokens and host registry are weak. Rebinding disconnects the old connection; disconnect keeps the last value. Actual read dependencies are tracked at object granularity, including conservative global reads; no explicit source-list parameter is required. Hidden retained Blocks update at successful input/event stabilization boundaries before all windows publish. Computes are read-only for existing objects and may allocate results. They have 100000 instructions/128 frames each, 128 active bindings per Block and a 10000-computation refresh limit that errors rather than truncates propagation. Binding failure stops the live VM and preserves published pictures. Non-Block targets, explicit dependency lists and general type/effect checking remain pending. See examples/property-bindings.endor.
|
||||
|
||||
Native input POST /events is a transport envelope, not Endor source. Each frame and input carries an opaque runtime window identity; omitted input window defaults to 1 for existing clients. GET /code exposes X-Tessera-Window. A window/session/layout identity mismatch is rejected before invoking code. Tab actions use kind tab-activate/tab-close/tab-detach and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. All spatial/tab actions validate session and layout_version before dispatch. Resource window-close uses mount=0 and no points; it validates the live window/session rather than its old layout version. The window
|
||||
sends current session, layout_version and Mount identity; stale positions fail without calling a callback. Pointer clicks also include point and press_point [x,y] in logical page coordinates. Both targets are resolved through read-only hitTest, with fallback behind a rejected candidate; a click is dispatched only when both resolve to the same Mount. Keyboard/code clicks omit coordinates and remain semantic activation. GET /code also exposes X-Tessera-Session and X-Tessera-Layout-Version headers for transport clients. Native mouse, Tab, Enter and Space delegate to the same
|
||||
managed click/focus methods used by code. Events appear in Network, not Console source history.
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
//! Target-owned managed bindings. Dependency versions are borrowed identities;
|
||||
//! the host's weak Block registry never roots an otherwise unreachable graph.
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{NativeContext, ObjectPayload, ObjectRef, Value, Vm, VmError, WeakObjectRef};
|
||||
|
||||
use crate::{block, event_dispatch::Subscription, ui_bridge::attach_desktop_type};
|
||||
|
||||
/// The output value is borrowed for equality only, including object handles.
|
||||
/// It never owns a reference or dereferences a possibly reclaimed cached object.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Cached {
|
||||
reads: BTreeMap<ObjectRef, u64>,
|
||||
output: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Binding {
|
||||
field: String,
|
||||
pub compute: Option<ObjectRef>,
|
||||
reads: Arc<Mutex<Option<Cached>>>,
|
||||
}
|
||||
impl ObjectPayload for Binding {
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-binding"
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(compute) = self.compute {
|
||||
visit(compute);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(
|
||||
cx: &mut NativeContext<'_>,
|
||||
target: ObjectRef,
|
||||
field: &str,
|
||||
compute: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
if field.is_empty() || field.len() > 128 || field == "type" {
|
||||
return Err(VmError::InvalidArgument("invalid binding property"));
|
||||
}
|
||||
let (reference, data) = block::resolve(cx.store(), target)?;
|
||||
let mut data = data.clone();
|
||||
// Only actual fields can be bound; method names are not writable targets.
|
||||
let properties = data
|
||||
.properties
|
||||
.ok_or(VmError::InvalidArgument("missing property storage"))?;
|
||||
cx.store().get_attr(properties, field)?;
|
||||
cx.store().object(compute)?;
|
||||
let mut retained = vec![];
|
||||
for connection in &data.bindings {
|
||||
let mut binding = cx
|
||||
.store()
|
||||
.payload::<Binding>(*connection, "Binding")?
|
||||
.clone();
|
||||
if binding.compute.is_some() && binding.field != field {
|
||||
retained.push(*connection);
|
||||
} else if binding.compute.is_some() {
|
||||
binding.compute = None;
|
||||
*binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| VmError::InvalidArgument("binding cache poisoned"))? = None;
|
||||
cx.replace_payload(*connection, binding)?;
|
||||
}
|
||||
}
|
||||
if retained.len() >= 128 {
|
||||
return Err(VmError::ExecutionLimit("128 bindings per Block"));
|
||||
}
|
||||
let connection = cx.allocate(Binding {
|
||||
field: field.into(),
|
||||
compute: Some(compute),
|
||||
reads: Arc::new(Mutex::new(None)),
|
||||
})?;
|
||||
retained.push(connection);
|
||||
data.bindings = retained;
|
||||
// Generic text bindings replace the legacy textOf derivation.
|
||||
if field == "text" {
|
||||
data.text_binding = None;
|
||||
}
|
||||
cx.replace_payload(reference, data)?;
|
||||
let token = cx.allocate(Subscription {
|
||||
connection: cx.store().downgrade(connection)?,
|
||||
})?;
|
||||
attach_desktop_type(cx, token, "Subscription", desktop)?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub fn refresh(vm: &mut Vm, nodes: &[WeakObjectRef]) -> Result<()> {
|
||||
let mut work = 0;
|
||||
loop {
|
||||
let mut evaluated = false;
|
||||
let mut seen = HashSet::new();
|
||||
for weak in nodes {
|
||||
let Some(target) = vm.upgrade(*weak)? else {
|
||||
continue;
|
||||
};
|
||||
let result: Result<()> = (|| {
|
||||
let (reference, data) = block::resolve(vm.object_store(), target)?;
|
||||
if !seen.insert(reference) {
|
||||
return Ok(());
|
||||
}
|
||||
let connections = data.bindings.clone();
|
||||
for connection in connections {
|
||||
let binding = vm.payload::<Binding>(connection, "Binding")?.clone();
|
||||
let Some(compute) = binding.compute else {
|
||||
continue;
|
||||
};
|
||||
let cached = binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("binding cache poisoned"))?
|
||||
.clone();
|
||||
if cached.as_ref().is_some_and(|cached| {
|
||||
cached.reads.iter().all(|(object, version)| {
|
||||
vm.object_store().change_version(*object).ok() == Some(*version)
|
||||
}) && vm
|
||||
.get_attr(target, &binding.field)
|
||||
.is_ok_and(|value| value == cached.output)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
work += 1;
|
||||
if work > 10_000 {
|
||||
bail!("property bindings did not stabilize within the execution budget");
|
||||
}
|
||||
evaluated = true;
|
||||
let (value, reads) = vm
|
||||
.call_read_only_with_limits(
|
||||
compute,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 100_000,
|
||||
},
|
||||
)
|
||||
.map_err(|error| crate::endor_host::runtime_error(vm, error))?;
|
||||
let applied: Result<()> = (|| {
|
||||
let mut versions = BTreeMap::new();
|
||||
for object in reads {
|
||||
if let Ok(version) = vm.object_store().change_version(object) {
|
||||
versions.insert(object, version);
|
||||
}
|
||||
}
|
||||
let (_, data) = block::resolve(vm.object_store(), target)?;
|
||||
block::apply_visual_property(&mut data.clone(), &binding.field, &value)?;
|
||||
if vm.get_attr(target, &binding.field)? != value {
|
||||
vm.set_attr(target, &binding.field, value.clone())?;
|
||||
}
|
||||
*binding
|
||||
.reads
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("binding cache poisoned"))? =
|
||||
Some(Cached {
|
||||
reads: versions,
|
||||
output: value.clone(),
|
||||
});
|
||||
Ok(())
|
||||
})();
|
||||
vm.release_value(value)?;
|
||||
applied?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
vm.release(target)?;
|
||||
result?;
|
||||
}
|
||||
if !evaluated {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
+103
-1
@@ -112,6 +112,7 @@ pub struct Data {
|
||||
pub next_slot: u64,
|
||||
pub history: Vec<ObjectRef>,
|
||||
pub history_index: usize,
|
||||
pub bindings: Vec<ObjectRef>,
|
||||
pub text_binding: Option<(ObjectRef, String)>,
|
||||
pub click: Option<ObjectRef>,
|
||||
pub subscriptions: Vec<ObjectRef>,
|
||||
@@ -136,6 +137,7 @@ impl Data {
|
||||
next_slot,
|
||||
history: vec![],
|
||||
history_index: 0,
|
||||
bindings: vec![],
|
||||
text_binding: None,
|
||||
click: None,
|
||||
subscriptions: vec![],
|
||||
@@ -173,6 +175,9 @@ impl ObjectPayload for Data {
|
||||
if let Some((source, _)) = &self.text_binding {
|
||||
visit(*source);
|
||||
}
|
||||
for binding in &self.bindings {
|
||||
visit(*binding);
|
||||
}
|
||||
for token in &self.subscriptions {
|
||||
visit(*token);
|
||||
}
|
||||
@@ -187,7 +192,11 @@ pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef,
|
||||
for child in &data.children {
|
||||
validate(cx.store(), child.block, None)?;
|
||||
}
|
||||
data.properties = Some(cx.new_object()?);
|
||||
let properties = cx.new_object()?;
|
||||
for (name, value) in native_properties(&data) {
|
||||
cx.set_attr(properties, name, value)?;
|
||||
}
|
||||
data.properties = Some(properties);
|
||||
let data = cx.allocate(data)?;
|
||||
let state = cx.new_cell(Some(Value::Object(data)))?;
|
||||
cx.allocate(Block { state, page })
|
||||
@@ -283,3 +292,96 @@ pub fn validate(
|
||||
pub fn snapshot(store: &ObjectStore, root: ObjectRef) -> Result<Arc<UiNode>, VmError> {
|
||||
crate::snapshot::RenderCache::default().snapshot(store, root)
|
||||
}
|
||||
|
||||
/// Native visual parameters are ordinary managed attributes too. Composition,
|
||||
/// histories and connections remain structural payload edges.
|
||||
pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
||||
fn number(value: f32) -> Value {
|
||||
Value::Number((value as f64).into())
|
||||
}
|
||||
let mut fields = vec![];
|
||||
match &data.kind {
|
||||
Kind::Text { value, size, color } => fields.extend([
|
||||
("text", Value::Text(value.clone())),
|
||||
("size", Value::Number((*size as i64).into())),
|
||||
("color", Value::Text(color.clone())),
|
||||
]),
|
||||
Kind::Rect {
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
} => fields.extend([
|
||||
("width", number(*width)),
|
||||
("height", number(*height)),
|
||||
("radius", number(*radius)),
|
||||
("color", Value::Text(color.clone())),
|
||||
]),
|
||||
Kind::Spacer(size) => fields.push(("size", number(*size))),
|
||||
_ => {}
|
||||
}
|
||||
if data.is_container() {
|
||||
fields.extend([("padding", number(data.padding)), ("gap", number(data.gap))]);
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
let mut data = data.clone();
|
||||
let properties = data
|
||||
.properties
|
||||
.ok_or(VmError::InvalidArgument("missing Block properties"))?;
|
||||
for (name, _) in native_properties(&data) {
|
||||
let value = store.get_attr(properties, name)?;
|
||||
apply_visual_property(&mut data, name, &value)?;
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Result<(), VmError> {
|
||||
let bad = || VmError::InvalidArgument("invalid native visual property");
|
||||
let number = || -> Result<f32, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
let n = value.to_string().parse::<f32>().map_err(|_| bad())?;
|
||||
if !n.is_finite() || !(0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(&n) {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(n)
|
||||
};
|
||||
let container = data.is_container();
|
||||
match (&mut data.kind, name) {
|
||||
(Kind::Text { value: text, .. }, "text") => {
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
if value.len() > 16_384 {
|
||||
return Err(bad());
|
||||
}
|
||||
text.clone_from(value);
|
||||
}
|
||||
(Kind::Text { size, .. }, "size") => {
|
||||
let n = number()?;
|
||||
if !(1.0..=8.0).contains(&n) || n.fract() != 0.0 {
|
||||
return Err(bad());
|
||||
}
|
||||
*size = n as u32;
|
||||
}
|
||||
(Kind::Text { color, .. } | Kind::Rect { color, .. }, "color") => {
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
crate::document::parse_color(value).map_err(|_| bad())?;
|
||||
color.clone_from(value);
|
||||
}
|
||||
(Kind::Rect { width, .. }, "width") => *width = number()?,
|
||||
(Kind::Rect { height, .. }, "height") => *height = number()?,
|
||||
(Kind::Rect { radius, .. }, "radius") => *radius = number()?,
|
||||
(Kind::Spacer(size), "size") => *size = number()?,
|
||||
(_, "padding") if container => data.padding = number()?,
|
||||
(_, "gap") if container => data.gap = number()?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
.map_err(|error| runtime_error(&candidate.vm, error))?;
|
||||
candidate.vm.release_value(value)?;
|
||||
}
|
||||
bridge.refresh_bindings(&mut candidate.vm)?;
|
||||
let ui_root = match &plan {
|
||||
SourcePlan::Script(_) => bridge
|
||||
.rendered(&candidate.vm)?
|
||||
@@ -75,6 +76,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
.vm
|
||||
.call_with_limits(entry, &[], LIMITS)
|
||||
.map_err(|error| runtime_error(&candidate.vm, error))?;
|
||||
bridge.refresh_bindings(&mut candidate.vm)?;
|
||||
let snapshot = bridge
|
||||
.rendered(&candidate.vm)
|
||||
.and_then(|rendered| match rendered {
|
||||
@@ -475,6 +477,10 @@ impl ReplSession {
|
||||
let mut mutated_mounts = false;
|
||||
let result = (|| {
|
||||
loop {
|
||||
if let Err(error) = self.bridge.refresh_bindings(&mut self.candidate.vm) {
|
||||
self.faulted = true;
|
||||
return Err(error);
|
||||
}
|
||||
let mut pass_changed = false;
|
||||
for id in self.bridge.window_ids()? {
|
||||
self.bridge.select_window(id)?;
|
||||
@@ -2556,6 +2562,167 @@ mod tests {
|
||||
assert!(!session.is_faulted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_property_bindings_update_hidden_objects_and_shared_window_geometry() {
|
||||
let mut session = ReplSession::new(220).unwrap();
|
||||
session
|
||||
.execute(
|
||||
r##"
|
||||
class Model {
|
||||
width: Number
|
||||
function read(self: Model): Number { return self.width }
|
||||
}
|
||||
model = Model(80)
|
||||
rect = RectBlock(1,20,0,"#DDEEFF")
|
||||
token = rect.bind("width",model.read)
|
||||
"##,
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session.execute("rect.width", "app.main").unwrap().value,
|
||||
"80"
|
||||
);
|
||||
session.execute("model.width = 140", "app.main").unwrap();
|
||||
assert_eq!(
|
||||
session.execute("rect.width", "app.main").unwrap().value,
|
||||
"140"
|
||||
);
|
||||
session.execute("first = Page()\nfirst.render(rect)\nother = Window()\nsecond = Page()\nsecond.open(other)\nsecond.render(rect)", "app.main").unwrap();
|
||||
let updated = session
|
||||
.execute("model.width = 260", "app.main")
|
||||
.unwrap()
|
||||
.document
|
||||
.unwrap();
|
||||
for frame in std::iter::once(&updated.frame)
|
||||
.chain(updated.windows.values().map(|document| &document.frame))
|
||||
{
|
||||
assert!(frame.mounts.iter().any(|mount| mount.width == 260.0));
|
||||
}
|
||||
session
|
||||
.execute("token.disconnect()\nmodel.width = 360", "app.main")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session.execute("rect.width", "app.main").unwrap().value,
|
||||
"260"
|
||||
);
|
||||
let direct = session
|
||||
.execute("rect.width = 180", "app.main")
|
||||
.unwrap()
|
||||
.document
|
||||
.unwrap();
|
||||
assert!(direct.frame.mounts.iter().any(|mount| mount.width == 180.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_object_outputs_on_one_target_do_not_invalidate_each_other() {
|
||||
let mut session = ReplSession::new(222).unwrap();
|
||||
session
|
||||
.execute(
|
||||
r##"
|
||||
class Record { value: Number }
|
||||
function makeRecord(): Object { return Record(7) }
|
||||
rect = RectBlock(1,20)
|
||||
rect.first = Record(0)
|
||||
rect.second = Record(0)
|
||||
first = rect.bind("first",makeRecord)
|
||||
second = rect.bind("second",makeRecord)
|
||||
"##,
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("rect.first.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"7"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("rect.second.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"7"
|
||||
);
|
||||
assert!(!session.is_faulted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binding_tokens_do_not_retain_hidden_targets_and_compute_is_read_only() {
|
||||
let mut session = ReplSession::new(221).unwrap();
|
||||
session
|
||||
.execute(
|
||||
r##"
|
||||
class Model {
|
||||
width: Number
|
||||
function read(self: Model): Number { return self.width }
|
||||
function bad(self: Model): Number {
|
||||
self.width = 999
|
||||
return self.width
|
||||
}
|
||||
}
|
||||
model = Model(80)
|
||||
rect = RectBlock(1,20,0,"#DDEEFF")
|
||||
token = rect.bind("width",model.read)
|
||||
"##,
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
let globals = session.candidate.globals.unwrap();
|
||||
let Value::Object(target) = session
|
||||
.candidate
|
||||
.vm
|
||||
.dict_get(globals, &Value::Text("rect".into()))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("expected Block");
|
||||
};
|
||||
let weak = session
|
||||
.candidate
|
||||
.vm
|
||||
.object_store()
|
||||
.downgrade(target)
|
||||
.unwrap();
|
||||
session
|
||||
.candidate
|
||||
.vm
|
||||
.dict_delete(globals, &Value::Text("rect".into()))
|
||||
.unwrap();
|
||||
session.candidate.vm.collect_cycles();
|
||||
assert!(session.candidate.vm.upgrade(weak).unwrap().is_none());
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("token.isConnected()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"false"
|
||||
);
|
||||
assert!(
|
||||
session
|
||||
.execute(
|
||||
"other = RectBlock(1,20)\nbadToken = other.bind(\"width\",model.bad)",
|
||||
"app.main"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(session.is_faulted());
|
||||
let Value::Object(model) = session
|
||||
.candidate
|
||||
.vm
|
||||
.dict_get(globals, &Value::Text("model".into()))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("expected model");
|
||||
};
|
||||
assert_eq!(
|
||||
session.candidate.vm.get_attr(model, "width").unwrap(),
|
||||
Value::Number(80.into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_method_callbacks_update_two_explicit_bindings() {
|
||||
let mut session = ReplSession::new(21).unwrap();
|
||||
|
||||
+27
-8
@@ -96,16 +96,35 @@ impl NativeCallable for Method {
|
||||
.connection;
|
||||
let connection = cx.upgrade(weak)?;
|
||||
let connected = if let Some(connection) = connection {
|
||||
let mut data = cx
|
||||
if cx
|
||||
.store()
|
||||
.payload::<Connection>(connection, "Connection")?
|
||||
.clone();
|
||||
let connected = data.handler.is_some();
|
||||
if matches!(self, Self::Disconnect) {
|
||||
data.handler = None;
|
||||
cx.replace_payload(connection, data)?;
|
||||
.object(connection)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.is::<crate::binding::Binding>()
|
||||
{
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<crate::binding::Binding>(connection, "Binding")?
|
||||
.clone();
|
||||
let connected = data.compute.is_some();
|
||||
if matches!(self, Self::Disconnect) {
|
||||
data.compute = None;
|
||||
cx.replace_payload(connection, data)?;
|
||||
}
|
||||
connected
|
||||
} else {
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<Connection>(connection, "Connection")?
|
||||
.clone();
|
||||
let connected = data.handler.is_some();
|
||||
if matches!(self, Self::Disconnect) {
|
||||
data.handler = None;
|
||||
cx.replace_payload(connection, data)?;
|
||||
}
|
||||
connected
|
||||
}
|
||||
connected
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod activity;
|
||||
mod api;
|
||||
mod app;
|
||||
mod binding;
|
||||
mod block;
|
||||
mod clipboard;
|
||||
mod developer_tools;
|
||||
|
||||
+10
-1
@@ -123,7 +123,8 @@ impl RenderCache {
|
||||
return Err(VmError::ExecutionLimit("expanded Block graph"));
|
||||
}
|
||||
}
|
||||
let (data_ref, data, raw_dependencies) = block::resolve_tracked(store, block)?;
|
||||
let (data_ref, raw_data, raw_dependencies) = block::resolve_tracked(store, block)?;
|
||||
let data = block::visual_data(store, raw_data)?;
|
||||
let mut dependencies: Vec<_> = raw_dependencies
|
||||
.into_iter()
|
||||
.map(|object| Dependency {
|
||||
@@ -131,6 +132,14 @@ impl RenderCache {
|
||||
property: None,
|
||||
})
|
||||
.collect();
|
||||
if let Some(properties) = data.properties {
|
||||
for (name, _) in block::native_properties(&data) {
|
||||
dependencies.push(Dependency {
|
||||
object: properties,
|
||||
property: Some(name.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !finish {
|
||||
if !path.insert(data_ref) {
|
||||
return Err(VmError::InvalidArgument("cyclic Block composition"));
|
||||
|
||||
+31
-2
@@ -214,6 +214,7 @@ enum Operation {
|
||||
StateSet,
|
||||
Increment,
|
||||
TextOf,
|
||||
Bind,
|
||||
Text,
|
||||
Rect,
|
||||
Spacer,
|
||||
@@ -609,7 +610,7 @@ impl NativeCallable for Function {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
use Operation::*;
|
||||
let (minimum, maximum) = match self.operation {
|
||||
IsInstance | IsSubtype => (2, 2),
|
||||
IsInstance | IsSubtype | Bind => (2, 2),
|
||||
Stats | Viewport | Window | PageWindow | Mounts => (0, 0),
|
||||
State | StateSet => (1, 1),
|
||||
Increment => (0, 0),
|
||||
@@ -967,6 +968,22 @@ impl NativeCallable for Function {
|
||||
)?)));
|
||||
}
|
||||
let owner = self.owner.ok_or(invalid("method has no owner"))?;
|
||||
if matches!(self.operation, Bind) {
|
||||
let field = text(args.first())?;
|
||||
let compute = object(args.get(1))?;
|
||||
return Ok(NativeResult::Return(Value::Object(
|
||||
crate::binding::connect(
|
||||
cx,
|
||||
owner,
|
||||
&field,
|
||||
compute,
|
||||
self.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.master,
|
||||
)?,
|
||||
)));
|
||||
}
|
||||
let (data_ref, data) = block::resolve(cx.store(), owner)?;
|
||||
let mut data = data.clone();
|
||||
let mut result = Value::Nil;
|
||||
@@ -979,12 +996,14 @@ impl NativeCallable for Function {
|
||||
}
|
||||
*value = next;
|
||||
data.text_binding = None;
|
||||
cx.set_attr(owner, "text", args[0].clone())?;
|
||||
}
|
||||
_ => return Err(invalid("setText requires a text Block")),
|
||||
},
|
||||
SetColor => match &mut data.kind {
|
||||
Kind::Text { color: value, .. } | Kind::Rect { color: value, .. } => {
|
||||
*value = color(args.first(), "#242422")?
|
||||
*value = color(args.first(), "#242422")?;
|
||||
cx.set_attr(owner, "color", Value::Text(value.clone()))?;
|
||||
}
|
||||
_ => return Err(invalid("this Block has no color")),
|
||||
},
|
||||
@@ -1638,6 +1657,15 @@ impl UiBridge {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn refresh_bindings(&self, vm: &mut Vm) -> Result<()> {
|
||||
let nodes = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?
|
||||
.nodes
|
||||
.clone();
|
||||
crate::binding::refresh(vm, &nodes)
|
||||
}
|
||||
pub fn prepare_frame(&self, vm: &mut Vm) -> Result<Option<Option<Arc<UiNode>>>> {
|
||||
let changes = vm.take_changes();
|
||||
let mut state = self
|
||||
@@ -2126,6 +2154,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
vm.attach_type(function, function_type)?;
|
||||
}
|
||||
for (type_name, name, operation) in [
|
||||
("Block", "bind", Operation::Bind),
|
||||
("Block", "mounts", Operation::Mounts),
|
||||
("Block", "invalidate", Operation::Invalidate),
|
||||
("Block", "onClick", Operation::OnClick),
|
||||
|
||||
Reference in New Issue
Block a user