Skip to content

Commit

Permalink
refined the code of indiox
Browse files Browse the repository at this point in the history
  • Loading branch information
mhfan committed Nov 18, 2024
1 parent e915b93 commit f547db9
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 58 deletions.
14 changes: 11 additions & 3 deletions indiox/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ getrandom = { version = "0.2", features = [ "js" ] }
#wasm-logger = "0.2" # WebAssembly Debug

[dependencies]
dioxus = { version = "0.5", features = [ "web" ] } # "router", "desktop", "web"
dioxus = { version = "0.5", features = [ "web" ] } # "web", "fullstack", "router"

#console_error_panic_hook = "0.1"
dioxus-logger = "0.5"
Expand All @@ -34,15 +34,23 @@ rand = "0.8" # git = "https://github.com/mhfan/inrust",
inrust = { path = "..", default-features = false, features = [ "ahash" ] } # "cc", "serde",
instant = { version = "0.1", features = [ "wasm-bindgen" ] }

[features]
default = []
desktop = ["dioxus/desktop"]
server = ["dioxus/axum"]
web = ["dioxus/web"]

[profile.dev]
opt-level = 1

[profile.release]
strip = "debuginfo"
codegen-units = 1
#opt-level = "s"
strip = true # "debuginfo"
opt-level = "z" # "s"
panic = 'abort'
lto = true
#debug = false
#incremental = false

[workspace]

4 changes: 2 additions & 2 deletions indiox/Dioxus.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ default_platform = "web"

[web.app]
title = "24 Puzzle" # HTML title tag content
base_path = "indiox" # "/"
#index_on_404 = true
#base_path = "indiox"

[web.watcher]
reload_html = true # when watcher trigger, regenerate the `index.html`

# which files or dirs will be watcher monitoring
watch_path = [ "src", "assets" ]
watch_path = [ "src", "assets", "index.html", "tailwind_base.css", "tailwind.config.js" ]

[web.resource] # include `assets` in web platform
style = [ "tailwind.css" ] # CSS style file
Expand Down
17 changes: 10 additions & 7 deletions indiox/build.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@

// https://doc.rust-lang.org/stable/cargo/reference/build-scripts.html

fn main() {
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=build.rs"); // XXX: prevent re-run indead
let (twcfg, twcss) = ("tailwind.config.js", "tailwind_base.css");
println!("cargo:rerun-if-changed={twcfg}");
println!("cargo:rerun-if-changed={twcss}");
println!("cargo:rerun-if-changed=src");

//if std::path::Path::new(twcss).exists() { return Ok(()) }
/* npm install -D tailwindcss; npm install tw-elements
sh -c "[ ! -d node_modules ] && npm i; npm run build_css"
npx tailwindcss init # generate a mininum tailwind.config.js
npx tailwindcss -m -i tailwind_base.css -o dist/tailwind.css #-c tailwind.config.js #-w
sh -c "[ ! -d node_modules ] && npm i; npm run build_css"
std::process::Command::new("npx").args(["tailwindcss", "-m", //"-c", twcfg,
"-i", twcss, "-o", "dist/tailwind.css"]).status()?; */

std::process::Command::new("npx").args(&["tailwindcss", "-m", //"-c", twcfg,
"-i", twcss, "-o", "dist/tailwind.css"]).status().unwrap();
*/

std::process::Command::new("npm").args(["run", "build_css"]).status().unwrap();
std::process::Command::new("npm").args(["run", "build_css"]).status()?;
Ok(())
}

8 changes: 4 additions & 4 deletions indiox/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
<html>
<head>
<title>{app_title}</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/{base_path}/"/>
{style_include}{script_include}
<script type="module">
import init from "/{base_path}/assets/dioxus/{app_name}.js";
Expand All @@ -13,8 +14,7 @@
});
</script>
</head>
<body id="main">
<!--div id="main"></div-->
<body id="main"> <!--div id="main"></div-->
</body>
</html>

73 changes: 37 additions & 36 deletions indiox/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,16 @@ fn set_checked(elm: &HtmlElement, checked: bool) {
}

