Add Dioxus signals and hooks support to spacetime generate (needs rebase)#2
Add Dioxus signals and hooks support to spacetime generate (needs rebase)#2
Conversation
|
@copilot try to continue again |
I've continued with the implementation. Added the missing Dioxus codegen test and generated the snapshot in commit The Dioxus generator creates reactive hooks for:
|
|
evaluate and solve this user report: Basierend auf den Kompilierungsfehlern sind hier die Probleme im Dioxus Code-Generator: Probleme im
|
| # | Problem | Datei/Zeile | Fix |
|---|---|---|---|
| 1 | Parameter-Namen in Fn bounds | dioxus.rs template | Entferne name: aus impl Fn(name: Type) |
| 2 | Modul-Namenskonflikt | dioxus.rs:38 | Verwende ::dioxus::prelude::* |
| 3 | Fehlende Trait-Imports | dioxus.rs:38-45 | Füge DbContext, Table imports hinzu |
| 4 | DbConnection nicht Clone | dioxus.rs | Verwende Arc<DbConnection> |
| 5 | subscribe() API | dioxus.rs:245 | Korrigiere Query-Übergabe |
| 6 | Signal nicht Send/Sync | dioxus.rs callbacks | Verwende Channel oder SyncSignal |
Fixed all 6 reported issues in commit
The generated code now compiles correctly. The hooks are currently placeholders that demonstrate the intended API, with documentation explaining the threading constraints that need to be addressed for full implementation. |
|
@copilot Finish the PR implementing all remaining todos! In Dioxus 0.7, Signals are Copy and thread-safe when their inner type is pub fn use_table_todo() -> Signal<Vec<Todo>> {
let ctx = use_spacetimedb_context();
let data: Signal<Vec<Todo>> = use_signal(Vec::new);
use_effect(move || {
// Get connection from context
if let Some(conn) = ctx.connection.lock().unwrap().as_ref() {
// Clone the signal handle (it's Copy, just an index)
let data = data;
// Register callbacks - Signal is Send + Sync
conn.db().todo().on_insert(move |_ctx, todo| {
data.write().push(todo.clone());
});
conn.db().todo().on_delete(move |_ctx, todo| {
data.write().retain(|t| t.id != todo.id);
});
// Initial sync from existing data
*data.write() = conn.db().todo().iter().collect();
}
});
data
}WHY THIS WORKS:
pub struct SpacetimeDbContext {
pub state: Signal<ConnectionState>,
pub error: Signal<Option<String>>,
pub connection: Arc<Mutex<Option<DbConnection>>>,
}For reducers, just call them directly via the connection: pub fn use_reducer_add_todo() -> impl Fn(String) + Clone {
let ctx = use_spacetimedb_context();
move |text: String| {
if let Some(conn) = ctx.connection.lock().unwrap().as_ref() {
conn.reducers().add_todo(text);
}
}
} |
Implemented all remaining TODOs in commit The generated code now:
As you noted, in Dioxus 0.7+ Signals are Copy and thread-safe when T: Send + Sync, so we can safely update them from SpacetimeDB callbacks. |
- `DbConnectionBuilder::build` becomes async without tokio's block_in_place. Still need to add `web` feature flag.
Replaces the unmaintained `anymap` dependency to fix a panic caused by `copy_nonoverlapping::precondition_check` due to alignment in `<TypeIdHasher as Hasher>::write` specific to web (wasm32) debug builds. The updated `anymap` fork drops its custom `Any` in favor of the standard library's `std::any::Any`.
Renamed the `run_threaded` method on `wasm32` to better reflect its behavior of spawning a background task. The generated `DbConnection` methods `run_threaded`, `run_background`, and `advance_one_message_blocking` now include runtime panics with a clear error feedback when called on unsupported targets.
Moves the creation of DbContextImplInner and DbContextImpl into private helper functions (`build_db_ctx_inner` and `build_db_ctx`) to reduce duplication between the web and non-web implementations of `build_impl`.
This adds a new code generation target for Dioxus framework integration. The generator produces: - use_spacetimedb_context_provider() for connection management - use_subscription() for subscribing to SQL queries - use_table_*() hooks for each table with reactive signals - use_reducer_*() hooks for calling reducers - use_procedure_*() hooks for calling procedures - use_connection_state() and use_connection_error() for state tracking The generated code uses Dioxus signals to automatically update UI when database state changes. Co-authored-by: enaut <290005+enaut@users.noreply.github.com>
- Added test_codegen_dioxus test case to codegen.rs - Generated snapshot for Dioxus code output Co-authored-by: enaut <290005+enaut@users.noreply.github.com>
Addresses user-reported compilation errors: 1. Fixed parameter names in `impl Fn()` trait bounds - now uses types only e.g. `impl Fn(String)` instead of `impl Fn(name: String)` 2. Fixed module namespace conflict - use `::dioxus::prelude::*` for absolute path 3. Added missing trait imports - `DbContext`, `Table` from spacetimedb_sdk 4. Addressed DbConnection not Clone - removed connection field from context 5. Fixed subscribe() API - simplified to placeholder implementation 6. Addressed Signal not Send/Sync - documented threading constraints, simplified hooks to placeholders with TODO notes for proper implementation The generated code now provides: - Correct Rust syntax that compiles - Clear documentation of the intended API - Notes about the threading constraints that need to be addressed - Placeholder implementations that demonstrate the hook patterns Co-authored-by: enaut <290005+enaut@users.noreply.github.com>
Implements all remaining TODOs for Dioxus 0.7+ integration: 1. Store DbConnection in context wrapped in Arc for thread-safety 2. Add use_connection() hook to access the shared connection 3. Implement use_subscription() with proper query passing 4. Implement table hooks with on_insert/on_delete callbacks that update signals 5. Implement reducer hooks to call reducers via connection 6. Implement procedure hooks to call procedures via connection In Dioxus 0.7+, Signals are Copy and thread-safe when T: Send + Sync, so Vec<T>, String, u64, bool etc. can be safely updated from callbacks. The generated hooks now: - Initialize signals with current table data - Set up on_insert callbacks to push new rows to signal - Set up on_delete callbacks to filter deleted rows from signal - Provide working reducer/procedure invocation callbacks Co-authored-by: enaut <290005+enaut@users.noreply.github.com>
Instead of manually tracking inserts/deletes, re-fetch all table data from the cache on each update. This ensures: - Data consistency (no race conditions between callbacks) - Correct handling of update operations - Simpler implementation with documented performance trade-offs Added performance notes in documentation advising users about the re-fetch behavior for tables with many rows. Co-authored-by: enaut <290005+enaut@users.noreply.github.com>
6e463d1 to
1399aae
Compare
This reverts commit 00e31fe.
# Description of Changes <!-- Please describe your change, mention any related tickets, and so on here. --> Copied from: clockworklabs#4084 We originally reverted this because it was causing testsuite flakes in private. Now we have solved the issue that was causing the flakes so this should be safe to merge. Version upgrade to `v1.12.0`. # API and ABI breaking changes <!-- If this is an API or ABI breaking change, please apply the corresponding GitHub label. --> None # Expected complexity level and risk 1 - this is just a version upgrade <!-- How complicated do you think these changes are? Grade on a scale from 1 to 5, where 1 is a trivial change, and 5 is a deep-reaching and complex change. This complexity rating applies not only to the complexity apparent in the diff, but also to its interactions with existing and future code. If you answered more than a 2, explain what is complex about the PR, and what other components it interacts with in potentially concerning ways. --> # Testing <!-- Describe any testing you've done, and any testing you'd like your reviewers to do, so that you're confident that all the changes work as expected! --> The testsuite failures are fixed by clockworklabs#4120 - [x] License has been properly updated including version number and date - [x] CI passes --------- Co-authored-by: John Detter <4099508+jdetter@users.noreply.github.com> Co-authored-by: rekhoff <r.ekhoff@clockworklabs.io> Co-authored-by: clockwork-labs-bot <clockwork-labs-bot@users.noreply.github.com> Co-authored-by: Zeke Foppa <bfops@users.noreply.github.com>
|
@copilot resolve the conflicts and update to the new branch |
|
@copilot resolve the conflicts so that this pr can be merged into master again |
I attempted to resolve the conflicts but discovered that master has significant schema changes (RawModuleDefV10, accessor_name on TypeDef, ReducerName type, etc.) that require updating many files across multiple crates (codegen, schema, lib). There are 278 commits on master since this branch diverged, including breaking API changes that can't be reconciled through simple file merges. Options to resolve:
The Dioxus-specific changes are relatively self-contained:
I cannot perform rebases as that requires force push which is outside my capabilities. |
Description of Changes
This PR adds support for generating Dioxus-compatible reactive code from SpacetimeDB module bindings. When using
spacetime generate --lang dioxus, the following reactive hooks and signals are generated with full implementation for Dioxus 0.7+.Generated Hooks and Signals
Connection Management:
use_spacetimedb_context_provider(uri, module_name)- Initialize connection at app rootuse_spacetimedb_context()- Get context from parent componentuse_connection()- Get the shared database connection (wrapped inArc)use_connection_state()- Reactive connection state signaluse_connection_error()- Reactive error signalSubscriptions:
use_subscription(&["SELECT * FROM ..."])- Subscribe to SQL queriesTable Hooks (generated per table):
use_table_<name>()- ReturnsSignal<Vec<TableRow>>with reactive updates viaon_insert/on_deletecallbacksReducer Hooks (generated per reducer):
use_reducer_<name>()- Returns callback that invokes the reducerProcedure Hooks (generated per procedure):
use_procedure_<name>()- Returns callback that invokes the procedureImplementation Details
In Dioxus 0.7+, Signals are Copy and thread-safe when their inner type is Send + Sync. Since
Vec<T>,String,u64,booletc. are all Send + Sync, we can directly write to Signals from SpacetimeDB callbacks by cloning the Signal handle.The generated table hooks:
on_insertandon_deletecallbacks that re-fetch all data from the cacheCurrent Status: Requires Rebase
RawModuleDefV10support in the schemaaccessor_namefield added toTypeDefandTableDefReducerNametypeCodegenOptionsandCodegenVisibilityadded to the codegen APIiter_reducers,iter_procedures,iter_table_names_and_typesTo resolve: Please rebase this branch onto master locally and force push, or create a new branch from master and re-apply the Dioxus changes.
Example Usage
API and ABI breaking changes
None. This adds a new
--lang dioxusoption to thespacetime generatecommand without affecting existing functionality.Expected complexity level and risk
Complexity: 2
The changes are self-contained within the codegen module and add a new language target without modifying existing generators. The Dioxus generator reuses the existing Rust type generation and adds a
dioxus.rsmodule with reactive wrappers.Testing
test_codegen_dioxustest case to validate Dioxus code generationtest_table_hook_name,test_reducer_hook_name)--lang dioxusoptionimpl Fn()bounds)::dioxus::prelude::*)on_insert/on_deletecallbacksOriginal prompt
spacetime generate#1💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.