Site

Auth form

The site's sign-in and sign-up form in a 400px column: the title and lead, a quiet provider button, the or rule, the email field with its message beside the label, the one White button, the legal line and the way to the other mode; a pressed button shows a spinner until the app takes over.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add auth-form
<script type="module" src="/spyglass-ds/elements/auth-form.js"></script>
Sign up

Create your Acme account

500 free credits every month. No card required.

or

By continuing, you acknowledge that you understand and agree to the Terms & Conditions and Privacy Policy.

Already have an account? Sign in

Usage

Signing in or up on a page of your own, or inside a dialog; the sign-in page uses it.

Never

  • A third-party logo shipped with the library: the provider's mark comes in through providerIcon (the provider-icon slot)
  • A second White button
  • Errors in red: the message is White beside the label and the field's ring turns White

Adds with it: button

Props

The web component takes the same as attributes or properties (<spyglass-auth-form>); title is heading there.

<AuthForm>

PropTypeDefault
modeAuthMode'sign-up'
contentAuthContent
providerIconReactNode

The provider's mark, 20px, before the provider button's label.

onProvider() => void

The provider button's press.

onEmail(email: string) => void

A valid email sent.

classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/auth-form/Form.tsx
'use client'
import { KeyRound } from 'lucide-react'
import { AuthForm } from '@/react/components/site/AuthForm'
// The form alone, for a page of your own: sign up with a neutral mark in the provider button.

export default function Form() {
  return <AuthForm mode="sign-up" providerIcon={<KeyRound size={20} strokeWidth={1.5} aria-hidden="true" />} onProvider={() => {}} onEmail={() => {}} />
}
elements/examples/auth-form/Form.html
<!-- The form alone, for a page of your own: sign up with a neutral mark in the provider button. -->
<spyglass-auth-form id="auth-form" mode="sign-up"><i slot="provider-icon" data-lucide="key-round" data-size="20" data-stroke-width="1.5" aria-hidden="true"></i></spyglass-auth-form>
<script type="module">
  const form = document.getElementById('auth-form')
  form.addEventListener('provider', (event) => event.preventDefault())
  form.addEventListener('email', (event) => event.preventDefault())
</script>

Source

react/components/site/AuthForm.tsx
'use client'
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { Button } from '@/react/components/ui/Button'
import { authContent, emailProblem, type AuthContent } from '@/lib/pages/auth'
import { cn } from '@/react/lib/cn'

// The site's sign-in and sign-up form (pages/Auth/AuthForm): the title and lead, a quiet provider button, a rule with
// "or", the email field with its label and the message beside it, the one White button, the legal line and the way to
// the other mode. Centered in a 400px column. A press shows a spinner in the pressed button (the label and the spinner
// cross-fade over 160ms) until the app takes over; pressing again does nothing meanwhile. The email is checked as the
// site checks it: empty or malformed puts the message beside the label, rings the field White and focuses it.
// The provider's mark comes in through `providerIcon` (no third-party logo ships with the library). `onProvider` and
// `onEmail` take the presses; without them a press goes to the mode's `next` address.
export type AuthMode = 'sign-in' | 'sign-up'

export interface AuthFormProps {
  mode?: AuthMode
  content?: AuthContent
  /** The provider's mark, 20px, before the provider button's label. */
  providerIcon?: ReactNode
  /** The provider button's press. */
  onProvider?: () => void
  /** A valid email sent. */
  onEmail?: (email: string) => void
  className?: string
}

function Labels({ busy, children }: { busy: boolean; children: ReactNode }) {
  return (
    <span className="grid place-items-center">
      <span className={cn('col-start-1 row-start-1 inline-flex items-center gap-3 transition-opacity duration-160 ease-out', busy && 'opacity-0')}>{children}</span>
      <span aria-hidden="true" className={cn('col-start-1 row-start-1 inline-flex items-center transition-opacity duration-160 ease-out', !busy && 'opacity-0')}>
        <span className={cn('ds-auth-spin size-5 rounded-full border-2 border-current border-t-transparent', !busy && '[animation-play-state:paused]')} />
      </span>
    </span>
  )
}

const LINK = 'rounded-ds-sm underline decoration-transparent decoration-from-font underline-offset-4 transition-[text-decoration-color] duration-160 ease-out pointer-fine:hover:decoration-current'

