Brand

Text swap

A value that changes in place: the old one rises 12px and fades out while the new one rises in from below, in one clipped grid cell, with an optional muted unit and a small badge. Sentences, its companion, keeps each sentence of a line whole on a phone.

Install

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

npx spyglass-ds add text-swap
<script type="module" src="/spyglass-ds/elements/text-swap.js"></script>
A price and its unit

$20/month

Sentences

Ask in plain words. Acme's library answers with the ads that fit. Every one ranked by how long it ran.

Usage

A price that follows the billing period, a plan name an estimator picks, a sort label; a hero line that should break between sentences on a phone (Sentences).

Never

  • For text people are reading: only short values that change on a choice
  • Swapping on a timer: it answers a choice
  • Moving with reduced motion: the value changes at once

Props

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

<TextSwap>

PropTypeDefault
textstring
unitstring

Small muted text after the value ("/month").

tagstring

A small badge after the value ("Save 20%").

classNamestring

<Sentences>

PropTypeDefault
textstring
classNamestring

Examples

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

react/examples/text-swap/Price.tsx
'use client'
import { useState } from 'react'
import { TextSwap } from '@/react/components/ui/TextSwap'
// A plan's price that swaps with the billing period: the amount and the unit each rise out as the new ones rise in.

export default function Price() {
  const [yearly, setYearly] = useState(false)
  const pick = 'h-8 rounded-ds-sm px-3 type-ui text-fg-muted transition-[background-color,color] duration-160 ease-standard aria-pressed:bg-surface-subtle aria-pressed:text-fg'
  return (
    <div className="flex flex-col items-start gap-8">
      <div role="group" aria-label="Billing" className="flex gap-1 rounded-control bg-surface-raised p-1">
        <button type="button" aria-pressed={!yearly} onClick={() => setYearly(false)} className={pick}>Monthly</button>
        <button type="button" aria-pressed={yearly} onClick={() => setYearly(true)} className={pick}>Yearly</button>
      </div>
      <p className="flex flex-wrap items-baseline gap-x-2 text-fg">
        <TextSwap className="font-heading text-heading-3" text={yearly ? '$16' : '$20'} />
        <TextSwap className="type-ui text-fg-muted" text={yearly ? '/month, billed yearly' : '/month'} tag={yearly ? 'Save 20%' : undefined} />
      </p>
    </div>
  )
}
elements/examples/text-swap/Price.html
<!-- A plan's price that swaps with the billing period: the amount and the unit each rise out as the new ones rise in. -->
<div class="flex flex-col items-start gap-8">
  <div role="group" aria-label="Billing" class="flex gap-1 rounded-control bg-surface-raised p-1">
    <button type="button" aria-pressed="true" data-period="monthly" class="h-8 rounded-ds-sm px-3 type-ui text-fg-muted transition-[background-color,color] duration-160 ease-standard aria-pressed:bg-surface-subtle aria-pressed:text-fg">Monthly</button>
    <button type="button" aria-pressed="false" data-period="yearly" class="h-8 rounded-ds-sm px-3 type-ui text-fg-muted transition-[background-color,color] duration-160 ease-standard aria-pressed:bg-surface-subtle aria-pressed:text-fg">Yearly</button>
  </div>
  <p class="flex flex-wrap items-baseline gap-x-2 text-fg">
    <spyglass-text-swap id="price-amount" class="font-heading text-heading-3" text="$20"></spyglass-text-swap>
    <spyglass-text-swap id="price-unit" class="type-ui text-fg-muted" text="/month"></spyglass-text-swap>
  </p>
</div>
<script type="module">
  const amount = document.getElementById('price-amount')
  const unit = document.getElementById('price-unit')
  for (const b of document.querySelectorAll('[data-period]')) b.addEventListener('click', () => {
    const yearly = b.dataset.period === 'yearly'
    for (const o of document.querySelectorAll('[data-period]')) o.setAttribute('aria-pressed', String(o === b))
    amount.text = yearly ? '$16' : '$20'
    unit.text = yearly ? '/month, billed yearly' : '/month'
    unit.tag = yearly ? 'Save 20%' : undefined
  })
