#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateIdentity {
pub name: String,
pub source: String,
}
impl TemplateIdentity {
fn hash(&self) -> String {
let seed = if self.source.is_empty() {
self.name.as_str()
} else {
self.source.as_str()
};
let mut hash: u32 = 0x811c_9dc5;
for byte in seed.as_bytes() {
hash ^= u32::from(*byte);
hash = hash.wrapping_mul(0x0100_0193);
}
format!("{hash:08x}")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompileOptions {
pub inject_morph_markers: bool,
pub smart_wire_keys: bool,
}
pub fn compile(source: &str, identity: &TemplateIdentity, options: CompileOptions) -> String {
let mut compiler = Compiler::new(identity.hash(), options, loops_need_aliases(source));
compiler.translate(source, false)
}
const BLOCK_START: &str = "<!--[if BLOCK]><![endif]-->";
const BLOCK_END: &str = "<!--[if ENDBLOCK]><![endif]-->";
struct Compiler {
alias_loops: bool,
depth: usize,
hash: String,
island_occurrence: usize,
loop_occurrence: usize,
loops: Vec<String>,
occurrence: usize,
options: CompileOptions,
slot_occurrence: usize,
}
impl Compiler {
fn new(hash: String, options: CompileOptions, alias_loops: bool) -> Self {
Self {
alias_loops,
depth: 0,
hash,
island_occurrence: 0,
loop_occurrence: 0,
loops: Vec::new(),
occurrence: 0,
options,
slot_occurrence: 0,
}
}
fn translate(&mut self, text: &str, in_tag: bool) -> String {
if self.depth > 64 {
return text.to_string();
}
self.depth += 1;
let result = self.translate_inner(text, in_tag);
self.depth -= 1;
result
}
fn translate_inner(&mut self, text: &str, start_in_tag: bool) -> String {
let bytes = text.as_bytes();
let mut out = String::with_capacity(text.len() + 64);
let mut index = 0;
let mut in_tag = start_in_tag;
let mut quote: Option<u8> = None;
let mut raw_text: Option<String> = None;
let mut pending_tag: Option<(String, bool)> = None;
while index < bytes.len() {
if let Some(active_quote) = quote {
if bytes[index] == active_quote {
quote = None;
out.push(char::from(active_quote));
index += 1;
continue;
}
if bytes[index] == b'@' {
if let Some((consumed, replacement)) = self.directive(text, index) {
out.push_str(&replacement);
index += consumed;
} else {
out.push('@');
index += 1;
}
continue;
}
if bytes[index] == b'{' && starts_jinja(bytes, index) {
match jinja_end(text, index) {
Some(end) => {
out.push_str(&text[index..end]);
index = end;
}
None => {
out.push('{');
index += 1;
}
}
continue;
}
let start = index;
index += 1;
while index < bytes.len()
&& bytes[index] != b'@'
&& bytes[index] != b'{'
&& bytes[index] != active_quote
{
index += 1;
}
out.push_str(&text[start..index]);
continue;
}
match bytes[index] {
b'<' if !in_tag => {
if let Some(tag) = LivewireTag::parse(text, index) {
match tag.compile(self) {
Some(compiled) => {
out.push_str(&compiled);
index = tag.end;
}
None => {
out.push('<');
index += 1;
}
}
continue;
}
let mut cursor = index + 1;
let closing = cursor < bytes.len() && bytes[cursor] == b'/';
if closing {
cursor += 1;
}
let name_start = cursor;
while cursor < bytes.len() && bytes[cursor].is_ascii_alphanumeric() {
cursor += 1;
}
let opens_tag =
cursor > name_start || (cursor < bytes.len() && matches!(bytes[cursor], b'!' | b'?'));
if opens_tag {
in_tag = true;
pending_tag = if cursor > name_start {
Some((text[name_start..cursor].to_ascii_lowercase(), closing))
} else {
None
};
}
out.push('<');
index += 1;
}
b'>' if in_tag => {
in_tag = false;
if let Some((name, closing)) = pending_tag.take()
&& (name == "script" || name == "style")
{
let self_closing = index > 0 && bytes[index - 1] == b'/';
if closing {
if raw_text.as_deref() == Some(name.as_str()) {
raw_text = None;
}
} else if !self_closing {
raw_text = Some(name);
}
}
out.push('>');
index += 1;
}
b'"' | b'\'' if in_tag => {
quote = Some(bytes[index]);
out.push(char::from(bytes[index]));
index += 1;
}
b'{' if starts_jinja(bytes, index) => match jinja_end(text, index) {
None => {
out.push('{');
index += 1;
}
Some(end) => {
let tag = &text[index..end];
let keyword = if bytes[index + 1] == b'%' {
jinja_keyword(tag)
} else {
""
};
let markers = self.options.inject_morph_markers && !in_tag && raw_text.is_none();
if keyword == "raw" {
match text.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
Some(offset) => {
let stop = end + offset + "{% endraw %}".len();
out.push_str(&text[index..stop]);
index = stop;
}
None => {
out.push_str(tag);
index = end;
}
}
} else {
if keyword == "endfor" && !in_tag && !self.loops.is_empty() {
self.loops.pop();
}
if keyword == "for" && self.options.smart_wire_keys && self.alias_loops && !in_tag {
let alias = format!("lw_loop_{}", self.loop_occurrence);
self.loop_occurrence += 1;
if markers {
out.push_str(BLOCK_START);
}
out.push_str(tag);
out.push_str("{% set ");
out.push_str(&alias);
out.push_str(" = loop %}");
self.loops.push(alias);
} else if (keyword == "if" || keyword == "for") && markers {
out.push_str(BLOCK_START);
out.push_str(tag);
} else if (keyword == "endif" || keyword == "endfor") && markers {
out.push_str(tag);
out.push_str(BLOCK_END);
} else {
out.push_str(tag);
}
index = end;
}
}
},
b'@' => match self.directive(text, index) {
Some((consumed, replacement)) => {
out.push_str(&replacement);
index += consumed;
}
None => {
out.push('@');
index += 1;
}
},
_ => {
let start = index;
index += 1;
while index < bytes.len() && !matches!(bytes[index], b'@' | b'<' | b'{' | b'"' | b'\'' | b'>') {
index += 1;
}
out.push_str(&text[start..index]);
}
}
}
out
}
fn directive(&mut self, text: &str, at: usize) -> Option<(usize, String)> {
let bytes = text.as_bytes();
if at > 0 && bytes[at - 1] == b'@' {
return None;
}
let mut word_end = at + 1;
if word_end >= bytes.len() || !(bytes[word_end].is_ascii_alphabetic() || bytes[word_end] == b'_') {
return None;
}
word_end += 1;
while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
word_end += 1;
}
let word = &text[at + 1..word_end];
let mut cursor = word_end;
while cursor < bytes.len() && (bytes[cursor] == b' ' || bytes[cursor] == b'\t') {
cursor += 1;
}
let mut expression: Option<&str> = None;
let mut after = word_end;
if cursor < bytes.len() && bytes[cursor] == b'(' {
let end = balanced_paren(text, cursor)?;
expression = Some(&text[cursor + 1..end - 1]);
after = end;
}
let word_consumed = word_end - at;
match word {
"this" => Some((word_consumed, "$wire".to_string())),
"entangle" => {
let value = expression?;
let mut replacement = format!("$wire.entangle({})", value.trim());
let mut consumed = after;
for suffix in [".live", ".defer"] {
if text.get(after..).is_some_and(|rest| rest.starts_with(suffix)) {
replacement.push_str(suffix);
consumed += suffix.len();
break;
}
}
Some((consumed - at, replacement))
}
"livewire" => {
let arguments = expression?;
let replacement = self.livewire_expression(arguments)?;
Some((after - at, replacement))
}
"assets" => Some((word_consumed, "{% livewire_assets %}".to_string())),
"endassets" => Some((word_consumed, "{% endlivewire_assets %}".to_string())),
"script" => Some((word_consumed, "{% livewire_script %}".to_string())),
"endscript" => Some((word_consumed, "{% endlivewire_script %}".to_string())),
"teleport" => {
let selector = directive_value(expression);
Some((after - at, format!("<template x-teleport=\"{selector}\">")))
}
"endteleport" => Some((word_consumed, "</template>".to_string())),
"persist" => {
let name = directive_value(expression);
Some((after - at, format!("<div x-persist=\"{name}\">")))
}
"endpersist" => Some((word_consumed, "</div>".to_string())),
"island" => self.island(text, at, expression, after),
"livewireStyles" => Some((word_consumed, "{{ livewire_styles() }}".to_string())),
"livewireScripts" => Some((word_consumed, "{{ livewire_scripts() }}".to_string())),
"livewireScriptConfig" => Some((word_consumed, "{{ livewire_script_config() }}".to_string())),
_ => None,
}
}
fn island(&mut self, text: &str, at: usize, expression: Option<&str>, after: usize) -> Option<(usize, String)> {
let (end_at, end_after) = find_matching_endisland(text, after)?;
let options = IslandOptions::parse(expression);
let token = format!("{}-{}", self.hash, self.island_occurrence);
self.island_occurrence += 1;
let inner = self.translate(&text[after..end_at], false);
let name = options.name.clone().unwrap_or_else(|| token.clone());
let mode = options.mode.clone().unwrap_or_else(|| "morph".to_string());
let inner = match options.directive() {
Some(directive) => inject_island_attribute(&inner, directive),
None => inner,
};
let metadata = format!("type=island|name={name}|token={token}|mode={mode}");
let replacement =
format!("<!--[if FRAGMENT:{metadata}]><![endif]-->{inner}<!--[if ENDFRAGMENT:{metadata}]><![endif]-->");
Some((end_after - at, replacement))
}
fn livewire_expression(&mut self, expression: &str) -> Option<String> {
let arguments = split_top_level(expression, ',');
let name = arguments.first()?.trim();
if name.is_empty() {
return None;
}
let occurrence = self.occurrence;
self.occurrence += 1;
let params = match arguments.get(1) {
None => "{}".to_string(),
Some(argument) => convert_params(argument.trim()),
};
let mut key: Option<String> = None;
for argument in arguments.iter().skip(2) {
let argument = argument.trim();
if let Some(rest) = argument.strip_prefix("key:") {
key = Some(rest.trim().to_string());
} else if let Some(inner) = argument.strip_prefix("key(").and_then(|rest| rest.strip_suffix(')')) {
key = Some(inner.trim().to_string());
}
}
let key = key.unwrap_or_else(|| self.missing_key(occurrence));
Some(format!("{{{{ livewire({name}, {params}, {key}) }}}}"))
}
fn missing_key(&self, occurrence: usize) -> String {
if !self.options.smart_wire_keys || self.loops.is_empty() {
return "none".to_string();
}
let mut key = format!("'lw-{}-{}'", self.hash, occurrence);
for alias in &self.loops {
key.push_str(" ~ '-' ~ ");
key.push_str(alias);
key.push_str(".index0");
}
key
}
fn attribute_expression(&mut self, value: &str) -> String {
if value.is_empty() {
return "true".to_string();
}
let compiled = self.translate(value, true);
if !compiled.contains("{{") {
return jinja_string(&compiled);
}
interpolate(&compiled)
}
fn component_expression(&mut self, name: &str, attributes: &str, slot: Option<&str>) -> String {
let occurrence = self.occurrence;
self.occurrence += 1;
let mut params: Vec<(String, String)> = Vec::new();
let mut key: Option<String> = None;
for (attribute, value) in parse_attributes(attributes) {
match attribute.as_str() {
"wire:key" | "key" => {
key = Some(match value {
Some(value) => self.attribute_expression(&value),
None => "none".to_string(),
});
continue;
}
_ => {}
}
if let Some(bound) = attribute.strip_prefix(':') {
let value = match value {
None => "true".to_string(),
Some(value) => {
let trimmed = value.trim();
match strip_braces(trimmed) {
Some(inner) => inner.trim().to_string(),
None => trimmed.to_string(),
}
}
};
params.push((bound.to_string(), value));
} else {
let value = match value {
Some(value) => self.attribute_expression(&value),
None => "true".to_string(),
};
params.push((attribute, value));
}
}
if let Some(slot) = slot {
params.push(("slot".to_string(), slot.to_string()));
}
let key = key.unwrap_or_else(|| self.missing_key(occurrence));
let mut expression = String::from("{{ livewire(");
expression.push_str(&jinja_string(name));
expression.push_str(", {");
for (index, (name, value)) in params.iter().enumerate() {
if index > 0 {
expression.push_str(", ");
}
expression.push_str(&jinja_string(name));
expression.push_str(": ");
expression.push_str(value);
}
expression.push_str("}, ");
expression.push_str(&key);
expression.push_str(") }}");
expression
}
}
struct LivewireTag<'a> {
attributes: &'a str,
end: usize,
inner: Option<&'a str>,
name: &'a str,
self_closing: bool,
}
impl<'a> LivewireTag<'a> {
fn parse(text: &'a str, at: usize) -> Option<Self> {
let bounds = livewire_tag_bounds(text, at)?;
if bounds.self_closing {
return Some(Self {
attributes: &text[bounds.name_end..bounds.attributes_end],
end: bounds.tag_end,
inner: None,
name: &text[bounds.name_start..bounds.name_end],
self_closing: true,
});
}
let name = &text[bounds.name_start..bounds.name_end];
let closing = format!("</livewire:{name}>");
let close_offset = text.get(bounds.tag_end..)?.find(&closing)?;
let close_start = bounds.tag_end + close_offset;
let end = close_start + closing.len();
Some(Self {
attributes: &text[bounds.name_end..bounds.attributes_end],
end,
inner: Some(&text[bounds.tag_end..close_start]),
name,
self_closing: false,
})
}
fn compile(&self, compiler: &mut Compiler) -> Option<String> {
match self.name {
"styles" => return Some("{{ livewire_styles() }}".to_string()),
"scripts" => return Some("{{ livewire_scripts() }}".to_string()),
_ => {}
}
if self.self_closing {
return Some(compiler.component_expression(self.name, self.attributes, None));
}
let inner = self.inner?;
let inner = compiler.translate(inner, false);
let variable = format!("lw_slot_{}", compiler.slot_occurrence);
compiler.slot_occurrence += 1;
let expression = compiler.component_expression(self.name, self.attributes, Some(&variable));
Some(format!("{{% set {variable} %}}{inner}{{% endset %}}{expression}"))
}
}
struct TagBounds {
attributes_end: usize,
name_end: usize,
name_start: usize,
self_closing: bool,
tag_end: usize,
}
fn livewire_tag_bounds(text: &str, at: usize) -> Option<TagBounds> {
let prefix = "<livewire:";
if !text.get(at..)?.starts_with(prefix) {
return None;
}
let bytes = text.as_bytes();
let mut cursor = at + prefix.len();
let name_start = cursor;
while cursor < bytes.len()
&& (bytes[cursor].is_ascii_alphanumeric() || matches!(bytes[cursor], b'_' | b'.' | b'-' | b':'))
{
cursor += 1;
}
if cursor == name_start {
return None;
}
let name_end = cursor;
let mut quote: Option<u8> = None;
while cursor < bytes.len() {
let byte = bytes[cursor];
if let Some(active) = quote {
if byte == active {
quote = None;
}
cursor += 1;
continue;
}
match byte {
b'"' | b'\'' => quote = Some(byte),
b'>' => {
let self_closing = cursor > name_end && bytes[cursor - 1] == b'/';
let attributes_end = if self_closing { cursor - 1 } else { cursor };
return Some(TagBounds {
attributes_end,
name_end,
name_start,
self_closing,
tag_end: cursor + 1,
});
}
_ => {}
}
cursor += 1;
}
None
}
fn attributes_have_key(attributes: &str) -> bool {
parse_attributes(attributes)
.iter()
.any(|(name, _)| name == "wire:key" || name == "key")
}
fn parse_attributes(attributes: &str) -> Vec<(String, Option<String>)> {
let bytes = attributes.as_bytes();
let mut parsed = Vec::new();
let mut index = 0;
while index < bytes.len() {
while index < bytes.len() && bytes[index].is_ascii_whitespace() {
index += 1;
}
if index >= bytes.len() {
break;
}
if bytes[index] == b'/' {
index += 1;
continue;
}
let name_start = index;
while index < bytes.len() && !bytes[index].is_ascii_whitespace() && !matches!(bytes[index], b'=' | b'/' | b'>')
{
index += 1;
}
if index == name_start {
index += 1;
continue;
}
let name = attributes[name_start..index].to_string();
while index < bytes.len() && bytes[index].is_ascii_whitespace() {
index += 1;
}
let mut value = None;
if index < bytes.len() && bytes[index] == b'=' {
index += 1;
while index < bytes.len() && bytes[index].is_ascii_whitespace() {
index += 1;
}
if index < bytes.len() && (bytes[index] == b'"' || bytes[index] == b'\'') {
let quote = bytes[index];
index += 1;
let start = index;
while index < bytes.len() && bytes[index] != quote {
index += 1;
}
value = Some(attributes[start..index].to_string());
if index < bytes.len() {
index += 1;
}
} else {
let start = index;
while index < bytes.len() && !bytes[index].is_ascii_whitespace() {
index += 1;
}
value = Some(attributes[start..index].to_string());
}
}
parsed.push((name, value));
}
parsed
}
struct IslandOptions {
defer: bool,
lazy: bool,
mode: Option<String>,
name: Option<String>,
}
impl IslandOptions {
fn parse(expression: Option<&str>) -> Self {
let mut options = Self {
defer: false,
lazy: false,
mode: None,
name: None,
};
if let Some(expression) = expression {
for part in split_top_level(expression, ',') {
let Some((key, value)) = part.split_once(':') else {
continue;
};
let key = key.trim();
let value = value.trim();
match key {
"name" => options.name = Some(unquote(value).unwrap_or(value).to_string()),
"mode" => options.mode = Some(unquote(value).unwrap_or(value).to_string()),
"lazy" => options.lazy = value == "true",
"defer" => options.defer = value == "true",
_ => {}
}
}
}
options
}
fn directive(&self) -> Option<&'static str> {
if self.lazy {
Some("wire:intersect.once=\"__lazyLoadIsland\"")
} else if self.defer {
Some("wire:init=\"__lazyLoadIsland\"")
} else {
None
}
}
}
fn find_matching_endisland(text: &str, from: usize) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut index = from;
let mut depth = 0usize;
while index < bytes.len() {
if bytes[index] == b'{' && starts_jinja(bytes, index) {
index = jinja_end(text, index)?;
continue;
}
if bytes[index] == b'@' {
let mut word_end = index + 1;
while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
word_end += 1;
}
match &text[index + 1..word_end] {
"island" => {
depth += 1;
index = word_end;
continue;
}
"endisland" if depth == 0 => return Some((index, word_end)),
"endisland" => {
depth -= 1;
index = word_end;
continue;
}
_ => {}
}
index = word_end;
continue;
}
index += 1;
}
None
}
fn loops_need_aliases(source: &str) -> bool {
let bytes = source.as_bytes();
let mut index = 0;
let mut depth = 0usize;
while index < bytes.len() {
if bytes[index] == b'{'
&& starts_jinja(bytes, index)
&& let Some(end) = jinja_end(source, index)
{
let keyword = if bytes[index + 1] == b'%' {
jinja_keyword(&source[index..end])
} else {
""
};
match keyword {
"for" => depth += 1,
"endfor" => depth = depth.saturating_sub(1),
"raw" => {
if let Some(offset) = source.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
index = end + offset + "{% endraw %}".len();
continue;
}
}
_ => {}
}
index = end;
continue;
}
if bytes[index] == b'<'
&& let Some(bounds) = livewire_tag_bounds(source, index)
{
if depth > 0 && !attributes_have_key(&source[bounds.name_end..bounds.attributes_end]) {
return true;
}
index = bounds.tag_end;
continue;
}
index += 1;
}
false
}
fn inject_island_attribute(html: &str, attribute: &str) -> String {
let bytes = html.as_bytes();
let mut index = 0;
while index + 1 < bytes.len() {
if bytes[index] == b'<' && bytes[index + 1].is_ascii_alphabetic() {
let mut cursor = index + 2;
while cursor < bytes.len() && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'-') {
cursor += 1;
}
let mut out = String::with_capacity(html.len() + attribute.len() + 1);
out.push_str(&html[..cursor]);
out.push(' ');
out.push_str(attribute);
out.push_str(&html[cursor..]);
return out;
}
index += 1;
}
format!("<span {attribute}>{html}</span>")
}
fn directive_value(expression: Option<&str>) -> String {
match expression {
None => String::new(),
Some(expression) => {
let trimmed = expression.trim();
if let Some(inner) = unquote(trimmed) {
escape_attribute(inner)
} else if trimmed.starts_with("{{") {
trimmed.to_string()
} else {
format!("{{{{ {trimmed} }}}}")
}
}
}
}
fn escape_attribute(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for character in value.chars() {
match character {
'&' => escaped.push_str("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
other => escaped.push(other),
}
}
escaped
}
fn convert_params(value: &str) -> String {
if value.is_empty() {
return "{}".to_string();
}
if value.starts_with('[') && value.ends_with(']') {
return convert_php_array(&value[1..value.len() - 1]);
}
if value.starts_with('{') && value.ends_with('}') {
return convert_object(&value[1..value.len() - 1]);
}
if let Some(inner) = value.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
return convert_php_array(inner);
}
value.to_string()
}
fn convert_php_array(inner: &str) -> String {
let mut pairs: Vec<(Option<String>, String)> = Vec::new();
for entry in split_top_level(inner, ',') {
let entry = entry.trim();
if entry.is_empty() {
continue;
}
if let Some(position) = find_top_level(entry, "=>") {
let key = entry[..position].trim();
let value = entry[position + 2..].trim();
pairs.push((Some(unquote(key).unwrap_or(key).to_string()), convert_value(value)));
} else {
pairs.push((None, convert_value(entry)));
}
}
if pairs.is_empty() {
return "{}".to_string();
}
if pairs.iter().any(|(key, _)| key.is_some()) {
let mut out = String::from("{");
for (index, (key, value)) in pairs.iter().enumerate() {
if index > 0 {
out.push_str(", ");
}
let key = key.clone().unwrap_or_else(|| index.to_string());
out.push_str(&jinja_string(&key));
out.push_str(": ");
out.push_str(value);
}
out.push('}');
return out;
}
let values: Vec<String> = pairs.into_iter().map(|(_, value)| value).collect();
format!("[{}]", values.join(", "))
}
fn convert_object(inner: &str) -> String {
let mut pairs: Vec<(String, String)> = Vec::new();
for entry in split_top_level(inner, ',') {
let entry = entry.trim();
if entry.is_empty() {
continue;
}
let Some(position) = find_top_level(entry, ":") else {
return format!("{{{inner}}}");
};
let key = entry[..position].trim();
let value = entry[position + 1..].trim();
pairs.push((unquote(key).unwrap_or(key).to_string(), convert_value(value)));
}
let mut out = String::from("{");
for (index, (key, value)) in pairs.iter().enumerate() {
if index > 0 {
out.push_str(", ");
}
out.push_str(&jinja_string(key));
out.push_str(": ");
out.push_str(value);
}
out.push('}');
out
}
fn convert_value(value: &str) -> String {
let trimmed = value.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') && trimmed.len() >= 2 {
return convert_php_array(&trimmed[1..trimmed.len() - 1]);
}
if trimmed.starts_with('{') && trimmed.ends_with('}') && trimmed.len() >= 2 {
return convert_object(&trimmed[1..trimmed.len() - 1]);
}
if let Some(inner) = trimmed.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
return convert_php_array(inner);
}
trimmed.to_string()
}
fn interpolate(compiled: &str) -> String {
let bytes = compiled.as_bytes();
let mut parts: Vec<(bool, &str)> = Vec::new();
let mut index = 0;
let mut literal_start = 0;
while index + 1 < bytes.len() {
if bytes[index] == b'{'
&& bytes[index + 1] == b'{'
&& let Some(end) = jinja_end(compiled, index)
{
if index > literal_start {
parts.push((false, &compiled[literal_start..index]));
}
parts.push((true, &compiled[index + 2..end - 2]));
index = end;
literal_start = end;
continue;
}
index += 1;
}
if literal_start < compiled.len() {
parts.push((false, &compiled[literal_start..]));
}
match parts.as_slice() {
[] => "''".to_string(),
[(true, expression)] => expression.trim().to_string(),
[(false, literal)] => jinja_string(literal),
_ => {
let mut out = String::new();
for (index, (is_expression, part)) in parts.iter().enumerate() {
if index > 0 {
out.push_str(" ~ ");
}
if *is_expression {
out.push('(');
out.push_str(part.trim());
out.push(')');
} else if part.is_empty() {
out.push_str("''");
} else {
out.push_str(&jinja_string(part));
}
}
out
}
}
}
fn jinja_string(value: &str) -> String {
let mut quoted = String::with_capacity(value.len() + 2);
quoted.push('\'');
for character in value.chars() {
match character {
'\\' => quoted.push_str("\\\\"),
'\'' => quoted.push_str("\\'"),
other => quoted.push(other),
}
}
quoted.push('\'');
quoted
}
fn unquote(value: &str) -> Option<&str> {
let bytes = value.as_bytes();
if bytes.len() < 2 {
return None;
}
let first = bytes[0];
let last = bytes[bytes.len() - 1];
if first != last || !matches!(first, b'"' | b'\'') {
return None;
}
Some(&value[1..value.len() - 1])
}
fn strip_braces(value: &str) -> Option<&str> {
value.strip_prefix("{{")?.strip_suffix("}}")
}
fn starts_jinja(bytes: &[u8], index: usize) -> bool {
index + 1 < bytes.len() && matches!(bytes[index + 1], b'{' | b'%' | b'#')
}
fn jinja_end(text: &str, start: usize) -> Option<usize> {
let bytes = text.as_bytes();
let closer: &[u8] = match bytes.get(start + 1) {
Some(b'{') => b"}}",
Some(b'%') => b"%}",
Some(b'#') => b"#}",
_ => return None,
};
let mut index = start + 2;
let mut quote: Option<u8> = None;
while index < bytes.len() {
if let Some(active) = quote {
if bytes[index] == b'\\' {
index = (index + 2).min(bytes.len());
continue;
}
if bytes[index] == active {
quote = None;
}
index += 1;
continue;
}
match bytes[index] {
b'"' | b'\'' => quote = Some(bytes[index]),
_ => {
if bytes[index..].starts_with(closer) {
return Some(index + closer.len());
}
}
}
index += 1;
}
None
}
fn jinja_keyword(tag: &str) -> &str {
let inner = tag.strip_prefix("{%").unwrap_or(tag);
let inner = inner.strip_suffix("%}").unwrap_or(inner);
let inner = inner.trim().trim_start_matches('-').trim_start();
let end = inner
.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.unwrap_or(inner.len());
&inner[..end]
}
fn balanced_paren(text: &str, open: usize) -> Option<usize> {
let bytes = text.as_bytes();
let mut index = open;
let mut depth = 0usize;
let mut quote: Option<u8> = None;
while index < bytes.len() {
if let Some(active) = quote {
if bytes[index] == b'\\' {
index = (index + 2).min(bytes.len());
continue;
}
if bytes[index] == active {
quote = None;
}
index += 1;
continue;
}
match bytes[index] {
b'"' | b'\'' => quote = Some(bytes[index]),
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
return Some(index + 1);
}
}
_ => {}
}
index += 1;
}
None
}
fn split_top_level(value: &str, separator: char) -> Vec<&str> {
let bytes = value.as_bytes();
let separator = separator as u8;
let mut parts = Vec::new();
let mut start = 0;
let mut index = 0;
let mut depth = 0usize;
let mut quote: Option<u8> = None;
while index < bytes.len() {
if let Some(active) = quote {
if bytes[index] == b'\\' {
index = (index + 2).min(bytes.len());
continue;
}
if bytes[index] == active {
quote = None;
}
index += 1;
continue;
}
match bytes[index] {
b'"' | b'\'' => quote = Some(bytes[index]),
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth = depth.saturating_sub(1),
byte if byte == separator && depth == 0 => {
parts.push(&value[start..index]);
start = index + 1;
}
_ => {}
}
index += 1;
}
parts.push(&value[start..]);
parts
}
fn find_top_level(value: &str, needle: &str) -> Option<usize> {
let bytes = value.as_bytes();
let mut index = 0;
let mut depth = 0usize;
let mut quote: Option<u8> = None;
while index < bytes.len() {
if let Some(active) = quote {
if bytes[index] == b'\\' {
index = (index + 2).min(bytes.len());
continue;
}
if bytes[index] == active {
quote = None;
}
index += 1;
continue;
}
match bytes[index] {
b'"' | b'\'' => quote = Some(bytes[index]),
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth = depth.saturating_sub(1),
_ => {
if depth == 0 && value[index..].starts_with(needle) {
return Some(index);
}
}
}
index += 1;
}
None
}
#[cfg(test)]
mod tests {
use super::*;
const NO_OPTIONS: CompileOptions = CompileOptions {
inject_morph_markers: false,
smart_wire_keys: false,
};
const MORPH: CompileOptions = CompileOptions {
inject_morph_markers: true,
smart_wire_keys: false,
};
const KEYS: CompileOptions = CompileOptions {
inject_morph_markers: false,
smart_wire_keys: true,
};
const ALL: CompileOptions = CompileOptions {
inject_morph_markers: true,
smart_wire_keys: true,
};
fn identity() -> TemplateIdentity {
TemplateIdentity {
name: "counter".to_string(),
source: "livewire.counter".to_string(),
}
}
fn hash() -> String {
identity().hash()
}
fn run(source: &str, options: CompileOptions) -> String {
compile(source, &identity(), options)
}
#[test]
fn a_self_closing_tag_becomes_the_livewire_expression() {
let source = r#"<div><livewire:post-row :post="post" wire:key="row-1" class="p-4" /></div>"#;
assert_eq!(
run(source, NO_OPTIONS),
r#"<div>{{ livewire('post-row', {'post': post, 'class': 'p-4'}, 'row-1') }}</div>"#
);
}
#[test]
fn a_paired_tag_compiles_its_slot() {
assert_eq!(
run("<livewire:counter>Hello</livewire:counter>", NO_OPTIONS),
"{% set lw_slot_0 %}Hello{% endset %}{{ livewire('counter', {'slot': lw_slot_0}, none) }}"
);
}
#[test]
fn slot_content_is_compiled_too() {
assert_eq!(
run(
"<livewire:counter>@this.now() @entangle('open')</livewire:counter>",
NO_OPTIONS
),
"{% set lw_slot_0 %}$wire.now() $wire.entangle('open'){% endset %}\
{{ livewire('counter', {'slot': lw_slot_0}, none) }}"
);
}
#[test]
fn the_livewire_directive_accepts_php_arrays_keys_and_json_objects() {
assert_eq!(
run("@livewire('counter', ['step' => 2], key: 'c1')", NO_OPTIONS),
"{{ livewire('counter', {'step': 2}, 'c1') }}"
);
assert_eq!(
run(r#"@livewire("counter", {"step": 2})"#, NO_OPTIONS),
r#"{{ livewire("counter", {'step': 2}, none) }}"#
);
assert_eq!(
run("@livewire('counter', [], key('c2'))", NO_OPTIONS),
"{{ livewire('counter', {}, 'c2') }}"
);
}
#[test]
fn the_livewire_directive_converts_nested_arrays() {
assert_eq!(
run("@livewire('x', ['a' => ['b' => 1], 'list' => [1, 2]])", NO_OPTIONS),
"{{ livewire('x', {'a': {'b': 1}, 'list': [1, 2]}, none) }}"
);
}
#[test]
fn this_becomes_wire() {
assert_eq!(
run(r#"<button wire:click="@this.increment">Go</button>"#, NO_OPTIONS),
r#"<button wire:click="$wire.increment">Go</button>"#
);
}
#[test]
fn entangle_becomes_wire_entangle_with_its_modifier() {
assert_eq!(
run(r#"<div x-data="{ open: @entangle('open') }"></div>"#, NO_OPTIONS),
r#"<div x-data="{ open: $wire.entangle('open') }"></div>"#
);
assert_eq!(run("@entangle('open').live", NO_OPTIONS), "$wire.entangle('open').live");
assert_eq!(
run("@entangle('open').defer", NO_OPTIONS),
"$wire.entangle('open').defer"
);
}
#[test]
fn assets_and_scripts_become_jinja_blocks() {
assert_eq!(
run("@assets<script src=\"/a.js\"></script>@endassets", NO_OPTIONS),
"{% livewire_assets %}<script src=\"/a.js\"></script>{% endlivewire_assets %}"
);
assert_eq!(
run("@script console.log('a') @endscript", NO_OPTIONS),
"{% livewire_script %} console.log('a') {% endlivewire_script %}"
);
}
#[test]
fn teleport_becomes_a_template() {
assert_eq!(
run("@teleport('#modal')<div>x</div>@endteleport", NO_OPTIONS),
"<template x-teleport=\"#modal\"><div>x</div></template>"
);
}
#[test]
fn persist_becomes_a_div() {
assert_eq!(
run("@persist('player')<div>x</div>@endpersist", NO_OPTIONS),
"<div x-persist=\"player\"><div>x</div></div>"
);
}
#[test]
fn an_island_emits_fragment_markers() {
let named = format!("{}-0", hash());
assert_eq!(
run("@island(name: 'timer')<p>t</p>@endisland", NO_OPTIONS),
format!(
"<!--[if FRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->\
<p>t</p>\
<!--[if ENDFRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->"
)
);
assert_eq!(
run("@island<p>t</p>@endisland", NO_OPTIONS),
format!(
"<!--[if FRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->\
<p>t</p>\
<!--[if ENDFRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->"
)
);
}
#[test]
fn islands_nest_with_distinct_tokens() {
let output = run(
"@island(name: 'outer')<div>@island(name: 'inner')x@endisland</div>@endisland",
NO_OPTIONS,
);
assert!(output.contains(&format!("name=outer|token={}-0", hash())));
assert!(output.contains(&format!("name=inner|token={}-1", hash())));
let inner_end = output.find("ENDFRAGMENT:type=island|name=inner").unwrap();
let outer_end = output.rfind("ENDFRAGMENT:type=island|name=outer").unwrap();
assert!(inner_end < outer_end);
}
#[test]
fn an_island_carries_its_mode() {
assert!(run("@island(name: 'feed', mode: 'append')x@endisland", NO_OPTIONS).contains("mode=append"));
}
#[test]
fn a_lazy_island_gets_a_load_attribute() {
assert!(
run("@island(defer: true)<p>x</p>@endisland", NO_OPTIONS)
.contains(r#"<p wire:init="__lazyLoadIsland">x</p>"#)
);
assert!(
run("@island(lazy: true)plain@endisland", NO_OPTIONS)
.contains(r#"<span wire:intersect.once="__lazyLoadIsland">plain</span>"#)
);
}
#[test]
fn the_asset_helpers_become_expressions() {
assert_eq!(
run("@livewireStyles@livewireScripts@livewireScriptConfig", NO_OPTIONS),
"{{ livewire_styles() }}{{ livewire_scripts() }}{{ livewire_script_config() }}"
);
}
#[test]
fn unknown_directives_pass_through_byte_for_byte() {
for source in [
"@if ($show) <p>@endif</p>",
"user@example.com",
"@unknownDirective('x')",
"@@livewire('counter')",
"@foreach($items as $item)@endforeach",
] {
assert_eq!(run(source, ALL), source, "source: {source}");
}
}
#[test]
fn morph_markers_wrap_conditionals_and_loops() {
assert_eq!(
run("{% if show %}a{% endif %}", MORPH),
format!("{BLOCK_START}{{% if show %}}a{{% endif %}}{BLOCK_END}")
);
assert_eq!(
run("{%- for x in y -%}a{%- endfor -%}", MORPH),
format!("{BLOCK_START}{{%- for x in y -%}}a{{%- endfor -%}}{BLOCK_END}")
);
}
#[test]
fn morph_markers_nest() {
assert_eq!(
run("{% if a %}{% for x in y %}z{% endfor %}{% endif %}", MORPH),
format!(
"{BLOCK_START}{{% if a %}}{BLOCK_START}{{% for x in y %}}z{{% endfor %}}{BLOCK_END}{{% endif %}}{BLOCK_END}"
)
);
}
#[test]
fn a_block_inside_an_attribute_gets_no_marker() {
let source = r#"<div class="{% if active %}on{% endif %}">x</div>"#;
assert_eq!(run(source, MORPH), source);
}
#[test]
fn script_contents_carry_no_morph_markers() {
let source = "<script>{% if a %}x{% endif %}</script>";
assert_eq!(run(source, MORPH), source);
}
#[test]
fn smart_keys_use_the_enclosing_loop() {
let output = run(
r#"<div>{% for post in posts %}<livewire:post-row :post="post" />{% endfor %}</div>"#,
KEYS,
);
assert!(output.contains("{% set lw_loop_0 = loop %}"));
assert!(output.contains(&format!("'lw-{}-0' ~ '-' ~ lw_loop_0.index0", hash())));
assert!(output.contains("{{ livewire('post-row', {'post': post}, "));
assert!(!output.contains(BLOCK_START));
}
#[test]
fn nested_loops_give_distinct_keys() {
let output = run(
"{% for a in xs %}{% for b in ys %}<livewire:row />{% endfor %}{% endfor %}",
KEYS,
);
assert!(output.contains("{% set lw_loop_0 = loop %}"));
assert!(output.contains("{% set lw_loop_1 = loop %}"));
assert!(output.contains(&format!(
"'lw-{}-0' ~ '-' ~ lw_loop_0.index0 ~ '-' ~ lw_loop_1.index0",
hash()
)));
}
#[test]
fn both_options_off_leave_keys_and_comments_out() {
assert_eq!(
run("{% for a in xs %}<livewire:row />{% endfor %}", NO_OPTIONS),
"{% for a in xs %}{{ livewire('row', {}, none) }}{% endfor %}"
);
assert_eq!(run("{% if a %}b{% endif %}", NO_OPTIONS), "{% if a %}b{% endif %}");
}
#[test]
fn an_explicit_key_always_wins() {
assert_eq!(
run(
"{% for p in ps %}<livewire:row wire:key=\"k-{{ p.id }}\" />{% endfor %}",
KEYS
),
"{% for p in ps %}{{ livewire('row', {}, 'k-' ~ (p.id)) }}{% endfor %}"
);
}
#[test]
fn existing_jinja_is_untouched() {
let source = "{% set x = 1 %}{{ x }}{# note #}";
assert_eq!(run(source, ALL), source);
}
#[test]
fn wire_island_attributes_pass_through() {
let source = r#"<button wire:click="increment" wire:island="foo">Go</button>"#;
assert_eq!(run(source, ALL), source);
}
#[test]
fn truncated_input_is_left_as_it_stands() {
for source in [
"@island",
"@island(",
"@endisland",
"@livewire(",
"@teleport(",
"@entangle(",
"<livewire:counter",
"<livewire:counter>",
"{% if x",
"{{ x",
] {
assert_eq!(run(source, ALL), source, "source: {source}");
}
}
#[test]
fn compiling_the_same_source_twice_gives_the_same_string() {
let source = "<livewire:row />@island(name: 'a')x@endisland";
assert_eq!(run(source, ALL), run(source, ALL));
}
}