BREP_app 0.2.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! step.parts online model library browser (Assembly workbench).
//!
//! The Assembly toolbar's library button opens THIS ctx-level window. It queries
//! the public step.parts v1 API (`https://api.step.parts/v1`), lists matching
//! standard mechanical parts WITH thumbnails, and — on pick — downloads the
//! part's STEP file, creates a NEW part document from it (an `IMPORT3D` feature
//! carrying the raw STEP text — the app's established STEP-import shape), writes
//! that document to a user-chosen location through the [`ModelStore`] seam
//! (keeping the STEP file's original filename), and adds it to the current
//! assembly as an `ACOMP` component via the ONE insert flow
//! ([`EngineState::insert_component`]).
//!
//! ## Networking
//! `ehttp` abstracts the two targets: native uses a background HTTP thread, wasm
//! uses the browser `fetch`. Every step.parts host (the API, the GitHub-LFS STEP
//! media host, and the Vercel-Blob PNG host) sends `Access-Control-Allow-Origin:
//! *`, so the wasm/browser path is NOT CORS-blocked. Async results marshal back
//! into the synchronous egui frame through `std::sync::mpsc` channels drained at
//! the top of [`StepPartsPanel::show`], each fetch calling `ctx.request_repaint`
//! so the UI wakes when a reply lands. A failed request never panics/hangs — it
//! surfaces as a status line and the dialog stays usable.
//!
//! ## Testability
//! The request/response SHAPE lives in free functions ([`search_url`],
//! [`parse_search_response`], [`step_filename_stem`], [`build_part_document`])
//! and the store-write + component-add lives in [`StepPartsPanel::import_step_text`],
//! all unit-tested with injected data — no network in the test suite.

use crate::panels::assembly_edit::document_signature;
use crate::panels::file_explorer::{FileExplorer, FileExplorerOptions};
use crate::store::{model_display_name, ModelStore};
use brep_render::engine_state::{ComponentInsert, EngineState};
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::mpsc::Receiver;

/// The public step.parts v1 API base (the app uses the same `/v1` routes an
/// agent would; see `GET /v1/openapi.json`).
const API_BASE: &str = "https://api.step.parts/v1";
/// Results per page. Kept modest (vs. the API's 500 cap) so a search fires a
/// bounded burst of thumbnail fetches; Prev/Next page through the rest.
const PAGE_SIZE: u32 = 24;

/// One search result — the subset of the API `AgentPart` record this UI needs.
/// Field names come straight from `openapi.json` (`stepUrl` = canonical STEP
/// download, `pngUrl` = thumbnail), never guessed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PartItem {
    pub id: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub step_url: String,
    pub png_url: String,
}

// --- pure helpers (unit-tested; no egui, no network) -------------------------