</script>
react/examples/text-swap/Lines.tsx
import { Sentences } from '@/react/components/ui/Sentences'
// Sentences: on a phone each sentence wraps as a whole; wider, the copy reads as one paragraph.

export default function Lines() {
  return (
    <p className="max-w-xl type-body-lg text-fg-soft">
      <Sentences text="Ask in plain words. Acme's library answers with the ads that fit. Every one ranked by how long it ran." />
    </p>
  )
}
elements/examples/text-swap/Lines.html
<!-- Sentences: on a phone each sentence wraps as a whole; wider, the copy reads as one paragraph. -->
<p class="max-w-xl type-body-lg text-fg-soft">
  <spyglass-sentences text="Ask in plain words. Acme's library answers with the ads that fit. Every one ranked by how long it ran."></spyglass-sentences>
</p>

Source

react/components/ui/TextSwap.tsx
'use client'
import { useEffect, useRef, useState } from 'react'
import { prefersReduced, SWAP_CSS, swapLeaveMs, swapTo, type SwapItem } from '@/lib/text-swap'
import { cn } from '@/react/lib/cn'

// The site's animated value swap (pages/Pricing/Swap): a price, a plan name or a sort label that changes in place. The
// old value rises 12px and fades out while the new one rises in from below, in one grid cell clipped 4px out, over
// 480ms on the loop curve; a value that changes again mid-swap takes over from where it is. `unit` follows the value in
// small muted type ("/month"), `tag` as a small White badge ("Save 20%", the plan badge's look). The type comes from the page (`className`). With
// reduced motion the value changes at once. The leaving value is hidden from assistive tech.
export interface TextSwapProps {
  text: string
  /** Small muted text after the value ("/month"). */
  unit?: string
  /** A small badge after the value ("Save 20%"). */
  tag?: string
  className?: string
}

export function TextSwap({ text, unit, tag, className }: TextSwapProps) {
  const ref = useRef<HTMLSpanElement>(null)
  const [items, setItems] = useState<SwapItem[]>([{ id: 0, text, unit, tag, state: 'in' }])
  const [asked, setAsked] = useState({ text, unit, tag })
  const dropAt = useRef(new Map<number, number>())

  if (asked.text !== text || asked.unit !== unit || asked.tag !== tag) {
    setAsked({ text, unit, tag })
    setItems(swapTo(items, { text, unit, tag }, prefersReduced()))
  }

  useEffect(() => {
    let frame = 0
    if (items.some((i) => i.state === 'enter')) {
      frame = requestAnimationFrame(() => {
        frame = requestAnimationFrame(() => setItems((now) => now.map((i) => (i.state === 'enter' ? { ...i, state: 'in' as const } : i))))
      })
    }
    const now = performance.now()
    const leaving = items.filter((i) => i.state === 'out')
    const live = new Set(leaving.map((i) => i.id))
    for (const id of dropAt.current.keys()) if (!live.has(id)) dropAt.current.delete(id)
    const ms = ref.current ? swapLeaveMs(ref.current) : 480
    for (const i of leaving) if (!dropAt.current.has(i.id)) dropAt.current.set(i.id, now + ms)
    let timer = 0
    if (leaving.length) {
      const due = Math.min(...leaving.map((i) => dropAt.current.get(i.id) ?? now))
      timer = window.setTimeout(() => {
        const t = performance.now()
        const done = new Set(leaving.filter((i) => (dropAt.current.get(i.id) ?? 0) <= t).map((i) => i.id))
        setItems((cur) => cur.filter((c) => !done.has(c.id)))
      }, Math.max(0, due - now))
    }
    return () => {
      cancelAnimationFrame(frame)
      clearTimeout(timer)
    }
  }, [items])

  return (
    <span ref={ref} data-ds="text-swap" className={cn('inline-grid overflow-clip align-top [overflow-clip-margin:var(--ds-space-xs)]', className)}>
      <style href="ds-text-swap" precedence="ds">{SWAP_CSS}</style>
      {items.map((item) => (
        <span key={item.id} className="ds-swap-item" data-state={item.state} aria-hidden={item.state === 'out' || undefined}>
          {item.text}
          {item.unit ? <span className="ms-2 font-text text-ui/5 text-fg-muted">{item.unit}</span> : null}
          {item.tag ? <span className="relative ms-2 inline-block rounded-ds-sm bg-action-primary px-2 py-1 font-text text-caption/5 font-medium whitespace-nowrap text-action-primary-fg">{item.tag}</span> : null}
        </span>
      ))}
    </span>
  )
}

