Idea: deferred and live
A vote button (<Link @method="post" @only>) whose count is a live prop: a vote in another tab shows up here over Reverb. A Save button (@service saved), a delete that asks first (@onBefore), comments that load when they scroll into view (<WhenVisible>), "similar ideas" as a deferred prop, and a useForm comment form.
The page
gts
import Component from '@glimmer/component';
import { array, fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { bind, Deferred, Link, type PageSignature, useForm, WhenVisible } from 'inertia-ember';
import { buttonClass, CategoryBadge, FieldError, inputClass, Skeleton } from '../../components/ui.gts';
import type SavedService from '../../services/saved.ts';
import type { Comment, Idea } from '../../types.ts';
interface Props {
idea: Idea;
commentsCount: number;
/** Deferred: arrives after the first render. */
similar?: Idea[];
/** Optional: loaded by <WhenVisible> when the comments scroll into view. */
comments?: Comment[];
}
const confirmDelete = () => window.confirm('Delete this idea and its comments?');
export default class IdeasShow extends Component<PageSignature<Props>> {
// From the owner `createInertiaApp` was given: the list outlives this page.
@service declare saved: SavedService;
comment = useForm({ author: '', body: '' });
get idea(): Idea {
return this.args.props.idea;
}
get paragraphs(): string[] {
return this.idea.body.split(/\n+/).filter(Boolean);
}
addComment = (event: SubmitEvent): void => {
event.preventDefault();
this.comment.post(`/ideas/${this.idea.id}/comments`, {
preserveScroll: true,
only: ['comments', 'commentsCount'],
onSuccess: () => this.comment.reset('body'),
});
};
<template>
<article class='grid gap-10 lg:grid-cols-[1fr_18rem]'>
<div>
<Link @href='/ideas' class='mb-6 inline-block text-sm text-stone-500 hover:text-stone-900'>← All ideas</Link>
<div class='mb-3 flex items-center gap-3'>
<CategoryBadge @category={{this.idea.category}} />
<span class='text-xs text-stone-500'>#{{this.idea.id}}</span>
</div>
<h1
class='text-3xl font-semibold tracking-tight text-balance first-letter:uppercase sm:text-4xl'
data-test-title
>{{this.idea.title}}</h1>
<div class='mt-5 space-y-4 text-lg leading-relaxed text-stone-700'>
{{#each this.paragraphs as |paragraph|}}
<p class='first-letter:uppercase'>{{paragraph}}</p>
{{/each}}
</div>
<div class='mt-8 flex flex-wrap items-center gap-3'>
<Link
@href='/ideas/{{this.idea.id}}/vote'
@method='post'
@preserveScroll={{true}}
@only={{array 'idea'}}
class='inline-flex items-center gap-2 rounded-lg bg-[#e04e39] px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-[#c43f2c] data-loading:opacity-60'
data-test-vote
>
▲ Vote
<span class='rounded bg-white/20 px-1.5 font-mono tabular-nums' data-test-votes>{{this.idea.votes}}</span>
</Link>
<Link
@href='/ideas/{{this.idea.id}}/edit'
class='rounded-lg border border-stone-300 bg-white px-4 py-2 text-sm font-medium shadow-sm hover:bg-stone-50'
>Edit</Link>
<button
type='button'
class='rounded-lg border border-stone-300 bg-white px-4 py-2 text-sm font-medium shadow-sm hover:bg-stone-50'
aria-pressed={{if (this.saved.has this.idea.id) 'true' 'false'}}
data-test-bookmark
{{on 'click' (fn this.saved.toggle this.idea)}}
>{{if (this.saved.has this.idea.id) '★ Saved' '☆ Save'}}</button>
<Link
@href='/ideas/{{this.idea.id}}'
@method='delete'
@onBefore={{confirmDelete}}
class='rounded-lg px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-50'
>Delete</Link>
</div>
<section class='mt-14' aria-labelledby='comments-title'>
<h2 id='comments-title' class='mb-1 text-xl font-semibold'>
Comments
<span class='text-stone-400'>({{@props.commentsCount}})</span>
</h2>
<p class='mb-6 text-sm text-stone-500'>
Not in the first response:
<code><WhenVisible></code>
asks for them when this section scrolls into view.
</p>
<WhenVisible @data='comments' @buffer={{100}}>
<:default>
<ul class='space-y-4' data-test-comments>
{{#each @props.comments key='id' as |comment|}}
<li class='rounded-xl bg-white p-4 shadow-sm ring-1 ring-stone-200'>
<p class='text-sm font-semibold'>{{comment.author}}</p>
<p class='mt-1 text-stone-700 first-letter:uppercase'>{{comment.body}}</p>
</li>
{{else}}
<li class='text-stone-500'>No comments yet. Be the first.</li>
{{/each}}
</ul>
</:default>
<:fallback>
<div class='space-y-4' data-test-comments-loading>
<Skeleton />
<Skeleton />
</div>
</:fallback>
</WhenVisible>
<form
class='mt-8 space-y-3 rounded-xl bg-white p-4 shadow-sm ring-1 ring-stone-200'
{{on 'submit' this.addComment}}
>
<h3 class='font-semibold'>Add a comment</h3>
<div>
<label class='mb-1 block text-sm font-medium' for='comment-author'>Name</label>
<input id='comment-author' class={{inputClass}} autocomplete='name' {{bind this.comment 'author'}} />
<FieldError @field='author' @message={{this.comment.errors.author}} />
</div>
<div>
<label class='mb-1 block text-sm font-medium' for='comment-body'>Comment</label>
<textarea id='comment-body' rows='3' class={{inputClass}} {{bind this.comment 'body'}}></textarea>
<FieldError @field='body' @message={{this.comment.errors.body}} />
</div>
<button type='submit' class={{buttonClass}} disabled={{this.comment.processing}}>
{{if this.comment.processing 'Posting…' 'Post comment'}}
</button>
</form>
</section>
</div>
<aside class='lg:pt-12'>
<h2 class='mb-1 text-sm font-semibold tracking-wider text-stone-500 uppercase'>Similar ideas</h2>
<p class='mb-4 text-xs text-stone-500'>Deferred: fetched right after the page shows.</p>
<Deferred @data='similar'>
<:default>
<ul class='space-y-3' data-test-similar>
{{#each @props.similar key='id' as |idea|}}
<li>
<Link
@href='/ideas/{{idea.id}}'
@prefetch={{true}}
class='block rounded-xl bg-white p-3 text-sm shadow-sm ring-1 ring-stone-200 hover:ring-stone-300'
>
<span class='font-medium first-letter:uppercase'>{{idea.title}}</span>
<span class='mt-1 block font-mono text-xs text-stone-500'>▲ {{idea.votes}}</span>
</Link>
</li>
{{else}}
<li class='text-sm text-stone-500'>Nothing else in this category.</li>
{{/each}}
</ul>
</:default>
<:fallback>
<div class='space-y-4' data-test-similar-loading>
<Skeleton />
<Skeleton />
<Skeleton />
</div>
</:fallback>
</Deferred>
</aside>
</article>
</template>
}The handler
rs
/// `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
}),
},
))
}The comment form posts here:
rs
use laravel::inertia;
use laravel::model::create;
use laravel::prelude::*;
use crate::models::{Comment, Idea};
#[laravel::input(fills = Comment)]
#[validate(anyone)]
pub struct CommentInput {
#[validate(required, max_length(60))]
pub author: String,
#[validate(required, min_length(3), max_length(1000))]
pub body: String,
}
pub async fn store(idea: Idea, Valid(input): Valid<CommentInput>) -> laravel::Result<Redirect> {
create!(idea.comments() { ..input }).await?;
inertia::flash("toast", "Comment added.")?;
Ok(Redirect::back())
}