Skip to contentVibraUI

Next viewing

The next viewing booked on the listing and who is showing it, or that a closed listing has none; reads listingRecord(id).

Preview

Install

npx shadcn@latest add @vibra/widget-real-estate-listing-viewing-card

Needs the @vibra registry in your components.json — set it up once.

Source

app/real-estate/listings/[id]/components/viewing-card.tsx
"use client"

import Link from "next/link"
import { CalendarClockIcon } from "lucide-react"

import { isOpen } from "@/lib/dashboards/real-estate/vocabulary"
import { buttonVariants } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"

import { useListingState } from "./listing-state"
import { DAY, VIEWING_DAY, VIEWING_TIME } from "./listing-vocabulary"

export type ViewingCardProps = {
  /** The viewing booked on the listing, if it has one. */
  at?: Date
  agent?: string
  viewingsHref: string
}

/**
 * The next viewing booked on the listing, with who is showing it. A listing
 * that has closed has none to show, whatever its row still carries — and it
 * reads the page's listing state, so a sale made here closes it at once.
 */
export function ViewingCard({ at, agent, viewingsHref }: ViewingCardProps) {
  const { listing } = useListingState()
  const closed = !isOpen(listing)

  return (
    <Card data-widget="widget-real-estate-listing-viewing-card" role="region" aria-labelledby="listing-viewing-title">
      <CardHeader>
        <CardTitle id="listing-viewing-title">Next viewing</CardTitle>
      </CardHeader>
      <CardContent>
        {closed ? (
          <p className="text-sm text-muted-foreground">
            {listing.closedAt
              ? `Closed on ${DAY.format(listing.closedAt)} — there is nothing left to view.`
              : "Off the market — there is nothing left to view."}
          </p>
        ) : at ? (
          <div className="flex items-center gap-3">
            <span aria-hidden="true" className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-surface ring-1 ring-border">
              <CalendarClockIcon className="size-5 text-muted-foreground" />
            </span>
            <div className="flex min-w-0 flex-col">
              <p data-slot="viewing-at" className="text-sm font-medium tabular-nums">
                {`${VIEWING_DAY.format(at)} · ${VIEWING_TIME.format(at)}`}
              </p>
              <p className="truncate text-xs text-muted-foreground">{agent ? `Shown by ${agent}` : "Nobody showing it yet"}</p>
            </div>
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">No viewing booked.</p>
        )}
      </CardContent>
      <CardFooter>
        <Link href={viewingsHref} className={buttonVariants({ variant: "link", size: "sm", className: "px-0" })}>
          All viewings
        </Link>
      </CardFooter>
    </Card>
  )
}
app/real-estate/listings/[id]/actions.ts
"use server"

import { mockAuthAdapter } from "@/lib/auth-adapter"
import { formatDate } from "@/lib/format"
import { REFERENCE_DATE, db, type Listing, type Result } from "@/lib/sample-data"

/**
 * The three things this page changes. Each action looks the listing up by id
 * and trusts only the stored row; a listing that has sold or let is off the
 * market, and both verbs refuse it with the day it closed. What comes back is
 * the listing trimmed to what the page prints, never the stored row.
 */

export type ListingChange = { id: string; title: string; status: Listing["status"]; closedAt?: Date }

export async function signOut(): Promise<Result<{ signedOut: true }>> {
  await mockAuthAdapter.signOut()
  return { ok: true, data: { signedOut: true } }
}

/** Takes an offer on a listing that is on the market; refuses one already under offer, sold or let. */
export async function markUnderOffer(id: string): Promise<Result<ListingChange>> {
  const row = await db.listings.get(id)
  if (!row) return { ok: false, error: { code: "not_found", message: `No listing with id "${id}".` } }
  if (row.status === "sold" || row.status === "rented") {
    return { ok: false, error: { code: "closed", message: offTheMarket(row) } }
  }
  if (row.status === "under_offer") {
    return { ok: false, error: { code: "already_under_offer", message: `${row.title} is already under offer.` } }
  }
  const updated = await db.listings.update(row.id, { status: "under_offer" })
  if (!updated.ok) return updated
  return { ok: true, data: { id: row.id, title: row.title, status: updated.data.status } }
}

