Skip to content

Commit

Permalink
run lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Pistonight committed Feb 22, 2024
1 parent 38ed1e8 commit 1b36f81
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 77 deletions.
4 changes: 2 additions & 2 deletions compiler-base/src/util/escape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ macro_rules! escape_impl {
/// - `"` becomes `"`
/// - `'` becomes `'`
pub fn xml_escape(s: &str) -> Cow<str> {
escape_impl!{
escape_impl! {
s,
b'&' => b"&amp;",
b'<' => b"&lt;",
Expand All @@ -63,7 +63,7 @@ pub fn xml_escape(s: &str) -> Cow<str> {
/// - `"` becomes `&quot;`
/// - `'` becomes `&#39;`
pub fn html_attr_escape(s: &str) -> Cow<str> {
escape_impl!{
escape_impl! {
s,
b'&' => b"&amp;",
b'<' => b"&lt;",
Expand Down
7 changes: 5 additions & 2 deletions server/src/api/compile.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! The `/compile` API endpoint.

use axum::{Json, Router};
use axum::extract::Path;
use axum::routing;
use axum::{Json, Router};
use instant::Instant;
use serde::{Deserialize, Serialize};
use serde_json::Value;
Expand All @@ -13,7 +13,10 @@ use crate::compiler;

pub fn init_api() -> Router {
Router::new()
.route("/:owner/:repo/:reference", routing::get(compile_owner_repo_ref))
.route(
"/:owner/:repo/:reference",
routing::get(compile_owner_repo_ref),
)
.route(
"/:owner/:repo/:reference/*path",
routing::get(compile_owner_repo_ref_path),
Expand Down
103 changes: 61 additions & 42 deletions server/src/api/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ use std::fs;
use std::io;
use std::sync::OnceLock;

use axum::extract::Path;
use axum::http::header;
use axum::http::HeaderValue;
use axum::http::StatusCode;
use axum::http::{HeaderValue, StatusCode};
use axum::routing;
use axum::extract::Path;
use axum::Router;
use cached::proc_macro::cached;
use celerc::env;
use celerc::util;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::set_header::SetResponseHeaderLayer;
use tracing::error;

use celerc::env;
use celerc::util;

use crate::compiler;

pub fn init_api(app_dir: &str) -> Result<Router, io::Error> {
Expand All @@ -26,17 +26,21 @@ pub fn init_api(app_dir: &str) -> Result<Router, io::Error> {
let router = Router::new()
.route("/:owner/:repo", routing::get(view_owner_repo))
.route("/:owner/:repo/*path", routing::get(view_owner_repo_path))
.layer(ServiceBuilder::new()
.layer(CompressionLayer::new())
.layer(SetResponseHeaderLayer::overriding(
header::CONTENT_TYPE, HeaderValue::from_static("text/html;charset=utf-8")
))
.layer(SetResponseHeaderLayer::overriding(
header::CACHE_CONTROL, HeaderValue::from_static("public,max-age=600")
))
.layer(SetResponseHeaderLayer::overriding(
header::EXPIRES, HeaderValue::from_static("600")
))
.layer(
ServiceBuilder::new()
.layer(CompressionLayer::new())
.layer(SetResponseHeaderLayer::overriding(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html;charset=utf-8"),
))
.layer(SetResponseHeaderLayer::overriding(
header::CACHE_CONTROL,
HeaderValue::from_static("public,max-age=600"),
))
.layer(SetResponseHeaderLayer::overriding(
header::EXPIRES,
HeaderValue::from_static("600"),
)),
);

Ok(router)
Expand Down Expand Up @@ -67,7 +71,9 @@ fn get_tail() -> Result<&'static str, StatusCode> {
}

fn init_view_html(app_dir: &str) -> Result<(), io::Error> {
let view_path = std::path::Path::new(app_dir).join("view.html").canonicalize()?;
let view_path = std::path::Path::new(app_dir)
.join("view.html")
.canonicalize()?;
let view_html = fs::read_to_string(view_path)?;

let mut split = view_html.split(SERVER_INJECTED_TAGS);
Expand All @@ -76,19 +82,28 @@ fn init_view_html(app_dir: &str) -> Result<(), io::Error> {
VIEW_HTML_HEAD.get_or_init(|| head.to_string());
}
None => {
return Err(io::Error::new(io::ErrorKind::InvalidData, "view.html missing head".to_string()));
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"view.html missing head".to_string(),
));
}
};
match split.next() {
Some(tail) => {
VIEW_HTML_TAIL.get_or_init(|| tail.to_string());
}
None => {
return Err(io::Error::new(io::ErrorKind::InvalidData, "view.html missing tail".to_string()));
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"view.html missing tail".to_string(),
));
}
};
if split.next().is_some() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "view.html has multiple inject tags".to_string()));
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"view.html has multiple inject tags".to_string(),
));
}

Ok(())
Expand All @@ -103,10 +118,7 @@ async fn view_owner_repo(
Some(repo) => repo,
None => return view_fallback(),
};
let reference = match repo_parts.next() {
Some(reference) => reference,
None => "main",
};
let reference = repo_parts.next().unwrap_or("main");
view_internal(&owner, repo, reference, "").await
}

Expand All @@ -115,25 +127,24 @@ async fn view_owner_repo_path(
) -> Result<String, StatusCode> {
// try to separate path:reference:remaining
let mut path_parts = path.splitn(3, ':');
let path = match path_parts.next() {
Some(path) => path,
None => "",
};
let reference = match path_parts.next() {
Some(reference) => reference,
None => "main",
};
let path = path_parts.next().unwrap_or("");
let reference = path_parts.next().unwrap_or("main");
view_internal(&owner, &repo, reference, path).await
}

#[cached(
size=128,
time=600,
key= "String",
convert=r#"{ format!("{owner}/{repo}/{reference}/{path}") }"#,
size = 128,
time = 600,
key = "String",
convert = r#"{ format!("{owner}/{repo}/{reference}/{path}") }"#,
result = true
)]
async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) -> Result<String, StatusCode> {
async fn view_internal(
owner: &str,
repo: &str,
reference: &str,
path: &str,
) -> Result<String, StatusCode> {
let mut builder = compiler::new_context_builder(owner, repo, Some(reference));
if !path.is_empty() {
builder = builder.entry_point(Some(path.to_string()));
Expand All @@ -143,7 +154,7 @@ async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) ->
Err(e) => {
error!("Error getting metadata for project {owner}/{repo}/{reference}/{path}: {e}");
return view_fallback();
},
}
Ok(metadata) => metadata,
};
let title = &metadata.title;
Expand Down Expand Up @@ -183,9 +194,18 @@ async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) ->
}
url
};
let title_tag = format!("<meta name=\"og:title\" content=\"{}\">", util::html_attr_escape(&title));
let description_tag = format!("<meta name=\"og:description\" content=\"{}\">", util::html_attr_escape(&description));
let url_tag = format!("<meta name=\"og:url\" content=\"{}\">", util::html_attr_escape(&view_url));
let title_tag = format!(
"<meta name=\"og:title\" content=\"{}\">",
util::html_attr_escape(&title)
);
let description_tag = format!(
"<meta name=\"og:description\" content=\"{}\">",
util::html_attr_escape(&description)
);
let url_tag = format!(
"<meta name=\"og:url\" content=\"{}\">",
util::html_attr_escape(&view_url)
);

