livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! The console commands the package registers, starting with `make:livewire`.
//!
//! The generator writes Rust, not PHP: a component is a module whose struct derives
//! `LivewireComponent` and whose implementation carries `#[livewire::component]`. The view is either
//! inline in the module or a sibling `.livewire` template.

use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use laravel::config::Section;
use laravel::console::{Console, clap};

use crate::config::{ComponentKind, LivewireConfig};
use crate::registry::normalize_name;

/// Creates a component module, and the view it renders.
#[derive(Debug, clap::Parser)]
#[command(name = "make:livewire", about = "Create a Livewire component and its view")]
pub struct MakeLivewire {
    /// The component's name, such as `counter`, `pages.counter`, or `pages::counter`.
    pub name: String,

    /// Write a module whose view it declares itself, as `--class` does.
    #[arg(long, conflicts_with_all = ["sfc", "inline"])]
    pub class: bool,

    /// Write one module that carries its markup, the default.
    #[arg(long, conflicts_with_all = ["mfc", "class", "inline"])]
    pub sfc: bool,

    /// Write a module beside a `.livewire` view.
    #[arg(long, conflicts_with_all = ["sfc", "class", "inline"])]
    pub mfc: bool,

    /// Write a module whose view is inline, as `--sfc` does.
    #[arg(long, conflicts_with_all = ["mfc", "class", "sfc"])]
    pub inline: bool,

    /// Also write an empty `.js` module for the component.
    #[arg(long)]
    pub js: bool,

    /// Also write an empty `.css` module for the component.
    #[arg(long)]
    pub css: bool,

    /// Also write a test file for the component.
    #[arg(long)]
    pub test: bool,

    /// Replace files that already exist.
    #[arg(long)]
    pub force: bool,

    /// Write into this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Creates a component, called by the `livewire:make` alias.
///
/// It takes the same options as [`MakeLivewire`], which it forwards to.
#[derive(Debug, clap::Parser)]
#[command(name = "livewire:make", about = "Create a Livewire component and its view")]
pub struct LivewireMake {
    /// The component's name, such as `counter`, `pages.counter`, or `pages::counter`.
    pub name: String,

    /// Write a module whose view it declares itself, as `--class` does.
    #[arg(long, conflicts_with_all = ["sfc", "inline"])]
    pub class: bool,

    /// Write one module that carries its markup, the default.
    #[arg(long, conflicts_with_all = ["mfc", "class", "inline"])]
    pub sfc: bool,

    /// Write a module beside a `.livewire` view.
    #[arg(long, conflicts_with_all = ["sfc", "class", "inline"])]
    pub mfc: bool,

    /// Write a module whose view is inline, as `--sfc` does.
    #[arg(long, conflicts_with_all = ["mfc", "class", "sfc"])]
    pub inline: bool,

    /// Also write an empty `.js` module for the component.
    #[arg(long)]
    pub js: bool,

    /// Also write an empty `.css` module for the component.
    #[arg(long)]
    pub css: bool,

    /// Also write a test file for the component.
    #[arg(long)]
    pub test: bool,

    /// Replace files that already exist.
    #[arg(long)]
    pub force: bool,

    /// Write into this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Prints the Livewire configuration the application resolved.
#[derive(Debug, clap::Parser)]
#[command(name = "livewire:config", about = "Show the resolved Livewire configuration")]
pub struct LivewireConfigCommand;

/// Reports whether the temporary upload disk needs a bucket lifecycle, which only an S3 disk has.
#[derive(Debug, clap::Parser)]
#[command(
    name = "livewire:configure-s3-upload-cleanup",
    about = "Configure temporary file upload s3 directory to automatically cleanup files older than 24hrs"
)]
pub struct ConfigureS3UploadCleanup;

/// Writes a layout a page component can render inside.
#[derive(Debug, clap::Parser)]
#[command(name = "livewire:layout", about = "Create a layout view for page components")]
pub struct Layout {
    /// The layout's name, such as `app`.
    pub name: String,

    /// Replace a file that already exists.
    #[arg(long)]
    pub force: bool,

    /// Write into this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Moves a component between its single-file and module-and-view forms.
#[derive(Debug, clap::Parser)]
#[command(
    name = "livewire:convert",
    about = "Convert a component between single-file and multi-file"
)]
pub struct Convert {
    /// The component's name, such as `counter` or `pages.counter`.
    pub name: String,

