Skip to content

New idea: <Form> ​

<Form> with no state of its own, and Precognition: each field is checked against the server's rules on change, with a ✓ when it passes. As you type a title, useHttp looks up similar ones. On success, a redirect with a toast.

Open it in the live demo ↗

The page ​

gts
import Component from '@glimmer/component';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { createForm, Link, type PageSignature, useHttp } from 'inertia-ember';

import { buttonClass, FieldError, inputClass, PageHeader, ValidMark } from '../../components/ui.gts';
import type { Idea, IdeaInput } from '../../types.ts';

// The same <Form>, typed by its fields: `form.errors.title` and `form.valid 'title'` are checked by Glint.
const IdeaForm = createForm<IdeaInput>();

export default class IdeasCreate extends Component<PageSignature<{ categories: string[] }>> {
  // A JSON lookup, not a visit: the page stays put while the title is typed.
  similar = useHttp<{ title: string }, Idea[]>({ title: '' });
  timer: ReturnType<typeof setTimeout> | undefined;

  lookUp = (event: Event): void => {
    clearTimeout(this.timer);
    this.similar.title = (event.target as HTMLInputElement).value;
    this.timer = setTimeout(() => this.similar.get('/api/ideas/similar').catch(() => {}), 300);
  };

  willDestroy(): void {
    super.willDestroy();
    clearTimeout(this.timer);
    this.similar.cancel();
  }

  <template>
    <PageHeader
      @eyebrow='&lt;Form&gt; · Precognition · useHttp'
      @title='New idea'
      @lead="A plain HTML form: fields are read by their name, no state to wire up. Each field is checked against the server's rules when you leave it, before anything is saved."
    />

    <IdeaForm
      @action='/ideas'
      @method='post'
      @disableWhileProcessing={{true}}
      @validationTimeout={{300}}
      class='max-w-2xl space-y-5 rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200 sm:p-6'
      data-test-form
      as |form|
    >
      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='title'>Title</label>
          <ValidMark @field='title' @valid={{form.valid 'title'}} />
        </div>
        <input
          id='title'
          name='title'
          class={{inputClass}}
          placeholder='A short pitch'
          autocomplete='off'
          {{on 'input' this.lookUp}}
          {{on 'change' (fn form.validate 'title')}}
        />
        <FieldError @field='title' @message={{form.errors.title}} />

