### Running Leptos Examples (Bash) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Provides bash commands for managing and running example applications within a Leptos project. Includes commands to list available examples and to run a specific example. ```bash # Listing Available Examples make examples-list # Running an Example # (Specific command depends on the example, typically `make run-example EX=example_name`) ``` -------------------------------- ### Clone and Setup leptos-store Repository Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Instructions for cloning the leptos-store repository and performing initial setup checks, including verifying the build and running tests. ```bash # Clone the repository git clone https://github.com/your-org/leptos-store.git cd leptos-store # Verify setup make check # Run tests make test ``` -------------------------------- ### Run Leptos Example with CSR Source: https://github.com/web-mech/leptos-store/blob/main/examples/auth-store-example/README.md Instructions for running the Leptos authentication store example in Client-Side Rendering (CSR) mode using `trunk`. This provides a simpler setup without SSR. ```bash # Install trunk cargo install trunk # Run with trunk trunk serve --features csr ``` -------------------------------- ### Leptos Store Contribution Quick Start Source: https://github.com/web-mech/leptos-store/blob/main/README.md Begin contributing to the leptos-store project by cloning the repository and running initial setup and test commands. Refer to AUTHORING.md for detailed development guidelines. ```bash # Quick start for contributors git clone https://github.com/your-org/leptos-store.git cd leptos-store make check # Verify setup make test # Run tests make help # See all commands ``` -------------------------------- ### Install Leptos CLI and WASM Target Source: https://github.com/web-mech/leptos-store/blob/main/examples/auth-store-example/README.md Instructions for installing the `cargo-leptos` tool for SSR development and setting up the WASM target for manual builds. This is a prerequisite for running the example in different rendering modes. ```bash # Install cargo-leptos (recommended for SSR) cargo install cargo-leptos # Or for manual builds, ensure WASM target is installed rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Development Commands for Leptos Store Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md A quick reference for common development commands using `make`. This includes running tests, linters, formatting, building examples, and managing documentation. ```bash # Development make check # Check compilation make test # Run tests make clippy # Run lints make fmt # Format code make ci # Full CI pipeline # Examples (generic) make examples-list # List all examples make run NAME=token-explorer-example # Run specific example make build-example NAME=auth-store-example # Build specific example make check-all-examples # Check all examples compile make test-all-examples # Test all examples # Examples (legacy auth-store-example) make example # Run auth example make example-release # Build optimized # Documentation make doc-open # View docs in browser # Publishing make publish-dry # Test publish make publish # Publish to crates.io # Version Management make version # Show current version make bump # Auto-bump based on commits make release # Full release process # Utilities make clean # Clean artifacts make help # Show all commands make loc # Lines of code stats ``` -------------------------------- ### leptos-store Quick Command Reference Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md A reference for common make commands used in the leptos-store project for tasks like checking compilation, running tests, linting, formatting, listing and running examples, and viewing documentation. ```bash make help # Show all available commands make check # Verify compilation make test # Run all tests make clippy # Run lints make fmt # Format code make examples-list # List all examples make run NAME=token-explorer-example # Run SSR example make example # Run auth example (legacy) make doc-open # View documentation ``` -------------------------------- ### Running Leptos Store Examples with Make Source: https://github.com/web-mech/leptos-store/blob/main/README.md Execute various Leptos Store examples using the provided `make` commands. This includes listing examples, running specific examples in SSR mode, and building individual examples. ```bash # List all available examples make examples-list # Run a specific example (SSR mode with cargo-leptos) make run NAME=auth-store-example make run NAME=token-explorer-example # Build an example make build-example NAME=token-explorer-example ``` -------------------------------- ### Writing Unit Tests for Leptos Store (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates how to write unit tests for a Leptos Store within a `#[cfg(test)]` module. It includes examples for testing store creation and verifying mutator functions. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn test_store_creation() { let store = MyStore::new(); assert_eq!(store.state().get().field, expected_value); } #[test] fn test_mutator() { let store = MyStore::new(); store.set_field("new value".to_string()); assert_eq!(store.state().get().field, "new value"); } } ``` -------------------------------- ### Running the Token Explorer Example Source: https://github.com/web-mech/leptos-store/blob/main/README.md Launch the 'token-explorer-example' which demonstrates full SSR hydration, including server-side data fetching, automatic state hydration, client-side polling, reactive filtering, and sorting. ```bash # Run the token explorer make run NAME=token-explorer-example # Opens at http://127.0.0.1:3005 ``` -------------------------------- ### Run Counter Example (Bash) Source: https://github.com/web-mech/leptos-store/blob/main/examples/counter-example/README.md Command to run the counter example from the project root using `make`. This command initiates the server and provides the URL where the application can be accessed. ```bash # From the project root make run NAME=counter-example # Opens at http://127.0.0.1:3001 ``` -------------------------------- ### Run Leptos Example with cargo-leptos Source: https://github.com/web-mech/leptos-store/blob/main/examples/auth-store-example/README.md Commands to run the Leptos authentication store example using `cargo-leptos`. Includes options for development mode with hot-reloading and production builds. ```bash # Development mode with hot-reload cargo leptos watch # Production build cargo leptos build --release ``` -------------------------------- ### CSR Quick Start for leptos-store Source: https://github.com/web-mech/leptos-store/blob/main/README.md This Rust code demonstrates the basic setup for leptos-store in Client-Side Rendering (CSR) mode. It shows how to create a store instance and provide it to the Leptos application context, with an alternative helper function mentioned. ```rust use leptos::prelude::*; use leptos_store::prelude::*; // In CSR mode, just create and provide — no server needed let store = MyStore::new(); provide_store(store); // Or use the CSR helper: // mount_csr_store(store); ``` -------------------------------- ### Writing Rustdoc Comments for Leptos Store (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Illustrates the standard `rustdoc` conventions for writing documentation comments in Rust code. It covers brief and longer descriptions, documenting arguments, return values, panics, and providing usage examples. ```rust /// Brief description of the item. /// /// Longer description with more details about behavior, /// edge cases, and usage patterns. /// /// # Arguments /// /// * `param` - Description of the parameter /// /// # Returns /// /// Description of what is returned. /// /// # Panics /// /// Conditions under which this function panics. /// /// # Examples /// /// ```rust,ignore /// let result = my_function(arg); /// assert_eq!(result, expected); /// ``` pub fn my_function(param: Type) -> ReturnType { // ... } ``` -------------------------------- ### Complete Leptos Store Example with Middleware and Coordination Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/08-middleware.md Demonstrates the setup and usage of Leptos Store's middleware, audit trail, and coordination features. It shows how to create a shared event bus, wrap stores with middleware for logging and validation, set up an audit trail, configure cross-store coordination, and execute tracked mutations. ```rust use leptos_store::middleware::*; use leptos_store::audit::*; use leptos_store::coordination::*; use std::sync::Arc; // 1. Create shared event bus let bus = Arc::new(EventBus::new()); // 2. Wrap stores with middleware let cart = MiddlewareStore::with_event_bus(CartStore::new(), Arc::clone(&bus)); cart.add_middleware(LoggingMiddleware::new()); cart.add_middleware(ValidationMiddleware::new() .add_validator(|s: &CartState| { if s.items.len() > 100 { Err("Cart too large".into()) } else { Ok(()) } }) ); // 3. Set up audit trail let trail: AuditTrail = AuditTrail::new() .with_max_entries(500) .with_user_context(|| AuditUserContext::new().with_user_id("current-user")); // 4. Set up cross-store coordination let mut coord = StoreCoordinator::with_event_bus(Arc::clone(&bus)); coord.on_change(&cart, &totals_store, |totals, _| totals.recalculate()); coord.activate(); // 5. Execute a tracked mutation let before = cart.inner().get_state(); cart.mutate("add_item", || { cart.inner().add_item(item); }).unwrap(); let after = cart.inner().get_state(); trail.record_with_diff("add_item", &before, &after); ``` -------------------------------- ### Setting Up Feature Flags (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/examples/feature-flags-example/README.md Initializes a FeatureFlagStore and sets initial feature flags with their states and optional variants. This store is then provided as context for the application. ```rust let flags = FeatureFlagStore::new(); flags.set_flags(vec![ FeatureFlag::new("dark_mode", true), FeatureFlag::new("beta_features", false), FeatureFlag::with_variant("hero_style", true, "modern"), ]); provide_context(flags); ``` -------------------------------- ### Leptos Store Build Commands for SSR and Hydration Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Example bash commands for building a Leptos application with SSR and hydration capabilities using Cargo. It shows how to build the server binary and the client WASM module with the appropriate feature flags. ```bash # Server binary (includes SSR rendering) cargo build --features ssr # Client WASM (hydrates in browser) cargo build --lib --target wasm32-unknown-unknown --features hydrate ``` -------------------------------- ### Run Leptos Example with Manual SSR Source: https://github.com/web-mech/leptos-store/blob/main/examples/auth-store-example/README.md Steps to manually build and run the Leptos authentication store example in SSR mode. This involves building the WASM for hydration and then running the server. ```bash # Build the WASM for hydration cargo build --lib --features hydrate --target wasm32-unknown-unknown # Run the server cargo run --features ssr Then open http://127.0.0.1:3000 in your browser. ``` -------------------------------- ### Add WASM Target for Examples Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md This command adds the necessary WASM target to your Rust toolchain, which is required for building and running the project's examples that utilize WebAssembly. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Running Leptos Store Tests (Bash) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Provides bash commands for running various test suites for a Leptos project. This includes running all tests, verbose output, library-specific tests, example tests, and tests with code coverage. ```bash # All tests make test # Verbose output make test-verbose # Library tests only make test-lib # Example tests only make test-example # With coverage make coverage ``` -------------------------------- ### Complete Leptos CSR App with Counter Example Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/09-csr-deployment.md Provides the full project structure for a Client-Side Rendering (CSR) Leptos application using `leptos-store`. This includes `Cargo.toml` dependencies, `index.html` setup, and the main Rust code for a counter component. Ensure the `csr` feature is enabled for `leptos-store`. ```toml [package] name = "my-csr-app" version = "0.1.0" edition = "2024" [dependencies] leptos = { version = "0.8", features = ["csr"] } leptos-store = { version = "0.5", features = ["csr"] } console_error_panic_hook = "0.1" wasm-bindgen = "0.2" ``` ```html My CSR App ``` ```rust use leptos::prelude::*; use leptos_store::prelude::*; #[derive(Clone, Debug, Default)] pub struct CounterState { pub count: i32, } #[derive(Clone)] pub struct CounterStore { state: RwSignal, } impl CounterStore { pub fn new() -> Self { Self { state: RwSignal::new(CounterState::default()) } } pub fn count(&self) -> i32 { self.state.with(|s| s.count) } pub fn increment(&self) { self.state.update(|s| s.count += 1); } pub fn decrement(&self) { self.state.update(|s| s.count -= 1); } } impl Store for CounterStore { type State = CounterState; fn state(&self) -> ReadSignal { self.state.read_only() } } #[component] fn App() -> impl IntoView { let store = CounterStore::new(); mount_csr_store(store); view! { } } #[component] fn Counter() -> impl IntoView { let store = use_store::(); view! {

