Files
figcraft/crates/engine/src/proto_run.rs
T
BFlatandClaude Opus 5.5 c662e56de4 M5: drag to reorder prototype actions; variable mode lookups in expressions (#94)
- Interaction editor: actions (top level and inside conditional blocks) reorder by dragging
  their row's grip (list_drag, now also for lists shown in model order), one proto.action.move
  per drop; the open action stays open where it lands; Escape cancels a row drag without
  deselecting or closing what holds the list. The ... menu keeps Move up / Move down.
- Prototype expressions: `accent[Dark]` reads a variable's value in one mode of its collection
  (Expr::InMode) and `mode(Theme)` is the name of the mode a collection is in where the
  interaction runs (Expr::Mode); parsed, type-checked, displayed, stored by id (names accepted in
  JSON), evaluated with the layer's modes. REST import maps VAR_MODE_LOOKUP over a variable and
  one of its modes.
- Overlays opened through commands close on a click outside unless told not to, as in the editor.
- Collection::find_mode / current_mode replace repeated lookups.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:21:53 +07:00

150 lines
6.5 KiB
Rust

//! Prototype actions run by the prototype player on its own copy of the document: set variable (a
//! value or an expression), set variable mode, choosing the branch of a conditional action, and
//! where navigating to a section goes, and the hotspots a screen offers.
use std::collections::HashMap;
use figcraft_doc::proto::{Action, ConditionalBlock, Expr};
use figcraft_doc::{Document, NodeId, NodeKind, VariableType, VariableValue};
use figcraft_geom::Rect;
use serde_json::Value;
use crate::cmd::styles::apply_bindings;
use crate::params::{color_of, f64_of};
/// A JSON value as a value of a `kind` variable (`None` when it doesn't fit).
pub fn literal(kind: VariableType, v: &Value) -> Option<VariableValue> {
Some(match kind {
VariableType::Color => VariableValue::Color(color_of(v)?),
VariableType::Number => VariableValue::Number(f64_of(v).filter(|n| n.is_finite())?),
VariableType::Boolean => VariableValue::Boolean(match v {
Value::Bool(b) => *b,
Value::String(s) => s == "true",
Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
_ => return None,
}),
VariableType::String => VariableValue::String(match v {
Value::String(s) => s.clone(),
Value::Bool(_) | Value::Number(_) => v.to_string(),
_ => return None,
}),
})
}
/// An expression result as a value of a `kind` variable: numbers and booleans become text for
/// string variables; other mismatches don't fit.
fn fit(kind: VariableType, v: VariableValue) -> Option<VariableValue> {
match (kind, v) {
(VariableType::String, v @ (VariableValue::Number(_) | VariableValue::Boolean(_))) => Some(VariableValue::String(v.display())),
(k, v) if v.type_of() == Some(k) => Some(v),
_ => None,
}
}
/// Set `variable` to `value`, or to `expr` evaluated in the modes of `node` (the layer whose
/// interaction runs), in every mode, and re-apply bindings. False when nothing could be set.
pub fn set_variable(doc: &mut Document, node: NodeId, variable: &str, value: &Value, expr: Option<&Expr>) -> bool {
let Some(var) = doc.variables.get(variable) else { return false };
let (id, kind) = (var.id.clone(), var.kind);
let v = match expr {
Some(e) => e.eval(&doc.variables, &doc.modes_for(node)).and_then(|v| fit(kind, v)),
None => literal(kind, value),
};
let Some(v) = v else { return false };
let Some(slot) = doc.variables.variables.iter_mut().find(|x| x.id == id) else { return false };
for val in slot.values.values_mut() {
*val = v.clone();
}
apply_bindings(doc);
true
}
/// Switch `collection` to `mode` (ids or names) for the prototype `frame` is in: on its page, and
/// on the page's top-level frames that chose another mode of it (modes chosen deeper inside still
/// win), then re-apply bindings. False for an unknown collection or mode.
pub fn set_mode(doc: &mut Document, frame: NodeId, collection: &str, mode: &str) -> bool {
let Some(c) = doc.variables.collection(collection) else { return false };
let Some(mode) = c.find_mode(mode).map(|m| m.id.clone()) else {
return false;
};
let cid = c.id.clone();
let Some(page) = doc.page_of(frame) else { return false };
let mut targets: Vec<NodeId> = doc
.node(page)
.map(|p| p.children.iter().copied().filter(|t| doc.node(*t).is_some_and(|n| n.var_modes.contains_key(&cid))).collect())
.unwrap_or_default();
targets.push(page);
for id in targets {
if let Some(n) = doc.node_mut(id) {
n.var_modes.insert(cid.clone(), mode.clone());
}
}
apply_bindings(doc);
true
}
/// The actions of the branch of a conditional action that runs, with variables resolved in the
/// modes of `node`.
pub fn branch(doc: &Document, node: NodeId, blocks: &[ConditionalBlock]) -> Vec<Action> {
ConditionalBlock::choose(blocks, &doc.variables, &doc.modes_for(node)).map(<[Action]>::to_vec).unwrap_or_default()
}
/// The frame "Navigate to" `dest` shows: the top-level frame holding it; for a section, the frame
/// in it shown last (`visited`: section → frame, see [`remember_sections`]), else its first frame
/// in reading order. `None` when there's nothing to show.
pub fn navigate_target(doc: &Document, dest: NodeId, visited: &HashMap<NodeId, NodeId>) -> Option<NodeId> {
let n = doc.node(dest)?;
if !matches!(n.kind, NodeKind::Section { .. }) {
return Some(doc.top_level_frame(dest).unwrap_or(dest));
}
visited.get(&dest).copied().filter(|f| doc.contains(*f) && doc.is_ancestor(dest, *f)).or_else(|| doc.frames_in(dest).first().copied())
}
/// Record `frame` as the frame shown last in each section around it.
pub fn remember_sections(doc: &Document, frame: NodeId, visited: &mut HashMap<NodeId, NodeId>) {
for a in doc.ancestors(frame) {
if doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. })) {
visited.insert(a, frame);
}
}
}
/// The hotspots of the screen `root` (a presented frame or overlay): its visible layers with
/// interactions, bottom-most first, with their bounds on the page clipped by the frames around
/// them that clip content (the presenter flashes them after a click where nothing reacts).
pub fn hotspots(doc: &Document, root: NodeId) -> Vec<(NodeId, Rect)> {
let mut out = Vec::new();
// Each visible layer's clip: its bounds cut by the clipping frames around it (inside `root`).
let mut clips: HashMap<NodeId, Option<Rect>> = HashMap::new();
for id in doc.subtree(root) {
let Some(n) = doc.node(id) else { continue };
let parent_clip = match n.parent.filter(|_| id != root) {
Some(p) => match clips.get(&p) {
Some(c) => *c,
// The parent is hidden.
None => continue,
},
None => None,
};
if !n.visible {
continue;
}
let bounds = doc.world_bounds(id);
let own = match (parent_clip, bounds) {
(Some(c), Some(b)) if n.clip && n.kind.is_frame_like() => Some(c.intersect(b)),
(None, Some(b)) if n.clip && n.kind.is_frame_like() => Some(b),
(c, _) => c,
};
clips.insert(id, own);
if n.interactions.is_empty() {
continue;
}
let Some(b) = bounds else { continue };
let r = parent_clip.map_or(b, |c| c.intersect(b));
if r.width() > 0.0 && r.height() > 0.0 {
out.push((id, r));
}
}
out
}