Components

Input Group

A field with an icon, a prefix, a unit or a small button inside its hairline, drawn and sized as the input is. The hairline turns White while the field has focus.

Install

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

npx spyglass-ds add input-group
<script type="module" src="/spyglass-ds/elements/input-group.js"></script>
Icons, text and buttons
spyglass.so/b/
$per month
Sizes
spyglass.so/b/

Usage

Fields that read better with their context attached: a search icon, a link's fixed start, a currency and its period, an invite button beside an email.

Never

  • A primary search: use the search bar
  • Icons that do nothing at the end of a field
  • More than one button inside a field

Props

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

<InputGroup>

PropTypeDefault
startReactNode

What sits before the text: an icon, a prefix.

endReactNode

What sits after the text: a unit, a count, a small button.

sizeInputGroupSize

sm (32px), md (40px) or lg (48px).

'md'
invalidboolean

A red hairline (with the message beside it).

Examples

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

react/examples/input-group/Addons.tsx
import { Search } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { InputGroup } from '@/react/components/ui/InputGroup'
// An icon, a prefix, a unit and a button, each inside the field's hairline.

export default function Addons() {
  return (
    <div className="flex w-96 max-w-full flex-col gap-4">
      <InputGroup aria-label="Search boards" placeholder="Search boards" start={<Search size={16} strokeWidth={1.5} aria-hidden="true" />} />
      <InputGroup aria-label="Board link" defaultValue="acme-hooks" start="spyglass.so/b/" />
      <InputGroup aria-label="Monthly budget" type="number" defaultValue="20" start="$" end="per month" />
      <InputGroup aria-label="Invite by email" type="email" placeholder="name@acme.com" end={<Button variant="secondary" size="sm">Invite</Button>} />
    </div>
  )
}
elements/examples/input-group/Addons.html
<!-- An icon, a prefix, a unit and a button, each inside the field's hairline. -->
<div class="flex w-96 max-w-full flex-col gap-4">
  <spyglass-input-group aria-label="Search boards" placeholder="Search boards"><i data-lucide="search" data-size="16" data-stroke-width="1.5" slot="start" aria-hidden="true"></i></spyglass-input-group>
  <spyglass-input-group aria-label="Board link" value="acme-hooks"><span slot="start">spyglass.so/b/</span></spyglass-input-group>
  <spyglass-input-group aria-label="Monthly budget" type="number" value="20"><span slot="start">$</span><span slot="end">per month</span></spyglass-input-group>
  <spyglass-input-group aria-label="Invite by email" type="email" placeholder="name@acme.com"><spyglass-button slot="end" variant="secondary" size="sm">Invite</spyglass-button></spyglass-input-group>
</div>
react/examples/input-group/Sizes.tsx
import { Search } from 'lucide-react'
import { InputGroup } from '@/react/components/ui/InputGroup'
// The three sizes, matching the input's, and one that says what is wrong.

export default function Sizes() {
  return (
    <div className="flex w-80 max-w-full flex-col gap-3">
      <InputGroup size="sm" aria-label="Search, small" placeholder="Search" start={<Search size={16} strokeWidth={1.5} aria-hidden="true" />} />
      <InputGroup size="md" aria-label="Search, medium" placeholder="Search" start={<Search size={16} strokeWidth={1.5} aria-hidden="true" />} />
      <InputGroup size="lg" aria-label="Search, large" placeholder="Search" start={<Search size={16} strokeWidth={1.5} aria-hidden="true" />} />
      <InputGroup aria-label="Board link, taken" defaultValue="acme" start="spyglass.so/b/" invalid />
    </div>
  )
}
elements/examples/input-group/Sizes.html
<!-- The three sizes, matching the input's, and one that says what is wrong. -->
<div class="flex w-80 max-w-full flex-col gap-3">
  <spyglass-input-group size="sm" aria-label="Search, small" placeholder="Search"><i data-lucide="search" data-size="16" data-stroke-width="1.5" slot="start" aria-hidden="true"></i></spyglass-input-group>
  <spyglass-input-group size="md" aria-label="Search, medium" placeholder="Search"><i data-lucide="search" data-size="16" data-stroke-width="1.5" slot="start" aria-hidden="true"></i></spyglass-input-group>
  <spyglass-input-group size="lg" aria-label="Search, large" placeholder="Search"><i data-lucide="search" data-size="16" data-stroke-width="1.5" slot="start" aria-hidden="true"></i></spyglass-input-group>
  <spyglass-input-group aria-label="Board link, taken" value="acme" invalid><span slot="start">spyglass.so/b/</span></spyglass-input-group>
