Compare commits

..

2 Commits

Author SHA1 Message Date
Savanni D'Gerinel f4d990546b Remove the legacy glib channel 2024-11-08 09:51:53 -05:00
Savanni D'Gerinel 288cecc92f Extract animations into a subcrate 2024-11-08 09:47:01 -05:00
84 changed files with 2453 additions and 18838 deletions

1
.envrc
View File

@ -1,2 +1 @@
mkdir .direnv
use flake

1489
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
[workspace]
resolver = "2"
members = [
# "authdb",
"authdb",
# "bike-lights/bike",
"bike-lights/core",
"bike-lights/simulator",
@ -14,7 +14,7 @@ members = [
"cyberpunk-splash",
"dashboard",
"emseries",
# "file-service",
"file-service",
"fitnesstrax/core",
"fitnesstrax/app",
"fluent-ergonomics",
@ -32,6 +32,5 @@ members = [
"sgf",
"timezone-testing",
"tree",
"visions/server",
"gm-dash/server"
"visions/server", "gm-dash/server"
]

View File

@ -18,7 +18,9 @@ base64ct = { version = "1", features = [ "alloc" ] }
clap = { version = "4", features = [ "derive" ] }
serde = { version = "1.0", features = ["derive"] }
sha2 = { version = "0.10" }
sqlx = { version = "0.8", features = [ "runtime-tokio", "sqlite" ] }
sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite" ] }
# sqlformat introduced a mistaken breaking change in 0.2.7
sqlformat = { version = "=0.2.6" }
thiserror = { version = "1" }
tokio = { version = "1", features = [ "full" ] }
uuid = { version = "0.4", features = [ "serde", "v4" ] }

View File

@ -0,0 +1,121 @@
use fixed::types::U16F0;
use crate::{
calculate_frames, Animation, BodyPattern, DashboardPattern, Fade, FadeDirection, Instant, BLINKER_FRAMES, LEFT_BLINKER_BODY, LEFT_BLINKER_DASHBOARD, OFF_BODY, OFF_DASHBOARD, RIGHT_BLINKER_BODY, RIGHT_BLINKER_DASHBOARD
};
pub enum BlinkerDirection {
Left,
Right,
}
pub struct Blinker {
transition: Fade,
fade_in: Fade,
fade_out: Fade,
direction: FadeDirection,
start_time: Instant,
frames: U16F0,
}
impl Blinker {
pub fn new(
starting_dashboard: DashboardPattern,
starting_body: BodyPattern,
direction: BlinkerDirection,
time: Instant,
) -> Self {
let mut ending_dashboard = OFF_DASHBOARD.clone();
match direction {
BlinkerDirection::Left => {
ending_dashboard[0].r = LEFT_BLINKER_DASHBOARD[0].r;
ending_dashboard[0].g = LEFT_BLINKER_DASHBOARD[0].g;
ending_dashboard[0].b = LEFT_BLINKER_DASHBOARD[0].b;
}
BlinkerDirection::Right => {
ending_dashboard[2].r = RIGHT_BLINKER_DASHBOARD[2].r;
ending_dashboard[2].g = RIGHT_BLINKER_DASHBOARD[2].g;
ending_dashboard[2].b = RIGHT_BLINKER_DASHBOARD[2].b;
}
}
let mut ending_body = OFF_BODY.clone();
match direction {
BlinkerDirection::Left => {
for i in 0..30 {
ending_body[i].r = LEFT_BLINKER_BODY[i].r;
ending_body[i].g = LEFT_BLINKER_BODY[i].g;
ending_body[i].b = LEFT_BLINKER_BODY[i].b;
}
}
BlinkerDirection::Right => {
for i in 30..60 {
ending_body[i].r = RIGHT_BLINKER_BODY[i].r;
ending_body[i].g = RIGHT_BLINKER_BODY[i].g;
ending_body[i].b = RIGHT_BLINKER_BODY[i].b;
}
}
}
Blinker {
transition: Fade::new(
starting_dashboard.clone(),
starting_body.clone(),
ending_dashboard.clone(),
ending_body.clone(),
BLINKER_FRAMES,
time,
),
fade_in: Fade::new(
OFF_DASHBOARD.clone(),
OFF_BODY.clone(),
ending_dashboard.clone(),
ending_body.clone(),
BLINKER_FRAMES,
time,
),
fade_out: Fade::new(
ending_dashboard.clone(),
ending_body.clone(),
OFF_DASHBOARD.clone(),
OFF_BODY.clone(),
BLINKER_FRAMES,
time,
),
direction: FadeDirection::Transition,
start_time: time,
frames: BLINKER_FRAMES,
}
}
}
impl Animation for Blinker {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern) {
let frames = calculate_frames(self.start_time.0, time.0);
if frames > self.frames {
match self.direction {
FadeDirection::Transition => {
self.direction = FadeDirection::FadeOut;
self.fade_out.start_time = time;
}
FadeDirection::FadeIn => {
self.direction = FadeDirection::FadeOut;
self.fade_out.start_time = time;
}
FadeDirection::FadeOut => {
self.direction = FadeDirection::FadeIn;
self.fade_in.start_time = time;
}
}
self.start_time = time;
}
match self.direction {
FadeDirection::Transition => self.transition.tick(time),
FadeDirection::FadeIn => self.fade_in.tick(time),
FadeDirection::FadeOut => self.fade_out.tick(time),
}
}
}

View File

@ -0,0 +1,100 @@
use fixed::types::{I8F8, U16F0};
use crate::{calculate_frames, calculate_slope, linear_ease, Animation, BodyPattern, DashboardPattern, Instant, OFF_BODY, OFF_DASHBOARD, RGB};
pub struct Fade {
starting_dashboard: DashboardPattern,
starting_lights: BodyPattern,
pub start_time: Instant,
dashboard_slope: [RGB<I8F8>; 3],
body_slope: [RGB<I8F8>; 60],
frames: U16F0,
}
impl Fade {
pub fn new(
dashboard: DashboardPattern,
lights: BodyPattern,
ending_dashboard: DashboardPattern,
ending_lights: BodyPattern,
frames: U16F0,
time: Instant,
) -> Self {
let mut dashboard_slope = [Default::default(); 3];
let mut body_slope = [Default::default(); 60];
for i in 0..3 {
let slope = RGB {
r: calculate_slope(dashboard[i].r, ending_dashboard[i].r, frames),
g: calculate_slope(dashboard[i].g, ending_dashboard[i].g, frames),
b: calculate_slope(dashboard[i].b, ending_dashboard[i].b, frames),
};
dashboard_slope[i] = slope;
}
for i in 0..60 {
let slope = RGB {
r: calculate_slope(lights[i].r, ending_lights[i].r, frames),
g: calculate_slope(lights[i].g, ending_lights[i].g, frames),
b: calculate_slope(lights[i].b, ending_lights[i].b, frames),
};
body_slope[i] = slope;
}
Self {
starting_dashboard: dashboard,
starting_lights: lights,
start_time: time,
dashboard_slope,
body_slope,
frames,
}
}
}
impl Animation for Fade {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern) {
let mut frames = calculate_frames(self.start_time.0, time.0);
if frames > self.frames {
frames = self.frames
}
let mut dashboard_pattern: DashboardPattern = OFF_DASHBOARD;
let mut body_pattern: BodyPattern = OFF_BODY;
for i in 0..3 {
dashboard_pattern[i].r = linear_ease(
self.starting_dashboard[i].r,
frames,
self.dashboard_slope[i].r,
);
dashboard_pattern[i].g = linear_ease(
self.starting_dashboard[i].g,
frames,
self.dashboard_slope[i].g,
);
dashboard_pattern[i].b = linear_ease(
self.starting_dashboard[i].b,
frames,
self.dashboard_slope[i].b,
);
}
for i in 0..60 {
body_pattern[i].r =
linear_ease(self.starting_lights[i].r, frames, self.body_slope[i].r);
body_pattern[i].g =
linear_ease(self.starting_lights[i].g, frames, self.body_slope[i].g);
body_pattern[i].b =
linear_ease(self.starting_lights[i].b, frames, self.body_slope[i].b);
}
(dashboard_pattern, body_pattern)
}
}
#[derive(Debug)]
pub enum FadeDirection {
Transition,
FadeIn,
FadeOut,
}

View File

@ -0,0 +1,43 @@
use crate::{Animation, BodyPattern, DashboardPattern, Instant};
pub struct FlagRipple {
dashboard: DashboardPattern,
body: BodyPattern,
centers: [usize; 12],
}
impl FlagRipple {
fn new(dashboard: DashboardPattern, body: BodyPattern) -> Self {
Self {
dashboard,
body,
centers: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],
}
}
}
impl Animation for FlagRipple {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern, Option<Animation>) {
// How does a flag ripple work? I think have some center points that are darker and have a
// bit of a darker pattern around them.
let mut body_pattern = self.body.clone();
for i in 0..60 {
if self.centers.contains(&i) {
body_pattern[i].r = self.body[i].r / 2;
body_pattern[i].g = self.body[i].g / 2;
body_pattern[i].b = self.body[i].b / 2;
} else {
body_pattern[i].r = self.body[i].r;
body_pattern[i].g = self.body[i].g;
body_pattern[i].b = self.body[i].b;
}
}
(self.dashboard, body_pattern, None)
}
}

View File

@ -0,0 +1,31 @@
use fixed::types::{I48F16, I8F8, U128F0, U16F0};
use az::*;
use crate::{BodyPattern, DashboardPattern, Instant, FPS};
mod blinker;
pub use blinker::*;
mod fade;
pub use fade::*;
pub trait Animation {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern);
}
pub fn linear_ease(value: I8F8, frames: U16F0, slope: I8F8) -> I8F8 {
let value_i16f16 = I48F16::from(value) + I48F16::from(frames) * I48F16::from(slope);
value_i16f16.saturating_as()
}
pub fn calculate_frames(starting_time: U128F0, now: U128F0) -> U16F0 {
let frames_128 = (now - starting_time) / U128F0::from(FPS);
(frames_128 % U128F0::from(U16F0::MAX)).cast()
}
pub fn calculate_slope(start: I8F8, end: I8F8, frames: U16F0) -> I8F8 {
let slope_i16f16 = (I48F16::from(end) - I48F16::from(start)) / I48F16::from(frames);
slope_i16f16.saturating_as()
}

View File

@ -0,0 +1,95 @@
use fixed::types::{I16F0, I8F0, I8F8, U16F0, U8F0};
use az::*;
use crate::{
calculate_frames, calculate_slope, linear_ease, sin, Animation, BodyPattern, DashboardPattern, Instant, OFF_BODY, OFF_DASHBOARD, RGB, WATER_1, WATER_BODY
};
const DROPLET_DIMMING: u8 = 30;
pub struct Ripple {
dashboard: DashboardPattern,
base: BodyPattern,
focii: [usize; 2],
dimming: I8F8,
slope: [RGB<I8F8>; 2],
pub start_time: Instant,
}
impl Ripple {
pub fn new(dashboard: DashboardPattern, base: BodyPattern, time: Instant) -> Self {
let mut slope = [Default::default(); 2];
let dimming = I8F8::lit("0.5");
let focii = [15, 45];
for (idx, focus) in focii.iter().enumerate() {
slope[idx] = RGB {
r: calculate_slope(
base[*focus].r,
base[*focus].r * dimming,
U16F0::from(DROPLET_DIMMING),
),
g: calculate_slope(
base[*focus].g,
base[*focus].g * dimming,
U16F0::from(DROPLET_DIMMING),
),
b: calculate_slope(
base[*focus].b,
base[*focus].b * dimming,
U16F0::from(DROPLET_DIMMING),
),
};
}
Self {
dashboard,
base,
focii,
dimming,
slope,
start_time: time,
}
}
fn pixel(&self, pos: U8F0, frames: U16F0) -> RGB<I8F8> {
let focus: I16F0 = if pos <= 30 { I16F0::from(15 as i16) } else { I16F0::from(45 as i16) };
let distance_from_focus: I8F0 = (focus - I16F0::from(pos)).saturating_as();
let pos: usize = pos.into();
/*
let target = RGB {
r: WATER_BODY[pos].r * self.dimming,
g: WATER_BODY[pos].g * self.dimming,
b: WATER_BODY[pos].b * self.dimming,
};
let slope = RGB{
r: calculate_slope(WATER_BODY[pos].r, target.r, U16F0::from(DROPLET_DIMMING)),
g: calculate_slope(WATER_BODY[pos].g, target.g, U16F0::from(DROPLET_DIMMING)),
b: calculate_slope(WATER_BODY[pos].b, target.b, U16F0::from(DROPLET_DIMMING)),
};
*/
RGB {
r: WATER_BODY[pos].r + sin(frames * 5) * I8F8::from_num(0.5),
g: WATER_BODY[pos].g + sin(frames * 6) * I8F8::from_num(0.5),
b: WATER_BODY[pos].b + sin(frames * 7) * I8F8::from_num(0.5),
}
}
}
impl Animation for Ripple {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern) {
let frames = calculate_frames(self.start_time.0, time.0);
let mut body_pattern: BodyPattern = OFF_BODY;
for i in 0..60 {
body_pattern[i] = self.pixel(U8F0::from(i as u8), frames);
}
(self.dashboard.clone(), body_pattern)
}
}

View File

