Skip to main content

brep_app/
javascript.rs

1//! In-app scratch scripts. Source is saved only on request and never on a model.
2use crate::{
3    document::Documents,
4    store::{ModelStore, JAVASCRIPT_DRAFT_KEY},
5};
6use crate::ui_kit;
7use crate::automation::hit_keys::HitKeyDoc;
8use eframe::egui;
9use std::collections::HashMap;
10
11/// The window's egui id — one name for the panel, the tests and the host.
12pub const WINDOW_ID: &str = "brep-javascript-editor";
13
14/// The hit keys this window publishes under `__brepJavascriptHit`
15/// (see `automation::hit_keys`); `panel:clip` is the key every scrolling pane
16/// publishes for its visible region, so `click_widget` can wheel a row into view.
17pub static HIT_KEYS: &[HitKeyDoc] = &[
18    HitKeyDoc { panel: "javascript", prefix: "panel:clip", meaning: "the JavaScript editor window's OUTER rect — its whole visible region, frame included, so the title and grip handles below count as in view", command: None },
19    HitKeyDoc { panel: "javascript", prefix: "title", meaning: "a point on the window's title bar — a drag from it MOVES the window", command: None },
20    HitKeyDoc { panel: "javascript", prefix: "grip", meaning: "a point on the window's bottom-right resize corner — a drag from it RESIZES the window in both axes, up to the app surface", command: None },
21    HitKeyDoc { panel: "javascript", prefix: "run", meaning: "run the script in the active document", command: None },
22    HitKeyDoc { panel: "javascript", prefix: "cancel", meaning: "cancel the running script", command: None },
23    HitKeyDoc { panel: "javascript", prefix: "save", meaning: "save the source as the local draft", command: None },
24    HitKeyDoc { panel: "javascript", prefix: "open", meaning: "open a .js file into the editor (native; file-interchange stores only)", command: None },
25    HitKeyDoc { panel: "javascript", prefix: "export", meaning: "export the source as script.js through the file dialog's export door: the Save-file chooser on desktop, a download in the browser", command: None },
26    HitKeyDoc { panel: "javascript", prefix: "help", meaning: "the CAD API and examples collapsing header", command: None },
27    HitKeyDoc { panel: "javascript", prefix: "example", meaning: "load the box example into the editor (inside `help`)", command: None },
28    HitKeyDoc { panel: "javascript", prefix: "source", meaning: "the source editor's scroll region (the free space of the window: it grows with the window)", command: None },
29    HitKeyDoc { panel: "javascript", prefix: "output", meaning: "the output's scroll region, at the bottom of the window", command: None },
30];
31
32const EXAMPLE: &str = r#"// Run adds a box to the current document. Undo removes the whole run.
33cad.document.addFeature("P.CU", { sizeX: 30, sizeY: 20, sizeZ: 10 });
34console.log("Created a box");
35ui.notify("Edit its dimensions in the feature history");
36return { featuresBefore: cad.document.features.length };
37"#;
38
39/// Where Run sends a program when the app has a script runner: the app's
40/// own server's code mode (`crate::mcp::EditorHost`), the same worker, limits
41/// and `sdk.<namespace>.<action>` functions an agent's `run` program gets.
42/// Without one (the web build, a bare test harness) Run uses the plugin
43/// runner's editor action.
44pub trait ScriptHost {
45    /// Whether the runner is up; the first call starts it.
46    fn ready(&self) -> Result<bool, String>;
47    /// Submit a program; answers its execution id.
48    fn run(&self, source: &str) -> Result<String, String>;
49    /// The execution's result once it has ended, `None` while it runs.
50    fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String>;
51    /// Halt it: the worker is killed wherever it is.
52    fn halt(&self, id: &str) -> Result<(), String>;
53}
54
55/// A run on the [`ScriptHost`], in its document. Its edits fold into one
56/// undo group, kept when the program succeeds and rolled back otherwise, as
57/// the plugin runner's transaction is.
58enum Script {
59    Starting { doc: u64, program: String },
60    Running { doc: u64, id: String, token: u64 },
61    /// Ended: the group closes once the document's engine is idle, so a
62    /// staged feature still landing folds in (or rolls back) with the rest.
63    Closing { doc: u64, token: u64, rollback: bool, output: String, since: web_time::Instant, idle: u32 },
64}
65
66/// How long a closing run waits for its document to go idle before the
67/// group closes anyway (an edit still landing then stands on its own).
68const CLOSE_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
69
70/// A closing run's document must read idle this many polls running, and
71/// [`CLOSE_SETTLE`] must have passed: a tool call the program issued just
72/// before it ended (or was killed) may still be on its way to the app's
73/// queue, which drains AFTER this poll in the frame, and its edit belongs in
74/// the group.
75const CLOSE_IDLE_POLLS: u32 = 5;
76const CLOSE_SETTLE: std::time::Duration = std::time::Duration::from_millis(250);
77
78/// An editor script as a program for the [`ScriptHost`]: both are plain
79/// script bodies with top-level `await` and `return`, and `sdk` (every app
80/// command as `await sdk.<namespace>.<action>(args)`) is the runner's global.
81/// The editor adds its own names around the body: `cad.document` (the history
82/// snapshot with `addFeature(type, params, persistentData)`,
83/// `updateFeature(id, params)` (a merge, as `feature_set_params` merges) and
84/// `deleteFeature(id)`), `cad.selection`, `cad.sdk` (the same `sdk`) and
85/// `ui.notify`. The document commands apply in order after the body returns,
86/// and a returned value prints as `Result:`. One leading
87/// `import … from "@brep/cad"` line is dropped, as the runner drops it.
88pub fn program(source: &str) -> String {
89    let source = without_sdk_import(source);
90    format!(
91        r#"const __commands = [];
92const __stage = c => {{ if (__commands.length >= 256) throw Error("too many document commands"); __commands.push(c); }};
93const __snapshot = (await sdk.document.doc_json({{}})).document;
94const __selection = (await sdk.scene.selection({{}})).selection;
95const __document = Object.freeze({{
96  ...__snapshot,
97  addFeature: (type, params = {{}}, persistentData = {{}}) => __stage(() => sdk.features.feature_add(Object.keys(persistentData).length ? {{ type, params, persistent_data: persistentData }} : {{ type, params }})),
98  updateFeature: (id, params) => __stage(() => sdk.features.feature_set_params({{ id, patch: params }})),
99  deleteFeature: id => __stage(() => sdk.history.feature_delete({{ id }})),
100}});
101const __notify = message => console.log(String(message));
102const __result = await (async function (cad, ui) {{
103{source}
104}})(Object.freeze({{ document: __document, selection: __selection, params: {{}}, notify: __notify, sdk }}), Object.freeze({{ notify: __notify }}));
105for (const command of __commands) await command();
106if (__result !== undefined) console.log("Result:", JSON.stringify(__result));
107return null;
108"#
109    )
110}
111
112/// `source` with its first statement blanked when that is an
113/// `import … from "@brep/cad"` line (a script written as an agent's module
114/// would be): the editor's wrapper comes first, so the runner's own strip
115/// never sees it. Its line stays, so the rows below keep their numbers.
116fn without_sdk_import(source: &str) -> String {
117    let Some(first) = source.lines().find(|l| !l.trim().is_empty() && !l.trim_start().starts_with("//")) else { return source.to_string() };
118    let line = first.trim();
119    let import = line.starts_with("import") && (line.ends_with("\"@brep/cad\";") || line.ends_with("\"@brep/cad\"") || line.ends_with("'@brep/cad';") || line.ends_with("'@brep/cad'"));
120    if !import {
121        return source.to_string();
122    }
123    source.replacen(first, "", 1)
124}
125
126/// What a finished execution shows: the outcome, the console lines, and a
127/// module's returned value.
128fn script_output(result: &serde_json::Value) -> String {
129    let mut lines = vec![match result["state"].as_str() {
130        Some("succeeded") => "Completed.".to_string(),
131        Some("cancelled") => "Cancelled.".to_string(),
132        _ => format!("Failed: {}", result["error"]["message"].as_str().unwrap_or("the script failed")),
133    }];
134    if let Some(log) = result["logText"].as_str().filter(|l| !l.is_empty()) {
135        lines.push(log.to_string());
136    }
137    if !result["output"].is_null() {
138        lines.push(format!("Result: {}", result["output"]));
139    }
140    lines.join("\n")
141}
142
143pub struct JavaScriptEditor {
144    pub open: bool,
145    source: String,
146    output: String,
147    pending: Option<u64>, // originating document, retained across tab switches
148    /// The app's script runner, when it has one (see [`ScriptHost`]).
149    pub host: Option<Box<dyn ScriptHost>>,
150    script: Option<Script>,
151    importing: bool,
152    /// This frame's widget rects (egui points) for the automation host; empty
153    /// while the window is closed.
154    hits: HashMap<String, egui::Rect>,
155    /// The window's outer rect this frame, `None` while it is closed.
156    rect: Option<egui::Rect>,
157    /// The surface the window may fill (`ctx.content_rect()`), for the host.
158    surface: egui::Rect,
159    /// "Export .js…" asked: the shell hands these to the file dialog's export
160    /// door ([`Self::take_save_requests`]), which on desktop asks where.
161    exports: Vec<crate::panels::file::SaveRequest>,
162}
163
164
165impl JavaScriptEditor {
166    pub fn running_in(&self, document: u64) -> bool {
167        self.pending == Some(document)
168    }
169
170    pub fn set_source(&mut self, source: String) {
171        self.source = source;
172    }
173
174    pub fn editing_source(ctx: &egui::Context) -> bool {
175        ctx.memory(|memory| memory.has_focus(egui::Id::new("cad-javascript-source")))
176    }
177
178    pub fn new(store: &dyn ModelStore) -> Self {
179        Self {
180            open: false,
181            source: store
182                .read(JAVASCRIPT_DRAFT_KEY)
183                .unwrap_or_else(|| EXAMPLE.into()),
184            output: String::new(),
185            pending: None,
186            host: None,
187            script: None,
188            importing: false,
189            hits: HashMap::new(),
190            exports: Vec::new(),
191            rect: None,
192            surface: egui::Rect::NOTHING,
193        }
194    }
195
196    /// Logical state for the automation host: `rect` is the window's outer
197    /// rect `[x, y, w, h]` in egui points (null while closed), `surface` the
198    /// screen rect it may fill `[w, h]`.
199    pub fn state_json(&self) -> String {
200        let rect = |r: egui::Rect| serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]);
201        serde_json::json!({
202            "open": self.open,
203            "rect": self.rect.map(rect),
204            "surface": [self.surface.width(), self.surface.height()],
205            "running": self.pending.is_some(),
206            "output": self.output,
207        })
208        .to_string()
209    }
210
211    /// The published widget hit-rects (`[x, y, w, h]`, egui points).
212    pub fn hits_json(&self) -> String {
213        crate::automation::hit_rects::hits_json(&self.hits)
214    }
215
216    /// Halt the running script and roll its edits back once its document
217    /// is idle; `output` says why.
218    fn halt_script(&mut self, docs: &mut Documents, output: String) {
219        match self.script.take() {
220            Some(Script::Starting { .. }) => {
221                self.pending = None;
222                self.output = output;
223            }
224            Some(Script::Running { doc, id, token }) => {
225                if let Some(host) = &self.host {
226                    let _ = host.halt(&id);
227                }
228                // Brake a history run the script started, as the app's
229                // cancel button does; a staged feature then rolls back.
230                if let Some(d) = docs.iter_mut().find(|d| d.id() == doc) {
231                    d.engine.cancel_run();
232                }
233                self.script = Some(Script::Closing { doc, token, rollback: true, output, since: web_time::Instant::now(), idle: 0 });
234            }
235            other => self.script = other,
236        }
237    }
238
239    /// One frame of a run on the [`ScriptHost`].
240    fn poll_script(&mut self, ctx: &egui::Context, docs: &mut Documents) {
241        ctx.request_repaint_after(std::time::Duration::from_millis(30));
242        let doc_id = match &self.script {
243            Some(Script::Starting { doc, .. } | Script::Running { doc, .. } | Script::Closing { doc, .. }) => *doc,
244            None => return,
245        };
246        if !docs.iter().any(|d| d.id() == doc_id) {
247            if let (Some(Script::Running { id, .. }), Some(host)) = (&self.script, &self.host) {
248                let _ = host.halt(id);
249            }
250            self.script = None;
251            self.pending = None;
252            self.output = "The script's document was closed.".into();
253            return;
254        }
255        // The app's tools act on the ACTIVE document: a run whose document
256        // is no longer active would write another one.
257        if docs.active_id() != doc_id && matches!(self.script, Some(Script::Starting { .. } | Script::Running { .. })) {
258            return self.halt_script(docs, "Halted: the active document changed while the script ran; its edits were rolled back.".into());
259        }
260        let Some(host) = &self.host else { return };
261        let doc = docs.iter_mut().find(|d| d.id() == doc_id).expect("checked above");
262        match self.script.take() {
263            Some(Script::Starting { doc: d, program }) => match host.ready() {
264                Ok(true) => {
265                    let token = doc.engine.history_group_begin();
266                    match host.run(&program) {
267                        Ok(id) => self.script = Some(Script::Running { doc: d, id, token }),
268                        Err(e) => {
269                            let _ = doc.engine.history_group_end(token, false);
270                            self.pending = None;
271                            self.output = e;
272                        }
273                    }
274                }
275                Ok(false) => self.script = Some(Script::Starting { doc: d, program }),
276                Err(e) => {
277                    self.pending = None;
278                    self.output = e;
279                }
280            },
281            Some(Script::Running { doc: d, id, token }) => match host.result(&id) {
282                Ok(None) => self.script = Some(Script::Running { doc: d, id, token }),
283                Ok(Some(result)) => {
284                    let rollback = result["state"] != "succeeded";
285                    let output = script_output(&result);
286                    self.script = Some(Script::Closing { doc: d, token, rollback, output, since: web_time::Instant::now(), idle: 0 });
287                }
288                Err(e) => self.script = Some(Script::Closing { doc: d, token, rollback: true, output: e, since: web_time::Instant::now(), idle: 0 }),
289            },
290            Some(Script::Closing { doc: d, token, rollback, output, since, idle }) => {
291                doc.engine.pump();
292                let quiet = !doc.engine.run_pending() && !doc.engine.stage_feature_pending();
293                let idle = if quiet { idle + 1 } else { 0 };
294                let settled = idle >= CLOSE_IDLE_POLLS && since.elapsed() >= CLOSE_SETTLE;
295                if !settled && since.elapsed() < CLOSE_WAIT {
296                    self.script = Some(Script::Closing { doc: d, token, rollback, output, since, idle });
297                    return;
298                }
299                self.pending = None;
300                self.output = match doc.engine.history_group_end(token, rollback) {
301                    Ok(true) => format!("{output}\nIts edits were rolled back."),
302                    Ok(false) => output,
303                    Err(e) => format!("{output}\n{e}"),
304                };
305            }
306            None => {}
307        }
308    }
309
310    /// Record a widget's VISIBLE rect for the host.
311    fn hit(&mut self, key: &str, resp: &egui::Response) {
312        self.hits.insert(key.to_string(), resp.interact_rect);
313    }
314
315    pub fn poll(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
316        if self.importing {
317            if let Some(file) = store.take_import() {
318                self.importing = false;
319                match String::from_utf8(file.bytes) {
320                    Ok(source) => self.source = source,
321                    Err(e) => self.output = format!("Cannot open script: {e}"),
322                }
323            }
324        }
325        if self.script.is_some() {
326            return self.poll_script(ctx, docs);
327        }
328        let Some(id) = self.pending else {
329            return;
330        };
331        let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) else {
332            self.pending = None;
333            self.output = "The script's document was closed.".into();
334            return;
335        };
336        doc.engine.pump();
337        let status = doc.engine.plugin_action_status();
338        match status["state"].as_str() {
339            Some("complete") => {
340                let lines: Vec<_> = status["result"]["notifications"]
341                    .as_array()
342                    .into_iter()
343                    .flatten()
344                    .filter_map(|v| v.as_str())
345                    .collect();
346                self.output = format!("Completed.\n{}", lines.join("\n"));
347                self.pending = None;
348            }
349            Some("error") => {
350                self.output = status["error"].as_str().unwrap_or("Script failed").into();
351                self.pending = None;
352            }
353            _ => {
354                ctx.request_repaint_after(std::time::Duration::from_millis(30));
355            }
356        }
357    }
358
359    /// The files "Export .js…" asked to save, once: the shell hands them to
360    /// [`crate::panels::file::FileDialog::request_save_file`].
361    pub fn take_save_requests(&mut self) -> Vec<crate::panels::file::SaveRequest> {
362        std::mem::take(&mut self.exports)
363    }
364
365    pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
366        self.hits.clear();
367        self.rect = None;
368        self.surface = ctx.content_rect();
369        let mut open = self.open;
370        let shown = egui::Window::new("JavaScript editor").id(egui::Id::new(WINDOW_ID)).open(&mut open)
371            // Under the toolbar / Ribbon like Settings, Plugins and Info: without
372            // a position egui put it over the menu bar (ui-polish-2026-10-28 row 5).
373            .default_pos(crate::panels::below_chrome(ctx, 16.0, 0.0))
374            .default_size(egui::vec2(720.0, 620.0)).min_size(egui::vec2(420.0, 320.0)).resizable(true).show(ctx, |ui| {
375            ui.label(format!("Run in: {}", docs.active().title()));
376            if let Some(id) = self.pending {
377                if let Some(doc) = docs.iter().find(|doc| doc.id() == id) {
378                    ui.horizontal(|ui| {
379                        ui.spinner();
380                        ui.label(format!("Running in: {}", doc.title()));
381                    });
382                }
383            }
384            ui.horizontal(|ui| {
385                let busy = self.pending.is_some() || docs.engine().run_pending()
386                    || docs.engine().plugin_action_status()["state"] == "pending";
387                let run = ui_kit::button::add_enabled(ui, !busy, ui_kit::Button::new("Run script"));
388                self.hit("run", &run);
389                // `cad.geometry` (kernel solids in an editor body) is the
390                // plugin runner's; such a script stays there.
391                if run.clicked() && self.host.is_some() && !self.source.contains("cad.geometry") {
392                    self.pending = Some(docs.active_id());
393                    self.script = Some(Script::Starting { doc: docs.active_id(), program: program(&self.source) });
394                    self.output = "Running…".into();
395                } else if run.clicked() {
396                    match docs.engine_mut().run_javascript(&self.source) {
397                        Ok(_) => { self.pending = Some(docs.active_id()); self.output = "Running…".into(); }
398                        Err(e) => self.output = e,
399                    }
400                }
401                let cancel = ui_kit::button::add_enabled(ui, self.pending.is_some(), ui_kit::Button::new("Cancel"));
402                self.hit("cancel", &cancel);
403                if cancel.clicked() && self.script.is_some() {
404                    self.halt_script(docs, "Cancelled.".into());
405                } else if cancel.clicked() {
406                    if let Some(id) = self.pending {
407                        if let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) {
408                            doc.engine.cancel_plugin_action();
409                        }
410                    }
411                }
412                let save = ui.add(ui_kit::Button::new("Save draft"));
413                self.hit("save", &save);
414                if save.clicked() {
415                    self.output = match store.write(JAVASCRIPT_DRAFT_KEY, &self.source) {
416                        Ok(()) => "Draft saved.".into(), Err(e) => format!("Cannot save draft: {e}"),
417                    };
418                }
419                // Open .js… drives the browser's file input, so only where
420                // there is one. Export leaves through the file dialog's export
421                // door on every platform (the Save-file chooser on desktop),
422                // so it is always offered: gated with Open, desktop had no
423                // way to export a script at all.
424                if store.supports_file_interchange() {
425                    let open = ui_kit::button::add_enabled(ui, !self.importing, ui_kit::Button::new("Open .js…"));
426                    self.hit("open", &open);
427                    if open.clicked() {
428                        match store.begin_import_filtered(("JavaScript", &["js"])) {
429                            Ok(()) => self.importing = true, Err(e) => self.output = e,
430                        }
431                    }
432                }
433                let export = ui.add(ui_kit::Button::new("Export .js…"));
434                self.hit("export", &export);
435                if export.clicked() {
436                    self.exports.push(crate::panels::file::SaveRequest::text("Export the script", "script.js", self.source.clone()));
437                }
438            });
439            let help = ui.collapsing("CAD API and examples", |ui| {
440                ui.label("Write JavaScript statements. cad.document is a snapshot of the current history; cad.selection contains the current selection.");
441                ui.monospace("cad.document.addFeature(type, params)\ncad.document.updateFeature(id, params)\ncad.document.deleteFeature(id)\nconsole.log / info / warn / error(...)\nui.notify(text)\nreturn { any: 'JSON result' };");
442                ui.label("Built-in types include P.CU (sizeX, sizeY, sizeZ), P.S (radius), and P.CY (radius, height). Successful changes form one undo step. Each Run executes the script again.");
443                if self.host.is_some() {
444                    ui.label("Every app command is a function too: await sdk.<namespace>.<action>(args), the same functions an agent's run program gets (the MCP sdk tool lists and types them). The script is a plain body: await at the top level, and return a value to see it as Result. A failed or cancelled run is rolled back.");
445                }
446                let example = ui.add(ui_kit::Button::new("Load box example"));
447                if example.clicked() { self.source = EXAMPLE.into(); }
448                example
449            });
450            self.hits.insert("help".into(), help.header_response.interact_rect);
451            if let Some(example) = help.body_returned {
452                self.hits.insert("example".into(), example.interact_rect);
453            }
454            // The rest of the window is the editor over the output. Two panels
455            // rather than two capped scroll areas: egui sizes a window's axis to
456            // its CONTENT (its Resize is not resizable, the content ui merely
457            // gets the dragged size as its max rect), so content that does not
458            // fill the dragged size snaps the window back to the content's
459            // height. Panels fill whatever the window is given, so the window
460            // follows the drag — up to the surface, which egui clamps to.
461            // The output panel keeps its own height (draggable at its top edge)
462            // and the editor takes everything above it.
463            egui::containers::panel::Panel::bottom(egui::Id::new("brep-javascript-output"))
464                .resizable(true)
465                .default_size(160.0)
466                .min_size(48.0)
467                .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4)))
468                .show_inside(ui, |ui| {
469                    ui.label("Output");
470                    let output = egui::ScrollArea::both().id_salt("javascript-output").auto_shrink(false).show(ui, |ui| {
471                        ui.add(egui::Label::new(egui::RichText::new(&self.output).monospace()).selectable(true));
472                    });
473                    self.hits.insert("output".into(), output.inner_rect);
474                });
475            egui::CentralPanel::default().frame(egui::Frame::NONE).show_inside(ui, |ui| {
476                // The text box fills the free space, so a click in the empty
477                // area under a short script still lands in the editor. By ROWS:
478                // egui's `TextEdit::min_size` honours only the width, and the
479                // box's height is its rows (or its text, whichever is taller).
480                // Floored, so a box that fills the space never scrolls by the
481                // odd point.
482                let free = ui.available_height();
483                let row = ui.fonts_mut(|f| f.row_height(&egui::TextStyle::Monospace.resolve(ui.style())));
484                let rows = ((free - 4.0) / row).floor().max(4.0) as usize;
485                let source = egui::ScrollArea::both().id_salt("javascript-source").auto_shrink(false).show(ui, |ui| {
486                    ui.add(egui::TextEdit::multiline(&mut self.source).code_editor()
487                        .id(egui::Id::new("cad-javascript-source"))
488                        .desired_rows(rows).desired_width(f32::INFINITY));
489                });
490                self.hits.insert("source".into(), source.inner_rect);
491            });
492        });
493        // Published only while OPEN: egui keeps returning the window through its
494        // fade-out, and a host reading a rect for a window the user just closed
495        // would drag on nothing.
496        if let (Some(shown), true) = (shown, open) {
497            let rect = shown.response.rect;
498            self.rect = Some(rect);
499            // The window's handles, as points egui's own hit zones answer to: the
500            // title bar's centre (a drag moves the window) and a point just inside
501            // the bottom-right corner, within the corner grab radius (a drag
502            // resizes). `panel:clip` is the outer rect so both read as in view.
503            self.hits.insert("panel:clip".into(), rect);
504            self.hits.insert("title".into(), egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.min.y + 12.0), egui::Vec2::ZERO));
505            self.hits.insert("grip".into(), egui::Rect::from_center_size(rect.max - egui::vec2(3.0, 3.0), egui::Vec2::ZERO));
506        } else {
507            self.hits.clear();
508        }
509        self.open = open;
510    }
511}