Compare commits

..

15 Commits

Author SHA1 Message Date
Savanni D'Gerinel 154efcb6df Set up a GM control panel that can control the currently selected background 2024-11-19 22:48:36 -05:00
Savanni D'Gerinel 2ab6e88634 Start using the code-generated types module 2024-11-19 16:21:16 -05:00
Savanni D'Gerinel e20ec206a8 Add a package for shared server types 2024-11-19 16:02:32 -05:00
Savanni D'Gerinel c1ee4074b0 Organize the player view and tabletop 2024-11-19 14:53:42 -05:00
Savanni D'Gerinel f0ce3a9fab Rename playfield to tabletop 2024-11-19 08:53:04 -05:00
Savanni D'Gerinel e5deaa51d9 Extract the websocket code into a wrapper component 2024-11-19 00:09:48 -05:00
Savanni D'Gerinel 45275be11b Serve up the background image via the websocket 2024-11-18 23:32:54 -05:00
Savanni D'Gerinel 54162d0072 Move client construction up to app root 2024-11-18 20:52:04 -05:00
Savanni D'Gerinel a8170fd5c6 Try out rendering some basic components with a websocket 2024-11-18 20:35:35 -05:00
Savanni D'Gerinel 0237393c0b Set up a websocket that relays messages 2024-11-18 19:08:49 -05:00
Savanni D'Gerinel 962ea66506 Move the handlers out of main.rs 2024-11-12 09:45:34 -05:00
Savanni D'Gerinel 69ef3c3892 Load up thumbnails of all images in the image directory 2024-11-12 00:16:54 -05:00
Savanni D'Gerinel 6416931c67 Apply a maximum size to the playing field 2024-11-11 23:22:41 -05:00
Savanni D'Gerinel c35cbd75d7 Overhaul the UI application and build a placeholder for loading the background 2024-11-11 23:13:52 -05:00
Savanni D'Gerinel addfd2072c Create an image server and create the playing field 2024-11-11 19:58:50 -05:00
52 changed files with 17995 additions and 1106 deletions

319
Cargo.lock generated
View File