</div>

Source

react/components/ui/InputGroup.tsx
import type { InputHTMLAttributes, ReactNode, Ref } from 'react'
import { cn } from '@/react/lib/cn'

// A field with something at its start or end inside the same hairline: an icon, a unit or a prefix in the muted gray,
// or a small button. It is drawn as the Input is (a #666666 hairline on Black that turns White while the field has
// focus, DM Sans at 14px, 16px on phones, the brand corner) and sized as it is: sm 32px, md 40px, lg 48px. A button in
// `end` sits 4px from the edge (use a ghost or secondary sm button in md, md in lg). `invalid` turns the hairline red.
// `className` lands on the group; every other prop on the <input> (value and onChange as React's own).
export type InputGroupSize = 'sm' | 'md' | 'lg'

const SIZES: Record<InputGroupSize, string> = { sm: 'h-control-sm gap-1.5 px-2.5', md: 'h-control-md gap-2 px-3', lg: 'h-control-lg gap-2 px-4' }
// A button at the end comes 4px from the edge, whatever the group's padding.
const END: Record<InputGroupSize, string> = { sm: 'has-[button]:-mr-1.5', md: 'has-[button]:-mr-2', lg: 'has-[button]:-mr-3' }

export interface InputGroupProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> {
  /** What sits before the text: an icon, a prefix. */
  start?: ReactNode
  /** What sits after the text: a unit, a count, a small button. */
  end?: ReactNode
  /** sm (32px), md (40px) or lg (48px). */
  size?: InputGroupSize
  /** A red hairline (with the message beside it). */
  invalid?: boolean
  ref?: Ref<HTMLInputElement>
}

export function InputGroup({ start, end, size = 'md', invalid, className, ...rest }: InputGroupProps) {
  return (
    <div
      data-ds="input-group"
      data-invalid={invalid || undefined}
      className={cn('flex w-full min-w-0 items-center rounded-control border border-edge-strong bg-surface-subtle text-fg transition-[border-color] duration-160 ease-standard hover:not-has-[input:disabled]:border-action-secondary-edge-hover has-[input:focus-visible]:border-edge-focus data-invalid:border-action-danger has-[input:disabled]:cursor-not-allowed', SIZES[size], className)}
    >
      {start && <span className="flex shrink-0 items-center gap-1.5 type-ui text-fg-muted">{start}</span>}
      <input {...rest} aria-invalid={invalid || undefined} className="h-full w-full min-w-0 flex-1 bg-transparent type-ui text-fg outline-none placeholder:text-fg-muted disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input pointer-coarse:text-input" />
      {end && <span className={cn('flex shrink-0 items-center gap-1.5 type-ui text-fg-muted', END[size])}>{end}</span>}
    </div>
  )
}

