Skip to content

Commit

Permalink
Create readme app
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoburns committed Nov 5, 2024
1 parent 928155b commit d607720
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 54 deletions.
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ members = [
"packages/blitz-net",
"packages/blitz-renderer-vello",
"packages/dioxus-native",
"apps/wpt"]
"apps/wpt",
"apps/readme",
]
resolver = "2"

[workspace.package]
Expand Down Expand Up @@ -106,7 +108,6 @@ blitz-net = { path = "./packages/blitz-net" }
blitz-traits = { path = "./packages/blitz-traits" }
blitz-renderer-vello = { path = "./packages/blitz-renderer-vello" }
dioxus-native = { path = "./packages/dioxus-native", features = ["tracing"] }
comrak = { git = "https://github.com/kivikakk/comrak", rev = "96a64d1befcaa8715098bf617e836c2ef70cb692", default-features = false, features = ["syntect"] }
png = { version = "0.17" }
dioxus = { workspace = true }
euclid = { version = "0.22", features = ["serde"] }
Expand Down
16 changes: 16 additions & 0 deletions apps/readme/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "readme"
version = "0.1.0"
edition = "2021"
license.workspace = true

[dependencies]
blitz-dom = { path = "../../packages/blitz-dom" }
blitz-net = { path = "../../packages/blitz-net" }
blitz-traits = { path = "../../packages/blitz-traits" }
blitz-renderer-vello = { path = "../../packages/blitz-renderer-vello" }
dioxus-native = { path = "../../packages/dioxus-native", features = ["tracing"] }
tokio = { workspace = true }
reqwest = { workspace = true }
url = { workspace = true }
comrak = { git = "https://github.com/kivikakk/comrak", rev = "96a64d1befcaa8715098bf617e836c2ef70cb692", default-features = false, features = ["syntect"] }
File renamed without changes.
118 changes: 118 additions & 0 deletions apps/readme/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
mod markdown;
use blitz_dom::net::Resource;
use blitz_dom::HtmlDocument;
use blitz_net::Provider;
use blitz_traits::net::SharedCallback;
use markdown::{markdown_to_html, MARKDOWN_STYLESHEET};
use reqwest::header::HeaderName;

use dioxus_native::Callback;
use std::env::current_dir;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::runtime::Handle;
use url::Url;

const USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/81.0";
fn main() {
let raw_url = std::env::args().nth(1);

// Turn on the runtime and enter it
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();

let _guard = rt.enter();

let (base_url, contents, is_md) = rt.block_on(fetch(raw_url));

// Process markdown if necessary
let mut html = contents;
let mut stylesheets = Vec::new();
if is_md {
html = markdown_to_html(html);
stylesheets.push(String::from(MARKDOWN_STYLESHEET));
}

println!("{html}");

let net_callback = Arc::new(Callback::new());
let net_provider = Arc::new(Provider::new(
Handle::current(),
Arc::clone(&net_callback) as SharedCallback<Resource>,
));

let document = HtmlDocument::from_html(&html, Some(base_url), stylesheets, net_provider);
dioxus_native::launch_with_document(document, rt, Some(net_callback));
}

async fn fetch(raw_url: Option<String>) -> (String, String, bool) {
match raw_url {
None => {
let cwd = current_dir().ok();
let mut maybe_dir = cwd.as_deref();
while let Some(dir) = maybe_dir {
let path = dir.join("README.md");
if fs::exists(&path).unwrap() {
let base_url = format!("file://{}/", dir.display());
let contents = std::fs::read_to_string(&path).unwrap();
return (base_url, contents, true);
}

maybe_dir = dir.parent()
}

eprintln!("Could not find README.md file in the current directory");
std::process::exit(1);
}
Some(raw_url) => {
if let Ok(url) = Url::parse(&raw_url) {
match url.scheme() {
"file" => {
let raw_file_content = std::fs::read(url.path()).unwrap();
let file_content = String::from_utf8(raw_file_content).unwrap();
let base_url = PathBuf::from(&raw_url)
.parent()
.unwrap()
.to_string_lossy()
.to_string();
let is_md = raw_url.ends_with(".md");
(base_url, file_content, is_md)
}
_ => {
let client = reqwest::Client::new();
let response = client
.get(url)
.header("User-Agent", USER_AGENT)
.send()
.await
.unwrap();
let content_type = response
.headers()
.get(HeaderName::from_static("content-type"));
let is_md = raw_url.ends_with(".md")
|| content_type.is_some_and(|ct| {
ct.to_str().is_ok_and(|ct| ct.starts_with("text/markdown"))
});
let file_content = response.text().await.unwrap();

(raw_url, file_content, is_md)
}
}
} else if fs::exists(&raw_url).unwrap() {
let base_path = std::path::absolute(Path::new(&raw_url)).unwrap();
let base_path = base_path.parent().unwrap().to_string_lossy();
let base_url = format!("file://{}/", base_path);
let contents = std::fs::read_to_string(&raw_url).unwrap();
let is_md = raw_url.ends_with(".md");

(base_url, contents, is_md)
} else {
eprintln!("Cannot parse {} as url or find it as a file", raw_url);
std::process::exit(1);
}
}
}
}
36 changes: 5 additions & 31 deletions examples/markdown.rs → apps/readme/src/markdown.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,20 @@
//! Render the readme.md using the gpu renderer