/** Closes a listing on the market as sold, today; refuses one already sold or let. */
export async function markSold(id: string): Promise<Result<ListingChange>> {
  const row = await db.listings.get(id)
  if (!row) return { ok: false, error: { code: "not_found", message: `No listing with id "${id}".` } }
  if (row.status === "sold" || row.status === "rented") {
    return { ok: false, error: { code: "closed", message: offTheMarket(row) } }
  }
  const updated = await db.listings.update(row.id, { status: "sold", closedAt: REFERENCE_DATE })
  if (!updated.ok) return updated
  return { ok: true, data: { id: row.id, title: row.title, status: updated.data.status, closedAt: REFERENCE_DATE } }
}

/** "14 Linden Lane was sold on Aug 2, 2026 — it is off the market." */
function offTheMarket(row: Listing): string {
  const verb = row.status === "sold" ? "sold" : "let"
  const day = row.closedAt ? ` on ${formatDate(row.closedAt, "medium", { timeZone: "UTC" })}` : ""
  return `${row.title} was ${verb}${day} — it is off the market.`
}
app/real-estate/listings/[id]/components/listing-state.tsx
"use client"

import * as React from "react"

import { LISTING_STATUS_LABELS, LISTING_STATUS_MAP } from "@/lib/dashboards/real-estate/vocabulary"
import { StatusBadge } from "@/components/ui/status-badge"

import { type ListingChange } from "../actions"

import { DAY } from "./listing-vocabulary"

const DAY_MS = 86_400_000

type ListingState = {
  /** Where the listing stands now, a sale made on this page included. */
  listing: ListingChange
  /** Where it stood when the server read it: what the server-side figures were counted with. */
  initial: ListingChange
  /** Takes what the server handed back after an action. */
  settle: (next: ListingChange) => void
}

const ListingStateContext = React.createContext<ListingState | null>(null)

/**
 * Where the listing stands, held once for the page. Everything that changes
 * when it sells reads this state — the header's pill and the line under the
 * title, the deal card's verbs, the city comparison, the price history, the
 * agent's book and the viewing — so a sale shows in all of them the moment
 * the server says so, with nothing re-read and no refresh.
 */
export function ListingStateProvider({ initial, children }: { initial: ListingChange; children: React.ReactNode }) {
  const [listing, setListing] = React.useState(initial)
  const value = React.useMemo(() => ({ listing, initial, settle: setListing }), [listing, initial])
  return <ListingStateContext.Provider value={value}>{children}</ListingStateContext.Provider>
}

export function useListingState(): ListingState {
  const state = React.useContext(ListingStateContext)
  if (!state) throw new Error("useListingState needs a ListingStateProvider above it")
  return state
}

/** The line under the title: when it went on the market and for how long — or, once it has closed, after how long. */
export function ListingMarketLine({ listedAt, now }: { listedAt: Date; now: Date }) {
  const { listing } = useListingState()
  const days = Math.floor(((listing.closedAt ?? now).getTime() - listedAt.getTime()) / DAY_MS)
  const span = `${days} day${days === 1 ? "" : "s"}`
  const listed = DAY.format(listedAt)
  return listing.closedAt ? `Listed ${listed} · closed after ${span}` : `Listed ${listed} · ${span} on the market`
}

/** The status pill beside the page title. */
export function ListingStatusBadge() {
  const { listing } = useListingState()
  return (
    <StatusBadge status={listing.status} label={LISTING_STATUS_LABELS[listing.status]} map={LISTING_STATUS_MAP} />
  )
}
app/real-estate/listings/[id]/components/listing-vocabulary.ts
/**
 * How this page writes a day and a viewing's slot. The words the whole
 * dashboard shares — a listing's kind and status, its glyph, how a price is
 * written — are in `@/lib/dashboards/real-estate/vocabulary`.
 */

export const DAY = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" })

/** "Tue, Sep 8 · 10:30 AM", in UTC, the zone viewings are booked in. */
export const VIEWING_DAY = new Intl.DateTimeFormat("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" })
export const VIEWING_TIME = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: "UTC" })

Its page

On its page the card sits among the rest of the dashboard and shares its range and its data with them.

From the Listing page page