export default InputGroup
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/input-group.ts
import { html, LitElement, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { live } from 'lit/directives/live.js'
import { DsFormElement, define, HostLayoutController } from '@/elements/lib/element'
import styles from 'virtual:tw'

// InputGroup.tsx as <spyglass-input-group>: a field with something at its start or end inside the same hairline: an
// icon, a unit or a prefix in the muted gray (slot="start", slot="end"), or a small button. Drawn and sized as the
// input is (sm 32px, md 40px, lg 48px); the hairline turns White while the field has focus and red when `invalid`.
// Form-associated (its `name` and `value` go with its form); the value is `value` with the native `input` and `change`
// events, and Enter submits its form. aria-label and aria-description pass to the inner input.

const SIZES = { sm: 'h-control-sm gap-1.5 px-2.5', md: 'h-control-md gap-2 px-3', lg: 'h-control-lg gap-2 px-4' } as const
// A button at the end comes 4px from the edge, whatever the group's padding. The slot is in the box, so the button
// it holds is read from the host.
const END = { sm: '-mr-1.5', md: '-mr-2', lg: '-mr-3' } as const
export type InputGroupSize = keyof typeof SIZES

/**
 * @summary A field with an icon, a unit or a button inside its hairline.
 * @slot start - What sits before the text: an icon, a prefix.
 * @slot end - What sits after the text: a unit, a count, a small button.
 * @fires input - On every keystroke (read `value`).
 * @fires change - When the value is committed.
 */
export class InputGroup extends DsFormElement {
	static styles = [DsFormElement.styles, styles]
	static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
	static dsField = true
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="input-group"]'))
	static properties = {
		value: {},
		type: {},
		name: {},
		placeholder: {},
		autocomplete: {},
		size: { reflect: true },
		disabled: { type: Boolean, reflect: true },
		readonly: { type: Boolean },
		required: { type: Boolean },
		invalid: { type: Boolean, reflect: true },
		label: { attribute: 'aria-label' },
		description: { attribute: 'aria-description' },
	}

	value = ''
	type = 'text'
	name?: string
	placeholder?: string
	autocomplete?: string
	/** sm (32px), md (40px) or lg (48px). */
	size: InputGroupSize = 'md'
	disabled = false
	readonly = false
	required = false
	/** A red hairline (with the message beside it). */
	invalid = false
	/** The name for assistive tech, passed to the inner input. */
	label?: string
	/** The description or error, passed to the inner input. */
	description?: string

	// The start and end slots are drawn only when they have content, so the element follows its children: content that
	// lands after the first render (a parser still streaming, a framework filling it) gets its addon box.
	private observer = new MutationObserver(() => this.requestUpdate())
	connectedCallback() {
		super.connectedCallback()
		if (!this.value && this.getAttribute('value')) this.value = this.getAttribute('value')!
		this.observer.observe(this, { childList: true })
		this.requestUpdate()
	}
	disconnectedCallback() {
		super.disconnectedCallback()
		this.observer.disconnect()
	}
	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (changed.has('value')) this.internals.setFormValue(this.value)
	}
	protected validityControl() {
		return this.renderRoot.querySelector<HTMLInputElement>('input')
	}
	formResetCallback() {
		this.value = this.getAttribute('value') ?? ''
	}
	private onInput(event: Event) {
		this.value = (event.target as HTMLInputElement).value
	}
	private onKeyDown(event: KeyboardEvent) {
		if (event.key === 'Enter' && !event.isComposing && this.form) {
			event.preventDefault()
			this.form.requestSubmit()
		}
	}
	private onChange() {
		this.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
	}

	render() {
		const size = SIZES[this.size] ? this.size : 'md'
		const button = !!this.querySelector(':scope > [slot="end"] button, :scope > button[slot="end"], :scope > [slot="end"][data-ds="button"]')
		const box = ['flex w-full min-w-0 items-center rounded-control border border-edge-strong bg-surface-subtle text-fg transition-[border-color] duration-160 ease-standard hover:not-has-[input:disabled]:border-action-secondary-edge-hover has-[input:focus-visible]:border-edge-focus data-invalid:border-action-danger has-[input:disabled]:cursor-not-allowed', SIZES[size]].join(' ')
		return html`<div data-ds="input-group" data-invalid=${ifDefined(this.invalid ? 'true' : undefined)} class=${box}>${this.hasSlot('start') ? html`<span class="flex shrink-0 items-center gap-1.5 type-ui text-fg-muted"><slot name="start"></slot></span>` : nothing}<input .value=${live(this.value)} type=${this.type} name=${ifDefined(this.name)} placeholder=${ifDefined(this.placeholder)} autocomplete=${ifDefined(this.autocomplete as never)} ?disabled=${this.inactive} ?readonly=${this.readonly} ?required=${this.required} aria-invalid=${ifDefined(this.invalid ? 'true' : undefined)} aria-label=${ifDefined(this.label)} aria-description=${ifDefined(this.description)} class="h-full w-full min-w-0 flex-1 bg-transparent type-ui text-fg outline-none placeholder:text-fg-muted disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input pointer-coarse:text-input" @input=${this.onInput} @change=${this.onChange} @keydown=${this.onKeyDown}>${this.hasSlot('end') ? html`<span class=${['flex shrink-0 items-center gap-1.5 type-ui text-fg-muted', button ? END[size] : ''].join(' ')}><slot name="end"></slot></span>` : nothing}</div>`
	}
}

define('input-group', InputGroup)

Reference: Derived from the brand guidelines (no grouped field in the brand assets): the input's hairline, fill and corner, and the search bar's button set inside the field.