fn main() {
dioxus_logger::init(tracing::Level::INFO).expect("failed to init logger");
//dioxus_logger::init(tracing::Level::INFO).expect("failed to init logger");

//tracing::info!("starting game24");
#[cfg(not(feature = "desktop"))] launch(app);
#[cfg(feature = "desktop")] LaunchBuilder::desktop().with_cfg( // XXX:
dioxus::desktop::Config::new().with_window(
dioxus::desktop::WindowBuilder::new().with_title(env!("CARGO_PKG_NAME")))
.with_custom_head("<link rel='stylesheet' href='dist/tailwind.css'/>".into())
#[cfg(feature = "desktop")] LaunchBuilder::desktop().with_cfg(dioxus::desktop::Config::new()
.with_window(dioxus::desktop::WindowBuilder::new().with_title(env!("CARGO_PKG_NAME")))
//.with_custom_head("<script src='https://cdn.tailwindcss.com'/>".into())
//.with_custom_index(r"<!DOCTYPE html><html>...</html>".into())
.with_custom_head("<link rel='stylesheet' href='tailwind.css'/>".into())
.with_custom_index(include_str!("../index.html").replace(r"{base_path}", ".")
.replace(r"{style_include}{script_include}", "").into())
).launch(app);
}

Expand Down Expand Up @@ -178,20 +178,20 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
//link { rel: "stylesheet",
// href: "https://cdn.jsdelivr.net/npm/tw-elements/dist/css/index.min.css" }

style { dangerous_inner_html: format_args!("{}\n{}", // XXX:
style { dangerous_inner_html: format!("{}\n{}", // XXX:
"html { background-color: #15191D; color: #DCDCDC; }",
"body { font-family: Courier, Monospace; text-align: center; height: 100vh; }")
}

header { class: "text-4xl m-8",
a { href: format_args!("{}", env!("CARGO_PKG_REPOSITORY")), dangerous_inner_html:
format_args!("{}", include_str!("../assets/gh-corner.html")),
a { href: format!("{}", env!("CARGO_PKG_REPOSITORY")), dangerous_inner_html:
format!("{}", include_str!("../assets/gh-corner.html")),
class: "github-corner", "aria-label": "View source on GitHub", }
a { href: "https://github.com/mhfan/inrust", "24 Challenge" }
}

main { class: "mt-auto mb-auto",
div { id: "play-cards", class: "relative", hidden: true,
/* div { id: "play-cards", class: "relative", hidden: true,
img { src: "poker-modern-qr-Maze/2C.svg",
class: "inline-block absolute origin-bottom-left -rotate-[15deg]", }
img { src: "poker-modern-qr-Maze/3D.svg",
Expand All @@ -200,7 +200,7 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
class: "inline-block absolute origin-bottom-left rotate-[5deg]", }
img { src: "poker-modern-qr-Maze/5S.svg",
class: "inline-block absolute origin-bottom-left rotate-[15deg]", }
} // TODO:
} // TODO: */

p { class: "hidden",
"Click on a operator and two numbers to form expression, " br {}
Expand All @@ -210,7 +210,7 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);

fieldset { id: "ops-group", "data-bs-toggle": "tooltip",
title: "Click to (un)check\nDrag over to replace/exchange",
"disabled": format_args!("{}", eqm_state.read().is_some() || !*ovr_state.read()),
"disabled": format!("{}", eqm_state.read().is_some() || !*ovr_state.read()),
// use onclick instead of onchange for capable of de-selection
onclick: move |evt| if let Ok(inp) = evt.web_event().target().unwrap()
.dyn_into::<HtmlInputElement>() { game24.with_mut(|game| {
Expand All @@ -222,19 +222,18 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
});
},

{[ "+", "-", "×", "÷" ].into_iter().map(|op| rsx! {
div { class: "mx-6 my-4 inline-block",
input { r#type: "radio", name: "ops", id: "{op}",
class: "hidden peer", value: "{op}",
} // require value='xxx', default is 'on'

label { "for": "{op}", draggable: "true",
class: "px-4 py-2 bg-indigo-600 text-white text-3xl font-bold \
hover:bg-indigo-400 peer-checked:outline-none peer-checked:ring-2 \
peer-checked:ring-indigo-500 peer-checked:ring-offset-2 \
peer-checked:bg-transparent rounded-md shadow-xl", "{op}" }
}
})}
for op in [ "+", "-", "×", "÷" ] { div {
class: "mx-6 my-4 inline-block",
input { r#type: "radio", name: "ops", id: "{op}",
class: "hidden peer", value: "{op}",
} // require value='xxx', default is 'on'

label { "for": "{op}", draggable: "true",
class: "px-4 py-2 bg-indigo-600 text-white text-3xl font-bold \
hover:bg-indigo-400 peer-checked:outline-none peer-checked:ring-2 \
peer-checked:ring-indigo-500 peer-checked:ring-offset-2 \
peer-checked:bg-transparent rounded-md shadow-xl", "{op}" }
} }
}

div { id: "expr-skel",
Expand All @@ -243,7 +242,7 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
title: "Click to (un)check\nDouble click to input\nDrag over to exchange",
ondoubleclick: num_editable, onchange: num_changed,
onclick: num_checked, onfocusout: num_focusout,
{game24.peek().nums.iter().enumerate().map(|(idx, num)| {
for (idx, num) in game24.peek().nums.iter().enumerate() {
/*let (num, sid) = ((num % 13) + 1, (num / 13)/* % 4 */);
// https://en.wikipedia.org/wiki/Playing_cards_in_Unicode
Expand All @@ -254,12 +253,12 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
10..=13 => court[(num - 10) as usize].to_owned(),
_ => "?".to_owned() }, suits[sid as usize]); //num // TODO: */

rsx! { input { r#type: "text", id: "N{idx}", value: "{num}", name: "nums",
input { r#type: "text", id: "N{idx}", value: "{num}", name: "nums",
maxlength: "6", size: "3", readonly: "true", draggable: "true",
placeholder: "?", "inputmode": "numeric", pattern: r"-?\d+(\/\d+)?",
class: "{num_class} aria-checked:ring-purple-600 aria-checked:ring \
rounded-full mx-2", }} // https://regexr.com, https://regex101.com
})} // https://rustexp.lpil.uk
rounded-full mx-2", } // https://regexr.com, https://regex101.com
} // https://rustexp.lpil.uk
}
} else {
input { r#type: "text", id: "overall", name: "operands",
Expand Down Expand Up @@ -327,8 +326,8 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
},

option { value: "1", "Overall" } // selected: !*ovr_state.read(),
{(4..=6).map(|n| rsx! { option { value: "{n}", selected: format_args!("{}",
/* *ovr_state.read() && */n == game24.peek().nums.len()), "{n} nums" }})}
for n in 4..=6 { option { value: "{n}", selected: format!("{}",
/* *ovr_state.read() && */n == game24.peek().nums.len()), "{n} nums" } }
}

button { class: "{ctrl_class}", onclick: move |_| { if *ovr_state.peek() {
Expand All @@ -351,14 +350,16 @@ fn app() -> Element { //let win = dioxus_desktop::use_window(&cx);
let exps = calc24_coll(&game.goal, &game.nums, DynProg);
let cnt = exps.len();

exps.into_iter().map(|str| rsx! { li { {str.chars().map(|ch|
rsx! { for s in exps { li { { s.chars().map(|ch|
match ch { '*' => '×', '/' => '÷', _ => ch }).collect::<String>()
}}}).chain(std::iter::once_with(move || rsx! { if 5 < cnt {
span { class: "text-white", {format_args!("Got {cnt} solutions")} }
} } }

if 5 < cnt {
span { class: "text-white", {format!("Got {cnt} solutions")} }
} else if cnt < 1 {
span { class: "text-red-500", "Got NO solutions!" }
}}))
})}}
} }
})} }
}
}

