Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OpenGraph and Twitter cards dynamically #228

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ serde_json = "1.0"
tokio = { version = "1.37", features = ["full"] }
wait-timeout = "0.2"
url = { version = "2.5", "features" = ["serde"] }
minijinja = { version = "2.0", features = ["builtins"] }
regex = "1.10"

[dev-dependencies]
anyhow = "1.0"
Expand Down
4 changes: 2 additions & 2 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use axum::{
Router,
};

use crate::routes::{compile, create_gist, evaluate, static_css, static_html, static_js};
use crate::routes::{compile, create_gist, evaluate, get_web_html, static_css, static_html, static_js};
use crate::GithubClient;
use std::net::SocketAddr;

Expand All @@ -26,7 +26,7 @@ pub async fn serve(addr: SocketAddr, github_client: GithubClient) -> Result<()>
let router = Router::new()
.route(
"/",
get(|| async { static_html(include_bytes!("../static/web.html")) }),
get(get_web_html),
)
.route("/evaluate.json", post(evaluate))
.route("/compile.json", post(compile))
Expand Down
140 changes: 136 additions & 4 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,142 @@ pub async fn create_gist(
}
}

use serde::{Serialize,Deserialize};
use minijinja::render;
use std::collections::HashMap;

#[derive(Debug, Serialize)]
struct Metadata {
title: String,
description: String,
}

const WEB_HTML_TEMPLATE: &'static str = r#"
<!doctype html>
<html lang="en">

<head>
<title>Pony Playground</title>
<meta charset="utf-8" />
<meta name=viewport id=meta-viewport content="width=720">
<script>if (screen.width > 720) { document.getElementById("meta-viewport").setAttribute('content', 'width=device-width'); }</script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700" />
<link rel="shortcut icon" href="https://avatars1.githubusercontent.com/u/12997238" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.13/ace.js"
integrity="sha512-OMjy8oWtPbx9rJmoprdaQdS2rRovgTetHjiBf7RL7LvRSouoMLks5aIcgqHb6vGEAduuPdBTDCoztxLR+nv45g=="
crossorigin="anonymous" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.13/ext-themelist.min.js"
integrity="sha512-Y7MEa84tKNdub5CgOzVCI7jCitaDVPUUrSQmoACBnhOxMQUtxSqZllJ5HsYJvJFQXLfqcbGMCzwid0xMaI7MCA=="
crossorigin="anonymous" charset="utf-8"></script>

<link rel="stylesheet" href="/static/web.css">
<script src="/static/web.js"></script>
<script src="/static/mode-pony.js"></script>

<meta property="og:type" content="website" />
<meta name="twitter:card" content="app" />
<meta name="twitter:site" content="ponylang" />
<meta name="twitter:creator" content="ponylang" />
{% for (key, value) in metadata %}
<meta property="og:{{ key }}" content="{{ value }}">
<meta name="twitter:{{ key }}" content="{{ value }}">
{% endfor %}
</head>

<body>
<form id="control">
<div><button type="button" class="primary" id="evaluate"
title="Execute your code (you can also press Ctrl+Enter when editing code)">Run</button><button
type="button" id="asm" title="Compile to ASM">ASM</button><button type="button" id="llvm-ir"
title="Compile to LLVM IR">LLVM IR</button></div><wbr>
<div><button type="button" id="gist" title="Share a link to your code via Gist">Share</button></div><wbr>
<div class="right-c-e"><button type="button" id="configure-editor"><span>Configure editor</span></button>
<div class="dropdown">
<p><label for="keyboard">Keyboard bindings:</label>
<select name="keyboard" id="keyboard">
<option>Ace</option>
<option>Emacs</option>
<option>Vim</option>
</select>
<p><label for="themes">Theme:</label>
<select name="themes" id="themes"></select>
</div>
</div>
</form>
<main>
<div id="editor">actor Main
new create(env: Env) =>
env.out.print("Hello, world!")</div>
<div id="result" data-empty>
<div></div><button type="button" id="clear-result" title="Close this pane">×</button>
</div>
</main>
</body>

</html>
</body>
</html>
"#;

#[derive(Deserialize)]
struct URLSearchParams {
snippet: Option<String>,
gist: Option<String>,
code: Option<String>,
run: Option<bool>,
branch: Option<String>,
}

fn extract_docstring(url: String) -> String {
let re = Regex::new(r"^\"\"\"\n(?<docstring>.*?)\n\"\"\"").unwrap();
let Some(caps) = re.captures(resp.text()?) else { return };
let end = &caps["docstring"].chars().map(|c| c.len_utf8()).take(60).sum();
return &caps["docstring"][..end];
}

#[derive(Deserialize)]
struct Gist {
files: HashMap<String, GistFile>,
}

#[derive(Deserialize)]
struct GistFile {
filename: String,
r#type: String,
language: String,
raw_url: String,
size: u128,
truncated: bool,
content: String,
}

async fn get_web_html(urlSearchParams: Query<URLSearchParams>) -> Html<String> {
let metadata_defaults = Metadata {
title: "Pony Playground",
description: "Run ponylang code or compile it to ASM/LLVM IR",
};

if Query.snippet.is_some() {
let snippet_name = Query.snippet.as_ref().unwrap();
let resp = reqwest::blocking::get(concat!("https://raw.githubusercontent.com/ponylang/pony-tutorial/main/code-samples/", snippet_name))?;
if resp.status().is_success() {
metadata_defaults.title = snippet_name
metadata_defaults.description = extract_docstring(resp.text()?);
}
} else if Query.gist.is_some() {
let snippet_name = Query.snippet.as_ref().unwrap();
let resp = reqwest::blocking::get(concat!("https://raw.githubusercontent.com/ponylang/pony-tutorial/main/code-samples/", snippet_name))?;
if description.is_some() {
metadata_defaults.title = snippet_name
let json: Gist = resp.json().unwrap();
metadata_defaults.description = extract_docstring(json.content);
}
}

let r = render!(WEB_HTML_TEMPLATE, metadata => metadata_defaults );
Html(r)
}

// static routes

static APPLICATION_JAVASCRIPT: HeaderValue = HeaderValue::from_static("application/javascript");
Expand All @@ -154,7 +290,3 @@ pub fn static_js(content: &'static [u8]) -> Result<Response<Body>, StatusCode> {
pub fn static_css(content: &'static [u8]) -> Result<Response<Body>, StatusCode> {
static_content(content, TEXT_CSS.clone())
}

pub fn static_html(content: &'static [u8]) -> Result<Response<Body>, StatusCode> {
static_content(content, TEXT_HTML.clone())
}
53 changes: 0 additions & 53 deletions static/web.html

This file was deleted.

Loading