let head = get_head()?;
let tail = get_tail()?;
Expand All @@ -199,7 +219,6 @@ async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) ->
);

Ok(html)

}

fn view_fallback() -> Result<String, StatusCode> {
Expand Down
59 changes: 39 additions & 20 deletions web-client/src/core/doc/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import type { ExpoContext } from "low/celerc";
import { fetchAsJson, getApiUrl } from "low/fetch";
import { console, wrapAsync } from "low/utils";

export type LoadDocumentResult = {
type: "success";
data: ExpoContext;
} | {
type: "failure";
data: string;
help?: string;
}
export type LoadDocumentResult =
| {
type: "success";
data: ExpoContext;
}
| {
type: "failure";
data: string;
help?: string;
};

const HELP_URL = "/docs/route/publish#viewing-the-route-on-celer";

Expand All @@ -21,20 +23,29 @@ const HELP_URL = "/docs/route/publish#viewing-the-route-on-celer";
export async function loadDocumentFromCurrentUrl(): Promise<LoadDocumentResult> {
const pathname = window.location.pathname;
if (!pathname.startsWith("/view")) {
return createLoadError("Invalid document URL. Please double check you have the correct URL.", HELP_URL);
return createLoadError(
"Invalid document URL. Please double check you have the correct URL.",
HELP_URL,
);
}
const parts = pathname.substring(6).split("/").filter(Boolean);
// parts[0] is owner
// parts[1] is repo
// parts[2:] is path
// last is path:reference
if (parts.length < 2) {
return createLoadError("Invalid document reference. Please double check you have the correct URL.", HELP_URL);
return createLoadError(
"Invalid document reference. Please double check you have the correct URL.",
HELP_URL,
);
}

const [owner, repo, ...rest] = parts;
if (!owner || !repo) {
return createLoadError("Invalid document reference. Please double check you have the correct URL.", HELP_URL);
return createLoadError(
"Invalid document reference. Please double check you have the correct URL.",
HELP_URL,
);
}
let reference = "main";
let realRepo = repo;
Expand All @@ -56,29 +67,37 @@ export async function loadDocumentFromCurrentUrl(): Promise<LoadDocumentResult>
return await loadDocument(owner, realRepo, reference, path);
}

function createLoadError(message: string, help: string | undefined): LoadDocumentResult {
function createLoadError(
message: string,
help: string | undefined,
): LoadDocumentResult {
return {
type: "failure",
data: message,
help
help,
};
}

export async function loadDocument(
owner: string,
repo: string,
reference: string,
path: string | undefined
owner: string,
repo: string,
reference: string,
path: string | undefined,
): Promise<LoadDocumentResult> {
console.info(`loading document: ${owner}/${repo}/${reference} ${path}`);
const startTime = performance.now();
let url = `/compile/${owner}/${repo}/${reference}`;
if (path) {
url += `/${path}`;
}
const result = await wrapAsync(async () => fetchAsJson<LoadDocumentResult>(getApiUrl(url)));
const result = await wrapAsync(async () =>
fetchAsJson<LoadDocumentResult>(getApiUrl(url)),
);
if (result.isErr()) {
return createLoadError("There was an error loading the document from the server.", undefined);
return createLoadError(
"There was an error loading the document from the server.",
undefined,
);
}
const response = result.inner();
const elapsed = Math.round(performance.now() - startTime);
Expand All @@ -90,7 +109,7 @@ export async function loadDocument(
response.help = HELP_URL;
}
}

return result.inner();
}

Expand Down
7 changes: 4 additions & 3 deletions web-client/src/core/kernel/Kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ export class Kernel implements KernelAccess {
const compiler = await this.getCompiler();
compiler.compile();
return;
}
}
await this.reloadDocumentFromServer();
}

