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

Use embedded Font Awesome SVG icons #2484

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ clap = { version = "4.3.12", features = ["cargo", "wrap_help"] }
clap_complete = "4.3.2"
once_cell = "1.17.1"
env_logger = "0.11.1"
font-awesome-as-a-crate = "0.3.0"
handlebars = "6.0"
log = "0.4.17"
memchr = "2.5.0"
Expand Down
4 changes: 2 additions & 2 deletions guide/src/format/configuration/renderers.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ additional-css = ["custom.css", "custom2.css"]
additional-js = ["custom.js"]
no-section-label = false
git-repository-url = "https://github.com/rust-lang/mdBook"
git-repository-icon = "fa-github"
git-repository-icon = "fab-github"
edit-url-template = "https://github.com/rust-lang/mdBook/edit/master/guide/{path}"
site-url = "/example-book/"
cname = "myproject.rs"
Expand Down Expand Up @@ -147,7 +147,7 @@ The following configuration options are available:
- **git-repository-url:** A url to the git repository for the book. If provided
an icon link will be output in the menu bar of the book.
- **git-repository-icon:** The FontAwesome icon class to use for the git
repository link. Defaults to `fa-github` which looks like <i class="fa fa-github"></i>.
repository link. Defaults to `fab-github` which looks like <i class="fa fab-github"></i>.
If you are not using GitHub, another option to consider is `fa-code-fork` which looks like <i class="fa fa-code-fork"></i>.
- **edit-url-template:** Edit url template, when provided shows a
"Suggest an edit" button (which looks like <i class="fa fa-edit"></i>) for directly jumping to editing the currently
Expand Down
16 changes: 16 additions & 0 deletions guide/src/format/mdbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,19 @@ fatigue," where people are trained to ignore them because they usually don't
matter for what they're doing.

</div>


## Font-Awesome icons

