Browser: hidden items grey out, and folders keep their own visibility (#2308)

Thanks @N3MI-DG.
This commit is contained in:
N3MI-DG
2026-10-19 02:34:55 +11:00
committed by GitHub
parent a0610a6329
commit 3eeb20d2bd
18 changed files with 412 additions and 120 deletions
+116 -1
View File
@@ -40,7 +40,9 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("browser.visibility", "Show/Hide", visibility).icon("eye").noundo().params(
"visible: bool; items?: [sketch id or name | body name | construction name | joint name | O|X|Y|Z|XY|XZ|YZ]; \
or joints?: [joint id or name] (their glyphs; they still constrain and move parts); \
or folder?: bodies|sketches|construction|origin|joints (all of it); or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (requires paths and visible:true). Saved with the design; not an undo step",
or folder?: bodies|sketches|construction|origin|joints (all of it; showing also shows its browser folders and groups); \
or tree_folders?: [browser folder or group key: c0/bodies, o:4/sketches, c0/g7, c0/joints, c0/canvases] (the folder or group itself: its items keep their own state); \
or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (requires paths and visible:true). Saved with the design; not an undo step",
),
];
@@ -197,9 +199,46 @@ fn shown_item(s: &Session, key: &str) -> Option<Shown> {
ORIGIN.iter().find(|o| o.eq_ignore_ascii_case(key)).map(|o| Shown::Origin(o.to_string()))
}
/// A browser folder or group key (`Visibility::hidden_folders`): `c0` or `o:<ids>`, then
/// `/bodies`, `/sketches`, `/construction`, `/joints`, `/canvases` or `/g<group id>`.
fn tree_folder_key(k: &str) -> bool {
let Some((scope, last)) = k.rsplit_once('/') else { return false };
let scope_ok =
scope == "c0" || scope.strip_prefix("o:").is_some_and(|ids| ids.split('/').count() <= 64 && ids.split('/').all(|i| i.parse::<u64>().is_ok()));
let last_ok =
FOLDERS.contains(&last) || ["joints", "canvases"].contains(&last) || last.strip_prefix('g').is_some_and(|g| g.parse::<u64>().is_ok());
k.len() <= 2048 && scope_ok && last_ok
}
fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "browser.visibility";
let visible = bool_(p, "visible").ok_or_else(|| bad(cmd, "`visible` must be true or false"))?;
if let Some(value) = p.get("tree_folders") {
if ["items", "folder", "joints", "paths"].iter().any(|k| p.get(*k).is_some()) {
return Err(bad(cmd, "give `tree_folders`, `items`, `folder`, `joints` or `paths`, not several"));
}
let keys = value
.as_array()
.filter(|a| !a.is_empty() && a.len() <= 10_000)
.ok_or_else(|| bad(cmd, "`tree_folders` must list 1..10000 browser folder or group keys"))?;
// Every key is checked before anything changes.
let keys: Vec<String> = keys
.iter()
.map(|k| {
k.as_str().filter(|k| tree_folder_key(k)).map(str::to_string).ok_or_else(|| {
bad(cmd, "a browser folder or group key is `<c0 | o:ids>/<folder | g<group id>>`, such as `c0/bodies` or `o:4/g7`")
})
})
.collect::<Result<_>>()?;
for k in &keys {
s.visibility.hidden_folders.retain(|h| h != k);
if !visible {
s.visibility.hidden_folders.push(k.clone());
}
}
s.revision += 1;
return Ok(json!({"visible":visible,"changed":keys.len(),"visibility":s.visibility}));
}
if let Some(value) = p.get("paths") {
if p.get("items").is_some() || p.get("folder").is_some() {
return Err(bad(cmd, "give paths, items or folder, not several"));
@@ -291,6 +330,12 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, None) => return Err(bad(cmd, "`items` or `folder` is required")),
};
// Showing all of a kind also shows the browser folders and groups that hold it.
if visible && let Some(f) = str_(p, "folder") {
let groups: Vec<String> = s.doc.browser_groups.iter().filter(|g| g.folder == f).map(|g| format!("/g{}", g.id)).collect();
let own = format!("/{f}");
s.visibility.hidden_folders.retain(|k| !k.ends_with(&own) && !groups.iter().any(|g| k.ends_with(g.as_str())));
}
let v = &mut s.visibility;
if visible && str_(p, "folder") == Some("bodies") {
v.hidden_occurrences.clear();
@@ -979,6 +1024,13 @@ mod tests {
assert!(std::sync::Arc::ptr_eq(&s.doc, &doc0) && s.undo.len() == undo0, "view state, not a design change");
run(&mut s, "browser.visibility", json!({"folder": "sketches", "visible": true}));
assert_eq!(lines(&s), n0);
// The browser's Sketches folder hidden: sketches shown one by one aren't drawn either,
// only the sketch being edited.
assert!(s.visibility.shown_sketches.contains(&floor));
assert!([floor, drain].iter().all(|id| !crate::view::sketch_drawn(&s, *id, false)));
s.active_sketch = Some(floor);
assert!(crate::view::sketch_drawn(&s, floor, false) && !crate::view::sketch_drawn(&s, drain, false));
s.active_sketch = None;
// Bodies (following a rename) and construction planes.
run(&mut s, "browser.visibility", json!({"items": [body.clone(), "Floor", "xy"], "visible": false}));
assert!(crate::view::scene(&s, &cam).meshes.is_empty());
@@ -1066,4 +1118,67 @@ mod tests {
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.browser_groups.len(), 1, "ungroup undoes");
}
#[test]
fn hidden_folders_and_groups_keep_their_items_state() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0]}));
let [a, b, c] = [names(&s)[0].clone(), names(&s)[1].clone(), names(&s)[2].clone()];
let shown = |s: &Session| [&a, &b, &c].map(|n| s.body_visible(n));
run(&mut s, "browser.visibility", json!({"items": [a.clone()], "visible": false}));
// Hiding the folder hides every body; their own state is kept.
run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/bodies"], "visible": false}));
assert_eq!(shown(&s), [false; 3]);
assert_eq!(s.visibility.hidden_bodies, vec![a.clone()]);
// Showing a body in a hidden folder doesn't show the folder, nor draw the body.
run(&mut s, "browser.visibility", json!({"items": [b.clone()], "visible": true}));
assert!(s.folder_hidden("c0/bodies") && !s.body_visible(&b));
// Showing the folder brings back what was shown before.
run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/bodies"], "visible": true}));
assert_eq!(shown(&s), [false, true, true]);
// Hiding every body leaves the folder shown.
run(&mut s, "browser.visibility", json!({"items": [a.clone(), b.clone(), c.clone()], "visible": false}));
assert!(!s.folder_hidden("c0/bodies"), "hiding every item doesn't hide the folder");
run(&mut s, "browser.visibility", json!({"items": [b.clone(), c.clone()], "visible": true}));
// A group the same way.
let g = run(&mut s, "browser.group", json!({"folder": "bodies", "items": [a.clone(), b.clone()]}))["group"].as_u64().unwrap();
let key = format!("c0/g{g}");
run(&mut s, "browser.visibility", json!({"tree_folders": [key], "visible": false}));
assert_eq!(shown(&s), [false, false, true]);
run(&mut s, "browser.visibility", json!({"tree_folders": [key], "visible": true}));
assert_eq!(shown(&s), [false, true, true]);
run(&mut s, "browser.visibility", json!({"items": [a.clone(), b.clone()], "visible": false}));
assert!(!s.folder_hidden(&key), "hiding every item doesn't hide the group");
// Saved with the design.
run(&mut s, "browser.visibility", json!({"tree_folders": [key, "o:4/sketches"], "visible": false}));
let v: solidcraft_doc::Visibility = serde_json::from_value(serde_json::to_value(&s.visibility).unwrap()).unwrap();
assert_eq!(v.hidden_folders, vec![key.clone(), "o:4/sketches".to_string()]);
// Showing every body also shows the folders and groups that hold bodies.
run(&mut s, "browser.visibility", json!({"folder": "bodies", "visible": true}));
assert_eq!(shown(&s), [true; 3]);
assert_eq!(s.visibility.hidden_folders, vec!["o:4/sketches".to_string()]);
// Hostile keys are refused, and nothing changes.
for p in [
json!({"tree_folders": [], "visible": false}),
json!({"tree_folders": "c0/bodies", "visible": false}),
json!({"tree_folders": ["bodies"], "visible": false}),
json!({"tree_folders": ["c1/bodies"], "visible": false}),
json!({"tree_folders": ["o:/bodies"], "visible": false}),
json!({"tree_folders": ["o:x/bodies"], "visible": false}),
json!({"tree_folders": ["c0/gx"], "visible": false}),
json!({"tree_folders": ["c0/nope"], "visible": false}),
json!({"tree_folders": [7], "visible": false}),
json!({"tree_folders": ["c0/bodies"], "items": [c.clone()], "visible": false}),
json!({"tree_folders": [format!("o:{}1/bodies", "1/".repeat(70))], "visible": false}),
] {
assert!(s.execute("browser.visibility", &p).is_err(), "{p}");
}
assert_eq!(s.visibility.hidden_folders, vec!["o:4/sketches".to_string()]);
}
}
+87 -11
View File
@@ -28,6 +28,7 @@ fn invalid(message: &str) -> EngineError {
pub(crate) struct VisibilityCache {
revision: u64,
paths: Vec<Vec<u64>>,
folders: Vec<String>,
bodies: std::collections::BTreeSet<String>,
}
@@ -186,31 +187,106 @@ impl Session {
/// Whether a joint's glyph is drawn (`browser.visibility`). Hiding a joint only hides its
/// drawing: it still constrains and drives the parts.
/// Is the joint shown itself (its own eye; the Joints folder may still hide it)?
pub fn joint_visible(&self, id: u64) -> bool {
!self.visibility.hidden_joints.contains(&id)
}
/// Is the joint's glyph drawn: shown itself, in a shown Joints folder?
pub fn joint_drawn(&self, id: u64) -> bool {
self.joint_visible(id) && !self.folder_hidden("c0/joints")
}
/// The scope of a placement's browser folders and groups: `c0` for the design (an empty
/// path), `o:<ids joined by />` for a placement.
pub fn folder_scope(path: &[u64]) -> String {
if path.is_empty() { "c0".to_string() } else { format!("o:{}", path.iter().map(u64::to_string).collect::<Vec<_>>().join("/")) }
}
/// Is a browser folder or group hidden itself (by tree key, see `Visibility::hidden_folders`)?
pub fn folder_hidden(&self, key: &str) -> bool {
self.visibility.hidden_folders.iter().any(|k| k == key)
}
/// Is an item (its browser key: body name, feature id) hidden by its folder, or by a group
/// of that folder it is in, at a placement scope ([`Self::folder_scope`])?
pub fn item_folder_hidden(&self, scope: &str, component: u64, folder: &str, item: &str) -> bool {
if self.visibility.hidden_folders.is_empty() {
return false;
}
self.folder_hidden(&format!("{scope}/{folder}"))
|| self.doc.browser_groups.iter().any(|g| {
g.component == component
&& g.folder == folder
&& g.items.iter().any(|i| i == item)
&& self.folder_hidden(&format!("{scope}/g{}", g.id))
})
}
/// Is a sketch or construction feature hidden by its folder or group, at the placement it
/// is drawn at (the active one while its component is being edited, else the first)?
pub fn feature_folder_hidden(&self, id: u64, folder: &str) -> bool {
if self.visibility.hidden_folders.is_empty() {
return false;
}
let component = self.doc.feature(id).map_or(0, |f| f.component);
let path = match &self.active_occurrence_path {
_ if component == 0 => Vec::new(),
Some(p) if self.active_component == component => p.clone(),
_ => self.doc.first_path(component),
};
self.item_folder_hidden(&Self::folder_scope(&path), component, folder, &id.to_string())
}
/// Is construction geometry or an origin item (by name) shown: not hidden itself, nor by
/// its folder or a group it is in?
pub fn construction_visible(&self, name: &str) -> bool {
if self.visibility.hidden_origin.iter().any(|h| h == name) {
return false;
}
match self.doc.features.iter().find(|f| f.name == name) {
Some(f) => !self.feature_folder_hidden(f.id, "construction"),
None => true,
}
}
pub fn body_visible(&self, name: &str) -> bool {
if self.visibility.hidden_bodies.iter().any(|n| n == name) || self.body_removed_later(name) {
return false;
}
if self.visibility.hidden_occurrences.is_empty() {
let v = &self.visibility;
if v.hidden_occurrences.is_empty() && v.hidden_folders.is_empty() {
return true;
}
if let Ok(mut cache) = self.occurrence_visibility_cache.lock() {
if cache.as_ref().is_none_or(|c| c.revision != self.revision || c.paths != self.visibility.hidden_occurrences) {
let bodies = self
.doc
.body_frames(&self.model.state())
.into_iter()
.filter(|(_, _, path, _)| !self.occurrence_visible(path))
.map(|(name, _, _, _)| name)
.collect();
*cache = Some(VisibilityCache { revision: self.revision, paths: self.visibility.hidden_occurrences.clone(), bodies });
if cache.as_ref().is_none_or(|c| c.revision != self.revision || c.paths != v.hidden_occurrences || c.folders != v.hidden_folders) {
*cache = Some(VisibilityCache {
revision: self.revision,
paths: v.hidden_occurrences.clone(),
folders: v.hidden_folders.clone(),
bodies: self.bodies_hidden_by_parents(),
});
}
return cache.as_ref().is_none_or(|c| !c.bodies.contains(name));
}
self.doc.body_frames(&self.model.state()).iter().find(|(n, _, _, _)| n == name).is_none_or(|(_, _, path, _)| self.occurrence_visible(path))
!self.bodies_hidden_by_parents().contains(name)
}
/// World names of the bodies a hidden placement, folder or group above them hides (their
/// own state aside).
fn bodies_hidden_by_parents(&self) -> std::collections::BTreeSet<String> {
let st = self.model.state();
let mut out = std::collections::BTreeSet::new();
for (component, path, _) in self.doc.placements() {
let placement_hidden = !path.is_empty() && !self.occurrence_visible(&path);
let scope = Self::folder_scope(&path);
for b in st.bodies.iter().filter(|b| self.doc.model_body_component(b) == component) {
if placement_hidden || self.item_folder_hidden(&scope, component, "bodies", &b.name) {
out.insert(self.doc.world_body_name(&st, &b.name, component, &path));
}
}
}
out
}
/// Is this body deleted by a feature the history marker has rolled off, while a sketch is
+5 -5
View File
@@ -533,18 +533,18 @@ pub fn sketch_shown(s: &Session, id: u64) -> bool {
sketch_drawn(s, id, true)
}
/// Is a sketch drawn, with the browser's Sketches folder shown (`folder`) or hidden? The sketch
/// being edited always is; otherwise not when hidden, nor in a hidden component, and one used by
/// a feature only when shown on its own.
/// Is a sketch drawn, with sketches shown (`folder`) or hidden? The sketch being edited always
/// is; otherwise not when hidden, nor in a hidden component, Sketches folder or group (even one
/// shown on its own), and one used by a feature only when shown on its own.
pub fn sketch_drawn(s: &Session, id: u64, folder: bool) -> bool {
let v = &s.visibility;
if s.active_sketch == Some(id) {
return true;
}
if v.hidden_sketches.contains(&id) || !sketch_component_visible(s, id) {
if !folder || v.hidden_sketches.contains(&id) || !sketch_component_visible(s, id) || s.feature_folder_hidden(id, "sketches") {
return false;
}
v.shown_sketches.contains(&id) || (folder && !sketch_consumed(s, id))
v.shown_sketches.contains(&id) || !sketch_consumed(s, id)
}
/// Is the placement a sketch is drawn at shown (the active one while its component is being