1
0
mirror of https://git.ngram.ca/OpenJam/rc-servers synced 2026-08-23 23:08:52 +00:00

add factory web frontend (#77)

### Description

This PR adds a web frontend for factory.
Please let me know if you think the directory names or API endpoints should be changed.
For example, I personally think there are better names than rc_factory_api, and there may be better API names than webui...

### Game

Robocraft

### Please confirm

- [x] I am the legal owner or represent the owner of all work submitted
- [x] I consent to my submission being added to this FOSS project
- [x] This PR used LLMs to generate some or all of the code changes

Reviewed-on: https://git.ngram.ca/OpenJam/rc-servers/pulls/77
Reviewed-by: NGnius <ngniusness@gmail.com>
Co-authored-by: MaxSignal <kastera58@gmail.com>
Co-committed-by: MaxSignal <kastera58@gmail.com>
This commit is contained in:
MaxSignal
2026-01-17 20:00:14 +00:00
committed by NGnius
parent f2896509ba
commit 5fd4acdf62
11 changed files with 589 additions and 4 deletions

View File

@@ -23,7 +23,7 @@ members = [
"rc_singleplayer", "rc_singleplayer_room",
"rc_lobby", "rc_lobby_room",
"rc_core", "rc_database", "rc_factory",
"rc_factory_api" ,"rc_multiplayer",
"rc_factory_web" ,"rc_multiplayer",
"rc_plugins",
]

View File

@@ -0,0 +1,220 @@
(function () {
const $ = (id) => document.getElementById(id);
const TIER_MAX = {
"1": 1000,
"2": 6434,
"3": 79999,
"4": 1299999,
"5": 20000000,
"M": 100000000,
};
const state = {
page: 1,
pageSize: 100,
lastItemCount: 0,
};
const basePayload = {
page: 1,
pageSize: 100,
order: 0,
playerFilter: false,
movementFilter: "100000,200000,300000,400000,500000,600000,700000,800000,900000,1000000,1100000,1200000",
movementCategoryFilter: "100000,200000,300000,400000,500000,600000,700000,800000,900000,1000000,1100000,1200000",
weaponFilter: "10000000,20000000,25000000,30000000,40000000,50000000,60000000,65000000,70100000,75000000",
weaponCategoryFilter: "10000000,20000000,25000000,30000000,40000000,50000000,60000000,65000000,70100000,75000000",
minimumCpu: -1,
maximumCpu: -1,
textFilter: "",
textSearchField: 0, // ALL=0, PLAYER=1, NAME=2
buyable: true,
prependFeaturedRobot: false,
featuredOnly: false,
defaultPage: false
};
function escapeHtml(s) {
return String(s)
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");
}
async function fetchJson(url, opts) {
const r = await fetch(url, opts);
const t = await r.text();
if (!r.ok) throw new Error(`${r.status} ${r.statusText}: ${t}`);
try { return JSON.parse(t); } catch { return t; }
}
function buildPayload() {
const q = ($("q").value || "").trim();
const textSearchField = Number($("searchField").value || "0"); // ALL=0, PLAYER=1, NAME=2
const order = Number($("order").value || "0");
const tier = $("tier").value || ""; // "" or "1".."5" or "M"
const p = { ...basePayload };
p.page = state.page;
p.pageSize = state.pageSize;
p.order = order;
p.textFilter = q;
p.textSearchField = textSearchField;
p.playerFilter = (textSearchField === 1);
if (tier !== "") {
const mx = TIER_MAX[tier] ?? 0;
if (mx > 0) {
p.minimumRobotRanking = 0;
p.maximumRobotRanking = mx;
}
}
return p;
}
function setStatus(msg) {
$("status").textContent = msg || "";
}
function setPagerEnabled() {
const prevDisabled = state.page <= 1;
$("btnPrevTop").disabled = prevDisabled;
$("btnPrevBottom").disabled = prevDisabled;
const nextDisabled = state.lastItemCount < state.pageSize;
$("btnNextTop").disabled = nextDisabled;
$("btnNextBottom").disabled = nextDisabled;
}
function renderList(data) {
const grid = $("grid");
grid.innerHTML = "";
const items = data?.response?.roboShopItems ?? [];
state.lastItemCount = items.length;
setStatus(`page: ${state.page} / items: ${items.length}`);
for (const it of items) {
const id = it.itemId;
const name = it.itemName;
const thumb = it.thumbnail;
const author = it.addedByDisplayName;
const card = document.createElement("div");
card.className = "card";
const img = document.createElement("img");
img.className = "thumb";
img.loading = "lazy";
if (thumb) img.src = thumb;
card.appendChild(img);
const h = document.createElement("div");
h.style.marginTop = "8px";
h.innerHTML = `<strong>${escapeHtml(name)}</strong><div class="muted">id: ${escapeHtml(id ?? "?")}</div>`;
card.appendChild(h);
const p = document.createElement("div");
p.className = "muted";
p.textContent = author ? `by: ${author}` : "";
p.style.marginTop = "6px";
card.appendChild(p);
const btn = document.createElement("button");
btn.className = "btn";
btn.textContent = "About";
btn.addEventListener("click", async () => {
if (id == null) return;
try { await doGet(id); } catch (e) { showDialog(`id: ${id}`, String(e)); }
});
card.appendChild(btn);
grid.appendChild(card);
}
setPagerEnabled();
}
function showDialog(title, body) {
$("dlgTitle").textContent = title || "";
$("detail").textContent = body || "";
const dlg = $("dlg");
if (!dlg.open) dlg.showModal();
}
async function doSearch(resetPage) {
if (resetPage) state.page = 1;
setStatus("loading...");
const payload = buildPayload();
const data = await fetchJson("/api/roboShopItems/list", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
renderList(data);
}
async function doGet(id) {
const data = await fetchJson(`/api/roboShopItems/get/${encodeURIComponent(id)}`, { method: "GET" });
if (typeof data === "string") {
showDialog(`id: ${id}`, data);
return;
}
const resp = data?.response ?? data;
const title =
resp?.name
? `${resp.name} (id: ${resp.id ?? id})`
: `id: ${id}`;
showDialog(title, JSON.stringify(resp, null, 2));
}
$("btnSearch").addEventListener("click", async () => {
try { await doSearch(true); } catch (e) { setStatus(String(e)); }
});
$("btnPrevTop").addEventListener("click", async () => {
if (state.page <= 1) return;
state.page--;
try { await doSearch(false); } catch (e) { setStatus(String(e)); }
});
$("btnPrevBottom").addEventListener("click", async () => {
if (state.page <= 1) return;
state.page--;
try { await doSearch(false); } catch (e) { setStatus(String(e)); }
});
$("btnNextTop").addEventListener("click", async () => {
state.page++;
try { await doSearch(false); } catch (e) { setStatus(String(e)); }
});
$("btnNextBottom").addEventListener("click", async () => {
state.page++;
try { await doSearch(false); } catch (e) { setStatus(String(e)); }
});
$("q").addEventListener("keydown", async (ev) => {
if (ev.key === "Enter") {
ev.preventDefault();
try { await doSearch(true); } catch (e) { setStatus(String(e)); }
}
});
$("dlgClose").addEventListener("click", () => {
$("dlg").close();
});
doSearch(true).catch((e) => setStatus(String(e)));
})();

View File

@@ -0,0 +1,282 @@
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Factory</title>
<link rel="icon" type="image/x-icon" href="/robocraft/favicon">
<style>
:root{
--bg: #1b1b1b;
--top: #3a3a3a;
--panel: #2a2a2a;
--text: #eaeaea;
--muted: #b9b9b9;
--orange: #ff8f2a;
--orange2: #e67600;
--border: #1a1a1a;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
}
.topbar{
width: 100%;
background: var(--top);
border-bottom: 1px solid #2b2b2b;
padding: 12px 8px;
}
.controls{
max-width: none;
width: 100%;
margin: 0;
display: flex;
justify-content: flex-end;
}
.content{
max-width: none;
width: 100%;
margin: 0;
padding: 24px 8px 8px;
}
.stack{
display: grid;
gap: 10px;
min-width: min(720px, 100%);
}
.row{
display: flex;
gap: 10px;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
}
.search{
width: min(420px, 60vw);
padding: 10px 14px;
border-radius: 0;
border: 1px solid #000;
background: linear-gradient(#0f0f0f, #000);
color: var(--text);
outline: none;
font-size: 16px;
}
.search::placeholder{ color: #9a9a9a; }
select{
padding: 9px 34px 9px 12px;
border-radius: 0;
border: 1px solid #000;
background: linear-gradient(#1a1a1a, #000);
color: var(--text);
font-size: 14px;
outline: none;
}
.btn{
padding: 10px 16px;
border-radius: 0;
border: 0;
background: #444;
color: var(--text);
cursor: pointer;
font-weight: 700;
letter-spacing: .02em;
text-transform: uppercase;
}
.btn.primary{ background: var(--orange); }
.btn.primary:hover{ background: var(--orange2); }
.btn:disabled{ opacity: .45; cursor: not-allowed; }
.pager{
display: flex;
justify-content: center;
gap: 6px;
margin: 30px 0;
}
.pager .btn{
width: 110px;
height: 48px;
background: var(--orange);
}
.pager .btn:hover{ background: var(--orange2); }
.pager .btn:disabled{ background: #5a3a1f; opacity: .7; }
.status{
text-align: center;
color: var(--muted);
margin-top: 6px;
font-size: 13px;
min-height: 18px;
}
.grid{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 12px;
margin-top: 16px;
}
.card{
background: var(--panel);
border: 1px solid var(--border);
border-radius: 0;
padding: 10px;
}
.thumb{
width: 100%;
aspect-ratio: 216 / 116;
object-fit: cover;
background: #101010;
border-radius: 0;
display: block;
}
.muted{ color: var(--muted); font-size: 12px; }
.card button{
margin-top: 10px;
width: 100%;
background: #4a4a4a;
border-radius: 0;
text-transform: none;
letter-spacing: 0;
}
.card button:hover{ background: #5a5a5a; }
dialog{
width: min(980px, 92vw);
border: 1px solid #111;
border-radius: 0;
background: #111;
color: var(--text);
padding: 0;
}
dialog::backdrop{ background: rgba(0,0,0,.65); }
.dlg-head{
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px;
border-bottom: 1px solid #222;
background: #141414;
}
.dlg-title{
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 70vw;
}
.dlg-body{ padding: 12px 14px; }
pre{
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
font-size: 12px;
color: #d9d9d9;
}
footer{
margin-top: 8px;
padding: 14px 8px;
border-top: 1px solid #222;
background: #141414;
}
.footer{
text-align: center;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.footer a{
color: var(--text);
text-decoration: none;
}
.footer a:hover{
text-decoration: underline;
}
</style>
</head>
<body>
<div class="topbar">
<div class="controls">
<div class="stack">
<div class="row">
<input id="q" class="search" type="text" placeholder="Search..." />
<select id="searchField">
<option value="0">ALL</option>
<option value="1">PLAYER</option>
<option value="2">NAME</option>
</select>
<button id="btnSearch" class="btn primary">Search</button>
</div>
<div class="row">
<select id="order">
<option value="0">SUGGESTED</option>
<option value="1">COMBAT RATING</option>
<option value="2">COSMETIC RATING</option>
<option value="3">ADDED DATE</option>
<option value="4">MOST BOUGHT</option>
</select>
<select id="tier">
<option value="">ANY TIERS</option>
<option value="1">TIER 1</option>
<option value="2">TIER 2</option>
<option value="3">TIER 3</option>
<option value="4">TIER 4</option>
<option value="5">TIER 5</option>
<option value="M">TIER M</option>
</select>
</div>
</div>
</div>
</div>
<div class="content">
<div class="pager">
<button id="btnPrevTop" class="btn" disabled>PREV</button>
<button id="btnNextTop" class="btn">NEXT</button>
</div>
<div id="status" class="status"></div>
<div id="grid" class="grid"></div>
<div class="pager">
<button id="btnPrevBottom" class="btn" disabled>PREV</button>
<button id="btnNextBottom" class="btn">NEXT</button>
</div>
</div>
<dialog id="dlg">
<div class="dlg-head">
<div id="dlgTitle" class="dlg-title"></div>
<button id="dlgClose" class="btn">Close</button>
</div>
<div class="dlg-body">
<pre id="detail"></pre>
</div>
</dialog>
<script src="/app.js"></script>
<footer>
<div class="footer">
{{version}}
| <a href="{{source_url}}#readme">About</a>
| <a href="https://liberapay.com/NGram">Support Me</a>
</div>
</footer>
</body>
</html>

View File

@@ -1,5 +1,5 @@
[package]
name = "oj_factory_api"
name = "oj_factory_web"
version.workspace = true
edition.workspace = true
repository.workspace = true
@@ -9,12 +9,15 @@ readme.workspace = true
[dependencies]
actix-web.workspace = true
actix-files.workspace = true
clap.workspace = true
log.workspace = true
env_logger.workspace = true
git-version.workspace = true
base64.workspace = true
serde.workspace = true
serde_json.workspace = true
handlebars = { version = "6", features = ["dir_source"] }
libfj.workspace = true
oj_rc_core = { version = "*", path = "../rc_core" }

View File

@@ -4,7 +4,7 @@ mod robocraft;
use actix_web::{App, HttpServer, Responder};
use oj_rc_core::persist::config::{ConfigImpl, ConfigProvider};
#[actix_web::get("/")]
#[actix_web::get("/version")]
async fn index() -> impl Responder {
let name = env!("CARGO_PKG_NAME");
let version = env!("CARGO_PKG_VERSION");
@@ -26,13 +26,33 @@ async fn main() -> std::io::Result<()> {
let conf = ConfigImpl::load(&cli_args.assets).map_err(io_error)?;
let factory_enum = <ConfigImpl as ConfigProvider<()>>::factory(&conf).await.map_err(io_error)?;
let factory_data = actix_web::web::Data::new(factory_enum);
let mut handlebars_conf = handlebars::Handlebars::new();
let mut dir_conf = handlebars::DirectorySourceOptions::default();
dir_conf.tpl_extension = ".html.hbs".to_owned();
dir_conf.hidden = false;
dir_conf.temporary = false;
handlebars_conf
.register_templates_directory(
std::path::PathBuf::from(&cli_args.assets).parent().expect("Bad asset path").join("templates"),
dir_conf,
)
.unwrap();
let handlebars_ref = actix_web::web::Data::new(handlebars_conf);
let assets_root = actix_web::web::Data::new(std::path::PathBuf::from(&cli_args.assets));
HttpServer::new(move || {
App::new()
.app_data(factory_data.clone())
.app_data(assets_root.clone())
.app_data(handlebars_ref.clone())
.service(index)
.service(robocraft::web_ui::index)
.service(robocraft::web_ui::app_js)
.service(robocraft::web_ui::favicon)
.service(robocraft::web_ui::favicon_standard)
.service(robocraft::factory::crf_api::list)
.service(robocraft::factory::crf_api::list_default)
.service(robocraft::factory::crf_api::get)

View File

@@ -1 +1,2 @@
pub mod factory;
pub mod web_ui;

View File

@@ -0,0 +1,59 @@
use actix_web::{get, web::Data, HttpResponse};
use handlebars::Handlebars;
const TEMPLATE_INDEX: &str = "rc_factory_web/index";
const TEMPLATE_APP_JS: &str = "rc_factory_web/app.js";
#[derive(serde::Serialize)]
struct Context {
version: String,
source_url: String,
}
fn version_string() -> String {
let name = env!("CARGO_PKG_NAME");
let version = env!("CARGO_PKG_VERSION");
//let license = env!("CARGO_PKG_LICENSE");
//let repo = env!("CARGO_PKG_REPOSITORY");
format!("OpenJam {} {}", name, version)
}
#[get("/")]
pub async fn index(hb: Data<Handlebars<'_>>) -> HttpResponse {
let ctx = Context {
version: version_string(),
source_url: env!("CARGO_PKG_REPOSITORY").to_string(),
};
match hb.render(TEMPLATE_INDEX, &ctx) {
Ok(body) => HttpResponse::Ok()
.insert_header(("Content-Type", "text/html; charset=utf-8"))
.body(body),
Err(e) => HttpResponse::InternalServerError().body(format!("template render error: {e}")),
}
}
#[get("/app.js")]
pub async fn app_js(hb: Data<Handlebars<'_>>) -> HttpResponse {
match hb.render(TEMPLATE_APP_JS, &()) {
Ok(body) => HttpResponse::Ok()
.insert_header(("Content-Type", "application/javascript; charset=utf-8"))
.body(body),
Err(e) => HttpResponse::InternalServerError().body(format!("template render error: {e}")),
}
}
async fn favicon_impl(assets_root: Data<std::path::PathBuf>) -> impl actix_web::Responder {
let path = assets_root.join("favicon.jpg");
actix_files::NamedFile::open_async(path).await
}
#[get("/robocraft/favicon")]
pub async fn favicon(assets_root: Data<std::path::PathBuf>) -> impl actix_web::Responder {
favicon_impl(assets_root).await
}
#[get("/favicon.ico")]
pub async fn favicon_standard(assets_root: Data<std::path::PathBuf>) -> impl actix_web::Responder {
favicon_impl(assets_root).await
}