export function AuthForm({ mode = 'sign-up', content: c = authContent, providerIcon, onProvider, onEmail, className }: AuthFormProps) {
  const m = mode === 'sign-in' ? c.signIn : c.signUp
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')
  const [busy, setBusy] = useState<'provider' | 'email' | null>(null)
  const input = useRef<HTMLInputElement>(null)
  const id = useId()

  // Back from the next page (the page restored from the cache): the buttons wake up again.
  useEffect(() => {
    const back = (event: PageTransitionEvent) => { if (event.persisted) setBusy(null) }
    window.addEventListener('pageshow', back)
    return () => window.removeEventListener('pageshow', back)
  }, [])

  function go(method: 'provider' | 'email', value = '') {
    if (busy) return
    setBusy(method)
    if (method === 'provider' && onProvider) onProvider()
    else if (method === 'email' && onEmail) onEmail(value)
    else window.location.assign(m.next)
  }

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (busy) return
    const problem = emailProblem(email, c)
    setError(problem)
    if (problem) input.current?.focus()
    else go('email', email.trim())
  }

  return (
    <section data-ds="auth-form" aria-labelledby={`${id}-title`} className={cn('mx-auto flex w-full max-w-[calc(var(--ds-layout-auth)+2*var(--ds-layout-gutter))] flex-col items-center px-(--ds-layout-gutter) text-center text-fg', className)}>
      <style href="ds-auth-form" precedence="ds">{css}</style>
      <h1 id={`${id}-title`} className="type-title md:whitespace-nowrap">{m.title}</h1>
      {m.lead && <p className="mt-3 type-body text-balance text-fg-soft">{m.lead}</p>}
      <Button variant="secondary" size="form" className="mt-8 w-full" aria-disabled={busy ? true : undefined} onClick={() => go('provider')}>
        <Labels busy={busy === 'provider'}>{providerIcon && <span className="grid size-5 flex-none place-items-center [&_svg]:size-5">{providerIcon}</span>}{c.provider}</Labels>
      </Button>
      <p className="my-4 flex w-full items-center gap-4 type-ui text-fg-muted before:h-px before:flex-1 before:bg-edge after:h-px after:flex-1 after:bg-edge">{c.or}</p>
      <form noValidate onSubmit={submit} className="flex w-full flex-col text-left">
        <div className="mb-2 flex justify-between gap-4 type-ui">
          <label htmlFor={`${id}-email`} className="font-medium">{c.email}</label>
          <span id={`${id}-error`} role="alert" className="text-fg">{error}</span>
        </div>
        <input
          ref={input}
          id={`${id}-email`}
          type="email"
          inputMode="email"
          autoComplete="email"
          autoCapitalize="none"
          autoCorrect="off"
          spellCheck={false}
          enterKeyHint="go"
          placeholder={c.placeholder}
          value={email}
          aria-invalid={error ? true : undefined}
          aria-describedby={error ? `${id}-error` : undefined}
          onChange={(event) => { setEmail(event.target.value); if (error) setError('') }}
          className="mb-3 h-control-form w-full appearance-none rounded-control bg-surface-subtle px-4 type-body text-fg shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-edge)] transition-[box-shadow] duration-160 ease-out placeholder:text-fg-muted focus-visible:-outline-offset-1 aria-invalid:shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-white)]"
        />
        <Button type="submit" size="form" className="w-full" aria-disabled={busy ? true : undefined}>
          <Labels busy={busy === 'email'}>{m.submit}</Labels>
        </Button>
      </form>
      <p role="status" className="sr-only">{busy ? c.working : ''}</p>
      <p className="mt-5 type-ui text-balance text-fg-faint">
        {c.legal.before}<a href={c.legal.terms.href} className={cn('text-fg-soft', LINK)}>{c.legal.terms.label}</a>{c.legal.between}<a href={c.legal.privacy.href} className={cn('text-fg-soft', LINK)}>{c.legal.privacy.label}</a>{c.legal.after}
      </p>
      <p className="mt-5 type-ui text-fg-muted">
        {m.other.ask} <a href={m.other.href} className={cn('relative py-3 font-medium text-fg', LINK)}>{m.other.label}</a>
      </p>
    </section>
  )
}

export default AuthForm