@ -350,22 +350,6 @@ version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
[[package]]
name = "bike"
version = "0.1.0"
dependencies = [
"az",
"cortex-m",
"cortex-m-rt",
"embedded-alloc",
"embedded-hal 0.2.7",
"fixed",
"fugit",
"lights-core",
"panic-halt 0.2.0",
"rp-pico 0.8.0",
]
[[package]] [[package]]
name = "bindgen" name = "bindgen"
version = "0.69.5" version = "0.69.5"
@ -408,18 +392,6 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61" checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61"
[[package]]
name = "bitfield"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
[[package]]
name = "bitfield"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d7e60934ceec538daadb9d8432424ed043a904d8e0243f3c6446bce549a46ac"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
@ -550,7 +522,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
name = "changeset" name = "changeset"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"uuid 1.10.0", "uuid 1.11.0",
] ]
[[package]] [[package]]
@ -759,38 +731,6 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cortex-m"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ec610d8f49840a5b376c69663b6369e71f4b34484b9b2eb29fb918d92516cb9"
dependencies = [
"bare-metal",
"bitfield 0.13.2",
"embedded-hal 0.2.7",
"volatile-register",
]
[[package]]
name = "cortex-m-rt"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee84e813d593101b1723e13ec38b6ab6abbdbaaa4546553f5395ed274079ddb1"
dependencies = [
"cortex-m-rt-macros",
]
[[package]]
name = "cortex-m-rt-macros"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f6f3e36f203cfedbc78b357fb28730aa2c6dc1ab060ee5c2405e843988d3c7"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.14" version = "0.2.14"
@ -1033,66 +973,6 @@ dependencies = [
"serde 1.0.210", "serde 1.0.210",
] ]
[[package]]
name = "embedded-alloc"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddae17915accbac2cfbc64ea0ae6e3b330e6ea124ba108dada63646fd3c6f815"
dependencies = [
"critical-section",
"linked_list_allocator",
]
[[package]]
name = "embedded-dma"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "994f7e5b5cb23521c22304927195f236813053eb9c065dd2226a32ba64695446"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "embedded-hal"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff"
dependencies = [
"nb 0.1.3",
"void",
]
[[package]]
name = "embedded-hal"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "361a90feb7004eca4019fb28352a9465666b24f840f5c3cddf0ff13920590b89"
[[package]]
name = "embedded-hal-async"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4c685bbef7fe13c3c6dd4da26841ed3980ef33e841cddfa15ce8a8fb3f1884"
dependencies = [
"embedded-hal 1.0.0",
]
[[package]]
name = "embedded-hal-nb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fba4268c14288c828995299e59b12babdbe170f6c6d73731af1b4648142e8605"
dependencies = [
"embedded-hal 1.0.0",
"nb 1.1.0",
]
[[package]]
name = "embedded-io"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]] [[package]]
name = "emseries" name = "emseries"
version = "0.6.0" version = "0.6.0"
@ -1945,26 +1825,6 @@ dependencies = [
"crunchy", "crunchy",
] ]
[[package]]
name = "halloween-leds"
version = "0.1.0"
dependencies = [
"cortex-m-rt",
"embedded-hal 1.0.0",
"embedded-io",
"panic-halt 1.0.0",
"rp-pico 0.9.0",
]
[[package]]
name = "hash32"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
dependencies = [
"byteorder",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.14.5" version = "0.14.5"
@ -2014,16 +1874,6 @@ dependencies = [
"http 0.2.12", "http 0.2.12",
] ]
[[package]]
name = "heapless"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [
"hash32",
"stable_deref_trait",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.4.1" version = "0.4.1"
@ -3035,18 +2885,6 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "panic-halt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812"
[[package]]
name = "panic-halt"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a513e167849a384b7f9b746e517604398518590a9142f4846a32e3c2a4de7b11"
[[package]] [[package]]
name = "parking" name = "parking"
version = "2.2.1" version = "2.2.1"
@ -3749,130 +3587,6 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "rp-pico"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6341771e6f8e5d130b2b3cbc23435b7847761adf198af09f4b2a60407d43bd56"
dependencies = [
"cortex-m-rt",
"fugit",
"rp2040-boot2",
"rp2040-hal 0.9.2",
"usb-device 0.2.9",
]
[[package]]
name = "rp-pico"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9342d3ac7011ac688300979e9b52a81f0add1d05feb02868cf94bfee0705b28"
dependencies = [
"cortex-m-rt",
"fugit",
"rp2040-boot2",
"rp2040-hal 0.10.2",
"usb-device 0.3.2",
]
[[package]]
name = "rp2040-boot2"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c92f344f63f950ee36cf4080050e4dce850839b9175da38f9d2ffb69b4dbb21"
dependencies = [
"crc-any",
]
[[package]]
name = "rp2040-hal"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ff2b9ae7e6dd6720fd9f64250c9087260e50fe98b6b032ccca65be3581167ca"
dependencies = [
"cortex-m",
"critical-section",
"embedded-dma",
"embedded-hal 0.2.7",
"frunk",
"fugit",
"itertools 0.10.5",
"nb 1.1.0",
"paste",
"pio",
"rand_core 0.6.4",
"rp2040-hal-macros",
"rp2040-pac 0.5.0",
"usb-device 0.2.9",
"vcell",
"void",
]
[[package]]
name = "rp2040-hal"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d11e711940087f2cdff8aeae9f4b902e2014c06a00b39a1092686b81ec973d6f"
dependencies = [
"bitfield 0.14.0",
"cortex-m",
"critical-section",
"embedded-dma",
"embedded-hal 0.2.7",
"embedded-hal 1.0.0",
"embedded-hal-async",
"embedded-hal-nb",
"embedded-io",
"frunk",
"fugit",
"itertools 0.10.5",
"nb 1.1.0",
"paste",
"pio",
"rand_core 0.6.4",
"rp2040-hal-macros",
"rp2040-pac 0.6.0",
"usb-device 0.3.2",
"vcell",
"void",
]
[[package]]
name = "rp2040-hal-macros"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86479063e497efe1ae81995ef9071f54fd1c7427e04d6c5b84cde545ff672a5e"
dependencies = [
"cortex-m-rt",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "rp2040-pac"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12d9d8375815f543f54835d01160d4e47f9e2cae75f17ff8f1ec19ce1da96e4c"
dependencies = [
"cortex-m",
"cortex-m-rt",
"critical-section",
"vcell",
]
[[package]]
name = "rp2040-pac"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83cbcd3f7a0ca7bbe61dc4eb7e202842bee4e27b769a7bf3a4a72fa399d6e404"
dependencies = [
"cortex-m",
"cortex-m-rt",
"critical-section",
"vcell",
]
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "0.9.6" version = "0.9.6"
@ -4923,9 +4637,9 @@ checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]] [[package]]
name = "typeshare" name = "typeshare"
version = "1.0.3" version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04f17399b76c2e743d58eac0635d7686e9c00f48cd4776f00695d9882a7d3187" checksum = "19be0f411120091e76e13e5a0186d8e2bcc3e7e244afdb70152197f1a8486ceb"
dependencies = [ dependencies = [
"chrono", "chrono",
"serde 1.0.210", "serde 1.0.210",
@ -5067,22 +4781,6 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "usb-device"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f6cc3adc849b5292b4075fc0d5fdcf2f24866e88e336dd27a8943090a520508"
[[package]]
name = "usb-device"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98816b1accafbb09085168b90f27e93d790b4bfa19d883466b5e53315b5f06a6"
dependencies = [
"heapless",
"portable-atomic",
]
[[package]] [[package]]
name = "utf-8" name = "utf-8"
version = "0.7.6" version = "0.7.6"
@ -5117,9 +4815,9 @@ dependencies = [
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.10.0" version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a"
dependencies = [ dependencies = [
"getrandom", "getrandom",
] ]
@ -5159,10 +4857,17 @@ name = "visions"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"authdb", "authdb",
"futures",
"http 1.1.0", "http 1.1.0",
"mime 0.3.17",
"mime_guess 2.0.5",
"serde 1.0.210", "serde 1.0.210",
"serde_json", "serde_json",
"tokio", "tokio",
"tokio-stream",
"typeshare",
"urlencoding",
"uuid 1.11.0",
"warp", "warp",
] ]

View File

@ -32,5 +32,6 @@ members = [
"sgf", "sgf",
"timezone-testing", "timezone-testing",
"tree", "tree",
"visions/server", "gm-dash/server", "halloween-leds" "visions/server",
"gm-dash/server"
] ]