/// Percent-encode a query VALUE (RFC 3986 unreserved set kept; everything else,
/// space included, becomes `%XX`). One field only — not worth a urlencoding crate.
fn encode_query(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// The `/v1/parts` search URL for `query` (blank ⇒ plain list) at 1-based `page`.
fn search_url(base: &str, query: &str, page: u32) -> String {
    let mut url = format!("{base}/parts?pageSize={PAGE_SIZE}&page={page}");
    let q = query.trim();
    if !q.is_empty() {
        url.push_str("&q=");
        url.push_str(&encode_query(q));
    }
    url
}

/// A string field off a JSON object, or `""` when absent/non-string.
fn str_field(obj: &Value, key: &str) -> String {
    obj.get(key).and_then(Value::as_str).unwrap_or("").to_string()
}

/// The response's `hasNextPage` flag (defaults `false` when absent).
fn response_has_next(json: &Value) -> bool {
    json.get("hasNextPage").and_then(Value::as_bool).unwrap_or(false)
}

/// Parse a `/v1/parts` response body into result items. Tolerant of missing
/// optional fields; errors only on a structurally wrong body (no `items` array).
fn parse_search_response(json: &str) -> Result<(Vec<PartItem>, bool), String> {
    let v: Value = serde_json::from_str(json).map_err(|e| format!("bad response: {e}"))?;
    // The API also returns `{ "error": "…" }` on a bad request — surface it.
    if let Some(err) = v.get("error").and_then(Value::as_str) {
        return Err(err.to_string());
    }
    let items = v
        .get("items")
        .and_then(Value::as_array)
        .ok_or("response missing `items` array")?;
    let parts = items
        .iter()
        .map(|it| PartItem {
            id: str_field(it, "id"),
            name: str_field(it, "name"),
            description: str_field(it, "description"),
            category: str_field(it, "category"),
            step_url: str_field(it, "stepUrl"),
            png_url: str_field(it, "pngUrl"),
        })
        .collect();
    Ok((parts, response_has_next(&v)))
}

/// The STEP file's ORIGINAL filename stem — the last path segment of `stepUrl`
/// with any query string and a `.step`/`.stp` extension stripped. This becomes
/// the default part-document name so the saved part keeps its source filename.
fn step_filename_stem(step_url: &str) -> String {
    let last = step_url
        .rsplit('/')
        .next()
        .unwrap_or(step_url);
    let last = last.split(['?', '#']).next().unwrap_or(last);
    let stem = last
        .strip_suffix(".step")
        .or_else(|| last.strip_suffix(".STEP"))
        .or_else(|| last.strip_suffix(".stp"))
        .or_else(|| last.strip_suffix(".STP"))
        .unwrap_or(last);
    if stem.is_empty() {
        "imported-part".to_string()
    } else {
        stem.to_string()
    }
}

/// Build a part HistoryRequest document that embeds `step_text` as an `IMPORT3D`
/// feature — the exact shape [`EngineState::import_step_feature`] uses. The
/// ISO-10303-21 gate is enforced HERE, strictly BEFORE any store write or
/// component insert, so a non-STEP payload is refused up front and the
/// insert/library error path (which aborts the NATIVE app — see project memory
/// `jsvalue-native-abort-trap`) is never reached on a bad download.
fn build_part_document(step_text: &str) -> Result<String, String> {
    if !step_text.contains("ISO-10303-21") {
        return Err("not a STEP file (missing the ISO-10303-21 header)".into());
    }
    Ok(serde_json::json!({
        "expressions": "",
        "configurator": {},
        "features": [{
            "type": "IMPORT3D",
            "inputParams": { "id": "IMPORT3D1", "stepText": step_text },
            "persistentData": {}
        }]
    })
    .to_string())
}

// --- async fetch plumbing (both targets, via ehttp) --------------------------

/// Fetch `url` as UTF-8 text; the reply (or a human error) arrives on the
/// returned channel and `ctx` is repainted so the frame loop drains it.
fn fetch_text(ctx: &egui::Context, url: String) -> Receiver<Result<String, String>> {
    let (tx, rx) = std::sync::mpsc::channel();
    let ctx = ctx.clone();
    ehttp::fetch(ehttp::Request::get(url), move |result| {
        let out = match result {
            Ok(resp) if resp.ok => Ok(resp
                .text()
                .map(str::to_owned)
                .unwrap_or_else(|| String::from_utf8_lossy(&resp.bytes).into_owned())),
            Ok(resp) => Err(format!("HTTP {} {}", resp.status, resp.status_text)),
            Err(err) => Err(err),
        };
        let _ = tx.send(out);
        ctx.request_repaint();
    });
    rx
}

/// Fetch `url` as raw bytes (thumbnail PNGs).
fn fetch_bytes(ctx: &egui::Context, url: String) -> Receiver<Result<Vec<u8>, String>> {
    let (tx, rx) = std::sync::mpsc::channel();
    let ctx = ctx.clone();
    ehttp::fetch(ehttp::Request::get(url), move |result| {
        let out = match result {
            Ok(resp) if resp.ok => Ok(resp.bytes),
            Ok(resp) => Err(format!("HTTP {} {}", resp.status, resp.status_text)),
            Err(err) => Err(err),
        };
        let _ = tx.send(out);
        ctx.request_repaint();
    });
    rx
}

/// Decode PNG bytes into an egui texture (thumbnail). `None` on a decode error
/// so the row shows a neutral placeholder rather than failing the whole dialog.
fn decode_thumbnail(ctx: &egui::Context, id: &str, bytes: &[u8]) -> Option<egui::TextureHandle> {
    let image = image::load_from_memory(bytes).ok()?.to_rgba8();
    let (w, h) = image.dimensions();
    let color = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], image.as_raw());
    Some(ctx.load_texture(format!("steplib-thumb:{id}"), color, egui::TextureOptions::LINEAR))
}

