puerto 0.33.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
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
//! What each tab draws. Reads the `App`, never changes it.
use super::forms::{self, Kind, Suggestions};
use super::map::EdgeKind;
use super::{App, Tab};
use crate::generators::naming::pascal_to_snake;
use crate::puerto_toml::{Entity, Field};
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::symbols::Marker;
use ratatui::text::{Line, Span};
use ratatui::widgets::canvas::{Canvas, Line as Segment};
use ratatui::widgets::{Block, List, ListItem, ListState, Paragraph, Tabs, Wrap};

const SELECTED: Style = Style::new().fg(Color::Yellow).add_modifier(Modifier::BOLD);

pub fn render(frame: &mut Frame, app: &App) {
    let [top, body, bottom] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .areas(frame.area());
    let tab = match app.tab {
        Tab::Contexts => 0,
        Tab::Relations => 1,
        Tab::Generate => 2,
        Tab::Tasks => 3,
        Tab::Manual => 4,
    };
    frame.render_widget(
        Tabs::new([
            "1 Contextos",
            "2 Relaciones",
            "3 Generar",
            "4 Tareas",
            "5 Manual",
        ])
        .select(tab)
        .highlight_style(SELECTED)
        .divider("│"),
        top,
    );
    match app.tab {
        Tab::Contexts => contexts(frame, app, body),
        Tab::Relations => relations(frame, app, body),
        Tab::Generate => generate(frame, app, body),
        Tab::Tasks => tasks(frame, app, body),
        Tab::Manual => manual(frame, app, body),
    }
    let keys = if app.form.is_some() {
        "↑↓ campo · ←→ entidad o valor · Espacio casilla · Intro ejecutar · Esc volver"
    } else if app.tab == Tab::Tasks && app.task_line.is_some() {
        "Tab completar · ↑↓ elegir · Intro ejecutar · Esc cerrar"
    } else if app.tab == Tab::Tasks {
        "1-5 / Tab pestaña · ↑↓ elegir · Intro ejecutar · / escribir · q salir"
    } else if app.tab == Tab::Manual {
        "1-5 / Tab pestaña · ↑↓ comando · RePág AvPág desplazar · q salir"
    } else {
        "1-5 / Tab pestaña · ↑↓ elegir · Intro abrir · q salir"
    };
    let status = if app.status.is_empty() {
        Line::from(keys.dark_gray())
    } else {
        Line::from(vec![
            app.status.clone().bold(),
            "  ·  ".into(),
            keys.dark_gray(),
        ])
    };
    frame.render_widget(Paragraph::new(status), bottom);
}

fn entity_list(app: &App, title: &str) -> (List<'static>, ListState) {
    let items: Vec<ListItem> = app
        .config
        .entity
        .iter()
        .map(|e| ListItem::new(e.name.clone()))
        .collect();
    let state = ListState::default().with_selected((!items.is_empty()).then_some(app.entity));
    let list = List::new(items)
        .block(Block::bordered().title(format!(" {title} ")))
        .highlight_style(SELECTED)
        .highlight_symbol("▸ ");
    (list, state)
}

fn contexts(frame: &mut Frame, app: &App, area: Rect) {
    let [left, right] =
        Layout::horizontal([Constraint::Length(28), Constraint::Min(0)]).areas(area);
    let (list, mut state) = entity_list(app, &app.config.project.name);
    frame.render_stateful_widget(list, left, &mut state);
    let (title, lines) = match app.config.entity.get(app.entity) {
        Some(entity) => (format!(" {} ", entity.name), detail(app, entity)),
        None => (
            String::new(),
            vec![Line::from(
                "puerto.toml no declara entidades: pestaña 3, scaffold".dark_gray(),
            )],
        ),
    };
    frame.render_widget(
        Paragraph::new(lines)
            .block(Block::bordered().title(title))
            .wrap(Wrap { trim: false }),
        right,
    );
}

fn heading(text: &str) -> Line<'static> {
    Line::from(text.to_string().bold().cyan())
}