View File

@ -5,11 +5,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1681202837, "lastModified": 1710146030,
"narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=", "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "cfacdce06f30d2b68473a46042957675eebb3401", "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -35,11 +35,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1681303793, "lastModified": 1714906307,
"narHash": "sha256-JEdQHsYuCfRL2PICHlOiH/2ue3DwoxUX7DJ6zZxZXFk=", "narHash": "sha256-UlRZtrCnhPFSJlDQE7M0eyhgvuuHBTe1eJ9N9AQlJQ0=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "fe2ecaf706a5907b5e54d979fbde4924d84b65fc", "rev": "25865a40d14b3f9cf19f19b924e2ab4069b09588",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -76,11 +76,11 @@
"nixpkgs": "nixpkgs_2" "nixpkgs": "nixpkgs_2"
}, },
"locked": { "locked": {
"lastModified": 1698205128, "lastModified": 1731966246,
"narHash": "sha256-jP+81TkldLtda8bzmsBWahETGsyFkoDOCT244YkA+S4=", "narHash": "sha256-e/V7Ffm5wPd9DVzCThnPZ7lFxd43bb64tSk8/oGP4Ag=",
"owner": "1Password", "owner": "1Password",
"repo": "typeshare", "repo": "typeshare",
"rev": "c3ee2ad8f27774c45db7af4f2ba746c4ae11de21", "rev": "e0e5f27ee34d7d4da76a9dc96a11552e98be56da",
"type": "github" "type": "github"
}, },
"original": { "original": {

View File

@ -44,6 +44,7 @@
pkgs.sqlx-cli pkgs.sqlx-cli
pkgs.udev pkgs.udev
pkgs.wasm-pack pkgs.wasm-pack
pkgs.go-task
typeshare.packages."x86_64-linux".default typeshare.packages."x86_64-linux".default
pkgs.nodePackages_latest.typescript-language-server pkgs.nodePackages_latest.typescript-language-server
]; ];

View File

@ -12,3 +12,10 @@ serde_json = { version = "*" }
serde = { version = "1" } serde = { version = "1" }
tokio = { version = "1", features = [ "full" ] } tokio = { version = "1", features = [ "full" ] }
warp = { version = "0.3" } warp = { version = "0.3" }
mime_guess = "2.0.5"
mime = "0.3.17"
uuid = { version = "1.11.0", features = ["v4"] }
futures = "0.3.31"
tokio-stream = "0.1.16"
typeshare = "1.0.4"
urlencoding = "2.1.3"