    /// Delete the view file the conversion leaves behind.
    #[arg(long)]
    pub remove_view: bool,

    /// Convert inside this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Publishes the runtime, so the application serves it from `public/`.
#[derive(Debug, clap::Parser)]
#[command(name = "livewire:publish", about = "Publish the Livewire front-end assets")]
pub struct Publish {
    /// Publish the front-end assets, which is the default and the only thing to publish.
    #[arg(long)]
    pub assets: bool,

    /// Replace files that already exist.
    #[arg(long)]
    pub force: bool,

    /// Write into this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Writes the stubs `make:livewire` copies, so an application can change them.
#[derive(Debug, clap::Parser)]
#[command(name = "livewire:stubs", about = "Publish the component stubs make:livewire uses")]
pub struct Stubs {
    /// Replace files that already exist.
    #[arg(long)]
    pub force: bool,

    /// Write into this directory instead of the application's own.
    #[arg(long)]
    pub path: Option<PathBuf>,
}

#[laravel::console::command]
impl MakeLivewire {
    async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
        let kind = if self.inline {
            ComponentKind::Sfc
        } else if self.class {
            ComponentKind::Class
        } else if self.mfc {
            ComponentKind::Mfc
        } else if self.sfc {
            ComponentKind::Sfc
        } else {
            config.make_command.kind
        };

        let options = Options {
            kind,
            js: self.js || config.make_command.js,
            css: self.css || config.make_command.css,
            test: self.test || config.make_command.test,
            base: self.path.clone(),
        };

        let plan = plan(&self.name, &options, &config)?;
        let written = write(&plan, self.force)?;

        for path in &written {
            console.line(format!("created {}", path.display()));
        }

        Ok(())
    }
}

#[laravel::console::command]
impl LivewireMake {
    async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
        let command = MakeLivewire {
            name: self.name,
            class: self.class,
            sfc: self.sfc,
            mfc: self.mfc,
            inline: self.inline,
            js: self.js,
            css: self.css,
            test: self.test,
            force: self.force,
            path: self.path,
        };

        MakeLivewire::handle(command, console, config).await
    }
}

#[laravel::console::command]
impl Layout {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let plan = plan_layout(&self.name, self.path.as_deref())?;
        let written = write(&plan, self.force)?;

        for path in &written {
            console.line(format!("created {}", path.display()));
        }

        Ok(())
    }
}

#[laravel::console::command]
impl Convert {
    async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
        let plan = plan_convert(&self.name, self.path.as_deref(), &config)?;

        // A conversion rewrites the module it just read, which is the operation the command is for.
        let written = write(&plan.files, true)?;

        for path in &written {
            console.line(format!("wrote {}", path.display()));
        }

        match (&plan.leftover_view, self.remove_view) {
            (Some(view), true) => {
                std::fs::remove_file(view)
                    .map_err(|error| laravel::Error::msg(format!("{} can't be removed: {error}", view.display())))?;
                console.line(format!("removed {}", view.display()));
            }
            (Some(view), false) => console.line(format!(
                "left {} in place: pass --remove-view to delete it",
                view.display()
            )),
            (None, _) => {}
        }

        Ok(())
    }
}

#[laravel::console::command]
impl Publish {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let plan = plan_publish(self.path.as_deref());
        let written = write(&plan, self.force)?;

        for path in &written {
            console.line(format!("published {}", path.display()));
        }

        Ok(())
    }
}

#[laravel::console::command]
impl Stubs {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let plan = plan_stubs(self.path.as_deref());
        let written = write(&plan, self.force)?;

        for path in &written {
            console.line(format!("published {}", path.display()));
        }

        Ok(())
    }
}

#[laravel::console::command]
impl ConfigureS3UploadCleanup {
    async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
        // Only an S3 disk has a bucket lifecycle to configure. The port ships the local disk, whose
        // directory a scheduled `livewire::uploads::prune` empties, so a disk named `s3` is
        // reported as unsupported instead of pretending the bucket was changed.
        if config.temporary_file_upload.disk.as_deref() != Some("s3") {
            console
                .error("Configuration ['livewire.temporary_file_upload.disk'] is not set to a disk with an S3 driver.");

            return Ok(());
        }

