Skip to content

Commit

Permalink
Added ftd.code
Browse files Browse the repository at this point in the history
  • Loading branch information
Arpita-Jaiswal committed Jan 11, 2023
1 parent e17b9ce commit 5c5a821
Show file tree
Hide file tree
Showing 9 changed files with 1,486 additions and 27 deletions.
59 changes: 59 additions & 0 deletions src/executor/code.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
static SYNTAX_DIR: include_dir::Dir<'_> = include_dir::include_dir!("syntax");
pub const DEFAULT_THEME: &str = "base16-ocean.dark";

pub static SS: once_cell::sync::Lazy<syntect::parsing::SyntaxSet> =
once_cell::sync::Lazy::new(|| {
let mut builder = syntect::parsing::SyntaxSet::load_defaults_newlines().into_builder();
for f in SYNTAX_DIR.files() {
builder.add(
syntect::parsing::syntax_definition::SyntaxDefinition::load_from_str(
f.contents_utf8().unwrap(),
true,
f.path().file_stem().and_then(|x| x.to_str()),
)
.unwrap(),
);
}
builder.build()
});

/*pub static KNOWN_EXTENSIONS: once_cell::sync::Lazy<std::collections::HashSet<String>> =
once_cell::sync::Lazy::new(|| {
SS.syntaxes()
.iter()
.flat_map(|v| v.file_extensions.to_vec())
.collect()
});*/

pub static TS: once_cell::sync::Lazy<syntect::highlighting::ThemeSet> =
once_cell::sync::Lazy::new(syntect::highlighting::ThemeSet::load_defaults);

pub fn code(code: &str, ext: &str, theme: &str, doc_id: &str) -> ftd::executor::Result<String> {
let syntax = SS
.find_syntax_by_extension(ext)
.unwrap_or_else(|| SS.find_syntax_plain_text());
if !TS.themes.contains_key(theme) {
return Err(ftd::executor::Error::ParseError {
message: format!("'{}' is not a valid theme", theme),
doc_id: doc_id.to_string(),
line_number: 0,
});
}

let theme = &TS.themes[theme];

let code = code
.lines()
.skip_while(|l| l.trim().is_empty())
.collect::<Vec<_>>()
.join("\n")
.trim_end()
.to_string()
+ "\n";

// TODO: handle various params
Ok(
syntect::html::highlighted_html_for_string(code.as_str(), &SS, syntax, theme)?
.replacen('\n', "", 1),
)
}
100 changes: 100 additions & 0 deletions src/executor/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub enum Element {
Integer(Text),
Boolean(Text),
Image(Image),
Code(Code),
Null,
}

Expand All @@ -18,6 +19,7 @@ impl Element {
Element::Integer(i) => Some(&i.common),
Element::Boolean(b) => Some(&b.common),
Element::Image(i) => Some(&i.common),
Element::Code(c) => Some(&c.common),
Element::Null => None,
}
}
Expand Down Expand Up @@ -103,13 +105,111 @@ impl ImageSrc {
}
}

#[derive(serde::Deserialize, Debug, PartialEq, Default, Clone, serde::Serialize)]
pub struct Code {
pub text: ftd::executor::Value<Rendered>,
pub text_align: ftd::executor::Value<Option<ftd::executor::TextAlign>>,
pub common: Common,
}

pub fn code_from_properties(
properties: &[ftd::interpreter2::Property],
events: &[ftd::interpreter2::Event],
arguments: &[ftd::interpreter2::Argument],
condition: &Option<ftd::interpreter2::Expression>,
doc: &ftd::executor::TDoc,
local_container: &[usize],
line_number: usize,
) -> ftd::executor::Result<Code> {
// TODO: `text`, `lang` and `theme` cannot have condition

let text =
ftd::executor::value::optional_string("text", properties, arguments, doc, line_number)?;
if text.value.is_none() && condition.is_none() {
// TODO: Check condition if `value is not null` is there
return ftd::executor::utils::parse_error(
"Expected string for text property",
doc.name,
line_number,
);
}

let lang = ftd::executor::value::string_with_default(
"lang",
properties,
arguments,
"txt",
doc,
line_number,
)?;

let theme = ftd::executor::value::string_with_default(
"theme",
properties,
arguments,
ftd::executor::code::DEFAULT_THEME,
doc,
line_number,
)?;

let text = ftd::executor::Value::new(
ftd::executor::element::code_with_theme(
text.value.unwrap_or_default().as_str(),
lang.value.as_str(),
theme.value.as_str(),
doc.name,
)?,
text.line_number,
text.properties,
);

let common = common_from_properties(
properties,
events,
arguments,
condition,
doc,
local_container,
line_number,
)?;

Ok(Code {
text,
text_align: ftd::executor::TextAlign::optional_text_align(
properties,
arguments,
doc,
line_number,
"text-align",
)?,
common,
})
}

pub fn markup_inline(s: &str) -> Rendered {
Rendered {
original: s.to_string(),
rendered: ftd::executor::markup::markup_inline(s),
}
}

pub fn code_with_theme(
code: &str,
ext: &str,
theme: &str,
doc_id: &str,
) -> ftd::executor::Result<Rendered> {
Ok(Rendered {
original: code.to_string(),
rendered: ftd::executor::code::code(
code.replace("\n\\-- ", "\n-- ").as_str(),
ext,
theme,
doc_id,
)?,
})
}

