Exclusivobeta

One More Thing <mv-one-more-thing>

Validação de formulários priorizada, que pede uma coisa de cada vez em vez de mostrar um paredão de erros. Envolva um formulário longo (onboarding, cadastro, pagamento, configurações) ou aponte para um com for=: o formulário recebe novalidate e, no envio, todos os problemas são coletados (a validação nativa de restrições lida por validity e validationMessage, regras do app com prioridade e bloqueio, sugestões declarativas em campos opcionais), ordenados (primeiro os bloqueantes, depois por prioridade e então pela ordem no documento, um problema por campo) e só o mais importante é apresentado, como um aviso tranquilo inserido logo abaixo do campo, com uma seta apontando para ele: “Before you continue · VAT number: Your company’s VAT number is needed to issue invoices in the EU.”, um contador (“2 more after this (1 optional)”) e pontos de progresso para que nunca pareça um ciclo sem fim. O campo é rolado até ficar visível e recebe o foco, ganha aria-invalid e aria-describedby, e o aviso passa para “Looks good” ao vivo assim que o problema é corrigido. Enter ou Continue enviam de novo: o formulário segue quando não resta nada bloqueante (mv-all-clear, e então os próprios handlers de envio do app são executados); caso contrário, o aviso passa para o próximo campo. Um select, checkbox ou rádio avança sozinho após uma escolha, mas o envio final sempre exige uma ação deliberada. As sugestões não bloqueantes vêm por último, com “Skip, I’ll add it later”, “Show everything” lista o que falta para os usuários avançados (cada item leva ao seu campo), as regras são simples funções síncronas que podem ler qualquer campo, o aviso sai das linhas de várias colunas para nunca quebrar um grid, campos escondidos em um <details> fechado são revelados, e mv-one-more-thing (cancelável) permite que o app abra uma etapa de um assistente ou apresente o problema do seu jeito.

CategoriaFormulários
TipoWeb Component (<mv-one-more-thing>)
Statusbeta
KitFormulários que não perdem ninguém
Também instalabutton
Keywordsexclusive, culture, form, validation, form-validation, constraint-validation, error-summary, one-at-a-time, prioritized, focus-management, onboarding, checkout, application-form, suggestion, skippable, accessibility, novalidate, submit

When to use

  • A long onboarding, application or checkout form fails on submit and a list of ten red errors would discourage people
  • Some problems matter more than others (a tax ID needed to invoice, a legal consent) and must be asked first
  • Optional but valuable fields (phone, logo, team size) deserve a gentle, skippable ask right before the form is sent
  • Validation messages should be written as one clear request at a time, anchored to the field, with native constraints kept

Avoid when

  • The form is short (login, newsletter): inline field errors are faster to scan than a one-by-one flow → use Field instead
  • The value is valid but the content probably forgot something (an attachment mentioned, a leftover placeholder) → use Forgot instead
  • People need hints while filling the form in, before they ever submit it → use Insist instead

Instalação

node scripts/add.mjs one-more-thing --out ./src/marvelous

Agente de IA com o servidor MCP do Marvelous UI: install_components({ slugs: ["one-more-thing"], target_dir: "<absolute path>/src/marvelous", framework: "react" }).

Arquivos copiados (dependências incluídas): tokens/tokens.css, core/base.css, core/dom.js, core/element.js, core/focus.js, core/motion.js, core/observe.js, components/one-more-thing/one-more-thing.js, components/one-more-thing/one-more-thing.css, components/button/button.css.

Uso

Início rápido, a menor marcação que funciona:

<mv-one-more-thing>
  <form>
    <label>Email <input name="email" type="email" required></label>
    <label>VAT number <input name="vat" required data-one-more-thing-message="Your VAT number is needed to issue invoices."></label>
    <button>Continue</button>
  </form>
</mv-one-more-thing>

Marcação de referência, para usar como ponto de partida e personalizar com atributos, data-* e variáveis CSS:

