Thing 2.0 bind: an Image's catalog entry is one more bind site; Measure reads the bound extent
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 1m55s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 2m31s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 07:27:38 +01:00
commit dd0e61d8ec
10 changed files with 121 additions and 39 deletions

View file

@ -72,6 +72,6 @@ pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
format!("thing:result:{invocation_id}.{}", seq.get())
}
pub(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
pub fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
}

View file

@ -27,7 +27,7 @@ mod style;
pub use asset::*;
pub use command::*;
pub use domain::{Count, DomainError, Segment, Seq, Version};
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId};
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key};
pub use node::*;
pub use result::*;
pub use source::*;

View file

@ -12,7 +12,7 @@ mod walk;
use std::collections::{BTreeMap, HashMap, HashSet};
use thing_contract::{NodeId, SelectOption};
use thing_contract::{AssetEntry, NodeId, SelectOption};
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, Change, Interest, Ledger, StatePort};
@ -34,6 +34,7 @@ pub enum Field {
Selected,
Options,
Series,
Asset,
}
impl Field {
@ -51,6 +52,7 @@ impl Field {
Field::Selected => "selected",
Field::Options => "options",
Field::Series => "series",
Field::Asset => "asset",
}
}
}
@ -70,6 +72,8 @@ pub enum Bound {
Bool(bool),
Series(Vec<f64>),
Options(Vec<SelectOption>),
/// The catalog entry an Image names.
Asset(AssetEntry),
/// The record or the member is not there (or is nil).
Absent,
Error(BindError),

View file

@ -50,6 +50,7 @@ enum Site<'n> {
Number(&'n NumberSource),
Bind(&'n Bind, Want),
Options(&'n OptionList),
Asset(&'n ImageNode),
}
fn kind(value: &StateValue) -> &'static str {
@ -160,7 +161,10 @@ fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
}
match node {
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
Node::Image(n) => found.push((Field::Alt, Site::Text(&n.alt))),
Node::Image(n) => {
found.push((Field::Alt, Site::Text(&n.alt)));
found.push((Field::Asset, Site::Asset(n)));
}
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
@ -301,6 +305,7 @@ impl<'a> Walker<'a> {
Site::Bind(bind, want) => self.bind(bind, want, item),
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
Site::Asset(image) => self.asset(image),
}
}
@ -349,6 +354,33 @@ impl<'a> Walker<'a> {
})
}
/// The catalog entry an Image names: the catalog record is one more interest of the Image.
fn asset(&mut self, image: &ImageNode) -> Bound {
let Ok(catalog) = Segment::new(image.catalog.as_str()) else {
return Bound::Error(fault(Code::AssetMissing, "catalog id is not one segment"));
};
let address = Address {
provider: self.provider.clone(),
schema: SchemaId::new(AssetCatalog::SCHEMA_NAME),
key: RecordKey::new(asset_catalog_key(self.provider, &catalog)),
};
self.part.interests.insert(Interest::Record(address.clone()));
match self.port.read(&address) {
Lookup::Present(Entry { record: Record::Catalog(held), .. }) => {
match held.assets.into_iter().find(|entry| entry.id == image.asset) {
Some(entry) => Bound::Asset(entry),
None => Bound::Error(fault(Code::AssetMissing, format!("no asset {} in the catalog", image.asset))),
}
}
Lookup::Present(_) => Bound::Error(fault(
Code::BindSchemaMismatch,
format!("the record is not held under {}", AssetCatalog::SCHEMA_NAME),
)),
Lookup::Absent => Bound::Absent,
Lookup::Refused(refusal) => Bound::Error(fault(Code::DecodeRefused, refusal.detail)),
}
}
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
let entries = match self.collection(&bound.collection, item) {
Ok(entries) => entries,

View file

@ -27,6 +27,8 @@ pub enum Code {
TooDeepToResolve,
/// A state record held under another schema than the Bind names.
BindSchemaMismatch,
/// An Image names a catalog or an asset the catalog does not hold.
AssetMissing,
/// A member path names a member the value does not have.
BindMemberMissing,
/// A value of another type than its site takes; no value is coerced.

View file

@ -31,7 +31,7 @@ pub enum Leaf<'a> {
Toggle { node: &'a NodeId },
Slider { node: &'a NodeId },
Select { node: &'a NodeId, selected: &'a Bound },
Image { node: &'a NodeId, catalog: &'a str, asset: &'a str },
Image { node: &'a NodeId, asset: &'a Bound },
Plot { node: &'a NodeId },
}

View file

@ -270,7 +270,7 @@ impl<'a> Builder<'a, '_> {
}
Node::Image(n) => {
if !self.hidden(&n.common.id) {
let leaf = Leaf::Image { node: &n.common.id, catalog: &n.catalog, asset: &n.asset };
let leaf = Leaf::Image { node: &n.common.id, asset: self.value(&n.common.id, Field::Asset) };
self.leaf(&n.common.id, parent, leaf, out);
}
}

View file

@ -80,6 +80,7 @@ fn show(bound: &Bound) -> String {
Bound::Options(options) => {
format!("options [{}]", options.iter().map(|o| format!("{}={}", o.value, o.label)).collect::<Vec<_>>().join(", "))
}
Bound::Asset(entry) => format!("asset {} {}x{}", entry.id, entry.width.get(), entry.height.get()),
Bound::Absent => "absent".to_string(),
Bound::Error(error) => format!("error {:?}", error.code),
}
@ -1031,3 +1032,58 @@ fn a_listed_record_of_another_schema_is_refused_in_place() {
assert_eq!(code(value(bound, "minds!6:mind-9/mind-name", Field::Content)), Code::BindSchemaMismatch);
assert_eq!(applied.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::BindSchemaMismatch]);
}
fn picture(catalog: &str, asset: &str) -> Node {
Node::Image(ImageNode { common: common("pic"), catalog: catalog.into(), asset: asset.into(), fit: ImageFit::Contain, alt: lit_text("alt") })
}
fn icons(width: i32, assets: &[&str]) -> AssetCatalog {
let entry = |id: &str| AssetEntry {
id: id.into(),
media_type: "image/png".into(),
uri: format!("asset://{id}"),
width: count(width),
height: count(width / 2),
};
AssetCatalog { provider_id: ProviderId::new(SWARM), catalog_id: seg("icons"), version: ver(1), assets: assets.iter().map(|id| entry(id)).collect() }
}
#[test]
fn an_image_binds_its_catalog_entry_and_a_republish_dirties_it() {
let mut state = MemState::new();
state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
let mut rig = Rig::new(state);
let document = page("pictures", vec![picture("icons", "logo")]);
assert_eq!(rig.bind(&document).diagnostics, vec![]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 64x32");
rig.settle();
rig.state.put(&ProviderId::new(SWARM), &icons(128, &["logo"]));
let applied = rig.settle();
assert_eq!(nodes(&applied, &document), ["pic"]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 128x64");
}
#[test]
fn an_image_whose_catalog_is_not_published_is_absent_until_it_is() {
let mut rig = Rig::new(MemState::new());
let document = page("pictures", vec![picture("icons", "logo")]);
assert_eq!(rig.bind(&document).diagnostics, vec![]);
assert_eq!(value(rig.tree(&document), "pic", Field::Asset), &Bound::Absent);
rig.settle();
rig.state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
assert_eq!(nodes(&rig.settle(), &document), ["pic"]);
assert_eq!(show(value(rig.tree(&document), "pic", Field::Asset)), "asset logo 64x32");
}
#[test]
fn an_image_naming_what_the_catalog_lacks_or_a_bad_catalog_id_is_asset_missing() {
let mut state = MemState::new();
state.put(&ProviderId::new(SWARM), &icons(64, &["logo"]));
let mut rig = Rig::new(state);
let document = page("pictures", vec![picture("icons", "other")]);
rig.bind(&document);
assert_eq!(code(value(rig.tree(&document), "pic", Field::Asset)), Code::AssetMissing);
let bad = page("bad", vec![picture("a.b", "logo")]);
rig.bind(&bad);
assert_eq!(code(value(rig.tree(&bad), "pic", Field::Asset)), Code::AssetMissing);
}

View file

@ -92,8 +92,8 @@ fn laid_fixture(fixture: Fixture, frame: &LayoutFrame) -> Vec<(String, Result<La
.map(|document| {
let laid = bind(&mut state, document).map(|tree| {
let mut measure = match frame.metrics {
Metrics::Pixels => FixedMeasure::pixels(&set.catalogs),
Metrics::Cells => FixedMeasure::cells(&set.catalogs),
Metrics::Pixels => FixedMeasure::pixels(),
Metrics::Cells => FixedMeasure::cells(),
};
layout(&tree, frame, &mut measure).unwrap()
});
@ -245,7 +245,7 @@ fn surface_of(root: Node) -> SurfaceDocument {
fn lay_with(state: &mut MemState, root: Node, frame: &LayoutFrame) -> LaidTree {
let tree = bind(state, &surface_of(root)).expect("resolves");
layout(&tree, frame, &mut FixedMeasure::pixels(&[])).unwrap()
layout(&tree, frame, &mut FixedMeasure::pixels()).unwrap()
}
fn lay(root: Node, w: f32, h: f32) -> LaidTree {
@ -628,7 +628,7 @@ fn image_measures_through_the_measure() {
// Stretched across the column, the image keeps its two-to-one shape.
assert_eq!(rect(&laid, "pic"), (0.0, 0.0, 200.0, 100.0));
// With no extent known, an Image is 0x0.
let none = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])).unwrap();
let none = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels()).unwrap();
assert_eq!(rect(&none, "pic").2 + rect(&none, "pic").3, 200.0);
}
@ -718,7 +718,7 @@ fn deep_limits() -> Limits {
fn run_default_thread(tree: &BoundTree) -> LaidTree {
std::thread::scope(|scope| {
scope
.spawn(|| layout(tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])).unwrap())
.spawn(|| layout(tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels()).unwrap())
.join()
.expect("layout stays inside a default thread stack")
})
@ -930,7 +930,7 @@ fn random_styles_never_panic() {
]);
let scale = [1.0, 1.5, 2.0][round % 3];
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
let Ok(laid) = layout(&tree, &pixels(800.0, 600.0, scale), &mut FixedMeasure::pixels(&[])) else { continue };
let Ok(laid) = layout(&tree, &pixels(800.0, 600.0, scale), &mut FixedMeasure::pixels()) else { continue };
assert!(laid.nodes.iter().all(|n| [n.rect.x, n.rect.y, n.rect.w, n.rect.h].iter().chain(n.max_scroll.iter().flat_map(|m| [&m.0, &m.1])).all(|v| v.is_finite())));
}
}
@ -938,7 +938,7 @@ fn random_styles_never_panic() {
#[test]
fn bad_frames_are_refused() {
let tree = bind(&mut MemState::new(), &surface_of(bx("root", plain(), vec![]))).unwrap();
let run = |frame: LayoutFrame| layout(&tree, &frame, &mut FixedMeasure::pixels(&[])).map(|laid| laid.nodes.len());
let run = |frame: LayoutFrame| layout(&tree, &frame, &mut FixedMeasure::pixels()).map(|laid| laid.nodes.len());
for scale in [f32::NAN, f32::INFINITY, 0.0, -1.0, 2048.0] {
assert_eq!(run(pixels(800.0, 600.0, scale)), Err(LayoutError::Frame(FrameError::Scale)), "scale {scale}");
}
@ -966,7 +966,7 @@ fn large_siblings_on_one_axis_are_exact_or_refused() {
for root_style in [plain(), sized(800.0, 600.0)] {
let root = bx("root", BoxStyle { direction: direction.clone(), ..root_style }, kids.clone());
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
match layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])) {
match layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels()) {
Ok(laid) => {
exact += 1;
for (id, w, h) in [("fixed", 30.0, 20.0)] {
@ -991,7 +991,7 @@ fn large_siblings_on_one_axis_are_exact_or_refused() {
fn each_edge_of_the_precision_bound_refuses() {
let refused = |root: Node| {
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
matches!(layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])), Err(LayoutError::OutOfRange(_)))
matches!(layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels()), Err(LayoutError::OutOfRange(_)))
};
let column = BoxStyle { direction: Direction::Column, ..plain() };
// The bottom edge alone is past the bound: the top is not.
@ -1187,7 +1187,7 @@ fn a_scroll_extent_past_the_bound_refuses_though_every_rect_is_in_range() {
};
let run = |overflow: Overflow| {
let tree = bind(&mut MemState::new(), &surface_of(tree(overflow))).unwrap();
layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[]))
layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels())
};
assert!(run(Overflow::Visible).is_ok(), "the same boxes without a scroll lay out, horizontal {horizontal}");
match run(Overflow::Scroll) {
@ -1204,7 +1204,7 @@ fn overlays_hold_the_bound() {
let wrap = BoxStyle { direction: Direction::Column, align_self: ItemAlign::Start, ..plain() };
let root = bx("root", plain(), vec![overlay("pop", Anchor::Viewport, vec![bx("wrap", wrap, vec![embed("a", 10.0, 16.0), embed("b", 10.0, tall)])])]);
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[]))
layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels())
};
assert!(stack(1000.0).is_ok());
match stack(2_097_152.0) {

View file

@ -1,37 +1,22 @@
//! A layout oracle, not a text engine: every size is a fixed function of the leaf, so layout
//! goldens never move when a real text measure changes.
use std::collections::HashMap;
use thing_contract::AssetCatalog;
use thing_core::bind::Bound;
use thing_core::layout::{Avail, Constraint, Leaf, Measure};
/// Text is 8 px wide per character and 16 px tall per line (one cell each in Cells); controls
/// have fixed sizes; an Image is its catalog entry's extent (0x0 when missing); a Plot is 0x0.
/// have fixed sizes; an Image is its bound catalog entry's extent (0x0 when missing); a Plot is 0x0.
pub struct FixedMeasure {
cells: bool,
extents: HashMap<(String, String), (f32, f32)>,
}
impl FixedMeasure {
pub fn pixels(catalogs: &[AssetCatalog]) -> Self {
Self::new(false, catalogs)
pub fn pixels() -> Self {
Self { cells: false }
}
pub fn cells(catalogs: &[AssetCatalog]) -> Self {
Self::new(true, catalogs)
}
fn new(cells: bool, catalogs: &[AssetCatalog]) -> Self {
let mut extents = HashMap::new();
for catalog in catalogs {
for asset in &catalog.assets {
let key = (catalog.catalog_id.as_str().to_string(), asset.id.clone());
extents.insert(key, (asset.width.get() as f32, asset.height.get() as f32));
}
}
Self { cells, extents }
pub fn cells() -> Self {
Self { cells: true }
}
fn text(&self, content: &Bound, wrap: bool, max_lines: Option<u32>, c: &Constraint) -> (f32, f32) {
@ -68,8 +53,11 @@ impl Measure for FixedMeasure {
Leaf::Toggle { .. } => control(40.0, 20.0),
Leaf::Slider { .. } => control(160.0, 20.0),
Leaf::Select { .. } => control(160.0, 24.0),
Leaf::Image { catalog, asset, .. } => {
let (w, h) = self.extents.get(&(catalog.to_string(), asset.to_string())).copied().unwrap_or((0.0, 0.0));
Leaf::Image { asset, .. } => {
let (w, h) = match asset {
Bound::Asset(entry) => (entry.width.get() as f32, entry.height.get() as f32),
_ => (0.0, 0.0),
};
if self.cells { (w / 8.0, (h / 16.0).ceil()) } else { (w, h) }
}
Leaf::Plot { .. } => (0.0, 0.0),