From 1b36f81586613b8728c9698b097dab38d4f2768a Mon Sep 17 00:00:00 2001 From: Pistonight Date: Wed, 21 Feb 2024 19:39:41 -0800 Subject: [PATCH] run lint --- compiler-base/src/util/escape.rs | 4 +- server/src/api/compile.rs | 7 +- server/src/api/view.rs | 103 +++++++++++------- web-client/src/core/doc/loader.ts | 59 ++++++---- web-client/src/core/kernel/Kernel.ts | 7 +- web-client/src/low/fetch.ts | 2 +- web-client/src/ui/toolbar/Header.tsx | 8 +- web-client/src/ui/toolbar/ReloadDocument.tsx | 8 +- .../src/ui/toolbar/getHeaderControls.ts | 6 +- 9 files changed, 127 insertions(+), 77 deletions(-) diff --git a/compiler-base/src/util/escape.rs b/compiler-base/src/util/escape.rs index df98619a..c75ebd76 100644 --- a/compiler-base/src/util/escape.rs +++ b/compiler-base/src/util/escape.rs @@ -44,7 +44,7 @@ macro_rules! escape_impl { /// - `"` becomes `"` /// - `'` becomes `'` pub fn xml_escape(s: &str) -> Cow { - escape_impl!{ + escape_impl! { s, b'&' => b"&", b'<' => b"<", @@ -63,7 +63,7 @@ pub fn xml_escape(s: &str) -> Cow { /// - `"` becomes `"` /// - `'` becomes `'` pub fn html_attr_escape(s: &str) -> Cow { - escape_impl!{ + escape_impl! { s, b'&' => b"&", b'<' => b"<", diff --git a/server/src/api/compile.rs b/server/src/api/compile.rs index 345d31c8..95c6be67 100644 --- a/server/src/api/compile.rs +++ b/server/src/api/compile.rs @@ -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; @@ -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), diff --git a/server/src/api/view.rs b/server/src/api/view.rs index f10f741d..c2e6acdf 100644 --- a/server/src/api/view.rs +++ b/server/src/api/view.rs @@ -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 { @@ -26,17 +26,21 @@ pub fn init_api(app_dir: &str) -> Result { 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) @@ -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); @@ -76,7 +82,10 @@ 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() { @@ -84,11 +93,17 @@ fn init_view_html(app_dir: &str) -> Result<(), io::Error> { 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(()) @@ -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 } @@ -115,25 +127,24 @@ async fn view_owner_repo_path( ) -> Result { // 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 { +async fn view_internal( + owner: &str, + repo: &str, + reference: &str, + path: &str, +) -> Result { let mut builder = compiler::new_context_builder(owner, repo, Some(reference)); if !path.is_empty() { builder = builder.entry_point(Some(path.to_string())); @@ -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; @@ -183,9 +194,18 @@ async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) -> } url }; - let title_tag = format!("", util::html_attr_escape(&title)); - let description_tag = format!("", util::html_attr_escape(&description)); - let url_tag = format!("", util::html_attr_escape(&view_url)); + let title_tag = format!( + "", + util::html_attr_escape(&title) + ); + let description_tag = format!( + "", + util::html_attr_escape(&description) + ); + let url_tag = format!( + "", + util::html_attr_escape(&view_url) + ); let head = get_head()?; let tail = get_tail()?; @@ -199,7 +219,6 @@ async fn view_internal(owner: &str, repo: &str, reference: &str, path: &str) -> ); Ok(html) - } fn view_fallback() -> Result { diff --git a/web-client/src/core/doc/loader.ts b/web-client/src/core/doc/loader.ts index 047b685e..14af1566 100644 --- a/web-client/src/core/doc/loader.ts +++ b/web-client/src/core/doc/loader.ts @@ -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"; @@ -21,7 +23,10 @@ const HELP_URL = "/docs/route/publish#viewing-the-route-on-celer"; export async function loadDocumentFromCurrentUrl(): Promise { 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 @@ -29,12 +34,18 @@ export async function loadDocumentFromCurrentUrl(): Promise // 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; @@ -56,19 +67,22 @@ export async function loadDocumentFromCurrentUrl(): Promise 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 { console.info(`loading document: ${owner}/${repo}/${reference} ${path}`); const startTime = performance.now(); @@ -76,9 +90,14 @@ export async function loadDocument( if (path) { url += `/${path}`; } - const result = await wrapAsync(async () => fetchAsJson(getApiUrl(url))); + const result = await wrapAsync(async () => + fetchAsJson(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); @@ -90,7 +109,7 @@ export async function loadDocument( response.help = HELP_URL; } } - + return result.inner(); } diff --git a/web-client/src/core/kernel/Kernel.ts b/web-client/src/core/kernel/Kernel.ts index 9de775c1..832bc37a 100644 --- a/web-client/src/core/kernel/Kernel.ts +++ b/web-client/src/core/kernel/Kernel.ts @@ -304,7 +304,7 @@ export class Kernel implements KernelAccess { const compiler = await this.getCompiler(); compiler.compile(); return; - } + } await this.reloadDocumentFromServer(); } @@ -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; } diff --git a/web-client/src/low/fetch.ts b/web-client/src/low/fetch.ts index c4131ab4..87508273 100644 --- a/web-client/src/low/fetch.ts +++ b/web-client/src/low/fetch.ts @@ -17,7 +17,7 @@ export const fetchAsJson = (url: string): Promise => { return doFetch(url, (response) => { return response.json(); }); -} +}; const API_PREFIX = "/api/v1"; export const getApiUrl = (path: string) => { diff --git a/web-client/src/ui/toolbar/Header.tsx b/web-client/src/ui/toolbar/Header.tsx index 54a5bdfb..256b288e 100644 --- a/web-client/src/ui/toolbar/Header.tsx +++ b/web-client/src/ui/toolbar/Header.tsx @@ -105,12 +105,16 @@ export const Header: React.FC = ({ 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"; } diff --git a/web-client/src/ui/toolbar/ReloadDocument.tsx b/web-client/src/ui/toolbar/ReloadDocument.tsx index af03b625..db8ceb87 100644 --- a/web-client/src/ui/toolbar/ReloadDocument.tsx +++ b/web-client/src/ui/toolbar/ReloadDocument.tsx @@ -71,10 +71,10 @@ function useReloadDocumentControl() { } function getViewerTooltip(compileInProgress: boolean) { - if (compileInProgress) { - return "Loading..."; - } - return "Reload Document"; + if (compileInProgress) { + return "Loading..."; + } + return "Reload Document"; } function getEditorTooltip(isOpened: boolean, compileInProgress: boolean) { diff --git a/web-client/src/ui/toolbar/getHeaderControls.ts b/web-client/src/ui/toolbar/getHeaderControls.ts index d002d9dc..83ad5f97 100644 --- a/web-client/src/ui/toolbar/getHeaderControls.ts +++ b/web-client/src/ui/toolbar/getHeaderControls.ts @@ -34,7 +34,11 @@ export const getHeaderControls = ( { priority: 40, controls: [ - ...(mode === "view" ? [ReloadDocument] : []), SelectSection, ViewDiagnostics, Export], + ...(mode === "view" ? [ReloadDocument] : []), + SelectSection, + ViewDiagnostics, + Export, + ], }, // Map Controls {