extract types

This commit is contained in:
Tao Tien 2026-02-07 17:46:03 -08:00
parent d7d567b0e6
commit c86f8d93f1
30 changed files with 986 additions and 474 deletions

12
Cargo.lock generated
View file

@ -3744,6 +3744,7 @@ dependencies = [
"bevy_ratatui",
"bevy_spacetimedb",
"clap",
"jong-types",
"log",
"rand 0.9.2",
"ratatui",
@ -3754,11 +3755,20 @@ dependencies = [
"tui-logger",
]
[[package]]
name = "jong-types"
version = "0.1.0"
dependencies = [
"bevy",
"spacetimedb",
"strum 0.27.2",
]
[[package]]
name = "jongline"
version = "0.1.0"
dependencies = [
"jong",
"jong-types",
"log",
"spacetimedb",
]

View file

@ -1,20 +1,16 @@
[workspace]
resolver = "3"
members = ["jong", "spacetimedb"]
members = ["jong", "jong-types", "spacetimedb"]
[workspace.dependencies]
bevy = "0.17.3"
bevy_ratatui = "0.10.0"
bevy_spacetimedb = "0.7"
clap = "4.5.54"
log = "0.4.29"
rand = "0.9.2"
ratatui = "0.30.0"
strum = "0.27.2"
tracing = "0.1.44"
tracing-subscriber = "0.3.22"
tui-logger = "0.18.0"
jong = { version = "0.1.0", path = "jong" }
jong-types = { version = "0.1.0", path = "jong-types" }
spacetimedb = "1.11.*"
[profile.dev]

View file

@ -22,6 +22,12 @@
in {
devShells.default = with pkgs;
mkShell rec {
nativeBuildInputs = [
pkg-config
# spacetimedb
openssl
binaryen
];
buildInputs =
[
# Rust dependencies
@ -29,7 +35,6 @@
extensions = ["rust-src" "rust-docs" "rustc-codegen-cranelift" "rust-analyzer" "rustfmt"];
targets = ["x86_64-unknown-linux-gnu" "wasm32-unknown-unknown"];
})
pkg-config
]
++ lib.optionals (lib.strings.hasInfix "linux" system) [
# for Linux
@ -47,10 +52,6 @@
xorg.libXrandr
libxkbcommon
wayland
# spacetimedb
openssl
binaryen
];
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
LD_LIBRARY_PATH = lib.makeLibraryPath buildInputs;

13
jong-types/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "jong-types"
version = "0.1.0"
edition = "2024"
[lib]
[dependencies]
bevy.version = "0.17.3"
bevy.default-features = false
spacetimedb.workspace = true
strum.workspace = true
strum.features = ["derive"]

77
jong-types/src/lib.rs Normal file
View file

@ -0,0 +1,77 @@
use bevy::prelude::*;
use spacetimedb::SpacetimeType;
use strum::FromRepr;
#[derive(Component, Debug, Clone, Copy, SpacetimeType)]
pub struct Tile {
pub suit: Suit,
}
#[derive(/* MapEntities, */ Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Suit {
Man(Rank),
Pin(Rank),
Sou(Rank),
Wind(Wind),
Dragon(Dragon),
}
impl Suit {
pub fn rank(&self) -> Option<Rank> {
match self {
Suit::Man(rank) => Some(*rank),
Suit::Pin(rank) => Some(*rank),
Suit::Sou(rank) => Some(*rank),
// Suit::Wind(wind) | Suit::Dragon(dragon) => None,
_ => None,
}
}
}
#[derive(Deref, DerefMut, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub struct Rank {
pub number: u8,
}
#[derive(FromRepr, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Wind {
Ton,
Nan,
Shaa,
Pei,
}
#[derive(Debug, FromRepr, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Dragon {
Haku,
Hatsu,
Chun,
}
pub fn tiles() -> Vec<Tile> {
let mut tiles = vec![];
for _ in 0..4 {
for i in 1..=9 {
tiles.push(Tile {
suit: Suit::Pin(Rank { number: i }),
});
tiles.push(Tile {
suit: Suit::Sou(Rank { number: i }),
});
tiles.push(Tile {
suit: Suit::Man(Rank { number: i }),
});
}
for i in 0..4 {
tiles.push(Tile {
suit: Suit::Wind(Wind::from_repr(i).unwrap()),
});
}
for i in 0..3 {
tiles.push(Tile {
suit: Suit::Dragon(Dragon::from_repr(i).unwrap()),
});
}
}
tiles
}

View file

