Skip to content
Product block

Unsaved Changes Prompt

The interception that keeps work: three answers rather than two, the changed fields listed by name, a destructive-styled discard, and Escape resolving to cancel.

237 lineslucide-reactAdded 31 Aug 2026
  • modal
  • unsaved changes
  • alertdialog
  • forms
  • focus trap

What's included

  • components/modal-unsaved-changes.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add modal-unsaved-changes

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

You have 3 unsaved changes

Closing now discards them. Saving keeps them and closes the editor.

Display name
Acme CorpAcme Corporation Ltd
Billing email
ap@acme.comaccounts-payable@acme.com
Seat limit
2440

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/modal-unsaved-changes.tsx
'use client'

/**
 * <ModalUnsavedChanges> — the interception that stops work being lost.
 *
 * The catalog's confirm dialog guards a destructive action the user chose.
 * This guards a destructive outcome the user did *not* choose: closing a
 * form, following a link, hitting Escape, with edits still in the buffer.
 * It is the same shape and the opposite situation, and the difference
 * changes every word in it.
 *
 * THREE BUTTONS, NOT TWO
 *
 * A confirm dialog offers cancel and proceed. An unsaved-changes prompt has
 * a third answer — save and then leave — and it is the one most people
 * want. Products that ship only "Discard" and "Cancel" force the user to
 * cancel, find the save button, press it, then repeat the thing they were
 * originally doing. The default action here is Save and close.
 *
 * DISCARD IS NAMED AND STYLED AS DESTRUCTIVE
 *
 * Not "OK", not "Leave", not "Don't save". The button says what happens to
 * the work, and it carries the destructive colour — because the two
 * fast paths through a dialog are the default button and the one under the
 * cursor, and neither should quietly throw away twenty minutes.
 *
 * IT SAYS WHAT IS UNSAVED. A list of changed fields turns "are you sure"
 * into a decision that can actually be made. Three edits the user forgot
 * about is exactly why they are about to lose them.
 *
 * ACCESSIBILITY: `role="alertdialog"` rather than `dialog` — this
 * interrupts, and the distinction is what tells a screen reader to announce
 * it immediately. Focus moves to the dialog on open and returns to the
 * trigger on close, focus is trapped while open, and Escape resolves to
 * Cancel (the safe answer) rather than to the primary.
 */

import * as React from 'react'
import { AlertTriangle, Save, Trash2, X } from 'lucide-react'

export interface UnsavedChange {
  field: string
  from: string
  to: string
}

export interface ModalUnsavedChangesProps {
  changes?: UnsavedChange[]
  /** Open on first render — the preview needs the dialog, not the button. */
  defaultOpen?: boolean
  className?: string
}

const DEFAULT_CHANGES: UnsavedChange[] = [
  { field: 'Display name', from: 'Acme Corp', to: 'Acme Corporation Ltd' },
  { field: 'Billing email', from: 'ap@acme.com', to: 'accounts-payable@acme.com' },
  { field: 'Seat limit', from: '24', to: '40' },
]

