BREP_app 0.1.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
//! The storage / filesystem seam — the ONE platform exception in the
//! engine-native UI (see `engine-native-ui-design.md`). Everything else in the
//! UI is platform-agnostic egui; only persistence differs by platform, so it
//! goes through this trait with two `#[cfg]`-gated impls:
//!
//! * **Desktop** → a small config file under the OS config dir.
//! * **Browser** → `localStorage` via `web_sys`.
//!
//! This slice uses it for settings persistence (`key = "settings"`, `val =` the
//! full `RenderSettings::to_json()`). Model save/load + import/export will cross
//! the SAME trait in a later slice.

/// A minimal key→string blob store. Keys are short, filesystem-safe slugs.
pub trait Store {
    /// Load a previously-saved value, or `None` if absent/unreadable.
    fn load(&self, key: &str) -> Option<String>;
    /// Persist a value under `key`, overwriting any prior value. Best-effort:
    /// a failure is swallowed (persistence is a convenience, not correctness).
    fn save(&self, key: &str, val: &str);
}

/// Construct the platform's default store. The ONLY platform-specific
/// construction in the app — the trait object it returns is used identically on
/// web and desktop.
pub fn default_store() -> Box<dyn Store> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        Box::new(native::FileStore::new())
    }
    #[cfg(target_arch = "wasm32")]
    {
        Box::new(web::LocalStore)
    }
}

// --- Desktop: a config file ----------------------------------------------------
#[cfg(not(target_arch = "wasm32"))]
mod native {
    use super::Store;
    use std::path::PathBuf;

    /// Persist each key as `<config>/brep-app/<key>.json`. `<config>` is
    /// `$XDG_CONFIG_HOME`, else `$HOME/.config`, else the current dir — a sane
    /// default without pulling in a directories crate.
    pub struct FileStore {
        dir: PathBuf,
    }

    impl FileStore {
        pub fn new() -> Self {
            let base = std::env::var_os("XDG_CONFIG_HOME")
                .map(PathBuf::from)
                .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
                .unwrap_or_else(|| PathBuf::from("."));
            Self {
                dir: base.join("brep-app"),
            }
        }

        /// Filesystem-safe path for a key (keys are our own short slugs, but be
        /// defensive against separators).
        fn path(&self, key: &str) -> PathBuf {
            let safe: String = key
                .chars()
                .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
                .collect();
            self.dir.join(format!("{safe}.json"))
        }
    }

    impl Store for FileStore {
        fn load(&self, key: &str) -> Option<String> {
            std::fs::read_to_string(self.path(key)).ok()
        }

        fn save(&self, key: &str, val: &str) {
            let _ = std::fs::create_dir_all(&self.dir);
            let _ = std::fs::write(self.path(key), val);
        }
    }
}

// --- Browser: localStorage -----------------------------------------------------
#[cfg(target_arch = "wasm32")]
mod web {
    use super::Store;

    /// `window.localStorage`-backed store. Keys are namespaced so they can't
    /// collide with anything else on the origin.
    pub struct LocalStore;

    impl LocalStore {
        fn storage() -> Option<web_sys::Storage> {
            web_sys::window()?.local_storage().ok()?
        }
        fn namespaced(key: &str) -> String {
            format!("brep-app:{key}")
        }
    }

    impl Store for LocalStore {
        fn load(&self, key: &str) -> Option<String> {
            Self::storage()?.get_item(&Self::namespaced(key)).ok()?
        }

        fn save(&self, key: &str, val: &str) {
            if let Some(storage) = Self::storage() {
                let _ = storage.set_item(&Self::namespaced(key), val);
            }
        }
    }
}

// =============================================================================
// Model documents — the OTHER half of the storage seam
// =============================================================================
//
// The `Store` above is a settings key→value blob. A MODEL is a whole document
// (the engine-owned `HistoryRequest` JSON — one `.BREP.json` recipe), and the
// file panel needs to *enumerate*, read, and write NAMED documents, plus (in the
// browser) hand a file to / take a file from the user's real filesystem. That is
// a different shape than key/value, so it gets its OWN trait, still with the two
// `#[cfg]`-gated platform impls behind it (the storage seam is the ONE platform
// exception — see `engine-native-ui-design.md`).
//
// The trait is deliberately a **named-document CRUD** (`list` / `read` / `write`
// / `remove`) plus a poll-based **file-interchange** side-channel. That shape is
// exactly what a later **GitHub backend** needs: `list` = a repo directory
// listing, `read` = fetch a file's contents, `write` = create/update (commit)
// a file, `remove` = delete a file — the model name is the path within the repo.
// An async backend (GitHub over HTTP, or the browser File System Access API /
// OPFS whose main-thread API is async) slots in behind the SAME trait by driving
// its request on a background task and surfacing the result through the
// `begin_import` → `take_import` poll pattern used here for uploads, so the
// synchronous panel code never changes. GitHub itself is a deferred follow-up;
// this lands the seam it plugs into.

