puerto 0.31.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.
import type { Esquemas } from "../../../api/cliente";
{%- if form_helpers %}
import {% if form_helpers_type_only %}type {% endif %}{ {{ form_helpers | join(sep=", ") }} } from "../../../compartido/formularios";
{%- endif %}
import { ErrorCampo } from "../../../compartido/ui/error-campo";
{%- set enums = form_fields | filter(attribute="is_enum", value=true) %}
{%- if enums %}
import { {% for f in enums %}{{ f.texts_const }}{% if not loop.last %}, {% endif %}{% endfor %} } from "../../../generado/textos";
{%- endif %}
import type { Problema{{ pascal }} } from "../mensajes";

type {{ pascal }} = Esquemas["Dto{{ pascal }}"];
type Peticion{{ pascal }} = Esquemas["{% if defaulted %}PeticionActualizar{% else %}PeticionCrear{% endif %}{{ pascal }}"];

/** Lo que guardan los inputs: el texto de cada input, `checked` en una casilla. */
export interface ValoresFormulario{{ pascal }} {
{%- for f in form_fields %}{% if f.is_composite %}{% for p in f.parts %}
  {{ p.camel }}: {% if p.input == "checkbox" %}boolean{% else %}string{% endif %};
{%- endfor %}{% else %}
  {{ f.camel }}: {% if f.input == "checkbox" %}boolean{% elif f.input == "references" %}string[]{% else %}string{% endif %};
{%- endif %}{% endfor %}
}