Expand Down Expand Up @@ -398,13 +398,14 @@ export class Kernel implements KernelAccess {
if (!retry) {
await this.alertMgr.show({
title: "Load cancelled",
message: "You can retry at any time by refreshing the page, or by clicking \"Reload Document\" from the toolbar.",
message:
'You can retry at any time by refreshing the page, or by clicking "Reload Document" from the toolbar.',
okButton: "Got it",
cancelButton: "",
});
break;
}
this.log.warn("retrying in 1s...")
this.log.warn("retrying in 1s...");
await sleep(1000);
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion web-client/src/low/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const fetchAsJson = <T>(url: string): Promise<T> => {
return doFetch(url, (response) => {
return response.json();
});
}
};

const API_PREFIX = "/api/v1";
export const getApiUrl = (path: string) => {
Expand Down
8 changes: 6 additions & 2 deletions web-client/src/ui/toolbar/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,16 @@ export const Header: React.FC<HeaderProps> = ({ toolbarAnchor }) => {
);
};

function useTitle(stageMode: string, document: ExecDoc | undefined, compileInProgress: boolean) {
function useTitle(
stageMode: string,
document: ExecDoc | undefined,
compileInProgress: boolean,
) {
if (document) {
// if document is loaded, return the document title
return document?.project.title;
}
if (stageMode ==="edit"){
if (stageMode === "edit") {
// if in edit mode, return the editor title
return "Celer Editor";
}
Expand Down
Loading

0 comments on commit 1b36f81

Please sign in to comment.