        console.error("This port does not talk to S3: schedule livewire::uploads::prune for the local disk instead.");

        Ok(())
    }
}

#[laravel::console::command]
impl LivewireConfigCommand {
    async fn handle(self, console: &mut Console, config: Section<LivewireConfig>) -> laravel::Result<()> {
        console.line(format!("{config:#?}"));

        Ok(())
    }
}

/// What the generator should write.
#[derive(Debug, Clone)]
pub struct Options {
    /// The component kind to write.
    pub kind: ComponentKind,
    /// Whether to write a `.js` module.
    pub js: bool,
    /// Whether to write a `.css` module.
    pub css: bool,
    /// Whether to write a test file.
    pub test: bool,
    /// The directory to write into, or `None` for the application's.
    pub base: Option<PathBuf>,
}

/// One file the generator writes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Planned {
    /// Where the file goes.
    pub path: PathBuf,
    /// What it holds.
    pub contents: String,
}

/// The files `name` needs, and their contents.
///
/// # Errors
///
/// Fails when the name is not a valid component name.
pub fn plan(name: &str, options: &Options, config: &LivewireConfig) -> laravel::Result<Vec<Planned>> {
    let name = normalize_name(name).map_err(|error| laravel::Error::msg(error.to_string()))?;

    let parts: Vec<&str> = name.split(['.', ':']).filter(|part| !part.is_empty()).collect();
    let Some(leaf) = parts.last() else {
        return Err(laravel::Error::msg("the component name is empty"));
    };

    let struct_name = pascal_case(leaf);
    let kebab = kebab_case(leaf);
    let dotted = parts.join(".");
    let relative: PathBuf = parts.iter().collect();

    let base = options.base.clone();
    let root = |path: &str| -> PathBuf {
        match &base {
            Some(base) => base.join(path),
            None => PathBuf::from(path),
        }
    };

    let component_path = root(&config.component_path).join(&relative).with_extension("rs");
    let view_path = root(&config.view_path).join(&relative).with_extension("livewire");

    let inline = matches!(options.kind, ComponentKind::Sfc);

    // An application that published the stubs owns them: `make:livewire` then fills them in.
    let markup = format!("<div>\n    <h2>{struct_name}</h2>\n</div>");
    let module = match read_stub(&root("stubs/livewire/component.rs.stub")) {
        Some(stub) => substitute(&stub, &struct_name, &kebab, &dotted),
        None if inline => module_source(&struct_name, &kebab, &markup, None),
        None => module_source(&struct_name, &kebab, "", Some(&dotted)),
    };

    let mut files = vec![Planned {
        path: component_path,
        contents: module,
    }];

    if !inline {
        let view = match read_stub(&root("stubs/livewire/view.livewire.stub")) {
            Some(stub) => substitute(&stub, &struct_name, &kebab, &dotted),
            None => format!("<div>\n    <h2>{struct_name}</h2>\n</div>\n"),
        };

        files.push(Planned {
            path: view_path.clone(),
            contents: view,
        });
    }

    if options.js {
        files.push(Planned {
            path: view_path.with_extension("js"),
            contents: format!("// The `{kebab}` component's browser module.\n"),
        });
    }

    if options.css {
        files.push(Planned {
            path: view_path.with_extension("css"),
            contents: format!("/* The `{kebab}` component's styles. */\n"),
        });
    }

    if options.test {
        files.push(Planned {
            path: root("tests").join(format!("{kebab}.rs")),
            contents: format!(
                "//! 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",
                snake = snake_case(leaf),
            ),
        });
    }

    Ok(files)
}

/// Writes the planned files, refusing to replace one that exists unless `force` is set.
///
/// # Errors
///
/// Fails when a file exists and `force` is not set, or when a file cannot be written.
pub fn write(plan: &[Planned], force: bool) -> laravel::Result<Vec<PathBuf>> {
    let mut written = Vec::with_capacity(plan.len());

    for file in plan {
        if file.path.exists() && !force {
            return Err(laravel::Error::msg(format!(
                "{} already exists: pass --force to replace it",
                file.path.display()
            )));
        }

        if let Some(parent) = file.path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|error| laravel::Error::msg(format!("{} can't be created: {error}", parent.display())))?;
        }

        std::fs::write(&file.path, &file.contents)
            .map_err(|error| laravel::Error::msg(format!("{} can't be written: {error}", file.path.display())))?;

        written.push(file.path.clone());
    }

    Ok(written)
}

