Skip to content

Live: polling ​

usePoll every 2 seconds on just the stats prop, with a pause button. stats is also live, so votes arrive at once even while paused. "Simulate" votes go through a POST. <Head> puts the vote count in the tab title.

Open it in the live demo ↗

The page ​

gts
import Component from '@glimmer/component';
import { array } from '@ember/helper';
import { on } from '@ember/modifier';
import { Head, Link, type PageSignature, usePoll } from 'inertia-ember';

import { CategoryBadge, PageHeader, secondaryButtonClass } from '../components/ui.gts';
import type { Idea } from '../types.ts';

interface Stats {
  ideas: number;
  comments: number;
  votes: number;
  top: Idea[];
  serverTime: string;
}

const time = (value: string | undefined): string => (value ? new Date(value).toLocaleTimeString() : '—');

export default class Dashboard extends Component<PageSignature<{ stats: Stats }>> {
  // A partial reload of `stats` every two seconds, stopped when the page goes away.
  poll = usePoll(this, 2000, { only: ['stats'] });

  get stats(): Stats {
    return this.args.props.stats;
  }

  get title(): string {
    return `${this.stats.votes} votes · Live`;
  }

  toggle = () => {
    if (this.poll.polling) {
      this.poll.stop();
    } else {
      this.poll.start();
    }
  };

  <template>
    <Head @title={{this.title}}>
      <meta name='description' content='Live numbers from the ideas board' head-key='description' />
    </Head>

    <PageHeader
      @eyebrow='usePoll · <Head>'
      @title='Live'
      @lead='Refreshes every two seconds with a partial reload of one lazy prop. Watch the tab title too.'
    >
      <div class='flex flex-wrap gap-2'>
        <button type='button' class={{secondaryButtonClass}} data-test-toggle {{on 'click' this.toggle}}>
          <span
            class='size-2 rounded-full {{if this.poll.polling "animate-pulse bg-emerald-500" "bg-stone-400"}}'
          ></span>
          {{if this.poll.polling 'Polling' 'Paused'}}
        </button>
        <Link
          @href='/dashboard/simulate'
          @method='post'
          @preserveScroll={{true}}
          @only={{array 'stats'}}
          class='rounded-lg bg-[#e04e39] px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-[#c43f2c]'
          data-test-simulate
        >+10 random votes</Link>
      </div>
    </PageHeader>

    <dl class='grid grid-cols-2 gap-4 lg:grid-cols-4'>
      <div class='rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200'>
        <dt class='text-sm text-stone-500'>Votes</dt>
        <dd class='mt-1 font-mono text-3xl font-semibold tabular-nums' data-test-stat='votes'>{{this.stats.votes}}</dd>
      </div>
      <div class='rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200'>
        <dt class='text-sm text-stone-500'>Ideas</dt>
        <dd class='mt-1 font-mono text-3xl font-semibold tabular-nums'>{{this.stats.ideas}}</dd>
      </div>
      <div class='rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200'>
        <dt class='text-sm text-stone-500'>Comments</dt>
        <dd class='mt-1 font-mono text-3xl font-semibold tabular-nums'>{{this.stats.comments}}</dd>
      </div>
      <div class='rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200'>
        <dt class='text-sm text-stone-500'>Server time</dt>
        <dd class='mt-1 font-mono text-xl font-semibold tabular-nums' data-test-stat='time'>{{time
            this.stats.serverTime
          }}</dd>
      </div>
    </dl>

    <section class='mt-10'>
      <h2 class='mb-4 text-sm font-semibold tracking-wider text-stone-500 uppercase'>Top ideas</h2>
      <ol class='divide-y divide-stone-200 rounded-2xl bg-white shadow-sm ring-1 ring-stone-200' data-test-top>
        {{#each this.stats.top key='id' as |idea|}}
          <li>
            <Link
              @href='/ideas/{{idea.id}}'
              @prefetch={{true}}
              class='flex items-center gap-3 px-4 py-3 hover:bg-stone-50'
            >
              <span class='w-12 shrink-0 font-mono text-sm font-semibold tabular-nums text-[#e04e39]'>▲
                {{idea.votes}}</span>
              <span class='min-w-0 flex-1 truncate first-letter:uppercase'>{{idea.title}}</span>
              <CategoryBadge @category={{idea.category}} />
            </Link>
          </li>
        {{/each}}
      </ol>
    </section>
  </template>
}

The handler ​

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

use crate::events::IdeaVoted;
use crate::models::{Comment, Idea};

#[derive(Serialize)]
pub struct Stats {
    ideas: u64,
    comments: u64,
    votes: i64,
    top: Vec<Idea>,
    #[serde(rename = "serverTime")]
    server_time: String,
}

async fn stats() -> laravel::Result<Stats> {
    Ok(Stats {
        ideas: Idea::query().count().await?,
        comments: Comment::query().count().await?,
        votes: Idea::query().sum(Idea::votes).await?.unwrap_or(0),
        top: Idea::query()
            .order_by(Idea::votes.desc())
            .order_by(Idea::id.desc())
            .limit(5)
            .get()
            .await?,
        server_time: laravel::now().timestamp().to_string(),
    })
}

/// The page polls `only: ['stats']` every two seconds, so `stats` is lazy: a partial reload that doesn't
/// ask for it never runs the queries. It's also live: a vote anywhere refreshes it at once, poll or not.
///
/// Laravel renders the page's `<title>` on the server, so crawlers read "Live"; the `<Head>` on the page
/// turns it into the vote count once the browser takes over.
pub async fn show() -> laravel::Result<Page> {
    head::merge(Head::new().title("Live"));

    Ok(inertia::render(
        "Dashboard",
        props! {
            stats => inertia::lazy(async || stats().await)
                .live(inertia::on_channel::<IdeaVoted>(Channel::public("ideas")?)),
        },
    ))
}

/// Spreads 10 votes over random ideas, so the live numbers move without a second browser.
pub async fn simulate() -> laravel::Result<Redirect> {
    let ideas = Idea::all().await?;

    let mut seed = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_nanos() as u64)
        .unwrap_or(7);

    if !ideas.is_empty() {
        for _ in 0..10 {
            // A small linear congruential step is random enough to pick which ideas get the votes.
            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            let mut idea = ideas[(seed >> 33) as usize % ideas.len()].clone();
            update!(idea { votes += 1 }).await?;
            IdeaVoted { idea_id: idea.id }.dispatch().await?;
        }
    }

    Ok(Redirect::back())
}

Released under the MIT License.