1#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct TemplateIdentity {
31 pub name: String,
33 pub source: String,
35}
36
37impl TemplateIdentity {
38 fn hash(&self) -> String {
40 let seed = if self.source.is_empty() {
41 self.name.as_str()
42 } else {
43 self.source.as_str()
44 };
45
46 let mut hash: u32 = 0x811c_9dc5;
47
48 for byte in seed.as_bytes() {
49 hash ^= u32::from(*byte);
50 hash = hash.wrapping_mul(0x0100_0193);
51 }
52
53 format!("{hash:08x}")
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct CompileOptions {
60 pub inject_morph_markers: bool,
62 pub smart_wire_keys: bool,
64}
65
66pub fn compile(source: &str, identity: &TemplateIdentity, options: CompileOptions) -> String {
68 let mut compiler = Compiler::new(identity.hash(), options, loops_need_aliases(source));
69
70 compiler.translate(source, false)
71}
72
73const BLOCK_START: &str = "<!--[if BLOCK]><![endif]-->";
75
76const BLOCK_END: &str = "<!--[if ENDBLOCK]><![endif]-->";
78
79struct Compiler {
81 alias_loops: bool,
83 depth: usize,
85 hash: String,
87 island_occurrence: usize,
89 loop_occurrence: usize,
91 loops: Vec<String>,
93 occurrence: usize,
95 options: CompileOptions,
97 slot_occurrence: usize,
99}
100
101impl Compiler {
102 fn new(hash: String, options: CompileOptions, alias_loops: bool) -> Self {
104 Self {
105 alias_loops,
106 depth: 0,
107 hash,
108 island_occurrence: 0,
109 loop_occurrence: 0,
110 loops: Vec::new(),
111 occurrence: 0,
112 options,
113 slot_occurrence: 0,
114 }
115 }
116
117 fn translate(&mut self, text: &str, in_tag: bool) -> String {
119 if self.depth > 64 {
120 return text.to_string();
121 }
122
123 self.depth += 1;
124
125 let result = self.translate_inner(text, in_tag);
126
127 self.depth -= 1;
128
129 result
130 }
131
132 fn translate_inner(&mut self, text: &str, start_in_tag: bool) -> String {
134 let bytes = text.as_bytes();
135 let mut out = String::with_capacity(text.len() + 64);
136 let mut index = 0;
137 let mut in_tag = start_in_tag;
138 let mut quote: Option<u8> = None;
139 let mut raw_text: Option<String> = None;
140 let mut pending_tag: Option<(String, bool)> = None;
141
142 while index < bytes.len() {
143 if let Some(active_quote) = quote {
144 if bytes[index] == active_quote {
145 quote = None;
146 out.push(char::from(active_quote));
147 index += 1;
148 continue;
149 }
150
151 if bytes[index] == b'@' {
152 if let Some((consumed, replacement)) = self.directive(text, index) {
153 out.push_str(&replacement);
154 index += consumed;
155 } else {
156 out.push('@');
157 index += 1;
158 }
159 continue;
160 }
161
162 if bytes[index] == b'{' && starts_jinja(bytes, index) {
163 match jinja_end(text, index) {
164 Some(end) => {
165 out.push_str(&text[index..end]);
166 index = end;
167 }
168 None => {
169 out.push('{');
170 index += 1;
171 }
172 }
173 continue;
174 }
175
176 let start = index;
177 index += 1;
178
179 while index < bytes.len()
180 && bytes[index] != b'@'
181 && bytes[index] != b'{'
182 && bytes[index] != active_quote
183 {
184 index += 1;
185 }
186
187 out.push_str(&text[start..index]);
188 continue;
189 }
190
191 match bytes[index] {
192 b'<' if !in_tag => {
193 if let Some(tag) = LivewireTag::parse(text, index) {
194 match tag.compile(self) {
195 Some(compiled) => {
196 out.push_str(&compiled);
197 index = tag.end;
198 }
199 None => {
200 out.push('<');
201 index += 1;
202 }
203 }
204 continue;
205 }
206
207 let mut cursor = index + 1;
208 let closing = cursor < bytes.len() && bytes[cursor] == b'/';
209
210 if closing {
211 cursor += 1;
212 }
213
214 let name_start = cursor;
215
216 while cursor < bytes.len() && bytes[cursor].is_ascii_alphanumeric() {
217 cursor += 1;
218 }
219
220 let opens_tag =
221 cursor > name_start || (cursor < bytes.len() && matches!(bytes[cursor], b'!' | b'?'));
222
223 if opens_tag {
224 in_tag = true;
225 pending_tag = if cursor > name_start {
226 Some((text[name_start..cursor].to_ascii_lowercase(), closing))
227 } else {
228 None
229 };
230 }
231
232 out.push('<');
233 index += 1;
234 }
235 b'>' if in_tag => {
236 in_tag = false;
237
238 if let Some((name, closing)) = pending_tag.take()
239 && (name == "script" || name == "style")
240 {
241 let self_closing = index > 0 && bytes[index - 1] == b'/';
242
243 if closing {
244 if raw_text.as_deref() == Some(name.as_str()) {
245 raw_text = None;
246 }
247 } else if !self_closing {
248 raw_text = Some(name);
249 }
250 }
251
252 out.push('>');
253 index += 1;
254 }
255 b'"' | b'\'' if in_tag => {
256 quote = Some(bytes[index]);
257 out.push(char::from(bytes[index]));
258 index += 1;
259 }
260 b'{' if starts_jinja(bytes, index) => match jinja_end(text, index) {
261 None => {
262 out.push('{');
263 index += 1;
264 }
265 Some(end) => {
266 let tag = &text[index..end];
267 let keyword = if bytes[index + 1] == b'%' {
268 jinja_keyword(tag)
269 } else {
270 ""
271 };
272 let markers = self.options.inject_morph_markers && !in_tag && raw_text.is_none();
273
274 if keyword == "raw" {
275 match text.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
276 Some(offset) => {
277 let stop = end + offset + "{% endraw %}".len();
278 out.push_str(&text[index..stop]);
279 index = stop;
280 }
281 None => {
282 out.push_str(tag);
283 index = end;
284 }
285 }
286 } else {
287 if keyword == "endfor" && !in_tag && !self.loops.is_empty() {
288 self.loops.pop();
289 }
290
291 if keyword == "for" && self.options.smart_wire_keys && self.alias_loops && !in_tag {
292 let alias = format!("lw_loop_{}", self.loop_occurrence);
293 self.loop_occurrence += 1;
294
295 if markers {
296 out.push_str(BLOCK_START);
297 }
298
299 out.push_str(tag);
300 out.push_str("{% set ");
301 out.push_str(&alias);
302 out.push_str(" = loop %}");
303 self.loops.push(alias);
304 } else if (keyword == "if" || keyword == "for") && markers {
305 out.push_str(BLOCK_START);
306 out.push_str(tag);
307 } else if (keyword == "endif" || keyword == "endfor") && markers {
308 out.push_str(tag);
309 out.push_str(BLOCK_END);
310 } else {
311 out.push_str(tag);
312 }
313
314 index = end;
315 }
316 }
317 },
318 b'@' => match self.directive(text, index) {
319 Some((consumed, replacement)) => {
320 out.push_str(&replacement);
321 index += consumed;
322 }
323 None => {
324 out.push('@');
325 index += 1;
326 }
327 },
328 _ => {
329 let start = index;
330 index += 1;
331
332 while index < bytes.len() && !matches!(bytes[index], b'@' | b'<' | b'{' | b'"' | b'\'' | b'>') {
333 index += 1;
334 }
335
336 out.push_str(&text[start..index]);
337 }
338 }
339 }
340
341 out
342 }
343
344 fn directive(&mut self, text: &str, at: usize) -> Option<(usize, String)> {
346 let bytes = text.as_bytes();
347
348 if at > 0 && bytes[at - 1] == b'@' {
349 return None;
350 }
351
352 let mut word_end = at + 1;
353
354 if word_end >= bytes.len() || !(bytes[word_end].is_ascii_alphabetic() || bytes[word_end] == b'_') {
355 return None;
356 }
357
358 word_end += 1;
359
360 while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
361 word_end += 1;
362 }
363
364 let word = &text[at + 1..word_end];
365 let mut cursor = word_end;
366
367 while cursor < bytes.len() && (bytes[cursor] == b' ' || bytes[cursor] == b'\t') {
368 cursor += 1;
369 }
370
371 let mut expression: Option<&str> = None;
372 let mut after = word_end;
373
374 if cursor < bytes.len() && bytes[cursor] == b'(' {
375 let end = balanced_paren(text, cursor)?;
376 expression = Some(&text[cursor + 1..end - 1]);
377 after = end;
378 }
379
380 let word_consumed = word_end - at;
381
382 match word {
383 "this" => Some((word_consumed, "$wire".to_string())),
384 "entangle" => {
385 let value = expression?;
386 let mut replacement = format!("$wire.entangle({})", value.trim());
387 let mut consumed = after;
388
389 for suffix in [".live", ".defer"] {
390 if text.get(after..).is_some_and(|rest| rest.starts_with(suffix)) {
391 replacement.push_str(suffix);
392 consumed += suffix.len();
393 break;
394 }
395 }
396
397 Some((consumed - at, replacement))
398 }
399 "livewire" => {
400 let arguments = expression?;
401 let replacement = self.livewire_expression(arguments)?;
402
403 Some((after - at, replacement))
404 }
405 "assets" => Some((word_consumed, "{% livewire_assets %}".to_string())),
406 "endassets" => Some((word_consumed, "{% endlivewire_assets %}".to_string())),
407 "script" => Some((word_consumed, "{% livewire_script %}".to_string())),
408 "endscript" => Some((word_consumed, "{% endlivewire_script %}".to_string())),
409 "teleport" => {
410 let selector = directive_value(expression);
411 Some((after - at, format!("<template x-teleport=\"{selector}\">")))
412 }
413 "endteleport" => Some((word_consumed, "</template>".to_string())),
414 "persist" => {
415 let name = directive_value(expression);
416 Some((after - at, format!("<div x-persist=\"{name}\">")))
417 }
418 "endpersist" => Some((word_consumed, "</div>".to_string())),
419 "island" => self.island(text, at, expression, after),
420 "livewireStyles" => Some((word_consumed, "{{ livewire_styles() }}".to_string())),
421 "livewireScripts" => Some((word_consumed, "{{ livewire_scripts() }}".to_string())),
422 "livewireScriptConfig" => Some((word_consumed, "{{ livewire_script_config() }}".to_string())),
423 _ => None,
424 }
425 }
426
427 fn island(&mut self, text: &str, at: usize, expression: Option<&str>, after: usize) -> Option<(usize, String)> {
429 let (end_at, end_after) = find_matching_endisland(text, after)?;
430 let options = IslandOptions::parse(expression);
431
432 let token = format!("{}-{}", self.hash, self.island_occurrence);
433 self.island_occurrence += 1;
434
435 let inner = self.translate(&text[after..end_at], false);
436
437 let name = options.name.clone().unwrap_or_else(|| token.clone());
438 let mode = options.mode.clone().unwrap_or_else(|| "morph".to_string());
439
440 let inner = match options.directive() {
441 Some(directive) => inject_island_attribute(&inner, directive),
442 None => inner,
443 };
444
445 let metadata = format!("type=island|name={name}|token={token}|mode={mode}");
446 let replacement =
447 format!("<!--[if FRAGMENT:{metadata}]><![endif]-->{inner}<!--[if ENDFRAGMENT:{metadata}]><![endif]-->");
448
449 Some((end_after - at, replacement))
450 }
451
452 fn livewire_expression(&mut self, expression: &str) -> Option<String> {
454 let arguments = split_top_level(expression, ',');
455 let name = arguments.first()?.trim();
456
457 if name.is_empty() {
458 return None;
459 }
460
461 let occurrence = self.occurrence;
462 self.occurrence += 1;
463
464 let params = match arguments.get(1) {
465 None => "{}".to_string(),
466 Some(argument) => convert_params(argument.trim()),
467 };
468
469 let mut key: Option<String> = None;
470
471 for argument in arguments.iter().skip(2) {
472 let argument = argument.trim();
473
474 if let Some(rest) = argument.strip_prefix("key:") {
475 key = Some(rest.trim().to_string());
476 } else if let Some(inner) = argument.strip_prefix("key(").and_then(|rest| rest.strip_suffix(')')) {
477 key = Some(inner.trim().to_string());
478 }
479 }
480
481 let key = key.unwrap_or_else(|| self.missing_key(occurrence));
482
483 Some(format!("{{{{ livewire({name}, {params}, {key}) }}}}"))
484 }
485
486 fn missing_key(&self, occurrence: usize) -> String {
488 if !self.options.smart_wire_keys || self.loops.is_empty() {
489 return "none".to_string();
490 }
491
492 let mut key = format!("'lw-{}-{}'", self.hash, occurrence);
493
494 for alias in &self.loops {
495 key.push_str(" ~ '-' ~ ");
496 key.push_str(alias);
497 key.push_str(".index0");
498 }
499
500 key
501 }
502
503 fn attribute_expression(&mut self, value: &str) -> String {
505 if value.is_empty() {
506 return "true".to_string();
507 }
508
509 let compiled = self.translate(value, true);
510
511 if !compiled.contains("{{") {
512 return jinja_string(&compiled);
513 }
514
515 interpolate(&compiled)
516 }
517
518 fn component_expression(&mut self, name: &str, attributes: &str, slot: Option<&str>) -> String {
520 let occurrence = self.occurrence;
521 self.occurrence += 1;
522
523 let mut params: Vec<(String, String)> = Vec::new();
524 let mut key: Option<String> = None;
525
526 for (attribute, value) in parse_attributes(attributes) {
527 match attribute.as_str() {
528 "wire:key" | "key" => {
529 key = Some(match value {
530 Some(value) => self.attribute_expression(&value),
531 None => "none".to_string(),
532 });
533 continue;
534 }
535 _ => {}
536 }
537
538 if let Some(bound) = attribute.strip_prefix(':') {
539 let value = match value {
540 None => "true".to_string(),
541 Some(value) => {
542 let trimmed = value.trim();
543
544 match strip_braces(trimmed) {
545 Some(inner) => inner.trim().to_string(),
546 None => trimmed.to_string(),
547 }
548 }
549 };
550
551 params.push((bound.to_string(), value));
552 } else {
553 let value = match value {
554 Some(value) => self.attribute_expression(&value),
555 None => "true".to_string(),
556 };
557
558 params.push((attribute, value));
559 }
560 }
561
562 if let Some(slot) = slot {
563 params.push(("slot".to_string(), slot.to_string()));
564 }
565
566 let key = key.unwrap_or_else(|| self.missing_key(occurrence));
567
568 let mut expression = String::from("{{ livewire(");
569 expression.push_str(&jinja_string(name));
570 expression.push_str(", {");
571
572 for (index, (name, value)) in params.iter().enumerate() {
573 if index > 0 {
574 expression.push_str(", ");
575 }
576
577 expression.push_str(&jinja_string(name));
578 expression.push_str(": ");
579 expression.push_str(value);
580 }
581
582 expression.push_str("}, ");
583 expression.push_str(&key);
584 expression.push_str(") }}");
585
586 expression
587 }
588}
589
590struct LivewireTag<'a> {
592 attributes: &'a str,
594 end: usize,
596 inner: Option<&'a str>,
598 name: &'a str,
600 self_closing: bool,
602}
603
604impl<'a> LivewireTag<'a> {
605 fn parse(text: &'a str, at: usize) -> Option<Self> {
607 let bounds = livewire_tag_bounds(text, at)?;
608
609 if bounds.self_closing {
610 return Some(Self {
611 attributes: &text[bounds.name_end..bounds.attributes_end],
612 end: bounds.tag_end,
613 inner: None,
614 name: &text[bounds.name_start..bounds.name_end],
615 self_closing: true,
616 });
617 }
618
619 let name = &text[bounds.name_start..bounds.name_end];
620 let closing = format!("</livewire:{name}>");
621 let close_offset = text.get(bounds.tag_end..)?.find(&closing)?;
622 let close_start = bounds.tag_end + close_offset;
623 let end = close_start + closing.len();
624
625 Some(Self {
626 attributes: &text[bounds.name_end..bounds.attributes_end],
627 end,
628 inner: Some(&text[bounds.tag_end..close_start]),
629 name,
630 self_closing: false,
631 })
632 }
633
634 fn compile(&self, compiler: &mut Compiler) -> Option<String> {
636 match self.name {
637 "styles" => return Some("{{ livewire_styles() }}".to_string()),
638 "scripts" => return Some("{{ livewire_scripts() }}".to_string()),
639 _ => {}
640 }
641
642 if self.self_closing {
643 return Some(compiler.component_expression(self.name, self.attributes, None));
644 }
645
646 let inner = self.inner?;
647 let inner = compiler.translate(inner, false);
648
649 let variable = format!("lw_slot_{}", compiler.slot_occurrence);
650 compiler.slot_occurrence += 1;
651
652 let expression = compiler.component_expression(self.name, self.attributes, Some(&variable));
653
654 Some(format!("{{% set {variable} %}}{inner}{{% endset %}}{expression}"))
655 }
656}
657
658struct TagBounds {
660 attributes_end: usize,
662 name_end: usize,
664 name_start: usize,
666 self_closing: bool,
668 tag_end: usize,
670}
671
672fn livewire_tag_bounds(text: &str, at: usize) -> Option<TagBounds> {
674 let prefix = "<livewire:";
675
676 if !text.get(at..)?.starts_with(prefix) {
677 return None;
678 }
679
680 let bytes = text.as_bytes();
681 let mut cursor = at + prefix.len();
682 let name_start = cursor;
683
684 while cursor < bytes.len()
685 && (bytes[cursor].is_ascii_alphanumeric() || matches!(bytes[cursor], b'_' | b'.' | b'-' | b':'))
686 {
687 cursor += 1;
688 }
689
690 if cursor == name_start {
691 return None;
692 }
693
694 let name_end = cursor;
695 let mut quote: Option<u8> = None;
696
697 while cursor < bytes.len() {
698 let byte = bytes[cursor];
699
700 if let Some(active) = quote {
701 if byte == active {
702 quote = None;
703 }
704 cursor += 1;
705 continue;
706 }
707
708 match byte {
709 b'"' | b'\'' => quote = Some(byte),
710 b'>' => {
711 let self_closing = cursor > name_end && bytes[cursor - 1] == b'/';
712 let attributes_end = if self_closing { cursor - 1 } else { cursor };
713
714 return Some(TagBounds {
715 attributes_end,
716 name_end,
717 name_start,
718 self_closing,
719 tag_end: cursor + 1,
720 });
721 }
722 _ => {}
723 }
724
725 cursor += 1;
726 }
727
728 None
729}
730
731fn attributes_have_key(attributes: &str) -> bool {
733 parse_attributes(attributes)
734 .iter()
735 .any(|(name, _)| name == "wire:key" || name == "key")
736}
737
738fn parse_attributes(attributes: &str) -> Vec<(String, Option<String>)> {
740 let bytes = attributes.as_bytes();
741 let mut parsed = Vec::new();
742 let mut index = 0;
743
744 while index < bytes.len() {
745 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
746 index += 1;
747 }
748
749 if index >= bytes.len() {
750 break;
751 }
752
753 if bytes[index] == b'/' {
754 index += 1;
755 continue;
756 }
757
758 let name_start = index;
759
760 while index < bytes.len() && !bytes[index].is_ascii_whitespace() && !matches!(bytes[index], b'=' | b'/' | b'>')
761 {
762 index += 1;
763 }
764
765 if index == name_start {
766 index += 1;
767 continue;
768 }
769
770 let name = attributes[name_start..index].to_string();
771
772 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
773 index += 1;
774 }
775
776 let mut value = None;
777
778 if index < bytes.len() && bytes[index] == b'=' {
779 index += 1;
780
781 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
782 index += 1;
783 }
784
785 if index < bytes.len() && (bytes[index] == b'"' || bytes[index] == b'\'') {
786 let quote = bytes[index];
787 index += 1;
788 let start = index;
789
790 while index < bytes.len() && bytes[index] != quote {
791 index += 1;
792 }
793
794 value = Some(attributes[start..index].to_string());
795
796 if index < bytes.len() {
797 index += 1;
798 }
799 } else {
800 let start = index;
801
802 while index < bytes.len() && !bytes[index].is_ascii_whitespace() {
803 index += 1;
804 }
805
806 value = Some(attributes[start..index].to_string());
807 }
808 }
809
810 parsed.push((name, value));
811 }
812
813 parsed
814}
815
816struct IslandOptions {
818 defer: bool,
820 lazy: bool,
822 mode: Option<String>,
824 name: Option<String>,
826}
827
828impl IslandOptions {
829 fn parse(expression: Option<&str>) -> Self {
831 let mut options = Self {
832 defer: false,
833 lazy: false,
834 mode: None,
835 name: None,
836 };
837
838 if let Some(expression) = expression {
839 for part in split_top_level(expression, ',') {
840 let Some((key, value)) = part.split_once(':') else {
841 continue;
842 };
843
844 let key = key.trim();
845 let value = value.trim();
846
847 match key {
848 "name" => options.name = Some(unquote(value).unwrap_or(value).to_string()),
849 "mode" => options.mode = Some(unquote(value).unwrap_or(value).to_string()),
850 "lazy" => options.lazy = value == "true",
851 "defer" => options.defer = value == "true",
852 _ => {}
853 }
854 }
855 }
856
857 options
858 }
859
860 fn directive(&self) -> Option<&'static str> {
862 if self.lazy {
863 Some("wire:intersect.once=\"__lazyLoadIsland\"")
864 } else if self.defer {
865 Some("wire:init=\"__lazyLoadIsland\"")
866 } else {
867 None
868 }
869 }
870}
871
872fn find_matching_endisland(text: &str, from: usize) -> Option<(usize, usize)> {
874 let bytes = text.as_bytes();
875 let mut index = from;
876 let mut depth = 0usize;
877
878 while index < bytes.len() {
879 if bytes[index] == b'{' && starts_jinja(bytes, index) {
880 index = jinja_end(text, index)?;
881 continue;
882 }
883
884 if bytes[index] == b'@' {
885 let mut word_end = index + 1;
886
887 while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
888 word_end += 1;
889 }
890
891 match &text[index + 1..word_end] {
892 "island" => {
893 depth += 1;
894 index = word_end;
895 continue;
896 }
897 "endisland" if depth == 0 => return Some((index, word_end)),
898 "endisland" => {
899 depth -= 1;
900 index = word_end;
901 continue;
902 }
903 _ => {}
904 }
905
906 index = word_end;
907 continue;
908 }
909
910 index += 1;
911 }
912
913 None
914}
915
916fn loops_need_aliases(source: &str) -> bool {
918 let bytes = source.as_bytes();
919 let mut index = 0;
920 let mut depth = 0usize;
921
922 while index < bytes.len() {
923 if bytes[index] == b'{'
924 && starts_jinja(bytes, index)
925 && let Some(end) = jinja_end(source, index)
926 {
927 let keyword = if bytes[index + 1] == b'%' {
928 jinja_keyword(&source[index..end])
929 } else {
930 ""
931 };
932
933 match keyword {
934 "for" => depth += 1,
935 "endfor" => depth = depth.saturating_sub(1),
936 "raw" => {
937 if let Some(offset) = source.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
938 index = end + offset + "{% endraw %}".len();
939 continue;
940 }
941 }
942 _ => {}
943 }
944
945 index = end;
946 continue;
947 }
948
949 if bytes[index] == b'<'
950 && let Some(bounds) = livewire_tag_bounds(source, index)
951 {
952 if depth > 0 && !attributes_have_key(&source[bounds.name_end..bounds.attributes_end]) {
953 return true;
954 }
955
956 index = bounds.tag_end;
957 continue;
958 }
959
960 index += 1;
961 }
962
963 false
964}
965
966fn inject_island_attribute(html: &str, attribute: &str) -> String {
968 let bytes = html.as_bytes();
969 let mut index = 0;
970
971 while index + 1 < bytes.len() {
972 if bytes[index] == b'<' && bytes[index + 1].is_ascii_alphabetic() {
973 let mut cursor = index + 2;
974
975 while cursor < bytes.len() && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'-') {
976 cursor += 1;
977 }
978
979 let mut out = String::with_capacity(html.len() + attribute.len() + 1);
980 out.push_str(&html[..cursor]);
981 out.push(' ');
982 out.push_str(attribute);
983 out.push_str(&html[cursor..]);
984
985 return out;
986 }
987
988 index += 1;
989 }
990
991 format!("<span {attribute}>{html}</span>")
992}
993
994fn directive_value(expression: Option<&str>) -> String {
996 match expression {
997 None => String::new(),
998 Some(expression) => {
999 let trimmed = expression.trim();
1000
1001 if let Some(inner) = unquote(trimmed) {
1002 escape_attribute(inner)
1003 } else if trimmed.starts_with("{{") {
1004 trimmed.to_string()
1005 } else {
1006 format!("{{{{ {trimmed} }}}}")
1007 }
1008 }
1009 }
1010}
1011
1012fn escape_attribute(value: &str) -> String {
1014 let mut escaped = String::with_capacity(value.len());
1015
1016 for character in value.chars() {
1017 match character {
1018 '&' => escaped.push_str("&"),
1019 '<' => escaped.push_str("<"),
1020 '>' => escaped.push_str(">"),
1021 '"' => escaped.push_str("""),
1022 '\'' => escaped.push_str("'"),
1023 other => escaped.push(other),
1024 }
1025 }
1026
1027 escaped
1028}
1029
1030fn convert_params(value: &str) -> String {
1032 if value.is_empty() {
1033 return "{}".to_string();
1034 }
1035
1036 if value.starts_with('[') && value.ends_with(']') {
1037 return convert_php_array(&value[1..value.len() - 1]);
1038 }
1039
1040 if value.starts_with('{') && value.ends_with('}') {
1041 return convert_object(&value[1..value.len() - 1]);
1042 }
1043
1044 if let Some(inner) = value.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
1045 return convert_php_array(inner);
1046 }
1047
1048 value.to_string()
1049}
1050
1051fn convert_php_array(inner: &str) -> String {
1053 let mut pairs: Vec<(Option<String>, String)> = Vec::new();
1054
1055 for entry in split_top_level(inner, ',') {
1056 let entry = entry.trim();
1057
1058 if entry.is_empty() {
1059 continue;
1060 }
1061
1062 if let Some(position) = find_top_level(entry, "=>") {
1063 let key = entry[..position].trim();
1064 let value = entry[position + 2..].trim();
1065
1066 pairs.push((Some(unquote(key).unwrap_or(key).to_string()), convert_value(value)));
1067 } else {
1068 pairs.push((None, convert_value(entry)));
1069 }
1070 }
1071
1072 if pairs.is_empty() {
1073 return "{}".to_string();
1074 }
1075
1076 if pairs.iter().any(|(key, _)| key.is_some()) {
1077 let mut out = String::from("{");
1078
1079 for (index, (key, value)) in pairs.iter().enumerate() {
1080 if index > 0 {
1081 out.push_str(", ");
1082 }
1083
1084 let key = key.clone().unwrap_or_else(|| index.to_string());
1085 out.push_str(&jinja_string(&key));
1086 out.push_str(": ");
1087 out.push_str(value);
1088 }
1089
1090 out.push('}');
1091
1092 return out;
1093 }
1094
1095 let values: Vec<String> = pairs.into_iter().map(|(_, value)| value).collect();
1096
1097 format!("[{}]", values.join(", "))
1098}
1099
1100fn convert_object(inner: &str) -> String {
1102 let mut pairs: Vec<(String, String)> = Vec::new();
1103
1104 for entry in split_top_level(inner, ',') {
1105 let entry = entry.trim();
1106
1107 if entry.is_empty() {
1108 continue;
1109 }
1110
1111 let Some(position) = find_top_level(entry, ":") else {
1112 return format!("{{{inner}}}");
1113 };
1114
1115 let key = entry[..position].trim();
1116 let value = entry[position + 1..].trim();
1117
1118 pairs.push((unquote(key).unwrap_or(key).to_string(), convert_value(value)));
1119 }
1120
1121 let mut out = String::from("{");
1122
1123 for (index, (key, value)) in pairs.iter().enumerate() {
1124 if index > 0 {
1125 out.push_str(", ");
1126 }
1127
1128 out.push_str(&jinja_string(key));
1129 out.push_str(": ");
1130 out.push_str(value);
1131 }
1132
1133 out.push('}');
1134
1135 out
1136}
1137
1138fn convert_value(value: &str) -> String {
1140 let trimmed = value.trim();
1141
1142 if trimmed.starts_with('[') && trimmed.ends_with(']') && trimmed.len() >= 2 {
1143 return convert_php_array(&trimmed[1..trimmed.len() - 1]);
1144 }
1145
1146 if trimmed.starts_with('{') && trimmed.ends_with('}') && trimmed.len() >= 2 {
1147 return convert_object(&trimmed[1..trimmed.len() - 1]);
1148 }
1149
1150 if let Some(inner) = trimmed.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
1151 return convert_php_array(inner);
1152 }
1153
1154 trimmed.to_string()
1155}
1156
1157fn interpolate(compiled: &str) -> String {
1159 let bytes = compiled.as_bytes();
1160 let mut parts: Vec<(bool, &str)> = Vec::new();
1161 let mut index = 0;
1162 let mut literal_start = 0;
1163
1164 while index + 1 < bytes.len() {
1165 if bytes[index] == b'{'
1166 && bytes[index + 1] == b'{'
1167 && let Some(end) = jinja_end(compiled, index)
1168 {
1169 if index > literal_start {
1170 parts.push((false, &compiled[literal_start..index]));
1171 }
1172
1173 parts.push((true, &compiled[index + 2..end - 2]));
1174 index = end;
1175 literal_start = end;
1176 continue;
1177 }
1178
1179 index += 1;
1180 }
1181
1182 if literal_start < compiled.len() {
1183 parts.push((false, &compiled[literal_start..]));
1184 }
1185
1186 match parts.as_slice() {
1187 [] => "''".to_string(),
1188 [(true, expression)] => expression.trim().to_string(),
1189 [(false, literal)] => jinja_string(literal),
1190 _ => {
1191 let mut out = String::new();
1192
1193 for (index, (is_expression, part)) in parts.iter().enumerate() {
1194 if index > 0 {
1195 out.push_str(" ~ ");
1196 }
1197
1198 if *is_expression {
1199 out.push('(');
1200 out.push_str(part.trim());
1201 out.push(')');
1202 } else if part.is_empty() {
1203 out.push_str("''");
1204 } else {
1205 out.push_str(&jinja_string(part));
1206 }
1207 }
1208
1209 out
1210 }
1211 }
1212}
1213
1214fn jinja_string(value: &str) -> String {
1216 let mut quoted = String::with_capacity(value.len() + 2);
1217 quoted.push('\'');
1218
1219 for character in value.chars() {
1220 match character {
1221 '\\' => quoted.push_str("\\\\"),
1222 '\'' => quoted.push_str("\\'"),
1223 other => quoted.push(other),
1224 }
1225 }
1226
1227 quoted.push('\'');
1228
1229 quoted
1230}
1231
1232fn unquote(value: &str) -> Option<&str> {
1234 let bytes = value.as_bytes();
1235
1236 if bytes.len() < 2 {
1237 return None;
1238 }
1239
1240 let first = bytes[0];
1241 let last = bytes[bytes.len() - 1];
1242
1243 if first != last || !matches!(first, b'"' | b'\'') {
1244 return None;
1245 }
1246
1247 Some(&value[1..value.len() - 1])
1248}
1249
1250fn strip_braces(value: &str) -> Option<&str> {
1252 value.strip_prefix("{{")?.strip_suffix("}}")
1253}
1254
1255fn starts_jinja(bytes: &[u8], index: usize) -> bool {
1257 index + 1 < bytes.len() && matches!(bytes[index + 1], b'{' | b'%' | b'#')
1258}
1259
1260fn jinja_end(text: &str, start: usize) -> Option<usize> {
1262 let bytes = text.as_bytes();
1263 let closer: &[u8] = match bytes.get(start + 1) {
1264 Some(b'{') => b"}}",
1265 Some(b'%') => b"%}",
1266 Some(b'#') => b"#}",
1267 _ => return None,
1268 };
1269
1270 let mut index = start + 2;
1271 let mut quote: Option<u8> = None;
1272
1273 while index < bytes.len() {
1274 if let Some(active) = quote {
1275 if bytes[index] == b'\\' {
1276 index = (index + 2).min(bytes.len());
1277 continue;
1278 }
1279
1280 if bytes[index] == active {
1281 quote = None;
1282 }
1283
1284 index += 1;
1285 continue;
1286 }
1287
1288 match bytes[index] {
1289 b'"' | b'\'' => quote = Some(bytes[index]),
1290 _ => {
1291 if bytes[index..].starts_with(closer) {
1292 return Some(index + closer.len());
1293 }
1294 }
1295 }
1296
1297 index += 1;
1298 }
1299
1300 None
1301}
1302
1303fn jinja_keyword(tag: &str) -> &str {
1305 let inner = tag.strip_prefix("{%").unwrap_or(tag);
1306 let inner = inner.strip_suffix("%}").unwrap_or(inner);
1307 let inner = inner.trim().trim_start_matches('-').trim_start();
1308
1309 let end = inner
1310 .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
1311 .unwrap_or(inner.len());
1312
1313 &inner[..end]
1314}
1315
1316fn balanced_paren(text: &str, open: usize) -> Option<usize> {
1318 let bytes = text.as_bytes();
1319 let mut index = open;
1320 let mut depth = 0usize;
1321 let mut quote: Option<u8> = None;
1322
1323 while index < bytes.len() {
1324 if let Some(active) = quote {
1325 if bytes[index] == b'\\' {
1326 index = (index + 2).min(bytes.len());
1327 continue;
1328 }
1329
1330 if bytes[index] == active {
1331 quote = None;
1332 }
1333
1334 index += 1;
1335 continue;
1336 }
1337
1338 match bytes[index] {
1339 b'"' | b'\'' => quote = Some(bytes[index]),
1340 b'(' => depth += 1,
1341 b')' => {
1342 depth -= 1;
1343
1344 if depth == 0 {
1345 return Some(index + 1);
1346 }
1347 }
1348 _ => {}
1349 }
1350
1351 index += 1;
1352 }
1353
1354 None
1355}
1356
1357fn split_top_level(value: &str, separator: char) -> Vec<&str> {
1359 let bytes = value.as_bytes();
1360 let separator = separator as u8;
1361 let mut parts = Vec::new();
1362 let mut start = 0;
1363 let mut index = 0;
1364 let mut depth = 0usize;
1365 let mut quote: Option<u8> = None;
1366
1367 while index < bytes.len() {
1368 if let Some(active) = quote {
1369 if bytes[index] == b'\\' {
1370 index = (index + 2).min(bytes.len());
1371 continue;
1372 }
1373
1374 if bytes[index] == active {
1375 quote = None;
1376 }
1377
1378 index += 1;
1379 continue;
1380 }
1381
1382 match bytes[index] {
1383 b'"' | b'\'' => quote = Some(bytes[index]),
1384 b'(' | b'[' | b'{' => depth += 1,
1385 b')' | b']' | b'}' => depth = depth.saturating_sub(1),
1386 byte if byte == separator && depth == 0 => {
1387 parts.push(&value[start..index]);
1388 start = index + 1;
1389 }
1390 _ => {}
1391 }
1392
1393 index += 1;
1394 }
1395
1396 parts.push(&value[start..]);
1397
1398 parts
1399}
1400
1401fn find_top_level(value: &str, needle: &str) -> Option<usize> {
1403 let bytes = value.as_bytes();
1404 let mut index = 0;
1405 let mut depth = 0usize;
1406 let mut quote: Option<u8> = None;
1407
1408 while index < bytes.len() {
1409 if let Some(active) = quote {
1410 if bytes[index] == b'\\' {
1411 index = (index + 2).min(bytes.len());
1412 continue;
1413 }
1414
1415 if bytes[index] == active {
1416 quote = None;
1417 }
1418
1419 index += 1;
1420 continue;
1421 }
1422
1423 match bytes[index] {
1424 b'"' | b'\'' => quote = Some(bytes[index]),
1425 b'(' | b'[' | b'{' => depth += 1,
1426 b')' | b']' | b'}' => depth = depth.saturating_sub(1),
1427 _ => {
1428 if depth == 0 && value[index..].starts_with(needle) {
1429 return Some(index);
1430 }
1431 }
1432 }
1433
1434 index += 1;
1435 }
1436
1437 None
1438}
1439
1440#[cfg(test)]
1441mod tests {
1442 use super::*;
1443
1444 const NO_OPTIONS: CompileOptions = CompileOptions {
1445 inject_morph_markers: false,
1446 smart_wire_keys: false,
1447 };
1448 const MORPH: CompileOptions = CompileOptions {
1449 inject_morph_markers: true,
1450 smart_wire_keys: false,
1451 };
1452 const KEYS: CompileOptions = CompileOptions {
1453 inject_morph_markers: false,
1454 smart_wire_keys: true,
1455 };
1456 const ALL: CompileOptions = CompileOptions {
1457 inject_morph_markers: true,
1458 smart_wire_keys: true,
1459 };
1460
1461 fn identity() -> TemplateIdentity {
1462 TemplateIdentity {
1463 name: "counter".to_string(),
1464 source: "livewire.counter".to_string(),
1465 }
1466 }
1467
1468 fn hash() -> String {
1469 identity().hash()
1470 }
1471
1472 fn run(source: &str, options: CompileOptions) -> String {
1473 compile(source, &identity(), options)
1474 }
1475
1476 #[test]
1477 fn a_self_closing_tag_becomes_the_livewire_expression() {
1478 let source = r#"<div><livewire:post-row :post="post" wire:key="row-1" class="p-4" /></div>"#;
1479
1480 assert_eq!(
1481 run(source, NO_OPTIONS),
1482 r#"<div>{{ livewire('post-row', {'post': post, 'class': 'p-4'}, 'row-1') }}</div>"#
1483 );
1484 }
1485
1486 #[test]
1487 fn a_paired_tag_compiles_its_slot() {
1488 assert_eq!(
1489 run("<livewire:counter>Hello</livewire:counter>", NO_OPTIONS),
1490 "{% set lw_slot_0 %}Hello{% endset %}{{ livewire('counter', {'slot': lw_slot_0}, none) }}"
1491 );
1492 }
1493
1494 #[test]
1495 fn slot_content_is_compiled_too() {
1496 assert_eq!(
1497 run(
1498 "<livewire:counter>@this.now() @entangle('open')</livewire:counter>",
1499 NO_OPTIONS
1500 ),
1501 "{% set lw_slot_0 %}$wire.now() $wire.entangle('open'){% endset %}\
1502 {{ livewire('counter', {'slot': lw_slot_0}, none) }}"
1503 );
1504 }
1505
1506 #[test]
1507 fn the_livewire_directive_accepts_php_arrays_keys_and_json_objects() {
1508 assert_eq!(
1509 run("@livewire('counter', ['step' => 2], key: 'c1')", NO_OPTIONS),
1510 "{{ livewire('counter', {'step': 2}, 'c1') }}"
1511 );
1512
1513 assert_eq!(
1514 run(r#"@livewire("counter", {"step": 2})"#, NO_OPTIONS),
1515 r#"{{ livewire("counter", {'step': 2}, none) }}"#
1516 );
1517
1518 assert_eq!(
1519 run("@livewire('counter', [], key('c2'))", NO_OPTIONS),
1520 "{{ livewire('counter', {}, 'c2') }}"
1521 );
1522 }
1523
1524 #[test]
1525 fn the_livewire_directive_converts_nested_arrays() {
1526 assert_eq!(
1527 run("@livewire('x', ['a' => ['b' => 1], 'list' => [1, 2]])", NO_OPTIONS),
1528 "{{ livewire('x', {'a': {'b': 1}, 'list': [1, 2]}, none) }}"
1529 );
1530 }
1531
1532 #[test]
1533 fn this_becomes_wire() {
1534 assert_eq!(
1535 run(r#"<button wire:click="@this.increment">Go</button>"#, NO_OPTIONS),
1536 r#"<button wire:click="$wire.increment">Go</button>"#
1537 );
1538 }
1539
1540 #[test]
1541 fn entangle_becomes_wire_entangle_with_its_modifier() {
1542 assert_eq!(
1543 run(r#"<div x-data="{ open: @entangle('open') }"></div>"#, NO_OPTIONS),
1544 r#"<div x-data="{ open: $wire.entangle('open') }"></div>"#
1545 );
1546
1547 assert_eq!(run("@entangle('open').live", NO_OPTIONS), "$wire.entangle('open').live");
1548 assert_eq!(
1549 run("@entangle('open').defer", NO_OPTIONS),
1550 "$wire.entangle('open').defer"
1551 );
1552 }
1553
1554 #[test]
1555 fn assets_and_scripts_become_jinja_blocks() {
1556 assert_eq!(
1557 run("@assets<script src=\"/a.js\"></script>@endassets", NO_OPTIONS),
1558 "{% livewire_assets %}<script src=\"/a.js\"></script>{% endlivewire_assets %}"
1559 );
1560
1561 assert_eq!(
1562 run("@script console.log('a') @endscript", NO_OPTIONS),
1563 "{% livewire_script %} console.log('a') {% endlivewire_script %}"
1564 );
1565 }
1566
1567 #[test]
1568 fn teleport_becomes_a_template() {
1569 assert_eq!(
1570 run("@teleport('#modal')<div>x</div>@endteleport", NO_OPTIONS),
1571 "<template x-teleport=\"#modal\"><div>x</div></template>"
1572 );
1573 }
1574
1575 #[test]
1576 fn persist_becomes_a_div() {
1577 assert_eq!(
1578 run("@persist('player')<div>x</div>@endpersist", NO_OPTIONS),
1579 "<div x-persist=\"player\"><div>x</div></div>"
1580 );
1581 }
1582
1583 #[test]
1584 fn an_island_emits_fragment_markers() {
1585 let named = format!("{}-0", hash());
1586
1587 assert_eq!(
1588 run("@island(name: 'timer')<p>t</p>@endisland", NO_OPTIONS),
1589 format!(
1590 "<!--[if FRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->\
1591 <p>t</p>\
1592 <!--[if ENDFRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->"
1593 )
1594 );
1595
1596 assert_eq!(
1597 run("@island<p>t</p>@endisland", NO_OPTIONS),
1598 format!(
1599 "<!--[if FRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->\
1600 <p>t</p>\
1601 <!--[if ENDFRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->"
1602 )
1603 );
1604 }
1605
1606 #[test]
1607 fn islands_nest_with_distinct_tokens() {
1608 let output = run(
1609 "@island(name: 'outer')<div>@island(name: 'inner')x@endisland</div>@endisland",
1610 NO_OPTIONS,
1611 );
1612
1613 assert!(output.contains(&format!("name=outer|token={}-0", hash())));
1614 assert!(output.contains(&format!("name=inner|token={}-1", hash())));
1615
1616 let inner_end = output.find("ENDFRAGMENT:type=island|name=inner").unwrap();
1617 let outer_end = output.rfind("ENDFRAGMENT:type=island|name=outer").unwrap();
1618
1619 assert!(inner_end < outer_end);
1620 }
1621
1622 #[test]
1623 fn an_island_carries_its_mode() {
1624 assert!(run("@island(name: 'feed', mode: 'append')x@endisland", NO_OPTIONS).contains("mode=append"));
1625 }
1626
1627 #[test]
1628 fn a_lazy_island_gets_a_load_attribute() {
1629 assert!(
1630 run("@island(defer: true)<p>x</p>@endisland", NO_OPTIONS)
1631 .contains(r#"<p wire:init="__lazyLoadIsland">x</p>"#)
1632 );
1633
1634 assert!(
1635 run("@island(lazy: true)plain@endisland", NO_OPTIONS)
1636 .contains(r#"<span wire:intersect.once="__lazyLoadIsland">plain</span>"#)
1637 );
1638 }
1639
1640 #[test]
1641 fn the_asset_helpers_become_expressions() {
1642 assert_eq!(
1643 run("@livewireStyles@livewireScripts@livewireScriptConfig", NO_OPTIONS),
1644 "{{ livewire_styles() }}{{ livewire_scripts() }}{{ livewire_script_config() }}"
1645 );
1646 }
1647
1648 #[test]
1649 fn unknown_directives_pass_through_byte_for_byte() {
1650 for source in [
1651 "@if ($show) <p>@endif</p>",
1652 "user@example.com",
1653 "@unknownDirective('x')",
1654 "@@livewire('counter')",
1655 "@foreach($items as $item)@endforeach",
1656 ] {
1657 assert_eq!(run(source, ALL), source, "source: {source}");
1658 }
1659 }
1660
1661 #[test]
1662 fn morph_markers_wrap_conditionals_and_loops() {
1663 assert_eq!(
1664 run("{% if show %}a{% endif %}", MORPH),
1665 format!("{BLOCK_START}{{% if show %}}a{{% endif %}}{BLOCK_END}")
1666 );
1667
1668 assert_eq!(
1669 run("{%- for x in y -%}a{%- endfor -%}", MORPH),
1670 format!("{BLOCK_START}{{%- for x in y -%}}a{{%- endfor -%}}{BLOCK_END}")
1671 );
1672 }
1673
1674 #[test]
1675 fn morph_markers_nest() {
1676 assert_eq!(
1677 run("{% if a %}{% for x in y %}z{% endfor %}{% endif %}", MORPH),
1678 format!(
1679 "{BLOCK_START}{{% if a %}}{BLOCK_START}{{% for x in y %}}z{{% endfor %}}{BLOCK_END}{{% endif %}}{BLOCK_END}"
1680 )
1681 );
1682 }
1683
1684 #[test]
1685 fn a_block_inside_an_attribute_gets_no_marker() {
1686 let source = r#"<div class="{% if active %}on{% endif %}">x</div>"#;
1687
1688 assert_eq!(run(source, MORPH), source);
1689 }
1690
1691 #[test]
1692 fn script_contents_carry_no_morph_markers() {
1693 let source = "<script>{% if a %}x{% endif %}</script>";
1694
1695 assert_eq!(run(source, MORPH), source);
1696 }
1697
1698 #[test]
1699 fn smart_keys_use_the_enclosing_loop() {
1700 let output = run(
1701 r#"<div>{% for post in posts %}<livewire:post-row :post="post" />{% endfor %}</div>"#,
1702 KEYS,
1703 );
1704
1705 assert!(output.contains("{% set lw_loop_0 = loop %}"));
1706 assert!(output.contains(&format!("'lw-{}-0' ~ '-' ~ lw_loop_0.index0", hash())));
1707 assert!(output.contains("{{ livewire('post-row', {'post': post}, "));
1708 assert!(!output.contains(BLOCK_START));
1709 }
1710
1711 #[test]
1712 fn nested_loops_give_distinct_keys() {
1713 let output = run(
1714 "{% for a in xs %}{% for b in ys %}<livewire:row />{% endfor %}{% endfor %}",
1715 KEYS,
1716 );
1717
1718 assert!(output.contains("{% set lw_loop_0 = loop %}"));
1719 assert!(output.contains("{% set lw_loop_1 = loop %}"));
1720 assert!(output.contains(&format!(
1721 "'lw-{}-0' ~ '-' ~ lw_loop_0.index0 ~ '-' ~ lw_loop_1.index0",
1722 hash()
1723 )));
1724 }
1725
1726 #[test]
1727 fn both_options_off_leave_keys_and_comments_out() {
1728 assert_eq!(
1729 run("{% for a in xs %}<livewire:row />{% endfor %}", NO_OPTIONS),
1730 "{% for a in xs %}{{ livewire('row', {}, none) }}{% endfor %}"
1731 );
1732
1733 assert_eq!(run("{% if a %}b{% endif %}", NO_OPTIONS), "{% if a %}b{% endif %}");
1734 }
1735
1736 #[test]
1737 fn an_explicit_key_always_wins() {
1738 assert_eq!(
1739 run(
1740 "{% for p in ps %}<livewire:row wire:key=\"k-{{ p.id }}\" />{% endfor %}",
1741 KEYS
1742 ),
1743 "{% for p in ps %}{{ livewire('row', {}, 'k-' ~ (p.id)) }}{% endfor %}"
1744 );
1745 }
1746
1747 #[test]
1748 fn existing_jinja_is_untouched() {
1749 let source = "{% set x = 1 %}{{ x }}{# note #}";
1750
1751 assert_eq!(run(source, ALL), source);
1752 }
1753
1754 #[test]
1755 fn wire_island_attributes_pass_through() {
1756 let source = r#"<button wire:click="increment" wire:island="foo">Go</button>"#;
1757
1758 assert_eq!(run(source, ALL), source);
1759 }
1760
1761 #[test]
1762 fn truncated_input_is_left_as_it_stands() {
1763 for source in [
1764 "@island",
1765 "@island(",
1766 "@endisland",
1767 "@livewire(",
1768 "@teleport(",
1769 "@entangle(",
1770 "<livewire:counter",
1771 "<livewire:counter>",
1772 "{% if x",
1773 "{{ x",
1774 ] {
1775 assert_eq!(run(source, ALL), source, "source: {source}");
1776 }
1777 }
1778
1779 #[test]
1780 fn compiling_the_same_source_twice_gives_the_same_string() {
1781 let source = "<livewire:row />@island(name: 'a')x@endisland";
1782
1783 assert_eq!(run(source, ALL), run(source, ALL));
1784 }
1785}