mdBook includes a copy of [Font Awesome's](https://fontawesome.com) free
MIT-licensed SVG files. It emulates the `<i>` syntax, but converts the results
to inline SVG. Only the regular, solid, and brands icons are included; paid
features such as the light icons are not.

For example, given this HTML syntax:

```hbs
The result looks like this: <i class="fa fas-print"></i>
```

The result looks like this: <i class="fa fas-print"></i>
125 changes: 89 additions & 36 deletions src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ impl HtmlHandlebars {
let rendered = fix_code_blocks(&rendered);
let rendered = add_playground_pre(&rendered, playground_config, edition);
let rendered = hide_lines(&rendered, code_config);
let rendered = convert_fontawesome(&rendered);

rendered
}
Expand Down Expand Up @@ -258,41 +259,7 @@ impl HtmlHandlebars {
write_file(destination, "ayu-highlight.css", &theme.ayu_highlight_css)?;
write_file(destination, "highlight.js", &theme.highlight_js)?;
write_file(destination, "clipboard.min.js", &theme.clipboard_js)?;
write_file(
destination,
"FontAwesome/css/font-awesome.css",
theme::FONT_AWESOME,
)?;
write_file(
destination,
"FontAwesome/fonts/fontawesome-webfont.eot",
theme::FONT_AWESOME_EOT,
)?;
write_file(
destination,
"FontAwesome/fonts/fontawesome-webfont.svg",
theme::FONT_AWESOME_SVG,
)?;
write_file(
destination,
"FontAwesome/fonts/fontawesome-webfont.ttf",
theme::FONT_AWESOME_TTF,
)?;
write_file(
destination,
"FontAwesome/fonts/fontawesome-webfont.woff",
theme::FONT_AWESOME_WOFF,
)?;
write_file(
destination,
"FontAwesome/fonts/fontawesome-webfont.woff2",
theme::FONT_AWESOME_WOFF2,
)?;
write_file(
destination,
"FontAwesome/fonts/FontAwesome.ttf",
theme::FONT_AWESOME_TTF,
)?;

// Don't copy the stock fonts if the user has specified their own fonts to use.
if html_config.copy_fonts && theme.fonts_css.is_none() {
write_file(destination, "fonts/fonts.css", theme::fonts::CSS)?;
Expand Down Expand Up @@ -379,6 +346,7 @@ impl HtmlHandlebars {
handlebars.register_helper("next", Box::new(helpers::navigation::next));
// TODO: remove theme_option in 0.5, it is not needed.
handlebars.register_helper("theme_option", Box::new(helpers::theme::theme_option));
handlebars.register_helper("fa", Box::new(helpers::fontawesome::fa_helper));
}

/// Copy across any additional CSS and JavaScript files which the book
Expand Down Expand Up @@ -754,9 +722,19 @@ fn make_data(

let git_repository_icon = match html_config.git_repository_icon {
Some(ref git_repository_icon) => git_repository_icon,
None => "fa-github",
None => "fab-github",
};
let git_repository_icon_class = match git_repository_icon.split('-').next() {
Some("fa") => "regular",
Some("fas") => "solid",
Some("fab") => "brands",
_ => "regular",
};
data.insert("git_repository_icon".to_owned(), json!(git_repository_icon));
data.insert(
"git_repository_icon_class".to_owned(),
json!(git_repository_icon_class),
);

let mut chapters = vec![];

Expand Down Expand Up @@ -855,6 +833,56 @@ fn insert_link_into_header(
)
}

// Convert fontawesome `<i>` tags to inline SVG
fn convert_fontawesome(html: &str) -> String {
use font_awesome_as_a_crate as fa;

let regex = Regex::new(r##"<i([^>]+)class="([^"]+)"([^>]*)></i>"##).unwrap();
regex
.replace_all(html, |caps: &Captures<'_>| {
let text = &caps[0];
let before = &caps[1];
let classes = &caps[2];
let after = &caps[3];

let mut icon = String::new();
let mut type_ = fa::Type::Regular;
let mut other_classes = String::new();

for class in classes.split(" ") {
if let Some((prefix, remainder)) = class.split_once('-') {
if let Some(t) = match prefix {
"fa" => Some(fa::Type::Regular),
"fas" => Some(fa::Type::Solid),
"fab" => Some(fa::Type::Brands),
_ => None,
} {
type_ = t;
icon = remainder.to_owned();
continue;
}
}
other_classes += " ";
other_classes += class;
}

if icon.is_empty() {
text.to_owned()
} else if let Ok(svg) = fa::svg(type_, &icon) {
uncenter marked this conversation as resolved.
Show resolved Hide resolved
format!(
r#"<span{before}class="fa-svg{other_classes}"{after}>{svg}</span>"#,
before = before,
other_classes = other_classes.replace(" fa", ""),
after = after,
svg = svg
)
} else {
text.to_owned()
}
})
.into_owned()
}

// The rust book uses annotations for rustdoc to test code snippets,
// like the following:
// ```rust,should_panic
Expand Down Expand Up @@ -1294,4 +1322,29 @@ mod tests {
assert_eq!(json!(TextDirection::RightToLeft), json!("rtl"));
assert_eq!(json!(TextDirection::LeftToRight), json!("ltr"));
}

#[test]
fn convert_valid_fontawesome_class() {
assert!(convert_fontawesome("<i class=\"fa fab-github\"></i>").contains("class=\"fa-svg\""));
assert!(
convert_fontawesome("<i class=\"fa fab-github some-class\"></i>")
.contains("class=\"fa-svg some-class\"")
);
assert!(convert_fontawesome("<i class=\"fa fas-print\"></i>").contains("class=\"fa-svg\""));
assert!(convert_fontawesome("<i class=\"fa fa-eye\"></i>").contains("class=\"fa-svg\""));
}

#[test]
fn convert_invalid_fontawesome_class() {
let invalid_fontawesome_i_tag = "<i class=\"fa\"></i>";
assert_eq!(
convert_fontawesome(invalid_fontawesome_i_tag),
invalid_fontawesome_i_tag
);
let non_fontawesome_i_tag = "<i class=\"some-class\"></i>";
assert_eq!(
convert_fontawesome(non_fontawesome_i_tag),
non_fontawesome_i_tag
);
}
}
53 changes: 53 additions & 0 deletions src/renderer/html_handlebars/helpers/fontawesome.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use font_awesome_as_a_crate as fa;
use handlebars::{
Context, Handlebars, Helper, Output, RenderContext, RenderError, RenderErrorReason,
};
use log::trace;
use std::str::FromStr;

pub fn fa_helper(
h: &Helper<'_>,
_r: &Handlebars<'_>,
_ctx: &Context,
_rc: &mut RenderContext<'_, '_>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
trace!("fa_helper (handlebars helper)");

let type_ = h
.param(0)
.and_then(|v| v.value().as_str())
.and_then(|v| fa::Type::from_str(v).ok())
.ok_or_else(|| {
RenderErrorReason::Other(
"Param 0 with String type is required for fontawesome helper.".to_owned(),
)
})?;

let name = h.param(1).and_then(|v| v.value().as_str()).ok_or_else(|| {
RenderErrorReason::Other(
"Param 1 with String type is required for fontawesome helper.".to_owned(),
)
})?;

trace!("fa_helper: {} {}", type_, name);

let name = name
.strip_prefix("fa-")
.or_else(|| name.strip_prefix("fab-"))
.or_else(|| name.strip_prefix("fas-"))
.unwrap_or(name);

if let Some(id) = h.param(2).and_then(|v| v.value().as_str()) {
out.write(&format!("<span class=\"fa-svg\" id=\"{}\">", id))?;
} else {
out.write("<span class=\"fa-svg\">")?;
}
out.write(
fa::svg(type_, name)
uncenter marked this conversation as resolved.
Show resolved Hide resolved
.map_err(|_| RenderErrorReason::Other(format!("Missing font {}", name)))?,
)?;
out.write("</span>")?;

Ok(())
}
1 change: 1 addition & 0 deletions src/renderer/html_handlebars/helpers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod fontawesome;
pub mod navigation;
pub mod theme;
pub mod toc;
4 changes: 0 additions & 4 deletions src/theme/FontAwesome/css/font-awesome.min.css

This file was deleted.

Binary file removed src/theme/FontAwesome/fonts/FontAwesome.otf
Binary file not shown.
Binary file removed src/theme/FontAwesome/fonts/fontawesome-webfont.eot
Binary file not shown.
Loading