Expand Down
17 changes: 11 additions & 6 deletions indiox/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const fs = require('fs');

const fs = require('fs');
function findAllRsExtensions(dir) {
const extensions = [];
const files = fs.readdirSync(dir);
const extensions = [];
files.forEach(file => {
const filePath = `${dir}/${file}`;
const stat = fs.statSync(filePath);
Expand All @@ -15,19 +15,24 @@ function findAllRsExtensions(dir) {
return extensions;
}

/** @type {import('tailwindcss').Config} */
module.exports = {
content: findAllRsExtensions("./src"),
content: ["./src/**/*.{rs,html,css}", "./dist/**/*.html"],
//mode: "all",
theme: {
//extend: {},
container: { center: true, }
//extend: {},
},

plugins: [
//require('@tailwindcss/typography'),
//require('@tailwindcss/forms'),
//require('@tailwindcss/line-clamp'),
//require('tailwindcss-children'),
//require('@tailwindcss/typography'),
//require('@tailwindcss/aspect-ratio'),
//require('@tailwindcss/line-clamp'),
require('tw-elements/dist/plugin')
],
//presets: [ require('@acmecorp/tailwind-base') ],
// https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js
// npm install -D tailwindcss // npx tailwindcss init #--full
}
8 changes: 8 additions & 0 deletions indiox/tailwind_base.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@

/* @config "./tailwind.site.config.js"; */

@tailwind base;
@tailwind components;
@tailwind utilities;

/* .custom-class {
@apply text-center font-bold text-blue-500 p-4;
} */

0 comments on commit f547db9

Please sign in to comment.