/// The files `livewire:layout` writes.
///
/// # Errors
///
/// Fails when the name is not a plain layout name.
pub fn plan_layout(name: &str, base: Option<&Path>) -> laravel::Result<Vec<Planned>> {
    let leaf = name.rsplit(['.', ':']).next().unwrap_or(name);
    let valid = !leaf.is_empty()
        && leaf
            .chars()
            .all(|character| character.is_alphanumeric() || matches!(character, '-' | '_'));

    if !valid {
        return Err(laravel::Error::msg(format!(
            "[{name}] is not a layout name: use letters, digits, dashes, or underscores"
        )));
    }

    let root = base.map_or_else(
        || PathBuf::from("resources/views/layouts"),
        |base| base.join("resources/views/layouts"),
    );

    Ok(vec![Planned {
        path: root.join(leaf).with_extension("html"),
        contents: layout_source(leaf),
    }])
}

/// A page layout that loads the runtime and renders itself inside `{% block content %}`.
fn layout_source(name: &str) -> String {
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{{{ csrf_token() }}}}">
        <title>{{% block title %}}{name}{{% endblock %}} · {{{{ app_name }}}}</title>
        {{{{ livewire_styles() }}}}
    </head>
    <body>
        <main>
            {{% block content %}}{{% endblock %}}
        </main>
        {{{{ livewire_scripts() }}}}
    </body>
</html>
"#
    )
}

/// What `livewire:convert` changes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConvertPlan {
    /// The files to write.
    pub files: Vec<Planned>,
    /// The view file the conversion makes redundant, when it converted to a single file.
    pub leftover_view: Option<PathBuf>,
}

/// The conversion `name` needs, in whichever direction it is written today.
///
/// # Errors
///
/// Fails when the component does not exist, or when its module declares neither form.
pub fn plan_convert(name: &str, base: Option<&Path>, config: &LivewireConfig) -> laravel::Result<ConvertPlan> {
    let name = normalize_name(name).map_err(|error| laravel::Error::msg(error.to_string()))?;
    let parts: Vec<&str> = name.split(['.', ':']).filter(|part| !part.is_empty()).collect();
    let Some(leaf) = parts.last() else {
        return Err(laravel::Error::msg("the component name is empty"));
    };

    let relative: PathBuf = parts.iter().collect();
    let dotted = parts.join(".");
    let struct_name = pascal_case(leaf);
    let kebab = kebab_case(leaf);
    let root = |path: &str| -> PathBuf { base.map_or_else(|| PathBuf::from(path), |base| base.join(path)) };

    let module_path = root(&config.component_path).join(&relative).with_extension("rs");
    let view_path = root(&config.view_path).join(&relative).with_extension("livewire");

    let source = std::fs::read_to_string(&module_path)
        .map_err(|error| laravel::Error::msg(format!("{} can't be read: {error}", module_path.display())))?;

    if let Some(markup) = inline_markup(&source) {
        return Ok(ConvertPlan {
            files: vec![
                Planned {
                    path: module_path,
                    contents: source.replace(
                        &format!("#[livewire(inline = \"{markup}\")]"),
                        &format!("#[livewire(view = \"livewire.{dotted}\")]"),
                    ),
                },
                Planned {
                    path: view_path,
                    contents: format!("{}\n", unescape_literal(&markup)),
                },
            ],
            leftover_view: None,
        });
    }

    if source.contains("#[livewire(view = ") {
        let markup = std::fs::read_to_string(&view_path)
            .map_err(|error| laravel::Error::msg(format!("{} can't be read: {error}", view_path.display())))?;
        let escaped = escape_literal(markup.trim_end());

        let start = source.find("#[livewire(view = ").unwrap_or(0);
        let end = source[start..].find(']').map_or(source.len(), |end| start + end + 1);
        let mut converted = String::with_capacity(source.len());
        converted.push_str(&source[..start]);
        let _ = write!(converted, "#[livewire(inline = \"{escaped}\")]");
        converted.push_str(&source[end..]);

        let _ = (struct_name, kebab);

        return Ok(ConvertPlan {
            files: vec![Planned {
                path: module_path,
                contents: converted,
            }],
            leftover_view: Some(view_path),
        });
    }

    Err(laravel::Error::msg(format!(
        "{} declares neither #[livewire(inline = ..)] nor #[livewire(view = ..)]",
        module_path.display()
    )))
}