use std::{collections::HashMap, path::Path};
use std::collections::HashMap;

use comrak::{
adapters::SyntaxHighlighterAdapter, markdown_to_html_with_plugins,
plugins::syntect::SyntectAdapter, ExtensionOptionsBuilder, Options, Plugins,
RenderOptionsBuilder,
};
use dioxus_native::Config;

fn main() {
let (base_url, contents) = std::env::args()
.skip(1)
.next()
.map(|path| {
let base_path = std::path::absolute(Path::new(&path)).unwrap();
let base_path = base_path.parent().unwrap().to_string_lossy();
let base_url = format!("file://{}/", base_path);
let contents = std::fs::read_to_string(path).unwrap();
(base_url, contents)
})
.unwrap_or({
let base_url = "https://raw.githubusercontent.com/DioxusLabs/blitz/main/".to_string();
let contents = include_str!("../README.md").to_string();
(base_url, contents)
});
pub(crate) const MARKDOWN_STYLESHEET: &str = include_str!("../assets/github-markdown-light.css");

pub(crate) fn markdown_to_html(contents: String) -> String {
let plugins = Plugins::default();
// let syntax_highligher = CustomSyntectAdapter(SyntectAdapter::new(Some("InspiredGitHub")));
// plugins.render.codefence_syntax_highlighter = Some(&syntax_highligher as _);

let stylesheet = include_str!("./assets/github-markdown-light.css");
let body_html = markdown_to_html_with_plugins(
&contents,
&Options {
Expand Down Expand Up @@ -58,7 +42,7 @@ fn main() {
&plugins,
);

let html = format!(
format!(
r#"
<!DOCTYPE html>
<html>
Expand All @@ -68,17 +52,7 @@ fn main() {
</html>
"#,
body_html
);

println!("{html}");

dioxus_native::launch_static_html_cfg(
&html,
Config {
stylesheets: vec![String::from(stylesheet)],
base_url: Some(base_url),
},
);
)
}

#[allow(unused)]
Expand Down
18 changes: 0 additions & 18 deletions examples/html.rs

This file was deleted.

17 changes: 14 additions & 3 deletions packages/dioxus-native/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,11 @@ pub fn launch_static_html_cfg(html: &str, cfg: Config) {
launch_with_document(document, rt, Some(net_callback));
}

fn launch_with_document(doc: impl DocumentLike, rt: Runtime, net_callback: Option<Arc<Callback>>) {
pub fn launch_with_document(
doc: impl DocumentLike,
rt: Runtime,
net_callback: Option<Arc<Callback>>,
) {
let mut window_attrs = Window::default_attributes();
if !cfg!(all(target_os = "android", target_os = "ios")) {
window_attrs.inner_size = Some(
Expand Down Expand Up @@ -207,8 +211,8 @@ enum CallbackInner {
Queue(Vec<Resource>),
}
impl Callback {
fn new() -> Self {
Self(Mutex::new(CallbackInner::Queue(Vec::new())))
pub fn new() -> Self {
Default::default()
}
fn init(self: Arc<Self>, window_id: WindowId, proxy: &EventLoopProxy<BlitzEvent>) {
let old = std::mem::replace(
Expand All @@ -231,6 +235,13 @@ impl Callback {
.unwrap()
}
}

impl Default for Callback {
fn default() -> Self {
Self(Mutex::new(CallbackInner::Queue(Vec::new())))
}
}

impl blitz_traits::net::Callback for Callback {
type Data = Resource;
fn call(&self, data: Self::Data) {
Expand Down

0 comments on commit d607720

Please sign in to comment.