luminol_web/
lib.rs

1// Copyright (C) 2024 Melody Madeline Lyons
2//
3// This file is part of Luminol.
4//
5// Luminol is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Luminol is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Luminol.  If not, see <http://www.gnu.org/licenses/>.
17
18#[cfg(target_arch = "wasm32")]
19pub mod bindings;
20
21#[cfg(target_arch = "wasm32")]
22use std::future::IntoFuture;
23
24#[cfg(target_arch = "wasm32")]
25pub use indexed_db_futures::prelude::IdbTransactionMode;
26
27#[cfg(target_arch = "wasm32")]
28pub use indexed_db_futures::IdbQuerySource;
29
30#[cfg(target_arch = "wasm32")]
31use indexed_db_futures::prelude::*;
32
33#[cfg(target_arch = "wasm32")]
34/// Helper function for performing IndexedDB operations on an `IdbObjectStore` with a given
35/// `IdbTransactionMode`.
36pub async fn idb<R>(
37    store_name: &str,
38    mode: IdbTransactionMode,
39    f: impl FnOnce(IdbObjectStore<'_>) -> std::result::Result<R, web_sys::DomException>,
40) -> std::result::Result<R, web_sys::DomException> {
41    let mut db_req = IdbDatabase::open_u32("astrabit.luminol", 2)?;
42
43    db_req.set_on_upgrade_needed(Some(|e: &IdbVersionChangeEvent| {
44        if !e
45            .db()
46            .object_store_names()
47            .any(|n| n == "filesystem.dir_handles")
48        {
49            e.db().create_object_store("filesystem.dir_handles")?;
50        }
51
52        if !e.db().object_store_names().any(|n| n == "eframe.storage") {
53            e.db().create_object_store("eframe.storage")?;
54        }
55
56        Ok(())
57    }));
58
59    let db = db_req.into_future().await?;
60    let tx = db.transaction_on_one_with_mode(store_name, mode)?;
61    let store = tx.object_store(store_name)?;
62    let r = f(store);
63    tx.await.into_result()?;
64    r
65}