"Counter: " {move || store.count()}

} } fn main() { console_error_panic_hook::set_once(); leptos::mount::mount_to_body(App); } ``` -------------------------------- ### Initialize Leptos Store Devtools (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/examples/devtools-example/README.md Initializes the devtools integration for leptos-store. This feature is conditional and requires the 'devtools' feature to be enabled during compilation. ```rust #[cfg(feature = "devtools")] init_devtools(); ``` -------------------------------- ### Testing Feature Flags with Cargo Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates how to test all feature flag combinations for the leptos-store crate using Cargo commands. This ensures that different configurations of the crate can be built and checked. ```bash make check-features cargo check --no-default-features cargo check --features ssr cargo check --features hydrate cargo check --features csr ``` -------------------------------- ### leptos-store Project Structure Overview Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md An outline of the leptos-store project's directory structure, detailing the purpose of key files and directories such as Cargo.toml, Makefile, src/, examples/, scripts/, and docs/. ```text leptos-store/ ├── Cargo.toml # Workspace configuration ├── Makefile # Build automation ├── README.md # User-facing documentation ├── AUTHORING.md # This file │ ├── src/ # Library source code │ ├── lib.rs # Crate entry point, module docs │ ├── prelude.rs # Re-exports for users │ ├── store.rs # Core Store trait, builders │ ├── context.rs # Leptos context integration │ ├── async.rs # Async action support │ ├── hydration.rs # SSR hydration support (feature: hydrate) │ └── macros.rs # Declarative macros │ ├── examples/ │ ├── auth-store-example/ # Basic auth example │ │ ├── Cargo.toml │ │ ├── index.html │ │ └── src/ │ │ ├── lib.rs │ │ ├── auth_store.rs │ │ └── components.rs │ │ │ └── token-explorer-example/ # Full SSR hydration example │ ├── Cargo.toml │ ├── style/main.css │ └── src/ │ ├── main.rs # SSR server entry point │ ├── lib.rs # Hydration entry point │ ├── token_store.rs # HydratableStore implementation │ └── components.rs # Leptos components │ ├── scripts/ # Build and release scripts │ ├── bump-version.sh │ ├── release.sh │ └── publish.sh │ └── docs/ └── specs/ └── leptos-storekit-spec.md # Original specification ``` -------------------------------- ### Provide Store in Leptos Component Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates how to provide a store instance to the Leptos context within a component. This is crucial for making the store accessible to child components using `use_store`. ```rust use leptos::view; use leptos_meta::provide_context; use leptos_macro::component; // Assuming MyStore is defined elsewhere and has a ::new() constructor // pub struct MyStore { /* ... */ } // impl MyStore { pub fn new() -> Self { /* ... */ } } #[component] fn App() -> impl IntoView { provide_context(MyStore::new()); // Must be before children view! { } } ``` -------------------------------- ### leptos-store Standard Development Cycle Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md The typical workflow for developing within the leptos-store project, including making changes, checking compilation, running tests, linting, formatting, and committing code. ```bash # 1. Make changes to source files # 2. Check compilation make check # 3. Run tests make test # 4. Check lints make clippy # 5. Format code make fmt # 6. Commit changes git add -A && git commit -m "feat: your feature" ``` -------------------------------- ### Implement EventSubscriber for Metrics (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/examples/middleware-example/README.md Implements the `EventSubscriber` trait for a `MetricsSubscriber` to record metrics based on store events. It specifically handles `StoreEvent::MutationCompleted` to capture the mutation name and duration. ```rust impl EventSubscriber for MetricsSubscriber { fn on_event(&self, event: &StoreEvent) { match event { StoreEvent::MutationCompleted { name, duration_ms, .. } => { record_metric(name, *duration_ms); } _ => {} } } } ``` -------------------------------- ### Provide Hydrated Store in Server View Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates how to include the hydration script generated by `provide_hydrated_store` within the server-rendered view. This ensures the client can correctly rehydrate the store state. ```rust use leptos::view; // Assuming 'store' is your store instance on the server // view! { // {provide_hydrated_store(store)} // // } ``` -------------------------------- ### leptos-store Module Responsibilities Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md A breakdown of the responsibilities for each module within the leptos-store's src/ directory, explaining the core functionality of files like store.rs, context.rs, async.rs, hydration.rs, and macros.rs. ```text Module | Responsibility | -------|---------------| `store.rs` | Core `Store` trait, `Getter`, `Mutator`, `StoreBuilder`, `StoreRegistry` | `context.rs` | `provide_store`, `use_store`, `StoreProvider`, scoped stores, hydration context functions | `async.rs` | `Action`, `AsyncAction`, `ReactiveAction`, `ActionState` | `hydration.rs` | `HydratableStore` trait, serialization/deserialization, `HydrationBuilder` (feature: `hydrate`) | `macros.rs` | `store!`, `define_state!`, `define_hydratable_state!`, `define_action!`, `define_async_action!`, `impl_store!`, `impl_hydratable_store!` | `prelude.rs` | Public API re-exports | ``` -------------------------------- ### Build and Serve a Leptos CSR Application with Trunk Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/09-csr-deployment.md These commands demonstrate how to install the trunk build tool and use it to serve a development version of your Leptos application with hot reloading, or to build a production-ready release. ```bash cargo install trunk trunk serve # dev server with hot reload trunk build --release # production build ``` -------------------------------- ### Manual Leptos Store Implementation (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates how to manually implement a Leptos Store by defining a state struct, a store struct, and implementing the `Store` and `HydratableStore` traits. Requires `serde` for serialization and the `hydrate` feature for hydration. ```rust use leptos::prelude::*; use leptos_store::prelude::*; use serde::{Serialize, Deserialize}; // 1. State must be serializable #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct TokenState { pub tokens: Vec, pub error: Option, } // 2. Define store as usual #[derive(Clone)] pub struct TokenStore { state: RwSignal, } impl Store for TokenStore { type State = TokenState; fn state(&self) -> ReadSignal { self.state.read_only() } } // 3. Implement HydratableStore (feature: hydrate) #[cfg(feature = "hydrate")] impl HydratableStore for TokenStore { fn serialize_state(&self) -> Result { serde_json::to_string(&self.state.get()) .map_err(|e| StoreHydrationError::Serialization(e.to_string())) } fn from_hydrated_state(data: &str) -> Result { let state: TokenState = serde_json::from_str(data) .map_err(|e| StoreHydrationError::Deserialization(e.to_string()))?; Ok(Self { state: RwSignal::new(state) }) } fn store_key() -> &'static str { "token_store" // Unique key for this store } } ``` -------------------------------- ### Leptos Store Implementation with Macros (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Shows how to define a Leptos Store and implement `HydratableStore` using the `define_hydratable_state!` and `impl_hydratable_store!` macros. This approach simplifies the boilerplate code required for store definition and hydration. ```rust use leptos_store::{define_hydratable_state, impl_hydratable_store}; // Define state with serde derives define_hydratable_state! { pub struct TokenState { tokens: Vec, error: Option, } } // Implement HydratableStore impl_hydratable_store!(TokenStore, TokenState, state, "token_store"); ``` -------------------------------- ### Create and Provide RootStore in Rust Source: https://github.com/web-mech/leptos-store/blob/main/examples/composition-example/README.md This Rust code demonstrates how to create a RootStore by aggregating multiple domain stores (AuthStore, CartStore, UiStore) and then providing it to the Leptos application context using `provide_root_store`. This pattern centralizes state management. ```rust let root = RootStore::builder() .with_store(AuthStore::new()) .with_store(CartStore::new()) .with_store(UiStore::new()) .build(); provide_root_store(root); ``` -------------------------------- ### Access Stores from RootStore in Rust Source: https://github.com/web-mech/leptos-store/blob/main/examples/composition-example/README.md This Rust code snippet shows how to access individual domain stores (AuthStore, CartStore) that have been aggregated within a RootStore. It uses `use_root_store` to retrieve the root store from the context and then `expect` to get specific domain stores. ```rust let root = use_root_store(); let auth = root.expect::(); let cart = root.expect::(); ``` -------------------------------- ### Leptos Store Feature Gate Configuration (TOML) Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/troubleshooting.md Provides examples of `Cargo.toml` configurations for the `leptos-store` crate, showcasing different feature gates for client-side rendering (CSR), server-side rendering (SSR) with hydration, persistence, middleware, and a full enterprise setup. ```toml # Minimal CSR app leptos-store = { version = "0.5", features = ["csr"] } # Standard SSR + hydration leptos-store = { version = "0.5", features = ["ssr", "hydrate"] } # With persistence leptos-store = { version = "0.5", features = ["ssr", "hydrate", "persist-web"] } # With middleware + audit leptos-store = { version = "0.5", features = ["ssr", "hydrate", "middleware"] } # Full enterprise leptos-store = { version = "0.5", features = ["full"] } ``` -------------------------------- ### Building Leptos Store Documentation (Bash) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Contains bash commands for building and managing documentation for a Leptos project using `rustdoc`. Commands include building the documentation, building and opening it in a browser, and including private items in the documentation. ```bash # Build documentation make doc # Build and open in browser make doc-open # Include private items make doc-private ``` -------------------------------- ### Auto-load State from LocalStorage in Rust Source: https://github.com/web-mech/leptos-store/blob/main/examples/persistence-example/README.md This Rust code snippet illustrates how to automatically load the application's state from localStorage when the application starts. It uses an effect to retrieve data from localStorage using the key 'notes_store'. If data is found, it's deserialized from JSON using serde, and then loaded back into the leptos-store. This enables state restoration after a page refresh or application restart. ```rust Effect::new(move |_| { if let Ok(Some(data)) = storage.get_item("notes_store") { if let Ok(state) = serde_json::from_str(&data) { store.load_state(state); } } }); ``` -------------------------------- ### Create and Access RootStore Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/07-store-composition.md Demonstrates how to build a RootStore by aggregating multiple individual domain stores (AuthStore, CartStore, UiStore). It shows type-safe access, checking for store presence, and retrieving stores using `get` or `expect`. ```rust use leptos_store::composition::{RootStore, CompositeStore}; // Build a root store from individual domain stores let root = RootStore::builder() .with_store(AuthStore::new()) .with_store(CartStore::new()) .with_store(UiStore::new()) .build(); // Type-safe access — returns Option<&S> let auth: &AuthStore = root.get::().unwrap(); // Or panic with helpful message if missing let cart: &CartStore = root.expect::(); // Check presence assert!(root.contains::()); assert_eq!(root.len(), 3); ``` -------------------------------- ### Creating a Leptos Store Source: https://github.com/web-mech/leptos-store/blob/main/SKILL.md Demonstrates how to create a reactive store using the `store!` macro in Leptos. This includes defining state, getters, mutators, and actions for managing application state. ```rust use leptos_store::store; #[store] struct CounterStore { count: i32, } impl CounterStore { fn increment(&mut self) { self.count += 1; } } ``` -------------------------------- ### Hydrate Store on Client Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Shows the client-side code for using a store that was hydrated from the server. It emphasizes reading the store from the DOM context instead of creating a new instance. ```rust // Server: Serialize and embed state // let hydration_script = provide_hydrated_store(store); // Client: Read from DOM, not create new // Assuming MyStore is defined elsewhere // let store = use_hydrated_store::(); // NOT MyStore::new() ``` -------------------------------- ### Derive Serialize and Deserialize for State Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Illustrates adding `Serialize` and `Deserialize` derives to your state struct. This is necessary for the store's state to be correctly serialized and deserialized, especially for hydration. ```rust #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct MyState { // fields... } ``` -------------------------------- ### Set Store Initialization Order Hints with RootStoreBuilder (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/10-cache-invalidation.md Demonstrates how to use `RootStore::builder()` with `with_store_after` to provide hints for store initialization order, ensuring dependent stores are hydrated after their dependencies. ```rust use leptos_store::composition::RootStore; let root = RootStore::builder() .with_store(AuthStore::new()) .with_store_after::<_, AuthStore>(CartStore::new()) // cart after auth .with_store_after::<_, CartStore>(TotalsStore::new()) // totals after cart .build(); ``` -------------------------------- ### Using Stores in Leptos Components (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Shows how to provide and use a store within Leptos components. It demonstrates `provide_store` to make the store available in the component tree and `use_store` to access it in a child component, including accessing state and calling actions. ```rust use leptos::prelude::*; use leptos_store::prelude::*; #[component] pub fn App() -> impl IntoView { // Provide store to component tree provide_store(CounterStore::new()); view! { } } #[component] fn Counter() -> impl IntoView { let store = use_store::(); view! {