123
visions/server/src/core.rs Normal file
View File

@ -0,0 +1,123 @@
use std::{
collections::HashMap,
io::Read,
path::PathBuf,
sync::{Arc, RwLock},
};
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use urlencoding::decode;
use uuid::Uuid;
use crate::types::{AppError, Message, Tabletop, RGB};
#[derive(Debug)]
struct WebsocketClient {
sender: Option<UnboundedSender<Message>>,
}
#[derive(Debug)]
pub struct AppState {
pub image_base: PathBuf,
pub tabletop: Tabletop,
pub clients: HashMap<String, WebsocketClient>,
}
#[derive(Clone, Debug)]
pub struct Core(pub Arc<RwLock<AppState>>);
impl Core {
pub fn new() -> Self {
Self(Arc::new(RwLock::new(AppState {
image_base: PathBuf::from("/home/savanni/Pictures"),
tabletop: Tabletop {
background_color: RGB{ red: 0xca, green: 0xb9, blue: 0xbb },
background_image: None,
},
clients: HashMap::new(),
})))
}
pub fn register_client(&self) -> String {
let mut state = self.0.write().unwrap();
let uuid = Uuid::new_v4().simple().to_string();
let client = WebsocketClient { sender: None };
state.clients.insert(uuid.clone(), client);
uuid
}
pub fn unregister_client(&self, client_id: String) {
let mut state = self.0.write().unwrap();
let _ = state.clients.remove(&client_id);
}
pub fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> {
let mut state = self.0.write().unwrap();
match state.clients.get_mut(&client_id) {
Some(client) => {
let (tx, rx) = unbounded_channel();
client.sender = Some(tx);
rx
}
None => {
unimplemented!();
}
}
}
pub fn get_file(&self, file_name: String) -> Vec<u8> {
let file_name = decode(&file_name).expect("UTF-8");
let mut full_path = self.0.read().unwrap().image_base.clone();
full_path.push(file_name.to_string());
let mut content: Vec<u8> = Vec::new();
let mut file = std::fs::File::open(&full_path).unwrap();
file.read_to_end(&mut content).unwrap();
content
}
pub fn available_images(&self) -> Vec<String> {
std::fs::read_dir(&self.0.read().unwrap().image_base)
.unwrap()
.filter_map(|entry| match entry {
Ok(entry_) => match mime_guess::from_path(entry_.path()).first() {
Some(mime) if mime.type_() == mime::IMAGE => Some(
entry_
.path()
.file_name()
.and_then(|filename| filename.to_str())
.and_then(|filename| Some(filename.to_owned()))
.unwrap(),
),
_ => None,
},
Err(_) => None,
})
.collect()
}
pub fn set_background_image(&self, path: String) -> Result<(), AppError> {
let tabletop = {
let mut state = self.0.write().unwrap();
state.tabletop.background_image = Some(path.clone());
state.tabletop.clone()
};
self.publish(Message::UpdateTabletop(tabletop));
Ok(())
}
pub fn publish(&self, message: Message) {
let state = self.0.read().unwrap();
state.clients.values().for_each(|client| {
if let Some(ref sender) = client.sender {
let _ = sender.send(message.clone());
}
});
}
}

View File

