Port to TypeScript/Elysia

This commit is contained in:
sepia 2025-07-28 13:39:01 -05:00
parent 29739d243f
commit 513335c485
17 changed files with 413 additions and 2603 deletions

31
.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# build outputs
package-lock.json
dist/
target/
# common artifact extensions
**/*.trace
**/*.zip
**/*.tar.gz
**/*.tgz
**/*.log
**/*.bun

2419
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +0,0 @@
[package]
name = "sepiatones_xyz"
version = "1.0.0"
edition = "2021"
[dependencies]
# webserver framework
rocket = "0.5.1"
rocket_dyn_templates = { version = "0.2.0", features = ["handlebars"] }
# data serialization
serde = { version = "1.0.210", features = ["derive"] }
# HTML parsing
scraper = "0.20.0"
# handling times/dates
chrono = { version = "0.4.38", features = ["serde"] }

BIN
bun.lockb Normal file

Binary file not shown.

View File

@ -1,11 +1,43 @@
<article>
<h2>About</h2>
<p>I program sometimes. I can't decide on a language.</p>
<p>Lately I'm focused on processing e-sports statistics in rust for degenerate betting purposes, and writing games in zig with raylib.</p>
<p>This blog was made with htmx and rust. I will not post the code unless you bother me about it, because I am lazy.</p>
<p><b>bio:</b> mechanist, worldbuilder, hierophant</p>
<h3>Current Interests/Projects</h3>
<ul>
<li>
building <a href="https://civ.plus">civ+</a>, a game, a social experiment,
and living world
</li>
<li>building Pantalaimon, an AI agent system (coming soon)</li>
<li>
finishing up a little
<a href="https://gomoku.sepiatones.xyz">gomoku!</a> webapp
</li>
</ul>
<h3>Dormant Interests/Projects</h3>
<ul>
<li>
esports data analysis, especially for professional League of Legends
</li>
<li>game engine development</li>
<li>programming language design</li>
<li>fiction writing</li>
</ul>
<h3>Favorite Languages/Tools</h3>
<ul>
<li>Rust</li>
<li>TypeScript</li>
<li>Kotlin</li>
<li>Scala</li>
<li>HTMX</li>
</ul>
<h3>Socials</h3>
<ul>
<li><a href="https://x.com/sepiatonal">x</a></li>
<li><a href="https://discord.com/users/105121538805669888">discord</a></li>
</ul>
<br />
<p>
This website was made with htmx and rust. I will not post the code unless
you bother me about it, because I am lazy.
</p>
</article>

View File

@ -1,6 +1,6 @@
<head>
<meta name="title" content="Other Post">
<meta name="date" content="2024-09-24T00:00:00Z">
<meta name="title" content="Other Post" />
<meta name="date" content="2024-09-24T00:00:00Z" />
</head>
<article>
<h1>Welcome to another post!</h1>

View File

