Skip to main content

egui_pop_views/
steps.rs

1//! The views' steps (ADR 0011) and the plugin that declares them.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! Every moment a view acts on (a branch expanded, a selection changed,
7//! a drop, a rename, a sort) runs as a step: a plugin may watch it on the
8//! journal, veto or redirect it with a before-hook, do it its own way
9//! with a run-hook, or follow it with an after-hook. The default (the
10//! closure the view passes) changes the view's own state; the
11//! application owns its data and applies the change there (from the
12//! step's after-hook, or from the view's output signals).
13//!
14//! A view given no [`AppHandle`] runs its defaults directly: the signals
15//! are still in its output, nothing is published.
16//!
17//! | Step | Arguments | Default |
18//! |---|---|---|
19//! | `tree.load` | `tree`, `key` (`null`: the roots) | asks the source for the branch's children |
20//! | `tree.expand` | `tree`, `key`, `expanded` | opens or closes the branch (loading it the first time) |
21//! | `tree.select` | `tree`, `keys`, `cursor` | sets the selection |
22//! | `tree.drop` | `tree`, `keys`, `target`, `position` (`before`, `after`, `inside`) | asks the source and the view (`can_drop`), then moves the nodes in the view |
23//! | `tree.rename` | `tree`, `key`, `from`, `to` | renames the node in the view |
24//! | `tree.activate` | `tree`, `key` | nothing: the application opens the leaf |
25//! | `tree.context` | `tree`, `key` | opens the row's context menu, for that row |
26//! | `tree.action` | `tree`, `key`, `action` | nothing: the application acts (`TreeView::on_action`) |
27//! | `list.select` | `list`, `keys`, `cursor` | sets the selection |
28//! | `table.select` | `table`, `keys`, `cursor` | sets the selection |
29//! | `table.sort` | `table`, `column` (`null`: unsorted), `descending` | writes the sort to the store |
30//! | `table.resize` | `table`, `widths` | writes the widths to the store |
31//! | `table.select_columns` | `table`, `columns` | sets the column selection |
32
33#[cfg(feature = "api")]
34use egui_pop_api::steps::StepSpec;
35#[cfg(feature = "api")]
36use egui_pop_api::{Ctx, Plugin, PluginError};
37
38use crate::app_link::{AppHandle, Outcome};
39#[cfg(feature = "api")]
40use egui_pop_core::debug::FnCollector;
41#[cfg(feature = "api")]
42use egui_pop_model::commands::CommandSpec;
43use egui_pop_model::ids::{CommandId, PluginId, StepId};
44#[cfg(feature = "api")]
45use egui_pop_model::keymap::BindOptions;
46use serde_json::Value as Json;
47#[cfg(feature = "api")]
48use serde_json::json;
49
50pub const TREE_LOAD: StepId = StepId::from_static("tree.load");
51pub const TREE_EXPAND: StepId = StepId::from_static("tree.expand");
52pub const TREE_SELECT: StepId = StepId::from_static("tree.select");
53pub const TREE_DROP: StepId = StepId::from_static("tree.drop");
54pub const TREE_RENAME: StepId = StepId::from_static("tree.rename");
55pub const TREE_ACTIVATE: StepId = StepId::from_static("tree.activate");
56pub const TREE_CONTEXT: StepId = StepId::from_static("tree.context");
57pub const TREE_ACTION: StepId = StepId::from_static("tree.action");
58pub const LIST_SELECT: StepId = StepId::from_static("list.select");
59pub const TABLE_SELECT: StepId = StepId::from_static("table.select");
60pub const TABLE_SORT: StepId = StepId::from_static("table.sort");
61pub const TABLE_RESIZE: StepId = StepId::from_static("table.resize");
62pub const TABLE_SELECT_COLUMNS: StepId = StepId::from_static("table.select_columns");
63
64/// Moves the focus from a tree to its filter field (Ctrl+F, `/`).
65pub const CMD_TREE_FILTER: CommandId = CommandId::from_static("tree.filter");
66
67/// The plugin's id.
68pub const VIEWS: PluginId = PluginId::from_static("egui_pop.views");
69
70/// Declares the views' steps, the `tree.filter` command (Ctrl+F and `/`
71/// in a tree drawn with a [`FilterField`](crate::tree::FilterField), on
72/// its `treeFilter` surface) and the `trees` debug collector (each
73/// tree's filter and rows shown, [`crate::tree::filter::drawn`]).
74/// Connect it when views run with an [`AppHandle`]: a step nobody
75/// declares is reported.
76#[cfg(feature = "api")]
77#[derive(Debug, Default)]
78pub struct ViewsPlugin;
79
80/// Every step the views declare, with its description and an example of
81/// its arguments.
82#[cfg(feature = "api")]
83pub fn specs() -> Vec<StepSpec> {
84    vec![
85        StepSpec::new(TREE_LOAD, "A tree asks its source for a branch's children.")
86            .args(json!({ "tree": "folders", "key": "photos" })),
87        StepSpec::new(TREE_EXPAND, "A tree branch opens or closes; a veto keeps it as it is.")
88            .args(json!({ "tree": "folders", "key": "photos", "expanded": true })),
89        StepSpec::new(TREE_SELECT, "A tree's selection changes.")
90            .args(json!({ "tree": "folders", "keys": ["photos"], "cursor": "photos" })),
91        StepSpec::new(
92            TREE_DROP,
93            "Nodes dragged in a tree are dropped before, after or inside a node; a veto refuses the drop.",
94        )
95        .args(json!({ "tree": "folders", "keys": ["2024"], "target": "archive", "position": "inside" })),
96        StepSpec::new(TREE_RENAME, "A tree node is renamed in place; a veto keeps its name.")
97            .args(json!({ "tree": "folders", "key": "photos", "from": "Photos", "to": "Pictures" })),
98        StepSpec::new(TREE_ACTIVATE, "A tree leaf is opened (Enter, double click).")
99            .args(json!({ "tree": "folders", "key": "photos/1.jpg" })),
100        StepSpec::new(
101            TREE_CONTEXT,
102            "A tree row is right-clicked: its context menu opens for that row, whatever is selected; a veto keeps it closed.",
103        )
104        .args(json!({ "tree": "folders", "key": "photos/1.jpg" })),
105        StepSpec::new(
106            TREE_ACTION,
107            "An action button of a tree row is clicked (a visibility eye, remove); a veto ignores the click.",
108        )
109        .args(json!({ "tree": "layers", "key": "ground", "action": "visibility" })),
110        StepSpec::new(LIST_SELECT, "A list's selection changes.")
111            .args(json!({ "list": "recent", "keys": [3], "cursor": 3 })),
112        StepSpec::new(TABLE_SELECT, "A table's selection changes.")
113            .args(json!({ "table": "files", "keys": [3], "cursor": 3 })),
114        StepSpec::new(
115            TABLE_SORT,
116            "A table is sorted by a column, or unsorted; the application sorts its rows.",
117        )
118        .args(json!({ "table": "files", "column": "name", "descending": false })),
119        StepSpec::new(TABLE_RESIZE, "A table's columns are resized.")
120            .args(json!({ "table": "files", "widths": [200.0, 80.0] })),
121        StepSpec::new(
122            TABLE_SELECT_COLUMNS,
123            "A table's column selection changes (a header clicked); a veto keeps it.",
124        )
125        .args(json!({ "table": "files", "columns": ["size"] })),
126    ]
127}
128
129#[cfg(feature = "api")]
130impl Plugin for ViewsPlugin {
131    fn id(&self) -> PluginId {
132        VIEWS
133    }
134
135    fn title(&self) -> String {
136        "Data views".into()
137    }
138
139    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
140        for spec in specs() {
141            ctx.step(spec)?;
142        }
143        let surface = || BindOptions::surface(crate::tree::filter::SURFACE);
144        ctx.command(
145            CommandSpec::new(CMD_TREE_FILTER, "Filter the tree", "Views")
146                .description("Moves the focus from a tree to its filter field.")
147                .key_with("Ctrl+F", surface())
148                .key_with("Slash", surface())
149                .hidden(),
150            |call| {
151                crate::tree::filter::request(&call.app.egui());
152                Ok(Json::Bool(true))
153            },
154        )?;
155        ctx.collector(
156            FnCollector::new(
157                "trees",
158                "The trees drawn: each one's filter, how many nodes match it of how many are loaded, and the rows shown (key, label, depth, whether it matches, whether a branch is open).",
159            )
160            .snapshot(crate::tree::filter::drawn),
161        )?;
162        Ok(())
163    }
164}
165
166/// Runs a step through the application when there is one, else its
167/// default directly.
168pub(crate) fn run(
169    app: Option<&AppHandle>,
170    step: &StepId,
171    args: Json,
172    default: impl FnOnce(&Json) -> Result<Json, String>,
173) -> Outcome {
174    match app {
175        #[cfg(feature = "api")]
176        Some(app) => app.step(step, args, |_, args| default(args)),
177        #[cfg(not(feature = "api"))]
178        Some(app) => {
179            let _ = step;
180            match *app {}
181        }
182        None => Outcome::Done(default(&args)),
183    }
184}