Skip to content

Commit

Permalink
wip!
Browse files Browse the repository at this point in the history
  • Loading branch information
matze committed Feb 6, 2025
1 parent 9db7ec2 commit 076e1c4
Show file tree
Hide file tree
Showing 18 changed files with 229 additions and 350 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

### Changed

- **Breaking**: From now on, `WASTEBIN_BASE_URL` is only used for the QR code
link but not for internal routing. Use a dedicated proxy server to do that if
necessary.
- Use the [two-face](https://docs.rs/two-face) crate for an extended syntax
list.

Expand Down
45 changes: 22 additions & 23 deletions src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@ use crate::highlight::Theme;
pub struct Asset {
/// Route that this will be served under.
pub route: String,
/// MIME type of this asset determined for the ContentType response header.
/// MIME type of this asset determined for the `ContentType` response header.
mime: mime::Mime,
/// Actual asset content.
content: Vec<u8>,
}

/// Asset kind.
#[derive(Copy, Clone)]
pub enum Kind {
Css,
Js,
}

impl IntoResponse for Asset {
fn into_response(self) -> Response {
let content_type_header = headers::ContentType::from(self.mime);
Expand All @@ -43,11 +50,10 @@ impl Asset {
}
}

pub fn new_hashed(name: &str, mime: mime::Mime, content: Vec<u8>) -> Self {
let ext = match mime.subtype().as_str() {
"css" => "css",
"javascript" => "js",
_ => panic!("unsupported MIME type"),
pub fn new_hashed(name: &str, kind: Kind, content: Vec<u8>) -> Self {
let (mime, ext) = match kind {
Kind::Css => (mime::TEXT_CSS, "css"),
Kind::Js => (mime::TEXT_JAVASCRIPT, "js"),
};

let route = format!(
Expand All @@ -69,10 +75,11 @@ impl Asset {
}
}

/// Collection of light and dark CSS and main UI style CSS derived from them.
pub struct CssAssets {
pub style: Asset,
pub dark: Asset,
pub light: Asset,
pub dark: Asset,
}

trait ColorExt {
Expand All @@ -87,7 +94,7 @@ impl ColorExt for Color {

impl CssAssets {
/// Create CSS assets for `theme`.
pub fn new(theme: &Theme) -> Self {
pub fn new(theme: Theme) -> Self {
#[derive(Template)]
#[template(path = "style.css", escape = "none")]
struct StyleCss {
Expand Down Expand Up @@ -124,15 +131,15 @@ impl CssAssets {

let light = Asset::new_hashed(
"light",
mime::TEXT_CSS,
Kind::Css,
css_for_theme_with_class_style(&light_theme, ClassStyle::Spaced)
.expect("generating CSS")
.into_bytes(),
);

let dark = Asset::new_hashed(
"dark",
mime::TEXT_CSS,
Kind::Css,
css_for_theme_with_class_style(&dark_theme, ClassStyle::Spaced)
.expect("generating CSS")
.into_bytes(),
Expand All @@ -149,15 +156,15 @@ impl CssAssets {

let style = Asset::new_hashed(
"style",
mime::TEXT_CSS,
Kind::Css,
style.render().expect("rendering style css").into_bytes(),
);

Self { style, light, dark }
}
}

fn light_theme(theme: &Theme) -> syntect::highlighting::Theme {
fn light_theme(theme: Theme) -> syntect::highlighting::Theme {
let theme_set = two_face::theme::extra();

match theme {
Expand All @@ -176,7 +183,7 @@ fn light_theme(theme: &Theme) -> syntect::highlighting::Theme {
}
}

fn dark_theme(theme: &Theme) -> syntect::highlighting::Theme {
fn dark_theme(theme: Theme) -> syntect::highlighting::Theme {
let theme_set = two_face::theme::extra();

match theme {
Expand All @@ -199,18 +206,10 @@ mod tests {

#[test]
fn hashed_asset() {
let asset = Asset::new_hashed(
"style",
mime::TEXT_CSS,
String::from("body {}").into_bytes(),
);
let asset = Asset::new_hashed("style", Kind::Css, String::from("body {}").into_bytes());
assert_eq!(asset.route, "/style.62368a1a29259b30.css");

let asset = Asset::new_hashed(
"main",
mime::TEXT_JAVASCRIPT,
String::from("1 + 1").into_bytes(),
);
let asset = Asset::new_hashed("main", Kind::Js, String::from("1 + 1").into_bytes());
assert_eq!(asset.route, "/main.72fce59447a01f48.js");
}
}
50 changes: 0 additions & 50 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::env::VarError;
use std::net::SocketAddr;
use std::num::{NonZero, NonZeroU32, NonZeroUsize, ParseIntError};
use std::path::PathBuf;
use std::sync::LazyLock;
use std::time::Duration;

pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(5);
Expand Down Expand Up @@ -42,55 +41,6 @@ pub enum Error {
UnknownTheme(String),
}

pub struct BasePath(String);

impl BasePath {
pub fn path(&self) -> &str {
&self.0
}

pub fn join(&self, s: &str) -> String {
let b = &self.0;
format!("{b}{s}")
}
}

impl Default for BasePath {
fn default() -> Self {
BasePath("/".to_string())
}
}

// NOTE: This relies on `VAR_BASE_URL` but repeats parsing to handle errors.
pub static BASE_PATH: LazyLock<BasePath> = LazyLock::new(|| {
std::env::var(VAR_BASE_URL).map_or_else(
|err| {
match err {
VarError::NotPresent => (),
VarError::NotUnicode(_) => {
tracing::warn!("`VAR_BASE_URL` not Unicode, defaulting to '/'");
}
};
BasePath::default()
},
|var| match url::Url::parse(&var) {
Ok(url) => {
let path = url.path();

if path.ends_with('/') {
BasePath(path.to_string())
} else {
BasePath(format!("{path}/"))
}
}
Err(err) => {
tracing::error!("error parsing `VAR_BASE_URL`, defaulting to '/': {err}");
BasePath::default()
}
},
)
});

pub fn title() -> String {
std::env::var("WASTEBIN_TITLE").unwrap_or_else(|_| "wastebin".to_string())
}
Expand Down
1 change: 1 addition & 0 deletions src/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use syntect::util::LinesWithEndings;
const HIGHLIGHT_LINE_LENGTH_CUTOFF: usize = 2048;

/// Supported themes.
#[derive(Copy, Clone)]
pub enum Theme {
Ayu,
Base16Ocean,
Expand Down
13 changes: 5 additions & 8 deletions src/javascript/paste.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
const BASE_PATH = document.getElementById('js_base_path').innerHTML;
const BASE_PATH_ID = document.getElementById('js_base_path_id').innerHTML;
const EXT = document.getElementById('js_ext').innerHTML;

document.addEventListener('keydown', onKey);

function onKey(e) {
if (e.key == 'n') {
window.location.href = BASE_PATH;
}
else if (e.key == 'r') {
window.location.href = `${BASE_PATH_ID}?fmt=raw`;
window.location.href = "?fmt=raw";
}
else if (e.key == 'y') {
navigator.clipboard.writeText(window.location.href);
}
else if (e.key == 'd') {
window.location.href = `${BASE_PATH_ID}?dl=${EXT}`;
// FIXME: skips extension
window.location.href = "?dl";
}
else if (e.key == 'q') {
window.location.href = `${BASE_PATH_ID}?fmt=qr`;
window.location.href = "?fmt=qr";
}
else if (e.key == 'p') {
window.location.href = `${BASE_PATH_ID}`;
window.location.href = window.location.href.split("?")[0];
}
else if (e.key == '?') {
var overlay = document.getElementById("overlay");
Expand Down
Loading

0 comments on commit 076e1c4

Please sign in to comment.