/// A store of NAMED model documents — the model-file half of the storage seam
/// (distinct from the settings key/value [`Store`]). All methods take `&self`
/// (any per-backend mutable state — the browser's upload stash — lives behind
/// interior mutability) so the app can hold one `Box<dyn ModelStore>` and hand
/// panels a shared `&dyn ModelStore`, exactly like [`Store`].
pub trait ModelStore {
    /// A short human label of where documents persist, for the panel header
    /// (e.g. `"filesystem: ~/.config/brep-app/models"` or `"browser storage"`).
    fn backend_label(&self) -> String;

    /// The names of the documents currently available to **Open** (bare names,
    /// no extension). May be empty on a backend that cannot enumerate — then the
    /// panel falls back to the name field / import.
    fn list(&self) -> Vec<String>;

    /// Read a stored document by name, or `None` if absent/unreadable.
    fn read(&self, name: &str) -> Option<String>;

    /// Create or overwrite the document `name` with `contents`. `Err` carries a
    /// message the panel surfaces in its status line.
    fn write(&self, name: &str, contents: &str) -> Result<(), String>;

    /// Delete the document `name` (best-effort; `Ok` if it is already gone).
    fn remove(&self, name: &str) -> Result<(), String>;

    // --- real-file interchange (the platform "fallback") ----------------------
    // The browser cannot silently write to an arbitrary path, and a headless
    // native box has no dialog; these let the panel move a document to/from the
    // user's REAL filesystem where the platform supports it. Default: unsupported.

    /// Whether this backend can exchange files with the user's real filesystem
    /// (browser download+upload, or a native file dialog). The panel shows the
    /// Download / Import affordances only when this is `true`.
    fn supports_file_interchange(&self) -> bool {
        false
    }

    /// Hand `contents` to the user as a file named after `name` (browser: a
    /// download; native w/ dialog: a Save-As). Returns the saved document's
    /// identity — the full path the user chose on native (so the caller can
    /// re-save straight to it), the bare download name on the web — or `None`
    /// when the user cancelled. No-op (`None`) by default.
    fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
        let _ = (name, contents);
        Ok(None)
    }

    /// Begin importing a real file — opens the platform picker. The result is
    /// retrieved later via [`Self::take_import`] (upload/read is async in the
    /// browser). No-op by default.
    fn begin_import(&self) -> Result<(), String> {
        Ok(())
    }

    /// Poll for a completed import as `(suggested_name, contents)`, consuming it.
    /// `None` until a `begin_import` finishes. Default: never any.
    fn take_import(&self) -> Option<(String, String)> {
        None
    }

    // --- format-typed interchange (STEP / STL) --------------------------------
    // The model lanes above trade the `.BREP.json` recipe; import/export of a
    // foreign format (STEP text, ASCII STL) needs a DIFFERENT picker filter and
    // must NOT mangle the file extension. These two methods add that lane while
    // leaving the model lanes byte-for-byte. They share the SAME `take_import`
    // pickup channel — the panel routes the result by its filename extension.

    /// Begin importing a real file behind a specific picker `filter` (a human
    /// label + dot-less extensions, e.g. `("STEP", &["step","stp"])`). The chosen
    /// file's contents + its FULL name (extension preserved, so the panel can
    /// route it) arrive via [`Self::take_import`]. Default: reuse [`Self::begin_import`].
    fn begin_import_filtered(&self, _filter: (&str, &[&str])) -> Result<(), String> {
        self.begin_import()
    }

    /// Hand `contents` to the user under EXACTLY `file_name` (extension included,
    /// no model-extension munging) — the Save-As / download for a foreign export
    /// format. Default no-op (interchange unsupported).
    fn export_file_named(&self, _file_name: &str, _contents: &str) -> Result<(), String> {
        Ok(())
    }
}