export default TextSwap
react/components/ui/Sentences.tsx
import { Fragment } from 'react'
import { cn } from '@/react/lib/cn'

// The site's sentence keeper (ui/Sentences): a line of copy split after each sentence, so below 768 each sentence wraps
// as a whole (inline-block) instead of leaving one word alone on a line; wider, it reads as plain text.
export interface SentencesProps {
  text: string
  className?: string
}

export function Sentences({ text, className }: SentencesProps) {
  const parts = text.split(/(?<=[.!?])\s+/)
  return (
    <span data-ds="sentences" className={cn('contents', className)}>
      {parts.map((part, i) => (
        <Fragment key={`${i}-${part}`}>
          {i > 0 ? ' ' : null}
          <span className="max-md:inline-block">{part}</span>
        </Fragment>
      ))}
    </span>
  )
}

export default Sentences
lib/text-swap.ts
// The site's value swap (pages/Pricing/Swap): when the text changes, the old value rises 12px and fades out while the
// new one rises in from 12px below, both in one grid cell, over --ds-duration-slow on the loop curve. Both flavors keep
// their list of values with this, and share the CSS. With reduced motion the new value replaces the old at once.
export type SwapState = 'enter' | 'in' | 'out'
export interface SwapValue { text: string, unit?: string, tag?: string }
export interface SwapItem extends SwapValue { id: number, state: SwapState }

const same = (a: SwapValue | undefined, b: SwapValue) => !!a && a.text === b.text && a.unit === b.unit && a.tag === b.tag

/** The list after the value changes to `next`: the shown value leaves and `next` enters (or replaces it, reduced). */
export function swapTo(items: SwapItem[], next: SwapValue, reduced: boolean): SwapItem[] {
	if (same(items.find((i) => i.state !== 'out'), next)) return items
	const id = items.reduce((max, i) => Math.max(max, i.id), 0) + 1
	if (reduced) return [{ id, ...next, state: 'in' }]
	return [...items.map((i) => (i.state === 'out' ? i : { ...i, state: 'out' as const })), { id, ...next, state: 'enter' as const }]
}

export const prefersReduced = () => !!globalThis.matchMedia && globalThis.matchMedia('(prefers-reduced-motion: reduce)').matches

/** How long a leaving value stays: the swap's duration token, in ms. */
export function swapLeaveMs(el: Element): number {
	const v = getComputedStyle(el).getPropertyValue('--ds-duration-slow').trim()
	const n = parseFloat(v)
	return Number.isFinite(n) && n > 0 ? n * (v.endsWith('ms') ? 1 : 1000) : 480
}

export const SWAP_CSS = `
.ds-swap-item { grid-area: 1 / 1; white-space: nowrap; transition: opacity var(--ds-duration-slow) var(--ds-easing-loop), translate var(--ds-duration-slow) var(--ds-easing-loop); }
.ds-swap-item[data-state="enter"] { opacity: 0; translate: 0 var(--ds-space-md); transition: none; }
.ds-swap-item[data-state="out"] { opacity: 0; translate: 0 calc(-1 * var(--ds-space-md)); }
@media (prefers-reduced-motion: reduce) { .ds-swap-item { transition: none; } }
`
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/ui/text-swap.ts
import { html, nothing, unsafeCSS, type PropertyValues } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import { prefersReduced, SWAP_CSS, swapLeaveMs, swapTo, type SwapItem } from '@/lib/text-swap'
import styles from 'virtual:tw'

// TextSwap.tsx as <spyglass-text-swap>: a value that changes in place, the old one rising out as the new one rises in
// (480ms, the loop curve; at once with reduced motion). `text`, `unit` (small muted text after it) and `tag` (a badge).
// The type comes from the page: classes on the host reach the value by inheritance.