@ -12,27 +12,15 @@ use core::{
};
use fixed::types::{I48F16, I8F8, U128F0, U16F0};
mod animations;
pub use animations::*;
mod patterns;
pub use patterns::*;
mod types;
pub use types::{BodyPattern, DashboardPattern, RGB};
fn calculate_frames(starting_time: U128F0, now: U128F0) -> U16F0 {
let frames_128 = (now - starting_time) / U128F0::from(FPS);
(frames_128 % U128F0::from(U16F0::MAX)).cast()
}
fn calculate_slope(start: I8F8, end: I8F8, frames: U16F0) -> I8F8 {
let slope_i16f16 = (I48F16::from(end) - I48F16::from(start)) / I48F16::from(frames);
slope_i16f16.saturating_as()
}
fn linear_ease(value: I8F8, frames: U16F0, slope: I8F8) -> I8F8 {
let value_i16f16 = I48F16::from(value) + I48F16::from(frames) * I48F16::from(slope);
value_i16f16.saturating_as()
}
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
pub struct Instant(pub U128F0);
@ -65,233 +53,6 @@ pub trait UI {
fn update_lights(&self, dashboard_lights: DashboardPattern, body_lights: BodyPattern);
}
pub trait Animation {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern);
}
/*
pub struct DefaultAnimation {}
impl Animation for DefaultAnimation {
fn tick(&mut self, _: Instant) -> (DashboardPattern, BodyPattern) {
(WATER_DASHBOARD, WATER_BODY)
}
}
*/
pub struct Fade {
starting_dashboard: DashboardPattern,
starting_lights: BodyPattern,
start_time: Instant,
dashboard_slope: [RGB<I8F8>; 3],
body_slope: [RGB<I8F8>; 60],
frames: U16F0,
}
impl Fade {
fn new(
dashboard: DashboardPattern,
lights: BodyPattern,
ending_dashboard: DashboardPattern,
ending_lights: BodyPattern,
frames: U16F0,
time: Instant,
) -> Self {
let mut dashboard_slope = [Default::default(); 3];
let mut body_slope = [Default::default(); 60];
for i in 0..3 {
let slope = RGB {
r: calculate_slope(dashboard[i].r, ending_dashboard[i].r, frames),
g: calculate_slope(dashboard[i].g, ending_dashboard[i].g, frames),
b: calculate_slope(dashboard[i].b, ending_dashboard[i].b, frames),
};
dashboard_slope[i] = slope;
}
for i in 0..60 {
let slope = RGB {
r: calculate_slope(lights[i].r, ending_lights[i].r, frames),
g: calculate_slope(lights[i].g, ending_lights[i].g, frames),
b: calculate_slope(lights[i].b, ending_lights[i].b, frames),
};
body_slope[i] = slope;
}
Self {
starting_dashboard: dashboard,
starting_lights: lights,
start_time: time,
dashboard_slope,
body_slope,
frames,
}
}
}
impl Animation for Fade {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern) {
let mut frames = calculate_frames(self.start_time.0, time.0);
if frames > self.frames {
frames = self.frames
}
let mut dashboard_pattern: DashboardPattern = OFF_DASHBOARD;
let mut body_pattern: BodyPattern = OFF_BODY;
for i in 0..3 {
dashboard_pattern[i].r = linear_ease(
self.starting_dashboard[i].r,
frames,
self.dashboard_slope[i].r,
);
dashboard_pattern[i].g = linear_ease(
self.starting_dashboard[i].g,
frames,
self.dashboard_slope[i].g,
);
dashboard_pattern[i].b = linear_ease(
self.starting_dashboard[i].b,
frames,
self.dashboard_slope[i].b,
);
}
for i in 0..60 {
body_pattern[i].r =
linear_ease(self.starting_lights[i].r, frames, self.body_slope[i].r);
body_pattern[i].g =
linear_ease(self.starting_lights[i].g, frames, self.body_slope[i].g);
body_pattern[i].b =
linear_ease(self.starting_lights[i].b, frames, self.body_slope[i].b);
}
(dashboard_pattern, body_pattern)
}
}
#[derive(Debug)]
pub enum FadeDirection {
Transition,
FadeIn,
FadeOut,
}
pub enum BlinkerDirection {
Left,
Right,
}
pub struct Blinker {
transition: Fade,
fade_in: Fade,
fade_out: Fade,
direction: FadeDirection,
start_time: Instant,
frames: U16F0,
}
impl Blinker {
fn new(
starting_dashboard: DashboardPattern,
starting_body: BodyPattern,
direction: BlinkerDirection,
time: Instant,
) -> Self {
let mut ending_dashboard = OFF_DASHBOARD.clone();
match direction {
BlinkerDirection::Left => {
ending_dashboard[0].r = LEFT_BLINKER_DASHBOARD[0].r;
ending_dashboard[0].g = LEFT_BLINKER_DASHBOARD[0].g;
ending_dashboard[0].b = LEFT_BLINKER_DASHBOARD[0].b;
}
BlinkerDirection::Right => {
ending_dashboard[2].r = RIGHT_BLINKER_DASHBOARD[2].r;
ending_dashboard[2].g = RIGHT_BLINKER_DASHBOARD[2].g;
ending_dashboard[2].b = RIGHT_BLINKER_DASHBOARD[2].b;
}
}
let mut ending_body = OFF_BODY.clone();
match direction {
BlinkerDirection::Left => {
for i in 0..30 {
ending_body[i].r = LEFT_BLINKER_BODY[i].r;
ending_body[i].g = LEFT_BLINKER_BODY[i].g;
ending_body[i].b = LEFT_BLINKER_BODY[i].b;
}
}
BlinkerDirection::Right => {
for i in 30..60 {
ending_body[i].r = RIGHT_BLINKER_BODY[i].r;
ending_body[i].g = RIGHT_BLINKER_BODY[i].g;
ending_body[i].b = RIGHT_BLINKER_BODY[i].b;
}
}
}
Blinker {
transition: Fade::new(
starting_dashboard.clone(),
starting_body.clone(),
ending_dashboard.clone(),
ending_body.clone(),
BLINKER_FRAMES,
time,
),
fade_in: Fade::new(
OFF_DASHBOARD.clone(),
OFF_BODY.clone(),
ending_dashboard.clone(),
ending_body.clone(),
BLINKER_FRAMES,
time,
),
fade_out: Fade::new(
ending_dashboard.clone(),
ending_body.clone(),
OFF_DASHBOARD.clone(),
OFF_BODY.clone(),
BLINKER_FRAMES,
time,
),
direction: FadeDirection::Transition,
start_time: time,
frames: BLINKER_FRAMES,
}
}
}
impl Animation for Blinker {
fn tick(&mut self, time: Instant) -> (DashboardPattern, BodyPattern) {
let frames = calculate_frames(self.start_time.0, time.0);
if frames > self.frames {
match self.direction {
FadeDirection::Transition => {
self.direction = FadeDirection::FadeOut;
self.fade_out.start_time = time;
}
FadeDirection::FadeIn => {
self.direction = FadeDirection::FadeOut;
self.fade_out.start_time = time;
}
FadeDirection::FadeOut => {
self.direction = FadeDirection::FadeIn;
self.fade_in.start_time = time;
}
}
self.start_time = time;
}
match self.direction {
FadeDirection::Transition => self.transition.tick(time),
FadeDirection::FadeIn => self.fade_in.tick(time),
FadeDirection::FadeOut => self.fade_out.tick(time),
}
}
}
#[derive(Clone, Debug)]
pub enum Event {
Brake,

View File

@ -7,6 +7,7 @@ edition = "2021"
[dependencies]
adw = { version = "0.5", package = "libadwaita", features = [ "v1_2" ] }
async-channel = "2.3.1"
cairo-rs = { version = "0.18" }
fixed = { version = "1" }
gio = { version = "0.18" }

View File

@ -1,16 +1,13 @@
use std::{cell::RefCell, env, rc::Rc};
use adw::prelude::*;
use async_channel::{unbounded, Receiver, Sender, TryRecvError};
use fixed::types::{I8F8, U128F0};
use glib::{Object, Sender};
use glib::Object;
use gtk::subclass::prelude::*;
use lights_core::{
App, BodyPattern, DashboardPattern, Event, Instant, FPS, OFF_BODY, OFF_DASHBOARD, RGB, UI,
};
use std::{
cell::RefCell,
env,
rc::Rc,
sync::mpsc::{Receiver, TryRecvError},
};
const WIDTH: i32 = 640;
const HEIGHT: i32 = 480;
@ -156,13 +153,13 @@ impl UI for GTKUI {
match self.rx.try_recv() {
Ok(event) => Some(event),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => None,
Err(TryRecvError::Closed) => None,
}
}
fn update_lights(&self, dashboard_lights: DashboardPattern, lights: BodyPattern) {
self.tx
.send(Update {
.send_blocking(Update {
dashboard: dashboard_lights,
lights,
})
@ -176,9 +173,8 @@ fn main() {
.build();
adw_app.connect_activate(move |adw_app| {
let (update_tx, update_rx) =
gtk::glib::MainContext::channel::<Update>(gtk::glib::Priority::DEFAULT);
let (event_tx, event_rx) = std::sync::mpsc::channel();
let (update_tx, update_rx) = unbounded();
let (event_tx, event_rx) = unbounded();
std::thread::spawn(move || {
let mut bike_app = App::new(Box::new(GTKUI {
@ -218,21 +214,21 @@ fn main() {
left_button.connect_clicked({
let event_tx = event_tx.clone();
move |_| {
let _ = event_tx.send(Event::LeftBlinker);
let _ = event_tx.send_blocking(Event::LeftBlinker);
}
});
brake_button.connect_clicked({
let event_tx = event_tx.clone();
move |_| {
let _ = event_tx.send(Event::Brake);
let _ = event_tx.send_blocking(Event::Brake);
}
});
right_button.connect_clicked({
let event_tx = event_tx.clone();
move |_| {
let _ = event_tx.send(Event::RightBlinker);
let _ = event_tx.send_blocking(Event::RightBlinker);
}
});
@ -251,14 +247,14 @@ fn main() {
previous_pattern.connect_clicked({
let event_tx = event_tx.clone();
move |_| {
let _ = event_tx.send(Event::PreviousPattern);
let _ = event_tx.send_blocking(Event::PreviousPattern);
}
});
next_pattern.connect_clicked({
let event_tx = event_tx.clone();
move |_| {
let _ = event_tx.send(Event::NextPattern);
let _ = event_tx.send_blocking(Event::NextPattern);
}
});
@ -269,6 +265,7 @@ fn main() {
layout.append(&dashboard_lights);
layout.append(&bike_lights);
/*
update_rx.attach(None, {
let dashboard_lights = dashboard_lights.clone();
let bike_lights = bike_lights.clone();
@ -278,6 +275,19 @@ fn main() {
glib::ControlFlow::Continue
}
});
*/
glib::spawn_future_local({
let dashboard_lights = dashboard_lights.clone();
let bike_lights = bike_lights.clone();
async move {
while let Ok(Update { dashboard, lights }) = update_rx.recv().await {
dashboard_lights.set_lights(dashboard);
bike_lights.set_lights(lights);
}
}
});
window.set_content(Some(&layout));
window.present();

View File

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

View File

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

View File

@ -33,9 +33,9 @@ use std::{error::Error, fmt};
/// statement.
pub trait FatalError: Error {}
/// ResultExt<A, FE, E> represents a return value that might be a success, might be a fatal error, or
/// Result<A, FE, E> represents a return value that might be a success, might be a fatal error, or
/// might be a normal handleable error.
pub enum ResultExt<A, E, FE> {
pub enum Result<A, E, FE> {
/// The operation was successful
Ok(A),
/// Ordinary errors. These should be handled and the application should recover gracefully.
@ -45,72 +45,72 @@ pub enum ResultExt<A, E, FE> {
Fatal(FE),
}
impl<A, E, FE> ResultExt<A, E, FE> {
impl<A, E, FE> Result<A, E, FE> {
/// Apply an infallible function to a successful value.
pub fn map<B, O>(self, mapper: O) -> ResultExt<B, E, FE>
pub fn map<B, O>(self, mapper: O) -> Result<B, E, FE>
where
O: FnOnce(A) -> B,
{
match self {
ResultExt::Ok(val) => ResultExt::Ok(mapper(val)),
ResultExt::Err(err) => ResultExt::Err(err),
ResultExt::Fatal(err) => ResultExt::Fatal(err),
Result::Ok(val) => Result::Ok(mapper(val)),
Result::Err(err) => Result::Err(err),
Result::Fatal(err) => Result::Fatal(err),
}
}
/// Apply a potentially fallible function to a successful value.
///
/// Like `Result.and_then`, the mapping function can itself fail.
pub fn and_then<B, O>(self, handler: O) -> ResultExt<B, E, FE>
pub fn and_then<B, O>(self, handler: O) -> Result<B, E, FE>
where
O: FnOnce(A) -> ResultExt<B, E, FE>,
O: FnOnce(A) -> Result<B, E, FE>,
{
match self {
ResultExt::Ok(val) => handler(val),
ResultExt::Err(err) => ResultExt::Err(err),
ResultExt::Fatal(err) => ResultExt::Fatal(err),
Result::Ok(val) => handler(val),
Result::Err(err) => Result::Err(err),
Result::Fatal(err) => Result::Fatal(err),
}
}
/// Map a normal error from one type to another. This is useful for converting an error from
/// one type to another, especially in re-throwing an underlying error. `?` syntax does not
/// work with `Result`, so you will likely need to use this a lot.
pub fn map_err<F, O>(self, mapper: O) -> ResultExt<A, F, FE>
pub fn map_err<F, O>(self, mapper: O) -> Result<A, F, FE>
where
O: FnOnce(E) -> F,
{
match self {
ResultExt::Ok(val) => ResultExt::Ok(val),
ResultExt::Err(err) => ResultExt::Err(mapper(err)),
ResultExt::Fatal(err) => ResultExt::Fatal(err),
Result::Ok(val) => Result::Ok(val),
Result::Err(err) => Result::Err(mapper(err)),
Result::Fatal(err) => Result::Fatal(err),
}
}
/// Provide a function to use to recover from (or simply re-throw) an error.
pub fn or_else<O, F>(self, handler: O) -> ResultExt<A, F, FE>
pub fn or_else<O, F>(self, handler: O) -> Result<A, F, FE>
where
O: FnOnce(E) -> ResultExt<A, F, FE>,
O: FnOnce(E) -> Result<A, F, FE>,
{
match self {
ResultExt::Ok(val) => ResultExt::Ok(val),
ResultExt::Err(err) => handler(err),
ResultExt::Fatal(err) => ResultExt::Fatal(err),
Result::Ok(val) => Result::Ok(val),
Result::Err(err) => handler(err),
Result::Fatal(err) => Result::Fatal(err),
}
}
}
/// Convert from a normal `Result` type to a `ResultExt` type. The error condition for a `Result` will
/// Convert from a normal `Result` type to a `Result` type. The error condition for a `Result` will
/// be treated as `Result::Err`, never `Result::Fatal`.
impl<A, E, FE> From<std::result::Result<A, E>> for ResultExt<A, E, FE> {
impl<A, E, FE> From<std::result::Result<A, E>> for Result<A, E, FE> {
fn from(r: std::result::Result<A, E>) -> Self {
match r {
Ok(val) => ResultExt::Ok(val),
Err(err) => ResultExt::Err(err),
Ok(val) => Result::Ok(val),
Err(err) => Result::Err(err),
}
}
}
impl<A, E, FE> fmt::Debug for ResultExt<A, E, FE>
impl<A, E, FE> fmt::Debug for Result<A, E, FE>
where
A: fmt::Debug,
FE: fmt::Debug,
@ -118,14 +118,14 @@ where
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ResultExt::Ok(val) => f.write_fmt(format_args!("Result::Ok {:?}", val)),
ResultExt::Err(err) => f.write_fmt(format_args!("Result::Err {:?}", err)),
ResultExt::Fatal(err) => f.write_fmt(format_args!("Result::Fatal {:?}", err)),
Result::Ok(val) => f.write_fmt(format_args!("Result::Ok {:?}", val)),
Result::Err(err) => f.write_fmt(format_args!("Result::Err {:?}", err)),
Result::Fatal(err) => f.write_fmt(format_args!("Result::Fatal {:?}", err)),
}
}
}
impl<A, E, FE> PartialEq for ResultExt<A, E, FE>
impl<A, E, FE> PartialEq for Result<A, E, FE>
where
A: PartialEq,
FE: PartialEq,
@ -133,27 +133,27 @@ where
{
fn eq(&self, rhs: &Self) -> bool {
match (self, rhs) {
(ResultExt::Ok(val), ResultExt::Ok(rhs)) => val == rhs,
(ResultExt::Err(_), ResultExt::Err(_)) => true,
(ResultExt::Fatal(_), ResultExt::Fatal(_)) => true,
(Result::Ok(val), Result::Ok(rhs)) => val == rhs,
(Result::Err(_), Result::Err(_)) => true,
(Result::Fatal(_), Result::Fatal(_)) => true,
_ => false,
}
}
}
/// Convenience function to create an ok value.
pub fn ok<A, E: Error, FE: FatalError>(val: A) -> ResultExt<A, E, FE> {
ResultExt::Ok(val)
pub fn ok<A, E: Error, FE: FatalError>(val: A) -> Result<A, E, FE> {
Result::Ok(val)
}
/// Convenience function to create an error value.
pub fn error<A, E: Error, FE: FatalError>(err: E) -> ResultExt<A, E, FE> {
ResultExt::Err(err)
pub fn error<A, E: Error, FE: FatalError>(err: E) -> Result<A, E, FE> {
Result::Err(err)
}
/// Convenience function to create a fatal value.
pub fn fatal<A, E: Error, FE: FatalError>(err: FE) -> ResultExt<A, E, FE> {
ResultExt::Fatal(err)
pub fn fatal<A, E: Error, FE: FatalError>(err: FE) -> Result<A, E, FE> {
Result::Fatal(err)
}
/// Return early from the current function if the value is a fatal error.
@ -161,9 +161,9 @@ pub fn fatal<A, E: Error, FE: FatalError>(err: FE) -> ResultExt<A, E, FE> {
macro_rules! return_fatal {
($x:expr) => {
match $x {
ResultExt::Fatal(err) => return ResultExt::Fatal(err),
ResultExt::Err(err) => Err(err),
ResultExt::Ok(val) => Ok(val),
Result::Fatal(err) => return Result::Fatal(err),
Result::Err(err) => Err(err),
Result::Ok(val) => Ok(val),
}
};
}
@ -173,9 +173,9 @@ macro_rules! return_fatal {
macro_rules! return_error {
($x:expr) => {
match $x {
ResultExt::Ok(val) => val,
ResultExt::Err(err) => return ResultExt::Err(err),
ResultExt::Fatal(err) => return ResultExt::Fatal(err),
Result::Ok(val) => val,
Result::Err(err) => return Result::Err(err),
Result::Fatal(err) => return Result::Fatal(err),
}
};
}
@ -210,19 +210,19 @@ mod test {
#[test]
fn it_can_map_things() {
let success: ResultExt<i32, Error, FatalError> = ok(15);
let success: Result<i32, Error, FatalError> = ok(15);
assert_eq!(ok(16), success.map(|v| v + 1));
}
#[test]
fn it_can_chain_success() {
let success: ResultExt<i32, Error, FatalError> = ok(15);
let success: Result<i32, Error, FatalError> = ok(15);
assert_eq!(ok(16), success.and_then(|v| ok(v + 1)));
}
#[test]
fn it_can_handle_an_error() {
let failure: ResultExt<i32, Error, FatalError> = error(Error::Error);
let failure: Result<i32, Error, FatalError> = error(Error::Error);
assert_eq!(
ok::<i32, Error, FatalError>(16),
failure.or_else(|_| ok(16))
@ -231,7 +231,7 @@ mod test {
#[test]
fn early_exit_on_fatal() {
fn ok_func() -> ResultExt<i32, Error, FatalError> {
fn ok_func() -> Result<i32, Error, FatalError> {
let value = return_fatal!(ok::<i32, Error, FatalError>(15));
match value {
Ok(_) => ok(14),
@ -239,7 +239,7 @@ mod test {
}
}
fn err_func() -> ResultExt<i32, Error, FatalError> {
fn err_func() -> Result<i32, Error, FatalError> {
let value = return_fatal!(error::<i32, Error, FatalError>(Error::Error));
match value {
Ok(_) => panic!("shouldn't have gotten here"),
@ -247,7 +247,7 @@ mod test {
}
}
fn fatal_func() -> ResultExt<i32, Error, FatalError> {
fn fatal_func() -> Result<i32, Error, FatalError> {
let _ = return_fatal!(fatal::<i32, Error, FatalError>(FatalError::FatalError));
panic!("failed to bail");
}
@ -259,18 +259,18 @@ mod test {
#[test]
fn it_can_early_exit_on_all_errors() {
fn ok_func() -> ResultExt<i32, Error, FatalError> {
fn ok_func() -> Result<i32, Error, FatalError> {
let value = return_error!(ok::<i32, Error, FatalError>(15));
assert_eq!(value, 15);
ok(14)
}
fn err_func() -> ResultExt<i32, Error, FatalError> {
fn err_func() -> Result<i32, Error, FatalError> {
return_error!(error::<i32, Error, FatalError>(Error::Error));
panic!("failed to bail");
}
fn fatal_func() -> ResultExt<i32, Error, FatalError> {
fn fatal_func() -> Result<i32, Error, FatalError> {
return_error!(fatal::<i32, Error, FatalError>(FatalError::FatalError));
panic!("failed to bail");
}

View File

@ -6,27 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-std = { version = "1.13.0" }
async-trait = { version = "0.1.83" }
authdb = { path = "../../authdb/" }
futures = { version = "0.3.31" }
http = { version = "1" }
include_dir = { version = "0.7.4" }
lazy_static = { version = "1.5.0" }
mime = { version = "0.3.17" }
mime_guess = { version = "2.0.5" }
result-extended = { path = "../../result-extended" }
rusqlite = { version = "0.32.1" }
rusqlite_migration = { version = "1.3.1", features = ["from-directory"] }
serde = { version = "1" }
serde_json = { version = "*" }
thiserror = { version = "2.0.3" }
tokio = { version = "1", features = [ "full" ] }
tokio-stream = { version = "0.1.16" }
typeshare = { version = "1.0.4" }
urlencoding = { version = "2.1.3" }
uuid = { version = "1.11.0", features = ["v4"] }
warp = { version = "0.3" }
[dev-dependencies]
cool_asserts = "2.0.3"
authdb = { path = "../../authdb/" }
http = { version = "1" }
serde_json = { version = "*" }
serde = { version = "1" }
tokio = { version = "1", features = [ "full" ] }
warp = { version = "0.3" }

View File

@ -1,15 +0,0 @@
version: '3'
tasks:
build:
cmds:
- cargo build
test:
cmds:
# - cargo watch -x 'test -- --nocapture'
- cargo watch -x 'nextest run'
dev:
cmds:
- cargo watch -x run

View File

@ -1,32 +0,0 @@
CREATE TABLE users(
uuid TEXT PRIMARY KEY,
name TEXT,
password TEXT,
admin BOOLEAN,
enabled BOOLEAN
);
CREATE TABLE games(
uuid TEXT PRIMARY KEY,
name TEXT
);
CREATE TABLE characters(
uuid TEXT PRIMARY KEY,
game TEXT,
data TEXT,
FOREIGN KEY(game) REFERENCES games(uuid)
);
CREATE TABLE roles(
user_id TEXT,
game_id TEXT,
role TEXT,
FOREIGN KEY(user_id) REFERENCES users(uuid),
FOREIGN KEY(game_id) REFERENCES games(uuid)
);
INSERT INTO users VALUES ("admin", "admin", "", true, true);

View File

@ -1 +0,0 @@
{ "type_": "Candela", "name": "Soren Jensen", "pronouns": "he/him", "circle": "Circle of the Bluest Sky", "style": "dapper gentleman", "catalyst": "a cursed book", "question": "What were the contents of that book?", "nerve": { "type_": "nerve", "drives": { "current": 1, "max": 2 }, "resistances": { "current": 0, "max": 3 }, "move": { "gilded": false, "score": 2 }, "strike": { "gilded": false, "score": 1 }, "control": { "gilded": true, "score": 0 } }, "cunning": { "type_": "cunning", "drives": { "current": 1, "max": 1 }, "resistances": { "current": 0, "max": 3 }, "sway": { "gilded": false, "score": 0 }, "read": { "gilded": false, "score": 0 }, "hide": { "gilded": false, "score": 0 } }, "intuition": { "type_": "intuition", "drives": { "current": 0, "max": 0 }, "resistances": { "current": 0, "max": 3 }, "survey": { "gilded": false, "score": 0 }, "focus": { "gilded": false, "score": 0 }, "sense": { "gilded": false, "score": 0 } }, "role": "Slink", "role_abilities": [ "Scout: If you have time to observe a location, you can spend 1 Intuition to ask a question: What do I notice here that others do not see? What in this place might be of use to us? What path should we follow?" ], "specialty": "Detective", "specialty_abilities": [ "Mind Palace: When you want to figure out how two clues might relate or what path they should point you towards, burn 1 Intution resistance. The GM will give you the information you have deduced." ] }

View File

@ -1,156 +0,0 @@
use std::{
collections::{hash_map::Iter, HashMap}, fmt::{self, Display}, fs, io::Read, path::PathBuf
};
use mime::Mime;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use typeshare::typeshare;
#[derive(Debug, Error)]
pub enum Error {
#[error("Asset could not be found")]
NotFound,
#[error("Asset could not be opened")]
Inaccessible,
#[error("An unexpected IO error occured when retrieving an asset {0}")]
UnexpectedError(std::io::Error),
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
use std::io::ErrorKind::*;
match err.kind() {
NotFound => Error::NotFound,
PermissionDenied | UnexpectedEof => Error::Inaccessible,
_ => Error::UnexpectedError(err),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[typeshare]
pub struct AssetId(String);
impl AssetId {
pub fn as_str<'a>(&'a self) -> &'a str {
&self.0
}
}
impl Display for AssetId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AssetId({})", self.0)
}
}
impl From<&str> for AssetId {
fn from(s: &str) -> Self {
AssetId(s.to_owned())
}
}
impl From<String> for AssetId {
fn from(s: String) -> Self {
AssetId(s)
}
}
pub struct AssetIter<'a>(Iter<'a, AssetId, String>);
impl<'a> Iterator for AssetIter<'a> {
type Item = (&'a AssetId, &'a String);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub trait Assets {
fn assets<'a>(&'a self) -> AssetIter<'a>;
fn get(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), Error>;
}
pub struct FsAssets {
assets: HashMap<AssetId, String>,
}
impl FsAssets {
pub fn new(path: PathBuf) -> Self {
let dir = fs::read_dir(path).unwrap();
let mut assets = HashMap::new();
for dir_ent in dir {
let path = dir_ent.unwrap().path();
let file_name = path.file_name().unwrap().to_str().unwrap();
assets.insert(AssetId::from(file_name), path.to_str().unwrap().to_owned());
}
Self {
assets,
}
}
}
impl Assets for FsAssets {
fn assets<'a>(&'a self) -> AssetIter<'a> {
AssetIter(self.assets.iter())
}
fn get(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), Error> {
let path = match self.assets.get(&asset_id) {
Some(asset) => Ok(asset),
None => Err(Error::NotFound),
}?;
let mime = mime_guess::from_path(&path).first().unwrap();
let mut content: Vec<u8> = Vec::new();
let mut file = std::fs::File::open(&path)?;
file.read_to_end(&mut content)?;
Ok((mime, content))
}
}
#[cfg(test)]
pub mod mocks {
use std::collections::HashMap;
use super::*;
pub struct MemoryAssets {
asset_paths: HashMap<AssetId, String>,
assets: HashMap<AssetId, Vec<u8>>,
}
impl MemoryAssets {
pub fn new(data: Vec<(AssetId, String, Vec<u8>)>) -> Self {
let mut asset_paths = HashMap::new();
let mut assets = HashMap::new();
data.into_iter().for_each(|(asset, path, data)| {
asset_paths.insert(asset.clone(), path);
assets.insert(asset, data);
});
Self {
asset_paths,
assets,
}
}
}
impl Assets for MemoryAssets {
fn assets<'a>(&'a self) -> AssetIter<'a> {
AssetIter(self.asset_paths.iter())
}
fn get(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), Error> {
match (self.asset_paths.get(&asset_id), self.assets.get(&asset_id)) {
(Some(path), Some(data)) => {
let mime = mime_guess::from_path(&path).first().unwrap();
Ok((mime, data.to_vec()))
}
_ => Err(Error::NotFound),
}
}
}
}

View File

@ -1,330 +0,0 @@
use std::{collections::HashMap, sync::Arc};
use async_std::sync::RwLock;
use mime::Mime;
use result_extended::{error, fatal, ok, return_error, ResultExt};
use serde::Serialize;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use typeshare::typeshare;
use uuid::Uuid;
use crate::{
asset_db::{self, AssetId, Assets},
database::{CharacterId, Database, UserId},
types::{AppError, FatalError, Game, Message, Tabletop, User, RGB},
};
const DEFAULT_BACKGROUND_COLOR: RGB = RGB {
red: 0xca,
green: 0xb9,
blue: 0xbb,
};
#[derive(Clone, Serialize)]
#[typeshare]
pub struct Status {
pub admin_enabled: bool,
}
#[derive(Debug)]
struct WebsocketClient {
sender: Option<UnboundedSender<Message>>,
}
pub struct AppState {
pub asset_store: Box<dyn Assets + Sync + Send + 'static>,
pub db: Box<dyn Database + Sync + Send + 'static>,
pub clients: HashMap<String, WebsocketClient>,
pub tabletop: Tabletop,
}
#[derive(Clone)]
pub struct Core(Arc<RwLock<AppState>>);
impl Core {
pub fn new<A, DB>(assetdb: A, db: DB) -> Self
where
A: Assets + Sync + Send + 'static,
DB: Database + Sync + Send + 'static,
{
Self(Arc::new(RwLock::new(AppState {
asset_store: Box::new(assetdb),
db: Box::new(db),
clients: HashMap::new(),
tabletop: Tabletop {
background_color: DEFAULT_BACKGROUND_COLOR,
background_image: None,
},
})))
}
pub async fn status(&self) -> ResultExt<Status, AppError, FatalError> {
let mut state = self.0.write().await;
let admin_user = return_error!(match state.db.user(UserId::from("admin")).await {
Ok(Some(admin_user)) => ok(admin_user),
Ok(None) => {
return ok(Status {
admin_enabled: false,
});
}
Err(err) => fatal(err),
});
ok(Status {
admin_enabled: !admin_user.password.is_empty(),
})
}
pub async fn register_client(&self) -> String {
let mut state = self.0.write().await;
let uuid = Uuid::new_v4().simple().to_string();
let client = WebsocketClient { sender: None };
state.clients.insert(uuid.clone(), client);
uuid
}
pub async fn unregister_client(&self, client_id: String) {
let mut state = self.0.write().await;
let _ = state.clients.remove(&client_id);
}
pub async fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> {
let mut state = self.0.write().await;
match state.clients.get_mut(&client_id) {
Some(client) => {
let (tx, rx) = unbounded_channel();
client.sender = Some(tx);
rx
}
None => {
unimplemented!();
}
}
}
pub async fn list_users(&self) -> ResultExt<Vec<User>, AppError, FatalError> {
let users = self.0.write().await.db.users().await;
match users {
Ok(users) => ok(users.into_iter().map(|u| User::from(u)).collect()),
Err(err) => fatal(err),
}
}
pub async fn list_games(&self) -> ResultExt<Vec<Game>, AppError, FatalError> {
let games = self.0.write().await.db.games().await;
match games {
// Ok(games) => ok(games.into_iter().map(|g| Game::from(g)).collect()),
Ok(games) => unimplemented!(),
Err(err) => fatal(err),
}
}
pub async fn tabletop(&self) -> Tabletop {
self.0.read().await.tabletop.clone()
}
pub async fn get_asset(
&self,
asset_id: AssetId,
) -> ResultExt<(Mime, Vec<u8>), AppError, FatalError> {
ResultExt::from(
self.0
.read()
.await
.asset_store
.get(asset_id.clone())
.map_err(|err| match err {
asset_db::Error::NotFound => AppError::NotFound(format!("{}", asset_id)),
asset_db::Error::Inaccessible => {
AppError::Inaccessible(format!("{}", asset_id))
}
asset_db::Error::UnexpectedError(err) => {
AppError::Inaccessible(format!("{}", err))
}
}),
)
}
pub async fn available_images(&self) -> Vec<AssetId> {
self.0
.read()
.await
.asset_store
.assets()
.filter_map(
|(asset_id, value)| match mime_guess::from_path(&value).first() {
Some(mime) if mime.type_() == mime::IMAGE => Some(asset_id.clone()),
_ => None,
},
)
.collect()
}
pub async fn set_background_image(
&self,
asset: AssetId,
) -> ResultExt<(), AppError, FatalError> {
let tabletop = {
let mut state = self.0.write().await;
state.tabletop.background_image = Some(asset.clone());
state.tabletop.clone()
};
self.publish(Message::UpdateTabletop(tabletop)).await;
ok(())
}
pub async fn get_charsheet(
&self,
id: CharacterId,
) -> ResultExt<Option<serde_json::Value>, AppError, FatalError> {
let mut state = self.0.write().await;
let cr = state.db.character(id).await;
match cr {
Ok(Some(row)) => ok(Some(row.data)),
Ok(None) => ok(None),
Err(err) => fatal(err),
}
}
pub async fn publish(&self, message: Message) {
let state = self.0.read().await;
state.clients.values().for_each(|client| {
if let Some(ref sender) = client.sender {
let _ = sender.send(message.clone());
}
});
}
pub async fn set_password(
&self,
uuid: UserId,
password: String,
) -> ResultExt<(), AppError, FatalError> {
let mut state = self.0.write().await;
let user = match state.db.user(uuid.clone()).await {
Ok(Some(row)) => row,
Ok(None) => return error(AppError::NotFound(uuid.as_str().to_owned())),
Err(err) => return fatal(err),
};
match state
.db
.save_user(Some(uuid), &user.name, &password, user.admin, user.enabled)
.await
{
Ok(_) => ok(()),
Err(err) => fatal(err),
}
}
}
#[cfg(test)]
mod test {
use std::path::PathBuf;
use super::*;
use cool_asserts::assert_matches;
use crate::{
asset_db::mocks::MemoryAssets,
database::{DbConn, DiskDb},
};
fn test_core() -> Core {
let assets = MemoryAssets::new(vec![
(
AssetId::from("asset_1"),
"asset_1.png".to_owned(),
String::from("abcdefg").into_bytes(),
),
(
AssetId::from("asset_2"),
"asset_2.jpg".to_owned(),
String::from("abcdefg").into_bytes(),
),
(
AssetId::from("asset_3"),
"asset_3".to_owned(),
String::from("abcdefg").into_bytes(),
),
(
AssetId::from("asset_4"),
"asset_4".to_owned(),
String::from("abcdefg").into_bytes(),
),
(
AssetId::from("asset_5"),
"asset_5".to_owned(),
String::from("abcdefg").into_bytes(),
),
]);
let memory_db: Option<PathBuf> = None;
let conn = DbConn::new(memory_db);
Core::new(assets, conn)
}
#[tokio::test]
async fn it_lists_available_images() {
let core = test_core();
let image_paths = core.available_images().await;
assert_eq!(image_paths.len(), 2);
}
#[tokio::test]
async fn it_retrieves_an_asset() {
let core = test_core();
assert_matches!(core.get_asset(AssetId::from("asset_1")).await, ResultExt::Ok((mime, data)) => {
assert_eq!(mime.type_(), mime::IMAGE);
assert_eq!(data, "abcdefg".as_bytes());
});
}
#[tokio::test]
async fn it_can_retrieve_the_default_tabletop() {
let core = test_core();
assert_matches!(core.tabletop().await, Tabletop{ background_color, background_image } => {
assert_eq!(background_color, DEFAULT_BACKGROUND_COLOR);
assert_eq!(background_image, None);
});
}
#[tokio::test]
async fn it_can_change_the_tabletop_background() {
let core = test_core();
assert_matches!(
core.set_background_image(AssetId::from("asset_1")).await,
ResultExt::Ok(())
);
assert_matches!(core.tabletop().await, Tabletop{ background_color, background_image } => {
assert_eq!(background_color, DEFAULT_BACKGROUND_COLOR);
assert_eq!(background_image, Some(AssetId::from("asset_1")));
});
}
#[tokio::test]
async fn it_sends_notices_to_clients_on_tabletop_change() {
let core = test_core();
let client_id = core.register_client().await;
let mut receiver = core.connect_client(client_id).await;
assert_matches!(
core.set_background_image(AssetId::from("asset_1")).await,
ResultExt::Ok(())
);
match receiver.recv().await {
Some(Message::UpdateTabletop(Tabletop {
background_color,
background_image,
})) => {
assert_eq!(background_color, DEFAULT_BACKGROUND_COLOR);
assert_eq!(background_image, Some(AssetId::from("asset_1")));
}
None => panic!("receiver did not get a message"),
}
}
}

View File

@ -1,651 +0,0 @@
use std::path::Path;
use async_std::channel::{bounded, Receiver, Sender};
use async_trait::async_trait;
use include_dir::{include_dir, Dir};
use lazy_static::lazy_static;
use rusqlite::{
types::{FromSql, FromSqlResult, ValueRef},
Connection,
};
use rusqlite_migration::Migrations;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::types::FatalError;
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
lazy_static! {
static ref MIGRATIONS: Migrations<'static> =
Migrations::from_directory(&MIGRATIONS_DIR).unwrap();
}
#[derive(Debug)]
enum Request {
Charsheet(CharacterId),
Games,
User(UserId),
Users,
SaveUser(Option<UserId>, String, String, bool, bool),
}
#[derive(Debug)]
struct DatabaseRequest {
tx: Sender<DatabaseResponse>,
req: Request,
}
#[derive(Debug)]
enum DatabaseResponse {
Charsheet(Option<CharsheetRow>),
Games(Vec<GameRow>),
User(Option<UserRow>),
Users(Vec<UserRow>),
SaveUser(UserId),
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct UserId(String);
impl UserId {
pub fn new() -> Self {
Self(format!("{}", Uuid::new_v4().hyphenated()))
}
pub fn as_str<'a>(&'a self) -> &'a str {
&self.0
}
}
impl From<&str> for UserId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl From<String> for UserId {
fn from(s: String) -> Self {
Self(s)
}
}
impl FromSql for UserId {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Text(text) => Ok(Self::from(String::from_utf8(text.to_vec()).unwrap())),
_ => unimplemented!(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct GameId(String);
impl GameId {
pub fn new() -> Self {
Self(format!("{}", Uuid::new_v4().hyphenated()))
}
pub fn as_str<'a>(&'a self) -> &'a str {
&self.0
}
}
impl From<&str> for GameId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl From<String> for GameId {
fn from(s: String) -> Self {
Self(s)
}
}
impl FromSql for GameId {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Text(text) => Ok(Self::from(String::from_utf8(text.to_vec()).unwrap())),
_ => unimplemented!(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct CharacterId(String);
impl CharacterId {
pub fn new() -> Self {
Self(format!("{}", Uuid::new_v4().hyphenated()))
}
pub fn as_str<'a>(&'a self) -> &'a str {
&self.0
}
}
impl From<&str> for CharacterId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl From<String> for CharacterId {
fn from(s: String) -> Self {
Self(s)
}
}
impl FromSql for CharacterId {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Text(text) => Ok(Self::from(String::from_utf8(text.to_vec()).unwrap())),
_ => unimplemented!(),
}
}
}
#[derive(Clone, Debug)]
pub struct UserRow {
pub id: UserId,
pub name: String,
pub password: String,
pub admin: bool,
pub enabled: bool,
}
#[derive(Clone, Debug)]
pub struct Role {
userid: UserId,
gameid: GameId,
role: String,
}
#[derive(Clone, Debug)]
pub struct GameRow {
pub id: UserId,
pub name: String,
}
#[derive(Clone, Debug)]
pub struct CharsheetRow {
id: String,
game: GameId,
pub data: serde_json::Value,
}
#[async_trait]
pub trait Database: Send + Sync {
async fn user(&mut self, _: UserId) -> Result<Option<UserRow>, FatalError>;
async fn save_user(
&mut self,
user_id: Option<UserId>,
name: &str,
password: &str,
admin: bool,
enabled: bool,
) -> Result<UserId, FatalError>;
async fn users(&mut self) -> Result<Vec<UserRow>, FatalError>;
async fn games(&mut self) -> Result<Vec<GameRow>, FatalError>;
async fn character(&mut self, id: CharacterId) -> Result<Option<CharsheetRow>, FatalError>;
}
pub struct DiskDb {
conn: Connection,
}
/*
fn setup_test_database(conn: &Connection) -> Result<(), FatalError> {
let mut gamecount_stmt = conn.prepare("SELECT count(*) FROM games").unwrap();
let mut count = gamecount_stmt.query([]).unwrap();
if count.next().unwrap().unwrap().get::<usize, usize>(0) == Ok(0) {
let admin_id = format!("{}", Uuid::new_v4());
let user_id = format!("{}", Uuid::new_v4());
let game_id = format!("{}", Uuid::new_v4());
let char_id = CharacterId::new();
let mut user_stmt = conn
.prepare("INSERT INTO users VALUES (?, ?, ?, ?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
user_stmt
.execute((admin_id.clone(), "admin", "abcdefg", true, true))
.unwrap();
user_stmt
.execute((user_id.clone(), "savanni", "abcdefg", false, true))
.unwrap();
let mut game_stmt = conn
.prepare("INSERT INTO games VALUES (?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
game_stmt
.execute((game_id.clone(), "Circle of Bluest Sky"))
.unwrap();
let mut role_stmt = conn
.prepare("INSERT INTO roles VALUES (?, ?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
role_stmt
.execute((user_id.clone(), game_id.clone(), "gm"))
.unwrap();
let mut sheet_stmt = conn
.prepare("INSERT INTO characters VALUES (?, ?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
sheet_stmt.execute((char_id.as_str(), game_id, r#"{ "type_": "Candela", "name": "Soren Jensen", "pronouns": "he/him", "circle": "Circle of the Bluest Sky", "style": "dapper gentleman", "catalyst": "a cursed book", "question": "What were the contents of that book?", "nerve": { "type_": "nerve", "drives": { "current": 1, "max": 2 }, "resistances": { "current": 0, "max": 3 }, "move": { "gilded": false, "score": 2 }, "strike": { "gilded": false, "score": 1 }, "control": { "gilded": true, "score": 0 } }, "cunning": { "type_": "cunning", "drives": { "current": 1, "max": 1 }, "resistances": { "current": 0, "max": 3 }, "sway": { "gilded": false, "score": 0 }, "read": { "gilded": false, "score": 0 }, "hide": { "gilded": false, "score": 0 } }, "intuition": { "type_": "intuition", "drives": { "current": 0, "max": 0 }, "resistances": { "current": 0, "max": 3 }, "survey": { "gilded": false, "score": 0 }, "focus": { "gilded": false, "score": 0 }, "sense": { "gilded": false, "score": 0 } }, "role": "Slink", "role_abilities": [ "Scout: If you have time to observe a location, you can spend 1 Intuition to ask a question: What do I notice here that others do not see? What in this place might be of use to us? What path should we follow?" ], "specialty": "Detective", "specialty_abilities": [ "Mind Palace: When you want to figure out how two clues might relate or what path they should point you towards, burn 1 Intution resistance. The GM will give you the information you have deduced." ] }"#))
.unwrap();
}
Ok(())
}
*/
impl DiskDb {
pub fn new<P>(path: Option<P>) -> Result<Self, FatalError>
where
P: AsRef<Path>,
{
let mut conn = match path {
None => Connection::open(":memory:").expect("to create a memory connection"),
Some(path) => Connection::open(path).expect("to create connection"),
};
MIGRATIONS
.to_latest(&mut conn)
.map_err(|err| FatalError::DatabaseMigrationFailure(format!("{}", err)))?;
// setup_test_database(&conn)?;
Ok(DiskDb { conn })
}
fn user(&self, id: UserId) -> Result<Option<UserRow>, FatalError> {
let mut stmt = self
.conn
.prepare("SELECT uuid, name, password, admin, enabled FROM users WHERE uuid=?")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
let items: Vec<UserRow> = stmt
.query_map([id.as_str()], |row| {
Ok(UserRow {
id: row.get(0).unwrap(),
name: row.get(1).unwrap(),
password: row.get(2).unwrap(),
admin: row.get(3).unwrap(),
enabled: row.get(4).unwrap(),
})
})
.unwrap()
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
.unwrap();
match &items[..] {
[] => Ok(None),
[item] => Ok(Some(item.clone())),
_ => Err(FatalError::NonUniqueDatabaseKey(id.as_str().to_owned())),
}
}
fn users(&self) -> Result<Vec<UserRow>, FatalError> {
let mut stmt = self
.conn
.prepare("SELECT * FROM users")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
let items = stmt
.query_map([], |row| {
Ok(UserRow {
id: row.get(0).unwrap(),
name: row.get(1).unwrap(),
password: row.get(2).unwrap(),
admin: row.get(3).unwrap(),
enabled: row.get(4).unwrap(),
})
})
.unwrap()
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
.unwrap();
Ok(items)
}
fn save_user(
&self,
user_id: Option<UserId>,
name: &str,
password: &str,
admin: bool,
enabled: bool,
) -> Result<UserId, FatalError> {
match user_id {
None => {
let user_id = UserId::new();
let mut stmt = self
.conn
.prepare("INSERT INTO users VALUES (?, ?, ?, ?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
stmt.execute((user_id.as_str(), name, password, admin, enabled))
.unwrap();
Ok(user_id)
}
Some(user_id) => {
let mut stmt = self
.conn
.prepare(
"UPDATE users SET name=?, password=?, admin=?, enabled=? WHERE uuid=?",
)
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
stmt.execute((name, password, admin, enabled, user_id.as_str()))
.unwrap();
Ok(user_id)
}
}
}
fn save_game(&self, game_id: Option<GameId>, name: &str) -> Result<GameId, FatalError> {
match game_id {
None => {
let game_id = GameId::new();
let mut stmt = self
.conn
.prepare("INSERT INTO games VALUES (?, ?)")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
stmt.execute((game_id.as_str(), name)).unwrap();
Ok(game_id)
}
Some(game_id) => {
let mut stmt = self
.conn
.prepare("UPDATE games SET name=? WHERE uuid=?")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
stmt.execute((name, game_id.as_str())).unwrap();
Ok(game_id)
}
}
}
fn character(&self, id: CharacterId) -> Result<Option<CharsheetRow>, FatalError> {
let mut stmt = self
.conn
.prepare("SELECT uuid, game, data FROM characters WHERE uuid=?")
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
let items: Vec<CharsheetRow> = stmt
.query_map([id.as_str()], |row| {
let data: String = row.get(2).unwrap();
Ok(CharsheetRow {
id: row.get(0).unwrap(),
game: row.get(1).unwrap(),
data: serde_json::from_str(&data).unwrap(),
})
})
.unwrap()
.collect::<Result<Vec<CharsheetRow>, rusqlite::Error>>()
.unwrap();
match &items[..] {
[] => Ok(None),
[item] => Ok(Some(item.clone())),
_ => Err(FatalError::NonUniqueDatabaseKey(id.as_str().to_owned())),
}
}
fn save_character(
&self,
char_id: Option<CharacterId>,
game: GameId,
character: serde_json::Value,
) -> std::result::Result<CharacterId, FatalError> {
match char_id {
None => {
let char_id = CharacterId::new();
let mut stmt = self
.conn
.prepare("INSERT INTO characters VALUES (?, ?, ?)")
.unwrap();
stmt.execute((char_id.as_str(), game.as_str(), character.to_string()))
.unwrap();
Ok(char_id)
}
Some(char_id) => {
let mut stmt = self
.conn
.prepare("UPDATE characters SET data=? WHERE uuid=?")
.unwrap();
stmt.execute((character.to_string(), char_id.as_str()))
.unwrap();
Ok(char_id)
}
}
}
}
async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
while let Ok(DatabaseRequest { tx, req }) = requestor.recv().await {
println!("Request received: {:?}", req);
match req {
Request::Charsheet(id) => {
let sheet = db.character(id);
println!("sheet retrieved: {:?}", sheet);
match sheet {
Ok(sheet) => {
tx.send(DatabaseResponse::Charsheet(sheet)).await.unwrap();
}
_ => unimplemented!(),
}
}
Request::Games => {
unimplemented!();
}
Request::User(uid) => {
let user = db.user(uid);
match user {
Ok(user) => {
tx.send(DatabaseResponse::User(user)).await.unwrap();
}
err => panic!("{:?}", err),
}
}
Request::SaveUser(user_id, username, password, admin, enabled) => {
let user_id = db.save_user(user_id, username.as_ref(), password.as_ref(), admin, enabled);
match user_id {
Ok(user_id) => {
tx.send(DatabaseResponse::SaveUser(user_id)).await.unwrap();
}
err => panic!("{:?}", err),
}
}
Request::Users => {
let users = db.users();
match users {
Ok(users) => {
tx.send(DatabaseResponse::Users(users)).await.unwrap();
}
_ => unimplemented!(),
}
}
}
}
println!("ending db_handler");
}
pub struct DbConn {
conn: Sender<DatabaseRequest>,
handle: tokio::task::JoinHandle<()>,
}
impl DbConn {
pub fn new<P>(path: Option<P>) -> Self
where
P: AsRef<Path>,
{
let (tx, rx) = bounded::<DatabaseRequest>(5);
let db = DiskDb::new(path).unwrap();
let handle = tokio::spawn(async move {
db_handler(db, rx).await;
});
Self { conn: tx, handle }
}
}
#[async_trait]
impl Database for DbConn {
async fn user(&mut self, uid: UserId) -> Result<Option<UserRow>, FatalError> {
let (tx, rx) = bounded::<DatabaseResponse>(1);
let request = DatabaseRequest {
tx,
req: Request::User(uid),
};
match self.conn.send(request).await {
Ok(()) => (),
Err(_) => return Err(FatalError::DatabaseConnectionLost),
};
match rx.recv().await {
Ok(DatabaseResponse::User(user)) => Ok(user),
Ok(_) => Err(FatalError::MessageMismatch),
Err(_) => Err(FatalError::DatabaseConnectionLost),
}
}
async fn save_user(
&mut self,
user_id: Option<UserId>,
name: &str,
password: &str,
admin: bool,
enabled: bool,
) -> Result<UserId, FatalError> {
let (tx, rx) = bounded::<DatabaseResponse>(1);
let request = DatabaseRequest {
tx,
req: Request::SaveUser(
user_id,
name.to_owned(),
password.to_owned(),
admin,
enabled,
),
};
match self.conn.send(request).await {
Ok(()) => (),
Err(_) => return Err(FatalError::DatabaseConnectionLost),
};
match rx.recv().await {
Ok(DatabaseResponse::SaveUser(user_id)) => Ok(user_id),
Ok(_) => Err(FatalError::MessageMismatch),
Err(_) => Err(FatalError::DatabaseConnectionLost),
}
}
async fn users(&mut self) -> Result<Vec<UserRow>, FatalError> {
let (tx, rx) = bounded::<DatabaseResponse>(1);
let request = DatabaseRequest {
tx,
req: Request::Users,
};
match self.conn.send(request).await {
Ok(()) => (),
Err(_) => return Err(FatalError::DatabaseConnectionLost),
};
match rx.recv().await {
Ok(DatabaseResponse::Users(lst)) => Ok(lst),
Ok(_) => Err(FatalError::MessageMismatch),
Err(_) => Err(FatalError::DatabaseConnectionLost),
}
}
async fn games(&mut self) -> Result<Vec<GameRow>, FatalError> {
let (tx, rx) = bounded::<DatabaseResponse>(1);
let request = DatabaseRequest {
tx,
req: Request::Games,
};
match self.conn.send(request).await {
Ok(()) => (),
Err(_) => return Err(FatalError::DatabaseConnectionLost),
};
match rx.recv().await {
Ok(DatabaseResponse::Games(lst)) => Ok(lst),
Ok(_) => Err(FatalError::MessageMismatch),
Err(_) => Err(FatalError::DatabaseConnectionLost),
}
}
async fn character(&mut self, id: CharacterId) -> Result<Option<CharsheetRow>, FatalError> {
let (tx, rx) = bounded::<DatabaseResponse>(1);
let request = DatabaseRequest {
tx,
req: Request::Charsheet(id),
};
match self.conn.send(request).await {
Ok(()) => (),
Err(_) => return Err(FatalError::DatabaseConnectionLost),
};
match rx.recv().await {
Ok(DatabaseResponse::Charsheet(row)) => Ok(row),
Ok(_) => Err(FatalError::MessageMismatch),
Err(_) => Err(FatalError::DatabaseConnectionLost),
}
}
}
#[cfg(test)]
mod test {
use std::path::PathBuf;
use cool_asserts::assert_matches;
use super::*;
const soren: &'static str = r#"{ "type_": "Candela", "name": "Soren Jensen", "pronouns": "he/him", "circle": "Circle of the Bluest Sky", "style": "dapper gentleman", "catalyst": "a cursed book", "question": "What were the contents of that book?", "nerve": { "type_": "nerve", "drives": { "current": 1, "max": 2 }, "resistances": { "current": 0, "max": 3 }, "move": { "gilded": false, "score": 2 }, "strike": { "gilded": false, "score": 1 }, "control": { "gilded": true, "score": 0 } }, "cunning": { "type_": "cunning", "drives": { "current": 1, "max": 1 }, "resistances": { "current": 0, "max": 3 }, "sway": { "gilded": false, "score": 0 }, "read": { "gilded": false, "score": 0 }, "hide": { "gilded": false, "score": 0 } }, "intuition": { "type_": "intuition", "drives": { "current": 0, "max": 0 }, "resistances": { "current": 0, "max": 3 }, "survey": { "gilded": false, "score": 0 }, "focus": { "gilded": false, "score": 0 }, "sense": { "gilded": false, "score": 0 } }, "role": "Slink", "role_abilities": [ "Scout: If you have time to observe a location, you can spend 1 Intuition to ask a question: What do I notice here that others do not see? What in this place might be of use to us? What path should we follow?" ], "specialty": "Detective", "specialty_abilities": [ "Mind Palace: When you want to figure out how two clues might relate or what path they should point you towards, burn 1 Intution resistance. The GM will give you the information you have deduced." ] }"#;
fn setup_db() -> (DiskDb, GameId) {
let no_path: Option<PathBuf> = None;
let db = DiskDb::new(no_path).unwrap();
db.save_user(None, "admin", "abcdefg", true, true);
let game_id = db.save_game(None, "Candela").unwrap();
(db, game_id)
}
#[test]
fn it_can_retrieve_a_character() {
let (db, game_id) = setup_db();
assert_matches!(db.character(CharacterId::from("1")), Ok(None));
let js: serde_json::Value = serde_json::from_str(soren).unwrap();
let soren_id = db.save_character(None, game_id, js.clone()).unwrap();
assert_matches!(db.character(soren_id).unwrap(), Some(CharsheetRow{ data, .. }) => assert_eq!(js, data));
}
#[tokio::test]
async fn it_can_retrieve_a_character_through_conn() {
let memory_db: Option<PathBuf> = None;
let mut conn = DbConn::new(memory_db);
assert_matches!(
conn.character(CharacterId::from("1")).await,
ResultExt::Ok(None)
);
}
}

View File

@ -1,18 +1,6 @@
use std::future::Future;
use authdb::{AuthDB, AuthToken};
use http::{response::Response, status::StatusCode, Error};
use futures::{SinkExt, StreamExt};
use result_extended::{error, ok, return_error, ResultExt};
use serde::{Deserialize, Serialize};
use warp::{http::Response, http::StatusCode, reply::Reply, ws::Message};
use crate::{
asset_db::AssetId,
core::Core,
database::{CharacterId, UserId},
types::{AppError, FatalError},
};
/*
pub async fn handle_auth(
auth_ctx: &AuthDB,
auth_token: AuthToken,
@ -34,224 +22,3 @@ pub async fn handle_auth(
.body("".to_owned()),
}
}
*/
pub async fn handler<F>(f: F) -> impl Reply
where
F: Future<Output = ResultExt<Response<Vec<u8>>, AppError, FatalError>>,
{
match f.await {
ResultExt::Ok(response) => response,
ResultExt::Err(AppError::NotFound(_)) => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(vec![])
.unwrap(),
ResultExt::Err(_) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(vec![])
.unwrap(),
ResultExt::Fatal(err) => {
panic!("Shutting down with fatal error: {:?}", err);
}
}
}
pub async fn handle_server_status(core: Core) -> impl Reply {
handler(async move {
let status = return_error!(core.status().await);
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_vec(&status).unwrap())
.unwrap())
})
.await
}
pub async fn handle_file(core: Core, asset_id: AssetId) -> impl Reply {
handler(async move {
let (mime, bytes) = return_error!(core.get_asset(asset_id).await);
ok(Response::builder()
.header("content-type", mime.to_string())
.body(bytes)
.unwrap())
})
.await
}
pub async fn handle_available_images(core: Core) -> impl Reply {
handler(async move {
let image_paths: Vec<String> = core
.available_images()
.await
.into_iter()
.map(|path| format!("{}", path.as_str()))
.collect();
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_vec(&image_paths).unwrap())
.unwrap())
})
.await
}
#[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 {
handler(async move {
let client_id = core.register_client().await;
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(
serde_json::to_vec(&RegisterResponse {
url: format!("ws://127.0.0.1:8001/ws/{}", client_id),
})
.unwrap(),
)
.unwrap())
})
.await
}
pub async fn handle_unregister_client(core: Core, client_id: String) -> impl Reply {
handler(async move {
core.unregister_client(client_id);
ok(Response::builder()
.status(StatusCode::NO_CONTENT)
.body(vec![])
.unwrap())
})
.await
}
pub async fn handle_connect_websocket(
core: Core,
ws: warp::ws::Ws,
client_id: String,
) -> impl Reply {
ws.on_upgrade(move |socket| {
println!("upgrading websocket");
let core = core.clone();
async move {
let (mut ws_sender, _) = socket.split();
let mut receiver = core.connect_client(client_id.clone()).await;
tokio::task::spawn(async move {
let tabletop = core.tabletop().await;
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 {
handler(async move {
let _ = core.set_background_image(AssetId::from(image_name)).await;
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "*")
.header("Content-Type", "application/json")
.body(vec![])
.unwrap())
})
.await
}
pub async fn handle_get_users(core: Core) -> impl Reply {
handler(async move {
let users = match core.list_users().await {
ResultExt::Ok(users) => users,
ResultExt::Err(err) => return ResultExt::Err(err),
ResultExt::Fatal(err) => return ResultExt::Fatal(err),
};
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_vec(&users).unwrap())
.unwrap())
})
.await
}
pub async fn handle_get_games(core: Core) -> impl Reply {
handler(async move {
let games = match core.list_games().await {
ResultExt::Ok(games) => games,
ResultExt::Err(err) => return ResultExt::Err(err),
ResultExt::Fatal(err) => return ResultExt::Fatal(err),
};
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_vec(&games).unwrap())
.unwrap())
})
.await
}
pub async fn handle_get_charsheet(core: Core, charid: String) -> impl Reply {
handler(async move {
let sheet = match core.get_charsheet(CharacterId::from(charid)).await {
ResultExt::Ok(sheet) => sheet,
ResultExt::Err(err) => return ResultExt::Err(err),
ResultExt::Fatal(err) => return ResultExt::Fatal(err),
};
match sheet {
Some(sheet) => ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Content-Type", "application/json")
.body(serde_json::to_vec(&sheet).unwrap())
.unwrap()),
None => ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(vec![])
.unwrap()),
}
})
.await
}
pub async fn handle_set_admin_password(core: Core, password: String) -> impl Reply {
handler(async move {
let status = return_error!(core.status().await);
if status.admin_enabled {
return error(AppError::PermissionDenied);
}
core.set_password(UserId::from("admin"), password).await;
ok(Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "*")
.header("Content-Type", "application/json")
.body(vec![])
.unwrap())
})
.await
}

View File

@ -1,27 +1,19 @@
use authdb::{AuthDB, AuthError, AuthToken, SessionToken, Username};
use std::{
convert::Infallible,
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
};
use asset_db::{AssetId, FsAssets};
use authdb::AuthError;
use database::DbConn;
use handlers::{
handle_available_images, handle_connect_websocket, handle_file, handle_get_charsheet, handle_get_users, handle_register_client, handle_server_status, handle_set_admin_password, handle_set_background_image, handle_unregister_client, RegisterRequest
sync::Arc,
};
use warp::{
// header,
http::{Response, StatusCode},
reply::Reply,
header,
http::StatusCode,
reply::{Json, Reply},
Filter,
};
mod asset_db;
mod core;
mod database;
mod handlers;
mod types;
use handlers::handle_auth;
#[derive(Debug)]
struct Unauthorized;
@ -31,7 +23,6 @@ impl warp::reject::Reject for Unauthorized {}
struct AuthDBError(AuthError);
impl warp::reject::Reject for AuthDBError {}
/*
fn with_session(
auth_ctx: Arc<AuthDB>,
) -> impl Filter<Extract = (Username,), Error = warp::Rejection> + Clone {
@ -80,10 +71,8 @@ fn route_echo_authenticated(
warp::reply::json(&vec!["authenticated", username.as_str(), param.as_str()])
})
}
*/
async fn handle_rejection(err: warp::Rejection) -> Result<impl Reply, Infallible> {
println!("handle_rejection: {:?}", err);
if let Some(Unauthorized) = err.find() {
Ok(warp::reply::with_status(
"".to_owned(),
@ -99,121 +88,14 @@ async fn handle_rejection(err: warp::Rejection) -> Result<impl Reply, Infallible
#[tokio::main]
pub async fn main() {
let conn = DbConn::new(Some("/home/savanni/game.db"));
let auth_db = AuthDB::new(PathBuf::from("./auth_db.sqlite"))
.await
.expect("AuthDB should initialize");
let auth_ctx: Arc<AuthDB> = Arc::new(auth_db);
let core = core::Core::new(FsAssets::new(PathBuf::from("/home/savanni/Pictures")), conn);
let log = warp::log("visions::api");
let route_server_status = warp::path!("api" / "v1" / "status")
.and(warp::get())
.then({
let core = core.clone();
move || handle_server_status(core.clone())
});
let route_image = warp::path!("api" / "v1" / "image" / String)
.and(warp::get())
.then({
let core = core.clone();
move |file_name| handle_file(core.clone(), AssetId::from(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 route_get_users = warp::path!("api" / "v1" / "users")
.and(warp::get())
.then({
let core = core.clone();
move || handle_get_users(core.clone())
});
let route_get_charsheet = warp::path!("api" / "v1" / "charsheet" / String)
.and(warp::get())
.then({
let core = core.clone();
move |charid| handle_get_charsheet(core.clone(), charid)
});
let route_set_admin_password_options = warp::path!("api" / "v1" / "admin_password")
.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_admin_password = warp::path!("api" / "v1" / "admin_password")
.and(warp::put())
.and(warp::body::json())
.then({
let core = core.clone();
move |body| handle_set_admin_password(core.clone(), body)
});
let filter = route_server_status
.or(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)
.or(route_get_users)
.or(route_get_charsheet)
.or(route_set_admin_password_options)
.or(route_set_admin_password)
let filter = route_echo_authenticated(auth_ctx.clone())
.or(route_authenticate(auth_ctx.clone()))
.or(route_echo_unauthenticated())
.recover(handle_rejection);
let server = warp::serve(filter);

View File

@ -1,117 +0,0 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;
use typeshare::typeshare;
use crate::{asset_db::AssetId, database::UserRow};
#[derive(Debug, Error)]
pub enum FatalError {
#[error("Non-unique database key {0}")]
NonUniqueDatabaseKey(String),
#[error("Database migrations failed {0}")]
DatabaseMigrationFailure(String),
#[error("Failed to construct a query")]
ConstructQueryFailure(String),
#[error("Database connection lost")]
DatabaseConnectionLost,
#[error("Unexpected response for message")]
MessageMismatch,
}
impl result_extended::FatalError for FatalError {}
#[derive(Debug, Error)]
pub enum AppError {
#[error("something wasn't found {0}")]
NotFound(String),
#[error("object inaccessible {0}")]
Inaccessible(String),
#[error("the requested operation is not allowed")]
PermissionDenied,
#[error("invalid json {0}")]
JsonError(serde_json::Error),
#[error("wat {0}")]
UnexpectedError(String),
}
#[derive(Clone, Debug, Deserialize, PartialEq, 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 User {
pub id: String,
pub name: String,
pub password: String,
pub admin: bool,
pub enabled: bool,
}
impl From<UserRow> for User {
fn from(row: UserRow) -> Self {
Self {
id: row.id.as_str().to_owned(),
name: row.name.to_owned(),
password: row.password.to_owned(),
admin: row.admin,
enabled: row.enabled,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[typeshare]
pub enum PlayerRole {
Gm,
Player,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct Player {
user_id: String,
role: PlayerRole,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct Game {
pub id: String,
pub name: String,
pub players: Vec<Player>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct Tabletop {
pub background_color: RGB,
pub background_image: Option<AssetId>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type", content = "content")]
#[typeshare]
pub enum Message {
UpdateTabletop(Tabletop),
}

23
visions/ui/.gitignore vendored
View File

@ -1,23 +0,0 @@
# 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*

10
visions/ui/Makefile Normal file
View File

@ -0,0 +1,10 @@
release:
NODE_ENV=production npm run build
dev:
npm run build
server:
npx http-server ./dist

View File

@ -1,46 +0,0 @@
# 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/).

View File

@ -1,9 +0,0 @@
version: '3'
tasks:
dev:
cmds:
- cd ../visions-types && task build
- npm install
- npm run start

File diff suppressed because it is too large Load Diff

View File

@ -1,50 +1,24 @@
{
"name": "ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.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",
"classnames": "^2.5.1",
"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",
"visions-types": "../visions-types",
"web-vitals": "^2.1.4"
},
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
"author": "",
"license": "GPL-3.0-or-later",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"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"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -1,43 +0,0 @@
<!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.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -1,25 +0,0 @@
{
"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

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

View File

@ -1,37 +0,0 @@
.App {
}
.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

@ -1,9 +0,0 @@
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();
});

View File

@ -1,83 +0,0 @@
import React, { PropsWithChildren, useContext, useEffect, useState } from 'react';
import './App.css';
import { Client } from './client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { DesignPage } from './views/Design/Design';
import { GmView } from './views/GmView/GmView';
import { WebsocketProvider } from './components/WebsocketProvider';
import { PlayerView } from './views/PlayerView/PlayerView';
import { Admin } from './views/Admin/Admin';
import Candela from './plugins/Candela';
import { Authentication } from './views/Authentication/Authentication';
import { StateContext, StateProvider } from './providers/StateProvider/StateProvider';
const TEST_CHARSHEET_UUID = "12df9c09-1f2f-4147-8eda-a97bd2a7a803";
interface AppProps {
client: Client;
}
const CandelaCharsheet = ({ client }: { client: Client }) => {
let [sheet, setSheet] = useState(undefined);
useEffect(
() => { client.charsheet(TEST_CHARSHEET_UUID).then((c) => setSheet(c)); },
[client, setSheet]
);
return sheet ? <Candela.CharsheetElement sheet={sheet} /> : <div> </div>
}
interface AuthedViewProps {
client: Client;
}
const AuthedView = ({ client, children }: PropsWithChildren<AuthedViewProps>) => {
const [state, manager] = useContext(StateContext);
return (
<Authentication onAdminPassword={(password) => {
manager.setAdminPassword(password);
}} onAuth={(username, password) => console.log(username, password)}>
{children}
</Authentication>
);
}
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: "/",
element: <StateProvider client={client}><AuthedView client={client}> <PlayerView client={client} /> </AuthedView> </StateProvider>
},
{
path: "/gm",
element: websocketUrl ? <WebsocketProvider websocketUrl={websocketUrl}> <GmView client={client} /> </WebsocketProvider> : <div> </div>
},
{
path: "/admin",
element: <Admin client={client} />
},
{
path: "/candela",
element: <CandelaCharsheet client={client} />
},
{
path: "/design",
element: <DesignPage />
}
]);
return (
<div className="App">
<RouterProvider router={router} />
</div>
);
}
export default App;

View File

@ -1,73 +0,0 @@
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) });
}
async users() {
const url = new URL(this.base);
url.pathname = '/api/v1/users/';
return fetch(url).then((response) => response.json());
}
async charsheet(id: string) {
const url = new URL(this.base);
url.pathname = `/api/v1/charsheet/${id}`;
return fetch(url).then((response) => response.json());
}
async setAdminPassword(password: string) {
const url = new URL(this.base);
url.pathname = `/api/v1/admin_password`;
console.log("setting the admin password to: ", password);
return fetch(url, { method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify(password) });
}
async status() {
const url = new URL(this.base);
url.pathname = `/api/v1/status`;
return fetch(url).then((response) => response.json());
}
}

View File

@ -1,8 +0,0 @@
import React from 'react';
interface GuageProps {
current: number,
max: number,
}
export const SimpleGuage = ({ current, max }: GuageProps) => <> {current} / {max}</>

View File

@ -1,3 +0,0 @@
.tabletop > img {
max-width: 100%;
}

View File

@ -1,14 +0,0 @@
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 className="tabletop"> {backgroundUrl && <img src={backgroundUrl.toString()} alt="playing field" />} </div>
}

View File

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

View File

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

View File

@ -1,45 +0,0 @@
import React, { createContext, PropsWithChildren, useEffect, useReducer } from "react";
import useWebSocket from "react-use-websocket";
import { Message, Tabletop } from "visions-types";
type WebsocketState = { }
export const WebsocketContext = createContext<WebsocketState>({});
interface WebsocketProviderProps {
websocketUrl: string;
}
export const WebsocketProvider = ({ websocketUrl, children }: PropsWithChildren<WebsocketProviderProps>) => {
return <div> {children} </div>;
/*
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,
}
}
}
}
*/

View File

@ -1,5 +0,0 @@
import { ThumbnailElement } from './Thumbnail/Thumbnail'
import { TabletopElement } from './Tabletop/Tabletop'
import { SimpleGuage } from './Guages/SimpleGuage'
export default { ThumbnailElement, TabletopElement, SimpleGuage }

View File

@ -1,15 +0,0 @@
:root {
--border-standard: 2px solid black;
--border-radius-standard: 4px;
--border-shadow-shallow: 1px 1px 2px black;
--padding-m: 8px;
--margin-s: 4px;
}
.card {
border: var(--border-standard);
border-radius: var(--border-radius-standard);
box-shadow: var(--border-shadow-shallow);
padding: var(--padding-m);
}

View File

@ -1,13 +0,0 @@
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;
}

View File

@ -0,0 +1,6 @@
<!doctype html>
<html>
<body>
<div id="root"></div>
</body>
</html>

View File

@ -1,22 +0,0 @@
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();

View File

@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 2.6 KiB

11
visions/ui/src/main.tsx Normal file
View File

@ -0,0 +1,11 @@
import React from "react";
import ReactDOM from "react-dom";
const App = () => <div>App</div>;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);

View File

@ -1,110 +0,0 @@
.charsheet__header {
display: flex;
}
.charsheet__header > div {
margin: 8px;
width: 33%;
}
.charsheet__body {
display: flex;
}
.charsheet__body > div {
margin: 8px;
width: 33%;
}
.action-group {
position: relative;
border: 2px solid black;
border-radius: 4px;
padding-left: 8px;
padding-bottom: 8px;
}
.action-group:before {
content: " ";
position: absolute;
z-index: -1;
top: 2px;
left: 2px;
right: 2px;
bottom: 2px;
border: 2px solid black;
}
.action-group__header {
display: flex;
font-size: xx-large;
justify-content: space-between;
margin: 4px;
margin-left: -4px;
padding-left: 4px;
background-color: black;
color: white;
}
.action-group__action {
margin: 2px;
}
.action-group__dots {
margin: 0px;
padding: 0px;
padding-left: 16px;
}
.action-group__guage-column {
width: 10px;
height: 100%;
margin: 2px;
}
.action-group__guage-top {
position: relative;
background-color: white;
margin-bottom: 2px;
}
.action-group__guage-top:before {
content: " ";
position: absolute;
z-index: -1;
top: 2px;
right: 2px;
bottom: 2px;
left: 2px;
border: 1px solid black;
}
.action-group__guage-top_filled {
background-color: black;
margin-bottom: 2px;
}
.action-group__guage-bottom {
background-color: white;
height: 8px;
}
.action-group__guage-bottom_filled {
background-color: black;
height: 8px;
}
.action-group__guage-bottom:before {
content: " ";
position: absolute;
z-index: -1;
top: 1px;
left: 1px;
right: 1px;
bottom: 1px;
}
.action-group__guage {
display: flex;
}

View File

@ -1,164 +0,0 @@
import React from 'react';
import { assertNever } from '.';
import './Charsheet.css';
import { DriveGuage } from './DriveGuage/DriveGuage';
import { Charsheet, Nerve, Cunning, Intuition } from './types';
interface CharsheetProps {
sheet: Charsheet,
}
interface ActionElementProps {
name: string,
gilded: boolean,
value: number,
}
const ActionElement = ({ name, gilded, value }: ActionElementProps) => {
let dots = [];
for (let i = 0; i < value; i++) {
dots.push("\u25ef");
}
let diamond = gilded ? "\u25c6" : "\u25c7";
return (<div>
<h2 className="action-group__action"> {diamond} {name} </h2>
<div className="action-group__dots"> {dots} </div>
</div>);
}
interface ActionGroupElementProps {
group: Nerve | Cunning | Intuition;
}
const ActionGroupElement = ({ group }: ActionGroupElementProps) => {
var title;
var elements = [];
switch (group.type_) {
case "nerve": {
title = <div className="action-group__header"> Nerve <DriveGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Move" gilded={group.move.gilded} value={group.move.score} />);
elements.push(<ActionElement name="Strike" gilded={group.strike.gilded} value={group.strike.score} />);
elements.push(<ActionElement name="Control" gilded={group.control.gilded} value={group.control.score} />);
break
}
case "cunning": {
title = <div className="action-group__header"> Cunning <DriveGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Sway" gilded={group.sway.gilded} value={group.sway.score} />);
elements.push(<ActionElement name="Read" gilded={group.read.gilded} value={group.read.score} />);
elements.push(<ActionElement name="Hide" gilded={group.hide.gilded} value={group.hide.score} />);
break
}
case "intuition": {
title = <div className="action-group__header"> Intuition <DriveGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Survey" gilded={group.survey.gilded} value={group.survey.score} />);
elements.push(<ActionElement name="Focus" gilded={group.focus.gilded} value={group.focus.score} />);
elements.push(<ActionElement name="Sense" gilded={group.sense.gilded} value={group.sense.score} />);
break
}
default: {
assertNever(group);
}
}
return (<div className="action-group">
{title}
{elements}
</div>)
}
interface AbilitiesElementProps {
role: string
role_abilities: string[]
specialty: string
specialty_abilities: string[]
}
const AbilitiesElement = ({ role, role_abilities, specialty, specialty_abilities }: AbilitiesElementProps) => {
return (<div>
<h1> ROLE: {role} </h1>
<ul>
{role_abilities.map((ability) => <li>{ability}</li>)}
</ul>
<h1> SPECIALTY: {role} </h1>
<ul>
{specialty_abilities.map((ability) => <li>{ability}</li>)}
</ul>
</div>
);
}
export const CharsheetElement = ({ sheet }: CharsheetProps) => {
return (<div>
<div className="charsheet__header">
<div> Candela Obscura </div>
<div>
<p> {sheet.name} </p>
<p> {sheet.pronouns} </p>
<p> {sheet.circle} </p>
</div>
<div>
<p> {sheet.style} </p>
<p> {sheet.catalyst} </p>
<p> {sheet.question} </p>
</div>
</div >
<div className="charsheet__body">
<div>
<ActionGroupElement group={sheet.nerve} />
<ActionGroupElement group={sheet.cunning} />
<ActionGroupElement group={sheet.intuition} />
</div>
<div> <AbilitiesElement {...sheet} /> </div>
<div> Marks, Scars, Relationships </div>
</div>
</div>);
}
/*
export const CharsheetElement = () => {
const sheet = {
type_: 'Candela',
name: "Soren Jensen",
pronouns: 'he/him',
circle: 'Circle of the Bluest Sky',
style: 'dapper gentleman',
catalyst: 'a cursed book',
question: 'What were the contents of that book?',
nerve: {
type_: "nerve",
drives: { current: 1, max: 2 },
resistances: { current: 0, max: 3 },
move: { gilded: false, score: 2 },
strike: { gilded: false, score: 1 },
control: { gilded: true, score: 0 },
} as Nerve,
cunning: {
type_: "cunning",
drives: { current: 1, max: 1 },
resistances: { current: 0, max: 3 },
sway: { gilded: false, score: 0 },
read: { gilded: false, score: 0 },
hide: { gilded: false, score: 0 },
} as Cunning,
intuition: {
type_: "intuition",
drives: { current: 0, max: 0 },
resistances: { current: 0, max: 3 },
survey: { gilded: false, score: 0 },
focus: { gilded: false, score: 0 },
sense: { gilded: false, score: 0 },
} as Intuition,
role: 'Slink',
role_abilities: [
'Scout: If you have time to observe a location, you can spend 1 Intuition to ask a question: What do I notice here that others do not see? What in this place might be of use to us? What path should we follow?',
],
specialty: 'Detective',
specialty_abilities: [
"Mind Palace: When you want to figure out how two clues might relate or what path they should point you towards, burn 1 Intution resistance. The GM will give you the information you've deduced.",
],
};
return <CharsheetElement_ sheet={sheet} />
}
*/

View File

@ -1,24 +0,0 @@
.candela-panel-actions {
border: 1px solid black;
padding: 4px;
margin: 2px;
}
.candela-panel-actions__header {
display: flex;
padding: 2px;
padding-left: 4px;
padding-right: 4px;
justify-content: space-between;
background-color: black;
color: white;
}
.candela-panel-actions__action {
display: flex;
justify-content: space-between;
}
.candela-panel-actions__action_gilded {
font-weight: bold;
}

View File

@ -1,137 +0,0 @@
import React from 'react';
import { assertNever } from '.';
import { SimpleGuage } from '../../components/Guages/SimpleGuage';
import { Charsheet, Nerve, Cunning, Intuition } from './types';
import './CharsheetPanel.css';
import classNames from 'classnames';
interface CharsheetPanelProps {
sheet: Charsheet;
}
interface ActionElementProps {
name: string,
gilded: boolean,
value: number,
}
const ActionElement = ({ name, gilded, value }: ActionElementProps) => {
const className = gilded ? "candela-panel-actions__action_gilded" : "candela-panel-actions__action";
return (<div className={classNames({
"candela-panel-actions__action": true,
"candela-panel-actions__action_gilded": gilded,
})}> <div> {name} </div> <div> {value} </div> </div>);
}
interface ActionGroupElementProps {
group: Nerve | Cunning | Intuition;
}
const ActionGroupElement = ({ group }: ActionGroupElementProps) => {
var title;
var elements = [];
switch (group.type_) {
case "nerve": {
title = <div className="candela-panel-actions__header"> <div> Nerve </div> <SimpleGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Move" gilded={group.move.gilded} value={group.move.score} />);
elements.push(<ActionElement name="Strike" gilded={group.strike.gilded} value={group.strike.score} />);
elements.push(<ActionElement name="Control" gilded={group.control.gilded} value={group.control.score} />);
break
}
case "cunning": {
title = <div className="candela-panel-actions__header"> <div> Cunning </div> <SimpleGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Sway" gilded={group.sway.gilded} value={group.sway.score} />);
elements.push(<ActionElement name="Read" gilded={group.read.gilded} value={group.read.score} />);
elements.push(<ActionElement name="Hide" gilded={group.hide.gilded} value={group.hide.score} />);
break
}
case "intuition": {
title = <div className="candela-panel-actions__header"> <div> Intuition </div> <SimpleGuage current={group.drives.current} max={group.drives.max} /> </div>
elements.push(<ActionElement name="Survey" gilded={group.survey.gilded} value={group.survey.score} />);
elements.push(<ActionElement name="Focus" gilded={group.focus.gilded} value={group.focus.score} />);
elements.push(<ActionElement name="Sense" gilded={group.sense.gilded} value={group.sense.score} />);
break
}
default: {
assertNever(group);
}
}
return (<div className="candela-panel-actions">
{title}
{elements}
</div>)
}
export const CharsheetPanelElement = ({ sheet }: CharsheetPanelProps) => {
return (<div className="candela-panel">
<div className="candela-panel__header">
<p> {sheet.name} ({sheet.pronouns}) </p>
<p> {sheet.specialty} </p>
</div>
<div className="candela-panel__action-groups">
<ActionGroupElement group={sheet.nerve} />
<ActionGroupElement group={sheet.cunning} />
<ActionGroupElement group={sheet.intuition} />
</div>
<div>
<ul>
{sheet.role_abilities.map((ability) => <li> {ability} </li>)}
{sheet.specialty_abilities.map((ability) => <li> {ability} </li>)}
</ul>
</div>
</div>);
}
/*
export const CharsheetPanelElement = () => {
const sheet = {
type_: 'Candela',
name: "Soren Jensen",
pronouns: 'he/him',
circle: 'Circle of the Bluest Sky',
style: 'dapper gentleman',
catalyst: 'a cursed book',
question: 'What were the contents of that book?',
nerve: {
type_: "nerve",
drives: { current: 1, max: 2 },
resistances: { current: 0, max: 3 },
move: { gilded: false, score: 2 },
strike: { gilded: false, score: 1 },
control: { gilded: true, score: 0 },
} as Nerve,
cunning: {
type_: "cunning",
drives: { current: 1, max: 1 },
resistances: { current: 0, max: 3 },
sway: { gilded: false, score: 0 },
read: { gilded: false, score: 0 },
hide: { gilded: false, score: 0 },
} as Cunning,
intuition: {
type_: "intuition",
drives: { current: 0, max: 0 },
resistances: { current: 0, max: 3 },
survey: { gilded: false, score: 0 },
focus: { gilded: false, score: 0 },
sense: { gilded: false, score: 0 },
} as Intuition,
role: 'Slink',
role_abilities: [
'Scout: If you have time to observe a location, you can spend 1 Intuition to ask a question: What do I notice here that others do not see? What in this place might be of use to us? What path should we follow?',
],
specialty: 'Detective',
specialty_abilities: [
"Mind Palace: When you want to figure out how two clues might relate or what path they should point you towards, burn 1 Intution resistance. The GM will give you the information you've deduced.",
],
};
return <CharsheetPanelElement_ sheet={sheet} />
}
*/

View File

@ -1,44 +0,0 @@
.drive-guages_on-light {
background-color: white;
}
.drive-guage {
display: flex;
}
.drive-guage__element {
border: 1px solid black;
margin: 1px;
background-color: white;
}
.drive-guage__spacer {
margin: 1px;
}
.drive-guage__top {
margin: 1px;
width: 8px;
border: 1px solid black;
background-color: white;
}
.drive-guage__top_filled {
background-color: black;
}
.drive-guage__bottom {
margin: 1px;
border: 1px solid black;
width: 8px;
height: 8px;
background-color: white;
}
.drive-guage__bottom_filled {
background-color: black;
}
.drive-guages_on-dark {
background-color: black;
}

View File

@ -1,24 +0,0 @@
import React from 'react';
import './DriveGuage.css';
interface Guage {
current: number;
max: number;
}
export const DriveGuage = ({ current, max }: Guage) => {
let components = [];
for (let i = 0; i < 9; i++) {
components.push(<div className="drive-guage__element">
{i < current ? <div className="drive-guage__top drive-guage__top_filled">&nbsp;</div> :
<div className="drive-guage__top">&nbsp;</div>}
{i < max ? <div className="drive-guage__bottom drive-guage__bottom_filled">&nbsp;</div> :
<div className="drive-guage__bottom">&nbsp;</div>}
</div>)
}
components.splice(3, 0, <div className="drive-guage__spacer">&nbsp;</div>);
components.splice(7, 0, <div className="drive-guage__spacer">&nbsp;</div>);
return (<div className="drive-guage">
{components}
</div>)
}

View File

@ -1,9 +0,0 @@
import { CharsheetElement } from './Charsheet';
import { CharsheetPanelElement } from './CharsheetPanel';
export function assertNever(value: never) {
throw new Error("Unexpected value: " + value);
}
export default { CharsheetElement, CharsheetPanelElement };

View File

@ -1,65 +0,0 @@
export type Guage = {
current: number,
max: number,
}
export type Action = {
gilded: boolean,
score: number,
}
export type Actions = { [key: string]: Action }
export type ActionGroup = {
drives: Guage,
resistances: Guage,
actions: Actions,
}
export type Nerve = {
type_: "nerve",
drives: Guage,
resistances: Guage,
move: Action,
strike: Action,
control: Action,
}
export type Cunning = {
type_: "cunning",
drives: Guage,
resistances: Guage,
sway: Action,
read: Action,
hide: Action,
}
export type Intuition = {
type_: "intuition",
drives: Guage,
resistances: Guage,
survey: Action,
focus: Action,
sense: Action,
}
export type Charsheet = {
type_: string,
name: string,
pronouns: string
circle: string
style: string,
catalyst: string,
question: string,
nerve: Nerve,
cunning: Cunning,
intuition: Intuition,
role: string,
role_abilities: string[],
specialty: string,
specialty_abilities: string[],
}

View File

@ -1,70 +0,0 @@
import React, { createContext, PropsWithChildren, useCallback, useEffect, useReducer, useRef } from "react";
import { Status, Tabletop } from "visions-types";
import { Client } from "../../client";
import { assertNever } from "../../plugins/Candela";
type AuthState = { type: "NoAdmin" } | { type: "Unauthed" } | { type: "Authed", userid: string };
type AppState = {
auth: AuthState;
tabletop: Tabletop;
}
type Action = { type: "SetAuthState", content: AuthState };
const initialState = (): AppState => (
{
auth: { type: "NoAdmin" },
tabletop: { backgroundColor: { red: 0, green: 0, blue: 0 }, backgroundImage: undefined }
}
);
const stateReducer = (state: AppState, action: Action): AppState => {
return { ...state, auth: action.content }
}
class StateManager {
client: Client | undefined;
dispatch: React.Dispatch<Action> | undefined;
constructor(client: Client | undefined, dispatch: React.Dispatch<any> | undefined) {
this.client = client;
this.dispatch = dispatch;
}
async status() {
if (!this.client || !this.dispatch) return;
const { admin_enabled } = await this.client.status();
if (!admin_enabled) {
this.dispatch({ type: "SetAuthState", content: { type: "NoAdmin" } });
} else {
this.dispatch({ type: "SetAuthState", content: { type: "Unauthed" } });
}
}
async setAdminPassword(password: string) {
if (!this.client || !this.dispatch) return;
await this.client.setAdminPassword(password);
await this.status();
}
}
export const StateContext = createContext<[AppState, StateManager]>([initialState(), new StateManager(undefined, undefined)]);
interface StateProviderProps { client: Client; }
export const StateProvider = ({ client, children }: PropsWithChildren<StateProviderProps>) => {
const [state, dispatch] = useReducer(stateReducer, initialState());
const stateManager = useRef(new StateManager(client, dispatch));
useEffect(() => {
stateManager.current.status();
}, [stateManager]);
return <StateContext.Provider value={[state, stateManager.current]}>
{children}
</StateContext.Provider>;
}

View File

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

View File

@ -1,15 +0,0 @@
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

@ -1,5 +0,0 @@
// 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

@ -1,47 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Game, User } from 'visions-types';
import { Client } from '../../client';
interface UserRowProps {
user: User,
}
const UserRow = ({ user }: UserRowProps) => {
return (<tr>
<td> {user.name} </td>
<td> {user.admin && "admin"} </td>
<td> {user.enabled && "enabled"} </td>
</tr>);
}
interface GameRowProps {
game: Game,
}
const GameRow = ({ game }: GameRowProps) => {
return (<tr>
<td> {game.name} </td>
</tr>);
}
interface AdminProps {
client: Client,
}
export const Admin = ({ client }: AdminProps) => {
const [users, setUsers] = useState<Array<User>>([]);
useEffect(() => {
client.users().then((u) => {
console.log(u);
setUsers(u);
});
}, [client]);
console.log(users);
return (<table>
<tbody>
{users.map((user) => <UserRow user={user} />)}
</tbody>
</table>);
}

View File

@ -1,18 +0,0 @@
@import '../../design.css';
.auth {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
}
.auth__input-line {
display: flex;
justify-content: space-between;
}
.auth__input-line > * {
margin: var(--margin-s);
}

View File

@ -1,51 +0,0 @@
import { PropsWithChildren, useContext, useState } from 'react';
import { StateContext } from '../../providers/StateProvider/StateProvider';
import { assertNever } from '../../plugins/Candela';
import './Authentication.css';
interface AuthenticationProps {
onAdminPassword: (password: string) => void;
onAuth: (username: string, password: string) => void;
}
export const Authentication = ({ onAdminPassword, onAuth, children }: PropsWithChildren<AuthenticationProps>) => {
// No admin password set: prompt for the admin password
// Password set, nobody logged in: prompt for login
// User logged in: show the children
let [userField, setUserField] = useState<string>("");
let [pwField, setPwField] = useState<string>("");
let [state, _] = useContext(StateContext);
switch (state.auth.type) {
case "NoAdmin": {
return <div className="auth">
<div className="card">
<h1> Welcome to your new Visions VTT Instance </h1>
<p> Set your admin password: </p>
<input type="password" placeholder="Password" onChange={(evt) => setPwField(evt.target.value)} />
<input type="submit" value="Submit" onClick={() => onAdminPassword(pwField)} />
</div>
</div>;
}
case "Unauthed": {
return <div className="auth card">
<div className="card">
<h1> Welcome to Visions VTT </h1>
<div className="auth__input-line">
<input type="text" placeholder="Username" onChange={(evt) => setUserField(evt.target.value)} />
<input type="password" placeholder="Password" onChange={(evt) => setPwField(evt.target.value)} />
<input type="submit" value="Sign in" onClick={() => onAuth(userField, pwField)} />
</div>
</div>
</div>;
}
case "Authed": {
return <div> {children} </div>;
}
default: {
assertNever(state.auth);
return <div></div>;
}
}
}

View File

@ -1,4 +0,0 @@
.section {
border: 2px solid black;
border-radius: 4px;
}

View File

@ -1,19 +0,0 @@
import React from 'react';
import { DriveGuage } from '../../plugins/Candela/DriveGuage/DriveGuage';
const DriveGuages = () => {
return (<div className="section">
<div className="drive-guages_on-light">
<DriveGuage current={2} max={4} />
</div>
<div className="drive-guages_on-dark">
<DriveGuage current={2} max={4} />
</div>
</div>);
}
export const DesignPage = () => {
return (<div>
<DriveGuages />
</div>);
}

View File

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

View File

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

View File

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

View File

@ -1,39 +0,0 @@
import React, { useContext, useEffect, useState } from 'react';
import './PlayerView.css';
import { WebsocketContext } from '../../components/WebsocketProvider';
import { Client } from '../../client';
import { TabletopElement } from '../../components/Tabletop/Tabletop';
import Candela from '../../plugins/Candela';
import { StateContext } from '../../providers/StateProvider/StateProvider';
const TEST_CHARSHEET_UUID = "12df9c09-1f2f-4147-8eda-a97bd2a7a803";
interface PlayerViewProps {
client: Client;
}
export const PlayerView = ({ client }: PlayerViewProps) => {
const [state, dispatch] = useContext(StateContext);
const [charsheet, setCharsheet] = useState(undefined);
useEffect(
() => {
client.charsheet(TEST_CHARSHEET_UUID).then((c) => {
setCharsheet(c)
});
},
[client, setCharsheet]
);
const backgroundColor = state.tabletop.backgroundColor;
const tabletopColorStyle = `rgb(${backgroundColor.red}, ${backgroundColor.green}, ${backgroundColor.blue})`;
const backgroundUrl = state.tabletop.backgroundImage ? client.imageUrl(state.tabletop.backgroundImage) : undefined;
return (<div className="player-view" style={{ backgroundColor: tabletopColorStyle }}>
<div className="player-view__middle-panel"> <TabletopElement backgroundColor={backgroundColor} backgroundUrl={backgroundUrl} /> </div>
<div className="player-view__right-panel">
{charsheet ? <Candela.CharsheetPanelElement sheet={charsheet} /> : <div> </div>}</div>
</div>)
}

View File

@ -1,27 +0,0 @@
{
"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"
]
}

View File

@ -0,0 +1,24 @@
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
mode: "development",
entry: {
"main": "./src/main.tsx"
},
module: {
rules: [
{ test: /\.tsx?$/, use: "ts-loader", exclude: /node_modules/ }
]
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: "src/index.html" },
{ from: "src/visions.css" },
]
})
],
resolve: {
extensions: ['.ts', '.tsx'],
}
}

View File

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

View File

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

View File

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

View File

@ -1,14 +0,0 @@
{
"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.7.2"
}
}

View File

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