@ -1,6 +1,13 @@
use authdb::{AuthDB, AuthToken}; use std::{pin::Pin, time::Duration};
use http::{response::Response, status::StatusCode, Error};
use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio_stream::wrappers::UnboundedReceiverStream;
use warp::{http::Response, reply::Reply, ws::Message};
use crate::core::Core;
/*
pub async fn handle_auth( pub async fn handle_auth(
auth_ctx: &AuthDB, auth_ctx: &AuthDB,
auth_token: AuthToken, auth_token: AuthToken,
@ -22,3 +29,93 @@ pub async fn handle_auth(
.body("".to_owned()), .body("".to_owned()),
} }
} }
*/
pub async fn handle_file(core: Core, file_name: String) -> impl Reply {
let mimetype = mime_guess::from_path(&file_name).first().unwrap();
let bytes = core.get_file(file_name);
Response::builder()
.header("application-type", mimetype.to_string())
.body(bytes)
.unwrap()
}
pub async fn handle_available_images(core: Core) -> impl Reply {
Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_string(&core.available_images()).unwrap())
.unwrap()
}
#[derive(Deserialize, Serialize)]
pub struct RegisterRequest {}
#[derive(Deserialize, Serialize)]
pub struct RegisterResponse {
url: String,
}
pub async fn handle_register_client(core: Core, request: RegisterRequest) -> impl Reply {
let client_id = core.register_client();
Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(
serde_json::to_string(&RegisterResponse {
url: format!("ws://127.0.0.1:8001/ws/{}", client_id),
})
.unwrap(),
)
.unwrap()
}
pub async fn handle_unregister_client(core: Core, client_id: String) -> impl Reply {
core.unregister_client(client_id);
warp::reply::reply()
}
pub async fn handle_connect_websocket(
core: Core,
ws: warp::ws::Ws,
client_id: String,
) -> impl Reply {
// println!("handle_connect_websocket: {}", client_id);
ws.on_upgrade(move |socket| {
let core = core.clone();
async move {
let (mut ws_sender, _) = socket.split();
let mut receiver = core.connect_client(client_id.clone());
tokio::task::spawn(async move {
let tabletop = core.0.read().unwrap().tabletop.clone();
let _ = ws_sender
.send(Message::text(
serde_json::to_string(&crate::types::Message::UpdateTabletop(tabletop))
.unwrap(),
))
.await;
while let Some(msg) = receiver.recv().await {
println!("Relaying message: {:?}", msg);
let _ = ws_sender
.send(Message::text(serde_json::to_string(&msg).unwrap()))
.await;
}
println!("process ended for id {}", client_id);
});
}
})
}
pub async fn handle_set_background_image(core: Core, image_name: String) -> impl Reply {
let _ = core.set_background_image(image_name);
Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "*")
.header("Content-Type", "application/json")
.body("")
.unwrap()
}

View File

