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

Move fontawesome icons check at compile-time #2616

Merged
merged 3 commits into from
Sep 27, 2024
Merged
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
58 changes: 49 additions & 9 deletions crates/font-awesome-as-a-crate/build.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{
collections::HashMap,
env,
fmt::Write as FmtWrite,
fs::{read_dir, File},
io::{Read, Write},
path::Path,
Expand All @@ -11,13 +13,26 @@ fn main() {
write_fontawesome_sprite();
}

fn capitalize_first_letter(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().chain(c).collect(),
}
}

fn write_fontawesome_sprite() {
let mut types = HashMap::new();
let dest_path = Path::new(&env::var("OUT_DIR").unwrap()).join("fontawesome.rs");
let mut dest_file = File::create(dest_path).unwrap();
dest_file
.write_all(b"const fn fontawesome_svg(dir:&str,file:&str)->&'static str{match(dir.as_bytes(),file.as_bytes()){")
.expect("fontawesome fn write");
for dirname in &["brands", "regular", "solid"] {
for (dirname, trait_name) in &[
("brands", "Brands"),
("regular", "Regular"),
("solid", "Solid"),
] {
let dir = read_dir(Path::new("fontawesome-free-6.2.0-desktop/svgs").join(dirname)).unwrap();
let mut data = String::new();
for file in dir {
Expand All @@ -32,20 +47,45 @@ fn write_fontawesome_sprite() {
.expect("fontawesome file read");
// if this assert goes off, add more hashes here and in the format! below
assert!(!data.contains("###"), "file {filename} breaks raw string");
let filename = filename.replace(".svg", "");
dest_file
.write_all(
format!(
r####"(b"{dirname}",b"{filename}")=>r#"{data}"#,"####,
data = data,
dirname = dirname,
filename = filename.replace(".svg", ""),
)
.as_bytes(),
format!(r####"(b"{dirname}",b"{filename}")=>r#"{data}"#,"####).as_bytes(),
)
.expect("write fontawesome file");
types
.entry(filename)
.or_insert_with(|| (data.clone(), Vec::with_capacity(3)))
.1
.push(trait_name);
}
}
dest_file
.write_all(b"_=>\"\"}}")
.write_all(b"_=>\"\"}} pub mod icons { use super::{IconStr, Regular, Brands, Solid};")
.expect("fontawesome fn write");

for (icon, (data, kinds)) in types {
let mut type_name = "Icon".to_string();
type_name.extend(icon.split('-').map(capitalize_first_letter));
let kinds = kinds.iter().fold(String::new(), |mut acc, k| {
let _ = writeln!(acc, "impl {k} for {type_name} {{}}");
acc
});
dest_file
.write_all(
format!(
"\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct {type_name};
impl IconStr for {type_name} {{
fn icon_name(&self) -> &'static str {{ r#\"{icon}\"# }}
fn icon_str(&self) -> &'static str {{ r#\"{data}\"# }}
}}
{kinds}"
)
.as_bytes(),
)
.expect("write fontawesome file types");
}

dest_file.write_all(b"}").expect("fontawesome fn write");
}
23 changes: 23 additions & 0 deletions crates/font-awesome-as-a-crate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,29 @@ pub const fn svg(type_: Type, name: &str) -> Result<&'static str, NameError> {
Ok(svg)
}

pub trait IconStr {
/// Name of the icon, like "triangle-exclamation".
fn icon_name(&self) -> &'static str;
/// The SVG content of the icon.
fn icon_str(&self) -> &'static str;
}

pub trait Brands: IconStr {
fn get_type() -> Type {
Type::Brands
}
}
pub trait Regular: IconStr {
fn get_type() -> Type {
Type::Regular
}
}
pub trait Solid: IconStr {
fn get_type() -> Type {
Type::Solid
}
}

#[cfg(test)]
mod tests {
const fn usable_as_const_() {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub use self::registry_api::RegistryApi;
pub use self::storage::{AsyncStorage, Storage};
pub use self::web::{start_background_metrics_webserver, start_web_server};

pub(crate) use font_awesome_as_a_crate as f_a;

mod build_queue;
pub mod cdn;
mod config;
Expand Down
31 changes: 2 additions & 29 deletions src/web/page/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,10 @@ pub(crate) mod web_page;

pub(crate) use templates::TemplateData;

use serde::Serialize;

#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) struct GlobalAlert {
pub(crate) url: &'static str,
pub(crate) text: &'static str,
pub(crate) css_class: &'static str,
pub(crate) fa_icon: &'static str,
}

#[cfg(test)]
mod tera_tests {
use super::*;
use serde_json::json;

#[test]
fn serialize_global_alert() {
let alert = GlobalAlert {
url: "http://www.hasthelargehadroncolliderdestroyedtheworldyet.com/",
text: "THE WORLD WILL SOON END",
css_class: "THE END IS NEAR",
fa_icon: "https://gph.is/1uOvmqR",
};

let correct_json = json!({
"url": "http://www.hasthelargehadroncolliderdestroyedtheworldyet.com/",
"text": "THE WORLD WILL SOON END",
"css_class": "THE END IS NEAR",
"fa_icon": "https://gph.is/1uOvmqR"
});

assert_eq!(correct_json, serde_json::to_value(alert).unwrap());
}
pub(crate) fa_icon: crate::f_a::icons::IconTriangleExclamation,
syphar marked this conversation as resolved.
Show resolved Hide resolved
}
106 changes: 44 additions & 62 deletions src/web/page/templates.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::error::Result;
use crate::web::rustdoc::RustdocPage;
use anyhow::{anyhow, Context};
use anyhow::Context;
use rinja::Template;
use std::{fmt, sync::Arc};
use std::sync::Arc;
use tracing::trace;

#[derive(Template)]
Expand Down Expand Up @@ -88,7 +88,6 @@ impl TemplateData {
}

pub mod filters {
use super::IconType;
use chrono::{DateTime, Utc};
use rinja::filters::Safe;
use std::borrow::Cow;
Expand Down Expand Up @@ -201,16 +200,31 @@ pub mod filters {
Ok(unindented)
}

pub fn fas(value: &str, fw: bool, spin: bool, extra: &str) -> rinja::Result<Safe<String>> {
IconType::Strong.render(value, fw, spin, extra).map(Safe)
pub fn fas<T: font_awesome_as_a_crate::Solid>(
value: T,
fw: bool,
spin: bool,
extra: &str,
) -> rinja::Result<Safe<String>> {
super::render_icon(value.icon_str(), fw, spin, extra)
}

pub fn far(value: &str, fw: bool, spin: bool, extra: &str) -> rinja::Result<Safe<String>> {
IconType::Regular.render(value, fw, spin, extra).map(Safe)
pub fn far<T: font_awesome_as_a_crate::Regular>(
value: T,
fw: bool,
spin: bool,
extra: &str,
) -> rinja::Result<Safe<String>> {
super::render_icon(value.icon_str(), fw, spin, extra)
}

pub fn fab(value: &str, fw: bool, spin: bool, extra: &str) -> rinja::Result<Safe<String>> {
IconType::Brand.render(value, fw, spin, extra).map(Safe)
pub fn fab<T: font_awesome_as_a_crate::Brands>(
value: T,
fw: bool,
spin: bool,
extra: &str,
) -> rinja::Result<Safe<String>> {
super::render_icon(value.icon_str(), fw, spin, extra)
}

pub fn highlight(code: impl std::fmt::Display, lang: &str) -> rinja::Result<Safe<String>> {
Expand Down Expand Up @@ -241,59 +255,27 @@ pub mod filters {
}
}

enum IconType {
Strong,
Regular,
Brand,
}

impl fmt::Display for IconType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let icon = match self {
Self::Strong => "solid",
Self::Regular => "regular",
Self::Brand => "brands",
};

f.write_str(icon)
fn render_icon(
icon_str: &str,
fw: bool,
spin: bool,
extra: &str,
) -> rinja::Result<rinja::filters::Safe<String>> {
let mut classes = vec!["fa-svg"];
if fw {
classes.push("fa-svg-fw");
}
}

impl IconType {
fn render(self, icon_name: &str, fw: bool, spin: bool, extra: &str) -> rinja::Result<String> {
let type_ = match self {
IconType::Strong => font_awesome_as_a_crate::Type::Solid,
IconType::Regular => font_awesome_as_a_crate::Type::Regular,
IconType::Brand => font_awesome_as_a_crate::Type::Brands,
};

let icon_file_string = font_awesome_as_a_crate::svg(type_, icon_name).map_err(|err| {
rinja::Error::Custom(
anyhow!(err)
.context(format!(
"error trying to render icon with name \"{}\" and type \"{}\"",
icon_name, type_,
))
.into(),
)
})?;

let mut classes = vec!["fa-svg"];
if fw {
classes.push("fa-svg-fw");
}
if spin {
classes.push("fa-svg-spin");
}
if !extra.is_empty() {
classes.push(extra);
}
let icon = format!(
"\
<span class=\"{class}\" aria-hidden=\"true\">{icon_file_string}</span>",
class = classes.join(" "),
);

Ok(icon)
if spin {
classes.push("fa-svg-spin");
}
if !extra.is_empty() {
classes.push(extra);
}
let icon = format!(
"\
<span class=\"{class}\" aria-hidden=\"true\">{icon_str}</span>",
class = classes.join(" "),
);

Ok(rinja::filters::Safe(icon))
}
12 changes: 6 additions & 6 deletions templates/about-base.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,27 @@
<h1 id="crate-title" class="no-description">Docs.rs documentation</h1>
<div class="pure-menu pure-menu-horizontal">
<ul class="pure-menu-list">
{% set text = "circle-info"|fas(false, false, "") %}
{% set text = crate::f_a::icons::IconCircleInfo|fas(false, false, "") %}
{% set text = "{} <span class='title'>About</span>"|format(text) %}
{% call macros::active_link(expected="index", href="/about", text=text) %}

{% set text = "fonticons"|fab(false, false, "") %}
{% set text = crate::f_a::icons::IconFonticons|fab(false, false, "") %}
{% set text = "{} <span class='title'>Badges</span>"|format(text) %}
{% call macros::active_link(expected="badges", href="/about/badges", text=text) %}

{% set text = "gears"|fas(false, false, "") %}
{% set text = crate::f_a::icons::IconGears|fas(false, false, "") %}
{% set text = "{} <span class='title'>Builds</span>"|format(text) %}
{% call macros::active_link(expected="builds", href="/about/builds", text=text) %}

{% set text = "table"|fas(false, false, "") %}
{% set text = crate::f_a::icons::IconTable|fas(false, false, "") %}
{% set text = "{} <span class='title'>Metadata</span>"|format(text) %}
{% call macros::active_link(expected="metadata", href="/about/metadata", text=text) %}

{% set text = "road"|fas(false, false, "") %}
{% set text = crate::f_a::icons::IconRoad|fas(false, false, "") %}
{% set text = "{} <span class='title'>Shorthand URLs</span>"|format(text) %}
{% call macros::active_link(expected="redirections", href="/about/redirections", text=text) %}

{% set text = "download"|fas(false, false, "") %}
{% set text = crate::f_a::icons::IconDownload|fas(false, false, "") %}
{% set text = "{} <span class='title'>Download</span>"|format(text) %}
{% call macros::active_link(expected="download", href="/about/download", text=text) %}
</ul>
Expand Down
4 changes: 2 additions & 2 deletions templates/core/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

{%- block body -%}
<div class="container landing">
<h1 class="brand">{{ "cubes"|fas(false, false, "") }} Docs.rs</h1>
<h1 class="brand">{{ crate::f_a::icons::IconCubes|fas(false, false, "") }} Docs.rs</h1>

<form action="/releases/search" method="GET" class="landing-search-form">
<div>
Expand All @@ -36,7 +36,7 @@ <h1 class="brand">{{ "cubes"|fas(false, false, "") }} Docs.rs</h1>
<strong>Recent Releases</strong>
</a>
<a href="/releases/feed" title="Atom feed">
{{ "square-rss"|fas(false, false, "") }}
{{ crate::f_a::icons::IconSquareRss|fas(false, false, "") }}
</a>
</div>

Expand Down
2 changes: 1 addition & 1 deletion templates/crate/build_details.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
<li>
<a href="/crate/{{ metadata.name }}/{{ metadata.version }}/builds/{{ build_details.id }}/{{ filename }}" class="release">
<div class="pure-g">
<div class="pure-u-1 pure-u-sm-1-24 build">{{ "file-lines"|fas(false, false, "") }}</div>
<div class="pure-u-1 pure-u-sm-1-24 build">{{ crate::f_a::icons::IconFileLines|fas(false, false, "") }}</div>
<div class="pure-u-1 pure-u-sm-10-24">
{% if current_filename.as_deref().unwrap_or_default() == filename.as_str() %}
<b>{{ filename }}</b>
Expand Down
8 changes: 4 additions & 4 deletions templates/crate/builds.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@
<div class="pure-g">
<div class="pure-u-1 pure-u-sm-1-24 build">
{%- if build.build_status == "success" -%}
{{ "check"|fas(false, false, "") }}
{{ crate::f_a::icons::IconCheck|fas(false, false, "") }}
{%- elif build.build_status == "failure" -%}
{{ "triangle-exclamation"|fas(false, false, "") }}
{{ crate::f_a::icons::IconTriangleExclamation|fas(false, false, "") }}
{%- elif build.build_status == "in_progress" -%}
{{ "gear"|fas(false, true, "") }}
{{ crate::f_a::icons::IconGear|fas(false, true, "") }}
{%- else -%}
{{ "x"|fas(false, false, "") }}
{{ crate::f_a::icons::IconX|fas(false, false, "") }}
{%- endif -%}
</div>
<div class="pure-u-1 pure-u-sm-10-24">
Expand Down
Loading
Loading