Skip to content

Ace editor #338

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

Merged
merged 2 commits into from
Aug 5, 2017
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
6 changes: 5 additions & 1 deletion src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ use errors::*;

use config::BookConfig;
use config::tomlconfig::TomlConfig;
use config::htmlconfig::HtmlConfig;
use config::jsonconfig::JsonConfig;


pub struct MDBook {
config: BookConfig,

Expand Down Expand Up @@ -496,6 +496,10 @@ impl MDBook {
.get_additional_css()
}

pub fn get_html_config(&self) -> &HtmlConfig {
self.config.get_html_config()
}

// Construct book
fn parse_summary(&mut self) -> Result<()> {
// When append becomes stable, use self.content.append() ...
Expand Down
4 changes: 2 additions & 2 deletions src/config/bookconfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl BookConfig {
self.get_mut_html_config()
.fill_from_tomlconfig(root, tomlhtmlconfig);
}

self
}

Expand Down Expand Up @@ -213,7 +213,7 @@ impl BookConfig {
self.authors.as_slice()
}

pub fn set_html_config(&mut self, htmlconfig: HtmlConfig) -> &mut Self {
pub fn set_html_config(&mut self, htmlconfig: HtmlConfig) -> &mut Self {
self.html_config = htmlconfig;
self
}
Expand Down
18 changes: 17 additions & 1 deletion src/config/htmlconfig.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::path::{PathBuf, Path};

use super::tomlconfig::TomlHtmlConfig;
use super::playpenconfig::PlaypenConfig;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HtmlConfig {
Expand All @@ -11,6 +12,7 @@ pub struct HtmlConfig {
google_analytics: Option<String>,
additional_css: Vec<PathBuf>,
additional_js: Vec<PathBuf>,
playpen: PlaypenConfig,
}

impl HtmlConfig {
Expand All @@ -27,14 +29,16 @@ impl HtmlConfig {
/// ```
pub fn new<T: Into<PathBuf>>(root: T) -> Self {
let root = root.into();
let theme = root.join("theme");
HtmlConfig {
destination: root.clone().join("book"),
theme: root.join("theme"),
theme: theme.clone(),
curly_quotes: false,
mathjax_support: false,
google_analytics: None,
additional_css: Vec::new(),
additional_js: Vec::new(),
playpen: PlaypenConfig::new(theme),
}
}

Expand Down Expand Up @@ -81,6 +85,10 @@ impl HtmlConfig {
}
}

if let Some(playpen) = tomlconfig.playpen {
self.playpen.fill_from_tomlconfig(&self.theme, playpen);
}

self
}

Expand Down Expand Up @@ -154,4 +162,12 @@ impl HtmlConfig {
pub fn get_additional_js(&self) -> &[PathBuf] {
&self.additional_js
}

pub fn get_playpen_config(&self) -> &PlaypenConfig {
&self.playpen
}

pub fn get_mut_playpen_config(&mut self) -> &mut PlaypenConfig {
&mut self.playpen
}
}
2 changes: 2 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
pub mod bookconfig;
pub mod htmlconfig;
pub mod playpenconfig;
pub mod tomlconfig;
pub mod jsonconfig;

// Re-export the config structs
pub use self::bookconfig::BookConfig;
pub use self::htmlconfig::HtmlConfig;
pub use self::playpenconfig::PlaypenConfig;
pub use self::tomlconfig::TomlConfig;
68 changes: 68 additions & 0 deletions src/config/playpenconfig.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::path::{PathBuf, Path};

use super::tomlconfig::TomlPlaypenConfig;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlaypenConfig {
editor: PathBuf,
Copy link
Contributor Author

@projektir projektir Jun 22, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So maybe this could be another config, i.e., an EditorConfig. One thing, though, is that even if you abstract it away here, it's not abstracted in book.js.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Turtles all the way down ;) I guess that we should not worry about it atm. book.js and index.hbs are not as parametrized and more coupled than one would like anyway.

This might be a good material for a refactor in another PR. What do you think @azerupi?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something is better than nothing. 😉

This might be a good material for a refactor in another PR.

Do you have something specific in mind?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't get me wrong. I think that this PR is really good, just there is no need to try to refactor everything at once now.

I was thinking about some possible future changes. Some random ideas:

  • expanding the playpen config to make features opt in or opt out (clipboard support, resetable if editable, code runnable)
  • split book.js by features or make it parametric like index hbs
  • possibly support for alternative playpens like integer32 or other non rust speccific ones
  • make mathjax opt in (it is really heavy and blocks offline reading now)
  • start working on alternative renderers (possibly split off the renderers into separate crates)
  • make themes opt in or opt out (maybe some overridable list of defaults)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expanding the playpen config to make features opt in or opt out (clipboard support, resetable if editable, code runnable)

I would like that very much. Once we have plugins I want to make playpen etc. plugins with their own config. That would hook into the work that @Michael-F-Bryan is doing. I don't think it is worth refactoring right now, efforts are better spend making sure that the plugin system will support all of this.

split book.js by features

That is something we could do. I'm actually a fan of typescript instead of JavaScript, so maybe it's worth considering switching to it? The problem is that it adds a compilation phase and a dependency on the typescript compiler. One more thing to learn and setup for new contributors.

make mathjax opt in (it is really heavy and blocks offline reading now)

Absolutely, here again I would make MathJax a plugin in the future. But if it is really a problem we could find a temporary fix.

start working on alternative renderers (possibly split off the renderers into separate crates)

That would be great, but a lot of refactoring is needed before we can really begin to do this.

make themes opt in or opt out (maybe some overridable list of defaults)

Yes, that is something I would want. Actually the whole 'theme' handling should be rethought so that adding new themes is easy and configurable. One thing that could be beneficial is to move from stylus to SASS, because we then can use the Rust sass bindings to compile themes at runtime.

All those points are great but not related to this PR, so I propose you make issues for all / some of them to discuss them further and track progress :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All those points are great but not related to this PR.

Exactly. That is what I meant when talking about refactor in another PR's. Imho this PR should not be blocked on more refactoring.
Further rewrites should be given some thought.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm actually a fan of typescript instead of JavaScript, so maybe it's worth considering switching to it?

TypeScript would be cool to see. 😄 I kept being annoyed that I don't have types when going from Rust to JavaScript.

Copy link
Contributor

@budziq budziq Jun 23, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

editable: bool,
}

impl PlaypenConfig {
/// Creates a new `PlaypenConfig` for playpen configuration.
///
/// ```
/// # use std::path::PathBuf;
/// # use mdbook::config::PlaypenConfig;
/// #
/// let editor = PathBuf::from("root/editor");
/// let config = PlaypenConfig::new(PathBuf::from("root"));
///
/// assert_eq!(config.get_editor(), &editor);
/// assert_eq!(config.is_editable(), false);
/// ```
pub fn new<T: Into<PathBuf>>(root: T) -> Self {
PlaypenConfig {
editor: root.into().join("editor"),
editable: false,
}
}

pub fn fill_from_tomlconfig<T: Into<PathBuf>>(&mut self, root: T, tomlplaypenconfig: TomlPlaypenConfig) -> &mut Self {
let root = root.into();

if let Some(editor) = tomlplaypenconfig.editor {
if editor.is_relative() {
self.editor = root.join(editor);
} else {
self.editor = editor;
}
}

if let Some(editable) = tomlplaypenconfig.editable {
self.editable = editable;
}

self
}

pub fn is_editable(&self) -> bool {
self.editable
}

pub fn get_editor(&self) -> &Path {
&self.editor
}

pub fn set_editor<T: Into<PathBuf>>(&mut self, root: T, editor: T) -> &mut Self {
let editor = editor.into();

if editor.is_relative() {
self.editor = root.into().join(editor);
} else {
self.editor = editor;
}

self
}
}
9 changes: 7 additions & 2 deletions src/config/tomlconfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ pub struct TomlHtmlConfig {
pub mathjax_support: Option<bool>,
pub additional_css: Option<Vec<PathBuf>>,
pub additional_js: Option<Vec<PathBuf>>,
pub playpen: Option<TomlPlaypenConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TomlPlaypenConfig {
pub editor: Option<PathBuf>,
pub editable: Option<bool>,
}

/// Returns a `TomlConfig` from a TOML string
Expand All @@ -52,5 +59,3 @@ impl TomlConfig {
Ok(config)
}
}


63 changes: 43 additions & 20 deletions src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use preprocess;
use renderer::Renderer;
use book::MDBook;
use book::bookitem::{BookItem, Chapter};
use utils;
use theme::{self, Theme};
use config::PlaypenConfig;
use {utils, theme};
use theme::{Theme, playpen_editor};
use errors::*;
use regex::{Regex, Captures};

Expand All @@ -19,7 +20,6 @@ use handlebars::Handlebars;

use serde_json;


#[derive(Default)]
pub struct HtmlHandlebars;

Expand Down Expand Up @@ -69,8 +69,11 @@ impl HtmlHandlebars {
// Render the handlebars template with the data
debug!("[*]: Render template");
let rendered = ctx.handlebars.render("index", &ctx.data)?;

let filename = Path::new(&ch.path).with_extension("html");
let rendered = self.post_process(rendered, filename.file_name().unwrap().to_str().unwrap_or(""));
let rendered = self.post_process(rendered,
filename.file_name().unwrap().to_str().unwrap_or(""),
ctx.book.get_html_config().get_playpen_config());

// Write to file
info!("[*] Creating {:?} ✓", filename.display());
Expand Down Expand Up @@ -116,11 +119,11 @@ impl HtmlHandlebars {
Ok(())
}

fn post_process(&self, rendered: String, filename: &str) -> String {
fn post_process(&self, rendered: String, filename: &str, playpen_config: &PlaypenConfig) -> String {
let rendered = build_header_links(&rendered, filename);
let rendered = fix_anchor_links(&rendered, filename);
let rendered = fix_code_blocks(&rendered);
let rendered = add_playpen_pre(&rendered);
let rendered = add_playpen_pre(&rendered, playpen_config);

rendered
}
Expand Down Expand Up @@ -171,6 +174,19 @@ impl HtmlHandlebars {
theme::FONT_AWESOME_TTF,
)?;

let playpen_config = book.get_html_config().get_playpen_config();

// Ace is a very large dependency, so only load it when requested
if playpen_config.is_editable() {
// Load the editor
let editor = playpen_editor::PlaypenEditor::new(playpen_config.get_editor());
book.write_file("editor.js", &editor.js)?;
book.write_file("ace.js", &editor.ace_js)?;
book.write_file("mode-rust.js", &editor.mode_rust_js)?;
book.write_file("theme-dawn.js", &editor.theme_dawn_js)?;
book.write_file("theme-tomorrow_night.js", &editor.theme_tomorrow_night_js)?;
}

Ok(())
}

Expand Down Expand Up @@ -273,8 +289,10 @@ impl Renderer for HtmlHandlebars {
debug!("[*]: Render template");

let rendered = handlebars.render("index", &data)?;
let rendered = self.post_process(rendered, "print.html");

let rendered = self.post_process(rendered, "print.html",
book.get_html_config().get_playpen_config());

book.write_file(
Path::new("print").with_extension("html"),
&rendered.into_bytes(),
Expand Down Expand Up @@ -354,6 +372,15 @@ fn make_data(book: &MDBook) -> Result<serde_json::Map<String, serde_json::Value>
data.insert("additional_js".to_owned(), json!(js));
}

if book.get_html_config().get_playpen_config().is_editable() {
data.insert("playpens_editable".to_owned(), json!(true));
data.insert("editor_js".to_owned(), json!("editor.js"));
data.insert("ace_js".to_owned(), json!("ace.js"));
data.insert("mode_rust_js".to_owned(), json!("mode-rust.js"));
data.insert("theme_dawn_js".to_owned(), json!("theme-dawn.js"));
data.insert("theme_tomorrow_night_js".to_owned(), json!("theme-tomorrow_night.js"));
}

let mut chapters = vec![];

for item in book.iter() {
Expand Down Expand Up @@ -512,7 +539,7 @@ fn fix_code_blocks(html: &str) -> String {
.into_owned()
}

fn add_playpen_pre(html: &str) -> String {
fn add_playpen_pre(html: &str, playpen_config: &PlaypenConfig) -> String {
let regex = Regex::new(r##"((?s)<code[^>]?class="([^"]+)".*?>(.*?)</code>)"##).unwrap();
regex
.replace_all(html, |caps: &Captures| {
Expand All @@ -522,22 +549,18 @@ fn add_playpen_pre(html: &str) -> String {

if classes.contains("language-rust") && !classes.contains("ignore") {
// wrap the contents in an external pre block

if text.contains("fn main") || text.contains("quick_main!") {
if playpen_config.is_editable() &&
classes.contains("editable") || text.contains("fn main") || text.contains("quick_main!") {
format!("<pre class=\"playpen\">{}</pre>", text)
} else {
// we need to inject our own main
let (attrs, code) = partition_source(code);
format!(
"<pre class=\"playpen\"><code class=\"{}\"># #![allow(unused_variables)]
{}#fn main() {{
\
{}
#}}</code></pre>",
classes,
attrs,
code
)

format!("<pre class=\"playpen\"><code class=\"{}\">\n# #![allow(unused_variables)]\n\
{}#fn main() {{\n\
{}\
#}}</code></pre>",
classes, attrs, code)
}
} else {
// not language-rust, so no-op
Expand Down
3 changes: 3 additions & 0 deletions src/theme/book.css
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,9 @@ table thead td {
/* Force background to be printed in Chrome */
-webkit-print-color-adjust: exact;
}
pre > .buttons {
z-index: 2;
}
a,
a:visited,
a:active,
Expand Down
Loading