@ -10,17 +10,23 @@ readme = false
[lib]
[dependencies]
bevy = { workspace = true, features = ["dynamic_linking"] }
bevy_ratatui = { workspace = true }
# bevy_ratatui = { git = "https://github.com/kenianbei/bevy_ratatui.git", rev = "e4b022308e08ab360ef89eca8e9f8b1c969e9a56" }
# bevy_ratatui = { path = "/home/tao/clones/bevy_ratatui" }
bevy_spacetimedb = { workspace = true }
bevy.features = ["dynamic_linking"]
bevy.version = "0.17.3"
bevy_ratatui = "0.10.0"
bevy_spacetimedb = "0.7"
clap = { workspace = true, features = ["derive"] }
log = { workspace = true, features = ["release_max_level_error", "max_level_trace"] }
jong-types = { version = "0.1.0", path = "../jong-types" }
log = { workspace = true, features = [
"release_max_level_error",
"max_level_trace",
] }
rand = { workspace = true }
ratatui = { workspace = true }
ratatui = "0.30.0"
spacetimedb.workspace = true
strum = { workspace = true, features = ["derive"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tui-logger = { workspace = true, features = ["tracing-support", "crossterm"] }
tui-logger.features = ["tracing-support", "crossterm"]
tui-logger.version = "0.18.0"

View file

@ -2,10 +2,8 @@ use std::mem::discriminant;
use bevy::prelude::*;
use crate::{
game::{GameState, player::Player, wall::Wall},
tile::Tile,
};
use crate::game::{GameState, player::Player, wall::Wall};
use jong_types::*;
#[derive(Component)]
pub struct Hand;

View file

@ -1,80 +1,59 @@
use bevy::prelude::*;
use spacetimedb::SpacetimeType;
use strum::FromRepr;
// use spacetimedb::SpacetimeType;
// use strum::FromRepr;
#[derive(Component, Debug, Clone, Copy, SpacetimeType)]
pub struct Tile {
pub suit: Suit,
}
use jong_types::*;
#[derive(/* MapEntities, */ Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Suit {
Man(Rank),
Pin(Rank),
Sou(Rank),
Wind(Wind),
Dragon(Dragon),
}
// #[derive(Component, Debug, Clone, Copy, SpacetimeType)]
// pub struct Tile {
// pub suit: Suit,
// }
impl Suit {
pub fn rank(&self) -> Option<Rank> {
match self {
Suit::Man(rank) => Some(*rank),
Suit::Pin(rank) => Some(*rank),
Suit::Sou(rank) => Some(*rank),
// Suit::Wind(wind) | Suit::Dragon(dragon) => None,
_ => None,
}
}
}
// #[derive(/* MapEntities, */ Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
// pub enum Suit {
// Man(Rank),
// Pin(Rank),
// Sou(Rank),
// Wind(Wind),
// Dragon(Dragon),
// }
#[derive(Deref, DerefMut, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub struct Rank {
pub number: u8,
}
// impl Suit {
// pub fn rank(&self) -> Option<Rank> {
// match self {
// Suit::Man(rank) => Some(*rank),
// Suit::Pin(rank) => Some(*rank),
// Suit::Sou(rank) => Some(*rank),
// // Suit::Wind(wind) | Suit::Dragon(dragon) => None,
// _ => None,
// }
// }
// }
#[derive(FromRepr, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Wind {
Ton,
Nan,
Shaa,
Pei,
}
// #[derive(Deref, DerefMut, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
// pub struct Rank {
// pub number: u8,
// }
#[derive(Debug, FromRepr, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
pub enum Dragon {
Haku,
Hatsu,
Chun,
}
// #[derive(FromRepr, Debug, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
// pub enum Wind {
// Ton,
// Nan,
// Shaa,
// Pei,
// }
// #[derive(Debug, FromRepr, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, SpacetimeType)]
// pub enum Dragon {
// Haku,
// Hatsu,
// Chun,
// }
#[derive(Component)]
pub struct Dora;
pub fn init_tiles(mut commands: Commands) {
let mut tiles = vec![];
for _ in 0..4 {
for i in 1..=9 {
tiles.push(Tile {
suit: Suit::Pin(Rank { number: i }),
});
tiles.push(Tile {
suit: Suit::Sou(Rank { number: i }),
});
tiles.push(Tile {
suit: Suit::Man(Rank { number: i }),
});
}
for i in 0..4 {
tiles.push(Tile {
suit: Suit::Wind(Wind::from_repr(i).unwrap()),
});
}
for i in 0..3 {
tiles.push(Tile {
suit: Suit::Dragon(Dragon::from_repr(i).unwrap()),
});
}
}
let tiles = tiles();
commands.spawn_batch(tiles);
}

View file