        {{#if this.similar.response.length}}
          <div class='mt-2 rounded-lg bg-amber-50 p-3 text-sm ring-1 ring-amber-200' data-test-similar-titles>
            <p class='mb-1 font-medium text-amber-900'>Already proposed? Vote for one of these instead:</p>
            <ul class='space-y-1'>
              {{#each this.similar.response key='id' as |idea|}}
                <li class='flex gap-2'>
                  <span class='font-mono text-xs text-amber-800 tabular-nums'>▲{{idea.votes}}</span>
                  <Link
                    @href='/ideas/{{idea.id}}'
                    class='truncate text-amber-950 underline-offset-2 first-letter:uppercase hover:underline'
                  >
                    {{idea.title}}
                  </Link>
                </li>
              {{/each}}
            </ul>
          </div>
        {{/if}}
      </div>

      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='category'>Category</label>
          <ValidMark @field='category' @valid={{form.valid 'category'}} />
        </div>
        <select id='category' name='category' class={{inputClass}} {{on 'change' (fn form.validate 'category')}}>
          <option value=''>Pick one…</option>
          {{#each @props.categories as |category|}}
            <option value={{category}}>{{category}}</option>
          {{/each}}
        </select>
        <FieldError @field='category' @message={{form.errors.category}} />
      </div>

      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='body'>Description</label>
          <ValidMark @field='body' @valid={{form.valid 'body'}} />
        </div>
        <textarea
          id='body'
          name='body'
          rows='6'
          class={{inputClass}}
          placeholder='What should we build, and why?'
          {{on 'change' (fn form.validate 'body')}}
        ></textarea>
        <FieldError @field='body' @message={{form.errors.body}} />
      </div>

      <div class='flex flex-wrap items-center gap-3'>
        <button type='submit' class={{buttonClass}} disabled={{form.processing}} data-test-submit>
          {{if form.processing 'Publishing…' 'Publish idea'}}
        </button>
        <Link @href='/ideas' class='text-sm text-stone-600 hover:text-stone-900'>Cancel</Link>
        {{#if form.validating}}
          <span class='text-xs text-stone-500' data-test-validating>Checking…</span>
        {{/if}}
        {{#if form.isDirty}}
          <span class='ml-auto text-xs text-amber-700' data-test-dirty>Unsaved changes</span>
        {{/if}}
        {{#if form.hasErrors}}
          <span class='ml-auto text-xs text-red-600'>Fix the highlighted fields.</span>
        {{/if}}
      </div>
    </IdeaForm>
  </template>
}

Both forms post to the same handlers, store and update, in ideas.rs, which validate the same input:

rs
use laravel::axum::http::HeaderMap;
use laravel::broadcast::{self, Channel};
use laravel::head::{self, Head};
use laravel::inertia::{self, Page, props};
use laravel::model::{create, update};
use laravel::prelude::*;
use laravel::task;
use serde::Serialize;

use crate::events::IdeaVoted;
use crate::http::middleware::precognition;
use crate::models::{CATEGORIES, Comment, Idea};

#[laravel::query]
#[derive(Serialize)]
pub struct Filters {
    #[validate(max_length(100))]
    search: Option<String>,
    #[validate(one_of("frontend", "backend", "dx", "community"))]
    category: Option<String>,
}

#[laravel::input(fills = Idea)]
#[validate(anyone)]
pub struct IdeaInput {
    #[validate(required, min_length(4), max_length(120))]
    pub title: String,
    #[validate(required, min_length(10), max_length(2000))]
    pub body: String,
    #[validate(required, one_of("frontend", "backend", "dx", "community"))]
    pub category: String,
}

/// The list loads 12 ideas at a time as the visitor scrolls (`inertia::scroll_with`), filtered by the
/// query string, which the page changes with partial reloads.
pub async fn index(Query(filters): Query<Filters>) -> Page {
    let search = filters.search.clone().filter(|term| !term.trim().is_empty());
    let category = filters.category.clone();

    inertia::render(
        "Ideas/Index",
        props! {
            filters,
            categories => CATEGORIES,
            ideas => inertia::scroll_with(async move || {
                Idea::query()
                    .filter(search.as_ref().map(|term| Idea::title.contains(term) | Idea::body.contains(term)))
                    .filter(category.as_ref().map(|category| Idea::category.eq(category)))
                    .order_by(Idea::id.desc())
                    .paginate(12)
                    .await
                    .map(|page| page.with_query_string())
            }),
        },
    )
}

// #region show
/// `similar` is deferred: the page renders first and asks for it right after. `comments` is optional:
/// only sent when the page scrolls down to them. Both wait a little so the loading states show.
/// `idea` is live: when someone else votes, every open copy of the page reloads it.
pub async fn show(idea: Idea) -> laravel::Result<Page> {
    head::merge(Head::new().title(&idea.title));

    let idea_id = idea.id;
    let category = idea.category.clone();
    let comments_count = idea.comments().count().await?;

    Ok(inertia::render(
        "Ideas/Show",
        props! {
            idea => inertia::lazy(async move || Idea::find(idea_id).await)
                .live(inertia::on_channel::<IdeaVoted>(Channel::public(format!("ideas.{idea_id}"))?)),
            commentsCount => comments_count,
            similar => inertia::defer(async move || {
                task::sleep(1200.milliseconds()).await;

                Idea::query()
                    .filter(Idea::category.eq(&category) & Idea::id.ne(idea_id))
                    .order_by(Idea::votes.desc())
                    .limit(3)
                    .get()
                    .await
            }),
            comments => inertia::optional(async move || {
                task::sleep(700.milliseconds()).await;

                Comment::query()
                    .filter(Comment::idea_id.eq(idea_id))
                    .order_by(Comment::id.desc())
                    .get()
                    .await
            }),
        },
    ))
}
// #endregion show

pub async fn create() -> Page {
    head::merge(Head::new().title("New idea"));

    inertia::render("Ideas/Create", props! { categories => CATEGORIES })
}

/// With `Precognition: true` the input is only validated; nothing is saved.
pub async fn store(headers: HeaderMap, Valid(input): Valid<IdeaInput>) -> laravel::Result<Response> {
    if precognition::requested(&headers) {
        return Ok(precognition::passed());
    }

    let idea = create!(Idea { ..input }).await?;
    inertia::flash("toast", "Idea published.")?;

    Ok(Response::new(redirect!(show, &idea)))
}

pub async fn edit(idea: Idea) -> Page {
    head::merge(Head::new().title(format!("Edit · {}", idea.title)));

    inertia::render("Ideas/Edit", props! { idea, categories => CATEGORIES })
}

pub async fn update(mut idea: Idea, headers: HeaderMap, Valid(input): Valid<IdeaInput>) -> laravel::Result<Response> {
    if precognition::requested(&headers) {
        return Ok(precognition::passed());
    }

    update!(idea { ..input }).await?;
    inertia::flash("toast", "Changes saved.")?;

    Ok(Response::new(redirect!(show, &idea)))
}

pub async fn destroy(idea: Idea) -> laravel::Result<Redirect> {
    idea.delete().await?;
    inertia::flash("toast", "Idea deleted.")?;

    Ok(Redirect::to("/ideas"))
}

pub async fn vote(mut idea: Idea) -> laravel::Result<Redirect> {
    update!(idea { votes += 1 }).await?;
    // The tab that voted already reloads `idea`; tell the others.
    broadcast::event(IdeaVoted { idea_id: idea.id }).to_others().await?;

    Ok(Redirect::back())
}

Released under the MIT License.