mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 09:28:09 +00:00
Merge main into feat/dataset-import-graph-columns
This commit is contained in:
@@ -246,39 +246,92 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"name": name, "kind": kind.label()}))
|
||||
}
|
||||
|
||||
/// Whether the object `id`, bound to the variable `name`, can stay bound to it once the variable
|
||||
/// is of `kind`: a text variable drives type that holds no other text variable, an image variable
|
||||
/// drives an image object, a graph variable drives a graph root, and a visibility variable drives
|
||||
/// any object. Locks and hidden layers don't count, as they don't unbind anything else either.
|
||||
fn keeps_binding(doc: &Document, id: NodeId, name: &str, kind: VariableKind) -> bool {
|
||||
let Some(n) = doc.node(id) else { return false };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
matches!(n.kind, NodeKind::Text(_))
|
||||
&& !doc.variables.bindings.get(&id).is_some_and(|bound| {
|
||||
doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && v.name != name && bound.contains(&v.name))
|
||||
})
|
||||
}
|
||||
VariableKind::Visibility => true,
|
||||
VariableKind::Image => matches!(n.kind, NodeKind::Image(_)),
|
||||
VariableKind::Graph => n.extras().graph.is_some(),
|
||||
VariableKind::Unknown => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Variable Options: rename a variable (`newName`), change its kind (`kind`), or both, in one undo
|
||||
/// step, carrying its bindings and its values in every data set to the new name. A kind change
|
||||
/// unbinds the objects that can't hold the new kind ([`keeps_binding`]) and drops the variable's
|
||||
/// value in every data set. A call that changes nothing adds no undo step.
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.rename";
|
||||
let from = var_name(p, C)?;
|
||||
let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?;
|
||||
let st = s.doc()?;
|
||||
if st.doc.variables.variable(&from).is_none() {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
// An omitted key is no change; a null, like any other value that isn't a name or a kind, is refused.
|
||||
let to = match p.get("newName") {
|
||||
None => None,
|
||||
Some(v) => Some(named(v.as_str(), "newName", C)?),
|
||||
};
|
||||
let kind = match p.get("kind") {
|
||||
None => None,
|
||||
Some(v) => Some(v.as_str().and_then(VariableKind::parse).ok_or_else(|| bad(C, "`kind` must be `text`, `visibility`, `image` or `graph`"))?),
|
||||
};
|
||||
if to.is_none() && kind.is_none() {
|
||||
return Err(bad(C, "missing `newName` or `kind`"));
|
||||
}
|
||||
if st.doc.variables.variable(&to).is_some() {
|
||||
let doc = &s.doc()?.doc;
|
||||
let Some(old) = doc.variables.variable(&from) else {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
};
|
||||
let to = to.unwrap_or_else(|| from.clone());
|
||||
if to != from && doc.variables.variable(&to).is_some() {
|
||||
return Err(bad(C, format!("variable `{to}` already exists")));
|
||||
}
|
||||
s.edit("Rename Variable", |d, _| {
|
||||
let v = d.variables.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
let kind = kind.unwrap_or(old.kind);
|
||||
let retyped = kind != old.kind;
|
||||
let unbound: Vec<NodeId> =
|
||||
if retyped { doc.variables.objects_of(&from).into_iter().filter(|id| !keeps_binding(doc, *id, &from, kind)).collect() } else { Vec::new() };
|
||||
let label = if retyped { "Variable Options" } else { "Rename Variable" };
|
||||
let dropped = edit_variables(s, label, |vars| {
|
||||
let v = vars.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
v.name = to.clone();
|
||||
for bound in d.variables.bindings.values_mut() {
|
||||
v.kind = kind;
|
||||
for id in &unbound {
|
||||
vars.unbind(*id, &from);
|
||||
}
|
||||
for bound in vars.bindings.values_mut() {
|
||||
if bound.remove(&from) {
|
||||
bound.insert(to.clone());
|
||||
}
|
||||
}
|
||||
for ds in &mut d.variables.datasets {
|
||||
if let Some(value) = ds.values.remove(&from) {
|
||||
ds.values.insert(to.clone(), value);
|
||||
let mut dropped = 0;
|
||||
for ds in &mut vars.datasets {
|
||||
match ds.values.remove(&from) {
|
||||
// A rename alone carries every value, one that doesn't fit the kind included; a kind
|
||||
// change drops them all, as none was given for the new kind.
|
||||
Some(value) if !retyped => {
|
||||
ds.values.insert(to.clone(), value);
|
||||
}
|
||||
Some(_) => dropped += 1,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(dropped)
|
||||
})?;
|
||||
// The highlight names a variable, so it follows the rename rather than going stale.
|
||||
// The highlight names a variable, so it follows the rename rather than going stale. A call
|
||||
// that leaves the name as it was leaves the revision alone too.
|
||||
let st = s.doc_mut()?;
|
||||
if st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
if to != from && st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
st.variables_highlight = Some(to.clone());
|
||||
st.revision += 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(json!({"from": from, "name": to}))
|
||||
Ok(json!({"from": from, "name": to, "kind": kind.label(), "unbound": unbound.iter().map(|i| i.0).collect::<Vec<_>>(), "droppedValues": dropped}))
|
||||
}
|
||||
|
||||
/// Make Text / Visibility / Image / Graph Dynamic: define a variable of that kind and bind the
|
||||
@@ -331,18 +384,19 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let xml_id = s.prefs.identify_objects_by == "xmlId";
|
||||
let st = s.doc()?;
|
||||
let variables: Vec<Value> = st
|
||||
.doc
|
||||
.variables
|
||||
.variables
|
||||
.iter()
|
||||
let vars = &st.doc.variables.variables;
|
||||
let variables: Vec<Value> = variable_order(st, xml_id)
|
||||
.into_iter()
|
||||
.filter_map(|i| vars.get(i))
|
||||
.map(|v| {
|
||||
let bindings = st.doc.variables.objects_of(&v.name).len();
|
||||
json!({"name": v.name, "kind": v.kind.label(), "bindings": bindings})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"variables": variables, "locked": st.doc.variables.locked}))
|
||||
let sort = json!({"by": st.variables_sort.by.id(), "descending": st.variables_sort.descending});
|
||||
Ok(json!({"variables": variables, "locked": st.doc.variables.locked, "sort": sort}))
|
||||
}
|
||||
|
||||
/// Lock Variables: without `locked` it toggles. Setting the state the document already has
|
||||
@@ -418,6 +472,120 @@ fn highlight(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"variable": name}))
|
||||
}
|
||||
|
||||
/// The column the Variables panel sorts its list by (`variable.sort`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum VariableSortKey {
|
||||
/// The order the variables were defined in.
|
||||
#[default]
|
||||
Defined,
|
||||
/// The Variables column: the variable's name.
|
||||
Name,
|
||||
/// The Objects column: the name of the object the variable is bound to.
|
||||
Object,
|
||||
/// The type column: text, image, graph, visibility, then variables of unknown kind.
|
||||
Type,
|
||||
}
|
||||
|
||||
impl VariableSortKey {
|
||||
/// The values `variable.sort` takes for `by`, in the order of [`Self::id`].
|
||||
const IDS: [&'static str; 4] = ["name", "object", "type", "none"];
|
||||
|
||||
/// The value `variable.sort` takes for `by` and `variable.list` reports.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Name => "name",
|
||||
Self::Object => "object",
|
||||
Self::Type => "type",
|
||||
Self::Defined => "none",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"name" => Some(Self::Name),
|
||||
"object" => Some(Self::Object),
|
||||
"type" => Some(Self::Type),
|
||||
"none" => Some(Self::Defined),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the Variables panel orders its list: a column, and whether the order is reversed. Panel
|
||||
/// state, not saved and not an undo step.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct VariableSort {
|
||||
pub by: VariableSortKey,
|
||||
pub descending: bool,
|
||||
}
|
||||
|
||||
/// The place of a variable's kind in the order the type column sorts by.
|
||||
fn kind_rank(kind: VariableKind) -> u8 {
|
||||
match kind {
|
||||
VariableKind::Text => 0,
|
||||
VariableKind::Image => 1,
|
||||
VariableKind::Graph => 2,
|
||||
VariableKind::Visibility => 3,
|
||||
VariableKind::Unknown => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Variables panel's rows in its sort order, as indices into the document's variables.
|
||||
/// Names compare without regard to case. Sorted by object, a variable bound to nothing comes
|
||||
/// first and one bound to several objects comes after those bound to one; `xml_id` names objects
|
||||
/// by their XML ids, as the panel does with Identify Objects By set to XML ID. Ties go by name.
|
||||
pub fn variable_order(st: &crate::DocState, xml_id: bool) -> Vec<usize> {
|
||||
let vars = &st.doc.variables.variables;
|
||||
let sort = st.variables_sort;
|
||||
let mut order: Vec<usize> = (0..vars.len()).collect();
|
||||
if sort.by != VariableSortKey::Defined {
|
||||
order.sort_by_cached_key(|&i| {
|
||||
let v = &vars[i];
|
||||
let (rank, label) = match sort.by {
|
||||
VariableSortKey::Object => match st.doc.variables.objects_of(&v.name).as_slice() {
|
||||
[] => (0, String::new()),
|
||||
[one] => (1, st.doc.node(*one).map(|n| n.identify_label(xml_id)).unwrap_or_default()),
|
||||
_ => (2, String::new()),
|
||||
},
|
||||
VariableSortKey::Type => (kind_rank(v.kind), String::new()),
|
||||
VariableSortKey::Name | VariableSortKey::Defined => (0, String::new()),
|
||||
};
|
||||
(rank, label.to_lowercase(), label, v.name.to_lowercase(), v.name.clone())
|
||||
});
|
||||
}
|
||||
if sort.descending {
|
||||
order.reverse();
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// Sort the Variables panel's list. Panel state, like `variable.highlight`: not saved and not an
|
||||
/// undo step. Setting the order the panel already has changes nothing.
|
||||
fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.sort";
|
||||
let key = "by";
|
||||
let by = match p.get(key) {
|
||||
None => return Err(bad(C, format!("missing `{key}`"))),
|
||||
Some(v) => v
|
||||
.as_str()
|
||||
.and_then(VariableSortKey::parse)
|
||||
.ok_or_else(|| bad(C, format!("`{key}` must be one of {}", VariableSortKey::IDS.join(", "))))?,
|
||||
};
|
||||
// A `descending` that is given must be true or false: null is refused, not read as omitted.
|
||||
let key = "descending";
|
||||
let descending = match p.get(key) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(C, format!("`{key}` must be true or false")))?,
|
||||
};
|
||||
let sort = VariableSort { by, descending };
|
||||
let st = s.doc_mut()?;
|
||||
if st.variables_sort != sort {
|
||||
st.variables_sort = sort;
|
||||
st.revision += 1;
|
||||
}
|
||||
Ok(json!({"by": by.id(), "descending": descending}))
|
||||
}
|
||||
|
||||
fn dataset_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.new";
|
||||
let name = var_name(p, C)?;
|
||||
@@ -723,11 +891,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rename Variable",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{name, newName} rename a variable, with its bindings and its values in every dataset; refused while the variables are locked",
|
||||
"{name, newName?, kind?: text|visibility|image|graph} Variable Options: rename a variable, with its bindings and its values in every dataset, change its kind, or both, in one undo step (none when the name and the kind are the ones it has). A kind change unbinds every object that can't hold the new kind (a text variable keeps type that has no other text variable, an image variable keeps image objects, a graph variable keeps graph roots, a visibility variable keeps every object) and drops the variable's values in every dataset; locked and hidden objects keep their binding when they can hold it. Needs `newName` or `kind`, and a null or empty one is refused; refused while the variables are locked → {from, name, kind, unbound: [id…], droppedValues}",
|
||||
variables_unlocked,
|
||||
rename
|
||||
),
|
||||
cmd!(query "variable.list", "List Variables", [], None, "{} → variables with kinds and binding counts, and whether they are locked → {variables, locked}", has_doc, list),
|
||||
cmd!(
|
||||
query "variable.list",
|
||||
"List Variables",
|
||||
[],
|
||||
None,
|
||||
"{} → variables with kinds and binding counts in the Variables panel's order, whether they are locked, and the panel's sort (as variable.sort sets it) → {variables, locked, sort: {by, descending}}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"variable.makeTextDynamic",
|
||||
"Make Text Dynamic",
|
||||
@@ -800,6 +976,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
highlight
|
||||
),
|
||||
cmd!(
|
||||
"variable.sort",
|
||||
"Sort Variables",
|
||||
[],
|
||||
None,
|
||||
"{by: name|object|type|none, descending?: bool} sort the Variables panel's list (a click on a column header) by variable name, by the name of the bound object, or by type (text, image, graph, visibility, then unknown); `none` is the order the variables were defined in, and `descending` reverses the order. Names compare without regard to case; by object, unbound variables come first and variables bound to several objects last, and ties go by name. Panel state: not saved and not an undo step; variable.list reports it → {by, descending}",
|
||||
has_doc,
|
||||
sort
|
||||
),
|
||||
cmd!("dataset.new", "New Data Set…", ["Window", "Variables"], None, "{name, values?: {variable: value}} add a dataset", has_doc, dataset_new),
|
||||
cmd!(
|
||||
"dataset.set",
|
||||
|
||||
Reference in New Issue
Block a user