Skip to content

Commit

Permalink
Making Entry struct for StateStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
alex13sh committed Sep 26, 2021
1 parent 68e5df6 commit 17832e1
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 18 deletions.
7 changes: 4 additions & 3 deletions examples/todos/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,10 @@ impl Application for Todos {
}
Message::TaskMessage(i, task_message) => {
if let Some(task) = state.tasks.get_mut(i) {
states.enter(&format!("task_{}", i));
task.update(task_message, states);
states.exit();
task.update(
task_message,
&mut states.enter(&format!("task_{}", i))
);
}
}
Message::Saved(_) => {
Expand Down
16 changes: 6 additions & 10 deletions native/src/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,22 +268,18 @@ where
/// Making State Array of Widget for saving
pub fn into_states(self, hash: Hasher, states: &mut StateStorage) {
if let Some(id) = &self.root_id {
states.enter(&id);
}
self.widget.into_states(hash, states);
if self.root_id.is_some() {
states.exit();
self.widget.into_states(hash, &mut states.enter(&id));
} else {
self.widget.into_states(hash, states);
}
}

/// Apply States for widget
pub fn apply_states(&mut self, hash: Hasher, states: &mut StateStorage) {
if let Some(id) = &self.root_id {
states.enter(&id);
}
self.widget.apply_states(hash, states);
if self.root_id.is_some() {
states.exit();
self.widget.apply_states(hash, &mut states.enter(&id));
} else {
self.widget.apply_states(hash, states);
}
}

Expand Down
51 changes: 46 additions & 5 deletions native/src/state_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,52 @@ impl StateStorage {
}

/// Entering a state group
pub fn enter(&mut self, id: &str) {
self.path.push(id);
/// the function is called from [`Element`] and [`Application::update`]
pub fn enter(&mut self, id: &str) -> Entry<'_> {
Entry::new(self)
.enter(id)
}
/// Exit from the group
pub fn exit(&mut self) {
let _ = self.path.pop();
}

/// Access to the state at a lower level
/// This `struct` is constructed from the [`enter`] method on [`StateStorage`].
#[derive(Debug)]
pub struct Entry <'a> {
storage: &'a mut StateStorage,
is_enter: bool,
}

impl <'a> Entry<'a> {
fn new(storage: &'a mut StateStorage) -> Self {
Entry {
storage,
is_enter: false,
}
}
fn enter(mut self, id: &str) -> Self {
self.storage.path.push(id);
self.is_enter = true;
self
}
}

impl <'a> Drop for Entry <'a> {
fn drop(&mut self) {
if self.is_enter {
let _ = self.path.pop();
}
}
}

impl <'a> std::ops::Deref for Entry<'a> {
type Target = StateStorage;
fn deref(&self) -> &StateStorage {
&self.storage
}
}

impl <'a> std::ops::DerefMut for Entry<'a> {
fn deref_mut(&mut self) -> &mut StateStorage {
&mut self.storage
}
}

0 comments on commit 17832e1

Please sign in to comment.