/// `name` padded, then what follows it.
fn row(name: &str, rest: Vec<Span<'static>>) -> Line<'static> {
    let mut spans = vec![format!("  {name:<22}").into()];
    spans.extend(rest);
    Line::from(spans)
}

fn field_type(entity: &Entity, field: &Field) -> Vec<Span<'static>> {
    let optional = field.field_type.starts_with("Option<");
    let mut spans: Vec<Span> = match (&field.references, &field.value_object) {
        (Some(target), _) => {
            let arrow = if field.field_type.starts_with("Vec<") {
                "⇉"
            } else if *target == entity.name {
                "↺"
            } else {
                "→"
            };
            let mut spans = vec![format!("{arrow} {target}").green()];
            if optional {
                spans.push(" (opcional)".dark_gray());
            }
            spans
        }
        (None, Some(vo)) => match &field.enum_variants {
            Some(variants) => vec![
                vo.clone().magenta(),
                format!(" enum {}", variants.join("/")).dark_gray(),
            ],
            // A composite one (Fase 31) is its own type: its parts say what it holds.
            None if !field.parts.is_empty() => {
                let parts: Vec<&str> = field.parts.iter().map(|p| p.name.as_str()).collect();
                vec![
                    vo.clone().magenta(),
                    format!(" ({})", parts.join(", ")).dark_gray(),
                ]
            }
            None => vec![
                vo.clone().magenta(),
                format!(" {}", field.field_type).dark_gray(),
            ],
        },
        (None, None) => vec![field.field_type.clone().into()],
    };
    if field.unique {
        spans.push(" !".yellow());
    }
    for (on, mark) in [
        (field.private, " privado".to_string()),
        (field.generated, " generado".to_string()),
        (
            field.default.is_some(),
            format!(" por defecto {}", field.default.clone().unwrap_or_default()),
        ),
    ] {
        if on {
            spans.push(mark.dark_gray());
        }
    }
    spans
}

fn detail(app: &App, entity: &Entity) -> Vec<Line<'static>> {
    let snake = pascal_to_snake(&entity.name);
    let mut lines = vec![
        Line::from(format!("contextos/{snake}/").dark_gray()),
        Line::default(),
        heading("Campos"),
    ];
    for field in crate::generators::effective_fields(&entity.fields) {
        lines.push(row(&field.name, field_type(entity, &field)));
    }
    lines.push(Line::default());
    lines.push(heading("Casos de uso"));
    for use_case in &entity.use_cases {
        let mut marks: Vec<String> = Vec::new();
        if entity.public.contains(use_case) {
            marks.push("público".into());
        }
        if let Some(roles) = entity.roles.get(use_case) {
            marks.push(format!("rol {}", roles.join(", ")));
        }
        if entity.role_only.contains(use_case) {
            marks.push("solo rol".into());
        }
        if entity.internal.contains(use_case) {
            marks.push("interno".into());
        }
        lines.push(row(use_case, vec![marks.join(" · ").dark_gray()]));
    }
    let lists = [
        ("Transiciones", entity.transitions.join(", ")),
        ("Eventos propios", entity.events.join(", ")),
        ("Propietario", entity.owner.clone().unwrap_or_default()),
        (
            "Únicos",
            entity
                .uniques
                .iter()
                .map(|u| u.join(" + "))
                .collect::<Vec<_>>()
                .join(", "),
        ),
        ("Orden", entity.order.join(", ")),
    ];
    for (label, value) in lists.into_iter().filter(|(_, v)| !v.is_empty()) {
        lines.push(Line::default());
        lines.push(Line::from(vec![
            format!("{label:<17}").bold().cyan(),
            value.into(),
        ]));
    }
    let listeners = super::map::listeners(&app.config, &entity.name);
    if !listeners.is_empty() {
        lines.push(Line::default());
        lines.push(heading("Escuchan sus eventos"));
        for (event, who) in listeners {
            lines.push(row(&event, vec![format!("→ {}", who.join(", ")).green()]));
        }
    }
    lines
}

