2023-10-27 12:37:41 +01:00
|
|
|
use crate::{
|
2023-10-27 13:57:36 +01:00
|
|
|
core::{MaybeRwSignal, StorageType},
|
2023-10-28 12:13:55 +01:00
|
|
|
use_event_listener, use_window,
|
2023-10-27 12:37:41 +01:00
|
|
|
};
|
2023-10-27 14:50:29 +01:00
|
|
|
use cfg_if::cfg_if;
|
2023-10-26 11:46:47 +01:00
|
|
|
use leptos::*;
|
2023-10-28 12:19:33 +01:00
|
|
|
use std::rc::Rc;
|
2023-10-26 11:46:47 +01:00
|
|
|
use thiserror::Error;
|
|
|
|
use wasm_bindgen::JsValue;
|
|
|
|
|
2023-10-28 12:13:55 +01:00
|
|
|
const INTERNAL_STORAGE_EVENT: &str = "leptos-use-storage";
|
|
|
|
|
2023-10-28 12:19:33 +01:00
|
|
|
pub trait Codec<T>: Clone + 'static {
|
|
|
|
type Error;
|
|
|
|
fn encode(&self, val: &T) -> Result<String, Self::Error>;
|
|
|
|
fn decode(&self, str: String) -> Result<T, Self::Error>;
|
|
|
|
}
|
|
|
|
|
2023-10-26 11:46:47 +01:00
|
|
|
#[derive(Clone)]
|
2023-10-27 13:57:36 +01:00
|
|
|
pub struct UseStorageOptions<T: 'static, C: Codec<T>> {
|
2023-10-27 10:05:02 +01:00
|
|
|
codec: C,
|
|
|
|
on_error: Rc<dyn Fn(UseStorageError<C::Error>)>,
|
2023-10-26 12:01:04 +01:00
|
|
|
listen_to_storage_changes: bool,
|
2023-10-27 19:51:02 +01:00
|
|
|
default_value: MaybeRwSignal<T>,
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Session handling errors returned by [`use_storage`].
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum UseStorageError<Err> {
|
|
|
|
#[error("storage not available")]
|
|
|
|
StorageNotAvailable(JsValue),
|
|
|
|
#[error("storage not returned from window")]
|
|
|
|
StorageReturnedNone,
|
|
|
|
#[error("failed to get item")]
|
|
|
|
GetItemFailed(JsValue),
|
|
|
|
#[error("failed to set item")]
|
|
|
|
SetItemFailed(JsValue),
|
|
|
|
#[error("failed to delete item")]
|
|
|
|
RemoveItemFailed(JsValue),
|
2023-10-28 12:13:55 +01:00
|
|
|
#[error("failed to notify item changed")]
|
|
|
|
NotifyItemChangedFailed(JsValue),
|
2023-10-27 10:05:02 +01:00
|
|
|
#[error("failed to encode / decode item value")]
|
|
|
|
ItemCodecError(Err),
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Hook for using local storage. Returns a result of a signal and a setter / deleter.
|
2023-10-27 19:51:02 +01:00
|
|
|
pub fn use_local_storage<T, C>(
|
|
|
|
key: impl AsRef<str>,
|
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() -> () + Clone)
|
2023-10-26 11:46:47 +01:00
|
|
|
where
|
2023-10-27 16:08:51 +01:00
|
|
|
T: Clone + Default + PartialEq,
|
|
|
|
C: Codec<T> + Default,
|
2023-10-26 11:46:47 +01:00
|
|
|
{
|
2023-10-27 16:08:51 +01:00
|
|
|
use_storage_with_options(
|
|
|
|
StorageType::Local,
|
|
|
|
key,
|
|
|
|
UseStorageOptions::<T, C>::default(),
|
|
|
|
)
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
|
2023-10-27 10:05:02 +01:00
|
|
|
pub fn use_local_storage_with_options<T, C>(
|
2023-10-26 11:46:47 +01:00
|
|
|
key: impl AsRef<str>,
|
2023-10-27 10:05:02 +01:00
|
|
|
options: UseStorageOptions<T, C>,
|
2023-10-27 19:51:02 +01:00
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() -> () + Clone)
|
2023-10-27 11:56:47 +01:00
|
|
|
where
|
2023-10-27 13:57:36 +01:00
|
|
|
T: Clone + PartialEq,
|
2023-10-27 11:56:47 +01:00
|
|
|
C: Codec<T>,
|
|
|
|
{
|
2023-10-27 12:37:41 +01:00
|
|
|
use_storage_with_options(StorageType::Local, key, options)
|
2023-10-27 11:56:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Hook for using session storage. Returns a result of a signal and a setter / deleter.
|
2023-10-27 16:08:51 +01:00
|
|
|
pub fn use_session_storage<T, C>(
|
|
|
|
key: impl AsRef<str>,
|
2023-10-27 19:51:02 +01:00
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() -> () + Clone)
|
2023-10-27 11:56:47 +01:00
|
|
|
where
|
2023-10-27 16:08:51 +01:00
|
|
|
T: Clone + Default + PartialEq,
|
|
|
|
C: Codec<T> + Default,
|
2023-10-27 11:56:47 +01:00
|
|
|
{
|
2023-10-27 16:08:51 +01:00
|
|
|
use_storage_with_options(
|
|
|
|
StorageType::Session,
|
|
|
|
key,
|
|
|
|
UseStorageOptions::<T, C>::default(),
|
|
|
|
)
|
2023-10-27 11:56:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn use_session_storage_with_options<T, C>(
|
|
|
|
key: impl AsRef<str>,
|
|
|
|
options: UseStorageOptions<T, C>,
|
2023-10-27 19:51:02 +01:00
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() -> () + Clone)
|
2023-10-27 11:56:47 +01:00
|
|
|
where
|
2023-10-27 13:57:36 +01:00
|
|
|
T: Clone + PartialEq,
|
2023-10-27 11:56:47 +01:00
|
|
|
C: Codec<T>,
|
|
|
|
{
|
2023-10-27 12:37:41 +01:00
|
|
|
use_storage_with_options(StorageType::Session, key, options)
|
2023-10-27 11:56:47 +01:00
|
|
|
}
|
|
|
|
|
2023-10-27 12:37:41 +01:00
|
|
|
/// Hook for using any kind of storage. Returns a result of a signal and a setter / deleter.
|
2023-10-27 14:15:40 +01:00
|
|
|
pub fn use_storage_with_options<T, C>(
|
2023-10-27 12:37:41 +01:00
|
|
|
storage_type: StorageType,
|
2023-10-27 11:56:47 +01:00
|
|
|
key: impl AsRef<str>,
|
|
|
|
options: UseStorageOptions<T, C>,
|
2023-10-27 19:51:02 +01:00
|
|
|
) -> (Signal<T>, WriteSignal<T>, impl Fn() -> () + Clone)
|
2023-10-26 11:46:47 +01:00
|
|
|
where
|
2023-10-27 13:57:36 +01:00
|
|
|
T: Clone + PartialEq,
|
2023-10-27 10:05:02 +01:00
|
|
|
C: Codec<T>,
|
2023-10-26 11:46:47 +01:00
|
|
|
{
|
2023-10-27 14:50:29 +01:00
|
|
|
cfg_if! { if #[cfg(feature = "ssr")] {
|
|
|
|
let (data, set_data) = create_signal(None);
|
|
|
|
let set_value = move |value: Option<T>| {
|
|
|
|
set_data.set(value);
|
|
|
|
};
|
|
|
|
let value = create_memo(move |_| data.get().unwrap_or_default());
|
2023-10-27 19:51:02 +01:00
|
|
|
return (value, set_value, || ());
|
2023-10-27 14:50:29 +01:00
|
|
|
} else {
|
|
|
|
// Continue
|
|
|
|
}}
|
|
|
|
|
2023-10-26 12:01:04 +01:00
|
|
|
let UseStorageOptions {
|
2023-10-27 10:05:02 +01:00
|
|
|
codec,
|
2023-10-26 12:01:04 +01:00
|
|
|
on_error,
|
|
|
|
listen_to_storage_changes,
|
2023-10-27 13:57:36 +01:00
|
|
|
default_value,
|
2023-10-26 12:01:04 +01:00
|
|
|
} = options;
|
2023-10-26 11:46:47 +01:00
|
|
|
|
2023-10-27 11:56:47 +01:00
|
|
|
// Get storage API
|
2023-10-27 12:37:41 +01:00
|
|
|
let storage = storage_type
|
|
|
|
.into_storage()
|
|
|
|
.map_err(UseStorageError::StorageNotAvailable)
|
|
|
|
.and_then(|s| s.ok_or(UseStorageError::StorageReturnedNone));
|
|
|
|
let storage = handle_error(&on_error, storage);
|
2023-10-27 11:56:47 +01:00
|
|
|
|
2023-10-28 12:13:55 +01:00
|
|
|
// Schedules a storage event microtask. Uses a queue to avoid re-entering the runtime
|
|
|
|
let dispatch_storage_event = {
|
|
|
|
let key = key.as_ref().to_owned();
|
|
|
|
let on_error = on_error.to_owned();
|
|
|
|
move || {
|
|
|
|
let key = key.to_owned();
|
|
|
|
let on_error = on_error.to_owned();
|
|
|
|
queue_microtask(move || {
|
|
|
|
// Note: we cannot construct a full StorageEvent so we _must_ rely on a custom event
|
|
|
|
let mut custom = web_sys::CustomEventInit::new();
|
|
|
|
custom.detail(&JsValue::from_str(&key));
|
|
|
|
let result = window()
|
|
|
|
.dispatch_event(
|
|
|
|
&web_sys::CustomEvent::new_with_event_init_dict(
|
|
|
|
INTERNAL_STORAGE_EVENT,
|
|
|
|
&custom,
|
|
|
|
)
|
|
|
|
.expect("failed to create custom storage event"),
|
|
|
|
)
|
|
|
|
.map_err(UseStorageError::NotifyItemChangedFailed);
|
|
|
|
let _ = handle_error(&on_error, result);
|
|
|
|
})
|
2023-10-27 19:51:02 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-10-28 12:13:55 +01:00
|
|
|
// Fires when storage needs to be updated
|
|
|
|
let notify = create_trigger();
|
|
|
|
|
|
|
|
// Keeps track of how many times we've been notified. Does not increment for calls to set_data
|
|
|
|
let notify_id = create_memo::<usize>(move |prev| {
|
|
|
|
notify.track();
|
|
|
|
prev.map(|prev| prev + 1).unwrap_or_default()
|
|
|
|
});
|
|
|
|
|
|
|
|
// Fetch from storage and falls back to the default (possibly a signal) if deleted
|
|
|
|
let fetcher = {
|
|
|
|
let storage = storage.to_owned();
|
|
|
|
let codec = codec.to_owned();
|
|
|
|
let key = key.as_ref().to_owned();
|
|
|
|
let on_error = on_error.to_owned();
|
|
|
|
let (default, _) = default_value.into_signal();
|
|
|
|
create_memo(move |_| {
|
|
|
|
notify.track();
|
|
|
|
storage
|
|
|
|
.to_owned()
|
|
|
|
.and_then(|storage| {
|
|
|
|
// Get directly from storage
|
|
|
|
let result = storage
|
|
|
|
.get_item(&key)
|
|
|
|
.map_err(UseStorageError::GetItemFailed);
|
|
|
|
handle_error(&on_error, result)
|
|
|
|
})
|
|
|
|
.unwrap_or_default() // Drop handled Err(())
|
|
|
|
.map(|encoded| {
|
|
|
|
// Decode item
|
|
|
|
let result = codec
|
|
|
|
.decode(encoded)
|
|
|
|
.map_err(UseStorageError::ItemCodecError);
|
|
|
|
handle_error(&on_error, result)
|
|
|
|
})
|
|
|
|
.transpose()
|
|
|
|
.unwrap_or_default() // Drop handled Err(())
|
|
|
|
// Fallback to default
|
|
|
|
.unwrap_or_else(move || default.get())
|
|
|
|
})
|
2023-10-27 19:51:02 +01:00
|
|
|
};
|
2023-10-26 11:46:47 +01:00
|
|
|
|
2023-10-28 12:13:55 +01:00
|
|
|
// Create mutable data signal from our fetcher
|
|
|
|
let (data, set_data) = MaybeRwSignal::<T>::from(fetcher).into_signal();
|
|
|
|
let data = create_memo(move |_| data.get());
|
|
|
|
|
|
|
|
// Set storage value on data change
|
2023-10-27 19:51:02 +01:00
|
|
|
{
|
2023-10-26 11:46:47 +01:00
|
|
|
let storage = storage.to_owned();
|
2023-10-27 10:05:02 +01:00
|
|
|
let codec = codec.to_owned();
|
2023-10-27 19:51:02 +01:00
|
|
|
let key = key.as_ref().to_owned();
|
2023-10-26 11:46:47 +01:00
|
|
|
let on_error = on_error.to_owned();
|
2023-10-28 12:13:55 +01:00
|
|
|
let dispatch_storage_event = dispatch_storage_event.to_owned();
|
2023-10-27 19:51:02 +01:00
|
|
|
let _ = watch(
|
2023-10-28 12:13:55 +01:00
|
|
|
move || (notify_id.get(), data.get()),
|
|
|
|
move |(id, value), prev, _| {
|
|
|
|
// Skip setting storage on changes from external events. The ID will change on external events.
|
|
|
|
if prev.map(|(prev_id, _)| *prev_id != *id).unwrap_or_default() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-10-27 19:51:02 +01:00
|
|
|
if let Ok(storage) = &storage {
|
2023-10-28 12:13:55 +01:00
|
|
|
// Encode value
|
2023-10-27 19:51:02 +01:00
|
|
|
let result = codec
|
2023-10-28 12:13:55 +01:00
|
|
|
.encode(value)
|
2023-10-27 10:05:02 +01:00
|
|
|
.map_err(UseStorageError::ItemCodecError)
|
|
|
|
.and_then(|enc_value| {
|
2023-10-28 12:13:55 +01:00
|
|
|
// Set storage -- sends a global event
|
2023-10-27 10:05:02 +01:00
|
|
|
storage
|
2023-10-28 12:13:55 +01:00
|
|
|
.set_item(&key, &enc_value)
|
2023-10-27 10:05:02 +01:00
|
|
|
.map_err(UseStorageError::SetItemFailed)
|
2023-10-27 19:51:02 +01:00
|
|
|
});
|
2023-10-28 12:13:55 +01:00
|
|
|
let result = handle_error(&on_error, result);
|
|
|
|
// Send internal storage event
|
|
|
|
if result.is_ok() {
|
|
|
|
dispatch_storage_event();
|
|
|
|
}
|
2023-10-27 19:51:02 +01:00
|
|
|
}
|
|
|
|
},
|
|
|
|
false,
|
|
|
|
);
|
2023-10-26 11:46:47 +01:00
|
|
|
};
|
|
|
|
|
2023-10-26 12:01:04 +01:00
|
|
|
if listen_to_storage_changes {
|
2023-10-28 12:13:55 +01:00
|
|
|
let check_key = key.as_ref().to_owned();
|
|
|
|
// Listen to global storage events
|
|
|
|
let _ = use_event_listener(use_window(), leptos::ev::storage, move |ev| {
|
|
|
|
let ev_key = ev.key();
|
|
|
|
// Key matches or all keys deleted (None)
|
|
|
|
if ev_key == Some(check_key.clone()) || ev_key.is_none() {
|
|
|
|
notify.notify()
|
|
|
|
}
|
|
|
|
});
|
|
|
|
// Listen to internal storage events
|
|
|
|
let check_key = key.as_ref().to_owned();
|
|
|
|
let _ = use_event_listener(
|
2023-10-26 11:46:47 +01:00
|
|
|
use_window(),
|
2023-10-28 12:13:55 +01:00
|
|
|
ev::Custom::new(INTERNAL_STORAGE_EVENT),
|
|
|
|
move |ev: web_sys::CustomEvent| {
|
|
|
|
if Some(check_key.clone()) == ev.detail().as_string() {
|
|
|
|
notify.notify()
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
},
|
2023-10-26 12:01:04 +01:00
|
|
|
);
|
2023-10-26 11:46:47 +01:00
|
|
|
};
|
|
|
|
|
2023-10-27 19:51:02 +01:00
|
|
|
// Remove from storage fn
|
|
|
|
let remove = {
|
|
|
|
let key = key.as_ref().to_owned();
|
|
|
|
move || {
|
|
|
|
let _ = storage.as_ref().map(|storage| {
|
2023-10-28 12:13:55 +01:00
|
|
|
// Delete directly from storage
|
2023-10-27 19:51:02 +01:00
|
|
|
let result = storage
|
2023-10-28 12:13:55 +01:00
|
|
|
.remove_item(&key)
|
2023-10-27 19:51:02 +01:00
|
|
|
.map_err(UseStorageError::RemoveItemFailed);
|
|
|
|
let _ = handle_error(&on_error, result);
|
2023-10-28 12:13:55 +01:00
|
|
|
notify.notify();
|
|
|
|
dispatch_storage_event();
|
2023-10-27 19:51:02 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
2023-10-27 13:57:36 +01:00
|
|
|
|
2023-10-28 12:13:55 +01:00
|
|
|
(data.into(), set_data, remove)
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls the on_error callback with the given error. Removes the error from the Result to avoid double error handling.
|
|
|
|
fn handle_error<T, Err>(
|
|
|
|
on_error: &Rc<dyn Fn(UseStorageError<Err>)>,
|
|
|
|
result: Result<T, UseStorageError<Err>>,
|
|
|
|
) -> Result<T, ()> {
|
|
|
|
result.or_else(|err| Err((on_error)(err)))
|
|
|
|
}
|
|
|
|
|
2023-10-27 16:08:51 +01:00
|
|
|
impl<T: Default + 'static, C: Codec<T> + Default> Default for UseStorageOptions<T, C> {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
codec: C::default(),
|
|
|
|
on_error: Rc::new(|_err| ()),
|
|
|
|
listen_to_storage_changes: true,
|
2023-10-27 19:51:02 +01:00
|
|
|
default_value: MaybeRwSignal::default(),
|
2023-10-27 16:08:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-27 13:57:36 +01:00
|
|
|
impl<T: Clone + Default, C: Codec<T>> UseStorageOptions<T, C> {
|
2023-10-27 14:32:03 +01:00
|
|
|
pub(super) fn new(codec: C) -> Self {
|
2023-10-26 11:46:47 +01:00
|
|
|
Self {
|
2023-10-27 10:05:02 +01:00
|
|
|
codec,
|
2023-10-26 11:46:47 +01:00
|
|
|
on_error: Rc::new(|_err| ()),
|
2023-10-26 12:01:04 +01:00
|
|
|
listen_to_storage_changes: true,
|
2023-10-27 19:51:02 +01:00
|
|
|
default_value: MaybeRwSignal::default(),
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-27 10:05:02 +01:00
|
|
|
pub fn on_error(self, on_error: impl Fn(UseStorageError<C::Error>) + 'static) -> Self {
|
2023-10-26 11:46:47 +01:00
|
|
|
Self {
|
|
|
|
on_error: Rc::new(on_error),
|
2023-10-26 12:01:04 +01:00
|
|
|
..self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn listen_to_storage_changes(self, listen_to_storage_changes: bool) -> Self {
|
|
|
|
Self {
|
|
|
|
listen_to_storage_changes,
|
|
|
|
..self
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|
|
|
|
}
|
2023-10-27 13:57:36 +01:00
|
|
|
|
|
|
|
pub fn default_value(self, values: impl Into<MaybeRwSignal<T>>) -> Self {
|
|
|
|
Self {
|
2023-10-27 19:51:02 +01:00
|
|
|
default_value: values.into(),
|
2023-10-27 13:57:36 +01:00
|
|
|
..self
|
|
|
|
}
|
|
|
|
}
|
2023-10-26 11:46:47 +01:00
|
|
|
}
|