1use std::fmt::Write as _;
8use std::path::{Path, PathBuf};
9
10use laravel::config::Section;
11use laravel::console::{Console, clap};
12
13use crate::config::{ComponentKind, LivewireConfig};
14use crate::registry::normalize_name;
15
16#[derive(Debug, clap::Parser)]
18#[command(name = "make:livewire", about = "Create a Livewire component and its view")]
19pub struct MakeLivewire {
20 pub name: String,
22
23 #[arg(long, conflicts_with_all = ["sfc", "inline"])]
25 pub class: bool,
26
27 #[arg(long, conflicts_with_all = ["mfc", "class", "inline"])]
29 pub sfc: bool,
30
31 #[arg(long, conflicts_with_all = ["sfc", "class", "inline"])]
33 pub mfc: bool,
34
35 #[arg(long, conflicts_with_all = ["mfc", "class", "sfc"])]
37 pub inline: bool,
38
39 #[arg(long)]
41 pub js: bool,
42
43 #[arg(long)]
45 pub css: bool,
46
47 #[arg(long)]
49 pub test: bool,
50
51 #[arg(long)]
53 pub force: bool,
54
55 #[arg(long)]
57 pub path: Option<PathBuf>,
58}
59
60#[derive(Debug, clap::Parser)]
64#[command(name = "livewire:make", about = "Create a Livewire component and its view")]
65pub struct LivewireMake {
66 pub name: String,
68
69 #[arg(long, conflicts_with_all = ["sfc", "inline"])]
71 pub class: bool,
72
73 #[arg(long, conflicts_with_all = ["mfc", "class", "inline"])]
75 pub sfc: bool,
76
77 #[arg(long, conflicts_with_all = ["sfc", "class", "inline"])]
79 pub mfc: bool,
80
81 #[arg(long, conflicts_with_all = ["mfc", "class", "sfc"])]
83 pub inline: bool,
84
85 #[arg(long)]
87 pub js: bool,
88
89 #[arg(long)]
91 pub css: bool,
92
93 #[arg(long)]
95 pub test: bool,
96
97 #[arg(long)]
99 pub force: bool,
100
101 #[arg(long)]
103 pub path: Option<PathBuf>,
104}
105
106#[derive(Debug, clap::Parser)]
108#[command(name = "livewire:config", about = "Show the resolved Livewire configuration")]
109pub struct LivewireConfigCommand;
110
111#[derive(Debug, clap::Parser)]
113#[command(
114 name = "livewire:configure-s3-upload-cleanup",
115 about = "Configure temporary file upload s3 directory to automatically cleanup files older than 24hrs"
116)]
117pub struct ConfigureS3UploadCleanup;
118
119#[derive(Debug, clap::Parser)]
121#[command(name = "livewire:layout", about = "Create a layout view for page components")]
122pub struct Layout {
123 pub name: String,
125
126 #[arg(long)]
128 pub force: bool,
129
130 #[arg(long)]
132 pub path: Option<PathBuf>,
133}
134
135#[derive(Debug, clap::Parser)]
137#[command(
138 name = "livewire:convert",
139 about = "Convert a component between single-file and multi-file"
140)]
141pub struct Convert {
142 pub name: String,
144
145 #[arg(long)]
147 pub remove_view: bool,
148
149 #[arg(long)]
151 pub path: Option<PathBuf>,
152}
153
154#[derive(Debug, clap::Parser)]
156#[command(name = "livewire:publish", about = "Publish the Livewire front-end assets")]
157pub struct Publish {
158 #[arg(long)]
160 pub assets: bool,
161
162 #[arg(long)]
164 pub force: bool,
165
166 #[arg(long)]
168 pub path: Option<PathBuf>,
169}
170
171#[derive(Debug, clap::Parser)]
173#[command(name = "livewire:stubs", about = "Publish the component stubs make:livewire uses")]
174pub struct Stubs {
175 #[arg(long)]
177 pub force: bool,
178
179 #[arg(long)]
181 pub path: Option<PathBuf>,
182}
183
184#[laravel::console::command]
185impl MakeLivewire {
186 async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
187 let kind = if self.inline {
188 ComponentKind::Sfc
189 } else if self.class {
190 ComponentKind::Class
191 } else if self.mfc {
192 ComponentKind::Mfc
193 } else if self.sfc {
194 ComponentKind::Sfc
195 } else {
196 config.make_command.kind
197 };
198
199 let options = Options {
200 kind,
201 js: self.js || config.make_command.js,
202 css: self.css || config.make_command.css,
203 test: self.test || config.make_command.test,
204 base: self.path.clone(),
205 };
206
207 let plan = plan(&self.name, &options, &config)?;
208 let written = write(&plan, self.force)?;
209
210 for path in &written {
211 console.line(format!("created {}", path.display()));
212 }
213
214 Ok(())
215 }
216}
217
218#[laravel::console::command]
219impl LivewireMake {
220 async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
221 let command = MakeLivewire {
222 name: self.name,
223 class: self.class,
224 sfc: self.sfc,
225 mfc: self.mfc,
226 inline: self.inline,
227 js: self.js,
228 css: self.css,
229 test: self.test,
230 force: self.force,
231 path: self.path,
232 };
233
234 MakeLivewire::handle(command, console, config).await
235 }
236}
237
238#[laravel::console::command]
239impl Layout {
240 async fn handle(self, console: &mut Console) -> laravel::Result<()> {
241 let plan = plan_layout(&self.name, self.path.as_deref())?;
242 let written = write(&plan, self.force)?;
243
244 for path in &written {
245 console.line(format!("created {}", path.display()));
246 }
247
248 Ok(())
249 }
250}
251
252#[laravel::console::command]
253impl Convert {
254 async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
255 let plan = plan_convert(&self.name, self.path.as_deref(), &config)?;
256
257 let written = write(&plan.files, true)?;
259
260 for path in &written {
261 console.line(format!("wrote {}", path.display()));
262 }
263
264 match (&plan.leftover_view, self.remove_view) {
265 (Some(view), true) => {
266 std::fs::remove_file(view)
267 .map_err(|error| laravel::Error::msg(format!("{} can't be removed: {error}", view.display())))?;
268 console.line(format!("removed {}", view.display()));
269 }
270 (Some(view), false) => console.line(format!(
271 "left {} in place: pass --remove-view to delete it",
272 view.display()
273 )),
274 (None, _) => {}
275 }
276
277 Ok(())
278 }
279}
280
281#[laravel::console::command]
282impl Publish {
283 async fn handle(self, console: &mut Console) -> laravel::Result<()> {
284 let plan = plan_publish(self.path.as_deref());
285 let written = write(&plan, self.force)?;
286
287 for path in &written {
288 console.line(format!("published {}", path.display()));
289 }
290
291 Ok(())
292 }
293}
294
295#[laravel::console::command]
296impl Stubs {
297 async fn handle(self, console: &mut Console) -> laravel::Result<()> {
298 let plan = plan_stubs(self.path.as_deref());
299 let written = write(&plan, self.force)?;
300
301 for path in &written {
302 console.line(format!("published {}", path.display()));
303 }
304
305 Ok(())
306 }
307}
308
309#[laravel::console::command]
310impl ConfigureS3UploadCleanup {
311 async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
312 if config.temporary_file_upload.disk.as_deref() != Some("s3") {
316 console
317 .error("Configuration ['livewire.temporary_file_upload.disk'] is not set to a disk with an S3 driver.");
318
319 return Ok(());
320 }
321
322 console.error("This port does not talk to S3: schedule livewire::uploads::prune for the local disk instead.");
323
324 Ok(())
325 }
326}
327
328#[laravel::console::command]
329impl LivewireConfigCommand {
330 async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
331 console.line(format!("{config:#?}"));
332
333 Ok(())
334 }
335}
336
337#[derive(Debug, Clone)]
339pub struct Options {
340 pub kind: ComponentKind,
342 pub js: bool,
344 pub css: bool,
346 pub test: bool,
348 pub base: Option<PathBuf>,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct Planned {
355 pub path: PathBuf,
357 pub contents: String,
359}
360
361pub fn plan(name: &str, options: &Options, config: &LivewireConfig) -> laravel::Result<Vec<Planned>> {
367 let name = normalize_name(name).map_err(|error| laravel::Error::msg(error.to_string()))?;
368
369 let parts: Vec<&str> = name.split(['.', ':']).filter(|part| !part.is_empty()).collect();
370 let Some(leaf) = parts.last() else {
371 return Err(laravel::Error::msg("the component name is empty"));
372 };
373
374 let struct_name = pascal_case(leaf);
375 let kebab = kebab_case(leaf);
376 let dotted = parts.join(".");
377 let relative: PathBuf = parts.iter().collect();
378
379 let base = options.base.clone();
380 let root = |path: &str| -> PathBuf {
381 match &base {
382 Some(base) => base.join(path),
383 None => PathBuf::from(path),
384 }
385 };
386
387 let component_path = root(&config.component_path).join(&relative).with_extension("rs");
388 let view_path = root(&config.view_path).join(&relative).with_extension("livewire");
389
390 let inline = matches!(options.kind, ComponentKind::Sfc);
391
392 let markup = format!("<div>\n <h2>{struct_name}</h2>\n</div>");
394 let module = match read_stub(&root("stubs/livewire/component.rs.stub")) {
395 Some(stub) => substitute(&stub, &struct_name, &kebab, &dotted),
396 None if inline => module_source(&struct_name, &kebab, &markup, None),
397 None => module_source(&struct_name, &kebab, "", Some(&dotted)),
398 };
399
400 let mut files = vec![Planned {
401 path: component_path,
402 contents: module,
403 }];
404
405 if !inline {
406 let view = match read_stub(&root("stubs/livewire/view.livewire.stub")) {
407 Some(stub) => substitute(&stub, &struct_name, &kebab, &dotted),
408 None => format!("<div>\n <h2>{struct_name}</h2>\n</div>\n"),
409 };
410
411 files.push(Planned {
412 path: view_path.clone(),
413 contents: view,
414 });
415 }
416
417 if options.js {
418 files.push(Planned {
419 path: view_path.with_extension("js"),
420 contents: format!("// The `{kebab}` component's browser module.\n"),
421 });
422 }
423
424 if options.css {
425 files.push(Planned {
426 path: view_path.with_extension("css"),
427 contents: format!("/* The `{kebab}` component's styles. */\n"),
428 });
429 }
430
431 if options.test {
432 files.push(Planned {
433 path: root("tests").join(format!("{kebab}.rs")),
434 contents: format!(
435 "//! Tests for the `{kebab}` component.\n\nuse laravel::testing::prelude::*;\n\n#[laravel::test]\nasync fn the_{snake}_component_renders(app: Application) {{\n app.get(\"/{kebab}\").await.assert_ok();\n}}\n",
436 snake = snake_case(leaf),
437 ),
438 });
439 }
440
441 Ok(files)
442}
443
444pub fn write(plan: &[Planned], force: bool) -> laravel::Result<Vec<PathBuf>> {
450 let mut written = Vec::with_capacity(plan.len());
451
452 for file in plan {
453 if file.path.exists() && !force {
454 return Err(laravel::Error::msg(format!(
455 "{} already exists: pass --force to replace it",
456 file.path.display()
457 )));
458 }
459
460 if let Some(parent) = file.path.parent() {
461 std::fs::create_dir_all(parent)
462 .map_err(|error| laravel::Error::msg(format!("{} can't be created: {error}", parent.display())))?;
463 }
464
465 std::fs::write(&file.path, &file.contents)
466 .map_err(|error| laravel::Error::msg(format!("{} can't be written: {error}", file.path.display())))?;
467
468 written.push(file.path.clone());
469 }
470
471 Ok(written)
472}
473
474pub fn plan_layout(name: &str, base: Option<&Path>) -> laravel::Result<Vec<Planned>> {
480 let leaf = name.rsplit(['.', ':']).next().unwrap_or(name);
481 let valid = !leaf.is_empty()
482 && leaf
483 .chars()
484 .all(|character| character.is_alphanumeric() || matches!(character, '-' | '_'));
485
486 if !valid {
487 return Err(laravel::Error::msg(format!(
488 "[{name}] is not a layout name: use letters, digits, dashes, or underscores"
489 )));
490 }
491
492 let root = base.map_or_else(
493 || PathBuf::from("resources/views/layouts"),
494 |base| base.join("resources/views/layouts"),
495 );
496
497 Ok(vec![Planned {
498 path: root.join(leaf).with_extension("html"),
499 contents: layout_source(leaf),
500 }])
501}
502
503fn layout_source(name: &str) -> String {
505 format!(
506 r#"<!DOCTYPE html>
507<html lang="en">
508 <head>
509 <meta charset="utf-8">
510 <meta name="viewport" content="width=device-width, initial-scale=1">
511 <meta name="csrf-token" content="{{{{ csrf_token() }}}}">
512 <title>{{% block title %}}{name}{{% endblock %}} ยท {{{{ app_name }}}}</title>
513 {{{{ livewire_styles() }}}}
514 </head>
515 <body>
516 <main>
517 {{% block content %}}{{% endblock %}}
518 </main>
519 {{{{ livewire_scripts() }}}}
520 </body>
521</html>
522"#
523 )
524}
525
526#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct ConvertPlan {
529 pub files: Vec<Planned>,
531 pub leftover_view: Option<PathBuf>,
533}
534
535pub fn plan_convert(name: &str, base: Option<&Path>, config: &LivewireConfig) -> laravel::Result<ConvertPlan> {
541 let name = normalize_name(name).map_err(|error| laravel::Error::msg(error.to_string()))?;
542 let parts: Vec<&str> = name.split(['.', ':']).filter(|part| !part.is_empty()).collect();
543 let Some(leaf) = parts.last() else {
544 return Err(laravel::Error::msg("the component name is empty"));
545 };
546
547 let relative: PathBuf = parts.iter().collect();
548 let dotted = parts.join(".");
549 let struct_name = pascal_case(leaf);
550 let kebab = kebab_case(leaf);
551 let root = |path: &str| -> PathBuf { base.map_or_else(|| PathBuf::from(path), |base| base.join(path)) };
552
553 let module_path = root(&config.component_path).join(&relative).with_extension("rs");
554 let view_path = root(&config.view_path).join(&relative).with_extension("livewire");
555
556 let source = std::fs::read_to_string(&module_path)
557 .map_err(|error| laravel::Error::msg(format!("{} can't be read: {error}", module_path.display())))?;
558
559 if let Some(markup) = inline_markup(&source) {
560 return Ok(ConvertPlan {
561 files: vec![
562 Planned {
563 path: module_path,
564 contents: source.replace(
565 &format!("#[livewire(inline = \"{markup}\")]"),
566 &format!("#[livewire(view = \"livewire.{dotted}\")]"),
567 ),
568 },
569 Planned {
570 path: view_path,
571 contents: format!("{}\n", unescape_literal(&markup)),
572 },
573 ],
574 leftover_view: None,
575 });
576 }
577
578 if source.contains("#[livewire(view = ") {
579 let markup = std::fs::read_to_string(&view_path)
580 .map_err(|error| laravel::Error::msg(format!("{} can't be read: {error}", view_path.display())))?;
581 let escaped = escape_literal(markup.trim_end());
582
583 let start = source.find("#[livewire(view = ").unwrap_or(0);
584 let end = source[start..].find(']').map_or(source.len(), |end| start + end + 1);
585 let mut converted = String::with_capacity(source.len());
586 converted.push_str(&source[..start]);
587 let _ = write!(converted, "#[livewire(inline = \"{escaped}\")]");
588 converted.push_str(&source[end..]);
589
590 let _ = (struct_name, kebab);
591
592 return Ok(ConvertPlan {
593 files: vec![Planned {
594 path: module_path,
595 contents: converted,
596 }],
597 leftover_view: Some(view_path),
598 });
599 }
600
601 Err(laravel::Error::msg(format!(
602 "{} declares neither #[livewire(inline = ..)] nor #[livewire(view = ..)]",
603 module_path.display()
604 )))
605}
606
607fn inline_markup(source: &str) -> Option<String> {
609 let start = source.find("#[livewire(inline = \"")? + "#[livewire(inline = \"".len();
610 let rest = &source[start..];
611 let mut escaped = false;
612
613 for (index, character) in rest.char_indices() {
614 match character {
615 '\\' if !escaped => escaped = true,
616 '"' if !escaped => return Some(rest[..index].to_owned()),
617 _ => escaped = false,
618 }
619 }
620
621 None
622}
623
624fn escape_literal(markup: &str) -> String {
626 markup.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n")
627}
628
629fn unescape_literal(literal: &str) -> String {
631 let mut out = String::with_capacity(literal.len());
632 let mut characters = literal.chars();
633
634 while let Some(character) = characters.next() {
635 if character != '\\' {
636 out.push(character);
637 continue;
638 }
639
640 match characters.next() {
641 Some('n') => out.push('\n'),
642 Some('t') => out.push('\t'),
643 Some(other) => out.push(other),
644 None => {}
645 }
646 }
647
648 out
649}
650
651pub fn plan_publish(base: Option<&Path>) -> Vec<Planned> {
653 use laravel_core::embed::EmbeddedInternals as _;
654
655 let mut files = Vec::new();
656
657 for (path, bytes) in DIST.files() {
658 let contents = String::from_utf8_lossy(bytes).into_owned();
659 files.push(Planned {
660 path: base
661 .map_or_else(
662 || PathBuf::from("public/vendor/livewire"),
663 |base| base.join("public/vendor/livewire"),
664 )
665 .join(path),
666 contents,
667 });
668 }
669
670 files
671}
672
673pub fn plan_stubs(base: Option<&Path>) -> Vec<Planned> {
675 let root = base.map_or_else(|| PathBuf::from("stubs/livewire"), |base| base.join("stubs/livewire"));
676
677 vec![
678 Planned {
679 path: root.join("component.rs.stub"),
680 contents: module_source("Dummy", "dummy", "<div>\n <h2>Dummy</h2>\n</div>", Some("dummy")),
681 },
682 Planned {
683 path: root.join("view.livewire.stub"),
684 contents: "<div>\n <h2>Dummy</h2>\n</div>\n".to_owned(),
685 },
686 ]
687}
688
689static DIST: laravel::embed::Embedded = laravel::embed!("dist");
691
692fn read_stub(path: &Path) -> Option<String> {
694 std::fs::read_to_string(path).ok()
695}
696
697fn substitute(stub: &str, struct_name: &str, kebab: &str, dotted: &str) -> String {
700 stub.replace("livewire.dummy", &format!("livewire.{dotted}"))
701 .replace("Dummy", struct_name)
702 .replace("dummy", kebab)
703}
704
705fn module_source(struct_name: &str, kebab: &str, markup: &str, view: Option<&str>) -> String {
707 let view_attribute = match view {
708 Some(dotted) => format!("#[livewire(view = \"livewire.{dotted}\")]"),
709 None if markup.is_empty() => String::new(),
710 None => format!("#[livewire(inline = \"{}\")]", escape_literal(markup)),
711 };
712
713 format!(
714 r#"//! The `{kebab}` component.
715
716use livewire::{{LivewireComponent, component}};
717
718/// A component that {kebab}.
719#[derive(Default, LivewireComponent)]
720{view_attribute}
721pub struct {struct_name} {{
722 /// The text the component shows.
723 pub title: String,
724}}
725
726#[component]
727impl {struct_name} {{
728 /// Runs when the component first appears on the page.
729 pub fn mount(&mut self, title: Option<String>) {{
730 self.title = title.unwrap_or_else(|| "{struct_name}".to_owned());
731 }}
732}}
733"#
734 )
735}
736
737fn pascal_case(name: &str) -> String {
739 name.split(['-', '_'])
740 .filter(|part| !part.is_empty())
741 .map(|part| {
742 let mut characters = part.chars();
743 match characters.next() {
744 Some(first) => first.to_uppercase().collect::<String>() + characters.as_str(),
745 None => String::new(),
746 }
747 })
748 .collect()
749}
750
751fn kebab_case(name: &str) -> String {
753 let mut out = String::with_capacity(name.len() + 4);
754
755 for (index, character) in name.char_indices() {
756 if character.is_uppercase() {
757 if index > 0 {
758 out.push('-');
759 }
760 out.extend(character.to_lowercase());
761 } else if character == '_' {
762 out.push('-');
763 } else {
764 out.push(character);
765 }
766 }
767
768 out
769}
770
771fn snake_case(name: &str) -> String {
773 kebab_case(name).replace('-', "_")
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 fn options(kind: ComponentKind) -> Options {
781 Options {
782 kind,
783 js: false,
784 css: false,
785 test: false,
786 base: Some(PathBuf::from("/tmp/app")),
787 }
788 }
789
790 #[test]
791 fn a_single_file_component_carries_its_markup() {
792 let config = LivewireConfig::default();
793 let plan = plan("counter", &options(ComponentKind::Sfc), &config).expect("a plan");
794
795 assert_eq!(plan.len(), 1);
796 assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/counter.rs"));
797 assert!(plan[0].contents.contains("pub struct Counter"));
798 assert!(plan[0].contents.contains("#[livewire(inline = \"<div>"));
799 assert!(!plan[0].contents.contains("view = "));
800 }
801
802 #[test]
803 fn a_module_and_view_component_writes_both_files() {
804 let config = LivewireConfig::default();
805 let plan = plan("pages.counter", &options(ComponentKind::Mfc), &config).expect("a plan");
806
807 assert_eq!(plan.len(), 2);
808 assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/pages/counter.rs"));
809 assert!(
810 plan[0]
811 .contents
812 .contains("#[livewire(view = \"livewire.pages.counter\")]")
813 );
814 assert_eq!(
815 plan[1].path,
816 Path::new("/tmp/app/resources/views/livewire/pages/counter.livewire")
817 );
818 }
819
820 #[test]
821 fn a_namespace_through_colons_becomes_directories() {
822 let config = LivewireConfig::default();
823 let plan = plan("pages::counter", &options(ComponentKind::Mfc), &config).expect("a plan");
824
825 assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/pages/counter.rs"));
826 }
827
828 #[test]
829 fn the_module_and_css_and_test_files_follow_the_flags() {
830 let config = LivewireConfig::default();
831 let mut options = options(ComponentKind::Mfc);
832 options.js = true;
833 options.css = true;
834 options.test = true;
835
836 let plan = plan("post-editor", &options, &config).expect("a plan");
837
838 assert_eq!(plan.len(), 5);
839 assert!(plan.iter().any(|file| file.path.ends_with("post-editor.js")));
840 assert!(plan.iter().any(|file| file.path.ends_with("post-editor.css")));
841 assert!(
842 plan.iter()
843 .any(|file| file.path == Path::new("/tmp/app/tests/post-editor.rs"))
844 );
845 assert!(plan[0].contents.contains("pub struct PostEditor"));
846 }
847
848 #[test]
849 fn a_name_that_would_escape_the_directory_is_rejected() {
850 let config = LivewireConfig::default();
851
852 assert!(plan("../../etc/passwd", &options(ComponentKind::Sfc), &config).is_err());
853 assert!(plan("", &options(ComponentKind::Sfc), &config).is_err());
854 }
855
856 #[test]
857 fn an_existing_file_is_refused_without_force() {
858 let directory = tempfile::tempdir().expect("a temporary directory");
859 let config = LivewireConfig::default();
860 let mut options = options(ComponentKind::Mfc);
861 options.base = Some(directory.path().to_path_buf());
862
863 let plan = plan("counter", &options, &config).expect("a plan");
864 let written = write(&plan, false).expect("the first write succeeds");
865 assert_eq!(written.len(), 2);
866
867 let error = write(&plan, false).expect_err("the second write is refused");
868 assert!(error.to_string().contains("--force"));
869
870 write(&plan, true).expect("force replaces it");
871 }
872
873 #[test]
874 fn a_layout_loads_the_runtime_and_renders_a_content_block() {
875 let plan = plan_layout("app", Some(Path::new("/tmp/app"))).expect("a plan");
876
877 assert_eq!(plan.len(), 1);
878 assert_eq!(plan[0].path, Path::new("/tmp/app/resources/views/layouts/app.html"));
879 assert!(plan[0].contents.contains("{% block content %}"));
880 assert!(plan[0].contents.contains("{{ livewire_styles() }}"));
881 assert!(plan[0].contents.contains("{{ livewire_scripts() }}"));
882 assert!(plan[0].contents.contains("csrf-token"));
883 }
884
885 #[test]
886 fn a_layout_name_cannot_escape_its_directory() {
887 assert!(plan_layout("../secret", None).is_err());
888 assert!(plan_layout("app/../x", None).is_err());
889 }
890
891 #[test]
892 fn convert_moves_the_markup_between_the_module_and_its_view() {
893 let directory = tempfile::tempdir().expect("a temporary directory");
894 let base = directory.path();
895 let config = LivewireConfig::default();
896 let mut options = options(ComponentKind::Sfc);
897 options.base = Some(base.to_path_buf());
898
899 write(&plan("counter", &options, &config).expect("a plan"), false).expect("written");
901
902 let converted = plan_convert("counter", Some(base), &config).expect("a conversion");
903 assert!(
904 converted.leftover_view.is_none(),
905 "converting to a view leaves nothing behind"
906 );
907 assert!(
908 converted.files[0]
909 .contents
910 .contains("#[livewire(view = \"livewire.counter\")]")
911 );
912 assert!(!converted.files[0].contents.contains("inline"));
913 assert_eq!(
914 converted.files[1].path,
915 base.join("resources/views/livewire/counter.livewire")
916 );
917 assert!(converted.files[1].contents.contains("<h2>Counter</h2>"));
918 write(&converted.files, true).expect("written");
919
920 let restored = plan_convert("counter", Some(base), &config).expect("a conversion");
922 assert!(restored.files[0].contents.contains("#[livewire(inline = "));
923 assert!(restored.files[0].contents.contains("\\n <h2>Counter</h2>"));
924 assert_eq!(
925 restored.leftover_view,
926 Some(base.join("resources/views/livewire/counter.livewire"))
927 );
928 }
929
930 #[test]
931 fn convert_refuses_a_component_that_declares_neither_form() {
932 let directory = tempfile::tempdir().expect("a temporary directory");
933 let base = directory.path();
934 let config = LivewireConfig::default();
935
936 std::fs::create_dir_all(base.join("src/livewire")).expect("a directory");
937 std::fs::write(base.join("src/livewire/broken.rs"), "pub struct Broken;\n").expect("a file");
938
939 let error = plan_convert("broken", Some(base), &config).expect_err("refused");
940 assert!(error.to_string().contains("neither"));
941 }
942
943 #[test]
944 fn publish_carries_the_bundles_and_the_manifest() {
945 let plan = plan_publish(Some(Path::new("/tmp/app")));
946
947 assert!(plan.iter().any(|file| file.path.ends_with("livewire.min.js")));
948 assert!(plan.iter().any(|file| file.path.ends_with("manifest.json")));
949 assert!(plan.iter().all(|file| !file.contents.is_empty()));
950 }
951
952 #[test]
953 fn a_published_stub_replaces_the_built_in_template() {
954 let directory = tempfile::tempdir().expect("a temporary directory");
955 let base = directory.path();
956 let config = LivewireConfig::default();
957
958 write(&plan_stubs(Some(base)), false).expect("stubs written");
959
960 let mut options = options(ComponentKind::Mfc);
961 options.base = Some(base.to_path_buf());
962 let plan = plan("counter", &options, &config).expect("a plan");
963 let module = &plan[0].contents;
964
965 assert!(module.contains("pub struct Counter"), "the stub's struct was renamed");
966 assert!(module.contains("#[livewire(view = \"livewire.counter\")]"));
967 }
968
969 #[test]
970 fn every_generated_module_parses_as_rust() {
971 let config = LivewireConfig::default();
972
973 for kind in [ComponentKind::Sfc, ComponentKind::Mfc, ComponentKind::Class] {
974 let plan = plan("pages.post-editor", &options(kind), &config).expect("a plan");
975 let module = &plan[0];
976
977 syn::parse_file(&module.contents)
978 .unwrap_or_else(|error| panic!("the {kind} module does not parse: {error}\n{}", module.contents));
979 }
980 }
981
982 #[test]
983 fn the_generated_module_names_the_component_after_its_file() {
984 let config = LivewireConfig::default();
985 let plan = plan("post-editor", &options(ComponentKind::Sfc), &config).expect("a plan");
986
987 assert!(plan[0].contents.contains("//! The `post-editor` component."));
988 assert!(plan[0].contents.contains("pub struct PostEditor"));
989 assert!(!plan[0].contents.contains("sergio"));
990 }
991}