Rename a project
The project settings sheet has one Input for the name, prefilled. The hint says who will see the change.
Components / InputsStable
Takes one line of text, such as a name, an email address or a search term, with a label that stays visible.
Everyone in the workspace can see this name.
'use client'
import { useEffect, useId, useImperativeHandle, useRef, useState, type InputHTMLAttributes, type ReactNode, type Ref, type RefObject } from 'react'
import { Note } from './Note'
// Nacre Input: one line of text with a visible label, an optional hint and an error. invalid marks the field without a
// message (a group or summary owns it); error is the message and implies invalid. React plus Tailwind classes only;
// needs nacre-theme.css.
// Motion: the border colour changes quick 160 out. A hint or error rises 4 px into place and fades in, quick 160; a new
// error also nudges the field sideways once (240). The floating label shrinks to the top edge on focus or when filled
// (quick 160 out). The smooth caret glides to each new position (quick 160 out) instead of jumping; the native caret is
// hidden while it shows. The strength meter fills segment by segment (base 240). Reduced motion or an ancestor with
// [data-nacre-motion="off"]: the native caret, and nothing moves.
export type InputSize = 'sm' | 'md' | 'lg'
export type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
label: string
hideLabel?: boolean
/** The label sits inside the field and moves to its top edge on focus or once filled. */
floatingLabel?: boolean
hint?: string
invalid?: boolean
error?: string
/** A confirmation message (field passed its check). Draws a soft success outline and a check; error wins when both are set. */
success?: string
/** Keep one line of space for the hint, error or success line even when empty, so the layout never shifts. */
reserveNote?: boolean
size?: InputSize
leading?: ReactNode
trailing?: ReactNode
/** A caret that glides between positions. Falls back to the native caret with reduced motion. Default true. */
smoothCaret?: boolean
/** type="password" only: a four-step strength meter under the field, read out politely. */
strength?: boolean
/** type="password" only: a Show or Hide toggle at the end of the field. */
reveal?: boolean
ref?: Ref<HTMLInputElement>
}
const heights: Record<InputSize, string> = { sm: 'h-9 rounded-sm px-3 text-body', md: 'h-11 rounded-md px-3.5 text-body', lg: 'h-12 rounded-md px-4 text-body-lg' }
const floatingHeights: Record<InputSize, string> = { sm: 'h-12 rounded-sm px-3 text-body', md: 'h-12 rounded-md px-3.5 text-body', lg: 'h-14 rounded-md px-4 text-body-lg' }
const CARET_MS = 160
const STRENGTH = ['Too short', 'Weak', 'Fair', 'Good', 'Strong'] as const
const meterTone = ['bg-error-strong', 'bg-error-strong', 'bg-warning-strong', 'bg-success-strong', 'bg-success-strong'] as const
/** Reduced motion, or an ancestor that switched motion off, means no movement. */
function motionOk(el: Element): boolean {
return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}
/** 0 (shorter than 8) to 4: one point for 8+, one each for 12+ and 16+, one for three kinds of character. */
export function passwordStrength(value: string): 0 | 1 | 2 | 3 | 4 {
if (value.length < 8) return 0
let score = 1
if (value.length >= 12) score++
if (value.length >= 16) score++
if ([/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((r) => r.test(value)).length >= 3) score++
return Math.min(score, 4) as 0 | 1 | 2 | 3 | 4
}
/**
* A caret drawn by the field instead of the browser, so it can glide. The returned refs go on two spans inside a
* position: relative box that holds the input: `caret` (the 2 px bar) and `mirror` (an invisible copy of the text
* before the caret, in the input's font, that measures how far in the caret sits). Each move is a transform; a move
* that arrives mid-flight starts from where the bar is drawn now. It hides while text is selected, and hands back to
* the native caret for right-to-left text, unsupported types, reduced motion and Motion off.
*/
export function useSmoothCaret(input: RefObject<HTMLInputElement | null>, on = true) {
const caret = useRef<HTMLSpanElement>(null)
const mirror = useRef<HTMLSpanElement>(null)
useEffect(() => {
const el = input.current
const c = caret.current
const m = mirror.current
if (!on || !el || !c || !m) return
let frame = 0
let shown = false
let move: Animation | undefined
let blink: Animation | undefined
const usable = () =>
document.activeElement === el && /^(text|search|url|tel|password)$/.test(el.type) && getComputedStyle(el).direction === 'ltr' && motionOk(el)
const hide = () => {
shown = false
blink?.cancel()
move?.cancel()
c.style.opacity = '0'
el.style.caretColor = ''
}
const place = (jump: boolean) => {
frame = 0
if (!usable()) return hide()
const start = el.selectionStart ?? 0
if (start !== (el.selectionEnd ?? 0)) return hide()
const cs = getComputedStyle(el)
m.style.font = cs.font
m.style.letterSpacing = cs.letterSpacing
m.textContent = el.type === 'password' ? '•'.repeat(start) : el.value.slice(0, start)
const padL = parseFloat(cs.paddingLeft) || 0
const padR = parseFloat(cs.paddingRight) || 0
const inner = Math.min(Math.max((start ? m.getBoundingClientRect().width : 0) - el.scrollLeft, 0), el.clientWidth - padL - padR)
const fontPx = parseFloat(cs.fontSize) || 14
const h = Math.round(fontPx * 1.25)
const padT = parseFloat(cs.paddingTop) || 0
const padB = parseFloat(cs.paddingBottom) || 0
// The 2 px bar straddles the gap between two characters, where the native caret sits.
const x = Math.round((el.offsetLeft + el.clientLeft + padL + inner - 1) * 2) / 2
const y = Math.round(el.offsetTop + el.clientTop + padT + (el.clientHeight - padT - padB - h) / 2)
const to = `translate(${x}px, ${y}px)`
const from = move?.playState === 'running' ? getComputedStyle(c).transform : c.style.transform
move?.cancel()
c.style.height = `${h}px`
c.style.transform = to
if (!jump && shown && from && from !== 'none' && from !== to) {
const easing = getComputedStyle(el).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
move = c.animate([{ transform: from }, { transform: to }], { duration: CARET_MS, easing })
}
if (!shown) {
shown = true
c.style.opacity = '1'
el.style.caretColor = 'transparent'
}
// Solid while moving, then the usual blink.
blink?.cancel()
blink = c.animate([{ opacity: 1 }, { opacity: 1, offset: 0.5 }, { opacity: 0, offset: 0.5 }, { opacity: 0 }], { duration: 1060, delay: 530, iterations: Infinity })
}
const schedule = (jump: boolean) => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(() => place(jump))
}
const onFocus = () => schedule(true)
const onMove = () => { if (document.activeElement === el) schedule(false) }
const onJump = () => { if (document.activeElement === el) schedule(true) }
const ro = new ResizeObserver(onJump)
el.addEventListener('focus', onFocus)
el.addEventListener('blur', hide)
el.addEventListener('input', onMove)
el.addEventListener('scroll', onMove)
document.addEventListener('selectionchange', onMove)
ro.observe(el)
if (document.activeElement === el) schedule(true)
return () => {
cancelAnimationFrame(frame)
hide()
ro.disconnect()
el.removeEventListener('focus', onFocus)
el.removeEventListener('blur', hide)
el.removeEventListener('input', onMove)
el.removeEventListener('scroll', onMove)
document.removeEventListener('selectionchange', onMove)
}
}, [input, on])
return { caret, mirror }
}
/** The caret bar and its measuring copy; place inside the relative box that holds the input. */
export function CaretParts({ caret, mirror }: { caret: RefObject<HTMLSpanElement | null>; mirror: RefObject<HTMLSpanElement | null> }) {
return (
<>
<span aria-hidden="true" className="pointer-events-none absolute top-0 left-0 size-0 overflow-hidden">
<span ref={mirror} className="invisible whitespace-pre" />
</span>
<span ref={caret} aria-hidden="true" data-part="caret" className="pointer-events-none absolute top-0 left-0 w-0.5 rounded-full bg-fg-strong opacity-0" />
</>
)
}
function EyeIcon({ open }: { open: boolean }) {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="col-start-1 row-start-1 size-4">
<path d="M1.75 8s2.25-4.25 6.25-4.25S14.25 8 14.25 8 12 12.25 8 12.25 1.75 8 1.75 8z" />
<circle cx="8" cy="8" r="1.75" />
{!open && <path d="M2.5 2.5l11 11" />}
</svg>
)
}
export function Input({
label,
hideLabel = false,
floatingLabel = false,
hint,
error,
success,
reserveNote = false,
invalid = false,
size = 'md',
leading,
trailing,
smoothCaret = true,
strength = false,
reveal = false,
disabled,
id,
type,
placeholder,
className = '',
onChange,
ref,
...rest
}: InputProps) {
const auto = useId()
const inputId = id ?? auto
const input = useRef<HTMLInputElement>(null)
const field = useRef<HTMLDivElement>(null)
useImperativeHandle(ref, () => input.current as HTMLInputElement, [])
const { caret, mirror } = useSmoothCaret(input, smoothCaret && !disabled)
const [typed, setTyped] = useState(String(rest.value ?? rest.defaultValue ?? ''))
const [shown, setShown] = useState(false)
const password = type === 'password'
const value = rest.value === undefined ? typed : String(rest.value)
const score = passwordStrength(value)
const meter = password && strength && value.length > 0
const bad = invalid || Boolean(error)
const note = error || success || hint
const noteId = `${inputId}-note`
const meterId = `${inputId}-strength`
const describedBy = [rest['aria-describedby'], note ? noteId : undefined, meter ? meterId : undefined].filter(Boolean).join(' ') || undefined
const good = Boolean(success) && !bad
const tone = disabled ? 'border-line-subtle bg-sunken' : bad ? 'border-error bg-surface' : good ? 'border-success/50 bg-surface hover:border-success/70 has-focus:border-success/70' : 'border-line bg-surface hover:border-line-strong has-focus:border-line-strong'
// A new error nudges the field once, so the eye goes to it. Clearing it or changing its words does not.
const hadError = useRef(Boolean(error))
useEffect(() => {
const was = hadError.current
hadError.current = Boolean(error)
const f = field.current
if (!error || was || !f || !motionOk(f)) return
f.animate([{ transform: 'none' }, { transform: 'translateX(-3px)' }, { transform: 'translateX(3px)' }, { transform: 'translateX(-2px)' }, { transform: 'none' }], { duration: 240, easing: 'ease-out' })
}, [error])
const control = (
<input
ref={input}
id={inputId}
type={password && shown ? 'text' : type}
disabled={disabled}
placeholder={floatingLabel ? placeholder ?? ' ' : placeholder}
data-part="input"
onChange={(e) => {
setTyped(e.target.value)
onChange?.(e)
}}
className={`h-full min-w-0 flex-1 bg-transparent text-fg-strong outline-none placeholder:text-fg-muted disabled:cursor-not-allowed disabled:text-fg-disabled ${floatingLabel ? 'peer w-full pt-4 placeholder:opacity-0 focus:placeholder:opacity-100' : ''}`}
{...rest}
aria-invalid={bad || undefined}
aria-describedby={describedBy}
/>
)
return (
<div data-part="root" className={`flex flex-col gap-1.5 ${className}`}>
{!floatingLabel && (
<label data-part="label" htmlFor={inputId} className={hideLabel ? 'sr-only' : `text-label ${disabled ? 'text-fg-disabled' : 'text-fg-strong'}`}>
{label}
</label>
)}
<div
ref={field}
data-part="field"
className={`relative flex items-center gap-2 border transition-[border-color] duration-(--nx-dur-quick) ease-out has-focus-visible:outline-none has-focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--nx-fg-muted)_16%,transparent)] ${floatingLabel ? floatingHeights[size] : heights[size]} ${tone}`}
>
{leading && <span data-part="leading" aria-hidden="true" className="flex shrink-0 text-icon-muted">{leading}</span>}
{floatingLabel ? (
<span className="relative flex h-full min-w-0 flex-1">
{control}
<label
data-part="label"
htmlFor={inputId}
className={`pointer-events-none absolute top-1/2 left-0 max-w-full origin-[left_center] -translate-y-1/2 truncate transition-[translate,scale] duration-(--nx-dur-quick) ease-out peer-focus:translate-y-[calc(-50%_-_9px)] peer-focus:scale-[.8] peer-[:not(:placeholder-shown)]:translate-y-[calc(-50%_-_9px)] peer-[:not(:placeholder-shown)]:scale-[.8] ${disabled ? 'text-fg-disabled' : 'text-fg-muted'}`}
>
{label}
</label>
{smoothCaret && <CaretParts caret={caret} mirror={mirror} />}
</span>
) : (
control
)}
{smoothCaret && !floatingLabel && <CaretParts caret={caret} mirror={mirror} />}
{good && !trailing && (
<svg data-part="success-icon" aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className="size-4 shrink-0 text-success transition-[opacity,scale] duration-(--nx-dur-base) ease-out starting:scale-[.8] starting:opacity-0">
<circle cx="8" cy="8" r="6.25" />
<path d="M5.5 8.3l1.9 1.9 3.2-3.9" />
</svg>
)}
{trailing && <span data-part="trailing" className="flex shrink-0 text-icon-muted">{trailing}</span>}
{password && reveal && (
<button
type="button"
data-part="reveal"
aria-label={shown ? 'Hide password' : 'Show password'}
aria-pressed={shown}
disabled={disabled}
onClick={() => setShown((s) => !s)}
className="-me-1.5 inline-grid size-7 shrink-0 cursor-pointer place-items-center rounded-xs text-icon transition-colors duration-(--nx-dur-quick) ease-out enabled:hover:text-icon-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed disabled:text-fg-disabled"
>
{/* Both icons stay mounted and cross-fade through a light blur (quick 160). */}
<span className="grid">
<span className={`col-start-1 row-start-1 grid transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ${shown ? 'scale-[.8] opacity-0 blur-[2px]' : ''}`}><EyeIcon open /></span>
<span className={`col-start-1 row-start-1 grid transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ${shown ? '' : 'scale-[.8] opacity-0 blur-[2px]'}`}><EyeIcon open={false} /></span>
</span>
</button>
)}
</div>
{meter && (
<div data-part="strength" className="flex flex-col gap-1.5 transition-[opacity,translate] duration-(--nx-dur-quick) ease-out starting:-translate-y-1 starting:opacity-0">
<span aria-hidden="true" className="flex gap-1">
{[0, 1, 2, 3].map((i) => (
<span key={i} className="h-1 flex-1 overflow-hidden rounded-full bg-line-subtle">
<span
className={`block size-full origin-left rounded-full transition-[scale,background-color] duration-(--nx-dur-base) ease-out ${meterTone[score]} ${i < Math.max(score, 1) ? 'scale-x-100' : 'scale-x-0'}`}
style={{ transitionDelay: `${i * 30}ms` }}
/>
</span>
))}
</span>
<span id={meterId} aria-live="polite" className="text-caption text-fg-muted">Strength: {STRENGTH[score]}</span>
</div>
)}
<Note part={error ? 'error' : success ? 'success' : 'hint'} id={noteId} reserve={reserveNote}>{error || success || hint}</Note>
</div>
)
}
'use client'
import { useEffect, useRef, useState, type ReactNode } from 'react'
// Nacre Note: the hint, error or success line under a field. It rolls out: the row grows from 0 to its height (base 240
// out) while the words fade and rise 4 px into place, so the fields below glide down instead of jumping. On the way out
// it keeps its last words on screen while the row rolls back up (quick 160), then unmounts the words. reserve keeps one
// line of space even when there is nothing to say, for a field whose message is likely to appear (no layout shift at all).
// With motion off or reduced, it changes at once. Parts: data-part="hint" (muted), "error" and "success" (their tone).
// React plus Tailwind classes only; needs nacre-theme.css. --nx-note-gap (default 6 px) is the gap the parent puts above
// the note, so the collapsed row cancels it.
export type NoteProps = {
id?: string
part: 'hint' | 'error' | 'success'
children?: ReactNode
className?: string
as?: 'p' | 'span'
/** Keep one line of space while empty. */
reserve?: boolean
}
const tone = { hint: 'text-fg-muted', error: 'text-error-strong', success: 'text-success-strong' } as const
export function Note({ id, part, children, className = '', as: Tag = 'p', reserve = false }: NoteProps) {
const has = children !== undefined && children !== null && children !== false && children !== ''
const [last, setLast] = useState<ReactNode>(children)
const el = useRef<HTMLElement>(null)
const [leaving, setLeaving] = useState(false)
const [seen, setSeen] = useState(has)
if (has !== seen) {
setSeen(has)
setLeaving(!has)
}
if (has && children !== last) setLast(children)
useEffect(() => {
if (!leaving) return
const node = el.current
const raw = node ? getComputedStyle(node).transitionDuration.split(',')[0] : '0s'
const ms = parseFloat(raw) * (raw.endsWith('ms') ? 1 : 1000)
if (!ms) {
setLeaving(false)
return
}
const t = setTimeout(() => setLeaving(false), ms)
return () => clearTimeout(t)
}, [leaving])
const Element = 'span' as unknown as 'p'
const open = has
const hasWords = has || leaving
// The row: a one-cell grid whose track animates 0fr to 1fr. The negative margin cancels the parent's gap while closed.
const wrap = open || reserve ? 'grid-rows-[1fr]' : 'grid-rows-[0fr] mt-[calc(var(--nx-note-gap,6px)*-1)]'
const Wrap = Tag as 'p'
return (
<Wrap
data-part="note"
aria-hidden={hasWords ? undefined : true}
className={`grid transition-[grid-template-rows,margin-top] ease-out ${open ? 'duration-(--nx-dur-base)' : 'duration-(--nx-dur-quick)'} ${wrap} ${className}`}
>
<span className="block min-h-0 overflow-hidden">
{hasWords && (
<Element
ref={el as React.Ref<HTMLParagraphElement>}
data-part={part}
id={id}
aria-hidden={has ? undefined : true}
className={`block text-caption ${tone[part]} transition-[opacity,translate] duration-(--nx-dur-quick) ease-out starting:-translate-y-1 starting:opacity-0 ${has ? '' : '-translate-y-1 opacity-0'}`}
>
{has ? children : last}
</Element>
)}
{reserve && !hasWords && <span className="block text-caption" aria-hidden="true"> </span>}
</span>
</Wrap>
)
}
<div data-part="root" class="flex flex-col gap-1.5 ">
<label data-part="label" for="_R_0_" class="text-label text-fg-strong">Project name</label>
<div data-part="field" class="relative flex items-center gap-2 border transition-[border-color] duration-(--nx-dur-quick) ease-out has-focus-visible:outline-none has-focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--nx-fg-muted)_16%,transparent)] h-11 rounded-md px-3.5 text-body border-line bg-surface hover:border-line-strong has-focus:border-line-strong">
<input id="_R_0_" placeholder="Q3 launch" data-part="input" class="h-full min-w-0 flex-1 bg-transparent text-fg-strong outline-none placeholder:text-fg-muted disabled:cursor-not-allowed disabled:text-fg-disabled " aria-describedby="_R_0_-note"/>
<span aria-hidden="true" class="pointer-events-none absolute top-0 left-0 size-0 overflow-hidden">
<span class="invisible whitespace-pre"></span>
</span>
<span aria-hidden="true" data-part="caret" class="pointer-events-none absolute top-0 left-0 w-0.5 rounded-full bg-fg-strong opacity-0"></span>
</div>
<p data-part="note" class="grid transition-[grid-template-rows,margin-top] ease-out duration-(--nx-dur-base) grid-rows-[1fr] ">
<span class="block min-h-0 overflow-hidden">
<span data-part="hint" id="_R_0_-note" class="block text-caption text-fg-muted transition-[opacity,translate] duration-(--nx-dur-quick) ease-out starting:-translate-y-1 starting:opacity-0 ">Everyone in the workspace can see this name.</span>
</span>
</p>
</div>/* The Tailwind theme lines Input uses. They come from nacre-theme.css (Resources, Tokens), which also defines
the --nx-* values these lines point at. Import that file once; this list is what this component needs from it. */
@theme inline {
--color-surface: var(--nx-surface);
--color-sunken: var(--nx-sunken);
--color-fg-strong: var(--nx-fg-strong);
--color-fg-muted: var(--nx-fg-muted);
--color-fg-disabled: var(--nx-fg-disabled);
--color-line-subtle: var(--nx-line-subtle);
--color-line: var(--nx-line);
--color-line-strong: var(--nx-line-strong);
--color-focus: var(--nx-focus);
--color-icon-strong: var(--nx-icon-strong);
--color-icon: var(--nx-icon);
--color-icon-muted: var(--nx-icon-muted);
--color-success-strong: var(--nx-success-strong);
--color-success: var(--nx-success);
--color-warning-strong: var(--nx-warning-strong);
--color-error-strong: var(--nx-error-strong);
--color-error: var(--nx-error);
--color-transparent: transparent;
--text-body-lg: 1rem;
--text-body-lg--line-height: 1.5rem;
--text-body-lg--letter-spacing: 0em;
--text-body-lg--font-weight: 400;
--text-body: 0.875rem;
--text-body--line-height: 1.25rem;
--text-body--letter-spacing: 0em;
--text-body--font-weight: 400;
--text-label: 0.8125rem;
--text-label--line-height: 1rem;
--text-label--letter-spacing: 0em;
--text-label--font-weight: 600;
--text-caption: 0.75rem;
--text-caption--line-height: 1rem;
--text-caption--letter-spacing: 0.01em;
--text-caption--font-weight: 400;
--spacing: 0.25rem;
--radius-xs: 0.5rem;
--radius-sm: 0.75rem;
--radius-md: 1.125rem;
--ease-out: cubic-bezier(.23, 1, .32, 1);
--breakpoint-sm: 40rem;
--breakpoint-md: 48rem;
--breakpoint-lg: 64rem;
}
The project settings sheet has one Input for the name, prefilled. The hint says who will see the change.
An email Input with type email. When the address is already in the workspace, the error says so and names the fix.
A small Input with a leading search icon and a hidden label at the top of the task list.
DoKeep the label above the field at all times.
Don'tUse the placeholder as the label; it disappears as soon as someone types.
DoWrite errors that say how to fix it: Use at least three characters.
Don'tWrite errors that only blame: Invalid input.
Everyone in the workspace can see this name.
Everyone in the workspace can see this name.