/// Construct the platform's default model-document store — the sibling of
/// [`default_store`] for whole model files.
pub fn default_model_store() -> Box<dyn ModelStore> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        Box::new(native_model::FileModelStore::new())
    }
    #[cfg(target_arch = "wasm32")]
    {
        Box::new(web_model::LocalModelStore::new())
    }
}

/// The document extension for a model recipe (`<name>.BREP.json`).
pub const MODEL_EXT: &str = ".BREP.json";

/// Test-only: a native model store rooted at an explicit directory (a temp dir
/// in tests) so a round-trip test never touches the real config dir.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub fn native_test_store(dir: std::path::PathBuf) -> Box<dyn ModelStore> {
    Box::new(native_model::FileModelStore::with_dir(dir))
}

/// Strip the model extension (and any directory) from a filename to get the
/// bare display name — shared by both platform impls (and the file panel, which
/// shows the bare name while keeping the raw identity for re-saves).
pub(crate) fn model_display_name(file_name: &str) -> String {
    let base = file_name
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(file_name);
    base.strip_suffix(MODEL_EXT)
        .or_else(|| base.strip_suffix(".json"))
        .unwrap_or(base)
        .to_string()
}

// --- Desktop: a models directory (+ optional native file dialog) ---------------
#[cfg(not(target_arch = "wasm32"))]
mod native_model {
    use super::{model_display_name, ModelStore, MODEL_EXT};
    use std::path::PathBuf;

    /// Persist each model as `<config>/brep-app/models/<name>.BREP.json`, using
    /// the same config-dir resolution as the settings [`super::native::FileStore`]
    /// so both halves of the seam live together. Enumerable (for the Open list)
    /// and unit-testable without a display.
    ///
    /// With the (default-on) `native-dialog` cargo feature, Open / Save As /
    /// Import / Export drive a real `rfd` OS file dialog against the real
    /// filesystem; built with `--no-default-features` (the lean headless gate)
    /// file interchange is off and the panel uses the name field + the
    /// models-dir listing instead. Test stores ([`Self::with_dir`]) never open
    /// dialogs either way, keeping the suite headless.
    pub struct FileModelStore {
        dir: PathBuf,
        /// Whether this store may open OS dialogs: `true` for the real app store
        /// ([`Self::new`]), `false` for test stores ([`Self::with_dir`]). Only
        /// read by the `native-dialog` paths — hence the conditional allow.
        #[cfg_attr(not(feature = "native-dialog"), allow(dead_code))]
        dialogs: bool,
        /// A dialog-imported document awaiting pickup (only ever set by the
        /// `native-dialog` path). `RefCell` keeps the trait `&self`. Unread when
        /// the feature is off — hence the conditional allow.
        #[cfg_attr(not(feature = "native-dialog"), allow(dead_code))]
        pending: std::cell::RefCell<Option<(String, String)>>,
    }

    impl FileModelStore {
        pub fn new() -> Self {
            let base = std::env::var_os("XDG_CONFIG_HOME")
                .map(PathBuf::from)
                .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
                .unwrap_or_else(|| PathBuf::from("."));
            Self {
                dir: base.join("brep-app").join("models"),
                dialogs: true,
                pending: std::cell::RefCell::new(None),
            }
        }

        /// A store rooted at an explicit directory — used by the round-trip test.
        /// Never opens dialogs, so the tests stay headless (and keep exercising
        /// the egui-modal fallback path).
        #[cfg_attr(not(test), allow(dead_code))]
        pub fn with_dir(dir: PathBuf) -> Self {
            Self {
                dir,
                dialogs: false,
                pending: std::cell::RefCell::new(None),
            }
        }

