Skip to content

Ideas: infinite scroll ​

<InfiniteScroll @as="ul"> over a paginated prop. Category chips are <Link>s with @only and @reset. The search box uses router.get with a debounce and keeps focus. useRemember keeps the grid or list choice when you come back. Ideas you saved show up on top, from the saved service.

Open it in the live demo ↗

The page ​

gts
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { array, fn, hash } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { InfiniteScroll, Link, type PageSignature, router, useRemember } from 'inertia-ember';

import { CategoryBadge, inputClass, PageHeader } from '../../components/ui.gts';
import type SavedService from '../../services/saved.ts';
import type { Idea, Paginated } from '../../types.ts';

interface Props {
  filters: { search?: string | null; category?: string | null };
  categories: string[];
  ideas: Paginated<Idea>;
}

const eq = (a: unknown, b: unknown): boolean => a === b;

const excerpt = (text: string): string => (text.length > 140 ? `${text.slice(0, 140).trimEnd()}…` : text);

export default class IdeasIndex extends Component<PageSignature<Props>> {
  // The same service instance the Show page fills: what you saved there is here after the visit.
  @service declare saved: SavedService;

  // Kept in browser history: go to an idea and come back, and the view you picked is still there.
  view = useRemember<{ mode: 'grid' | 'list' }>({ mode: 'grid' }, 'Ideas/Index:view');

  @tracked search = this.args.props.filters.search ?? '';
  timer: ReturnType<typeof setTimeout> | undefined;

  get category(): string | null {
    return this.args.props.filters.category ?? null;
  }

  get ideas(): Idea[] {
    return this.args.props.ideas.data;
  }

  get total(): number {
    return this.args.props.ideas.total;
  }

  get listClass(): string {
    return this.view.mode === 'grid' ? 'grid gap-4 sm:grid-cols-2 lg:grid-cols-3' : 'flex flex-col gap-3';
  }

  // Swap the list for the first page of the new results, keeping the input focused.
  visit(params: { search?: string; category?: string }): void {
    router.get('/ideas', params, {
      preserveState: true,
      preserveScroll: true,
      replace: true,
      only: ['ideas', 'filters'],
      reset: ['ideas'],
    });
  }

  updateSearch = (event: Event): void => {
    this.search = (event.target as HTMLInputElement).value;
    clearTimeout(this.timer);
    this.timer = setTimeout(
      () => this.visit({ search: this.search || undefined, category: this.category || undefined }),
      250,
    );
  };

  setView = (mode: 'grid' | 'list'): void => {
    this.view.mode = mode;
  };

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

  <template>
    <PageHeader
      @eyebrow='InfiniteScroll · partial reloads'
      @title='Ideas'
      @lead='Scroll to load more. Filters change the URL with partial reloads that only ask for the list.'
    >
      <Link
        @href='/ideas/new'
        class='rounded-lg bg-stone-900 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-stone-700'
      >New idea</Link>
    </PageHeader>

    <div class='mb-6 flex flex-col gap-3 sm:flex-row sm:items-center'>
      <label class='relative flex-1'>
        <span class='sr-only'>Search ideas</span>
        <input
          type='search'
          value={{this.search}}
          placeholder='Search titles and descriptions…'
          class={{inputClass}}
          data-test-search
          {{on 'input' this.updateSearch}}
        />
      </label>
      <div
        class='flex shrink-0 self-start rounded-lg bg-white p-1 shadow-sm ring-1 ring-stone-200 sm:self-auto'
        role='group'
        aria-label='View'
      >
        <button
          type='button'
          class='rounded-md px-3 py-1 text-sm
            {{if (eq this.view.mode "grid") "bg-stone-900 text-white" "text-stone-600"}}'
          aria-pressed={{if (eq this.view.mode 'grid') 'true' 'false'}}
          data-test-view='grid'
          {{on 'click' (fn this.setView 'grid')}}
        >Grid</button>
        <button
          type='button'
          class='rounded-md px-3 py-1 text-sm
            {{if (eq this.view.mode "list") "bg-stone-900 text-white" "text-stone-600"}}'
          aria-pressed={{if (eq this.view.mode 'list') 'true' 'false'}}
          data-test-view='list'
          {{on 'click' (fn this.setView 'list')}}
        >List</button>
      </div>
    </div>