const css = `
.ds-auth-spin { animation: ds-auth-spin 800ms linear infinite; }
@keyframes ds-auth-spin { to { transform: rotate(1turn); } }
@keyframes ds-auth-breathe { 50% { opacity: 0.5; } }
@media (prefers-reduced-motion: reduce) { .ds-auth-spin { animation: ds-auth-breathe 2s var(--ds-easing-in-out) infinite; } }
`
lib/pages/auth.ts
// The sign-in and sign-up pages' copy (the site's content/pages/auth.ts, for Acme). Both flavors read this file. Each
// mode has its title, lead, the White button's label, `next` (where a press goes when no handler takes it) and the way
// to the other mode.
export const authContent = {
	signUp: { title: 'Create your Acme account', lead: '500 free credits every month. No card required.', submit: 'Get started', next: '/app/sign-up', other: { ask: 'Already have an account?', label: 'Sign in', href: '/sign-in' } },
	signIn: { title: 'Welcome back', lead: 'Sign in to your Acme account.', submit: 'Continue', next: '/app/sign-in', other: { ask: 'Don’t have an account?', label: 'Sign up', href: '/sign-up' } },
	provider: 'Continue with Google',
	or: 'or',
	email: 'Email',
	placeholder: 'you@acme.com',
	empty: 'Enter your email',
	invalid: 'Check your email address',
	working: 'One moment',
	legal: { before: 'By continuing, you acknowledge that you understand and agree to the ', terms: { label: 'Terms & Conditions', href: '/terms' }, between: ' and ', privacy: { label: 'Privacy Policy', href: '/privacy' }, after: '.' },
	proof: 'Trusted by teams at',
	home: 'Home',
}
export type AuthContent = typeof authContent

/** The site's email check: something@something.tld, two letters or more after the dot. */
export const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/

/** The message for what was typed, or '' when it will do. */
export function emailProblem(value: string, c: AuthContent = authContent): string {
	const v = value.trim()
	return !v ? c.empty : EMAIL.test(v) ? '' : c.invalid
}

/** The auth page's sections in order; pass `sections` to reorder them or leave some out. */
export const authSections = ['form', 'proof'] as const
export type AuthSection = (typeof authSections)[number]
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
elements/components/site/auth-form.ts
import { html, nothing } from 'lit'
import { live } from 'lit/directives/live.js'
import { DsElement, define, HostLayoutController, uid } from '@/elements/lib/element'
import { authContent, emailProblem, type AuthContent } from '@/lib/pages/auth'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'

// AuthForm.tsx as <spyglass-auth-form>: the site's sign-in and sign-up form, the title and lead, a quiet provider
// button, the "or" rule, the email field with its message, the one White button, the legal line and the way to the other
// mode. A press shows a spinner in the pressed button until the app takes over. The provider's mark goes in the
// `provider-icon` slot. `provider` and `email` (with { email }) fire on a press; unless a listener calls
// preventDefault(), the press goes to the mode's `next` address.

/**
 * @summary The sign-in and sign-up form.
 * @slot provider-icon - The provider's mark, 20px.
 * @fires provider - The provider button pressed (cancelable).
 * @fires email - A valid email sent, with { email } (cancelable).
 */
