Skip to content

Layout ​

The persistent layout: its "mounted … ago" clock keeps counting as you move between pages, and sits in <WhenMounted>, since the server has nothing to count. It also shows flash toasts from the server and nav links that prefetch on hover.

Open it in the live demo ↗

The page ​

gts
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { registerDestructor } from '@ember/destroyable';
import type Owner from '@ember/owner';
import { on } from '@ember/modifier';
import { VERSION as emberVersion } from '@ember/version';
import { type LayoutSignature, Link, page, WhenMounted } from 'inertia-ember';

interface NavItem {
  href: string;
  label: string;
  match: (url: string) => boolean;
}

const NAV: NavItem[] = [
  { href: '/', label: 'Home', match: (url) => url === '/' },
  { href: '/ideas', label: 'Ideas', match: (url) => url.startsWith('/ideas') && !url.startsWith('/ideas/new') },
  { href: '/ideas/new', label: 'New idea', match: (url) => url.startsWith('/ideas/new') },
  { href: '/dashboard', label: 'Live', match: (url) => url.startsWith('/dashboard') },
];

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

class Toast extends Component {
  @tracked dismissed: string | null = null;

  // Typed by `flashDataType` in types.ts.
  get message(): string | null {
    const toast = page.flash.toast;
    return typeof toast === 'string' && toast !== this.dismissed ? toast : null;
  }

  dismiss = () => {
    this.dismissed = this.message;
  };

  <template>
    {{#if this.message}}
      <div
        role='status'
        class='fixed inset-x-4 top-4 z-50 mx-auto flex max-w-md items-center gap-3 rounded-xl bg-stone-900 px-4 py-3 text-sm text-white shadow-xl sm:inset-x-auto sm:right-6'
        data-test-toast
      >
        <span class='size-2 shrink-0 rounded-full bg-emerald-400'></span>
        <span class='flex-1'>{{this.message}}</span>
        <button
          type='button'
          class='text-stone-400 hover:text-white'
          aria-label='Dismiss'
          {{on 'click' this.dismiss}}
        >✕</button>
      </div>
    {{/if}}
  </template>
}

// Counts the seconds since the layout mounted. It lives in the layout, so it keeps counting across visits.
class Uptime extends Component {
  @tracked seconds = 0;

  constructor(owner: Owner, args: object) {
    super(owner, args);
    const timer = setInterval(() => this.seconds++, 1000);
    registerDestructor(this, () => clearInterval(timer));
  }

  get uptime(): string {
    const minutes = Math.floor(this.seconds / 60);
    return `${minutes}:${String(this.seconds % 60).padStart(2, '0')}`;
  }

  <template>
    <span class='font-mono tabular-nums text-stone-700' data-test-uptime>{{this.uptime}}</span>
  </template>
}

/**
 * The persistent layout: it stays mounted while pages change, so the clock below keeps counting
 * across visits instead of starting over. The clock only runs in the browser (`<WhenMounted>`): on the
 * server there is nothing to count.
 */
export default class AppLayout extends Component<LayoutSignature> {
  get nav(): Array<NavItem & { active: boolean }> {
    const url = page.url ?? '/';
    return NAV.map((item) => ({ ...item, active: item.match(url) }));
  }

  <template>
    <div class='min-h-dvh bg-stone-50 text-stone-900'>
      <header class='sticky top-0 z-40 border-b border-stone-200 bg-white/90 backdrop-blur'>
        <div class='mx-auto flex max-w-5xl flex-wrap items-center gap-x-6 gap-y-2 px-4 py-3'>
          <Link @href='/' class='flex items-center gap-2 font-semibold tracking-tight'>
            <span class='grid size-7 place-items-center rounded-lg bg-[#e04e39] text-sm text-white'>ie</span>
            <span>inertia-ember</span>
          </Link>

          <nav
            class='order-last -mx-1 flex w-full gap-1 overflow-x-auto text-sm sm:order-none sm:w-auto sm:flex-1'
            aria-label='Main'
          >
            {{#each this.nav as |item|}}
              <Link
                @href={{item.href}}
                @prefetch={{true}}
                class='shrink-0 rounded-lg px-3 py-1.5 font-medium transition
                  {{if item.active "bg-stone-900 text-white" "text-stone-600 hover:bg-stone-100 hover:text-stone-900"}}'
                aria-current={{if item.active 'page'}}
              >{{item.label}}</Link>
            {{/each}}
          </nav>

          <p class='hidden text-xs text-stone-500 md:block' title='Persistent layouts keep their state between pages'>
            Layout mounted
            <WhenMounted>
              <:default><Uptime /></:default>
              <:fallback><span class='font-mono text-stone-700'>–:––</span></:fallback>
            </WhenMounted>
            ago
          </p>
        </div>
      </header>

      <Toast />

      <main class='mx-auto max-w-5xl px-4 py-8 sm:py-12'>
        {{yield}}
      </main>

      <footer class='mx-auto max-w-5xl px-4 pb-10 text-xs text-stone-500'>
        {{@props.appName}}
        · Ember
        {{emberVersion}}
        · Laravel Rust
        {{@props.laravelVersion}}
        · Inertia v3
        {{#if (eq page.component 'Welcome')}}
          · Every page here is a
          <code>.gts</code>
          file in
          <code>resources/js/pages</code>
        {{/if}}
      </footer>
    </div>
  </template>
}

Starting the app ​

ts
import '../css/app.css';

import { createInertiaApp, createOwner, router, socketId } from 'inertia-ember';
import { echo } from 'inertia-ember/echo';

import echoInstance from './echo.ts';
import AppLayout from './layouts/AppLayout.gts';

// Every request says which socket it came from, so the server can skip this tab when it broadcasts.
socketId.resolveUsing(() => echoInstance.socketId());

createInertiaApp({
  // Laravel sends each page's <title> (see `head::merge` in the handlers); <Head> can still add to it.
  serverHead: true,
  layout: () => AppLayout,
  // Services for `@service` in pages and layouts: ./services/saved.js becomes `service:saved`.
  owner: () => createOwner(import.meta.glob('./services/*.ts', { eager: true })),
  progress: { color: '#e04e39', delay: 150 },
  // Live props: a prop marked `.live(...)` on the server reloads when its broadcast event arrives.
  live: echo(echoInstance),
});

if (import.meta.env.DEV) {
  // The dev server restarts when Rust code changes; reload the page's props once it's back.
  document.addEventListener('laravel:restarted', (event) => {
    event.preventDefault();
    router.reload();
  });
}

Released under the MIT License.