    {{#if this.saved.ideas.length}}
      <section class='mb-6 rounded-xl bg-amber-50 p-4 ring-1 ring-amber-200' aria-label='Saved ideas' data-test-saved>
        <h2 class='mb-2 text-xs font-semibold tracking-wide text-amber-800 uppercase'>
          ★ Saved · a service, kept across visits
        </h2>
        <ul class='flex flex-wrap gap-2'>
          {{#each this.saved.ideas as |idea|}}
            <li>
              <Link
                @href='/ideas/{{idea.id}}'
                class='block max-w-64 truncate rounded-lg bg-white px-3 py-1 text-sm text-stone-700 shadow-sm ring-1 ring-amber-200 first-letter:uppercase hover:text-stone-900'
                data-test-saved-idea={{idea.id}}
              >{{idea.title}}</Link>
            </li>
          {{/each}}
        </ul>
      </section>
    {{/if}}

    <nav class='-mx-4 mb-6 flex gap-2 overflow-x-auto px-4 pb-1' aria-label='Categories'>
      <Link
        @href='/ideas'
        @data={{if this.search (hash search=this.search)}}
        @only={{array 'ideas' 'filters'}}
        @reset={{array 'ideas'}}
        @preserveState={{true}}
        class='shrink-0 rounded-full px-3 py-1 text-sm font-medium ring-1
          {{if this.category "bg-white text-stone-600 ring-stone-200" "bg-stone-900 text-white ring-stone-900"}}'
      >All</Link>
      {{#each @props.categories as |category|}}
        <Link
          @href='/ideas'
          @data={{hash category=category search=(if this.search this.search)}}
          @only={{array 'ideas' 'filters'}}
          @reset={{array 'ideas'}}
          @preserveState={{true}}
          class='shrink-0 rounded-full px-3 py-1 text-sm font-medium ring-1
            {{if
              (eq category this.category)
              "bg-stone-900 text-white ring-stone-900"
              "bg-white text-stone-600 ring-stone-200"
            }}'
          data-test-category={{category}}
        >{{category}}</Link>
      {{/each}}
    </nav>

    <p class='mb-4 text-sm text-stone-500' data-test-count>
      Showing
      {{this.ideas.length}}
      of
      {{this.total}}
    </p>

    <InfiniteScroll @data='ideas' @as='ul' @buffer={{400}} class={{this.listClass}} data-test-ideas>
      <:default>
        {{#each this.ideas key='id' as |idea|}}
          <li class='flex'><Link
              @href='/ideas/{{idea.id}}'
              @prefetch={{true}}
              class='flex flex-1 flex-col rounded-xl bg-white p-4 shadow-sm ring-1 ring-stone-200 transition hover:shadow-md hover:ring-stone-300'
              data-test-idea={{idea.id}}
            >
              <div class='mb-2 flex items-center justify-between gap-2'>
                <CategoryBadge @category={{idea.category}} />
                <span class='font-mono text-xs text-stone-500'>▲ {{idea.votes}}</span>
              </div>
              <h2 class='font-semibold text-balance first-letter:uppercase'>{{idea.title}}</h2>
              <p class='mt-1 text-sm text-stone-600 first-letter:uppercase'>{{excerpt idea.body}}</p>
            </Link></li>
        {{else}}
          <li class='col-span-full rounded-xl border border-dashed border-stone-300 p-8 text-center text-stone-500'>
            No ideas match. Try another search.
          </li>
        {{/each}}
      </:default>
      <:loading>
        <p class='py-6 text-center text-sm text-stone-500' data-test-loading-more>Loading more ideas…</p>
      </:loading>
    </InfiniteScroll>
  </template>
}

The handler ​

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.