export class AuthForm extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="auth-form"]'))
	static properties = { mode: { reflect: true }, content: { type: Object }, email: { state: true }, error: { state: true }, busy: { state: true } }
	/** sign-in or sign-up. */
	mode: 'sign-in' | 'sign-up' = 'sign-up'
	/** The copy (lib/pages/auth.ts by default). */
	content: AuthContent = authContent
	private email = ''
	private error = ''
	private busy: 'provider' | 'email' | null = null
	private uid = uid('auth')

	private back = (event: PageTransitionEvent) => { if (event.persisted) this.busy = null }
	connectedCallback() {
		super.connectedCallback()
		window.addEventListener('pageshow', this.back)
	}
	disconnectedCallback() {
		super.disconnectedCallback()
		window.removeEventListener('pageshow', this.back)
	}

	private go(method: 'provider' | 'email', value = '') {
		if (this.busy) return
		this.busy = method
		const c = this.content ?? authContent
		const m = this.mode === 'sign-in' ? c.signIn : c.signUp
		const free = method === 'provider' ? this.emit('provider', undefined, { cancelable: true }) : this.emit('email', { email: value }, { cancelable: true })
		if (free) window.location.assign(m.next)
	}

	private submit(event: Event) {
		event.preventDefault()
		if (this.busy) return
		const problem = emailProblem(this.email, this.content ?? authContent)
		this.error = problem
		if (problem) this.renderRoot.querySelector<HTMLInputElement>('input')?.focus()
		else this.go('email', this.email.trim())
	}

	private labels(busy: boolean, label: unknown) {
		return html`<span class="grid place-items-center"><span class=${['col-start-1 row-start-1 inline-flex items-center gap-3 transition-opacity duration-160 ease-out', busy ? 'opacity-0' : ''].join(' ')}>${label}</span><span aria-hidden="true" class=${['col-start-1 row-start-1 inline-flex items-center transition-opacity duration-160 ease-out', !busy ? 'opacity-0' : ''].join(' ')}><span class=${['ds-auth-spin size-5 rounded-full border-2 border-current border-t-transparent', !busy ? '[animation-play-state:paused]' : ''].join(' ')}></span></span></span>`
	}

	render() {
		const c = this.content ?? authContent
		const m = this.mode === 'sign-in' ? c.signIn : c.signUp
		const id = this.uid
		const link = 'rounded-ds-sm underline decoration-transparent decoration-from-font underline-offset-4 transition-[text-decoration-color] duration-160 ease-out pointer-fine:hover:decoration-current'
		const icon = this.querySelector('[slot="provider-icon"]') ? html`<span class="grid size-5 flex-none place-items-center [&_svg]:size-5"><slot name="provider-icon"></slot></span>` : nothing
		return html`<section data-ds="auth-form" aria-labelledby=${`${id}-title`} class="mx-auto flex w-full max-w-[calc(var(--ds-layout-auth)+2*var(--ds-layout-gutter))] flex-col items-center px-(--ds-layout-gutter) text-center text-fg"><h1 id=${`${id}-title`} class="type-title md:whitespace-nowrap">${m.title}</h1>${m.lead ? html`<p class="mt-3 type-body text-balance text-fg-soft">${m.lead}</p>` : nothing}<spyglass-button variant="secondary" size="form" class="mt-8 w-full" aria-disabled=${this.busy ? 'true' : nothing} @click=${() => this.go('provider')}>${this.labels(this.busy === 'provider', html`${icon}${c.provider}`)}</spyglass-button><p class="my-4 flex w-full items-center gap-4 type-ui text-fg-muted before:h-px before:flex-1 before:bg-edge after:h-px after:flex-1 after:bg-edge">${c.or}</p><form novalidate @submit=${(e: Event) => this.submit(e)} class="flex w-full flex-col text-left"><div class="mb-2 flex justify-between gap-4 type-ui"><label for=${`${id}-email`} class="font-medium">${c.email}</label><span id=${`${id}-error`} role="alert" class="text-fg">${this.error}</span></div><input id=${`${id}-email`} type="email" inputmode="email" autocomplete="email" autocapitalize="none" autocorrect="off" spellcheck="false" enterkeyhint="go" placeholder=${c.placeholder} .value=${live(this.email)} aria-invalid=${this.error ? 'true' : nothing} aria-describedby=${this.error ? `${id}-error` : nothing} @input=${(e: Event) => { this.email = (e.target as HTMLInputElement).value; if (this.error) this.error = '' }} class="mb-3 h-control-form w-full appearance-none rounded-control bg-surface-subtle px-4 type-body text-fg shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-edge)] transition-[box-shadow] duration-160 ease-out placeholder:text-fg-muted focus-visible:-outline-offset-1 aria-invalid:shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-white)]"><spyglass-button type="submit" size="form" class="w-full" aria-disabled=${this.busy ? 'true' : nothing}>${this.labels(this.busy === 'email', m.submit)}</spyglass-button></form><p role="status" class="sr-only">${this.busy ? c.working : ''}</p><p class="mt-5 type-ui text-balance text-fg-faint">${c.legal.before}<a href=${c.legal.terms.href} class=${`text-fg-soft ${link}`}>${c.legal.terms.label}</a>${c.legal.between}<a href=${c.legal.privacy.href} class=${`text-fg-soft ${link}`}>${c.legal.privacy.label}</a>${c.legal.after}</p><p class="mt-5 type-ui text-fg-muted">${m.other.ask} <a href=${m.other.href} class=${`relative py-3 font-medium text-fg ${link}`}>${m.other.label}</a></p></section>`
	}
}

define('auth-form', AuthForm)
elements/components/site/auth-form.css
.ds-auth-spin { animation: ds-auth-spin 800ms linear infinite; }
@keyframes ds-auth-spin { to { transform: rotate(1turn); } }
@keyframes ds-auth-breathe { 50% { opacity: 0.5; } }
@media (prefers-reduced-motion: reduce) { .ds-auth-spin { animation: ds-auth-breathe 2s var(--ds-easing-in-out) infinite; } }

Reference: Site pages/Auth/AuthForm and Auth.module.css: title h4 32/36, h3 40/44 from 768, at 450; lead --text-2 12px under; controls 48px (--control-m) with 16/24 labels; the or rule 14/20 --text-3 between --line hairlines, 16px above and below; the field on --raised with an inset --line ring, 8px corner; legal 14/20 --text-off with --text-2 links; the spinner 20px, a 2px ring turning every 800ms.