        /// Resolve a name to a path. A name containing a path separator is taken
        /// as an explicit path (e.g. one an `rfd` dialog returned); a bare name
        /// maps to `<dir>/<sanitized>.BREP.json`.
        fn resolve(&self, name: &str) -> PathBuf {
            if name.contains('/') || name.contains('\\') {
                return PathBuf::from(name);
            }
            let safe: String = name
                .strip_suffix(MODEL_EXT)
                .unwrap_or(name)
                .chars()
                .map(|c| {
                    if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                        c
                    } else {
                        '_'
                    }
                })
                .collect();
            self.dir.join(format!("{safe}{MODEL_EXT}"))
        }
    }

    impl ModelStore for FileModelStore {
        fn backend_label(&self) -> String {
            format!("filesystem: {}", self.dir.display())
        }

        fn list(&self) -> Vec<String> {
            let mut names: Vec<String> = std::fs::read_dir(&self.dir)
                .into_iter()
                .flatten()
                .flatten()
                .filter_map(|entry| {
                    let name = entry.file_name().to_string_lossy().into_owned();
                    name.ends_with(MODEL_EXT).then(|| model_display_name(&name))
                })
                .collect();
            names.sort();
            names
        }

        fn read(&self, name: &str) -> Option<String> {
            std::fs::read_to_string(self.resolve(name)).ok()
        }

        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            let path = self.resolve(name);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| format!("create models dir: {e}"))?;
            }
            std::fs::write(&path, contents).map_err(|e| format!("write {}: {e}", path.display()))
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            match std::fs::remove_file(self.resolve(name)) {
                Ok(()) => Ok(()),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                Err(e) => Err(format!("remove: {e}")),
            }
        }

        // File interchange is available only when built with a native dialog
        // (and never on a test store).
        #[cfg(feature = "native-dialog")]
        fn supports_file_interchange(&self) -> bool {
            self.dialogs
        }

        #[cfg(feature = "native-dialog")]
        fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
            if !self.dialogs {
                return Ok(None);
            }
            let Some(mut path) = rfd::FileDialog::new()
                .set_file_name(format!("{}{MODEL_EXT}", model_display_name(name)))
                .add_filter("BREP model", &["BREP.json", "json"])
                .save_file()
            else {
                return Ok(None); // user cancelled
            };
            // An extension-less chosen name would be invisible to Open's filter
            // and `list()` — normalize it to the model extension.
            if !path.to_string_lossy().to_ascii_lowercase().ends_with(".json") {
                path = PathBuf::from(format!("{}{MODEL_EXT}", path.display()));
            }
            std::fs::write(&path, contents)
                .map_err(|e| format!("write {}: {e}", path.display()))?;
            Ok(Some(path.display().to_string()))
        }

        #[cfg(feature = "native-dialog")]
        fn begin_import(&self) -> Result<(), String> {
            if !self.dialogs {
                return Ok(());
            }
            if let Some(path) = rfd::FileDialog::new()
                .add_filter("BREP model", &["BREP.json", "json"])
                .pick_file()
            {
                let contents =
                    std::fs::read_to_string(&path).map_err(|e| format!("read: {e}"))?;
                // Stash the FULL path as the document identity so a later plain
                // Save writes back to the file that was opened (`resolve()`
                // treats a separator-bearing name as an explicit path).
                *self.pending.borrow_mut() = Some((path.display().to_string(), contents));
            }
            Ok(())
        }

        #[cfg(feature = "native-dialog")]
        fn take_import(&self) -> Option<(String, String)> {
            self.pending.borrow_mut().take()
        }

        // Format-typed interchange: an rfd picker with the given filter; the FULL
        // file name (extension kept) is stashed so the panel routes by extension.
        #[cfg(feature = "native-dialog")]
        fn begin_import_filtered(&self, filter: (&str, &[&str])) -> Result<(), String> {
            if !self.dialogs {
                return Ok(());
            }
            let (label, extensions) = filter;
            if let Some(path) = rfd::FileDialog::new()
                .add_filter(label, extensions)
                .pick_file()
            {
                let contents =
                    std::fs::read_to_string(&path).map_err(|e| format!("read: {e}"))?;
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| path.to_string_lossy().into_owned());
                *self.pending.borrow_mut() = Some((name, contents));
            }
            Ok(())
        }

        #[cfg(feature = "native-dialog")]
        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            if !self.dialogs {
                return Ok(());
            }
            if let Some(path) = rfd::FileDialog::new().set_file_name(file_name).save_file() {
                std::fs::write(&path, contents)
                    .map_err(|e| format!("write {}: {e}", path.display()))
            } else {
                Ok(()) // user cancelled
            }
        }
    }
}

// --- Browser: localStorage documents + download / upload interchange -----------
#[cfg(target_arch = "wasm32")]
mod web_model {
    use super::{model_display_name, ModelStore, MODEL_EXT};
    use std::cell::RefCell;
    use wasm_bindgen::prelude::*;
    use wasm_bindgen::JsCast;

    // The origin-private persistent store on the web is `localStorage` (keys
    // `brep-app:model:<name>`): synchronous, enumerable, works on eframe's main
    // thread AND headless — unlike OPFS (async-only on the main thread) and the
    // File System Access API (needs a permission gesture that fails headless).
    // It plays the exact "origin-private document store" role and matches the
    // settings `Store` precedent; **download + upload** below bridge to the
    // user's REAL filesystem for portability.
    const PREFIX: &str = "brep-app:model:";