/// The markup of a module's `#[livewire(inline = "..")]` attribute, as written.
fn inline_markup(source: &str) -> Option<String> {
    let start = source.find("#[livewire(inline = \"")? + "#[livewire(inline = \"".len();
    let rest = &source[start..];
    let mut escaped = false;

    for (index, character) in rest.char_indices() {
        match character {
            '\\' if !escaped => escaped = true,
            '"' if !escaped => return Some(rest[..index].to_owned()),
            _ => escaped = false,
        }
    }

    None
}

/// Escapes markup for a Rust string literal.
fn escape_literal(markup: &str) -> String {
    markup.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n")
}

/// Reads markup back out of a Rust string literal, for the escapes the generator writes.
fn unescape_literal(literal: &str) -> String {
    let mut out = String::with_capacity(literal.len());
    let mut characters = literal.chars();

    while let Some(character) = characters.next() {
        if character != '\\' {
            out.push(character);
            continue;
        }

        match characters.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some(other) => out.push(other),
            None => {}
        }
    }

    out
}

/// The files `livewire:publish` writes: the runtime, from the copy embedded in this crate.
pub fn plan_publish(base: Option<&Path>) -> Vec<Planned> {
    use laravel_core::embed::EmbeddedInternals as _;

    let mut files = Vec::new();

    for (path, bytes) in DIST.files() {
        let contents = String::from_utf8_lossy(bytes).into_owned();
        files.push(Planned {
            path: base
                .map_or_else(
                    || PathBuf::from("public/vendor/livewire"),
                    |base| base.join("public/vendor/livewire"),
                )
                .join(path),
            contents,
        });
    }

    files
}

/// The stubs `livewire:stubs` writes, which `make:livewire` then copies.
pub fn plan_stubs(base: Option<&Path>) -> Vec<Planned> {
    let root = base.map_or_else(|| PathBuf::from("stubs/livewire"), |base| base.join("stubs/livewire"));

    vec![
        Planned {
            path: root.join("component.rs.stub"),
            contents: module_source("Dummy", "dummy", "<div>\n    <h2>Dummy</h2>\n</div>", Some("dummy")),
        },
        Planned {
            path: root.join("view.livewire.stub"),
            contents: "<div>\n    <h2>Dummy</h2>\n</div>\n".to_owned(),
        },
    ]
}

/// The runtime this crate carries, which `livewire:publish` copies out.
static DIST: laravel::embed::Embedded = laravel::embed!("dist");

/// A published stub's contents, when the application wrote one.
fn read_stub(path: &Path) -> Option<String> {
    std::fs::read_to_string(path).ok()
}

/// Fills a stub in: `Dummy` becomes the struct name, `dummy` the component name, and
/// `livewire.dummy` its view.
fn substitute(stub: &str, struct_name: &str, kebab: &str, dotted: &str) -> String {
    stub.replace("livewire.dummy", &format!("livewire.{dotted}"))
        .replace("Dummy", struct_name)
        .replace("dummy", kebab)
}

/// The module a new component starts as.
fn module_source(struct_name: &str, kebab: &str, markup: &str, view: Option<&str>) -> String {
    let view_attribute = match view {
        Some(dotted) => format!("#[livewire(view = \"livewire.{dotted}\")]"),
        None if markup.is_empty() => String::new(),
        None => format!("#[livewire(inline = \"{}\")]", escape_literal(markup)),
    };

    format!(
        r#"//! The `{kebab}` component.

use livewire::{{LivewireComponent, component}};

/// A component that {kebab}.
#[derive(Default, LivewireComponent)]
{view_attribute}
pub struct {struct_name} {{
    /// The text the component shows.
    pub title: String,
}}

#[component]
impl {struct_name} {{
    /// Runs when the component first appears on the page.
    pub fn mount(&mut self, title: Option<String>) {{
        self.title = title.unwrap_or_else(|| "{struct_name}".to_owned());
    }}
}}
"#
    )
}

/// `postEditor` and `post-editor` both become `PostEditor`.
fn pascal_case(name: &str) -> String {
    name.split(['-', '_'])
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut characters = part.chars();
            match characters.next() {
                Some(first) => first.to_uppercase().collect::<String>() + characters.as_str(),
                None => String::new(),
            }
        })
        .collect()
}

