2023-07-14 22:43:19 +01:00
|
|
|
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))]
|
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
use crate::core::MaybeRwSignal;
|
2023-06-10 00:57:35 +01:00
|
|
|
use crate::utils::{CloneableFn, CloneableFnWithArg, FilterOptions};
|
|
|
|
use crate::{
|
|
|
|
filter_builder_methods, use_event_listener, watch_pausable_with_options, DebounceOptions,
|
|
|
|
ThrottleOptions, WatchOptions, WatchPausableReturn,
|
|
|
|
};
|
2023-07-14 22:43:19 +01:00
|
|
|
use cfg_if::cfg_if;
|
2023-06-10 00:57:35 +01:00
|
|
|
use default_struct_builder::DefaultBuilder;
|
|
|
|
use js_sys::Reflect;
|
|
|
|
use leptos::*;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use serde_json::Error;
|
|
|
|
use std::time::Duration;
|
|
|
|
use wasm_bindgen::{JsCast, JsValue};
|
|
|
|
|
2023-06-23 22:04:16 +01:00
|
|
|
pub use crate::core::StorageType;
|
|
|
|
|
2023-06-10 00:57:35 +01:00
|
|
|
const CUSTOM_STORAGE_EVENT_NAME: &str = "leptos-use-storage";
|
|
|
|
|
2023-06-10 03:19:00 +01:00
|
|
|
/// Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) / [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
|
2023-06-10 00:57:35 +01:00
|
|
|
///
|
|
|
|
/// ## Demo
|
|
|
|
///
|
|
|
|
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_storage)
|
|
|
|
///
|
|
|
|
/// ## Usage
|
|
|
|
///
|
|
|
|
/// It returns a triplet `(read_signal, write_signal, delete_from_storage_func)` of type `(ReadSignal<T>, WriteSignal<T>, Fn())`.
|
|
|
|
///
|
2023-06-10 01:52:21 +01:00
|
|
|
/// Values are (de-)serialized to/from JSON using [`serde`](https://serde.rs/).
|
|
|
|
///
|
2023-06-10 00:57:35 +01:00
|
|
|
/// ```
|
|
|
|
/// # use leptos::*;
|
|
|
|
/// # use leptos_use::storage::{StorageType, use_storage, use_storage_with_options, UseStorageOptions};
|
|
|
|
/// # use serde::{Deserialize, Serialize};
|
|
|
|
/// #
|
|
|
|
/// #[derive(Serialize, Deserialize, Clone)]
|
|
|
|
/// pub struct MyState {
|
|
|
|
/// pub hello: String,
|
|
|
|
/// pub greeting: String,
|
|
|
|
/// }
|
|
|
|
///
|
2023-07-27 18:06:36 +01:00
|
|
|
/// # pub fn Demo() -> impl IntoView {
|
2023-06-10 00:57:35 +01:00
|
|
|
/// // bind struct. Must be serializable.
|
|
|
|
/// let (state, set_state, _) = use_storage(
|
|
|
|
/// "my-state",
|
|
|
|
/// MyState {
|
|
|
|
/// hello: "hi".to_string(),
|
|
|
|
/// greeting: "Hello".to_string()
|
|
|
|
/// },
|
|
|
|
/// ); // returns Signal<MyState>
|
|
|
|
///
|
|
|
|
/// // bind bool.
|
2023-07-27 18:06:36 +01:00
|
|
|
/// let (flag, set_flag, remove_flag) = use_storage("my-flag", true); // returns Signal<bool>
|
2023-06-10 00:57:35 +01:00
|
|
|
///
|
|
|
|
/// // bind number
|
2023-07-27 18:06:36 +01:00
|
|
|
/// let (count, set_count, _) = use_storage("my-count", 0); // returns Signal<i32>
|
2023-06-10 00:57:35 +01:00
|
|
|
///
|
|
|
|
/// // bind string with SessionStorage
|
|
|
|
/// let (id, set_id, _) = use_storage_with_options(
|
|
|
|
/// "my-id",
|
|
|
|
/// "some_string_id".to_string(),
|
|
|
|
/// UseStorageOptions::default().storage_type(StorageType::Session),
|
|
|
|
/// );
|
2023-07-27 18:06:36 +01:00
|
|
|
/// # view! { }
|
2023-06-10 00:57:35 +01:00
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ## Merge Defaults
|
|
|
|
///
|
|
|
|
/// By default, [`use_storage`] will use the value from storage if it is present and ignores the default value.
|
|
|
|
/// Be aware that when you add more properties to the default value, the key might be `None`
|
|
|
|
/// (in the case of an `Option<T>` field) if client's storage does not have that key
|
|
|
|
/// or deserialization might fail altogether.
|
|
|
|
///
|
|
|
|
/// Let's say you had a struct `MyState` that has been saved to storage
|
|
|
|
///
|
|
|
|
/// ```ignore
|
|
|
|
/// #[derive(Serialize, Deserialize, Clone)]
|
|
|
|
/// struct MyState {
|
|
|
|
/// hello: String,
|
|
|
|
/// }
|
|
|
|
///
|
2023-07-27 18:06:36 +01:00
|
|
|
/// let (state, .. ) = use_storage("my-state", MyState { hello: "hello" });
|
2023-06-10 00:57:35 +01:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Now, in a newer version you added a field `greeting` to `MyState`.
|
|
|
|
///
|
|
|
|
/// ```ignore
|
|
|
|
/// #[derive(Serialize, Deserialize, Clone)]
|
|
|
|
/// struct MyState {
|
|
|
|
/// hello: String,
|
|
|
|
/// greeting: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// let (state, .. ) = use_storage(
|
|
|
|
/// "my-state",
|
|
|
|
/// MyState { hello: "hi", greeting: "whatsup" },
|
|
|
|
/// ); // fails to deserialize -> default value
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// This will fail to deserialize the stored string `{"hello": "hello"}` because it has no field `greeting`.
|
|
|
|
/// Hence it just uses the new default value provided and the previously saved value is lost.
|
|
|
|
///
|
|
|
|
/// To mitigate that you can provide a `merge_defaults` option. This is a pure function pointer
|
|
|
|
/// that takes the serialized (to json) stored value and the default value as arguments
|
|
|
|
/// and should return the serialized merged value.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use leptos::*;
|
|
|
|
/// # use leptos_use::storage::{use_storage_with_options, UseStorageOptions};
|
|
|
|
/// # use serde::{Deserialize, Serialize};
|
|
|
|
/// #
|
|
|
|
/// #[derive(Serialize, Deserialize, Clone)]
|
|
|
|
/// pub struct MyState {
|
|
|
|
/// pub hello: String,
|
|
|
|
/// pub greeting: String,
|
|
|
|
/// }
|
|
|
|
/// #
|
2023-07-27 18:06:36 +01:00
|
|
|
/// # pub fn Demo() -> impl IntoView {
|
2023-06-10 00:57:35 +01:00
|
|
|
/// let (state, set_state, _) = use_storage_with_options(
|
|
|
|
/// "my-state",
|
|
|
|
/// MyState {
|
|
|
|
/// hello: "hi".to_string(),
|
|
|
|
/// greeting: "Hello".to_string()
|
|
|
|
/// },
|
|
|
|
/// UseStorageOptions::<MyState>::default().merge_defaults(|stored_value, default_value| {
|
|
|
|
/// if stored_value.contains(r#""greeting":"#) {
|
|
|
|
/// stored_value.to_string()
|
|
|
|
/// } else {
|
|
|
|
/// // add "greeting": "Hello" to the string
|
|
|
|
/// stored_value.replace("}", &format!(r#""greeting": "{}"}}"#, default_value.greeting))
|
|
|
|
/// }
|
|
|
|
/// }),
|
|
|
|
/// );
|
|
|
|
/// #
|
2023-07-27 18:06:36 +01:00
|
|
|
/// # view! { }
|
2023-06-10 00:57:35 +01:00
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ## Filter Storage Write
|
|
|
|
///
|
2023-06-10 01:52:21 +01:00
|
|
|
/// You can specify `debounce` or `throttle` options for limiting writes to storage.
|
2023-06-10 00:57:35 +01:00
|
|
|
///
|
2023-07-14 22:43:19 +01:00
|
|
|
/// ## Server-Side Rendering
|
|
|
|
///
|
2023-07-27 18:06:36 +01:00
|
|
|
/// On the server this falls back to a `create_signal(default)` and an empty remove function.
|
2023-07-14 22:43:19 +01:00
|
|
|
///
|
2023-06-10 00:57:35 +01:00
|
|
|
/// ## See also
|
|
|
|
///
|
|
|
|
/// * [`use_local_storage`]
|
|
|
|
/// * [`use_session_storage`]
|
2023-06-23 22:13:14 +01:00
|
|
|
// #[doc(cfg(feature = "storage"))]
|
2023-07-27 18:06:36 +01:00
|
|
|
pub fn use_storage<T, D>(key: &str, defaults: D) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone)
|
2023-06-10 00:57:35 +01:00
|
|
|
where
|
|
|
|
for<'de> T: Serialize + Deserialize<'de> + Clone + 'static,
|
2023-07-15 16:48:29 +01:00
|
|
|
D: Into<MaybeRwSignal<T>>,
|
2023-06-10 00:57:35 +01:00
|
|
|
T: Clone,
|
|
|
|
{
|
2023-07-27 18:06:36 +01:00
|
|
|
use_storage_with_options(key, defaults, UseStorageOptions::default())
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Version of [`use_storage`] that accepts [`UseStorageOptions`]. See [`use_storage`] for how to use.
|
2023-06-23 22:13:14 +01:00
|
|
|
// #[doc(cfg(feature = "storage"))]
|
2023-06-10 00:57:35 +01:00
|
|
|
pub fn use_storage_with_options<T, D>(
|
|
|
|
key: &str,
|
|
|
|
defaults: D,
|
|
|
|
options: UseStorageOptions<T>,
|
2023-07-15 16:48:29 +01:00
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone)
|
2023-06-10 00:57:35 +01:00
|
|
|
where
|
|
|
|
for<'de> T: Serialize + Deserialize<'de> + Clone + 'static,
|
2023-07-15 16:48:29 +01:00
|
|
|
D: Into<MaybeRwSignal<T>>,
|
2023-06-10 00:57:35 +01:00
|
|
|
T: Clone,
|
|
|
|
{
|
|
|
|
let defaults = defaults.into();
|
|
|
|
|
|
|
|
let UseStorageOptions {
|
|
|
|
storage_type,
|
|
|
|
listen_to_storage_changes,
|
|
|
|
write_defaults,
|
|
|
|
merge_defaults,
|
|
|
|
on_error,
|
|
|
|
filter,
|
|
|
|
} = options;
|
|
|
|
|
2023-07-27 18:06:36 +01:00
|
|
|
let (data, set_data) = defaults.into_signal();
|
2023-07-15 16:48:29 +01:00
|
|
|
|
2023-08-02 01:16:13 +01:00
|
|
|
let raw_init = data.get_untracked();
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
cfg_if! { if #[cfg(feature = "ssr")] {
|
|
|
|
let remove: Box<dyn CloneableFn> = Box::new(|| {});
|
|
|
|
} else {
|
|
|
|
let storage = storage_type.into_storage();
|
|
|
|
|
|
|
|
let remove: Box<dyn CloneableFn> = match storage {
|
|
|
|
Ok(Some(storage)) => {
|
2023-07-15 16:48:29 +01:00
|
|
|
let write = {
|
|
|
|
let on_error = on_error.clone();
|
|
|
|
let storage = storage.clone();
|
|
|
|
let key = key.to_string();
|
2023-07-14 22:43:19 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
move |v: &T| {
|
|
|
|
match serde_json::to_string(&v) {
|
|
|
|
Ok(ref serialized) => match storage.get_item(&key) {
|
|
|
|
Ok(old_value) => {
|
|
|
|
if old_value.as_ref() != Some(serialized) {
|
|
|
|
if let Err(e) = storage.set_item(&key, serialized) {
|
|
|
|
on_error(UseStorageError::StorageAccessError(e));
|
|
|
|
} else {
|
|
|
|
let mut event_init = web_sys::CustomEventInit::new();
|
|
|
|
event_init.detail(
|
|
|
|
&StorageEventDetail {
|
|
|
|
key: Some(key.clone()),
|
|
|
|
old_value,
|
|
|
|
new_value: Some(serialized.clone()),
|
|
|
|
storage_area: Some(storage.clone()),
|
|
|
|
}
|
|
|
|
.into(),
|
|
|
|
);
|
2023-07-14 22:43:19 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
// importantly this should _not_ be a StorageEvent since those cannot
|
|
|
|
// be constructed with a non-built-in storage area
|
|
|
|
let _ = window().dispatch_event(
|
|
|
|
&web_sys::CustomEvent::new_with_event_init_dict(
|
|
|
|
CUSTOM_STORAGE_EVENT_NAME,
|
|
|
|
&event_init,
|
|
|
|
)
|
|
|
|
.expect("Failed to create CustomEvent"),
|
|
|
|
);
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
}
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
2023-07-15 16:48:29 +01:00
|
|
|
Err(e) => {
|
|
|
|
on_error.clone()(UseStorageError::StorageAccessError(e));
|
|
|
|
}
|
|
|
|
},
|
2023-07-14 22:43:19 +01:00
|
|
|
Err(e) => {
|
2023-07-15 16:48:29 +01:00
|
|
|
on_error.clone()(UseStorageError::SerializationError(e));
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
let read = {
|
|
|
|
let storage = storage.clone();
|
|
|
|
let on_error = on_error.clone();
|
|
|
|
let key = key.to_string();
|
|
|
|
let raw_init = raw_init.clone();
|
2023-07-14 22:43:19 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
move |event_detail: Option<StorageEventDetail>| -> Option<T> {
|
|
|
|
let serialized_init = match serde_json::to_string(&raw_init) {
|
|
|
|
Ok(serialized) => Some(serialized),
|
2023-07-14 22:43:19 +01:00
|
|
|
Err(e) => {
|
2023-07-15 16:48:29 +01:00
|
|
|
on_error.clone()(UseStorageError::DefaultSerializationError(e));
|
2023-07-14 22:43:19 +01:00
|
|
|
None
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
2023-07-15 16:48:29 +01:00
|
|
|
};
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
let raw_value = if let Some(event_detail) = event_detail {
|
|
|
|
event_detail.new_value
|
|
|
|
} else {
|
|
|
|
match storage.get_item(&key) {
|
|
|
|
Ok(raw_value) => match raw_value {
|
|
|
|
Some(raw_value) => Some(merge_defaults(&raw_value, &raw_init)),
|
|
|
|
None => serialized_init.clone(),
|
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
on_error.clone()(UseStorageError::StorageAccessError(e));
|
|
|
|
None
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
}
|
2023-07-15 16:48:29 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
match raw_value {
|
|
|
|
Some(raw_value) => match serde_json::from_str(&raw_value) {
|
|
|
|
Ok(v) => Some(v),
|
|
|
|
Err(e) => {
|
|
|
|
on_error.clone()(UseStorageError::SerializationError(e));
|
|
|
|
None
|
|
|
|
}
|
|
|
|
},
|
|
|
|
None => {
|
|
|
|
if let Some(serialized_init) = &serialized_init {
|
|
|
|
if write_defaults {
|
|
|
|
if let Err(e) = storage.set_item(&key, serialized_init) {
|
|
|
|
on_error(UseStorageError::StorageAccessError(e));
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
Some(raw_init)
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
}
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
};
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
let WatchPausableReturn {
|
|
|
|
pause: pause_watch,
|
|
|
|
resume: resume_watch,
|
|
|
|
..
|
|
|
|
} = watch_pausable_with_options(
|
2023-08-02 01:16:13 +01:00
|
|
|
move || data.get(),
|
2023-07-14 22:43:19 +01:00
|
|
|
move |data, _, _| write.clone()(data),
|
|
|
|
WatchOptions::default().filter(filter),
|
|
|
|
);
|
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
let update = {
|
|
|
|
let key = key.to_string();
|
|
|
|
let storage = storage.clone();
|
|
|
|
let raw_init = raw_init.clone();
|
2023-07-14 22:43:19 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
move |event_detail: Option<StorageEventDetail>| {
|
|
|
|
if let Some(event_detail) = &event_detail {
|
|
|
|
if event_detail.storage_area != Some(storage) {
|
2023-06-10 00:57:35 +01:00
|
|
|
return;
|
|
|
|
}
|
2023-07-15 16:48:29 +01:00
|
|
|
|
|
|
|
match &event_detail.key {
|
|
|
|
None => {
|
|
|
|
set_data.set(raw_init);
|
2023-07-14 22:43:19 +01:00
|
|
|
return;
|
|
|
|
}
|
2023-07-15 16:48:29 +01:00
|
|
|
Some(event_key) => {
|
|
|
|
if event_key != &key {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
pause_watch();
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
if let Some(value) = read(event_detail.clone()) {
|
|
|
|
set_data.set(value);
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
|
2023-07-15 16:48:29 +01:00
|
|
|
if event_detail.is_some() {
|
|
|
|
// use timeout to avoid inifinite loop
|
|
|
|
let resume = resume_watch.clone();
|
|
|
|
let _ = set_timeout_with_handle(resume, Duration::ZERO);
|
|
|
|
} else {
|
|
|
|
resume_watch();
|
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
}
|
|
|
|
};
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
let upd = update.clone();
|
|
|
|
let update_from_custom_event =
|
|
|
|
move |event: web_sys::CustomEvent| upd.clone()(Some(event.into()));
|
|
|
|
|
|
|
|
let upd = update.clone();
|
|
|
|
let update_from_storage_event =
|
|
|
|
move |event: web_sys::StorageEvent| upd.clone()(Some(event.into()));
|
|
|
|
|
|
|
|
if listen_to_storage_changes {
|
2023-07-27 18:06:36 +01:00
|
|
|
let _ = use_event_listener(window(), ev::storage, update_from_storage_event);
|
2023-07-14 22:43:19 +01:00
|
|
|
let _ = use_event_listener(
|
2023-07-27 18:06:36 +01:00
|
|
|
window(),
|
2023-07-14 22:43:19 +01:00
|
|
|
ev::Custom::new(CUSTOM_STORAGE_EVENT_NAME),
|
|
|
|
update_from_custom_event,
|
|
|
|
);
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
update(None);
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
let k = key.to_string();
|
2023-06-10 00:57:35 +01:00
|
|
|
|
2023-07-14 22:43:19 +01:00
|
|
|
Box::new(move || {
|
|
|
|
let _ = storage.remove_item(&k);
|
|
|
|
})
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
2023-07-14 22:43:19 +01:00
|
|
|
Err(e) => {
|
|
|
|
on_error(UseStorageError::NoStorage(e));
|
|
|
|
Box::new(move || {})
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
// do nothing
|
|
|
|
Box::new(move || {})
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}}
|
2023-06-10 00:57:35 +01:00
|
|
|
|
|
|
|
(data, set_data, move || remove.clone()())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct StorageEventDetail {
|
|
|
|
pub key: Option<String>,
|
|
|
|
pub old_value: Option<String>,
|
|
|
|
pub new_value: Option<String>,
|
|
|
|
pub storage_area: Option<web_sys::Storage>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<web_sys::StorageEvent> for StorageEventDetail {
|
|
|
|
fn from(event: web_sys::StorageEvent) -> Self {
|
|
|
|
Self {
|
|
|
|
key: event.key(),
|
|
|
|
old_value: event.old_value(),
|
|
|
|
new_value: event.new_value(),
|
|
|
|
storage_area: event.storage_area(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<web_sys::CustomEvent> for StorageEventDetail {
|
|
|
|
fn from(event: web_sys::CustomEvent) -> Self {
|
|
|
|
let detail = event.detail();
|
|
|
|
Self {
|
|
|
|
key: get_optional_string(&detail, "key"),
|
|
|
|
old_value: get_optional_string(&detail, "oldValue"),
|
|
|
|
new_value: get_optional_string(&detail, "newValue"),
|
|
|
|
storage_area: Reflect::get(&detail, &"storageArea".into())
|
|
|
|
.map(|v| v.dyn_into::<web_sys::Storage>().ok())
|
|
|
|
.unwrap_or_default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<StorageEventDetail> for JsValue {
|
|
|
|
fn from(event: StorageEventDetail) -> Self {
|
|
|
|
let obj = js_sys::Object::new();
|
|
|
|
|
|
|
|
let _ = Reflect::set(&obj, &"key".into(), &event.key.into());
|
|
|
|
let _ = Reflect::set(&obj, &"oldValue".into(), &event.old_value.into());
|
|
|
|
let _ = Reflect::set(&obj, &"newValue".into(), &event.new_value.into());
|
|
|
|
let _ = Reflect::set(&obj, &"storageArea".into(), &event.storage_area.into());
|
|
|
|
|
|
|
|
obj.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_optional_string(v: &JsValue, key: &str) -> Option<String> {
|
|
|
|
Reflect::get(v, &key.into())
|
|
|
|
.map(|v| v.as_string())
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Error type for use_storage_with_options
|
2023-06-23 22:13:14 +01:00
|
|
|
// #[doc(cfg(feature = "storage"))]
|
2023-06-10 00:57:35 +01:00
|
|
|
pub enum UseStorageError<E = ()> {
|
|
|
|
NoStorage(JsValue),
|
|
|
|
StorageAccessError(JsValue),
|
|
|
|
CustomStorageAccessError(E),
|
|
|
|
SerializationError(Error),
|
|
|
|
DefaultSerializationError(Error),
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Options for [`use_storage_with_options`].
|
2023-06-23 22:13:14 +01:00
|
|
|
// #[doc(cfg(feature = "storage"))]
|
2023-06-10 00:57:35 +01:00
|
|
|
#[derive(DefaultBuilder)]
|
|
|
|
pub struct UseStorageOptions<T> {
|
|
|
|
/// Type of storage. Can be `Local` (default), `Session` or `Custom(web_sys::Storage)`
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) storage_type: StorageType,
|
2023-06-10 00:57:35 +01:00
|
|
|
/// Listen to changes to this storage key from somewhere else. Defaults to true.
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) listen_to_storage_changes: bool,
|
2023-06-10 00:57:35 +01:00
|
|
|
/// If no value for the give key is found in the storage, write it. Defaults to true.
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) write_defaults: bool,
|
2023-06-10 00:57:35 +01:00
|
|
|
/// Takes the serialized (json) stored value and the default value and returns a merged version.
|
|
|
|
/// Defaults to simply returning the stored value.
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) merge_defaults: fn(&str, &T) -> String,
|
2023-06-10 00:57:35 +01:00
|
|
|
/// Optional callback whenever an error occurs. The callback takes an argument of type [`UseStorageError`].
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) on_error: Box<dyn CloneableFnWithArg<UseStorageError>>,
|
2023-06-10 00:57:35 +01:00
|
|
|
|
|
|
|
/// Debounce or throttle the writing to storage whenever the value changes.
|
2023-06-10 01:52:21 +01:00
|
|
|
pub(crate) filter: FilterOptions,
|
2023-06-10 00:57:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Default for UseStorageOptions<T> {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
storage_type: Default::default(),
|
|
|
|
listen_to_storage_changes: true,
|
|
|
|
write_defaults: true,
|
|
|
|
merge_defaults: |stored_value, _default_value| stored_value.to_string(),
|
|
|
|
on_error: Box::new(|_| ()),
|
|
|
|
filter: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> UseStorageOptions<T> {
|
|
|
|
filter_builder_methods!(
|
|
|
|
/// the serializing and storing into storage
|
|
|
|
filter
|
|
|
|
);
|
|
|
|
}
|