@ -9,7 +9,7 @@ use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use jong::game::hand::{Drawn, Hand};
use jong::game::player::{CurrentPlayer, MainPlayer, Player};
use jong::game::round::Wind;
use jong::tile::Tile;
// use jong_types::*;
use crate::tui::input::Hovered;
use crate::tui::layout::*;
@ -20,23 +20,24 @@ pub(crate) struct PickRegion {
pub(crate) area: Rect,
}
fn render_tile(tile: &Tile, hovered: bool) -> Paragraph<'_> {
fn render_tile(tile: &jong_types::Tile, hovered: bool) -> Paragraph<'_> {
use jong_types::*;
let block = ratatui::widgets::Block::bordered();
let mut widget = Paragraph::new(match &tile.suit {
jong::tile::Suit::Pin(rank) => format!("{}\np", rank.number),
jong::tile::Suit::Sou(rank) => format!("{}\ns", rank.number),
jong::tile::Suit::Man(rank) => format!("{}\nm", rank.number),
jong::tile::Suit::Wind(wind) => (match wind {
jong::tile::Wind::Ton => "e\nw",
jong::tile::Wind::Nan => "s\nw",
jong::tile::Wind::Shaa => "w\nw",
jong::tile::Wind::Pei => "n\nw",
Suit::Pin(rank) => format!("{}\np", rank.number),
Suit::Sou(rank) => format!("{}\ns", rank.number),
Suit::Man(rank) => format!("{}\nm", rank.number),
Suit::Wind(wind) => (match wind {
Wind::Ton => "e\nw",
Wind::Nan => "s\nw",
Wind::Shaa => "w\nw",
Wind::Pei => "n\nw",
})
.into(),
jong::tile::Suit::Dragon(dragon) => (match dragon {
jong::tile::Dragon::Haku => "w\nd",
jong::tile::Dragon::Hatsu => "g\nd",
jong::tile::Dragon::Chun => "r\nd",
Suit::Dragon(dragon) => (match dragon {
Dragon::Haku => "w\nd",
Dragon::Hatsu => "g\nd",
Dragon::Chun => "r\nd",
})
.into(),
})
@ -102,7 +103,7 @@ pub(crate) fn render_hands(
hovered: Query<Entity, With<Hovered>>,
layouts: Res<HandLayouts>,
tiles: Query<&Tile>,
tiles: Query<&jong_types::Tile>,
main_player: Single<(&Player, Entity, &Wind), With<MainPlayer>>,
curr_player: Single<Entity, With<CurrentPlayer>>,
players: Query<(&Player, Entity, &Children)>,

View file

@ -14,4 +14,4 @@ update:
nix flake update
spacetime:
spacetime dev --module-bindings-path modules_bindings
spacetime dev --module-bindings-path module_bindings fantastic-key-0909

View file

@ -0,0 +1,102 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub(super) struct AddPlayerArgs {
pub name: Option<String>,
}
impl From<AddPlayerArgs> for super::Reducer {
fn from(args: AddPlayerArgs) -> Self {
Self::AddPlayer { name: args.name }
}
}
impl __sdk::InModule for AddPlayerArgs {
type Module = super::RemoteModule;
}
pub struct AddPlayerCallbackId(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `add_player`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait add_player {
/// Request that the remote module invoke the reducer `add_player` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_add_player`] callbacks.
fn add_player(&self, name: Option<String>) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `add_player`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`AddPlayerCallbackId`] can be passed to [`Self::remove_on_add_player`]
/// to cancel the callback.
fn on_add_player(
&self,
callback: impl FnMut(&super::ReducerEventContext, &Option<String>) + Send + 'static,
) -> AddPlayerCallbackId;
/// Cancel a callback previously registered by [`Self::on_add_player`],
/// causing it not to run in the future.
fn remove_on_add_player(&self, callback: AddPlayerCallbackId);
}
impl add_player for super::RemoteReducers {
fn add_player(&self, name: Option<String>) -> __sdk::Result<()> {
self.imp.call_reducer("add_player", AddPlayerArgs { name })
}
fn on_add_player(
&self,
mut callback: impl FnMut(&super::ReducerEventContext, &Option<String>) + Send + 'static,
) -> AddPlayerCallbackId {
AddPlayerCallbackId(self.imp.on_reducer(
"add_player",
Box::new(move |ctx: &super::ReducerEventContext| {
#[allow(irrefutable_let_patterns)]
let super::ReducerEventContext {
event:
__sdk::ReducerEvent {
reducer: super::Reducer::AddPlayer { name },
..
},
..
} = ctx
else {
unreachable!()
};
callback(ctx, name)
}),
))
}
fn remove_on_add_player(&self, callback: AddPlayerCallbackId) {
self.imp.remove_on_reducer("add_player", callback.0)
}
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `add_player`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait set_flags_for_add_player {
/// Set the call-reducer flags for the reducer `add_player` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn add_player(&self, flags: __ws::CallReducerFlags);
}
impl set_flags_for_add_player for super::SetReducerFlags {
fn add_player(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("add_player", flags);
}
}

View file

@ -0,0 +1,20 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
#[derive(Copy, Eq, Hash)]
pub enum Dragon {
Haku,
Hatsu,
Chun,
}
impl __sdk::InModule for Dragon {
type Module = super::RemoteModule;
}

View file

@ -0,0 +1,96 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use super::hand_type::Hand;
use super::tile_type::Tile;
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
/// Table handle for the table `hand`.
///
/// Obtain a handle from the [`HandTableAccess::hand`] method on [`super::RemoteTables`],
/// like `ctx.db.hand()`.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.hand().on_insert(...)`.
pub struct HandTableHandle<'ctx> {
imp: __sdk::TableHandle<Hand>,
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
}
#[allow(non_camel_case_types)]
/// Extension trait for access to the table `hand`.
///
/// Implemented for [`super::RemoteTables`].
pub trait HandTableAccess {
#[allow(non_snake_case)]
/// Obtain a [`HandTableHandle`], which mediates access to the table `hand`.
fn hand(&self) -> HandTableHandle<'_>;
}
impl HandTableAccess for super::RemoteTables {
fn hand(&self) -> HandTableHandle<'_> {
HandTableHandle {
imp: self.imp.get_table::<Hand>("hand"),
ctx: std::marker::PhantomData,
}
}
}
pub struct HandInsertCallbackId(__sdk::CallbackId);
pub struct HandDeleteCallbackId(__sdk::CallbackId);
impl<'ctx> __sdk::Table for HandTableHandle<'ctx> {
type Row = Hand;
type EventContext = super::EventContext;
fn count(&self) -> u64 {
self.imp.count()
}
fn iter(&self) -> impl Iterator<Item = Hand> + '_ {
self.imp.iter()
}
type InsertCallbackId = HandInsertCallbackId;
fn on_insert(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> HandInsertCallbackId {
HandInsertCallbackId(self.imp.on_insert(Box::new(callback)))
}
fn remove_on_insert(&self, callback: HandInsertCallbackId) {
self.imp.remove_on_insert(callback.0)
}
type DeleteCallbackId = HandDeleteCallbackId;
fn on_delete(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> HandDeleteCallbackId {
HandDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
}
fn remove_on_delete(&self, callback: HandDeleteCallbackId) {
self.imp.remove_on_delete(callback.0)
}
}
#[doc(hidden)]
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
let _table = client_cache.get_or_make_table::<Hand>("hand");
}
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::TableUpdate<__ws::BsatnFormat>,
) -> __sdk::Result<__sdk::TableUpdate<Hand>> {
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
__sdk::InternalError::failed_parse("TableUpdate<Hand>", "TableUpdate")
.with_cause(e)
.into()
})
}

View file

@ -0,0 +1,18 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::tile_type::Tile;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct Hand {
pub player_id: u32,
pub tiles: Vec<Tile>,
}
impl __sdk::InModule for Hand {
type Module = super::RemoteModule;
}

View file

@ -1,103 +0,0 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub(super) struct IdentityDisconnectedArgs {}
impl From<IdentityDisconnectedArgs> for super::Reducer {
fn from(args: IdentityDisconnectedArgs) -> Self {
Self::IdentityDisconnected
}
}
impl __sdk::InModule for IdentityDisconnectedArgs {
type Module = super::RemoteModule;
}
pub struct IdentityDisconnectedCallbackId(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `identity_disconnected`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait identity_disconnected {
/// Request that the remote module invoke the reducer `identity_disconnected` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_identity_disconnected`] callbacks.
fn identity_disconnected(&self) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `identity_disconnected`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`IdentityDisconnectedCallbackId`] can be passed to [`Self::remove_on_identity_disconnected`]
/// to cancel the callback.
fn on_identity_disconnected(
&self,
callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> IdentityDisconnectedCallbackId;
/// Cancel a callback previously registered by [`Self::on_identity_disconnected`],
/// causing it not to run in the future.
fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId);
}
impl identity_disconnected for super::RemoteReducers {
fn identity_disconnected(&self) -> __sdk::Result<()> {
self.imp
.call_reducer("identity_disconnected", IdentityDisconnectedArgs {})
}
fn on_identity_disconnected(
&self,
mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> IdentityDisconnectedCallbackId {
IdentityDisconnectedCallbackId(self.imp.on_reducer(
"identity_disconnected",
Box::new(move |ctx: &super::ReducerEventContext| {
#[allow(irrefutable_let_patterns)]
let super::ReducerEventContext {
event:
__sdk::ReducerEvent {
reducer: super::Reducer::IdentityDisconnected {},
..
},
..
} = ctx
else {
unreachable!()
};
callback(ctx)
}),
))
}
fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId) {
self.imp
.remove_on_reducer("identity_disconnected", callback.0)
}
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `identity_disconnected`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait set_flags_for_identity_disconnected {
/// Set the call-reducer flags for the reducer `identity_disconnected` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn identity_disconnected(&self, flags: __ws::CallReducerFlags);
}
impl set_flags_for_identity_disconnected for super::SetReducerFlags {
fn identity_disconnected(&self, flags: __ws::CallReducerFlags) {
self.imp
.set_call_reducer_flags("identity_disconnected", flags);
}
}

View file

@ -6,23 +6,37 @@
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
pub mod add_reducer;
pub mod identity_connected_reducer;
pub mod identity_disconnected_reducer;
pub mod person_table;
pub mod person_type;
pub mod say_hello_reducer;
pub mod add_player_reducer;
pub mod dragon_type;
pub mod hand_table;
pub mod hand_type;
pub mod player_table;
pub mod player_type;
pub mod rank_type;
pub mod set_name_reducer;
pub mod shuffle_wall_reducer;
pub mod sort_hand_reducer;
pub mod suit_type;
pub mod tile_type;
pub mod wall_table;
pub mod wall_type;
pub mod wind_type;
pub use add_reducer::{add, set_flags_for_add, AddCallbackId};
pub use identity_connected_reducer::{
identity_connected, set_flags_for_identity_connected, IdentityConnectedCallbackId,
};
pub use identity_disconnected_reducer::{
identity_disconnected, set_flags_for_identity_disconnected, IdentityDisconnectedCallbackId,
};
pub use person_table::*;
pub use person_type::Person;
pub use say_hello_reducer::{say_hello, set_flags_for_say_hello, SayHelloCallbackId};
pub use add_player_reducer::{add_player, set_flags_for_add_player, AddPlayerCallbackId};
pub use dragon_type::Dragon;
pub use hand_table::*;
pub use hand_type::Hand;
pub use player_table::*;
pub use player_type::Player;
pub use rank_type::Rank;
pub use set_name_reducer::{set_flags_for_set_name, set_name, SetNameCallbackId};
pub use shuffle_wall_reducer::{set_flags_for_shuffle_wall, shuffle_wall, ShuffleWallCallbackId};
pub use sort_hand_reducer::{set_flags_for_sort_hand, sort_hand, SortHandCallbackId};
pub use suit_type::Suit;
pub use tile_type::Tile;
pub use wall_table::*;
pub use wall_type::Wall;
pub use wind_type::Wind;
#[derive(Clone, PartialEq, Debug)]
@ -32,10 +46,10 @@ pub use say_hello_reducer::{say_hello, set_flags_for_say_hello, SayHelloCallback
/// to indicate which reducer caused the event.
pub enum Reducer {
Add { name: String },
IdentityConnected,
IdentityDisconnected,
SayHello,
AddPlayer { name: Option<String> },
SetName { name: String },
ShuffleWall,
SortHand,
}
impl __sdk::InModule for Reducer {
@ -45,10 +59,10 @@ impl __sdk::InModule for Reducer {
impl __sdk::Reducer for Reducer {
fn reducer_name(&self) -> &'static str {
match self {
Reducer::Add { .. } => "add",
Reducer::IdentityConnected => "identity_connected",
Reducer::IdentityDisconnected => "identity_disconnected",
Reducer::SayHello => "say_hello",
Reducer::AddPlayer { .. } => "add_player",
Reducer::SetName { .. } => "set_name",
Reducer::ShuffleWall => "shuffle_wall",
Reducer::SortHand => "sort_hand",
_ => unreachable!(),
}
}
@ -57,20 +71,28 @@ impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer {
type Error = __sdk::Error;
fn try_from(value: __ws::ReducerCallInfo<__ws::BsatnFormat>) -> __sdk::Result<Self> {
match &value.reducer_name[..] {
"add" => {
Ok(__sdk::parse_reducer_args::<add_reducer::AddArgs>("add", &value.args)?.into())
}
"identity_connected" => Ok(__sdk::parse_reducer_args::<
identity_connected_reducer::IdentityConnectedArgs,
>("identity_connected", &value.args)?
"add_player" => Ok(
__sdk::parse_reducer_args::<add_player_reducer::AddPlayerArgs>(
"add_player",
&value.args,
)?
.into(),
),
"set_name" => Ok(__sdk::parse_reducer_args::<set_name_reducer::SetNameArgs>(
"set_name",
&value.args,
)?
.into()),
"identity_disconnected" => Ok(__sdk::parse_reducer_args::<
identity_disconnected_reducer::IdentityDisconnectedArgs,
>("identity_disconnected", &value.args)?
.into()),
"say_hello" => Ok(
__sdk::parse_reducer_args::<say_hello_reducer::SayHelloArgs>(
"say_hello",
"shuffle_wall" => Ok(
__sdk::parse_reducer_args::<shuffle_wall_reducer::ShuffleWallArgs>(
"shuffle_wall",
&value.args,
)?
.into(),
),
"sort_hand" => Ok(
__sdk::parse_reducer_args::<sort_hand_reducer::SortHandArgs>(
"sort_hand",
&value.args,
)?
.into(),
@ -89,7 +111,9 @@ impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer {
#[allow(non_snake_case)]
#[doc(hidden)]
pub struct DbUpdate {
person: __sdk::TableUpdate<Person>,
hand: __sdk::TableUpdate<Hand>,
player: __sdk::TableUpdate<Player>,
wall: __sdk::TableUpdate<Wall>,
}
impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate {
@ -98,9 +122,15 @@ impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate {
let mut db_update = DbUpdate::default();
for table_update in raw.tables {
match &table_update.table_name[..] {
"person" => db_update
.person
.append(person_table::parse_table_update(table_update)?),
"hand" => db_update
.hand
.append(hand_table::parse_table_update(table_update)?),
"player" => db_update
.player
.append(player_table::parse_table_update(table_update)?),
"wall" => db_update
.wall
.append(wall_table::parse_table_update(table_update)?),
unknown => {
return Err(__sdk::InternalError::unknown_name(
@ -127,7 +157,11 @@ impl __sdk::DbUpdate for DbUpdate {
) -> AppliedDiff<'_> {
let mut diff = AppliedDiff::default();
diff.person = cache.apply_diff_to_table::<Person>("person", &self.person);
diff.hand = cache.apply_diff_to_table::<Hand>("hand", &self.hand);
diff.player = cache
.apply_diff_to_table::<Player>("player", &self.player)
.with_updates_by_pk(|row| &row.identity);
diff.wall = cache.apply_diff_to_table::<Wall>("wall", &self.wall);
diff
}
@ -137,7 +171,9 @@ impl __sdk::DbUpdate for DbUpdate {
#[allow(non_snake_case)]
#[doc(hidden)]
pub struct AppliedDiff<'r> {
person: __sdk::TableAppliedDiff<'r, Person>,
hand: __sdk::TableAppliedDiff<'r, Hand>,
player: __sdk::TableAppliedDiff<'r, Player>,
wall: __sdk::TableAppliedDiff<'r, Wall>,
__unused: std::marker::PhantomData<&'r ()>,
}
@ -151,7 +187,9 @@ impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> {
event: &EventContext,
callbacks: &mut __sdk::DbCallbacks<RemoteModule>,
) {
callbacks.invoke_table_row_callbacks::<Person>("person", &self.person, event);
callbacks.invoke_table_row_callbacks::<Hand>("hand", &self.hand, event);
callbacks.invoke_table_row_callbacks::<Player>("player", &self.player, event);
callbacks.invoke_table_row_callbacks::<Wall>("wall", &self.wall, event);
}
}
@ -871,6 +909,8 @@ impl __sdk::SpacetimeModule for RemoteModule {
type SubscriptionHandle = SubscriptionHandle;
fn register_tables(client_cache: &mut __sdk::ClientCache<Self>) {
person_table::register_table(client_cache);
hand_table::register_table(client_cache);
player_table::register_table(client_cache);
wall_table::register_table(client_cache);
}
}

View file

@ -1,95 +0,0 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use super::person_type::Person;
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
/// Table handle for the table `person`.
///
/// Obtain a handle from the [`PersonTableAccess::person`] method on [`super::RemoteTables`],
/// like `ctx.db.person()`.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.person().on_insert(...)`.
pub struct PersonTableHandle<'ctx> {
imp: __sdk::TableHandle<Person>,
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
}
#[allow(non_camel_case_types)]
/// Extension trait for access to the table `person`.
///
/// Implemented for [`super::RemoteTables`].
pub trait PersonTableAccess {
#[allow(non_snake_case)]
/// Obtain a [`PersonTableHandle`], which mediates access to the table `person`.
fn person(&self) -> PersonTableHandle<'_>;
}
impl PersonTableAccess for super::RemoteTables {
fn person(&self) -> PersonTableHandle<'_> {
PersonTableHandle {
imp: self.imp.get_table::<Person>("person"),
ctx: std::marker::PhantomData,
}
}
}
pub struct PersonInsertCallbackId(__sdk::CallbackId);
pub struct PersonDeleteCallbackId(__sdk::CallbackId);
impl<'ctx> __sdk::Table for PersonTableHandle<'ctx> {
type Row = Person;
type EventContext = super::EventContext;
fn count(&self) -> u64 {
self.imp.count()
}
fn iter(&self) -> impl Iterator<Item = Person> + '_ {
self.imp.iter()
}
type InsertCallbackId = PersonInsertCallbackId;
fn on_insert(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> PersonInsertCallbackId {
PersonInsertCallbackId(self.imp.on_insert(Box::new(callback)))
}
fn remove_on_insert(&self, callback: PersonInsertCallbackId) {
self.imp.remove_on_insert(callback.0)
}
type DeleteCallbackId = PersonDeleteCallbackId;
fn on_delete(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> PersonDeleteCallbackId {
PersonDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
}
fn remove_on_delete(&self, callback: PersonDeleteCallbackId) {
self.imp.remove_on_delete(callback.0)
}
}
#[doc(hidden)]
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
let _table = client_cache.get_or_make_table::<Person>("person");
}
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::TableUpdate<__ws::BsatnFormat>,
) -> __sdk::Result<__sdk::TableUpdate<Person>> {
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
__sdk::InternalError::failed_parse("TableUpdate<Person>", "TableUpdate")
.with_cause(e)
.into()
})
}

View file

@ -0,0 +1,144 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use super::player_type::Player;
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
/// Table handle for the table `player`.
///
/// Obtain a handle from the [`PlayerTableAccess::player`] method on [`super::RemoteTables`],
/// like `ctx.db.player()`.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.player().on_insert(...)`.
pub struct PlayerTableHandle<'ctx> {
imp: __sdk::TableHandle<Player>,
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
}
#[allow(non_camel_case_types)]
/// Extension trait for access to the table `player`.
///
/// Implemented for [`super::RemoteTables`].
pub trait PlayerTableAccess {
#[allow(non_snake_case)]
/// Obtain a [`PlayerTableHandle`], which mediates access to the table `player`.
fn player(&self) -> PlayerTableHandle<'_>;
}
impl PlayerTableAccess for super::RemoteTables {
fn player(&self) -> PlayerTableHandle<'_> {
PlayerTableHandle {
imp: self.imp.get_table::<Player>("player"),
ctx: std::marker::PhantomData,
}
}
}
pub struct PlayerInsertCallbackId(__sdk::CallbackId);
pub struct PlayerDeleteCallbackId(__sdk::CallbackId);
impl<'ctx> __sdk::Table for PlayerTableHandle<'ctx> {
type Row = Player;
type EventContext = super::EventContext;
fn count(&self) -> u64 {
self.imp.count()
}
fn iter(&self) -> impl Iterator<Item = Player> + '_ {
self.imp.iter()
}
type InsertCallbackId = PlayerInsertCallbackId;
fn on_insert(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> PlayerInsertCallbackId {
PlayerInsertCallbackId(self.imp.on_insert(Box::new(callback)))
}
fn remove_on_insert(&self, callback: PlayerInsertCallbackId) {
self.imp.remove_on_insert(callback.0)
}
type DeleteCallbackId = PlayerDeleteCallbackId;
fn on_delete(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> PlayerDeleteCallbackId {
PlayerDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
}
fn remove_on_delete(&self, callback: PlayerDeleteCallbackId) {
self.imp.remove_on_delete(callback.0)
}
}
#[doc(hidden)]
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
let _table = client_cache.get_or_make_table::<Player>("player");
_table.add_unique_constraint::<__sdk::Identity>("identity", |row| &row.identity);
}
pub struct PlayerUpdateCallbackId(__sdk::CallbackId);
impl<'ctx> __sdk::TableWithPrimaryKey for PlayerTableHandle<'ctx> {
type UpdateCallbackId = PlayerUpdateCallbackId;
fn on_update(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
) -> PlayerUpdateCallbackId {
PlayerUpdateCallbackId(self.imp.on_update(Box::new(callback)))
}
fn remove_on_update(&self, callback: PlayerUpdateCallbackId) {
self.imp.remove_on_update(callback.0)
}
}
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::TableUpdate<__ws::BsatnFormat>,
) -> __sdk::Result<__sdk::TableUpdate<Player>> {
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
__sdk::InternalError::failed_parse("TableUpdate<Player>", "TableUpdate")
.with_cause(e)
.into()
})
}
/// Access to the `identity` unique index on the table `player`,
/// which allows point queries on the field of the same name
/// via the [`PlayerIdentityUnique::find`] method.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.player().identity().find(...)`.
pub struct PlayerIdentityUnique<'ctx> {
imp: __sdk::UniqueConstraintHandle<Player, __sdk::Identity>,
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
}
impl<'ctx> PlayerTableHandle<'ctx> {
/// Get a handle on the `identity` unique index on the table `player`.
pub fn identity(&self) -> PlayerIdentityUnique<'ctx> {
PlayerIdentityUnique {
imp: self
.imp
.get_unique_constraint::<__sdk::Identity>("identity"),
phantom: std::marker::PhantomData,
}
}
}
impl<'ctx> PlayerIdentityUnique<'ctx> {
/// Find the subscribed row whose `identity` column value is equal to `col_val`,
/// if such a row is present in the client cache.
pub fn find(&self, col_val: &__sdk::Identity) -> Option<Player> {
self.imp.find(col_val)
}
}

View file

@ -0,0 +1,18 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct Player {
pub identity: __sdk::Identity,
pub id: u32,
pub name: Option<String>,
pub host: bool,
}
impl __sdk::InModule for Player {
type Module = super::RemoteModule;
}

View file

@ -6,10 +6,10 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct Person {
pub name: String,
pub struct Rank {
pub number: u8,
}
impl __sdk::InModule for Person {
impl __sdk::InModule for Rank {
type Module = super::RemoteModule;
}

View file

@ -6,65 +6,65 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub(super) struct AddArgs {
pub(super) struct SetNameArgs {
pub name: String,
}
impl From<AddArgs> for super::Reducer {
fn from(args: AddArgs) -> Self {
Self::Add { name: args.name }
impl From<SetNameArgs> for super::Reducer {
fn from(args: SetNameArgs) -> Self {
Self::SetName { name: args.name }
}
}
impl __sdk::InModule for AddArgs {
impl __sdk::InModule for SetNameArgs {
type Module = super::RemoteModule;
}
pub struct AddCallbackId(__sdk::CallbackId);
pub struct SetNameCallbackId(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `add`.
/// Extension trait for access to the reducer `set_name`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait add {
/// Request that the remote module invoke the reducer `add` to run as soon as possible.
pub trait set_name {
/// Request that the remote module invoke the reducer `set_name` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_add`] callbacks.
fn add(&self, name: String) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `add`.
/// and its status can be observed by listening for [`Self::on_set_name`] callbacks.
fn set_name(&self, name: String) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `set_name`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`AddCallbackId`] can be passed to [`Self::remove_on_add`]
/// The returned [`SetNameCallbackId`] can be passed to [`Self::remove_on_set_name`]
/// to cancel the callback.
fn on_add(
fn on_set_name(
&self,
callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static,
) -> AddCallbackId;
/// Cancel a callback previously registered by [`Self::on_add`],
) -> SetNameCallbackId;
/// Cancel a callback previously registered by [`Self::on_set_name`],
/// causing it not to run in the future.
fn remove_on_add(&self, callback: AddCallbackId);
fn remove_on_set_name(&self, callback: SetNameCallbackId);
}
impl add for super::RemoteReducers {
fn add(&self, name: String) -> __sdk::Result<()> {
self.imp.call_reducer("add", AddArgs { name })
impl set_name for super::RemoteReducers {
fn set_name(&self, name: String) -> __sdk::Result<()> {
self.imp.call_reducer("set_name", SetNameArgs { name })
}
fn on_add(
fn on_set_name(
&self,
mut callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static,
) -> AddCallbackId {
AddCallbackId(self.imp.on_reducer(
"add",
) -> SetNameCallbackId {
SetNameCallbackId(self.imp.on_reducer(
"set_name",
Box::new(move |ctx: &super::ReducerEventContext| {
#[allow(irrefutable_let_patterns)]
let super::ReducerEventContext {
event:
__sdk::ReducerEvent {
reducer: super::Reducer::Add { name },
reducer: super::Reducer::SetName { name },
..
},
..
@ -76,27 +76,27 @@ impl add for super::RemoteReducers {
}),
))
}
fn remove_on_add(&self, callback: AddCallbackId) {
self.imp.remove_on_reducer("add", callback.0)
fn remove_on_set_name(&self, callback: SetNameCallbackId) {
self.imp.remove_on_reducer("set_name", callback.0)
}
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `add`.
/// Extension trait for setting the call-flags for the reducer `set_name`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait set_flags_for_add {
/// Set the call-reducer flags for the reducer `add` to `flags`.
pub trait set_flags_for_set_name {
/// Set the call-reducer flags for the reducer `set_name` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn add(&self, flags: __ws::CallReducerFlags);
fn set_name(&self, flags: __ws::CallReducerFlags);
}
impl set_flags_for_add for super::SetReducerFlags {
fn add(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("add", flags);
impl set_flags_for_set_name for super::SetReducerFlags {
fn set_name(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("set_name", flags);
}
}

View file

@ -6,64 +6,63 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub(super) struct IdentityConnectedArgs {}
pub(super) struct ShuffleWallArgs {}
impl From<IdentityConnectedArgs> for super::Reducer {
fn from(args: IdentityConnectedArgs) -> Self {
Self::IdentityConnected
impl From<ShuffleWallArgs> for super::Reducer {
fn from(args: ShuffleWallArgs) -> Self {
Self::ShuffleWall
}
}
impl __sdk::InModule for IdentityConnectedArgs {
impl __sdk::InModule for ShuffleWallArgs {
type Module = super::RemoteModule;
}
pub struct IdentityConnectedCallbackId(__sdk::CallbackId);
pub struct ShuffleWallCallbackId(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `identity_connected`.
/// Extension trait for access to the reducer `shuffle_wall`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait identity_connected {
/// Request that the remote module invoke the reducer `identity_connected` to run as soon as possible.
pub trait shuffle_wall {
/// Request that the remote module invoke the reducer `shuffle_wall` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_identity_connected`] callbacks.
fn identity_connected(&self) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `identity_connected`.
/// and its status can be observed by listening for [`Self::on_shuffle_wall`] callbacks.
fn shuffle_wall(&self) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `shuffle_wall`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`IdentityConnectedCallbackId`] can be passed to [`Self::remove_on_identity_connected`]
/// The returned [`ShuffleWallCallbackId`] can be passed to [`Self::remove_on_shuffle_wall`]
/// to cancel the callback.
fn on_identity_connected(
fn on_shuffle_wall(
&self,
callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> IdentityConnectedCallbackId;
/// Cancel a callback previously registered by [`Self::on_identity_connected`],
) -> ShuffleWallCallbackId;
/// Cancel a callback previously registered by [`Self::on_shuffle_wall`],
/// causing it not to run in the future.
fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId);
fn remove_on_shuffle_wall(&self, callback: ShuffleWallCallbackId);
}
impl identity_connected for super::RemoteReducers {
fn identity_connected(&self) -> __sdk::Result<()> {
self.imp
.call_reducer("identity_connected", IdentityConnectedArgs {})
impl shuffle_wall for super::RemoteReducers {
fn shuffle_wall(&self) -> __sdk::Result<()> {
self.imp.call_reducer("shuffle_wall", ShuffleWallArgs {})
}
fn on_identity_connected(
fn on_shuffle_wall(
&self,
mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> IdentityConnectedCallbackId {
IdentityConnectedCallbackId(self.imp.on_reducer(
"identity_connected",
) -> ShuffleWallCallbackId {
ShuffleWallCallbackId(self.imp.on_reducer(
"shuffle_wall",
Box::new(move |ctx: &super::ReducerEventContext| {
#[allow(irrefutable_let_patterns)]
let super::ReducerEventContext {
event:
__sdk::ReducerEvent {
reducer: super::Reducer::IdentityConnected {},
reducer: super::Reducer::ShuffleWall {},
..
},
..
@ -75,27 +74,27 @@ impl identity_connected for super::RemoteReducers {
}),
))
}
fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId) {
self.imp.remove_on_reducer("identity_connected", callback.0)
fn remove_on_shuffle_wall(&self, callback: ShuffleWallCallbackId) {
self.imp.remove_on_reducer("shuffle_wall", callback.0)
}
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `identity_connected`.
/// Extension trait for setting the call-flags for the reducer `shuffle_wall`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait set_flags_for_identity_connected {
/// Set the call-reducer flags for the reducer `identity_connected` to `flags`.
pub trait set_flags_for_shuffle_wall {
/// Set the call-reducer flags for the reducer `shuffle_wall` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn identity_connected(&self, flags: __ws::CallReducerFlags);
fn shuffle_wall(&self, flags: __ws::CallReducerFlags);
}
impl set_flags_for_identity_connected for super::SetReducerFlags {
fn identity_connected(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("identity_connected", flags);
impl set_flags_for_shuffle_wall for super::SetReducerFlags {
fn shuffle_wall(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("shuffle_wall", flags);
}
}

View file

@ -6,63 +6,63 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub(super) struct SayHelloArgs {}
pub(super) struct SortHandArgs {}
impl From<SayHelloArgs> for super::Reducer {
fn from(args: SayHelloArgs) -> Self {
Self::SayHello
impl From<SortHandArgs> for super::Reducer {
fn from(args: SortHandArgs) -> Self {
Self::SortHand
}
}
impl __sdk::InModule for SayHelloArgs {
impl __sdk::InModule for SortHandArgs {
type Module = super::RemoteModule;
}
pub struct SayHelloCallbackId(__sdk::CallbackId);
pub struct SortHandCallbackId(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `say_hello`.
/// Extension trait for access to the reducer `sort_hand`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait say_hello {
/// Request that the remote module invoke the reducer `say_hello` to run as soon as possible.
pub trait sort_hand {
/// Request that the remote module invoke the reducer `sort_hand` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_say_hello`] callbacks.
fn say_hello(&self) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `say_hello`.
/// and its status can be observed by listening for [`Self::on_sort_hand`] callbacks.
fn sort_hand(&self) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `sort_hand`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`SayHelloCallbackId`] can be passed to [`Self::remove_on_say_hello`]
/// The returned [`SortHandCallbackId`] can be passed to [`Self::remove_on_sort_hand`]
/// to cancel the callback.
fn on_say_hello(
fn on_sort_hand(
&self,
callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> SayHelloCallbackId;
/// Cancel a callback previously registered by [`Self::on_say_hello`],
) -> SortHandCallbackId;
/// Cancel a callback previously registered by [`Self::on_sort_hand`],
/// causing it not to run in the future.
fn remove_on_say_hello(&self, callback: SayHelloCallbackId);
fn remove_on_sort_hand(&self, callback: SortHandCallbackId);
}
impl say_hello for super::RemoteReducers {
fn say_hello(&self) -> __sdk::Result<()> {
self.imp.call_reducer("say_hello", SayHelloArgs {})
impl sort_hand for super::RemoteReducers {
fn sort_hand(&self) -> __sdk::Result<()> {
self.imp.call_reducer("sort_hand", SortHandArgs {})
}
fn on_say_hello(
fn on_sort_hand(
&self,
mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static,
) -> SayHelloCallbackId {
SayHelloCallbackId(self.imp.on_reducer(
"say_hello",
) -> SortHandCallbackId {
SortHandCallbackId(self.imp.on_reducer(
"sort_hand",
Box::new(move |ctx: &super::ReducerEventContext| {
#[allow(irrefutable_let_patterns)]
let super::ReducerEventContext {
event:
__sdk::ReducerEvent {
reducer: super::Reducer::SayHello {},
reducer: super::Reducer::SortHand {},
..
},
..
@ -74,27 +74,27 @@ impl say_hello for super::RemoteReducers {
}),
))
}
fn remove_on_say_hello(&self, callback: SayHelloCallbackId) {
self.imp.remove_on_reducer("say_hello", callback.0)
fn remove_on_sort_hand(&self, callback: SortHandCallbackId) {
self.imp.remove_on_reducer("sort_hand", callback.0)
}
}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `say_hello`.
/// Extension trait for setting the call-flags for the reducer `sort_hand`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait set_flags_for_say_hello {
/// Set the call-reducer flags for the reducer `say_hello` to `flags`.
pub trait set_flags_for_sort_hand {
/// Set the call-reducer flags for the reducer `sort_hand` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn say_hello(&self, flags: __ws::CallReducerFlags);
fn sort_hand(&self, flags: __ws::CallReducerFlags);
}
impl set_flags_for_say_hello for super::SetReducerFlags {
fn say_hello(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("say_hello", flags);
impl set_flags_for_sort_hand for super::SetReducerFlags {
fn sort_hand(&self, flags: __ws::CallReducerFlags) {
self.imp.set_call_reducer_flags("sort_hand", flags);
}
}

View file

@ -0,0 +1,27 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::dragon_type::Dragon;
use super::rank_type::Rank;
use super::wind_type::Wind;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub enum Suit {
Man(Rank),
Pin(Rank),
Sou(Rank),
Wind(Wind),
Dragon(Dragon),
}
impl __sdk::InModule for Suit {
type Module = super::RemoteModule;
}

View file

@ -0,0 +1,17 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::suit_type::Suit;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct Tile {
pub suit: Suit,
}
impl __sdk::InModule for Tile {
type Module = super::RemoteModule;
}

View file

@ -0,0 +1,96 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use super::tile_type::Tile;
use super::wall_type::Wall;
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
/// Table handle for the table `wall`.
///
/// Obtain a handle from the [`WallTableAccess::wall`] method on [`super::RemoteTables`],
/// like `ctx.db.wall()`.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.wall().on_insert(...)`.
pub struct WallTableHandle<'ctx> {
imp: __sdk::TableHandle<Wall>,
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
}
#[allow(non_camel_case_types)]
/// Extension trait for access to the table `wall`.
///
/// Implemented for [`super::RemoteTables`].
pub trait WallTableAccess {
#[allow(non_snake_case)]
/// Obtain a [`WallTableHandle`], which mediates access to the table `wall`.
fn wall(&self) -> WallTableHandle<'_>;
}
impl WallTableAccess for super::RemoteTables {
fn wall(&self) -> WallTableHandle<'_> {
WallTableHandle {
imp: self.imp.get_table::<Wall>("wall"),
ctx: std::marker::PhantomData,
}
}
}
pub struct WallInsertCallbackId(__sdk::CallbackId);
pub struct WallDeleteCallbackId(__sdk::CallbackId);
impl<'ctx> __sdk::Table for WallTableHandle<'ctx> {
type Row = Wall;
type EventContext = super::EventContext;
fn count(&self) -> u64 {
self.imp.count()
}
fn iter(&self) -> impl Iterator<Item = Wall> + '_ {
self.imp.iter()
}
type InsertCallbackId = WallInsertCallbackId;
fn on_insert(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> WallInsertCallbackId {
WallInsertCallbackId(self.imp.on_insert(Box::new(callback)))
}
fn remove_on_insert(&self, callback: WallInsertCallbackId) {
self.imp.remove_on_insert(callback.0)
}
type DeleteCallbackId = WallDeleteCallbackId;
fn on_delete(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> WallDeleteCallbackId {
WallDeleteCallbackId(self.imp.on_delete(Box::new(callback)))
}
fn remove_on_delete(&self, callback: WallDeleteCallbackId) {
self.imp.remove_on_delete(callback.0)
}
}
#[doc(hidden)]
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
let _table = client_cache.get_or_make_table::<Wall>("wall");
}
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::TableUpdate<__ws::BsatnFormat>,
) -> __sdk::Result<__sdk::TableUpdate<Wall>> {
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {
__sdk::InternalError::failed_parse("TableUpdate<Wall>", "TableUpdate")
.with_cause(e)
.into()
})
}

View file

@ -0,0 +1,17 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::tile_type::Tile;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct Wall {
pub tiles: Vec<Tile>,
}
impl __sdk::InModule for Wall {
type Module = super::RemoteModule;
}

View file

@ -0,0 +1,22 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
#[derive(Copy, Eq, Hash)]
pub enum Wind {
Ton,
Nan,
Shaa,
Pei,
}
impl __sdk::InModule for Wind {
type Module = super::RemoteModule;
}

View file

@ -11,4 +11,4 @@ crate-type = ["cdylib"]
[dependencies]
spacetimedb = { workspace = true }
log = { workspace = true }
jong = { workspace = true }
jong-types = { workspace = true }

View file

@ -1,11 +1,13 @@
use spacetimedb::{Identity, ReducerContext, Table, rand::Rng, reducer, table};
use spacetimedb::{rand::seq::SliceRandom, reducer, table, Identity, ReducerContext, Table};
use jong::tile::Tile;
use jong_types::*;
#[table(name = player, public)]
pub struct Player {
#[primary_key]
identity: Identity,
#[auto_inc]
id: u32,
name: Option<String>,
host: bool,
}
@ -15,20 +17,14 @@ pub struct Wall {
tiles: Vec<Tile>,
}
#[reducer(init)]
pub fn init(_ctx: &ReducerContext) {
// Called when the module is initially published
#[table(name = hand)]
pub struct Hand {
player_id: u32,
tiles: Vec<Tile>,
}
#[reducer(client_connected)]
pub fn identity_connected(_ctx: &ReducerContext) {
// Called everytime a new client connects
}
#[reducer(client_disconnected)]
pub fn identity_disconnected(_ctx: &ReducerContext) {
// Called everytime a client disconnects
}
#[reducer]
pub fn add_player(ctx: &ReducerContext, name: Option<String>) {}
#[reducer]
pub fn set_name(ctx: &ReducerContext, name: String) -> Result<(), String> {
@ -49,14 +45,31 @@ pub fn set_name(ctx: &ReducerContext, name: String) -> Result<(), String> {
#[reducer]
pub fn shuffle_wall(ctx: &ReducerContext) {
let mut rng = ctx.rng();
let mut tiles: Vec<Tile> = todo();
// rng.fill();
// let tiles = rng.sh;
let mut tiles: Vec<Tile> = tiles();
tiles.shuffle(&mut rng);
ctx.db.wall().insert(Wall { tiles });
}
#[reducer]
pub fn sort_hand(ctx: &ReducerContext) {
todo!()
}
// #[reducer(init)]
// pub fn init(_ctx: &ReducerContext) {
// // Called when the module is initially published
// }
// #[reducer(client_connected)]
// pub fn identity_connected(_ctx: &ReducerContext) {
// // Called everytime a new client connects
// }
// #[reducer(client_disconnected)]
// pub fn identity_disconnected(_ctx: &ReducerContext) {
// // Called everytime a client disconnects
// }
// #[reducer]
// pub fn add(ctx: &ReducerContext, name: String) {
// ctx.db.player().insert(Player { name });