/// A thumbnail's lifecycle for one result row.
enum ThumbState {
    Loading,
    Failed,
    Ready(egui::TextureHandle),
}

/// Which sub-view the window is showing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum View {
    /// Search box + results list.
    Search,
    /// Destination picker for the part being imported.
    Destination,
}

/// The Assembly workbench's step.parts library browser (shell-owned, ctx-level
/// window — the Info/Interference idiom). Opened by the toolbar button; owns all
/// of its own search / thumbnail / import state.
pub struct StepPartsPanel {
    open: bool,
    view: View,
    /// The search field text.
    query: String,
    /// 1-based page currently shown.
    page: u32,
    /// Whether the API reported a further page (drives Next).
    has_next: bool,
    /// A search request is in flight.
    searching: bool,
    /// Human status / error line (search + import both write here).
    status: String,
    /// Current page of results.
    results: Vec<PartItem>,
    /// In-flight search reply channel.
    search_rx: Option<Receiver<Result<String, String>>>,
    /// Per-result thumbnail state, keyed by part id.
    thumbs: HashMap<String, ThumbState>,
    /// In-flight thumbnail byte channels, keyed by part id.
    thumb_rx: HashMap<String, Receiver<Result<Vec<u8>, String>>>,
    /// The part chosen for import (drives the Destination view).
    pending: Option<PartItem>,
    /// Destination document name — prefilled with the STEP filename stem.
    dest_name: String,
    /// The downloaded STEP text for `pending`, once it lands.
    pending_step: Option<String>,
    /// In-flight STEP download channel.
    step_rx: Option<Receiver<Result<String, String>>>,
    /// Embeddable store browser for choosing the save LOCATION.
    explorer: FileExplorer,
    /// Whether the first (blank-query) search has been kicked since opening.
    seeded: bool,
    /// Per-frame widget rects for the headed verifier.
    hits: HashMap<String, egui::Rect>,
}

impl Default for StepPartsPanel {
    fn default() -> Self {
        Self {
            open: false,
            view: View::Search,
            query: String::new(),
            page: 1,
            has_next: false,
            searching: false,
            status: String::new(),
            results: Vec::new(),
            search_rx: None,
            thumbs: HashMap::new(),
            thumb_rx: HashMap::new(),
            pending: None,
            dest_name: String::new(),
            pending_step: None,
            step_rx: None,
            explorer: FileExplorer::new(),
            seeded: false,
            hits: HashMap::new(),
        }
    }
}