fn relations(frame: &mut Frame, app: &App, area: Rect) {
    let [canvas_area, list_area] =
        Layout::vertical([Constraint::Min(0), Constraint::Length(7)]).areas(area);
    let map = &app.map;
    let layers = map.layer_count().max(1);
    // Where each node goes: its layer from the bottom, spread evenly along it.
    let positions: Vec<(f64, f64)> = (0..map.nodes.len())
        .map(|node| {
            let layer = map.layer(node);
            let row: Vec<usize> = (0..map.nodes.len())
                .filter(|n| map.layer(*n) == layer)
                .collect();
            let at = row.iter().position(|n| *n == node).unwrap_or(0);
            (
                (at as f64 + 0.5) * 100.0 / row.len() as f64,
                (layer as f64 + 0.5) * 100.0 / layers as f64,
            )
        })
        .collect();
    // A canvas unit per terminal cell, to centre the names.
    let cell = 100.0 / f64::from(canvas_area.width.saturating_sub(2).max(1));
    let selected = app.entity;
    let canvas = Canvas::default()
        .block(
            Block::bordered().title(" El mapa de contextos: cada uno, sobre los que referencia "),
        )
        .marker(Marker::Braille)
        .x_bounds([0.0, 100.0])
        .y_bounds([0.0, 100.0])
        .paint(|ctx| {
            for edge in map.edges.iter().filter(|e| e.from != e.to) {
                let ((x1, y1), (x2, y2)) = (positions[edge.from], positions[edge.to]);
                let color = if edge.from == selected || edge.to == selected {
                    Color::Yellow
                } else {
                    Color::DarkGray
                };
                ctx.draw(&Segment::new(x1, y1, x2, y2, color));
            }
            ctx.layer();
            for (node, (x, y)) in map.nodes.iter().zip(&positions) {
                let index = map.nodes.iter().position(|n| n.name == node.name);
                let self_ref =
                    index.is_some_and(|i| map.edges.iter().any(|e| e.from == i && e.to == i));
                let label = format!(" {}{} ", node.name, if self_ref { " ↺" } else { "" });
                let style = if index == Some(selected) {
                    SELECTED.bg(Color::Black)
                } else if node.declared {
                    Style::new().bg(Color::Black)
                } else {
                    Style::new().fg(Color::DarkGray).bg(Color::Black)
                };
                let width = label.chars().count() as f64 * cell;
                ctx.print(x - width / 2.0, *y, Line::from(Span::styled(label, style)));
            }
        });
    frame.render_widget(canvas, canvas_area);

    let describe = |kind: EdgeKind| match kind {
        EdgeKind::Required => "",
        EdgeKind::Optional => " (opcional)",
        EdgeKind::Set => " (conjunto)",
    };
    let mut lines = Vec::new();
    if selected < map.nodes.len() {
        for edge in map.outgoing(selected) {
            lines.push(Line::from(format!(
                "{} → {}{}",
                edge.field,
                map.nodes[edge.to].name,
                describe(edge.kind)
            )));
        }
        for edge in map.incoming(selected) {
            lines.push(Line::from(
                format!(
                    "{}.{} → {}{}",
                    map.nodes[edge.from].name,
                    edge.field,
                    map.nodes[selected].name,
                    describe(edge.kind)
                )
                .dark_gray(),
            ));
        }
        if lines.is_empty() {
            lines.push(Line::from("ni referencia ni la referencian".dark_gray()));
        }
    }
    let title = app
        .config
        .entity
        .get(selected)
        .map(|e| format!(" {} (↑↓ otra) ", e.name))
        .unwrap_or_default();
    frame.render_widget(
        Paragraph::new(lines).block(Block::bordered().title(title)),
        list_area,
    );
}

fn generate(frame: &mut Frame, app: &App, area: Rect) {
    let [left, right] =
        Layout::horizontal([Constraint::Length(28), Constraint::Min(0)]).areas(area);
    let items: Vec<ListItem> = app
        .generators
        .iter()
        .map(|g| ListItem::new(g.name.clone()))
        .collect();
    let mut state = ListState::default().with_selected(Some(app.generator));
    frame.render_stateful_widget(
        List::new(items)
            .block(Block::bordered().title(" Generar "))
            .highlight_style(SELECTED)
            .highlight_symbol("▸ "),
        left,
        &mut state,
    );
    let Some(generator) = app.generators.get(app.generator) else {
        return;
    };
    let title = format!(" {} ", generator.command.join(" "));
    let Some(form) = &app.form else {
        // Before opening it: what it does and what it takes.
        let mut lines = vec![Line::from(generator.about.clone()), Line::default()];
        for input in &generator.inputs {
            lines.push(Line::from(vec![
                format!("{:<24}", input.label).bold(),
                first_line(&input.help).dark_gray(),
            ]));
        }
        lines.push(Line::default());
        lines.push(Line::from("Intro para rellenarlo".yellow()));
        // One line each, cut at the edge: the whole text is in «Qué hace», on the input.
        frame.render_widget(
            Paragraph::new(lines).block(Block::bordered().title(title)),
            right,
        );
        return;
    };
    let [inputs_area, help_area] =
        Layout::vertical([Constraint::Min(0), Constraint::Length(8)]).areas(right);
    let mut lines = vec![
        Line::from(generator.about.clone().dark_gray()),
        Line::default(),
    ];
    for (at, input) in generator.inputs.iter().enumerate() {
        let focused = at == form.focus;
        let shown = match input.kind {
            Kind::Switch => if form.ticked[at] { "[x]" } else { "[ ]" }.to_string(),
            _ if input.suggestions != Suggestions::None => format!("‹ {} ›", form.values[at]),
            _ => form.values[at].clone(),
        };
        let cursor = if focused && input.kind != Kind::Switch {
            "▏"
        } else {
            ""
        };
        let mark = if input.required { "*" } else { " " };
        let line = Line::from(vec![
            if focused { "▸ " } else { "  " }.into(),
            format!("{:<24}{mark}", input.label).bold(),
            format!(" {shown}{cursor}").into(),
        ]);
        lines.push(if focused {
            line.style(Style::new().fg(Color::Yellow))
        } else {
            line
        });
    }
    lines.push(Line::default());
    lines.push(match form.args() {
        Ok(args) => Line::from(format!("› {}", forms::command_line(&args)).green()),
        Err(missing) => Line::from(format!("› {missing}").dark_gray()),
    });
    // Keep the focused input on screen: the about line, the blank one, then one per input.
    let visible = inputs_area.height.saturating_sub(2);
    let focus_line = form.focus as u16 + 2;
    let scroll = (focus_line + 1).saturating_sub(visible);
    frame.render_widget(
        Paragraph::new(lines)
            .block(Block::bordered().title(title))
            .scroll((scroll, 0)),
        inputs_area,
    );
    let help = generator
        .inputs
        .get(form.focus)
        .map(|i| format!("{}: {}", i.label, i.help))
        .unwrap_or_default();
    frame.render_widget(
        Paragraph::new(help)
            .block(Block::bordered().title(" Qué hace "))
            .wrap(Wrap { trim: false }),
        help_area,
    );
}