export function ModalUnsavedChanges({
  changes = DEFAULT_CHANGES,
  defaultOpen = true,
  className = '',
}: ModalUnsavedChangesProps) {
  /*
    Per-instance prefix for every id this block emits.

    The literals these replaced were a latent duplicate the moment the
    block appeared twice on one document, and `aria-labelledby` on a
    duplicated id resolves to the first match -- so the second copy was
    labelled by the first copy's heading. Client component, so `useId` is
    the right tool.
  */
  const uid = React.useId()

  const [open, setOpen] = React.useState(defaultOpen)
  const [outcome, setOutcome] = React.useState<string | null>(null)

  const dialogRef = React.useRef<HTMLDivElement>(null)
  const primaryRef = React.useRef<HTMLButtonElement>(null)
  const triggerRef = React.useRef<HTMLButtonElement>(null)

  // Focus in on open, focus back on close. The second half is the one that
  // gets skipped, and it is what leaves a keyboard user at the top of the
  // document after every dialog.
  React.useEffect(() => {
    if (open) primaryRef.current?.focus()
    else triggerRef.current?.focus()
  }, [open])

  function close(reason: string) {
    setOutcome(reason)
    setOpen(false)
  }

  function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
    if (event.key === 'Escape') {
      // Escape means "I did not mean to do this", which is Cancel — never
      // Discard. A dialog where the panic key destroys work is a trap.
      event.stopPropagation()
      close('cancelled')
      return
    }

    if (event.key !== 'Tab') return

    const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
    )
    if (!focusable || focusable.length === 0) return

    const first = focusable[0]
    const last = focusable[focusable.length - 1]

    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault()
      last.focus()
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault()
      first.focus()
    }
  }

  return (
    <div className={`rounded-2xl bg-muted/30 p-6 ${className}`}>
      <div className="flex flex-wrap items-center gap-3">
        <button
          ref={triggerRef}
          type="button"
          onClick={() => {
            setOutcome(null)
            setOpen(true)
          }}
          className="rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
        >
          Close the editor
        </button>
        {outcome ? (
          <p aria-live="polite" className="text-sm text-muted-foreground">
            Last answer: <span className="font-medium text-foreground">{outcome}</span>
          </p>
        ) : null}
      </div>

      {/* A separate, relatively-positioned stage below the trigger row — not
          wrapped around it — so the centred dialog's box never reaches back
          up over "Close the editor" at larger text sizes, where the taller
          dialog would otherwise sit closer to the top of a shared box. */}
      <div className="relative mt-4 min-h-[22rem]">
        {open ? (
          <div className="absolute inset-0 z-10 flex items-center justify-center p-4">
            <div
              aria-hidden
              className="absolute inset-0 rounded-2xl bg-background/80 backdrop-blur-sm"
              onClick={() => close('cancelled')}
            />

            <div
              ref={dialogRef}
              role="alertdialog"
              aria-modal="true"
              aria-labelledby={`${uid}-unsaved-title`}
              aria-describedby={`${uid}-unsaved-body`}
              onKeyDown={onKeyDown}
              className="relative max-h-full w-full max-w-md overflow-y-auto rounded-2xl border border-border bg-card p-6 text-card-foreground shadow-2xl"
            >
              <div className="flex items-start gap-3">
                <span
                  aria-hidden
                  className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-500/10"
                >
                  <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
                </span>
                <div className="min-w-0">
                  <h2 id={`${uid}-unsaved-title`} className="text-base font-semibold">
                    You have {changes.length} unsaved{' '}
                    {changes.length === 1 ? 'change' : 'changes'}
                  </h2>
                  <p id={`${uid}-unsaved-body`} className="mt-1 text-sm text-muted-foreground">
                    Closing now discards them. Saving keeps them and closes the editor.
                  </p>
                </div>
              </div>

              {/* Naming the changes is what makes this a decision rather than
                  a guess. */}
              <dl className="mt-4 space-y-2 rounded-xl border border-border bg-muted/40 p-3">
                {changes.map((change) => (
                  <div key={change.field} className="text-xs">
                    <dt className="font-medium">{change.field}</dt>
                    <dd className="mt-0.5 flex flex-wrap items-center gap-1.5 text-muted-foreground">
                      <span className="line-through">{change.from}</span>
                      <span aria-hidden>→</span>
                      <span className="font-medium text-foreground">{change.to}</span>
                    </dd>
                  </div>
                ))}
              </dl>

              <div className="mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
                <button
                  type="button"
                  onClick={() => close('cancelled')}
                  className="inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                >
                  <X aria-hidden className="h-4 w-4" />
                  Keep editing
                </button>

                <button
                  type="button"
                  onClick={() => close('discarded')}
                  className="inline-flex items-center justify-center gap-1.5 rounded-lg border border-destructive/40 px-3 py-2 text-sm font-medium text-destructive transition-colors hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                >
                  <Trash2 aria-hidden className="h-4 w-4" />
                  Discard changes
                </button>

                {/* The third button, and the default — see the header. */}
                <button
                  ref={primaryRef}
                  type="button"
                  onClick={() => close('saved and closed')}
                  className="inline-flex items-center justify-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
                >
                  <Save aria-hidden className="h-4 w-4" />
                  Save and close
                </button>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/modal-unsaved-changes.tsx and import it where you need the section:

import { ModalUnsavedChanges } from '@/components/modal-unsaved-changes'

Customize

1 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
changesUnsavedChange[]DEFAULT_CHANGES
defaultOpenOpen on first render — the preview needs the dialog, not the button.booleantrue
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

modal-unsaved-changes.html
<!--
  Unsaved Changes Prompt — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<div class="rounded-2xl bg-muted/30 p-6 ">
  <div class="flex flex-wrap items-center gap-3">
    <button type="button" class="rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Close the editor</button>
  </div>
  <div class="relative mt-4 min-h-[22rem]">
    <div class="absolute inset-0 z-10 flex items-center justify-center p-4">
      <div aria-hidden="true" class="absolute inset-0 rounded-2xl bg-background/80 backdrop-blur-sm"></div>
      <div role="alertdialog" aria-modal="true" aria-labelledby="_R_0_-unsaved-title" aria-describedby="_R_0_-unsaved-body" class="relative max-h-full w-full max-w-md overflow-y-auto rounded-2xl border border-border bg-card p-6 text-card-foreground shadow-2xl">
        <div class="flex items-start gap-3">
          <span aria-hidden="true" class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-500/10">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-triangle-alert h-4 w-4 text-amber-600 dark:text-amber-400" aria-hidden="true">
              <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"></path>
              <path d="M12 9v4"></path>
              <path d="M12 17h.01"></path>
            </svg>
          </span>
          <div class="min-w-0">
            <h2 id="_R_0_-unsaved-title" class="text-base font-semibold">You have 3 unsaved changes</h2>
            <p id="_R_0_-unsaved-body" class="mt-1 text-sm text-muted-foreground">Closing now discards them. Saving keeps them and closes the editor.</p>
          </div>
        </div>
        <dl class="mt-4 space-y-2 rounded-xl border border-border bg-muted/40 p-3">
          <div class="text-xs">
            <dt class="font-medium">Display name</dt>
            <dd class="mt-0.5 flex flex-wrap items-center gap-1.5 text-muted-foreground">
              <span class="line-through">Acme Corp</span>
              <span aria-hidden="true">→</span>
              <span class="font-medium text-foreground">Acme Corporation Ltd</span>
            </dd>
          </div>
          <div class="text-xs">
            <dt class="font-medium">Billing email</dt>
            <dd class="mt-0.5 flex flex-wrap items-center gap-1.5 text-muted-foreground">
              <span class="line-through">ap@acme.com</span>
              <span aria-hidden="true">→</span>
              <span class="font-medium text-foreground">accounts-payable@acme.com</span>
            </dd>
          </div>
          <div class="text-xs">
            <dt class="font-medium">Seat limit</dt>
            <dd class="mt-0.5 flex flex-wrap items-center gap-1.5 text-muted-foreground">
              <span class="line-through">24</span>
              <span aria-hidden="true">→</span>
              <span class="font-medium text-foreground">40</span>
            </dd>
          </div>
        </dl>
        <div class="mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
          <button type="button" class="inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x h-4 w-4" aria-hidden="true"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>Keep editing</button>
          <button type="button" class="inline-flex items-center justify-center gap-1.5 rounded-lg border border-destructive/40 px-3 py-2 text-sm font-medium text-destructive transition-colors hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash2 lucide-trash-2 h-4 w-4" aria-hidden="true"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" x2="10" y1="11" y2="17"></line><line x1="14" x2="14" y1="11" y2="17"></line></svg>Discard changes</button>
          <button type="button" class="inline-flex items-center justify-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-save h-4 w-4" aria-hidden="true"><path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"></path><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"></path><path d="M7 3v4a1 1 0 0 0 1 1h7"></path></svg>Save and close</button>
        </div>
      </div>
    </div>
  </div>
</div>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

7 more blocks in Modals & Drawers

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Modals & Drawers

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Modals & Drawers blocks

View category
Open the full page for this block

Destructive Confirm Dialog

A type-to-confirm dialog built on native <dialog>, so the focus trap, top layer and escape handling come from the browser. Focus lands on Cancel, and the button says the verb.

Modals & Drawers184 lines1 dep
Open the full page for this block

Cookie Consent Banner

Per-category consent where refusing is exactly as easy as accepting, nothing non-essential is pre-ticked, and the page behind it stays readable — the shape the law expects, wired to your own script gating.

Modals & Drawers232 lines1 dep
Open the full page for this block

Slide-Over Edit Panel

A side sheet for editing a record without losing the list behind it — native <dialog> for the trapping, a data attribute for the slide, and a sticky footer so Save never scrolls away.

Modals & Drawers208 lines1 dep
Open the full page for this block

Faceted Filter Drawer

Facets with per-option counts, zero-result options disabled rather than hidden so the list never jumps, and a pending selection applied on a button that says how many choices changed.

Modals & Drawers241 lines1 dep
Open the full page for this block

Share & Access Dialog

The share modal where a design mistake is a data leak: general access stated as its consequence rather than its setting, and a copy button that never silently widens access.

Modals & Drawers312 lines1 dep
Open the full page for this block

Mobile Bottom Sheet

Half and full snap points where the content owns the scroll and overscroll-contain keeps the page behind still. The drag handle is a real button, Escape and the backdrop close it, and safe-area padding keeps the last row pressable.

Modals & Drawers266 lines1 dep
Open the full page for this block

Record Inspector Drawer

A non-modal drawer that keeps the list on screen, with previous and next controls for moving between records and an activity tab beside the fields.

Modals & Drawers336 lines1 dep