/**
 * @summary A value that swaps in place when it changes.
 */
export class TextSwap extends DsElement {
	static styles = [DsElement.styles, styles, unsafeCSS(SWAP_CSS)]
	static properties = { text: {}, unit: {}, tag: {}, items: { state: true } }
	text = ''
	/** Small muted text after the value ("/month"). */
	unit?: string
	/** A small badge after the value ("Save 20%"). */
	tag?: string
	private items: SwapItem[] = []
	private dropAt = new Map<number, number>()
	private frame = 0
	private timer = 0

	protected willUpdate(changed: PropertyValues) {
		const next = { text: this.text ?? '', unit: this.unit || undefined, tag: this.tag || undefined }
		if (!this.items.length) this.items = [{ id: 0, ...next, state: 'in' }]
		else if (changed.has('text') || changed.has('unit') || changed.has('tag')) this.items = swapTo(this.items, next, prefersReduced())
	}

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (!changed.has('items')) return
		cancelAnimationFrame(this.frame)
		clearTimeout(this.timer)
		if (this.items.some((i) => i.state === 'enter')) {
			this.frame = requestAnimationFrame(() => {
				this.frame = requestAnimationFrame(() => (this.items = this.items.map((i) => (i.state === 'enter' ? { ...i, state: 'in' as const } : i))))
			})
		}
		const now = performance.now()
		const leaving = this.items.filter((i) => i.state === 'out')
		const live = new Set(leaving.map((i) => i.id))
		for (const id of this.dropAt.keys()) if (!live.has(id)) this.dropAt.delete(id)
		const ms = swapLeaveMs(this)
		for (const i of leaving) if (!this.dropAt.has(i.id)) this.dropAt.set(i.id, now + ms)
		if (leaving.length) {
			const due = Math.min(...leaving.map((i) => this.dropAt.get(i.id) ?? now))
			this.timer = window.setTimeout(() => {
				const t = performance.now()
				const done = new Set(leaving.filter((i) => (this.dropAt.get(i.id) ?? 0) <= t).map((i) => i.id))
				this.items = this.items.filter((c) => !done.has(c.id))
			}, Math.max(0, due - now))
		}
	}

	disconnectedCallback() {
		super.disconnectedCallback()
		cancelAnimationFrame(this.frame)
		clearTimeout(this.timer)
	}

	render() {
		return html`<span data-ds="text-swap" class="inline-grid overflow-clip align-top [overflow-clip-margin:var(--ds-space-xs)]">${this.items.map((item) => html`<span class="ds-swap-item" data-state=${item.state} aria-hidden=${item.state === 'out' ? 'true' : nothing}>${item.text}${item.unit ? html`<span class="ms-2 font-text text-ui/5 text-fg-muted">${item.unit}</span>` : nothing}${item.tag ? html`<span class="relative ms-2 inline-block rounded-ds-sm bg-action-primary px-2 py-1 font-text text-caption/5 font-medium whitespace-nowrap text-action-primary-fg">${item.tag}</span>` : nothing}</span>`)}</span>`
	}
}

define('text-swap', TextSwap)
elements/components/ui/sentences.ts
import { html } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'

// Sentences.tsx as <spyglass-sentences>: `text` split after each sentence, so below 768 each sentence wraps whole.

/**
 * @summary Copy that keeps each sentence whole on a phone.
 */
export class Sentences extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = { text: {} }
	text = ''

	render() {
		const parts = (this.text ?? '').split(/(?<=[.!?])\s+/)
		return html`<span data-ds="sentences" class="contents">${parts.map((part, i) => html`${i > 0 ? ' ' : ''}<span class="max-md:inline-block">${part}</span>`)}</span>`
	}
}

define('sentences', Sentences)

Reference: Site pages/Pricing/Swap (Pricing.module.css .swap, .swapItem, .swapUnit; the tag in the plan badge's look, .badge: White, Black caption 4px by 8px, the small corner): inline-grid, clip margin 4px, 12px rise over --dur-loop-badge on --ease-loop (480ms, the brand's slow step); ui/Sentences (inline-block sentences below 768).