<div id="omt-demo" style="width:min(100%,62rem);margin-inline:auto">
  <style>
    #omt-demo .omt-layout { display:grid; grid-template-columns:minmax(0,1fr) 16.5rem; gap:1.25rem; align-items:start }
    #omt-demo .omt-card { min-width:0; border:1px solid var(--mv-border); border-radius:var(--mv-radius-xl); background:var(--mv-surface); box-shadow:var(--mv-shadow-sm) }
    #omt-demo .omt-head { display:flex; align-items:center; justify-content:space-between; gap:.75rem; padding:1rem 1.25rem; border-bottom:1px solid var(--mv-border) }
    #omt-demo .omt-head h3 { margin:0; font-size:1rem; letter-spacing:-.01em }
    #omt-demo .omt-head p { margin:.125rem 0 0; color:var(--mv-fg-muted); font-size:.8125rem }
    #omt-demo form { display:grid; gap:1.125rem; padding:1.25rem }
    #omt-demo .omt-row { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:1rem }
    #omt-demo .omt-row[data-cols="3"] { grid-template-columns:minmax(0,2fr) minmax(0,1fr) minmax(0,1fr) }
    #omt-demo .omt-foot { display:flex; align-items:center; justify-content:flex-end; gap:.5rem; margin:.25rem -1.25rem -1.25rem; padding:.875rem 1.25rem; border-top:1px solid var(--mv-border); border-radius:0 0 var(--mv-radius-xl) var(--mv-radius-xl); background:var(--mv-bg-subtle) }
    #omt-demo .omt-foot .omt-note { order:-2; margin-right:auto; color:var(--mv-fg-muted); font-size:.75rem }
    #omt-demo .omt-foot [formnovalidate] { order:-1 }
    #omt-demo .omt-done { display:none; align-items:center; gap:.75rem; margin:1.25rem 1.25rem 0; padding:.75rem 1rem; border:1px solid color-mix(in oklab, var(--mv-success) 35%, var(--mv-border)); border-radius:var(--mv-radius-lg); background:color-mix(in oklab, var(--mv-success) 7%, var(--mv-surface)); font-size:.8125rem }
    #omt-demo .omt-done[data-show] { display:flex }
    #omt-demo .omt-done svg { flex:none; width:1.125rem; height:1.125rem; color:var(--mv-success) }
    #omt-demo .omt-side { position:sticky; top:1rem; display:grid; gap:1rem; padding:1.125rem; border:1px solid var(--mv-border); border-radius:var(--mv-radius-xl); background:var(--mv-surface-raised); box-shadow:var(--mv-shadow-sm); font-size:.8125rem }
    #omt-demo .omt-side h4 { display:flex; align-items:center; justify-content:space-between; gap:.5rem; margin:0; font-size:.8125rem; font-weight:600 }
    #omt-demo .omt-k { color:var(--mv-fg-muted); font-size:.6875rem; font-weight:600; letter-spacing:.04em; text-transform:uppercase }
    #omt-demo .omt-queue { display:grid; gap:.375rem; margin:0; padding:0; list-style:none }
    #omt-demo .omt-queue li { display:flex; align-items:baseline; gap:.5rem; color:var(--mv-fg-muted); font-size:.75rem }
    #omt-demo .omt-queue li b { color:var(--mv-fg); font-weight:500 }
    #omt-demo .omt-queue li[data-now] b { color:var(--mv-accent) }
    #omt-demo .omt-queue li span { margin-left:auto; white-space:nowrap }
    #omt-demo .omt-queue .omt-empty { color:var(--mv-fg-subtle) }
    #omt-demo .omt-log { display:grid; gap:.25rem; margin:0; padding:0; list-style:none; font:.6875rem/1.45 var(--mv-font-mono); color:var(--mv-fg-muted) }
    #omt-demo .omt-log li { overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
    #omt-demo .omt-log li b { color:var(--mv-fg); font-weight:500 }
    #omt-demo .omt-sep { height:1px; background:var(--mv-border) }
    #omt-demo .omt-actions { display:flex; flex-wrap:wrap; gap:.5rem }
    #omt-demo .mv-choice { font-size:.8125rem }
    #omt-demo .omt-hint { margin:.875rem 0 0; color:var(--mv-fg-muted); font-size:.75rem; text-align:center }
    @media (max-width:52rem) {
      #omt-demo .omt-layout { grid-template-columns:minmax(0,1fr) }
      #omt-demo .omt-side { position:static }
    }
    @media (max-width:34rem) {
      #omt-demo .omt-row, #omt-demo .omt-row[data-cols="3"] { grid-template-columns:minmax(0,1fr) }
    }
  </style>

  <div class="omt-layout">
    <section class="omt-card" aria-labelledby="omt-title">
      <div class="omt-head">
        <div>
          <h3 id="omt-title">Billing details</h3>
          <p>Northwind Labs workspace · Step 3 of 3</p>
        </div>
        <span class="mv-badge" data-variant="secondary">Pro · $240 / month</span>
      </div>
      <div class="omt-done" id="omt-done" role="status">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.5"/><path d="m8 12.5 2.8 2.8L16.5 9.5"/></svg>
        <span id="omt-done-text">Workspace created. The first invoice goes out on October 1, 2026.</span>
      </div>

      <mv-one-more-thing id="omt">
        <form id="omt-form" aria-labelledby="omt-title">
          <div class="mv-field">
            <label class="mv-label" for="omt-company" data-required>Company name</label>
            <input class="mv-input" id="omt-company" name="company" value="Northwind Labs GmbH" required autocomplete="organization">
          </div>

          <div class="mv-field">
            <label class="mv-label" for="omt-email" data-required>Billing email</label>
            <input class="mv-input" id="omt-email" name="email" type="email" value="dana.whitfield.northwind.io" required autocomplete="email" spellcheck="false">
          </div>

          <div class="omt-row">
            <div class="mv-field">
              <label class="mv-label" for="omt-country" data-required>Country</label>
              <select class="mv-select" id="omt-country" name="country" required autocomplete="country-name">
                <option value="">Select a country</option>
                <option value="US">United States</option>
                <option value="CA">Canada</option>
                <option value="DE" selected>Germany</option>
                <option value="FR">France</option>
                <option value="NL">Netherlands</option>
                <option value="GB">United Kingdom</option>
                <option value="JP">Japan</option>
              </select>
            </div>
            <div class="mv-field">
              <label class="mv-label" for="omt-vat">VAT number</label>
              <input class="mv-input" id="omt-vat" name="vat" placeholder="DE123456789" autocomplete="off" spellcheck="false">
            </div>
          </div>

          <div class="omt-row" data-cols="3">
            <div class="mv-field">
              <label class="mv-label" for="omt-street" data-required>Street address</label>
              <input class="mv-input" id="omt-street" name="street" value="Torstraße 128" required autocomplete="street-address">
            </div>
            <div class="mv-field">
              <label class="mv-label" for="omt-zip" data-required>Postal code</label>
              <input class="mv-input" id="omt-zip" name="zip" value="10119" required pattern="[0-9A-Za-z \-]{3,10}" autocomplete="postal-code" data-one-more-thing-message="Use the postal code printed on your company registration.">
            </div>
            <div class="mv-field">
              <label class="mv-label" for="omt-city" data-required>City</label>
              <input class="mv-input" id="omt-city" name="city" value="Berlin" required autocomplete="address-level2">
            </div>
          </div>

          <div class="mv-field">
            <label class="mv-label" for="omt-phone" data-optional="optional">Phone</label>
            <input class="mv-input" id="omt-phone" name="phone" type="tel" placeholder="+49 30 1234567" autocomplete="tel"
              data-one-more-thing-suggest="Your onboarding specialist can call you to set up SSO and invite your team.">
          </div>

          <label class="mv-choice">
            <input type="checkbox" class="mv-checkbox" id="omt-terms" name="terms" required
              data-one-more-thing-label="Terms of Service"
              data-one-more-thing-message="Accept the Terms of Service and the Data Processing Agreement to create the workspace.">
            I agree to the Terms of Service and the Data Processing Agreement
          </label>

          <div class="omt-foot">
            <span class="omt-note">You can change this later in Settings.</span>
            <!-- The primary button comes first in the DOM: it is the one Enter submits with. -->
            <button type="submit" class="mv-button">Create workspace</button>
            <button type="submit" class="mv-button" data-variant="ghost" formnovalidate>Save draft</button>
          </div>
        </form>
      </mv-one-more-thing>
    </section>

    <aside class="omt-side" aria-label="Validation monitor">
      <h4>Still to check <span class="mv-badge" data-variant="secondary" data-shape="pill" id="omt-count">-</span></h4>
      <ol class="omt-queue" id="omt-queue"><li class="omt-empty">Nothing yet</li></ol>
      <div class="omt-sep"></div>
      <div style="display:grid;gap:.5rem">
        <span class="omt-k">Events</span>
        <ol class="omt-log" id="omt-log"><li>Press <b>Create workspace</b></li></ol>
      </div>
      <div class="omt-sep"></div>
      <label class="mv-choice" data-control="end">
        <input type="checkbox" role="switch" class="mv-switch" id="omt-auto" checked>
        <span class="mv-choice-text"><span class="mv-choice-title">Move on after a choice</span></span>
      </label>
      <div class="omt-actions">
        <button type="button" class="mv-button" data-variant="outline" data-size="sm" id="omt-all">Show everything</button>
        <button type="button" class="mv-button" data-variant="ghost" data-size="sm" id="omt-reset">Start over</button>
      </div>
    </aside>
  </div>
  <p class="omt-hint">Fix the field in the prompt, then press Enter or Continue · Esc hides the prompt · the VAT rule only applies to EU countries</p>

  <script type="module">
    const omt = document.getElementById("omt");
    const form = document.getElementById("omt-form");
    const $ = (id) => document.getElementById(id);
    const EU = new Set(["DE", "FR", "NL"]);

    // App rules: a priority above the native checks, because invoices cannot be issued without it.
    omt.rules = [
      {
        id: "vat",
        field: "vat",
        priority: 10,
        message: "Your company’s VAT number is needed to issue invoices in the EU.",
        validate: (value, { get }) => !EU.has(get("country")) || /^[A-Z]{2}[0-9A-Z]{8,12}$/.test(value.replace(/\s+/g, "").toUpperCase()) || (value.trim() ? "That doesn’t look like an EU VAT number (e.g. DE123456789)." : false),
      },
    ];

    await customElements.whenDefined("mv-one-more-thing");

    let fresh = true;
    const log = (name, text) => {
      const list = $("omt-log");
      if (fresh) { list.replaceChildren(); fresh = false; }
      const li = document.createElement("li");
      const b = document.createElement("b");
      b.textContent = name;
      li.append(b, ` ${text}`);
      list.prepend(li);
      while (list.children.length > 5) list.lastElementChild.remove();
    };

    const renderQueue = () => {
      const issues = omt.issues;
      const q = $("omt-queue");
      $("omt-count").textContent = issues.length ? `${issues.length} left` : "clear";
      $("omt-count").dataset.variant = issues.length ? "secondary" : "success";
      if (!issues.length) {
        q.replaceChildren(Object.assign(document.createElement("li"), { className: "omt-empty", textContent: "Nothing left to check" }));
        return;
      }
      q.replaceChildren(...issues.map((i, n) => {
        const li = document.createElement("li");
        if (n === 0) li.dataset.now = "";
        const b = document.createElement("b");
        b.textContent = i.label;
        const s = document.createElement("span");
        s.textContent = n === 0 ? "asking" : i.blocking ? "needed" : "optional";
        li.append(b, s);
        return li;
      }));
    };

    omt.addEventListener("mv-one-more-thing", (e) => {
      log("mv-one-more-thing", `${e.detail.issue.label} · ${e.detail.remaining} more`);
      queueMicrotask(renderQueue);
    });
    omt.addEventListener("mv-skip", (e) => log("mv-skip", e.detail.issue.label));
    omt.addEventListener("mv-all-clear", (e) => {
      log("mv-all-clear", e.detail.skipped.length ? `${e.detail.skipped.length} skipped` : "submitting");
      queueMicrotask(renderQueue);
    });
    form.addEventListener("submit", (e) => {
      e.preventDefault(); // demo: no real request
      if (e.submitter?.formNoValidate) { log("submit", "draft saved, not checked"); return; }
      $("omt-done").dataset.show = "";
      log("submit", "workspace created");
    });

    $("omt-auto").addEventListener("change", (e) => { omt.manual = !e.target.checked; });
    $("omt-all").addEventListener("click", () => omt.showAll());
    $("omt-reset").addEventListener("click", () => {
      // A real reset also clears the browser's “user interacted” flags (and the component's state).
      form.reset();
      delete $("omt-done").dataset.show;
      fresh = true;
      log("reset", "form restored");
      setTimeout(() => { omt.present({ focus: false, scroll: false }); renderQueue(); });
    });

    // Show the mechanic right away, without moving focus or scrolling the page.
    omt.present({ focus: false, scroll: false });
    renderQueue();
  </script>