@ -1,19 +1,24 @@
use authdb::{AuthDB, AuthError, AuthToken, SessionToken, Username}; use authdb::AuthError;
use handlers::{
handle_available_images, handle_connect_websocket, handle_file, handle_register_client, handle_set_background_image, handle_unregister_client, RegisterRequest
};
use std::{ use std::{
convert::Infallible, convert::Infallible,
net::{IpAddr, Ipv4Addr, SocketAddr}, net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
sync::Arc,
}; };
use warp::{ use warp::{
header, // header,
http::StatusCode, http::{Response, StatusCode},
reply::{Json, Reply}, reply::Reply,
Filter, Filter,
}; };
mod core;
mod handlers; mod handlers;
use handlers::handle_auth; // use handlers::handle_auth;
mod types;
#[derive(Debug)] #[derive(Debug)]
struct Unauthorized; struct Unauthorized;
@ -23,6 +28,7 @@ impl warp::reject::Reject for Unauthorized {}
struct AuthDBError(AuthError); struct AuthDBError(AuthError);
impl warp::reject::Reject for AuthDBError {} impl warp::reject::Reject for AuthDBError {}
/*
fn with_session( fn with_session(
auth_ctx: Arc<AuthDB>, auth_ctx: Arc<AuthDB>,
) -> impl Filter<Extract = (Username,), Error = warp::Rejection> + Clone { ) -> impl Filter<Extract = (Username,), Error = warp::Rejection> + Clone {
@ -71,8 +77,10 @@ fn route_echo_authenticated(
warp::reply::json(&vec!["authenticated", username.as_str(), param.as_str()]) warp::reply::json(&vec!["authenticated", username.as_str(), param.as_str()])
}) })
} }
*/
async fn handle_rejection(err: warp::Rejection) -> Result<impl Reply, Infallible> { async fn handle_rejection(err: warp::Rejection) -> Result<impl Reply, Infallible> {
println!("handle_rejection: {:?}", err);
if let Some(Unauthorized) = err.find() { if let Some(Unauthorized) = err.find() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
"".to_owned(), "".to_owned(),
@ -88,14 +96,71 @@ async fn handle_rejection(err: warp::Rejection) -> Result<impl Reply, Infallible
#[tokio::main] #[tokio::main]
pub async fn main() { pub async fn main() {
let auth_db = AuthDB::new(PathBuf::from("./auth_db.sqlite")) let core = core::Core::new();
.await let log = warp::log("visions::api");
.expect("AuthDB should initialize");
let auth_ctx: Arc<AuthDB> = Arc::new(auth_db);
let filter = route_echo_authenticated(auth_ctx.clone()) let route_image = warp::path!("api" / "v1" / "image" / String)
.or(route_authenticate(auth_ctx.clone())) .and(warp::get())
.or(route_echo_unauthenticated()) .then({
let core = core.clone();
move |file_name| handle_file(core.clone(), file_name)
});
let route_available_images = warp::path!("api" / "v1" / "image").and(warp::get()).then({
let core = core.clone();
move || handle_available_images(core.clone())
});
let route_register_client = warp::path!("api" / "v1" / "client")
.and(warp::post())
.then({
let core = core.clone();
move || handle_register_client(core.clone(), RegisterRequest {})
});
let route_unregister_client = warp::path!("api" / "v1" / "client" / String)
.and(warp::delete())
.then({
let core = core.clone();
move |client_id| handle_unregister_client(core.clone(), client_id)
});
let route_websocket = warp::path("ws")
.and(warp::ws())
.and(warp::path::param())
.then({
let core = core.clone();
move |ws, client_id| handle_connect_websocket(core.clone(), ws, client_id)
});
let route_set_bg_image_options = warp::path!("api" / "v1" / "tabletop" / "bg_image")
.and(warp::options())
.map({
move || {
Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "PUT")
.header("Access-Control-Allow-Headers", "content-type")
.header("Content-Type", "application/json")
.body("")
.unwrap()
}
});
let route_set_bg_image = warp::path!("api" / "v1" / "tabletop" / "bg_image")
.and(warp::put())
.and(warp::body::json())
.then({
let core = core.clone();
move |body| handle_set_background_image(core.clone(), body)
}).with(log);
let filter = route_register_client
.or(route_unregister_client)
.or(route_websocket)
.or(route_image)
.or(route_available_images)
.or(route_set_bg_image_options)
.or(route_set_bg_image)
.recover(handle_rejection); .recover(handle_rejection);
let server = warp::serve(filter); let server = warp::serve(filter);

View File

@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
use typeshare::typeshare;
#[derive(Debug)]
pub enum AppError {
JsonError(serde_json::Error),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct RGB {
pub red: u32,
pub green: u32,
pub blue: u32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct Tabletop {
pub background_color: RGB,
pub background_image: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type", content = "content")]
#[typeshare]
pub enum Message {
UpdateTabletop(Tabletop),
}

1991
visions/ui.backup/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
{
"name": "ui",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "GPL-3.0-or-later",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.8",
"@types/react-dom": "^18.2.4",
"copy-webpack-plugin": "^11.0.0",
"ts-loader": "^9.4.3",
"webpack": "^5.85.0",
"webpack-cli": "^5.1.3"
}
}

View File

@ -0,0 +1,23 @@
type PlayingField = {
backgroundImage: string;
}
class Client {
playingField(): PlayingField {
return { backgroundImage: "tower-in-mist.jpg" };
}
async getFile(filename: string): Promise<Blob | undefined> {
try {
const response = await fetch(`http://localhost:8001/api/v1/file/${filename}`);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const body = await response.blob();
return body;
} catch (error) {
console.error(error.message);
}
}
}

23
visions/ui/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
visions/ui/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,49 @@
{ {
"name": "ui", "name": "ui",
"version": "1.0.0", "version": "0.1.0",
"description": "", "private": true,
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "GPL-3.0-or-later",
"dependencies": { "dependencies": {
"react": "^18.2.0", "@testing-library/jest-dom": "^5.17.0",
"react-dom": "^18.2.0" "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.119",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/react-router": "^5.1.20",
"@types/react-router-dom": "^5.3.3",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^6.28.0",
"react-router-dom": "^6.28.0",
"react-scripts": "5.0.1",
"react-use-websocket": "^4.11.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4",
"visions-types": "../visions-types"
}, },
"devDependencies": { "scripts": {
"@types/react": "^18.2.8", "start": "react-scripts start",
"@types/react-dom": "^18.2.4", "build": "react-scripts build",
"copy-webpack-plugin": "^11.0.0", "test": "react-scripts test",
"ts-loader": "^9.4.3", "eject": "react-scripts eject"
"webpack": "^5.85.0", },
"webpack-cli": "^5.1.3" "eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
visions/ui/src/App.css Normal file
View File

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@ -0,0 +1,9 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
// render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

39
visions/ui/src/App.tsx Normal file
View File

@ -0,0 +1,39 @@
import React, { useEffect, useState } from 'react';
import './App.css';
import { Client } from './client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { GmView } from './views/GmView/GmView';
import { WebsocketProvider } from './components/WebsocketProvider';
import { PlayerView } from './views/PlayerView/PlayerView';
interface AppProps {
client: Client;
}
const App = ({ client }: AppProps) => {
console.log("rendering app");
const [websocketUrl, setWebsocketUrl] = useState<string | undefined>(undefined);
useEffect(() => {
client.registerWebsocket().then((url) => setWebsocketUrl(url))
}, [client]);
let router =
createBrowserRouter([
{
path: "/gm",
element: websocketUrl ? <WebsocketProvider websocketUrl={websocketUrl}> <GmView client={client} /> </WebsocketProvider> : <div> </div>
},
{
path: "/",
element: websocketUrl ? <WebsocketProvider websocketUrl={websocketUrl}> <PlayerView client={client} /> </WebsocketProvider> : <div> </div>
}
]);
return (
<div className="App">
<RouterProvider router={router} />
</div>
);
}
export default App;

47
visions/ui/src/client.ts Normal file
View File

@ -0,0 +1,47 @@
export type PlayingField = {
backgroundImage: string;
}
export class Client {
private base: URL;
constructor() {
this.base = new URL("http://localhost:8001");
}
registerWebsocket() {
const url = new URL(this.base);
url.pathname = `api/v1/client`;
return fetch(url, { method: 'POST' }).then((response) => response.json()).then((ws) => ws.url);
}
/*
unregisterWebsocket() {
const url = new URL(this.base);
url.pathname = `api/v1/client`;
return fetch(url, { method: 'POST' }).then((response => response.json()));
}
*/
imageUrl(imageId: string) {
const url = new URL(this.base);
url.pathname = `/api/v1/image/${imageId}`;
return url;
}
async playingField(): Promise<PlayingField> {
return { backgroundImage: "trans-ferris.jpg" };
}
async availableImages(): Promise<string[]> {
const url = new URL(this.base);
url.pathname = `/api/v1/image`;
return fetch(url).then((response) => response.json());
}
async setBackgroundImage(name: string) {
const url = new URL(this.base);
url.pathname = `/api/v1/tabletop/bg_image`;
return fetch(url, { method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify(name) });
}
}

View File

@ -0,0 +1,7 @@
.playing-field__background {
flex-grow: 1;
}
.playing-field__background > img {
max-width: 100%;
}

View File

@ -0,0 +1,14 @@
import React, { useContext } from 'react';
import './Tabletop.css';
import { RGB } from 'visions-types';
interface TabletopElementProps {
backgroundColor: RGB;
backgroundUrl: URL | undefined;
}
export const TabletopElement = ({ backgroundColor, backgroundUrl }: TabletopElementProps) => {
const tabletopColorStyle = `rgb(${backgroundColor.red}, ${backgroundColor.green}, ${backgroundColor.blue})`;
return <div> {backgroundUrl && <img src={backgroundUrl.toString()} alt="playing field" />} </div>
}

View File

@ -0,0 +1,4 @@
.thumbnail > img {
max-width: 300px;
max-height: 300px;
}

View File

@ -0,0 +1,16 @@
import React, { useEffect, useState } from 'react';
import { Client } from '../../client';
import './Thumbnail.css';
interface ThumbnailProps {
id: string;
url: URL;
onclick?: () => void;
}
export const ThumbnailComponent = ({ id, url, onclick }: ThumbnailProps) => {
const clickHandler = () => {
if (onclick) { onclick(); }
}
return (<div id={id} className="thumbnail" onClick={clickHandler}> <img src={url.toString()} /> </div>)
}

View File

@ -0,0 +1,44 @@
import React, { createContext, PropsWithChildren, useEffect, useReducer } from "react";
import useWebSocket from "react-use-websocket";
import { Message, Tabletop } from "visions-types";
type TabletopState = {
tabletop: Tabletop;
}
const initialState = (): TabletopState => ({ tabletop: { backgroundColor: { red: 0, green: 0, blue: 0 }, backgroundImage: undefined } });
export const WebsocketContext = createContext<TabletopState>(initialState());
interface WebsocketProviderProps {
websocketUrl: string;
}
export const WebsocketProvider = ({ websocketUrl, children }: PropsWithChildren<WebsocketProviderProps>) => {
const { lastMessage } = useWebSocket(websocketUrl);
const [state, dispatch] = useReducer(handleMessage, initialState());
useEffect(() => {
if (lastMessage !== null) {
const message: Message = JSON.parse(lastMessage.data);
dispatch(message);
}
}, [lastMessage]);
return (<WebsocketContext.Provider value={state}>
{children}
</WebsocketContext.Provider>);
}
const handleMessage = (state: TabletopState, message: Message): TabletopState => {
console.log(message);
switch (message.type) {
case "UpdateTabletop": {
return {
...state,
tabletop: message.content,
}
}
}
}

13
visions/ui/src/index.css Normal file
View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

22
visions/ui/src/index.tsx Normal file
View File

@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Client } from './client';
const client = new Client();
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App client={client} />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

1
visions/ui/src/logo.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

1
visions/ui/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -0,0 +1,4 @@
.gm-view {
display: flex;
width: 100%;
}

View File

@ -0,0 +1,28 @@
import React, { useContext, useEffect, useState } from 'react';
import { Client, PlayingField } from '../../client';
import { TabletopElement } from '../../components/Tabletop/Tabletop';
import { ThumbnailComponent } from '../../components/Thumbnail/Thumbnail';
import { WebsocketContext } from '../../components/WebsocketProvider';
import './GmView.css';
interface GmViewProps {
client: Client
}
export const GmView = ({ client }: GmViewProps) => {
const { tabletop } = useContext(WebsocketContext);
const [images, setImages] = useState<string[]>([]);
useEffect(() => {
client.availableImages().then((images) => setImages(images));
}, [client]);
const backgroundUrl = tabletop.backgroundImage ? client.imageUrl(tabletop.backgroundImage) : undefined;
return (<div className="gm-view">
<div>
{images.map((imageName) => <ThumbnailComponent id={imageName} url={client.imageUrl(imageName)} onclick={() => { client.setBackgroundImage(imageName); }} />)}
</div>
<TabletopElement backgroundColor={tabletop.backgroundColor} backgroundUrl={backgroundUrl} />
</div>)
}

View File

@ -0,0 +1,18 @@
.player-view {
display: flex;
width: 100%;
}
.player-view__left-panel {
flex-grow: 0;
min-width: 100px;
max-width: 20%;
}
.player-view__right-panel {
flex-grow: 0;
min-width: 100px;
max-width: 20%;
}

View File

@ -0,0 +1,24 @@
import React, { useContext } from 'react';
import './PlayerView.css';
import { WebsocketContext } from '../../components/WebsocketProvider';
import { Client } from '../../client';
import { TabletopElement } from '../../components/Tabletop/Tabletop';
interface PlayerViewProps {
client: Client;
}
export const PlayerView = ({ client }: PlayerViewProps) => {
const { tabletop } = useContext(WebsocketContext);
const backgroundColor = tabletop.backgroundColor;
const tabletopColorStyle = `rgb(${backgroundColor.red}, ${backgroundColor.green}, ${backgroundColor.blue})`;
const backgroundUrl = tabletop.backgroundImage ? client.imageUrl(tabletop.backgroundImage) : undefined;
return (<div className="player-view" style={{ backgroundColor: tabletopColorStyle}}>
<div className="player-view__left-panel"> Left Side </div>
<TabletopElement backgroundColor={backgroundColor} backgroundUrl={backgroundUrl} />
<div className="player-view__right-panel"> Right Side </div>
</div>)
}

27
visions/ui/tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src",
"gen"
]
}

2
visions/visions-types/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
dist
visions.ts

View File

@ -0,0 +1,7 @@
version: '3'
tasks:
build:
cmds:
- typeshare --lang typescript --output-file visions.ts ../server/src
- npx tsc

28
visions/visions-types/package-lock.json generated Normal file
View File

@ -0,0 +1,28 @@
{
"name": "visions-types",
"version": "0.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "visions-types",
"version": "0.0.1",
"license": "ISC",
"dependencies": {
"typescript": "^5.6.3"
}
},
"node_modules/typescript": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz",
"integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}

View File

@ -0,0 +1,14 @@
{
"name": "visions-types",
"version": "0.0.1",
"description": "Shared data types for Visions",
"main": "visions.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"typescript": "^5.6.3"
}
}

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["./visions.ts"]
}