    thread_local! {
        /// The single hidden `<input type=file>`, created once and reused.
        static IMPORT_INPUT: RefCell<Option<web_sys::HtmlInputElement>> = const { RefCell::new(None) };
        /// The most recent completed upload, awaiting the panel's poll.
        static IMPORTED: RefCell<Option<(String, String)>> = const { RefCell::new(None) };
    }

    pub struct LocalModelStore;

    impl LocalModelStore {
        pub fn new() -> Self {
            Self
        }

        fn storage() -> Option<web_sys::Storage> {
            web_sys::window()?.local_storage().ok()?
        }

        fn key(name: &str) -> String {
            format!("{PREFIX}{}", model_display_name(name))
        }

        /// Lazily create the reusable hidden file input, wiring its `change`
        /// handler (which reads the chosen file and stashes it for `take_import`).
        /// `accept` is (re)applied every call so the picker's filter matches the
        /// current lane (the `.BREP.json` model lane vs. a `.step` import lane).
        fn ensure_input(accept: &str) -> Option<web_sys::HtmlInputElement> {
            if let Some(existing) = IMPORT_INPUT.with(|c| c.borrow().clone()) {
                existing.set_accept(accept);
                return Some(existing);
            }
            let document = web_sys::window()?.document()?;
            let input: web_sys::HtmlInputElement =
                document.create_element("input").ok()?.dyn_into().ok()?;
            input.set_type("file");
            input.set_accept(accept);
            input.set_hidden(true);

            // On change: read files[0] as text; on the reader's load, stash it.
            let input_for_cb = input.clone();
            let onchange = Closure::wrap(Box::new(move |_e: web_sys::Event| {
                let Some(files) = input_for_cb.files() else { return };
                let Some(file) = files.get(0) else { return };
                let name = file.name();
                let Ok(reader) = web_sys::FileReader::new() else { return };
                let reader_for_load = reader.clone();
                let onload = Closure::wrap(Box::new(move |_e: web_sys::Event| {
                    if let Some(text) = reader_for_load.result().ok().and_then(|v| v.as_string())
                    {
                        IMPORTED
                            .with(|c| *c.borrow_mut() = Some((model_display_name(&name), text)));
                    }
                }) as Box<dyn FnMut(web_sys::Event)>);
                reader.set_onload(Some(onload.as_ref().unchecked_ref()));
                // One small per-import leak (the app runs for the page lifetime).
                onload.forget();
                let _ = reader.read_as_text(&file);
            }) as Box<dyn FnMut(web_sys::Event)>);
            input.set_onchange(Some(onchange.as_ref().unchecked_ref()));
            onchange.forget(); // created once — leak is bounded

            if let Some(body) = document.body() {
                let _ = body.append_child(&input);
            }
            IMPORT_INPUT.with(|c| *c.borrow_mut() = Some(input.clone()));
            Some(input)
        }
    }

    impl ModelStore for LocalModelStore {
        fn backend_label(&self) -> String {
            "browser storage (localStorage) · download/upload for files".into()
        }

        fn list(&self) -> Vec<String> {
            let Some(storage) = Self::storage() else {
                return Vec::new();
            };
            let mut names = Vec::new();
            let len = storage.length().unwrap_or(0);
            for i in 0..len {
                if let Ok(Some(key)) = storage.key(i) {
                    if let Some(rest) = key.strip_prefix(PREFIX) {
                        names.push(rest.to_string());
                    }
                }
            }
            names.sort();
            names
        }

        fn read(&self, name: &str) -> Option<String> {
            Self::storage()?.get_item(&Self::key(name)).ok()?
        }

        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            let storage = Self::storage().ok_or("no localStorage")?;
            storage
                .set_item(&Self::key(name), contents)
                .map_err(|_| "localStorage write failed (quota?)".to_string())
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            if let Some(storage) = Self::storage() {
                let _ = storage.remove_item(&Self::key(name));
            }
            Ok(())
        }

        fn supports_file_interchange(&self) -> bool {
            true
        }