@ -1,8 +1,8 @@
@import url('https://fonts.cdnfonts.com/css/jetbrains-mono-2');
@import url("https://fonts.cdnfonts.com/css/jetbrains-mono-2");
:root {
--font-family: "JetBrains Mono", monospace;
--line-height: 1.20rem;
--line-height: 1.2rem;
--border-thickness: 2px;
--text-color: #000;
--text-color-alt: #666;
@ -64,17 +64,26 @@ body {
}
}
h1, h2, h3, h4, h5, h6 {
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: var(--font-weight-bold);
margin: 0 0;
line-height: var(--line-height);
}
h1, h2 {
h1,
h2 {
margin-bottom: var(--line-height);
}
h3, h4, h5, h6 {
h3,
h4,
h5,
h6 {
margin-bottom: 0;
}
@ -89,7 +98,7 @@ h2 {
}
h3 {
font-size: 1.0rem;
font-size: 1rem;
text-transform: uppercase;
}
@ -116,7 +125,8 @@ a {
text-decoration-thickness: var(--border-thickness);
}
a:link, a:visited {
a:link,
a:visited {
color: var(--text-color);
}
@ -138,7 +148,7 @@ sub {
vertical-align: sub;
line-height: 0;
width: calc(1ch / 0.75);
font-size: .75rem;
font-size: 0.75rem;
}
table {
@ -149,13 +159,12 @@ table {
margin: 0 0 calc(var(--line-height) * 2);
}
th, td {
th,
td {
border: var(--border-thickness) solid var(--text-color);
padding:
calc((var(--line-height) / 2))
padding: calc((var(--line-height) / 2))
calc(1ch - var(--border-thickness) / 2)
calc((var(--line-height) / 2) - (var(--border-thickness)))
;
calc((var(--line-height) / 2) - (var(--border-thickness)));
line-height: var(--line-height);
vertical-align: top;
text-align: left;
@ -164,7 +173,6 @@ table tbody tr:first-child > * {
padding-top: calc((var(--line-height) / 2) - var(--border-thickness));
}
th {
font-weight: 700;
}
@ -191,7 +199,8 @@ p {
hyphens: auto;
}
img, video {
img,
video {
display: block;
width: 100%;
object-fit: contain;
@ -218,11 +227,11 @@ details[open] summary {
details ::marker {
display: inline-block;
content: '▶';
content: "▶";
margin: 0;
}
details[open] ::marker {
content: '▼';
content: "▼";
}
details :last-child {
@ -239,7 +248,8 @@ figure pre {
margin: 0;
}
pre, code {
pre,
code {
font-family: var(--font-family);
}
@ -259,7 +269,8 @@ figcaption {
margin-top: var(--line-height);
}
ul, ol {
ul,
ol {
padding: 0;
margin: 0 0 var(--line-height);
}
@ -296,13 +307,14 @@ li::marker {
}
::-webkit-scrollbar {
height: var(--line-height);
height: var(--line-height);
}
input, button, textarea {
input,
button,
textarea {
border: var(--border-thickness) solid var(--text-color);
padding:
calc(var(--line-height) / 2 - var(--border-thickness))
padding: calc(var(--line-height) / 2 - var(--border-thickness))
calc(1ch - var(--border-thickness));
margin: 0;
font: inherit;
@ -318,7 +330,7 @@ input, button, textarea {
-webkit-appearance: none;
}
input[type=checkbox] {
input[type="checkbox"] {
display: inline-grid;
place-content: center;
vertical-align: top;
@ -326,14 +338,15 @@ input[type=checkbox] {
height: var(--line-height);
cursor: pointer;
}
input[type=checkbox]:checked:before {
input[type="checkbox"]:checked:before {
content: "";
width: 1ch;
height: calc(var(--line-height) / 2);
background: var(--text-color);
}
button:focus, input:focus {
button:focus,
input:focus {
--border-thickness: 3px;
outline: none;
}
@ -350,7 +363,7 @@ input {
}
button::-moz-focus-inner {
padding: 0;
border: 0
border: 0;
}
button {
@ -379,7 +392,8 @@ label input {
width: 100%;
}
.tree, .tree ul {
.tree,
.tree ul {
position: relative;
padding-left: 0;
list-style-type: none;
@ -420,28 +434,59 @@ label input {
--grid-cells: 0;
display: flex;
gap: 1ch;
width: calc(round(down, 100%, (1ch * var(--grid-cells)) - (1ch * var(--grid-cells) - 1)));
width: calc(
round(down, 100%, (1ch * var(--grid-cells)) - (1ch * var(--grid-cells) - 1))
);
margin-bottom: var(--line-height);
}
.grid > *,
.grid > input {
flex: 0 0 calc(round(down, (100% - (1ch * (var(--grid-cells) - 1))) / var(--grid-cells), 1ch));
flex: 0 0
calc(
round(
down,
(100% - (1ch * (var(--grid-cells) - 1))) / var(--grid-cells),
1ch
)
);
}
.grid:has(> :last-child:nth-child(1)) {
--grid-cells: 1;
}
.grid:has(> :last-child:nth-child(2)) {
--grid-cells: 2;
}
.grid:has(> :last-child:nth-child(3)) {
--grid-cells: 3;
}
.grid:has(> :last-child:nth-child(4)) {
--grid-cells: 4;
}
.grid:has(> :last-child:nth-child(5)) {
--grid-cells: 5;
}
.grid:has(> :last-child:nth-child(6)) {
--grid-cells: 6;
}
.grid:has(> :last-child:nth-child(7)) {
--grid-cells: 7;
}
.grid:has(> :last-child:nth-child(8)) {
--grid-cells: 8;
}
.grid:has(> :last-child:nth-child(9)) {
--grid-cells: 9;
}
.grid:has(> :last-child:nth-child(1)) { --grid-cells: 1; }
.grid:has(> :last-child:nth-child(2)) { --grid-cells: 2; }
.grid:has(> :last-child:nth-child(3)) { --grid-cells: 3; }
.grid:has(> :last-child:nth-child(4)) { --grid-cells: 4; }
.grid:has(> :last-child:nth-child(5)) { --grid-cells: 5; }
.grid:has(> :last-child:nth-child(6)) { --grid-cells: 6; }
.grid:has(> :last-child:nth-child(7)) { --grid-cells: 7; }
.grid:has(> :last-child:nth-child(8)) { --grid-cells: 8; }
.grid:has(> :last-child:nth-child(9)) { --grid-cells: 9; }
/* DEBUG UTILITIES */
.debug .debug-grid {
--color: color-mix(in srgb, var(--text-color) 10%, var(--background-color) 90%);
--color: color-mix(
in srgb,
var(--text-color) 10%,
var(--background-color) 90%
);
position: absolute;
top: 0;
left: 0;

View File

@ -6,18 +6,18 @@
--background-overlay: #f2e9e1;
}
a {
a:link {
color: #56949f;
text-decoration: underline;
cursor: pointer;
}
a:hover {
color: #286983;
color: #907aa9;
}
a:visited {
color: #907aa9;
color: #286983;
}
::selection {

25
justfile Normal file
View File

@ -0,0 +1,25 @@
install:
bun install
dev:
bun run --watch src/index.tsx
build:
bun build --compile --minify --target bun --outfile ./target/sepiatones_xyz ./src/index.tsx
deploy: build
rsync -avz target/sepiatones_xyz sepiatonesxyz:~/sepiatones_xyz/sepiatones_xyz
rsync -avz --delete public/ sepiatonesxyz:~/sepiatones_xyz/public
test:
bun test
check:
bunx tsc --noEmit --skipLibCheck
clean:
rm -rf node_modules
rm -rf dist
format:
bun run prettier . --write

16
package.json Normal file
View File

@ -0,0 +1,16 @@
{
"name": "sepiatones_xyz",
"version": "2.0.0",
"dependencies": {
"@elysiajs/html": "^1.3.0",
"@elysiajs/static": "^1.3.0",
"cheerio": "^1.1.2",
"elysia": "latest",
"handlebars": "^4.7.8"
},
"devDependencies": {
"bun-types": "latest",
"prettier": "^3.6.2"
},
"module": "src/index.js"
}

53
src/index.tsx Normal file
View File

@ -0,0 +1,53 @@
import { Elysia } from "elysia";
import { html } from "@elysiajs/html";
import { staticPlugin } from "@elysiajs/static";
import path from "path";
import fs from "fs/promises";
import { renderTemplate } from "./util";
import { recentPosts } from "./recent-posts";
const app = new Elysia()
.use(
staticPlugin({
assets: "./data/style",
prefix: "/style",
}),
)
.use(html())
.get("/", async ({ set }) => {
try {
const content = await fs.readFile(
path.join(process.cwd(), "data/pages/about.html"),
"utf8",
);
return renderTemplate("index.html", { content });
} catch (error) {
console.error("Error serving main page: ", error);
set.status = 500;
set.headers["Content-Type"] = "text/plain";
return "Internal server error";
}
})
.get("/posts/:post_name", async ({ params, set }) => {
try {
const filePath = path.join(
process.cwd(),
"data/posts",
`${params.post_name}.html`,
);
const fileContent = await fs.readFile(filePath, "utf8");
return renderTemplate("index.html", { content: fileContent });
} catch (error) {
console.error(`Error serving post ${params.post_name}: `, error);
set.status = 404;
set.headers["Content-Type"] = "text/plain";
return "Post not found.";
}
})
.use(recentPosts);
const port = Number(process.env.PORT || 3000);
app.listen(port, () => {
console.log(`🦊 Elysia is running at ${app.server?.hostname}:${port}`);
});

View File

@ -1,102 +0,0 @@
#[macro_use]
extern crate rocket;
use chrono::{DateTime, Utc};
use rocket::fs::NamedFile;
use rocket_dyn_templates::{context, Template};
use scraper::{Html, Selector};
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
#[get("/")]
fn serve_main() -> Template {
Template::render(
"index",
context! {
content: std::fs::read_to_string("data/pages/about.html").unwrap_or_else(|_| "Error loading about page.".to_string())
},
)
}
#[get("/posts/<post_name>")]
async fn serve_post(post_name: &str) -> Template {
let file_path = Path::new("data/posts").join(format!("{}.html", post_name));
let file_maybe = std::fs::read_to_string(file_path);
let file = match file_maybe.ok() {
Some(s) => s,
None => "404: File not found.".to_string(),
};
Template::render(
"index",
context! {
content: file
},
)
}
#[get("/style/<file>")]
async fn serve_css(file: &str) -> Option<NamedFile> {
let file_path = Path::new("data/style").join(format!("{}", file));
NamedFile::open(file_path).await.ok()
}
#[get("/recent_posts")]
fn list_recent_posts() -> Template {
#[derive(Serialize)]
struct Post {
title: String,
path: String,
date: String,
date_utc: DateTime<Utc>,
}
let posts_dir = Path::new("data/posts");
let mut posts = Vec::new();
if let Ok(entries) = std::fs::read_dir(posts_dir) {
for entry in entries {
if let Ok(entry) = entry {
if let Some(file_name) = entry.file_name().to_str() {
if file_name.ends_with(".html") {
let file = match std::fs::read_to_string(posts_dir.join(file_name)) {
Ok(s) => s,
Err(_) => continue,
};
let document = Html::parse_document(file.as_str());
let mut tags: HashMap<&str, &str> = HashMap::new();
for meta_tag in document.select(&Selector::parse("meta").unwrap()) {
let name = meta_tag.value().attr("name").unwrap_or("");
let content = meta_tag.value().attr("content").unwrap_or("");
tags.insert(name, content);
}
let title = tags.get("title").unwrap_or(&"Untitled Post").to_string();
let date_utc = tags
.get("date")
.and_then(|s_date| DateTime::parse_from_rfc3339(s_date).ok())
.map(|dt| dt.with_timezone(&Utc))
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap());
let date = date_utc.format("%d-%m-%Y").to_string();
posts.push(Post {
title,
date_utc,
date,
path: format!("/posts/{}", file_name.trim_end_matches(".html")),
});
}
}
}
}
}
posts.sort_by_key(|post| std::cmp::Reverse(post.date_utc));
Template::render("posts_list", context! { posts: posts })
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![serve_post, serve_main, serve_css, list_recent_posts])
.attach(Template::fairing())
}

92
src/recent-posts.tsx Normal file
View File

@ -0,0 +1,92 @@
import { Elysia } from "elysia";
import * as cheerio from "cheerio";
import path from "path";
import fs from "fs/promises";
import { renderTemplate } from "./util";
interface Post {
title: string;
path: string;
date: string;
date_utc: Date;
}
export const recentPosts = (app: Elysia) =>
app.get("/recent_posts", async ({ set }) => {
const postsDir = path.join(process.cwd(), "data/posts");
const posts: Post[] = [];
try {
const entries = await fs.readdir(postsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".html")) {
const filePath = path.join(postsDir, entry.name);
try {
const fileContent = await fs.readFile(filePath, "utf8");
const $ = cheerio.load(fileContent);
// Get a map of the post's metadata tags
const tags: { [key: string]: string } = {};
$("meta").each((_i, el) => {
const name = $(el).attr("name");
const content = $(el).attr("content");
if (name && content) {
tags[name] = content;
}
});
const title = tags["title"] || "Untitled Post";
const dateStr = tags["date"];
let date_utc: Date;
if (dateStr) {
try {
date_utc = new Date(dateStr);
if (isNaN(date_utc.getTime())) {
// Check for invalid date
date_utc = new Date(0); // Epoch start if invalid
}
} catch (e) {
console.warn(
`Could not parse date ${dateStr} for ${entry.name}, using epoch.`,
e,
);
date_utc = new Date(0); // Epoch start if parsing fails
}
} else {
date_utc = new Date(0); // Epoch start if no date provided
}
// dd-mm-yyyy
const date = date_utc.toLocaleDateString("en-GB", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
posts.push({
title,
date_utc,
date,
path: `/posts/${entry.name.replace(".html", "")}`,
});
} catch (readError) {
console.error(
`Error reading or processing file ${entry.name}:`,
readError,
);
continue;
}
}
}
posts.sort((a, b) => b.date_utc.getTime() - a.date_utc.getTime()); // Sort by date_utc descending
return renderTemplate("posts_list.html", { posts });
} catch (error) {
console.error("Error listing recent posts: ", error);
set.status = 500;
set.headers["Content-Type"] = "text/plain";
return "Internal Server Error";
}
});

22
src/util.tsx Normal file
View File

@ -0,0 +1,22 @@
import Handlebars from "handlebars";
import path from "path";
import fs from "fs/promises";
export async function renderTemplate(
templateName: string,
context: Record<string, any>,
) {
try {
const templatePath = path.join(
process.cwd(),
"templates",
`${templateName}.hbs`,
);
const templateContent = await fs.readFile(templatePath, "utf8");
const template = Handlebars.compile(templateContent);
return template(context);
} catch (error) {
console.error(`Error rendering template ${templateName}:`, error);
return `Error rendering template ${templateName}`;
}
}

View File

@ -1,20 +1,32 @@
<html>
<head>
<script src="https://unpkg.com/htmx.org@2.0.3" integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/style/monospace.css">
<link rel="stylesheet" href="/style/style.css">
</head>
<body style="max-width: 120ch; margin: auto;">
<header style="display: flex; justify-content: space-between; width: 100%;">
<h1>sepiatones.xyz</h1>
<nav>
<a href="/">about</a>
<a hx-get="/recent_posts" hx-target="#sidebar">posts</a>
</nav>
</header>
<main id="primary" style="display: flex; justify-content: space-between;">
<head>
<script
src="https://unpkg.com/htmx.org@2.0.3"
integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq"
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="/style/monospace.css" />
<link rel="stylesheet" href="/style/style.css" />
</head>
<body style="max-width: 120ch; margin: auto;">
<header style="display: flex; justify-content: space-between; width: 100%;">
<h1>sepiatones.xyz</h1>
<nav>
<a href="/">about</a>
<a href="https://git.sepiatones.xyz/sepia">code</a>
<a
hx-get="/recent_posts"
hx-target="#sidebar"
hx-trigger="click,load"
>posts</a>
</nav>
</header>
<main id="primary" style="display: flex; justify-content: space-between;">
{{{content}}}
<aside id="sidebar" style="width: 60ch; padding: var(--line-height) 1ch;"></aside>
<aside
id="sidebar"
style="width: 60ch; padding: var(--line-height) 1ch;"
></aside>
</main>
</body>
</html>
</body>
</html>

View File

@ -1,9 +1,12 @@
<h2 style="display: flex; justify-content: space-between; align-items: center;">
Posts
<span style="cursor: pointer;" hx-on:click="document.getElementById('sidebar').innerHTML = ''">X</span>
<span
style="cursor: pointer;"
hx-on:click="document.getElementById('sidebar').innerHTML = ''"
>X</span>
</h2>
<ul>
{{#each posts}}
<li><a href="{{path}}">{{title}} - {{date}}</a></li>
{{/each}}
</ul>
</ul>

15
tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"module": "ES2022",
"moduleResolution": "node",
"skipLibCheck": true,
"strict": true,
"target": "ES2021",
"types": ["bun-types"],
"jsx": "react",
"jsxFactory": "Html.createElement",
"jsxFragmentFactory": "Html.Fragment"
}
}