"Count: " {move || store.state().get().count}

"Doubled: " {move || store.doubled()}

} } ``` -------------------------------- ### Counter Component Usage (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/examples/counter-example/README.md A Leptos component that utilizes the `CounterStore` to display and interact with the counter state. It demonstrates how to access state, derived values, and trigger actions through the store. ```rust use leptos_store::prelude::*; use crate::counter_store::CounterStore; #[component] fn Counter() -> impl IntoView { let store = use_store::(); view! {

"Count: " {move || store.state().get().count}

"Doubled: " {move || store.doubled()}

// Components can only call PUBLIC actions
} } ``` -------------------------------- ### Integrate StoreDependencyGraph with StoreCoordinator (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/10-cache-invalidation.md Demonstrates how to integrate a `StoreDependencyGraph` with a `StoreCoordinator` to manage store initialization and coordination. It shows how to query the dependency graph from the coordinator after setup. ```rust let coord = StoreCoordinator::with_event_bus(Arc::clone(&bus)) .with_dependency_graph(graph); // Query the graph later if let Some(graph) = coord.dependency_graph() { let order = graph.topological_order().unwrap(); // Initialize stores in this order } ``` -------------------------------- ### Leptos Store SSR Hydration Sequence Diagram Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Illustrates the flow of data and state transfer during SSR hydration with leptos-store. It shows the interaction between the server, client, external API, and the TokenStore. ```mermaid sequenceDiagram participant API as External API participant Server as Server (SSR) participant HTML as HTML Response participant Client as Client (WASM) participant Store as TokenStore Note over Server: Build with --features ssr Server->>API: Fetch data API-->>Server: tokens[] Server->>Store: TokenStore::new_with_data(tokens) Server->>Server: provide_hydrated_store(store) Note over Server: Serializes state to JSON Server->>HTML: Render HTML + embedded state Note over HTML: HTML->>Client: Page loads in browser Note over Client: Build with --features hydrate Client->>Client: WASM loads, calls hydrate() Client->>HTML: use_hydrated_store::() Note over Client: Finds script tag by ID
Extracts JSON content HTML-->>Client: JSON state data Client->>Store: Deserialize into TokenStore Note over Store: State restored!
No flash, no re-fetch Client->>Client: Component renders with data Client->>API: Optional: Start polling for updates ``` -------------------------------- ### leptos-store Watch Mode for Development Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Commands to enable watch mode in leptos-store, which automatically rebuilds and runs tests or linters when source files are modified, streamlining the development feedback loop. ```bash # Watch and run tests on changes make watch # Watch and run clippy on changes make watch-clippy ``` -------------------------------- ### Organize Stores with `namespace!` Macro Source: https://github.com/web-mech/leptos-store/blob/main/README.md The `namespace!` macro creates a typed container for multiple domain stores, simplifying management in large applications. It generates context helpers for providing and accessing these stores. ```rust use leptos_store::namespace; namespace! { pub AppStores { user: UserStore, products: ProductStore, cart: CartStore, orders: OrderStore, ui: UiStore, } } // Generated API: // AppStores::new(user, products, cart, orders, ui) // app_stores.user() -> &UserStore // provide_app_stores(stores) — wraps provide_context // use_app_stores() -> AppStores — wraps use_context ``` -------------------------------- ### Initialize EventBus and MiddlewareStores (Rust) Source: https://github.com/web-mech/leptos-store/blob/main/docs/skills/08-middleware.md Demonstrates the setup of `EventBus` for shared event infrastructure and `MiddlewareStore` for stores that utilize this bus. It involves creating a shared `Arc` and then initializing middleware stores with a clone of this bus. ```rust use leptos_store::middleware::{EventBus, MiddlewareStore}; use std::sync::Arc; // Create a shared event bus let bus = Arc::new(EventBus::new()); // Middleware stores share the same bus let cart_mw = MiddlewareStore::with_event_bus(CartStore::new(), Arc::clone(&bus)); let totals_mw = MiddlewareStore::with_event_bus(TotalsStore::new(), Arc::clone(&bus)); ``` -------------------------------- ### Store Definition with `store!` Macro in Rust Source: https://github.com/web-mech/leptos-store/blob/main/AUTHORING.md Demonstrates defining a store using the `store!` macro in Rust, which provides a more concise syntax. It includes defining the state, getters, private mutators, and public actions within the macro. ```rust use leptos_store::store; store! { pub CounterStore { state CounterState { count: i32 = 0, name: String = "Counter".to_string(), } getters { doubled(this) -> i32 { this.read(|s| s.count * 2) } } // PRIVATE - internal state changes only mutators { set_count(this, value: i32) { this.mutate(|s| s.count = value); } set_name(this, name: String) { this.mutate(|s| s.name = name); } } // PUBLIC - the external API for writes actions { increment(this) { let current = this.read(|s| s.count); this.set_count(current + 1); } rename(this, name: String) { this.set_name(name); } reset(this) { this.set_count(0); this.set_name(String::new()); } } } } ```