/** Los inputs de `{{ ident }}`, vacíos cuando todavía no hay ninguno. */
{% if to_form_inline -%}
export function aFormulario{{ pascal }}({{ ident }}: {{ pascal }} | null): ValoresFormulario{{ pascal }} {
{%- else -%}
export function aFormulario{{ pascal }}(
  {{ ident }}: {{ pascal }} | null,
): ValoresFormulario{{ pascal }} {
{%- endif %}
  if ({{ ident }} === null) {
    return {
{%- for f in form_fields %}{% if f.is_composite %}{% for p in f.parts %}
      {{ p.camel }}: {{ p.empty_form }},
{%- endfor %}{% else %}
      {{ f.camel }}: {{ f.empty_form }},
{%- endif %}{% endfor %}
    };
  }
  return {
{%- for f in form_fields %}{% if f.is_composite %}{% for p in f.parts %}
    {{ p.camel }}: {{ p.to_form }},
{%- endfor %}{% else %}
    {{ f.camel }}: {{ f.to_form }},
{%- endif %}{% endfor %}
  };
}

{% if targets -%}
/** Lo que ofrece el select de cada referencia. */
export interface OpcionesFormulario{{ pascal }} {
{%- for f in form_fields %}{% if f.input == "reference" or f.input == "references" %}
  {{ f.camel }}: OpcionReferencia[];
{%- endif %}{% endfor %}
}

{% endif -%}
/** Lo que mandan crear y actualizar: los mismos campos en los dos. */
{% if to_request_inline -%}
export function aPeticion{{ pascal }}(valores: ValoresFormulario{{ pascal }}): Peticion{{ pascal }} {
{%- else -%}
export function aPeticion{{ pascal }}(
  valores: ValoresFormulario{{ pascal }},
): Peticion{{ pascal }} {
{%- endif %}
  return {
{%- for f in form_fields %}
    {{ f.camel }}: {{ f.from_form }},
{%- endfor %}
  };
}

export function VistaFormulario{{ pascal }}({
  valores,
{%- if targets %}
  opciones,
{%- endif %}
  guardando,
{%- if defaulted %}
  creando,
{%- endif %}
  problema,
  alCambiar,
  alEnviar,
}: {
  valores: ValoresFormulario{{ pascal }};
{%- if targets %}
  opciones: OpcionesFormulario{{ pascal }};
{%- endif %}
  guardando: boolean;
{%- if defaulted %}
  /** Crear no pide lo que pone el servidor (`por_defecto`): sus inputs solo se ven al editar. */
  creando: boolean;
{%- endif %}
  /** Lo que dijo la API del último envío: se muestra bajo su input. */
  problema: Problema{{ pascal }} | null;
  alCambiar: (valores: ValoresFormulario{{ pascal }}) => void;
  alEnviar: () => void;
}) {
  return (
    <form
      className="space-y-2"
      onSubmit={(event) => {
        event.preventDefault();
        alEnviar();
      }}
    >
{%- for f in form_fields %}
{%- if f.is_composite %}
      <fieldset className="fieldset">
        <legend className="fieldset-legend">{{ f.label }}</legend>
{%- for p in f.parts %}
{%- if p.input == "checkbox" %}
        <label className="label">
          <input
            className="checkbox"
            type="checkbox"
            checked={valores.{{ p.camel }}}
            onChange={(event) => alCambiar({ ...valores, {{ p.camel }}: event.target.checked })}
          />
          {{ p.label }}
        </label>
{%- elif p.input == "select" %}
        <label className="fieldset">
          <span className="fieldset-legend">{{ p.label }}</span>
          <select
            className="select w-full"
            value={valores.{{ p.camel }}}
            onChange={(event) => alCambiar({ ...valores, {{ p.camel }}: event.target.value })}
          >
            <option value="">{{ p.placeholder }}</option>
{%- for o in p.options %}
            <option value="{{ o.value }}">{{ o.label }}</option>
{%- endfor %}
          </select>
        </label>
{%- else %}
        <label className="fieldset">
          <span className="fieldset-legend">{{ p.label }}</span>
          <input
            className="input w-full"
            type="{{ p.input }}"
            aria-invalid={problema?.campo === "{{ p.camel }}"}
{%- if p.decimal %}
            step="any"
{%- endif %}
{%- if p.required %}
            required
{%- endif %}
            value={valores.{{ p.camel }}}
            onChange={(event) => alCambiar({ ...valores, {{ p.camel }}: event.target.value })}
          />
        </label>
        <ErrorCampo problema={problema} campo="{{ p.camel }}" />
{%- endif %}
{%- endfor %}
      </fieldset>
{%- elif f.input == "references" %}
      <fieldset className="fieldset">
        <legend className="fieldset-legend">{{ f.label }}</legend>
        {opciones.{{ f.camel }}.map((opcion) => (
          <label key={opcion.id} className="label">
            <input
              className="checkbox"
              type="checkbox"
              value={opcion.id}
              checked={valores.{{ f.camel }}.includes(opcion.id)}
              onChange={(event) =>
                alCambiar({
                  ...valores,
                  {{ f.camel }}: event.target.checked
                    ? [...valores.{{ f.camel }}, opcion.id]
                    : valores.{{ f.camel }}.filter((id) => id !== opcion.id),
                })
              }
            />
            {opcion.etiqueta}
          </label>
        ))}
      </fieldset>
      <ErrorCampo problema={problema} campo="{{ f.camel }}" />
{%- elif f.input == "checkbox" %}
      <label className="label"{% if f.defaulted %} hidden={creando}{% endif %}>
        <input
          className="checkbox"
          type="checkbox"
          checked={valores.{{ f.camel }}}
          onChange={(event) => alCambiar({ ...valores, {{ f.camel }}: event.target.checked })}
        />
        {{ f.label }}
      </label>
{%- elif f.input == "select" %}
      <label className="fieldset"{% if f.defaulted %} hidden={creando}{% endif %}>
        <span className="fieldset-legend">{{ f.label }}</span>
        <select
          className="select w-full"
          aria-invalid={problema?.campo === "{{ f.camel }}"}
{%- if f.required %}
          required
{%- endif %}
          value={valores.{{ f.camel }}}
          onChange={(event) => alCambiar({ ...valores, {{ f.camel }}: event.target.value })}
        >
{%- if not f.is_enum or not f.required %}
          <option value="">{{ f.placeholder }}</option>
{%- endif %}
{%- if f.is_enum %}
          {Object.entries({{ f.texts_const }}).map(([valor, texto]) => (
            <option key={valor} value={valor}>
              {texto}
            </option>
          ))}
{%- else %}
{%- for o in f.options %}
          <option value="{{ o.value }}">{{ o.label }}</option>
{%- endfor %}
{%- endif %}
        </select>
      </label>
      <ErrorCampo problema={problema} campo="{{ f.camel }}" />
{%- elif f.input == "reference" %}
      <label className="fieldset"{% if f.defaulted %} hidden={creando}{% endif %}>
        <span className="fieldset-legend">{{ f.label }}</span>
        <select
          className="select w-full"
          aria-invalid={problema?.campo === "{{ f.camel }}"}
{%- if f.required %}
          required
{%- endif %}
          value={valores.{{ f.camel }}}
          onChange={(event) => alCambiar({ ...valores, {{ f.camel }}: event.target.value })}
        >
          <option value="">{{ f.placeholder }}</option>
          {opciones.{{ f.camel }}.map((opcion) => (
            <option key={opcion.id} value={opcion.id}>
              {opcion.etiqueta}
            </option>
          ))}
        </select>
      </label>
      <ErrorCampo problema={problema} campo="{{ f.camel }}" />
{%- elif f.input == "textarea" %}
      <label className="fieldset"{% if f.defaulted %} hidden={creando}{% endif %}>
        <span className="fieldset-legend">{{ f.label }}</span>
        <textarea
          className="textarea w-full"
          aria-invalid={problema?.campo === "{{ f.camel }}"}
          placeholder="clave=valor, una por línea"
          value={valores.{{ f.camel }}}
          onChange={(event) => alCambiar({ ...valores, {{ f.camel }}: event.target.value })}
        />
      </label>
      <ErrorCampo problema={problema} campo="{{ f.camel }}" />
{%- else %}
      <label className="fieldset"{% if f.defaulted %} hidden={creando}{% endif %}>
        <span className="fieldset-legend">{{ f.label }}</span>
        <input
          className="input w-full"
          type="{{ f.input }}"
          aria-invalid={problema?.campo === "{{ f.camel }}"}
{%- if f.decimal %}
          step="any"
{%- endif %}
{%- if f.required %}
          required
{%- endif %}
          value={valores.{{ f.camel }}}
          onChange={(event) => alCambiar({ ...valores, {{ f.camel }}: event.target.value })}
        />
      </label>
      <ErrorCampo problema={problema} campo="{{ f.camel }}" />
{%- endif %}
{%- endfor %}
      <button type="submit" className="btn btn-primary" disabled={guardando}>
        Guardar
      </button>
    </form>
  );
}