        /// Offer the document to the user as a `<name>.BREP.json` download via a
        /// Blob object-URL + a synthetic anchor click. The returned identity is
        /// the bare name (the browser owns where the download lands).
        fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
            let document = web_sys::window()
                .and_then(|w| w.document())
                .ok_or("no document")?;
            let parts = js_sys::Array::of1(&JsValue::from_str(contents));
            let options = web_sys::BlobPropertyBag::new();
            options.set_type("application/json");
            let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &options)
                .map_err(|_| "blob create failed".to_string())?;
            let url = web_sys::Url::create_object_url_with_blob(&blob)
                .map_err(|_| "object url failed".to_string())?;
            let anchor: web_sys::HtmlAnchorElement = document
                .create_element("a")
                .map_err(|_| "anchor create failed".to_string())?
                .dyn_into()
                .map_err(|_| "anchor cast failed".to_string())?;
            anchor.set_href(&url);
            anchor.set_download(&format!("{}{MODEL_EXT}", model_display_name(name)));
            anchor.click();
            let _ = web_sys::Url::revoke_object_url(&url);
            Ok(Some(model_display_name(name)))
        }

        fn begin_import(&self) -> Result<(), String> {
            let input = Self::ensure_input(".json,.BREP.json,application/json")
                .ok_or("file input unavailable")?;
            // Clear so re-selecting the same file still fires `change`.
            input.set_value("");
            input.click();
            Ok(())
        }

        fn take_import(&self) -> Option<(String, String)> {
            IMPORTED.with(|c| c.borrow_mut().take())
        }

        // Format-typed interchange: the same hidden input, refiltered to the
        // requested extensions. The onchange handler stashes the file's real name
        // (its extension survives `model_display_name`, since that only strips
        // `.json` / `.BREP.json`), so the panel routes STEP imports by extension.
        fn begin_import_filtered(&self, filter: (&str, &[&str])) -> Result<(), String> {
            let accept = filter
                .1
                .iter()
                .map(|ext| format!(".{ext}"))
                .collect::<Vec<_>>()
                .join(",");
            let input = Self::ensure_input(&accept).ok_or("file input unavailable")?;
            input.set_value("");
            input.click();
            Ok(())
        }

        /// Offer `contents` as a download under EXACTLY `file_name` (extension
        /// kept) — the foreign-format sibling of [`Self::export_file`].
        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            let document = web_sys::window()
                .and_then(|w| w.document())
                .ok_or("no document")?;
            let parts = js_sys::Array::of1(&JsValue::from_str(contents));
            let options = web_sys::BlobPropertyBag::new();
            options.set_type("application/octet-stream");
            let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &options)
                .map_err(|_| "blob create failed".to_string())?;
            let url = web_sys::Url::create_object_url_with_blob(&blob)
                .map_err(|_| "object url failed".to_string())?;
            let anchor: web_sys::HtmlAnchorElement = document
                .create_element("a")
                .map_err(|_| "anchor create failed".to_string())?
                .dyn_into()
                .map_err(|_| "anchor cast failed".to_string())?;
            anchor.set_href(&url);
            anchor.set_download(file_name);
            anchor.click();
            let _ = web_sys::Url::revoke_object_url(&url);
            Ok(())
        }
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::native_model::FileModelStore;
    use super::ModelStore;

    #[test]
    fn native_model_store_round_trips_named_documents() {
        let dir = std::env::temp_dir().join(format!("brep-app-models-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = FileModelStore::with_dir(dir.clone());

        // Empty to start.
        assert!(store.list().is_empty());
        assert_eq!(store.read("missing"), None);

        // Write two documents, read them back verbatim, and enumerate by name.
        let doc_a = r#"{"features":[{"type":"P.CU"}]}"#;
        let doc_b = r#"{"features":[]}"#;
        store.write("alpha", doc_a).unwrap();
        store.write("beta", doc_b).unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some(doc_a));
        assert_eq!(store.read("beta").as_deref(), Some(doc_b));
        assert_eq!(store.list(), vec!["alpha".to_string(), "beta".to_string()]);

        // The `.BREP.json` extension is transparent to the name.
        assert_eq!(store.read("alpha.BREP.json").as_deref(), Some(doc_a));

        // Overwrite + remove.
        store.write("alpha", doc_b).unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some(doc_b));
        store.remove("alpha").unwrap();
        assert_eq!(store.read("alpha"), None);
        assert_eq!(store.list(), vec!["beta".to_string()]);
        store.remove("alpha").unwrap(); // removing an absent doc is Ok

        let _ = std::fs::remove_dir_all(&dir);
    }
}