</div>

Referência cultural

Columbo, Richard Levinson & William Link (NBC) (1968, série). O tenente parece ter terminado e vai em direção à porta, então se vira com “só mais uma coisa” e faz a única pergunta que mais importa, uma de cada vez. Aqui o formulário parece pronto para seguir, mas no envio o componente se volta com o problema mais importante, ancorado ao seu campo, e só depois com o seguinte, em contagem regressiva até o formulário poder sair.

API

Attributes

NameTipoDefaultDescription
foridChecks the form with this id instead of the form inside (or around) the element. Without it, the first <form> inside is used, then the closest ancestor form; a form rendered later is picked up when it appears.
manualbooleanfalseTurns off moving on by itself after a choice. By default, once a select, checkbox, radio, file, range or color field (or one marked data-one-more-thing-advance) fixes the current issue, the next one is presented after about half a second; the last issue never submits on its own either way.
data-stateaskingSet on the element while a prompt is open (styleable).
data-one-more-thing-prioritynumber0On a field: rank of its native issue or suggestion. Higher is asked first; blocking issues always come before suggestions, ties follow document order.
data-one-more-thing-messagestringOn a field: request shown when it fails native validation, instead of the browser's validationMessage (write it as one clear ask).
data-one-more-thing-labelstringOn a field: name shown as the prompt title (default: aria-labelledby, aria-label, <label> text without its controls, the legend of a radio group, placeholder, then name).
data-one-more-thing-suggeststringOn an optional field: when it is empty (unchecked, no file…) it becomes a non-blocking suggestion with this text, asked after every blocking issue and skippable.
data-one-more-thing-anchormarker attributeOn a wrapper around a field: the prompt is inserted after it (default: .mv-field, the fieldset of a checkbox or radio group, a wrapping <label>, else the field; the component then climbs out of any grid or flex row shared with other fields).
data-one-more-thing-ignoremarker attributeOn a field or a container: excluded from the checks (native and rules).
data-one-more-thing-skipmarker attributeOn a submit button: submits without any check, like formnovalidate (which is honored too), e.g. Save draft.
data-one-more-thing-advancemarker attributeOn a field (e.g. a custom picker): a committed change that fixes the current issue moves on by itself, like a select.
data-one-more-thingblocking | suggestionSet by the component on the field currently asked about (styleable), removed afterwards.