#[derive(serde::Deserialize, Debug, PartialEq, Default, Clone, serde::Serialize)]
pub struct Container {
pub spacing: ftd::executor::Value<Option<ftd::executor::Length>>,
Expand Down
11 changes: 11 additions & 0 deletions src/executor/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,17 @@ impl<'a> ExecuteDoc<'a> {
instruction.line_number,
)?)
}
"ftd#code" => {
ftd::executor::Element::Code(ftd::executor::element::code_from_properties(
instruction.properties.as_slice(),
instruction.events.as_slice(),
component_definition.arguments.as_slice(),
instruction.condition.as_ref(),
doc,
local_container,
instruction.line_number,
)?)
}
_ => unimplemented!(),
})
}
Expand Down
9 changes: 8 additions & 1 deletion src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#[macro_use]
mod test;

mod code;
mod element;
mod main;
mod markup;
Expand All @@ -10,7 +11,7 @@ mod tdoc;
mod utils;
mod value;

pub use element::{Column, Common, Container, Element, Event, Image, Row, Text};
pub use element::{Code, Column, Common, Container, Element, Event, Image, Row, Text};
pub use main::{ExecuteDoc, RT};
pub use styles::{
AlignSelf, Alignment, Anchor, Background, Color, ColorValue, Cursor, FontSize, Length,
Expand All @@ -31,6 +32,12 @@ pub enum Error {
doc_id: String,
line_number: usize,
},

#[error("syntect error: {source}")]
Syntect {
#[from]
source: syntect::Error,
},
}

pub type Result<T> = std::result::Result<T, Error>;
35 changes: 35 additions & 0 deletions src/executor/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,41 @@ pub fn optional_i64(
}
}

pub fn string_with_default(
key: &str,
properties: &[ftd::interpreter2::Property],
arguments: &[ftd::interpreter2::Argument],
default: &str,
doc: &ftd::executor::TDoc,
line_number: usize,
) -> ftd::executor::Result<ftd::executor::Value<String>> {
let value = get_value_from_properties_using_key_and_arguments(
key,
properties,
arguments,
doc,
line_number,
)?;

match value.value.and_then(|v| v.inner()) {
Some(ftd::interpreter2::Value::String { text }) => Ok(ftd::executor::Value::new(
text,
value.line_number,
value.properties,
)),
None => Ok(ftd::executor::Value::new(
default.to_string(),
value.line_number,
value.properties,
)),
t => ftd::executor::utils::parse_error(
format!("Expected value of type optional string, found: {:?}", t),
doc.name,
line_number,
),
}
}

pub fn optional_string(
key: &str,
properties: &[ftd::interpreter2::Property],
Expand Down
65 changes: 39 additions & 26 deletions src/interpreter2/things/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ pub fn default_bag() -> ftd::Map<ftd::interpreter2::Thing> {
"ftd#row".to_string(),
ftd::interpreter2::Thing::Component(row_function()),
),
(
"ftd#code".to_string(),
ftd::interpreter2::Thing::Component(code_function()),
),
(
"ftd#input".to_string(),
ftd::interpreter2::Thing::Component(row_function()),
Expand Down Expand Up @@ -6019,6 +6023,39 @@ pub fn integer_function() -> ftd::interpreter2::ComponentDefinition {
pub fn markup_function() -> ftd::interpreter2::ComponentDefinition {
ftd::interpreter2::ComponentDefinition {
name: "ftd#text".to_string(),
arguments: [
text_arguments(),
common_arguments(),
vec![ftd::interpreter2::Argument::default(
"text",
ftd::interpreter2::Kind::string()
.into_kind_data()
.caption_or_body(),
)],
]
.concat()
.into_iter()
.collect(),
definition: ftd::interpreter2::Component::from_name("ftd.kernel"),
line_number: 0,
}
}

pub fn row_function() -> ftd::interpreter2::ComponentDefinition {
ftd::interpreter2::ComponentDefinition {
name: "ftd#row".to_string(),
arguments: [container_arguments(), common_arguments()]
.concat()
.into_iter()
.collect(),
definition: ftd::interpreter2::Component::from_name("ftd.kernel"),
line_number: 0,
}
}

pub fn code_function() -> ftd::interpreter2::ComponentDefinition {
ftd::interpreter2::ComponentDefinition {
name: "ftd#code".to_string(),
arguments: [
text_arguments(),
common_arguments(),
Expand All @@ -6030,25 +6067,13 @@ pub fn markup_function() -> ftd::interpreter2::ComponentDefinition {
.caption_or_body(),
),
ftd::interpreter2::Argument::default(
"style",
"lang",
ftd::interpreter2::Kind::string()
.into_optional()
.into_kind_data(),
),
ftd::interpreter2::Argument::default(
"line-clamp",
ftd::interpreter2::Kind::integer()
.into_optional()
.into_kind_data(),
),
ftd::interpreter2::Argument::default(
"text-indent",
ftd::interpreter2::Kind::string()
.into_optional()
.into_kind_data(),
),
ftd::interpreter2::Argument::default(
"text-align",
"theme",
ftd::interpreter2::Kind::string()
.into_optional()
.into_kind_data(),
Expand All @@ -6063,18 +6088,6 @@ pub fn markup_function() -> ftd::interpreter2::ComponentDefinition {
}
}

pub fn row_function() -> ftd::interpreter2::ComponentDefinition {
ftd::interpreter2::ComponentDefinition {
name: "ftd#row".to_string(),
arguments: [container_arguments(), common_arguments()]
.concat()
.into_iter()
.collect(),
definition: ftd::interpreter2::Component::from_name("ftd.kernel"),
line_number: 0,
}
}

pub fn input_function() -> ftd::interpreter2::ComponentDefinition {
ftd::interpreter2::ComponentDefinition {
name: "ftd#input".to_string(),
Expand Down
Loading

0 comments on commit 5c5a821

Please sign in to comment.