Skip to content

jooby-htmx#3940

Open
jknack wants to merge 1 commit intomainfrom
3936
Open

jooby-htmx#3940
jknack wants to merge 1 commit intomainfrom
3936

Conversation

@jknack
Copy link
Copy Markdown
Member

@jknack jknack commented May 7, 2026

…ingle Page Applications (SPAs) without heavy JavaScript frameworks, Jooby developers need a first-class way to handle HTMX's unique response lifecycle. Currently, managing HX-Request headers, Out-Of-Band (OOB) swaps, Javascript triggers, and partial vs. full-page layout rendering requires significant boilerplate and repetitive try/catch logic in every controller.

Introduce jooby-htmx, a dedicated module providing both a Declarative Annotation API (via APT generation) and a memory-safe Imperative Builder API to orchestrate HTMX responses seamlessly. This allows developers to write 100% pure "Happy Path" business logic while the framework handles the UI state.

1. The Interceptor Pipeline (HtmxModule & HtmxMessageEncoder)

  • Registers directly into Jooby's MessageEncoder chain ahead of standard template engines.
  • Intercepts HtmxModelAndView payloads and safely drives the underlying template engine (e.g., Handlebars) in a loop to concatenate the primary view and multiple OOB templates into a single HTTP response.

2. The Imperative API (HtmxResponse)

  • A fluent builder for scenarios lacking a primary view (e.g., HTTP 204 No Content for drag-and-drop reordering or delete operations).
  • Easily chains multiple .addOob() and .trigger() events.

3. The Declarative API (APT Code Generation)

  • @HxView(value = "partial.hbs", layout = "base.hbs"): Automatically serves the partial for HTMX AJAX requests, but smartly wraps it in the layout for direct browser navigation or F5 refreshes.
  • @HxOob("counter.hbs") & @HxTrigger("itemAdded"): Automatically injects the necessary headers and models into the response.
  • @HxError("error.hbs"): The "UI Janitor". Automatically catches Bean Validation (@Valid) ConstraintViolationExceptions to render scoped inline errors (HTTP 422). Crucially, it automatically appends an empty OOB swap on success to instantly clear the UI of previous errors.

4. Global Error Resilience

  • Allows passing an HtmxErrorHandler directly into install(new HtmxModule(errorHandler)).
  • Safely intercepts global 500 server crashes and translates them into OOB Toast notifications, preventing raw HTML stack traces from breaking the client's DOM.

The resulting controller is entirely decoupled from HTTP headers and serialization logic:

@POST("/tasks")
@HxView("task_row.hbs")
@HxOob("task_counter.hbs")
@HxOob("toast.hbs")
@HxTrigger("taskAdded")
@HxError("task_error.hbs") // Automatically renders errors on failure, and clears them on success!
public Map<String, Object> addTask(@FormParam @Valid TaskDto dto) {
    var newTask = db.save(dto);

    return Map.of(
        "id", newTask.id(),
        "title", newTask.title(),
        "activeCount", db.getActiveCount(),
        "message", "Task added successfully!"
    );
}

fix #3936

…ingle Page Applications (SPAs) without heavy JavaScript frameworks, Jooby developers need a first-class way to handle HTMX's unique response lifecycle. Currently, managing `HX-Request` headers, Out-Of-Band (OOB) swaps, Javascript triggers, and partial vs. full-page layout rendering requires significant boilerplate and repetitive `try/catch` logic in every controller.

Introduce `jooby-htmx`, a dedicated module providing both a **Declarative Annotation API** (via APT generation) and a memory-safe **Imperative Builder API** to orchestrate HTMX responses seamlessly. This allows developers to write 100% pure "Happy Path" business logic while the framework handles the UI state.

**1. The Interceptor Pipeline (`HtmxModule` & `HtmxMessageEncoder`)**
* Registers directly into Jooby's `MessageEncoder` chain ahead of standard template engines.
* Intercepts `HtmxModelAndView` payloads and safely drives the underlying template engine (e.g., Handlebars) in a loop to concatenate the primary view and multiple OOB templates into a single HTTP response.

**2. The Imperative API (`HtmxResponse`)**
* A fluent builder for scenarios lacking a primary view (e.g., `HTTP 204 No Content` for drag-and-drop reordering or delete operations).
* Easily chains multiple `.addOob()` and `.trigger()` events.

**3. The Declarative API (APT Code Generation)**
* `@HxView(value = "partial.hbs", layout = "base.hbs")`: Automatically serves the partial for HTMX AJAX requests, but smartly wraps it in the layout for direct browser navigation or `F5` refreshes.
* `@HxOob("counter.hbs")` & `@HxTrigger("itemAdded")`: Automatically injects the necessary headers and models into the response.
* `@HxError("error.hbs")`: The "UI Janitor". Automatically catches Bean Validation (`@Valid`) `ConstraintViolationException`s to render scoped inline errors (HTTP 422). Crucially, it **automatically appends an empty OOB swap on success** to instantly clear the UI of previous errors.

**4. Global Error Resilience**
* Allows passing an `HtmxErrorHandler` directly into `install(new HtmxModule(errorHandler))`.
* Safely intercepts global `500` server crashes and translates them into OOB Toast notifications, preventing raw HTML stack traces from breaking the client's DOM.

The resulting controller is entirely decoupled from HTTP headers and serialization logic:

```java
@post("/tasks")
@HxView("task_row.hbs")
@HxOob("task_counter.hbs")
@HxOob("toast.hbs")
@HxTrigger("taskAdded")
@Hxerror("task_error.hbs") // Automatically renders errors on failure, and clears them on success!
public Map<String, Object> addTask(@FormParam @Valid TaskDto dto) {
    var newTask = db.save(dto);

    return Map.of(
        "id", newTask.id(),
        "title", newTask.title(),
        "activeCount", db.getActiveCount(),
        "message", "Task added successfully!"
    );
}

fix #3936
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant