Skip to content
opsinjs
Edit this page

Components

ConsentSheet

A sheet that asks permission for one specific thing at a time, explains what it is for, and makes saying no or changing your mind as easy as saying yes.

Usage

pnpm dlx shadcn@latest add @opsinjs/consent-sheet

The @opsinjs namespace is declared in your components.json. Everything it installs is code you then own. There is no runtime package to keep in step.

import { ConsentSheet } from "@/components/ui/consent-sheet"
<ConsentSheet
  open={open}
  onOpenChange={setOpen}
  consentId="example-consent"
  textVersion={copy.version}
  heading={copy.question}
  purpose={copy.purpose}
  scope={copy.scope}
  withdrawalPath={copy.withdrawal}
  acceptLabel={copy.accept}
  declineLabel={copy.decline}
  onDecision={store}
/>

Examples

Theme
Density
Text
Status
Accent theme
Accent
consent-sheet · base base · style base-lyraOpen under the product theme

Press a control and onDecision receives a record. Leave by any other exit and nothing arrives: no record, no false.

Theme
Density
Text
Status
Accent theme
Accent
consent-sheet-closing-is-not-consent · base base · style base-lyraOpen under the product theme
consent-sheet-closing-is-not-consent.tsx
"use client"

import { useState } from "react"

import { Button } from "@/components/ui/button"
import { ConsentSheet } from "@/components/ui/consent-sheet"

const EXAMPLE_SCOPE = {
  collected: "Placeholder for what is collected. The product writes this line.",
  sharedWith: "Placeholder for who can see it. The product writes this line.",
  retention: "Placeholder for how long it is kept. The product writes this line.",
}

export default function ConsentSheetClosingIsNotConsent() {
  const [open, setOpen] = useState(false)
  const [log, setLog] = useState<string[]>([])

  function record(line: string) {
    /* Newest first, and the list is bounded so a demo left open in a docs tab
       does not grow without end. */
    setLog((current) => [line, ...current].slice(0, 5))
  }

  return (
    <div className="flex w-full flex-col items-center gap-opsin-4 p-opsin-4">
      <p className="m-0 max-w-sm text-center text-opsin-footnote text-muted-foreground">
        Open it and leave without answering. Try the escape key, the dimmed
        area, or the close control in the header. Then open it again and press
        one of the two controls. Only the second produces a record.
      </p>

      <Button onClick={() => setOpen(true)}>Open the example question</Button>

      <ul className="m-0 flex w-full max-w-md list-none flex-col gap-opsin-1 p-0 text-opsin-caption1 text-muted-foreground">
        {log.length === 0 ? (
          <li>Nothing has reached the product yet.</li>
        ) : (
          log.map((line, index) => (
            <li key={`${line}-${String(index)}`} className="wrap-break-word">
              {line}
            </li>
          ))
        )}
      </ul>

      <ConsentSheet
        open={open}
        onOpenChange={(nextOpen, route) => {
          if (!nextOpen) {
            record(`closed by ${route} without onDecision being called`)
          }
          setOpen(nextOpen)
        }}
        consentId="example-consent"
        textVersion="example-wording-0"
        heading="Placeholder question. Is this the example thing?"
        purpose="Placeholder for the purpose. In a product this sentence says what the reader gets, in their own words."
        scope={EXAMPLE_SCOPE}
        withdrawalPath="Placeholder for where a reader changes this later. In a product it names the screen."
        acceptLabel="Yes, to the example thing"
        declineLabel="No, not the example thing"
        onDecision={(decision) => {
          record(
            `onDecision · ${decision.granted ? "granted" : "declined"} · ${decision.consentId} · ${decision.textVersion} · ${decision.at}`,
          )
          /* The component does not close itself, for the same reason Sheet does
             not: `open` is the caller's, so a product can show what happens next
             before the surface goes away. Here there is nothing next, so it
             closes immediately. */
          setOpen(false)
        }}
      />
    </div>
  )
}

Two questions, two sheets

No purposes array exists, so two permissions are two sheets and two records. The second follows an answer, never a dismissal, and shows consequenceOfDeclining.

Theme
Density
Text
Status
Accent theme
Accent
consent-sheet-two-questions-two-sheets · base base · style base-lyraOpen under the product theme
consent-sheet-two-questions-two-sheets.tsx
"use client"

import { useEffect, useRef, useState } from "react"

import { Button } from "@/components/ui/button"
import { ConsentSheet } from "@/components/ui/consent-sheet"

const FIRST_SCOPE = {
  collected: "Placeholder for what the first question collects.",
  sharedWith: "Placeholder for who can see it.",
  retention: "Placeholder for how long it is kept.",
}

const SECOND_SCOPE = {
  collected: "Placeholder for what the second question collects. This is a different thing.",
  sharedWith: "Placeholder for who can see it. This is a different recipient.",
  retention: "Placeholder for how long it is kept. This is a different period.",
}

export default function ConsentSheetTwoQuestionsTwoSheets() {
  const [asking, setAsking] = useState<"none" | "first" | "second">("none")
  const [answers, setAnswers] = useState<Record<string, string>>({})
  /* A sheet opened by a control returns focus to that control on its own. This
     one cannot, because by the time the last sheet closes the reader may have
     been through two of them and nothing they focused opened the second. So the
     return is written out. A counter rather than a boolean, because the reader
     can go through this more than once and a flag already `true` would not
     re-run the effect. */
  const triggerRef = useRef<HTMLDivElement>(null)
  const [returns, setReturns] = useState(0)
  /* Whether the first sheet closed because it was answered rather than because
     the reader left. It is a ref and not state, because the only reader of it is
     the first sheet's `onOpenChange`, which must not trigger a render of its own,
     and because it has to be set inside an event handler and read in the same
     handler without a re-render between the two. */
  const answeredRef = useRef(false)

  useEffect(() => {
    if (returns === 0) return
    triggerRef.current?.querySelector("button")?.focus()
  }, [returns])

  return (
    <div className="flex w-full flex-col items-center gap-opsin-4 p-opsin-4">
      <p className="m-0 max-w-sm text-center text-opsin-footnote text-muted-foreground">
        Two separate questions, asked one after the other. Answer them
        differently. The point of asking twice is that the two answers do not
        have to match.
      </p>

      {/* The trigger is read out of a wrapper rather than through a `ref` on
          Button, because `ButtonProps` omits `ref`: it extends the element's
          HTML attributes, and `ref` lives on `RefAttributes`. ConsentSheet
          reads its decision controls out of a wrapper for the same reason. */}
      <div ref={triggerRef}>
        <Button onClick={() => setAsking("first")}>Ask both example questions</Button>
      </div>

      <ul className="m-0 flex w-full max-w-md list-none flex-col gap-opsin-1 p-0 text-opsin-caption1 text-muted-foreground">
        {Object.keys(answers).length === 0 ? (
          <li>No answers yet.</li>
        ) : (
          Object.entries(answers).map(([id, verdict]) => (
            <li key={id} className="wrap-break-word">
              {id}: {verdict}
            </li>
          ))
        )}
      </ul>

      <ConsentSheet
        open={asking === "first"}
        onOpenChange={(nextOpen) => {
          if (nextOpen) return
          /* A close without an answer is not an answer, and it is not
             permission to ask the next thing either, so the reader is returned
             to the page. Telling "closed because it was answered" from "closed
             because the reader left" must not go through a state updater:
             React runs an updater twice in development StrictMode, so a
             `setReturns` called from inside one would count every dismissal
             twice. The answered case is recorded in a ref instead. Pressing a
             control runs `onDecision` first, which sets `answeredRef` and then
             `asking` to "second", thereby closing this sheet and firing
             `onOpenChange(false)` with the ref already true, so this handler
             consumes the flag and skips the return. A close the reader drove
             leaves the ref false and returns them to the page. A reader who
             wants question two can press the trigger again; in a real product
             it would be asked at the moment it became relevant. */
          if (answeredRef.current) {
            answeredRef.current = false
            return
          }
          setAsking("none")
          setReturns((count) => count + 1)
        }}
        consentId="example-consent-first"
        textVersion="example-wording-0"
        heading="Placeholder question one. Is this the first example thing?"
        purpose="Placeholder for the first purpose. In a product this sentence says what the reader gets."
        scope={FIRST_SCOPE}
        withdrawalPath="Placeholder for where a reader changes this first decision later."
        acceptLabel="Yes, to the first example thing"
        declineLabel="No, not the first example thing"
        onDecision={(decision) => {
          setAnswers((current) => ({
            ...current,
            [decision.consentId]: decision.granted ? "granted" : "declined",
          }))
          /* Record that this close is an answer before opening the next sheet,
             so the `onOpenChange` this triggers does not treat it as the reader
             leaving and does not return focus while the second sheet is opening. */
          answeredRef.current = true
          setAsking("second")
        }}
      />

      <ConsentSheet
        open={asking === "second"}
        onOpenChange={(nextOpen) => {
          if (nextOpen) return
          setAsking("none")
          setReturns((count) => count + 1)
        }}
        consentId="example-consent-second"
        textVersion="example-wording-0"
        heading="Placeholder question two. Is this the second example thing?"
        purpose="Placeholder for the second purpose, which is a different purpose and therefore a different question."
        scope={SECOND_SCOPE}
        withdrawalPath="Placeholder for where a reader changes this second decision later."
        consequenceOfDeclining="Placeholder for what a reader loses by saying no to this one. It is stated here, before they choose, and never raised as a confirmation afterwards."
        acceptLabel="Yes, to the second example thing"
        declineLabel="No, not the second example thing"
        onDecision={(decision) => {
          setAnswers((current) => ({
            ...current,
            [decision.consentId]: decision.granted ? "granted" : "declined",
          }))
          setAsking("none")
          setReturns((count) => count + 1)
        }}
      />
    </div>
  )
}

When the wording is missing

Any required string blank or absent means the sheet refuses to ask, showing the not-asked line and naming the missing fields in the console.

Theme
Density
Text
Status
Accent theme
Accent
consent-sheet-no-wording-supplied · base base · style base-lyraOpen under the product theme
consent-sheet-no-wording-supplied.tsx
"use client"

import { useState } from "react"

import { Button } from "@/components/ui/button"
import { ConsentSheet } from "@/components/ui/consent-sheet"

/* Empty strings rather than omitted keys, because a field that exists and has
   nothing in it is how the wording actually goes missing. The component treats
   a whitespace-only string as missing for the same reason. */
const NOTHING_SUPPLIED = {
  collected: "",
  sharedWith: "",
  retention: "",
}

export default function ConsentSheetNoWordingSupplied() {
  const [open, setOpen] = useState(false)

  return (
    <div className="flex w-full flex-col items-center gap-opsin-4 p-opsin-4">
      <p className="m-0 max-w-sm text-center text-opsin-footnote text-muted-foreground">
        This sheet was given a question and no answer to it: no scope, no
        withdrawal sentence, no words on the controls. It refuses to ask rather
        than asking half a question.
      </p>

      <Button onClick={() => setOpen(true)}>Open the incomplete sheet</Button>

      <ConsentSheet
        open={open}
        onOpenChange={(nextOpen) => setOpen(nextOpen)}
        consentId="example-consent-incomplete"
        textVersion="example-wording-0"
        heading="Placeholder question. Is this the example thing?"
        purpose="Placeholder for the purpose. Everything after this line was left empty on purpose."
        scope={NOTHING_SUPPLIED}
        withdrawalPath=""
        acceptLabel=""
        declineLabel=""
        onDecision={() => {
          /* Unreachable while the wording is missing: there are no controls to
             press, and nothing else in the component calls this. It is written
             out rather than left as a bare arrow so that the claim is legible
             from the example itself. */
        }}
      />
    </div>
  )
}

When to use it

Use it when

  • Asking permission to collect, use or share a specific kind of health data.
  • Re-asking for a permission whose scope has changed, so the earlier decision no longer covers it.
  • Confirming a decision with consequences the reader should see first, such as sharing a record.

Do not use it when

  • Showing permissions already given, to review or withdraw them.Use card instead.
  • The reader must simply acknowledge something before continuing, with no meaningful choice.Use dialog instead.
  • You need an operating-system permission, such as notifications; the platform owns that.Use sheet instead.
  • The message is the standing not-medical-advice note, not a request.Use disclaimer-note instead.
  • You are collecting the data itself rather than the permission to collect it.Use field instead.

Clinical meaning

Asserts. One specific permission is being asked for, and the reader has been told what is collected, what it is for, who sees it and how long it is kept.

Never read as. A condition of using the product, unless it genuinely is one and the sheet says so, and never as permanent, because the sheet says where to withdraw. See Consent and privacy.

Colour axis. Neither. No element carries data-status or data-category. See Health.

Thresholds. None. The sheet displays no reading. Every consent string arrives as a prop, because the wording is the product's legal statement (Safety review).

Closing is not deciding. Only the two controls call onDecision. Escape, scrim, drag and header Close call nothing, so did not answer is the absence of a call, never a stored false.

Accessibility

heading is the dialog's accessible name and purpose its description, and focus lands on the sheet. The two decisions are one grid, one Button variant at one size, decline first and never stacked, and the copy carries every meaning so nothing rides on colour. The details trigger is a real button with aria-expanded and aria-controls. The audit's one fix put its focus ring on the decision buttons' --opsin-border-focus token, so a theme that thickens the ring reaches it too. A ring was already visible, so no gap closed. pnpm run check:a11y holds every commit to no px size, raw colour, banned word or element resolving a category or status property.

Residual items.

  • With heading omitted the sheet refuses to ask and the dialog has no accessible name. The component warns in development, so this is invalid usage, not a supported state.
  • The open sheet could not be exercised rendered, so its verdicts rest on source.
  • Focus trap, focus return, dismissal and the swipe close alternative belong to Sheet and are verified there.
KeyActionNotes
TabMoves through the sheet in DOM order: close, scrolling region, disclosure if present, decline, acceptFocus starts on the sheet.
Shift+TabThe same order in reverseFocus is trapped while modal, so the order wraps.
EnterActivates the control that has focus
SpaceActivates the control that has focusIdentical to Enter.
EscapeCloses the sheet without deciding, returning focus to the openeronDecision is not called. onOpenChange reports route "escape".
Arrow keysNothingTwo tab stops, not a radio group.
Contrast: 36 measured token pairs, 15 below floor
PairThemeAPCA LcWCAG 2.2Floor
body text on the pagelight101.617.18:1Pass
body text on the pagedark-100.518.00:1Pass
body text on a cardlight104.717.96:1Pass
body text on a carddark-99.616.32:1Pass
body text on the muted groundlight98.116.32:1Pass
body text on the muted grounddark-97.513.77:1Pass
secondary text on the pagelight83.97.42:1Pass
secondary text on the pagedark-80.713.44:1Pass
secondary text on a cardlight87.07.76:1Pass
secondary text on a carddark-79.812.19:1Pass
secondary text on the muted groundlight80.47.05:1Pass
secondary text on the muted grounddark-77.810.28:1Pass
a hairline boundary on the pagelight19.31.41:1Below floor
a hairline boundary on the pagedark-8.21.90:1Below floor
a hairline boundary on a cardlight22.41.47:1Below floor
a hairline boundary on a carddark-7.31.72:1Below floor
a hairline boundary on the muted groundlight15.81.34:1Below floor
a hairline boundary on the muted grounddark0.01.45:1Below floor
a placeholder boundary on the pagelight69.84.52:1Pass
a placeholder boundary on the pagedark-51.07.62:1Pass
a placeholder boundary on a cardlight72.84.72:1Pass
a placeholder boundary on a carddark-50.16.91:1Pass
a placeholder boundary on the muted groundlight66.24.29:1Pass
a placeholder boundary on the muted grounddark-48.15.83:1Pass
a placeholder fill on the pagelight8.31.18:1Below floor
a placeholder fill on the pagedark-8.21.90:1Below floor
a placeholder fill on a cardlight11.41.23:1Below floor
a placeholder fill on a carddark-7.31.72:1Below floor
a placeholder fill on the muted groundlight0.01.12:1Below floor
a placeholder fill on the muted grounddark0.01.45:1Below floor
a placeholder boundary on its own filllight58.93.84:1Pass
a placeholder boundary on its own filldark-41.54.01:1Below floor
the card hairline on the pagelight69.84.52:1Pass
the card hairline on the pagedark-28.74.19:1Below floor
the card hairline on a cardlight72.84.72:1Pass
the card hairline on a carddark-27.93.80:1Below floor

These are the measured token pairs this component draws colour from, not a measurement of the component itself.

Props interface

Prop

Type

Generated from ConsentSheetProps in registry/bases/base/consent-sheet.tsx.

interface ConsentScope { collected: string; sharedWith: string; retention: string }
interface ConsentDetails { label: string; content: ReactNode }
interface ConsentDecision {
  granted: boolean; at: string; consentId: string; textVersion: string; scope: ConsentScope
}

ConsentSheetProps extends SheetProps with title, children and footer removed, because heading is the title. A whitespace-only string counts as missing. There is no purposes, defaultGranted, required, hideDecline, acceptVariant or declineVariant.