puerto 0.23.0

Puerto — Rust full-stack DDD framework CLI. Scaffolds Clean Architecture projects with auto-wired DI, SQLx support, and zero manual wiring. Formerly puerto-framework.
import { useState } from "react";
import { Link, useLocation } from "wouter";
import type { Esquemas } from "../../../api/cliente";
import { desenvolver{% if targets %}, LIMITE_PAGINA_MAXIMO{% endif %} } from "../../../api/http";
{%- if targets %}
import { opcionesReferencia } from "../../../compartido/formularios";
{%- endif %}
import { AlertaError, codigoError } from "../../../compartido/ui/alerta-error";
import { useCarga } from "../../../compartido/use-carga";
import { useDependencias } from "../../../dependencias";
import { aProblema } from "../mensajes";
import { aFormulario{{ pascal }}, aPeticion{{ pascal }}, VistaFormulario{{ pascal }} } from "../vistas/formulario-{{ kebab }}";

type {{ pascal }} = Esquemas["Dto{{ pascal }}"];
{%- if targets %}

/** La primera página de cada entidad referenciada: lo que ofrecen sus selects. */
const PRIMERA_PAGINA = { params: { query: { limite: LIMITE_PAGINA_MAXIMO } } };
{%- endif %}

/** Crear, o editar con `id`: el formulario de {{ words_plural }}. */
export function ContenedorFormulario{{ pascal }}({ id }: { id?: string }) {
  const { api } = useDependencias();
  const existente = useCarga(
    () =>
      id === undefined
        ? Promise.resolve(null)
        : desenvolver(api.GET("/{{ plural }}/{id}", { params: { path: { id } } })),
    [api, id],
  );
  const titulo = id === undefined ? "Crear {{ words }}" : "Editar {{ words }}";

  return (
    <section className="space-y-4">
      <h1 className="text-2xl font-bold">{titulo}</h1>
      {existente.estado === "cargando" && <span className="loading loading-spinner" />}
      {existente.estado === "error" && <AlertaError error={existente.error} />}
      {existente.estado === "listo" && <Formulario{{ pascal }} existente={existente.datos} />}
      <Link href={id === undefined ? "/{{ plural }}" : `/{{ plural }}/${id}`} className="link">
        Cancelar
      </Link>
    </section>
  );
}

function Formulario{{ pascal }}({ existente }: { existente: {{ pascal }} | null }) {
  const { api } = useDependencias();
{%- for t in targets %}
{%- if t.load_inline %}
  const {{ t.plural_ident }} = useCarga(() => desenvolver(api.GET("/{{ t.plural }}", PRIMERA_PAGINA)), [api]);
{%- else %}
  const {{ t.plural_ident }} = useCarga(
    () => desenvolver(api.GET("/{{ t.plural }}", PRIMERA_PAGINA)),
    [api],
  );
{%- endif %}
{%- endfor %}
  const [, navegar] = useLocation();
  const [valores, setValores] = useState(aFormulario{{ pascal }}(existente));
  const [guardando, setGuardando] = useState(false);
  const [fallo, setFallo] = useState<unknown>(null);
  const problema = fallo === null ? null : aProblema(codigoError(fallo));

  const guardar = async () => {
    setGuardando(true);
    setFallo(null);
    try {
      const cuerpo = aPeticion{{ pascal }}(valores);
      const guardado = await desenvolver(
        existente === null
          ? api.POST("/{{ plural }}", { body: cuerpo })
{%- if save_inline %}
          : api.PUT("/{{ plural }}/{id}", { params: { path: { id: existente.id } }, body: cuerpo }),
{%- else %}
          : api.PUT("/{{ plural }}/{id}", {
              params: { path: { id: existente.id } },
              body: cuerpo,
            }),
{%- endif %}
      );
      navegar(`/{{ plural }}/${guardado.id}`);
    } catch (error) {
      setFallo(error);
      setGuardando(false);
    }
  };

  return (
    <div className="card bg-base-100">
      <div className="card-body">
        {problema?.campo === null && <AlertaError error={fallo} mensaje={problema.texto} />}
{%- for t in targets %}
        {{ "{" }}{{ t.plural_ident }}.estado === "error" && <AlertaError error={{ "{" }}{{ t.plural_ident }}.error} />}
{%- endfor %}
        <VistaFormulario{{ pascal }}
          valores={valores}
{%- if targets %}
          opciones={{ "{{" }}
{%- for t in targets %}{% for c in t.fields %}
            {{ c }}: opcionesReferencia({{ t.plural_ident }}, ({{ t.ident }}) => {{ t.ident }}.{{ t.label }}),
{%- endfor %}{% endfor %}
          }}
{%- endif %}
          guardando={guardando}
          problema={problema}
          alCambiar={setValores}
          alEnviar={guardar}
        />
      </div>
    </div>
  );
}