/// `PostEditor` and `post_editor` both become `post-editor`.
fn kebab_case(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 4);

    for (index, character) in name.char_indices() {
        if character.is_uppercase() {
            if index > 0 {
                out.push('-');
            }
            out.extend(character.to_lowercase());
        } else if character == '_' {
            out.push('-');
        } else {
            out.push(character);
        }
    }

    out
}

/// `PostEditor` becomes `post_editor`.
fn snake_case(name: &str) -> String {
    kebab_case(name).replace('-', "_")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn options(kind: ComponentKind) -> Options {
        Options {
            kind,
            js: false,
            css: false,
            test: false,
            base: Some(PathBuf::from("/tmp/app")),
        }
    }

    #[test]
    fn a_single_file_component_carries_its_markup() {
        let config = LivewireConfig::default();
        let plan = plan("counter", &options(ComponentKind::Sfc), &config).expect("a plan");

        assert_eq!(plan.len(), 1);
        assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/counter.rs"));
        assert!(plan[0].contents.contains("pub struct Counter"));
        assert!(plan[0].contents.contains("#[livewire(inline = \"<div>"));
        assert!(!plan[0].contents.contains("view = "));
    }

    #[test]
    fn a_module_and_view_component_writes_both_files() {
        let config = LivewireConfig::default();
        let plan = plan("pages.counter", &options(ComponentKind::Mfc), &config).expect("a plan");

        assert_eq!(plan.len(), 2);
        assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/pages/counter.rs"));
        assert!(
            plan[0]
                .contents
                .contains("#[livewire(view = \"livewire.pages.counter\")]")
        );
        assert_eq!(
            plan[1].path,
            Path::new("/tmp/app/resources/views/livewire/pages/counter.livewire")
        );
    }

    #[test]
    fn a_namespace_through_colons_becomes_directories() {
        let config = LivewireConfig::default();
        let plan = plan("pages::counter", &options(ComponentKind::Mfc), &config).expect("a plan");

        assert_eq!(plan[0].path, Path::new("/tmp/app/src/livewire/pages/counter.rs"));
    }

    #[test]
    fn the_module_and_css_and_test_files_follow_the_flags() {
        let config = LivewireConfig::default();
        let mut options = options(ComponentKind::Mfc);
        options.js = true;
        options.css = true;
        options.test = true;

        let plan = plan("post-editor", &options, &config).expect("a plan");

        assert_eq!(plan.len(), 5);
        assert!(plan.iter().any(|file| file.path.ends_with("post-editor.js")));
        assert!(plan.iter().any(|file| file.path.ends_with("post-editor.css")));
        assert!(
            plan.iter()
                .any(|file| file.path == Path::new("/tmp/app/tests/post-editor.rs"))
        );
        assert!(plan[0].contents.contains("pub struct PostEditor"));
    }

    #[test]
    fn a_name_that_would_escape_the_directory_is_rejected() {
        let config = LivewireConfig::default();

        assert!(plan("../../etc/passwd", &options(ComponentKind::Sfc), &config).is_err());
        assert!(plan("", &options(ComponentKind::Sfc), &config).is_err());
    }

    #[test]
    fn an_existing_file_is_refused_without_force() {
        let directory = tempfile::tempdir().expect("a temporary directory");
        let config = LivewireConfig::default();
        let mut options = options(ComponentKind::Mfc);
        options.base = Some(directory.path().to_path_buf());

        let plan = plan("counter", &options, &config).expect("a plan");
        let written = write(&plan, false).expect("the first write succeeds");
        assert_eq!(written.len(), 2);

        let error = write(&plan, false).expect_err("the second write is refused");
        assert!(error.to_string().contains("--force"));

        write(&plan, true).expect("force replaces it");
    }

    #[test]
    fn a_layout_loads_the_runtime_and_renders_a_content_block() {
        let plan = plan_layout("app", Some(Path::new("/tmp/app"))).expect("a plan");

        assert_eq!(plan.len(), 1);
        assert_eq!(plan[0].path, Path::new("/tmp/app/resources/views/layouts/app.html"));
        assert!(plan[0].contents.contains("{% block content %}"));
        assert!(plan[0].contents.contains("{{ livewire_styles() }}"));
        assert!(plan[0].contents.contains("{{ livewire_scripts() }}"));
        assert!(plan[0].contents.contains("csrf-token"));
    }

    #[test]
    fn a_layout_name_cannot_escape_its_directory() {
        assert!(plan_layout("../secret", None).is_err());
        assert!(plan_layout("app/../x", None).is_err());
    }

    #[test]
    fn convert_moves_the_markup_between_the_module_and_its_view() {
        let directory = tempfile::tempdir().expect("a temporary directory");
        let base = directory.path();
        let config = LivewireConfig::default();
        let mut options = options(ComponentKind::Sfc);
        options.base = Some(base.to_path_buf());

        // A single-file component first.
        write(&plan("counter", &options, &config).expect("a plan"), false).expect("written");

        let converted = plan_convert("counter", Some(base), &config).expect("a conversion");
        assert!(
            converted.leftover_view.is_none(),
            "converting to a view leaves nothing behind"
        );
        assert!(
            converted.files[0]
                .contents
                .contains("#[livewire(view = \"livewire.counter\")]")
        );
        assert!(!converted.files[0].contents.contains("inline"));
        assert_eq!(
            converted.files[1].path,
            base.join("resources/views/livewire/counter.livewire")
        );
        assert!(converted.files[1].contents.contains("<h2>Counter</h2>"));
        write(&converted.files, true).expect("written");

        // And back again.
        let restored = plan_convert("counter", Some(base), &config).expect("a conversion");
        assert!(restored.files[0].contents.contains("#[livewire(inline = "));
        assert!(restored.files[0].contents.contains("\\n    <h2>Counter</h2>"));
        assert_eq!(
            restored.leftover_view,
            Some(base.join("resources/views/livewire/counter.livewire"))
        );
    }

    #[test]
    fn convert_refuses_a_component_that_declares_neither_form() {
        let directory = tempfile::tempdir().expect("a temporary directory");
        let base = directory.path();
        let config = LivewireConfig::default();

        std::fs::create_dir_all(base.join("src/livewire")).expect("a directory");
        std::fs::write(base.join("src/livewire/broken.rs"), "pub struct Broken;\n").expect("a file");

        let error = plan_convert("broken", Some(base), &config).expect_err("refused");
        assert!(error.to_string().contains("neither"));
    }

    #[test]
    fn publish_carries_the_bundles_and_the_manifest() {
        let plan = plan_publish(Some(Path::new("/tmp/app")));

        assert!(plan.iter().any(|file| file.path.ends_with("livewire.min.js")));
        assert!(plan.iter().any(|file| file.path.ends_with("manifest.json")));
        assert!(plan.iter().all(|file| !file.contents.is_empty()));
    }

    #[test]
    fn a_published_stub_replaces_the_built_in_template() {
        let directory = tempfile::tempdir().expect("a temporary directory");
        let base = directory.path();
        let config = LivewireConfig::default();

        write(&plan_stubs(Some(base)), false).expect("stubs written");

        let mut options = options(ComponentKind::Mfc);
        options.base = Some(base.to_path_buf());
        let plan = plan("counter", &options, &config).expect("a plan");
        let module = &plan[0].contents;

        assert!(module.contains("pub struct Counter"), "the stub's struct was renamed");
        assert!(module.contains("#[livewire(view = \"livewire.counter\")]"));
    }

    #[test]
    fn every_generated_module_parses_as_rust() {
        let config = LivewireConfig::default();

        for kind in [ComponentKind::Sfc, ComponentKind::Mfc, ComponentKind::Class] {
            let plan = plan("pages.post-editor", &options(kind), &config).expect("a plan");
            let module = &plan[0];

            syn::parse_file(&module.contents)
                .unwrap_or_else(|error| panic!("the {kind} module does not parse: {error}\n{}", module.contents));
        }
    }

    #[test]
    fn the_generated_module_names_the_component_after_its_file() {
        let config = LivewireConfig::default();
        let plan = plan("post-editor", &options(ComponentKind::Sfc), &config).expect("a plan");

        assert!(plan[0].contents.contains("//! The `post-editor` component."));
        assert!(plan[0].contents.contains("pub struct PostEditor"));
        assert!(!plan[0].contents.contains("sergio"));
    }
}