fn first_line(text: &str) -> String {
    text.lines().next().unwrap_or_default().to_string()
}

/// 37.8: the command line on top, the tasks it leaves under it.
fn tasks(frame: &mut Frame, app: &App, area: Rect) {
    let taskfile = match &app.tasks {
        Ok(taskfile) => taskfile,
        Err(why) => {
            frame.render_widget(
                Paragraph::new(why.clone())
                    .block(Block::bordered().title(" Tareas "))
                    .wrap(Wrap { trim: false }),
                area,
            );
            return;
        }
    };
    let [line_area, list_area] =
        Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).areas(area);
    let command = match &app.task_line {
        Some(line) => Line::from(vec![
            format!("$ {} ", taskfile.bin).dark_gray(),
            line.clone().bold(),
            "▏".into(),
        ]),
        None => Line::from(
            format!(
                "/ para escribir: {} <tarea> [argumentos] (p. ej. test:dominio -- --nocapture)",
                taskfile.bin
            )
            .dark_gray(),
        ),
    };
    frame.render_widget(
        Paragraph::new(command).block(Block::bordered().title(" Comando ")),
        line_area,
    );
    let shown = super::tasks::filtered(&taskfile.tasks, app.task_line.as_deref());
    let width = shown
        .iter()
        .map(|t| t.name.len())
        .max()
        .unwrap_or(0)
        .min(28);
    let items: Vec<ListItem> = shown
        .iter()
        .map(|t| {
            ListItem::new(Line::from(vec![
                format!("{:<width$}  ", t.name).into(),
                t.desc.clone().dark_gray(),
            ]))
        })
        .collect();
    let mut state = ListState::default().with_selected((!items.is_empty()).then_some(app.task));
    frame.render_stateful_widget(
        List::new(items)
            .block(Block::bordered().title(" Tareas (Taskfile.yml) "))
            .highlight_style(SELECTED)
            .highlight_symbol("▸ "),
        list_area,
        &mut state,
    );
}

fn manual(frame: &mut Frame, app: &App, area: Rect) {
    let [left, right] =
        Layout::horizontal([Constraint::Length(36), Constraint::Min(0)]).areas(area);
    let items: Vec<ListItem> = app
        .manual
        .iter()
        .map(|page| ListItem::new(page.command.clone()))
        .collect();
    let mut state = ListState::default().with_selected(Some(app.page));
    frame.render_stateful_widget(
        List::new(items)
            .block(Block::bordered().title(" Manual "))
            .highlight_style(SELECTED)
            .highlight_symbol("▸ "),
        left,
        &mut state,
    );
    if let Some(page) = app.manual.get(app.page) {
        // clap wraps it to the pane, with its own indentation; the paragraph does not again.
        let width = usize::from(right.width.saturating_sub(2)).max(20);
        frame.render_widget(
            Paragraph::new(page.help(width))
                .block(Block::bordered().title(format!(" {} --help ", page.command)))
                .scroll((app.scroll, 0)),
            right,
        );
    }
}