Properties

NameTipoDescription
rulesArray<{ id?, field?, validate(value, ctx), message?, priority?, blocking?, label? }>App rules. field: a name, a selector or an element of the form (omit it for a form-level rule anchored above the submit button; a rule whose field is not in the DOM is skipped). validate(value, { field, form, get(name) }) returns false or a string (the message) when there is a problem, anything else when it is fine; value is the string, checked state, radio group value, array (multi-select) or FileList. message: string or (ctx) => string. priority: number (default 0). blocking: default true; false makes it a skippable suggestion. A throwing rule never blocks.
stringsPartial<Record<string, string>>Overrides for every visible text and announcement (keys: eyebrow, resolved, optional, counter ({n}), counterOptional ({n}, {k}), last, continue, submit, skip, showAll ({n}), hideAll, listLabel, current, announce ({label}, {message}, {counter}), announceResolved ({label}, {action}), announceStill ({label}, {message})). English defaults.
formHTMLFormElement | nullThe form being checked (read-only).
current{ id, field, label, message, blocking, priority, source } | nullThe issue being asked about (read-only). source: "native" | "rule" | "suggestion".
issuesArray<issue>Every issue left at the last evaluation, ranked, the one asked about first (read-only).
skippedstring[]Ids of the suggestions skipped for this form session (read-only). Cleared by reset() and on form reset.
manualbooleanMirrors the attribute.