impl StepPartsPanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Toolbar entry point: open the window (a blank-query first page is fetched
    /// on the first frame so the list is never empty on open).
    pub fn open(&mut self) {
        self.open = true;
        self.view = View::Search;
        self.seeded = false;
    }

    fn hit(&mut self, key: &str, resp: &egui::Response) {
        self.hits.insert(key.to_string(), resp.rect);
    }

    // --- search ---------------------------------------------------------------

    /// Kick a search for the current `query` at `page` (clears the previous
    /// page's results + thumbnails so no stale texture leaks across a query).
    fn start_search(&mut self, ctx: &egui::Context, page: u32) {
        self.page = page.max(1);
        self.searching = true;
        self.status = "searching…".into();
        self.results.clear();
        self.thumbs.clear();
        self.thumb_rx.clear();
        self.search_rx = Some(fetch_text(ctx, search_url(API_BASE, &self.query, self.page)));
    }

    /// Populate results from a raw search response body, then kick a thumbnail
    /// fetch per result. Split out so a test can inject a stub response.
    fn apply_search_response(&mut self, ctx: &egui::Context, body: &str) {
        match parse_search_response(body) {
            Ok((parts, has_next)) => {
                self.has_next = has_next;
                self.status = if parts.is_empty() {
                    "no matches".into()
                } else {
                    format!("{} result{}", parts.len(), if parts.len() == 1 { "" } else { "s" })
                };
                for part in &parts {
                    if !part.png_url.is_empty() {
                        self.thumbs.insert(part.id.clone(), ThumbState::Loading);
                        self.thumb_rx
                            .insert(part.id.clone(), fetch_bytes(ctx, part.png_url.clone()));
                    }
                }
                self.results = parts;
            }
            Err(err) => {
                self.status = format!("search failed: {err}");
                self.results.clear();
                self.has_next = false;
            }
        }
    }

    /// Drain any in-flight async replies (search, thumbnails, STEP download).
    fn poll(&mut self, ctx: &egui::Context) {
        if let Some(rx) = &self.search_rx {
            if let Ok(reply) = rx.try_recv() {
                self.search_rx = None;
                self.searching = false;
                match reply {
                    Ok(body) => self.apply_search_response(ctx, &body),
                    Err(err) => self.status = format!("search failed: {err}"),
                }
            }
        }
        // Thumbnails: collect ready/failed ids, then apply (avoid borrow overlap).
        let ready: Vec<(String, Result<Vec<u8>, String>)> = self
            .thumb_rx
            .iter()
            .filter_map(|(id, rx)| rx.try_recv().ok().map(|r| (id.clone(), r)))
            .collect();
        for (id, reply) in ready {
            self.thumb_rx.remove(&id);
            let state = match reply {
                Ok(bytes) => decode_thumbnail(ctx, &id, &bytes)
                    .map(ThumbState::Ready)
                    .unwrap_or(ThumbState::Failed),
                Err(_) => ThumbState::Failed,
            };
            self.thumbs.insert(id, state);
        }
        if let Some(rx) = &self.step_rx {
            if let Ok(reply) = rx.try_recv() {
                self.step_rx = None;
                match reply {
                    Ok(text) => {
                        if text.contains("ISO-10303-21") {
                            self.pending_step = Some(text);
                            self.status = "STEP downloaded — choose a location and save".into();
                        } else {
                            self.status = "download is not a STEP file".into();
                        }
                    }
                    Err(err) => self.status = format!("STEP download failed: {err}"),
                }
            }
        }
    }

    // --- import ---------------------------------------------------------------

    /// Begin importing `part`: switch to the Destination view, prefill the name
    /// with the STEP stem, and start downloading its STEP file.
    fn begin_import(&mut self, ctx: &egui::Context, part: PartItem) {
        self.dest_name = step_filename_stem(&part.step_url);
        self.pending_step = None;
        self.status = format!("downloading {}", self.dest_name);
        self.step_rx = Some(fetch_text(ctx, part.step_url.clone()));
        self.pending = Some(part);
        self.view = View::Destination;
    }

    /// Create the part document from `step_text`, write it to the store under
    /// `dest_name` at the current browser location (keeping the original
    /// filename), and add it to the assembly as an `ACOMP`. Returns the new
    /// feature id on success. The store WRITE happens first and its error is
    /// surfaced BEFORE any insert, per the advisor's ordering.
    ///
    /// Free of egui/network so the full write+insert path is unit-testable with
    /// an injected `step_text` + an in-memory store.
    fn import_step_text(
        state: &mut EngineState,
        store: &dyn ModelStore,
        dest_name: &str,
        step_text: &str,
    ) -> Result<String, String> {
        let document = build_part_document(step_text)?;
        // Write the part document to the chosen location first (the realistic
        // failure — e.g. a storage quota on a multi-MB STEP — surfaces here,
        // before we touch the assembly).
        let identity = store.browser_write(dest_name, &document)?;
        let display = model_display_name(&identity);
        let id = state
            .insert_component(ComponentInsert::New {
                name: &display,
                source_key: &identity,
                source_signature: &document_signature(&document),
                document_json: &document,
            })
            .map_err(|e| format!("add component failed: {e}"))?;
        Ok(id)
    }

    // --- rendering ------------------------------------------------------------

    /// Draw the window (if open) at ctx level. `store` is the destination for the
    /// saved part document.
    pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
        self.hits.clear();
        if !self.open {
            return;
        }
        self.poll(ctx);
        // Seed a first (blank-query) page so the dialog opens with content.
        if !self.seeded && !self.searching && self.results.is_empty() {
            self.seeded = true;
            self.start_search(ctx, 1);
        }

        let mut open = true;
        egui::Window::new("step.parts library")
            .id(egui::Id::new("brep-step-parts-window"))
            .open(&mut open)
            .movable(true)
            .resizable(true)
            .default_size([460.0, 520.0])
            .default_pos([820.0, 70.0])
            .show(ctx, |ui| match self.view {
                View::Search => self.search_view(ui, ctx),
                View::Destination => self.destination_view(ui, state, store),
            });
        self.open = open;
    }

    fn search_view(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
        ui.horizontal(|ui| {
            let field = ui.add(
                egui::TextEdit::singleline(&mut self.query)
                    .hint_text("Search parts (e.g. M3 screw, ISO 4762)…")
                    .desired_width(260.0),
            );
            self.hit("steplib:query", &field);
            let enter = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
            let search = ui.button("Search");
            self.hit("steplib:search", &search);
            if search.clicked() || enter {
                self.start_search(ctx, 1);
            }
        });
        ui.horizontal(|ui| {
            ui.weak(&self.status);
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let next = ui.add_enabled(self.has_next && !self.searching, egui::Button::new("Next ›"));
                self.hit("steplib:next", &next);
                if next.clicked() {
                    self.start_search(ctx, self.page + 1);
                }
                let prev = ui.add_enabled(self.page > 1 && !self.searching, egui::Button::new("‹ Prev"));
                self.hit("steplib:prev", &prev);
                if prev.clicked() {
                    self.start_search(ctx, self.page - 1);
                }
                ui.weak(format!("page {}", self.page));
            });
        });
        ui.separator();

        // Snapshot the ids/urls to act on AFTER the row loop (no borrow overlap
        // with `self.thumbs` reads during the loop).
        let mut chosen: Option<PartItem> = None;
        egui::ScrollArea::vertical()
            .auto_shrink([false, false])
            .show(ui, |ui| {
                if self.results.is_empty() && !self.searching {
                    ui.weak("No results. Try a different search.");
                }
                let results = self.results.clone();
                for part in &results {
                    ui.horizontal(|ui| {
                        // Thumbnail (or placeholder), fixed 56×56 box.
                        let size = egui::vec2(56.0, 56.0);
                        match self.thumbs.get(&part.id) {
                            Some(ThumbState::Ready(tex)) => {
                                ui.add(egui::Image::new(tex).fit_to_exact_size(size));
                            }
                            Some(ThumbState::Loading) => {
                                ui.add_sized(size, egui::Spinner::new());
                            }
                            _ => {
                                let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
                                ui.painter().rect_filled(
                                    rect,
                                    3.0,
                                    ui.visuals().extreme_bg_color,
                                );
                                ui.painter().text(
                                    rect.center(),
                                    egui::Align2::CENTER_CENTER,
                                    "STEP",
                                    egui::TextStyle::Small.resolve(ui.style()),
                                    ui.visuals().weak_text_color(),
                                );
                            }
                        }
                        ui.vertical(|ui| {
                            let row = ui.selectable_label(
                                false,
                                egui::RichText::new(&part.name).strong(),
                            );
                            self.hit(&format!("steplib:result:{}", part.id), &row);
                            if !part.category.is_empty() {
                                ui.weak(&part.category);
                            }
                            if !part.description.is_empty() {
                                ui.small(truncate(&part.description, 90));
                            }
                            let add = ui.button("Add to assembly");
                            self.hit(&format!("steplib:add:{}", part.id), &add);
                            if add.clicked() || row.double_clicked() {
                                chosen = Some(part.clone());
                            }
                        });
                    });
                    ui.separator();
                }
            });

        if let Some(part) = chosen {
            self.begin_import(ctx, part);
        }
    }

    fn destination_view(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        store: &dyn ModelStore,
    ) {
        let part_name = self
            .pending
            .as_ref()
            .map(|p| p.name.clone())
            .unwrap_or_default();
        ui.heading("Save part & add component");
        ui.weak(&part_name);
        ui.add_space(4.0);

        // Location picker — reuse the shared store explorer (navigation only;
        // the name is fixed to the STEP filename below).
        let options = FileExplorerOptions {
            hit_prefix: "steplib:dest",
            empty_label: "(no saved models here)",
            row_icon: "\u{1F5CE}",
            current: None,
            allow_delete: false,
            allow_import: false,
            import_label: "",
            import_hit: "steplib:dest:upload",
            show_cancel: false,
            confirm_label: None,
            extensions: &["BREP.json", "json"],
        };
        let output = self.explorer.show_store(ui, store, options);
        for (key, rect) in output.hits {
            self.hits.insert(key, rect);
        }

        ui.add_space(4.0);
        ui.label("File name (from the STEP file)");
        let field = ui.add(
            egui::TextEdit::singleline(&mut self.dest_name)
                .hint_text("part name")
                .desired_width(f32::INFINITY),
        );
        self.hit("steplib:dest-name", &field);

        if !self.status.is_empty() {
            ui.add_space(2.0);
            ui.weak(&self.status);
        }
        ui.add_space(6.0);

        let step_ready = self.pending_step.is_some();
        let name_ok = !self.dest_name.trim().is_empty();
        let mut do_import = false;
        let mut go_back = false;
        ui.horizontal(|ui| {
            let save = ui.add_enabled(
                step_ready && name_ok,
                egui::Button::new("Save & Add"),
            );
            self.hit("steplib:save", &save);
            if save.clicked() {
                do_import = true;
            }
            let back = ui.button("Back");
            self.hit("steplib:back", &back);
            if back.clicked() {
                go_back = true;
            }
            if !step_ready {
                ui.add(egui::Spinner::new());
                ui.weak("downloading…");
            }
        });

        if do_import {
            let step_text = self.pending_step.clone().unwrap_or_default();
            let dest = self.dest_name.trim().to_string();
            match Self::import_step_text(state, store, &dest, &step_text) {
                Ok(id) => {
                    self.status = format!("added {dest} ({id})");
                    self.pending = None;
                    self.pending_step = None;
                    self.view = View::Search;
                }
                Err(err) => self.status = err,
            }
        } else if go_back {
            self.pending = None;
            self.pending_step = None;
            self.step_rx = None;
            self.status.clear();
            self.view = View::Search;
        }
    }

    // --- verifier surface -----------------------------------------------------

    /// The window's logical state for the headed verifier (`__brepStepParts`).
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn state_json(&self) -> String {
        let results: Vec<Value> = self
            .results
            .iter()
            .map(|p| {
                serde_json::json!({
                    "id": p.id,
                    "name": p.name,
                    "category": p.category,
                    "hasThumb": matches!(self.thumbs.get(&p.id), Some(ThumbState::Ready(_))),
                })
            })
            .collect();
        let pending = self.pending.as_ref().map(|p| {
            serde_json::json!({
                "id": p.id,
                "name": p.name,
                "destName": self.dest_name,
                "stepReady": self.pending_step.is_some(),
            })
        });
        serde_json::json!({
            "open": self.open,
            "view": match self.view { View::Search => "search", View::Destination => "destination" },
            "query": self.query,
            "status": self.status,
            "searching": self.searching,
            "page": self.page,
            "hasNext": self.has_next,
            "resultCount": self.results.len(),
            "results": results,
            "pending": pending.unwrap_or(Value::Null),
        })
        .to_string()
    }

    /// Per-frame widget rects for the headed verifier (`__brepStepPartsHit`).
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, Value> = self
            .hits
            .iter()
            .map(|(k, r)| {
                (
                    k.clone(),
                    serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }
}

/// Clip `s` to `max` chars with an ellipsis (thumbnail-row description).
fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(max).collect();
        out.push('');
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::MemModelStore;

    #[test]
    fn search_url_encodes_query_and_page() {
        assert_eq!(
            search_url("https://api.step.parts/v1", "", 1),
            "https://api.step.parts/v1/parts?pageSize=24&page=1"
        );
        assert_eq!(
            search_url("https://api.step.parts/v1", "M3 screw", 2),
            "https://api.step.parts/v1/parts?pageSize=24&page=2&q=M3%20screw"
        );
        // Reserved chars (the `lengthMm 12` attribute-search idiom) encode.
        assert!(search_url("b", "ISO 4762", 1).ends_with("&q=ISO%204762"));
    }

    #[test]
    fn parse_search_response_reads_documented_fields() {
        let body = serde_json::json!({
            "items": [
                {
                    "id": "din913_set_screw_m3x3",
                    "name": "M3×3 Set Screw",
                    "description": "DIN 913 set screw.",
                    "category": "fastener",
                    "stepUrl": "https://media.example/catalog/step/din913_set_screw_m3x3.step",
                    "pngUrl": "https://blob.example/preview/png/din913-abc.png"
                }
            ],
            "hasNextPage": true
        })
        .to_string();
        let (parts, has_next) = parse_search_response(&body).unwrap();
        assert!(has_next);
        assert_eq!(parts.len(), 1);
        let p = &parts[0];
        assert_eq!(p.id, "din913_set_screw_m3x3");
        assert_eq!(p.name, "M3×3 Set Screw");
        assert_eq!(p.category, "fastener");
        assert!(p.step_url.ends_with("din913_set_screw_m3x3.step"));
        assert!(p.png_url.ends_with(".png"));
    }

    #[test]
    fn parse_search_response_surfaces_api_error_and_bad_body() {
        let err = parse_search_response(r#"{"error":"bad query"}"#).unwrap_err();
        assert!(err.contains("bad query"), "{err}");
        assert!(parse_search_response("not json").is_err());
        assert!(parse_search_response(r#"{"total":0}"#).is_err(), "missing items");
    }

    #[test]
    fn step_filename_stem_keeps_the_original_name() {
        assert_eq!(
            step_filename_stem(
                "https://media.githubusercontent.com/media/x/y/catalog/step/adafruit_5128_macropad.step"
            ),
            "adafruit_5128_macropad"
        );
        assert_eq!(step_filename_stem("a/b/PART_01.STP?token=zzz"), "PART_01");
        assert_eq!(step_filename_stem(""), "imported-part");
    }

    #[test]
    fn build_part_document_gates_non_step_and_embeds_step_text() {
        assert!(build_part_document("garbage").is_err(), "ISO gate refuses non-STEP");
        let step = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\nENDSEC;\nEND-ISO-10303-21;\n";
        let doc = build_part_document(step).unwrap();
        let v: Value = serde_json::from_str(&doc).unwrap();
        assert_eq!(v["features"][0]["type"], "IMPORT3D");
        assert_eq!(v["features"][0]["inputParams"]["stepText"], step);
    }

    /// The full store-write + component-add path with REAL STEP text (generated
    /// via the kernel's export→import round-trip, so the part actually builds and
    /// the insert never hits the native-abort error path). Proves the part
    /// document is persisted under the chosen name AND an ACOMP is appended.
    #[test]
    fn import_step_text_writes_part_and_adds_acomp() {
        brep_render::brep_kernel::clear_history_cache();
        let solid = brep_render::brep_kernel::make_box_brep(
            brep_render::brep_kernel::Vec3::new(0.0, 0.0, 0.0),
            4.0,
            3.0,
            2.0,
        )
        .expect("box");
        let step_text = brep_render::brep_kernel::export_step(
            &[solid],
            "part",
            "MM",
            "2026-01-01T00:00:00Z",
        )
        .expect("export step");

        let mut state = EngineState::new();
        let store = MemModelStore::new();
        let id =
            StepPartsPanel::import_step_text(&mut state, &store, "bracket", &step_text).unwrap();
        assert!(id.starts_with("ACOMP"), "returns the new ACOMP id: {id}");

        // The part document was persisted under the original name and embeds the
        // IMPORT3D feature with the STEP text.
        let saved = store.read("bracket").expect("part document written");
        let v: Value = serde_json::from_str(&saved).unwrap();
        assert_eq!(v["features"][0]["type"], "IMPORT3D");
        assert!(v["features"][0]["inputParams"]["stepText"]
            .as_str()
            .unwrap()
            .contains("ISO-10303-21"));

        // The assembly now carries exactly one ACOMP referencing the part.
        let doc: Value = serde_json::from_str(&state.history_request_json()).unwrap();
        let acomps: Vec<&Value> = doc["features"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|f| f["type"] == "ACOMP")
            .collect();
        assert_eq!(acomps.len(), 1, "one component added");
        assert!(doc["partsLibrary"].as_object().unwrap().len() >= 1, "library entry seeded");
    }

    #[test]
    fn state_json_reports_view_and_pending() {
        let mut panel = StepPartsPanel::new();
        panel.open();
        let s: Value = serde_json::from_str(&panel.state_json()).unwrap();
        assert_eq!(s["open"], true);
        assert_eq!(s["view"], "search");
        assert_eq!(s["resultCount"], 0);
        assert_eq!(s["pending"], Value::Null);
    }
}