Methods

NameDescription
check()Evaluates the form without presenting anything and returns the ranked issues (skipped suggestions left out).
present({ focus?, scroll? })Asks about the most important issue now, without a submit (a Review step, a server error you mapped to a rule, a demo). Both options default to true; with focus: false nothing is announced either. Returns the issue presented, or null when all is clear.
showAll()Opens the “Show everything” list in the prompt (presenting first if needed). Returns false when there is nothing to show.
dismiss()Hides the prompt and restores the field's ARIA; the next submit starts over. Escape does the same from the field or the prompt.
reset()Forgets skipped suggestions and hides the prompt (done automatically on the form's reset event).

Events

NameDescription
mv-one-more-thingCancelable, before an issue is presented. detail: { field (null for a form-level rule), remaining (issues left after this one), issue, issues (ranked), submitter }. Open the wizard step or tab that holds the field here (focus waits a frame for hidden fields); preventDefault() keeps the submit held but lets you present the issue your own way (no prompt, no ARIA changes).
mv-skipA suggestion was skipped (“Skip, I’ll add it later”, or submitting again past it). detail: { field, id, issue }.
mv-all-clearNothing blocking and no suggestion left: emitted right before the submission goes on to the app's own submit handlers. detail: { form, submitter, skipped }.

Content structure

NameDescription
(content)A <form> (or nothing, with for=). The prompt is inserted inside the form, after the anchor of the field, and removed afterwards; two visually hidden live regions are appended to the element.

CSS classes

NameDescription
mv-one-more-thing-promptInserted wrapper (role=group, labelled by its eyebrow and title). data-kind="blocking | suggestion", data-side="below | above" (above for form-level rules), data-resolved once the issue is fixed. Spans every grid column.
mv-one-more-thing-cardThe visual card with its caret (--_caret-x, measured). Parts: -head, -icon, -eyebrow, -tag (“Optional”), -count, -dots (i[data-state=done|current|todo]), -title, -message, -actions, -continue, -skip, -all-toggle.
mv-one-more-thing-list / -item“Show everything” list: one button per issue (-item-index, -item-label, -item-message), aria-current on the one asked about.

CSS variables

NameDefaultDescription
--mv-one-more-thing-colorvar(--mv-accent)Tint of a blocking prompt: border, caret, icon, current dot. Deliberately not the danger color: it is a request, not a scolding.
--mv-one-more-thing-suggest-colorvar(--mv-info)Tint of a suggestion prompt.
--mv-one-more-thing-resolved-colorvar(--mv-success)Tint once the current issue is fixed, and of the done dots.

Accessibility

The prompt is a labelled group (eyebrow + field name) inserted right after the field in the DOM, so reading and Tab order stay natural: field, Continue (or Skip), Show everything, next field. The field asked about gets aria-invalid="true" (blocking issues only, removed live as soon as it is fixed, the previous value is restored afterwards) and the prompt's message is added to its aria-describedby; for a radio group every radio is wired. Focus moves to the field (the checked radio or the first one, the first focusable part of a form-associated custom element, or Continue for a form-level rule), with preventScroll, while the component scrolls the field and its prompt into view together (instant under reduced motion). Each issue is announced once in an assertive live region, a beat after focus moves: “Before you continue: VAT number. Your company’s VAT number is needed to issue invoices in the EU. 2 more after this.”; fixing it is announced politely once (“VAT number looks good. Press Enter or Continue to continue.”), and submitting again while it is still unanswered keeps focus on it with a polite “Still needed: …” and a soft ring (no shake). Everything works from the keyboard: Enter in a field submits again, Escape from the field or the prompt hides it, the “Show everything” toggle is a real button with aria-expanded and aria-controls, and its list items are buttons (aria-current on the one being asked) that move focus to their field. State is never color-only: an icon (a turn-back arrow, a bulb for suggestions, a check once fixed), the words “Before you continue” / “Looks good”, an “Optional” tag and a text counter carry it; the progress dots are aria-hidden. The final submission always takes a deliberate action (Enter, Continue or the submit button), never a checkbox tick. Reduced motion (OS or data-motion="reduce"): no height, slide or ring animation. Forced colors: system colors for the card, caret, icon and current item.

Esta página foi traduzida com IA. Informar um problema de tradução