# Search Reveal

A search field hidden above a scrolling list that appears when the user pulls the list down.

Search Reveal is an open-source mobile interaction from suiss/uim for React Native and Expo, with SwiftUI and Jetpack Compose versions built from the same design tokens. The @esuiss/uim CLI copies its source into your project, so you own the code.

Source: https://uim.suiss.app/docs/interactions/search-reveal

![Preview](https://uim.suiss.app/previews/interactions-search-reveal--default.light.webp)

```tsx
import * as React from "react"
import { Pressable, View } from "react-native"
import { SearchReveal, SearchRevealContent, SearchRevealField } from "@/components/interactions/search-reveal"
import { Text } from "@/components/ui/text"

const allNotes = [
  { id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee" },
  { id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road" },
  { id: 3, title: "Book list", preview: "Three novels for the summer" },
  { id: 4, title: "Meeting notes", preview: "Ship the beta on Friday" },
  { id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf" },
  { id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry" },
  { id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday" },
  {
    id: 8,
    title: "Movies to watch",
    preview: "Two documentaries and a classic",
  },
  { id: 9, title: "Garden", preview: "Plant tomatoes after the frost" },
  { id: 10, title: "Packing list", preview: "Charger, passport, rain jacket" },
  { id: 11, title: "Podcast notes", preview: "Episode about city design" },
  { id: 12, title: "Budget", preview: "Rent, groceries, savings" },
]

function NotesExample({
  count,
  defaultQuery = "",
}: {
  count: number
  defaultQuery?: string
}) {
  const [query, setQuery] = React.useState(defaultQuery)
  const notes = allNotes
    .slice(0, count)
    .filter((note) =>
      `${note.title} ${note.preview}`
        .toLowerCase()
        .includes(query.trim().toLowerCase())
    )

  return (
    <View className="flex-1 overflow-hidden rounded-2xl border border-separator">
      <Text variant="h1" className="px-4 pt-4 pb-2">
        Notes
      </Text>
      <SearchReveal>
        <SearchRevealField value={query} onValueChange={setQuery} />
        <SearchRevealContent>
          {notes.length === 0 ? (
            <Text className="px-4 py-16 text-center text-sm text-label-secondary">
              No results for “{query}”
            </Text>
          ) : (
            <View className="mx-4 overflow-hidden rounded-xl bg-surface-secondary">
              {notes.map((note, index) => (
                <Pressable
                  key={note.id}
                  className={
                    index > 0
                      ? "border-t border-separator px-4 py-3 active:bg-item-pressed"
                      : "px-4 py-3 active:bg-item-pressed"
                  }
                >
                  <Text numberOfLines={1} className="font-semibold">
                    {note.title}
                  </Text>
                  <Text
                    numberOfLines={1}
                    className="text-sm text-label-secondary"
                  >
                    {note.preview}
                  </Text>
                </Pressable>
              ))}
            </View>
          )}
          <Text className="px-4 py-3 text-center text-xs text-label-secondary">
            {notes.length} {notes.length === 1 ? "note" : "notes"}
          </Text>
        </SearchRevealContent>
      </SearchReveal>
    </View>
  )
}

export function SearchRevealExample() {
  return (
    <NotesExample count={12} />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct SearchRevealExample: View {
  var body: some View {
    SearchRevealNotes(count: 12)
  }
}

struct SearchRevealNote: Identifiable {
  let id: Int
  let title: String
  let preview: String
}

let searchRevealNotes = [
  SearchRevealNote(id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee"),
  SearchRevealNote(id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road"),
  SearchRevealNote(id: 3, title: "Book list", preview: "Three novels for the summer"),
  SearchRevealNote(id: 4, title: "Meeting notes", preview: "Ship the beta on Friday"),
  SearchRevealNote(id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf"),
  SearchRevealNote(id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry"),
  SearchRevealNote(id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday"),
  SearchRevealNote(id: 8, title: "Movies to watch", preview: "Two documentaries and a classic"),
  SearchRevealNote(id: 9, title: "Garden", preview: "Plant tomatoes after the frost"),
  SearchRevealNote(id: 10, title: "Packing list", preview: "Charger, passport, rain jacket"),
  SearchRevealNote(id: 11, title: "Podcast notes", preview: "Episode about city design"),
  SearchRevealNote(id: 12, title: "Budget", preview: "Rent, groceries, savings"),
]

struct SearchRevealNotes: View {
  let count: Int

  @State private var query: String

  init(count: Int, query: String = "") {
    self.count = count
    _query = State(initialValue: query)
  }

  var notes: [SearchRevealNote] {
    let needle = query.trimmingCharacters(in: .whitespaces).lowercased()
    return searchRevealNotes.prefix(count).filter { note in
      needle.isEmpty || "\(note.title) \(note.preview)".lowercased().contains(needle)
    }
  }

  var body: some View {
    let notes = notes
    let shape = RoundedRectangle(cornerRadius: Radius.xl2, style: .continuous)
    VStack(alignment: .leading, spacing: 0) {
      Text("Notes")
        .textVariant(.h1)
        .padding(.horizontal, 16)
        .padding(.top, 16)
        .padding(.bottom, 8)
      SearchReveal {
        SearchRevealField(text: $query)
        SearchRevealContent {
          if notes.isEmpty {
            Text(verbatim: "No results for “\(query)”")
              .textStyle(.sm)
              .foregroundStyle(Color.labelSecondary)
              .multilineTextAlignment(.center)
              .padding(.horizontal, 16)
              .padding(.vertical, 64)
              .frame(maxWidth: .infinity)
          } else {
            VStack(spacing: 0) {
              ForEach(Array(notes.enumerated()), id: \.element.id) { index, note in
                Button {} label: {
                  VStack(alignment: .leading, spacing: 0) {
                    Text(verbatim: note.title)
                      .textStyle(.base, weight: .semibold)
                      .foregroundStyle(Color.label)
                      .lineLimit(1)
                    Text(verbatim: note.preview)
                      .textStyle(.sm)
                      .foregroundStyle(Color.labelSecondary)
                      .lineLimit(1)
                  }
                  .padding(.horizontal, 16)
                  .padding(.vertical, 12)
                  .frame(maxWidth: .infinity, alignment: .leading)
                  .contentShape(Rectangle())
                }
                .buttonStyle(SearchRevealRowStyle())
                .overlay(alignment: .top) {
                  if index > 0 {
                    Color.separator.frame(height: 1)
                  }
                }
              }
            }
            .background(Color.surfaceSecondary)
            .clipShape(RoundedRectangle(cornerRadius: Radius.xl, style: .continuous))
            .padding(.horizontal, 16)
          }
          Text(verbatim: "\(notes.count) \(notes.count == 1 ? "note" : "notes")")
            .textStyle(.xs)
            .foregroundStyle(Color.labelSecondary)
            .multilineTextAlignment(.center)
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
            .frame(maxWidth: .infinity)
        }
      }
    }
    .clipShape(shape)
    .overlay { shape.strokeBorder(Color.separator) }
    .containerRelativeFrame(.vertical) { height, _ in height - 32 }
  }
}

struct SearchRevealRowStyle: ButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .background(configuration.isPressed ? Color.itemPressed : .clear)
  }
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.TextVariant
import com.esuiss.ui.interactions.SearchReveal
import com.esuiss.ui.interactions.SearchRevealContent
import com.esuiss.ui.interactions.SearchRevealField
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

@Composable
fun SearchRevealExample() {
    SearchRevealNotes(count = 12)
}

class SearchRevealNote(val id: Int, val title: String, val preview: String)

val searchRevealAllNotes = listOf(
    SearchRevealNote(1, "Groceries", "Milk, eggs, bread, coffee"),
    SearchRevealNote(2, "Trip ideas", "Lisbon, Porto, the coast road"),
    SearchRevealNote(3, "Book list", "Three novels for the summer"),
    SearchRevealNote(4, "Meeting notes", "Ship the beta on Friday"),
    SearchRevealNote(5, "Gift ideas", "Headphones, a plant, a scarf"),
    SearchRevealNote(6, "Recipes", "Lemon pasta and a quick curry"),
    SearchRevealNote(7, "Workout plan", "Run on Monday, swim on Thursday"),
    SearchRevealNote(8, "Movies to watch", "Two documentaries and a classic"),
    SearchRevealNote(9, "Garden", "Plant tomatoes after the frost"),
    SearchRevealNote(10, "Packing list", "Charger, passport, rain jacket"),
    SearchRevealNote(11, "Podcast notes", "Episode about city design"),
    SearchRevealNote(12, "Budget", "Rent, groceries, savings"),
)

@Composable
fun SearchRevealNotes(count: Int, defaultQuery: String = "") {
    val colors = EsuissTheme.colors
    var query by rememberSaveable { mutableStateOf(defaultQuery) }
    val needle = query.trim().lowercase()
    val notes = searchRevealAllNotes.take(count).filter { "${it.title} ${it.preview}".lowercase().contains(needle) }
    val shape = RoundedCornerShape(Radius.xl2)
    Column(
        Modifier
            .fillMaxWidth()
            .height(600.dp)
            .clip(shape)
            .border(1.dp, colors.separator, shape),
    ) {
        Text("Notes", modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp), variant = TextVariant.H1)
        SearchReveal(Modifier.weight(1f)) {
            SearchRevealField(value = query, onValueChange = { query = it })
            SearchRevealContent {
                if (notes.isEmpty()) {
                    Text(
                        "No results for “$query”",
                        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 64.dp),
                        style = Typography.sm.copy(color = colors.labelSecondary),
                        textAlign = TextAlign.Center,
                    )
                } else {
                    Column(
                        Modifier
                            .padding(horizontal = 16.dp)
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(Radius.xl))
                            .background(colors.surfaceSecondary),
                    ) {
                        notes.forEachIndexed { index, note ->
                            if (index > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(colors.separator))
                            SearchRevealRow(note)
                        }
                    }
                }
                Text(
                    "${notes.size} ${if (notes.size == 1) "note" else "notes"}",
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
                    style = Typography.xs.copy(color = colors.labelSecondary),
                    textAlign = TextAlign.Center,
                )
            }
        }
    }
}

@Composable
fun SearchRevealRow(note: SearchRevealNote) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    Column(
        Modifier
            .fillMaxWidth()
            .background(if (pressed) colors.itemPressed else Color.Transparent)
            .clickable(interactionSource = interaction, indication = null, role = Role.Button) {}
            .padding(horizontal = 16.dp, vertical = 12.dp),
    ) {
        Text(
            note.title,
            style = Typography.base.copy(fontWeight = FontWeight.SemiBold),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Text(
            note.preview,
            style = Typography.sm.copy(color = colors.labelSecondary),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}
```

`SearchReveal` is a scroll view that starts scrolled just past its `SearchRevealField`, so the list shows first and the field is out of view. Pulling down reveals the field, which fades in as it appears, and the scroll snaps either fully open or fully hidden.

Focusing the field scrolls it into view. While there is a query, snapping is turned off so the field stays visible. Use it for notes, mail or settings lists where search should be close but not take space.

## Installation

```bash title="Terminal"
npx @esuiss/uim@latest add search-reveal
```

```bash title="Terminal"
npx @esuiss/uim@latest add search-reveal --platform swift
```

```bash title="Terminal"
npx @esuiss/uim@latest add search-reveal --platform kotlin
```

The CLI also adds what it builds on: [Icon](/docs/components/icon).

### Manual

**Uniwind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn phosphor-react-native react-native-reanimated react-native-svg react-native-worklets
```

2. Add the pieces it builds on: [Icon](/docs/components/icon).

3. Copy the source into `components/interactions/search-reveal.tsx`:

```tsx title="uniwind/components/interactions/search-reveal.tsx"
import { cn } from "cn"
import { MagnifyingGlassIcon, XCircleIcon } from "phosphor-react-native"
import * as React from "react"
import {
  type LayoutChangeEvent,
  Pressable,
  type ScrollView,
  type ScrollViewProps,
  TextInput,
  View,
  type ViewProps,
} from "react-native"
import Animated, {
  type SharedValue,
  useAnimatedRef,
  useAnimatedScrollHandler,
  useAnimatedStyle,
  useSharedValue,
} from "react-native-reanimated"
import { Icon } from "@/components/ui/icon"

type SearchRevealContextProps = {
  offset: SharedValue<number>
  fieldHeight: number
  viewportHeight: number
  setFieldHeight: (height: number) => void
  setHasQuery: (hasQuery: boolean) => void
  reveal: () => void
}

const SearchRevealContext =
  React.createContext<SearchRevealContextProps | null>(null)

function useSearchReveal(componentName: string) {
  const context = React.useContext(SearchRevealContext)
  if (!context) {
    throw new Error(`${componentName} must be used within a <SearchReveal />`)
  }
  return context
}

function SearchReveal({
  className,
  onLayout,
  children,
  ...props
}: Omit<ScrollViewProps, "onScroll">) {
  const scrollRef = useAnimatedRef<Animated.ScrollView>()
  const offset = useSharedValue(0)
  const [fieldHeight, setFieldHeight] = React.useState(0)
  const [viewportHeight, setViewportHeight] = React.useState(0)
  const [hasQuery, setHasQuery] = React.useState(false)
  const positioned = React.useRef(false)

  const onScroll = useAnimatedScrollHandler((event) => {
    offset.value = event.contentOffset.y
  })

  React.useEffect(() => {
    if (positioned.current || fieldHeight <= 0 || viewportHeight <= 0) return
    positioned.current = true
    if (hasQuery) return
    const frame = requestAnimationFrame(() => {
      const scroll = scrollRef.current as ScrollView | null
      scroll?.scrollTo({ y: fieldHeight, animated: false })
    })
    return () => cancelAnimationFrame(frame)
  }, [fieldHeight, viewportHeight, hasQuery, scrollRef])

  const reveal = React.useCallback(() => {
    const scroll = scrollRef.current as ScrollView | null
    scroll?.scrollTo({ y: 0, animated: true })
  }, [scrollRef])

  const contextValue = React.useMemo(
    () => ({
      offset,
      fieldHeight,
      viewportHeight,
      setFieldHeight,
      setHasQuery,
      reveal,
    }),
    [offset, fieldHeight, viewportHeight, reveal]
  )

  return (
    <SearchRevealContext.Provider value={contextValue}>
      <Animated.ScrollView
        ref={scrollRef}
        onScroll={onScroll}
        scrollEventThrottle={16}
        snapToOffsets={
          fieldHeight > 0 && !hasQuery ? [0, fieldHeight] : undefined
        }
        snapToEnd={false}
        keyboardShouldPersistTaps="handled"
        className={cn("flex-1", className)}
        onLayout={(event: LayoutChangeEvent) => {
          setViewportHeight(event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {children}
      </Animated.ScrollView>
    </SearchRevealContext.Provider>
  )
}

function SearchRevealField({
  value,
  onValueChange,
  placeholder = "Search",
  className,
  onFocus,
  ...props
}: Omit<React.ComponentProps<typeof TextInput>, "value" | "onChangeText"> & {
  value: string
  onValueChange: (value: string) => void
}) {
  const { offset, fieldHeight, setFieldHeight, setHasQuery, reveal } =
    useSearchReveal("SearchRevealField")
  const inputRef = React.useRef<TextInput>(null)

  React.useEffect(() => setHasQuery(value.length > 0), [value, setHasQuery])

  const revealStyle = useAnimatedStyle(() => {
    if (fieldHeight <= 0) return { opacity: 1 }
    return {
      opacity: Math.min(Math.max(1 - offset.value / fieldHeight, 0), 1),
    }
  }, [fieldHeight])

  return (
    <Animated.View
      className="px-4 pb-2"
      style={revealStyle}
      onLayout={(event) => setFieldHeight(event.nativeEvent.layout.height)}
    >
      <View className="h-9 flex-row items-center gap-1.5 rounded-lg bg-control px-2">
        <Icon
          as={MagnifyingGlassIcon}
          className="size-4.5 shrink-0 text-label-secondary"
        />
        <TextInput
          ref={inputRef}
          role="searchbox"
          value={value}
          placeholder={placeholder}
          accessibilityLabel={placeholder}
          onChangeText={onValueChange}
          onFocus={(event) => {
            reveal()
            onFocus?.(event)
          }}
          autoCorrect={false}
          autoCapitalize="none"
          returnKeyType="search"
          className={cn(
            "h-full min-w-0 flex-1 py-0 text-base text-label",
            className
          )}
          placeholderTextColorClassName="accent-label-secondary"
          cursorColorClassName="accent-accent"
          selectionColorClassName="accent-accent"
          {...props}
        />
        {value ? (
          <Pressable
            role="button"
            accessibilityLabel="Clear search"
            hitSlop={8}
            onPress={() => {
              onValueChange("")
              inputRef.current?.focus()
            }}
            className="-me-1 size-7 shrink-0 items-center justify-center rounded-full"
          >
            <Icon
              as={XCircleIcon}
              weight="fill"
              className="size-4.5 text-label-secondary"
            />
          </Pressable>
        ) : null}
      </View>
    </Animated.View>
  )
}

function SearchRevealContent({ className, style, ...props }: ViewProps) {
  const { viewportHeight } = useSearchReveal("SearchRevealContent")
  return (
    <View
      className={className}
      style={[{ minHeight: viewportHeight }, style]}
      {...props}
    />
  )
}

export { SearchReveal, SearchRevealContent, SearchRevealField }
```

4. Update the import paths to match your project.

**NativeWind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn nativewind phosphor-react-native react-native-reanimated react-native-svg react-native-worklets
```

2. Add the pieces it builds on: [Icon](/docs/components/icon).

3. Copy the source into `components/interactions/search-reveal.tsx`:

```tsx title="nativewind/components/interactions/search-reveal.tsx"
import { cn } from "cn"
import { cssInterop } from "nativewind"
import { MagnifyingGlassIcon, XCircleIcon } from "phosphor-react-native"
import * as React from "react"
import {
  type LayoutChangeEvent,
  Pressable,
  type ScrollView,
  type ScrollViewProps,
  TextInput,
  View,
  type ViewProps,
} from "react-native"
import Animated, {
  type SharedValue,
  useAnimatedRef,
  useAnimatedScrollHandler,
  useAnimatedStyle,
  useSharedValue,
} from "react-native-reanimated"
import { Icon } from "@/components/ui/icon"

declare module "react-native" {
  interface TextInputProps {
    cursorColorClassName?: string
    selectionColorClassName?: string
  }
}

cssInterop(TextInput, {
  className: { target: "style", nativeStyleToProp: { textAlign: true } },
  placeholderClassName: {
    target: false,
    nativeStyleToProp: { color: "placeholderTextColor" },
  },
  cursorColorClassName: {
    target: false,
    nativeStyleToProp: { color: "cursorColor" },
  },
  selectionColorClassName: {
    target: false,
    nativeStyleToProp: { color: "selectionColor" },
  },
})

type SearchRevealContextProps = {
  offset: SharedValue<number>
  fieldHeight: number
  viewportHeight: number
  setFieldHeight: (height: number) => void
  setHasQuery: (hasQuery: boolean) => void
  reveal: () => void
}

const SearchRevealContext =
  React.createContext<SearchRevealContextProps | null>(null)

function useSearchReveal(componentName: string) {
  const context = React.useContext(SearchRevealContext)
  if (!context) {
    throw new Error(`${componentName} must be used within a <SearchReveal />`)
  }
  return context
}

function SearchReveal({
  className,
  onLayout,
  children,
  ...props
}: Omit<ScrollViewProps, "onScroll">) {
  const scrollRef = useAnimatedRef<Animated.ScrollView>()
  const offset = useSharedValue(0)
  const [fieldHeight, setFieldHeight] = React.useState(0)
  const [viewportHeight, setViewportHeight] = React.useState(0)
  const [hasQuery, setHasQuery] = React.useState(false)
  const positioned = React.useRef(false)

  const onScroll = useAnimatedScrollHandler((event) => {
    offset.value = event.contentOffset.y
  })

  React.useEffect(() => {
    if (positioned.current || fieldHeight <= 0 || viewportHeight <= 0) return
    positioned.current = true
    if (hasQuery) return
    const frame = requestAnimationFrame(() => {
      const scroll = scrollRef.current as ScrollView | null
      scroll?.scrollTo({ y: fieldHeight, animated: false })
    })
    return () => cancelAnimationFrame(frame)
  }, [fieldHeight, viewportHeight, hasQuery, scrollRef])

  const reveal = React.useCallback(() => {
    const scroll = scrollRef.current as ScrollView | null
    scroll?.scrollTo({ y: 0, animated: true })
  }, [scrollRef])

  const contextValue = React.useMemo(
    () => ({
      offset,
      fieldHeight,
      viewportHeight,
      setFieldHeight,
      setHasQuery,
      reveal,
    }),
    [offset, fieldHeight, viewportHeight, reveal]
  )

  return (
    <SearchRevealContext.Provider value={contextValue}>
      <Animated.ScrollView
        ref={scrollRef}
        onScroll={onScroll}
        scrollEventThrottle={16}
        snapToOffsets={
          fieldHeight > 0 && !hasQuery ? [0, fieldHeight] : undefined
        }
        snapToEnd={false}
        keyboardShouldPersistTaps="handled"
        className={cn("flex-1", className)}
        onLayout={(event: LayoutChangeEvent) => {
          setViewportHeight(event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {children}
      </Animated.ScrollView>
    </SearchRevealContext.Provider>
  )
}

function SearchRevealField({
  value,
  onValueChange,
  placeholder = "Search",
  className,
  onFocus,
  ...props
}: Omit<React.ComponentProps<typeof TextInput>, "value" | "onChangeText"> & {
  value: string
  onValueChange: (value: string) => void
}) {
  const { offset, fieldHeight, setFieldHeight, setHasQuery, reveal } =
    useSearchReveal("SearchRevealField")
  const inputRef = React.useRef<TextInput>(null)

  React.useEffect(() => setHasQuery(value.length > 0), [value, setHasQuery])

  const revealStyle = useAnimatedStyle(() => {
    if (fieldHeight <= 0) return { opacity: 1 }
    return {
      opacity: Math.min(Math.max(1 - offset.value / fieldHeight, 0), 1),
    }
  }, [fieldHeight])

  return (
    <Animated.View
      className="px-4 pb-2"
      style={revealStyle}
      onLayout={(event) => setFieldHeight(event.nativeEvent.layout.height)}
    >
      <View className="h-9 flex-row items-center gap-1.5 rounded-lg bg-control px-2">
        <Icon
          as={MagnifyingGlassIcon}
          className="size-[1.125rem] shrink-0 text-label-secondary"
        />
        <TextInput
          ref={inputRef}
          role="searchbox"
          value={value}
          placeholder={placeholder}
          accessibilityLabel={placeholder}
          onChangeText={onValueChange}
          onFocus={(event) => {
            reveal()
            onFocus?.(event)
          }}
          autoCorrect={false}
          autoCapitalize="none"
          returnKeyType="search"
          className={cn(
            "h-full min-w-0 flex-1 py-0 text-base text-label",
            className
          )}
          placeholderClassName="text-label-secondary"
          cursorColorClassName="text-accent"
          selectionColorClassName="text-accent"
          {...props}
        />
        {value ? (
          <Pressable
            role="button"
            accessibilityLabel="Clear search"
            hitSlop={8}
            onPress={() => {
              onValueChange("")
              inputRef.current?.focus()
            }}
            className="-me-1 size-7 shrink-0 items-center justify-center rounded-full"
          >
            <Icon
              as={XCircleIcon}
              weight="fill"
              className="size-[1.125rem] text-label-secondary"
            />
          </Pressable>
        ) : null}
      </View>
    </Animated.View>
  )
}

function SearchRevealContent({ className, style, ...props }: ViewProps) {
  const { viewportHeight } = useSearchReveal("SearchRevealContent")
  return (
    <View
      className={className}
      style={[{ minHeight: viewportHeight }, style]}
      {...props}
    />
  )
}

export { SearchReveal, SearchRevealContent, SearchRevealField }
```

4. Update the import paths to match your project.

**StyleSheet**

1. Install the dependencies:

```bash title="Terminal"
npx expo install phosphor-react-native react-native-reanimated react-native-svg react-native-worklets
```

2. Add the pieces it builds on: [Icon](/docs/components/icon).

3. Copy the source into `components/interactions/search-reveal.tsx`:

```tsx title="stylesheet/components/interactions/search-reveal.tsx"
import { MagnifyingGlassIcon, XCircleIcon } from "phosphor-react-native"
import * as React from "react"
import {
  type LayoutChangeEvent,
  Pressable,
  type ScrollView,
  type ScrollViewProps,
  StyleSheet,
  TextInput,
  View,
  type ViewProps,
} from "react-native"
import Animated, {
  type SharedValue,
  useAnimatedRef,
  useAnimatedScrollHandler,
  useAnimatedStyle,
  useSharedValue,
} from "react-native-reanimated"
import { Icon } from "@/components/ui/icon"
import { fontSize, radius, useTheme } from "@/components/ui/theme"

const styles = StyleSheet.create({
  root: { flex: 1 },
  field: { paddingHorizontal: 16, paddingBottom: 8 },
  box: {
    height: 36,
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
    borderRadius: radius.lg,
    paddingHorizontal: 8,
  },
  icon: { flexShrink: 0 },
  input: {
    height: "100%",
    minWidth: 0,
    flex: 1,
    paddingVertical: 0,
    ...fontSize.base,
  },
  clear: {
    marginEnd: -4,
    width: 28,
    height: 28,
    flexShrink: 0,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: radius.full,
  },
})

type SearchRevealContextProps = {
  offset: SharedValue<number>
  fieldHeight: number
  viewportHeight: number
  setFieldHeight: (height: number) => void
  setHasQuery: (hasQuery: boolean) => void
  reveal: () => void
}

const SearchRevealContext =
  React.createContext<SearchRevealContextProps | null>(null)

function useSearchReveal(componentName: string) {
  const context = React.useContext(SearchRevealContext)
  if (!context) {
    throw new Error(`${componentName} must be used within a <SearchReveal />`)
  }
  return context
}

function SearchReveal({
  style,
  onLayout,
  children,
  ...props
}: Omit<ScrollViewProps, "onScroll">) {
  const scrollRef = useAnimatedRef<Animated.ScrollView>()
  const offset = useSharedValue(0)
  const [fieldHeight, setFieldHeight] = React.useState(0)
  const [viewportHeight, setViewportHeight] = React.useState(0)
  const [hasQuery, setHasQuery] = React.useState(false)
  const positioned = React.useRef(false)

  const onScroll = useAnimatedScrollHandler((event) => {
    offset.value = event.contentOffset.y
  })

  React.useEffect(() => {
    if (positioned.current || fieldHeight <= 0 || viewportHeight <= 0) return
    positioned.current = true
    if (hasQuery) return
    const frame = requestAnimationFrame(() => {
      const scroll = scrollRef.current as ScrollView | null
      scroll?.scrollTo({ y: fieldHeight, animated: false })
    })
    return () => cancelAnimationFrame(frame)
  }, [fieldHeight, viewportHeight, hasQuery, scrollRef])

  const reveal = React.useCallback(() => {
    const scroll = scrollRef.current as ScrollView | null
    scroll?.scrollTo({ y: 0, animated: true })
  }, [scrollRef])

  const contextValue = React.useMemo(
    () => ({
      offset,
      fieldHeight,
      viewportHeight,
      setFieldHeight,
      setHasQuery,
      reveal,
    }),
    [offset, fieldHeight, viewportHeight, reveal]
  )

  return (
    <SearchRevealContext.Provider value={contextValue}>
      <Animated.ScrollView
        ref={scrollRef}
        onScroll={onScroll}
        scrollEventThrottle={16}
        snapToOffsets={
          fieldHeight > 0 && !hasQuery ? [0, fieldHeight] : undefined
        }
        snapToEnd={false}
        keyboardShouldPersistTaps="handled"
        style={[styles.root, style]}
        onLayout={(event: LayoutChangeEvent) => {
          setViewportHeight(event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {children}
      </Animated.ScrollView>
    </SearchRevealContext.Provider>
  )
}

function SearchRevealField({
  value,
  onValueChange,
  placeholder = "Search",
  style,
  onFocus,
  ...props
}: Omit<React.ComponentProps<typeof TextInput>, "value" | "onChangeText"> & {
  value: string
  onValueChange: (value: string) => void
}) {
  const { colors } = useTheme()
  const { offset, fieldHeight, setFieldHeight, setHasQuery, reveal } =
    useSearchReveal("SearchRevealField")
  const inputRef = React.useRef<TextInput>(null)

  React.useEffect(() => setHasQuery(value.length > 0), [value, setHasQuery])

  const revealStyle = useAnimatedStyle(() => {
    if (fieldHeight <= 0) return { opacity: 1 }
    return {
      opacity: Math.min(Math.max(1 - offset.value / fieldHeight, 0), 1),
    }
  }, [fieldHeight])

  return (
    <Animated.View
      style={[styles.field, revealStyle]}
      onLayout={(event) => setFieldHeight(event.nativeEvent.layout.height)}
    >
      <View style={[styles.box, { backgroundColor: colors.control }]}>
        <Icon
          as={MagnifyingGlassIcon}
          size={18}
          color={colors.labelSecondary}
          style={styles.icon}
        />
        <TextInput
          ref={inputRef}
          role="searchbox"
          value={value}
          placeholder={placeholder}
          accessibilityLabel={placeholder}
          onChangeText={onValueChange}
          onFocus={(event) => {
            reveal()
            onFocus?.(event)
          }}
          autoCorrect={false}
          autoCapitalize="none"
          returnKeyType="search"
          style={[styles.input, { color: colors.label }, style]}
          placeholderTextColor={colors.labelSecondary}
          cursorColor={colors.accent}
          selectionColor={colors.accent}
          {...props}
        />
        {value ? (
          <Pressable
            role="button"
            accessibilityLabel="Clear search"
            hitSlop={8}
            onPress={() => {
              onValueChange("")
              inputRef.current?.focus()
            }}
            style={styles.clear}
          >
            <Icon
              as={XCircleIcon}
              weight="fill"
              size={18}
              color={colors.labelSecondary}
            />
          </Pressable>
        ) : null}
      </View>
    </Animated.View>
  )
}

function SearchRevealContent({ style, ...props }: ViewProps) {
  const { viewportHeight } = useSearchReveal("SearchRevealContent")
  return <View style={[{ minHeight: viewportHeight }, style]} {...props} />
}

export { SearchReveal, SearchRevealContent, SearchRevealField }
```

4. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Add the Swift package to your app:

```swift title="Package.swift"
.package(url: "https://github.com/phosphor-icons/swift", from: "2.1.0")
```

3. Copy the theme files every view uses:

```swift title="swift/Theme/Theme.swift"
import SwiftUI
import UIKit

struct RGBA: Sendable {
  let red: CGFloat
  let green: CGFloat
  let blue: CGFloat
  let alpha: CGFloat

  init(_ hex: UInt32, _ alpha: CGFloat = 1) {
    red = CGFloat((hex >> 16) & 0xFF) / 255
    green = CGFloat((hex >> 8) & 0xFF) / 255
    blue = CGFloat(hex & 0xFF) / 255
    self.alpha = alpha
  }

  var uiColor: UIColor {
    UIColor(red: red, green: green, blue: blue, alpha: alpha)
  }
}

extension Color {
  static func adaptive(light: RGBA, dark: RGBA) -> Color {
    let lightColor = light.uiColor
    let darkColor = dark.uiColor
    return Color(uiColor: UIColor { traits in
      traits.userInterfaceStyle == .dark ? darkColor : lightColor
    })
  }
}

public struct TextStyle: Sendable, Hashable {
  public let size: CGFloat
  public let lineHeight: CGFloat
  public let letterSpacing: CGFloat

  public init(size: CGFloat, lineHeight: CGFloat, letterSpacing: CGFloat) {
    self.size = size
    self.lineHeight = lineHeight
    self.letterSpacing = letterSpacing
  }

  public func font(weight: Font.Weight = .regular) -> Font {
    .system(size: size, weight: weight)
  }

  public var lineSpacing: CGFloat {
    max(0, lineHeight - UIFont.systemFont(ofSize: size).lineHeight)
  }
}

extension Hashable where Self == Font {
  public static func textStyle(_ style: TextStyle, weight: Font.Weight = .regular) -> Font {
    style.font(weight: weight)
  }
}

private struct TextStyleModifier: ViewModifier {
  let style: TextStyle
  let weight: Font.Weight

  func body(content: Content) -> some View {
    content
      .font(style.font(weight: weight))
      .tracking(style.letterSpacing)
      .lineSpacing(style.lineSpacing)
      .padding(.vertical, style.lineSpacing / 2)
  }
}

extension View {
  public func textStyle(_ style: TextStyle, weight: Font.Weight = .regular) -> some View {
    modifier(TextStyleModifier(style: style, weight: weight))
  }
}

public struct Shadow: Sendable, Hashable {
  public let color: Color
  public let radius: CGFloat
  public let x: CGFloat
  public let y: CGFloat

  public init(color: Color, radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0) {
    self.color = color
    self.radius = radius
    self.x = x
    self.y = y
  }
}

extension View {
  public func shadow(_ shadow: Shadow) -> some View {
    self.shadow(color: shadow.color, radius: shadow.radius, x: shadow.x, y: shadow.y)
  }
}
```

```swift title="swift/Theme/Tokens.swift"
import SwiftUI

extension Color {
  public static let surface = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let surfaceSecondary = Color.adaptive(light: .init(0xF5F5F7), dark: .init(0x161617))
  public static let surfaceTertiary = Color.adaptive(light: .init(0xE8E8ED), dark: .init(0x2C2C2E))
  public static let surfaceRaised = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let label = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let labelSecondary = Color.adaptive(light: .init(0x6E6E73), dark: .init(0xA1A1A6))
  public static let labelTertiary = Color.adaptive(light: .init(0x86868B), dark: .init(0x86868B))
  public static let labelQuaternary = Color.adaptive(light: .init(0xD2D2D7), dark: .init(0x424245))
  public static let control = Color.adaptive(light: .init(0x000000, 0.04), dark: .init(0xFFFFFF, 0.1))
  public static let controlPressed = Color.adaptive(light: .init(0x000000, 0.12), dark: .init(0xFFFFFF, 0.22))
  public static let controlSelected = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let controlDisabled = Color.adaptive(light: .init(0x000000, 0.03), dark: .init(0xFFFFFF, 0.05))
  public static let onControlSelected = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let itemPressed = Color.adaptive(light: .init(0x000000, 0.08), dark: .init(0xFFFFFF, 0.12))
  public static let itemSelected = Color.adaptive(light: .init(0x000000, 0.06), dark: .init(0xFFFFFF, 0.1))
  public static let separator = Color.adaptive(light: .init(0xD2D2D7), dark: .init(0x424245))
  public static let separatorStrong = Color.adaptive(light: .init(0x86868B), dark: .init(0x6E6E73))
  public static let accent = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let accentPressed = Color.adaptive(light: .init(0x005BB8), dark: .init(0x004D9E))
  public static let accentSelected = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let accentDisabled = Color.adaptive(light: .init(0x0071E3, 0.4), dark: .init(0x0071E3, 0.4))
  public static let onAccent = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let accentSurface = Color.adaptive(light: .init(0x0071E3, 0.09), dark: .init(0x0071E3, 0.18))
  public static let accentSurfacePressed = Color.adaptive(light: .init(0x0071E3, 0.18), dark: .init(0x0071E3, 0.3))
  public static let link = Color.adaptive(light: .init(0x0066CC), dark: .init(0x2997FF))
  public static let focus = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let scrim = Color.adaptive(light: .init(0x000000, 0.48), dark: .init(0x000000, 0.48))
  public static let media = Color.adaptive(light: .init(0x000000), dark: .init(0x000000))
  public static let onMedia = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let danger = Color.adaptive(light: .init(0xD0000A), dark: .init(0xFF5447))
  public static let dangerSurface = Color.adaptive(light: .init(0xD70015, 0.08), dark: .init(0xFF453A, 0.2))
  public static let dangerSurfacePressed = Color.adaptive(light: .init(0xD70015, 0.16), dark: .init(0xFF453A, 0.36))
  public static let success = Color.adaptive(light: .init(0x008009), dark: .init(0x30D158))
  public static let successSurface = Color.adaptive(light: .init(0xEFFAF1), dark: .init(0x30D158, 0.16))
  public static let warning = Color.adaptive(light: .init(0xB64400), dark: .init(0xFF9F0A))
  public static let warningSurface = Color.adaptive(light: .init(0xFFF5EA), dark: .init(0xFF9F0A, 0.16))
}

public enum Radius {
  public static let xs: CGFloat = 3
  public static let sm: CGFloat = 5
  public static let md: CGFloat = 8
  public static let lg: CGFloat = 10
  public static let xl: CGFloat = 12
  public static let xl2: CGFloat = 18
  public static let xl3: CGFloat = 28
  public static let full: CGFloat = 9999
}

extension TextStyle {
  public static let xs3 = TextStyle(size: 11, lineHeight: 13, letterSpacing: 0.066)
  public static let xs2 = TextStyle(size: 12, lineHeight: 16, letterSpacing: 0)
  public static let xs = TextStyle(size: 13, lineHeight: 18, letterSpacing: -0.078)
  public static let sm = TextStyle(size: 15, lineHeight: 20, letterSpacing: -0.24)
  public static let md = TextStyle(size: 16, lineHeight: 21, letterSpacing: -0.32)
  public static let base = TextStyle(size: 17, lineHeight: 22, letterSpacing: -0.442)
  public static let lg = TextStyle(size: 20, lineHeight: 25, letterSpacing: -0.46)
  public static let xl = TextStyle(size: 22, lineHeight: 28, letterSpacing: -0.264)
  public static let xl2 = TextStyle(size: 28, lineHeight: 34, letterSpacing: 0.392)
  public static let xl3 = TextStyle(size: 34, lineHeight: 41, letterSpacing: 0.408)

  public static let allCases: [TextStyle] = [.xs3, .xs2, .xs, .sm, .md, .base, .lg, .xl, .xl2, .xl3]
}

extension Shadow {
  public static let md = Shadow(color: .black.opacity(0.08), radius: 6, x: 2, y: 4)
  public static let lg = Shadow(color: .black.opacity(0.12), radius: 12, y: 4)
}
```

4. Copy the source and every file it uses:

```swift title="swift/Interactions/SearchReveal.swift"
import PhosphorSwift
import SwiftUI

enum SearchRevealAnchor: Hashable, Sendable {
  case field, content
}

struct SearchRevealFieldInfo: Equatable {
  var height: CGFloat = 0
  var hasQuery = false
}

struct SearchRevealFieldKey: PreferenceKey {
  static var defaultValue: SearchRevealFieldInfo { SearchRevealFieldInfo() }

  static func reduce(value: inout SearchRevealFieldInfo, nextValue: () -> SearchRevealFieldInfo) {
    let next = nextValue()
    if next.height > 0 { value = next }
  }
}

struct SearchRevealContext {
  var viewport: CGFloat
  var reveal: () -> Void
}

extension EnvironmentValues {
  @Entry var searchReveal: SearchRevealContext?
}

struct SearchRevealSnap: ScrollTargetBehavior {
  let height: CGFloat
  let hasQuery: Bool

  static func target(for offset: CGFloat, height: CGFloat, hasQuery: Bool) -> CGFloat? {
    guard height > 0, offset > 0, offset < height else { return nil }
    return offset < height / 2 || hasQuery ? 0 : height
  }

  func updateTarget(_ target: inout ScrollTarget, context: TargetContext) {
    if let snapped = Self.target(for: target.rect.minY, height: height, hasQuery: hasQuery) {
      target.rect.origin.y = snapped
    }
  }
}

public struct SearchReveal<Content: View>: View {
  let content: Content

  @State private var field = SearchRevealFieldInfo()
  @State private var position: SearchRevealAnchor?
  @State private var viewport: CGFloat = 0
  @State private var settled = false
  @Environment(\.accessibilityReduceMotion) private var reduceMotion

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    let context = SearchRevealContext(viewport: viewport) {
      if reduceMotion {
        position = .field
      } else {
        withAnimation(.smooth(duration: 0.3)) { position = .field }
      }
    }
    ScrollView {
      VStack(spacing: 0) {
        content
      }
      .scrollTargetLayout()
    }
    .scrollPosition(id: $position, anchor: .top)
    .scrollTargetBehavior(SearchRevealSnap(height: field.height, hasQuery: field.hasQuery))
    .scrollBounceBehavior(.always)
    .environment(\.searchReveal, context)
    .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { viewport = $0 }
    .onPreferenceChange(SearchRevealFieldKey.self) { info in
      field = info
      if !settled, info.height > 0 {
        settled = true
        position = info.hasQuery ? .field : .content
      }
    }
  }
}

public struct SearchRevealField: View {
  let text: Binding<String>
  let placeholder: LocalizedStringKey

  @FocusState private var focused: Bool
  @Environment(\.searchReveal) private var reveal

  public init(text: Binding<String>, placeholder: LocalizedStringKey = "Search") {
    self.text = text
    self.placeholder = placeholder
  }

  public var body: some View {
    HStack(spacing: 6) {
      Ph.magnifyingGlass.regular
        .frame(width: 18, height: 18)
        .accessibilityHidden(true)
      TextField(placeholder, text: text, prompt: Text(placeholder).foregroundStyle(Color.labelSecondary))
        .focused($focused)
        .submitLabel(.search)
        .autocorrectionDisabled()
        .scaledFont(.base)
        .foregroundStyle(Color.label)
        .tint(Color.accent)
      if !text.wrappedValue.isEmpty {
        Button {
          text.wrappedValue = ""
          focused = true
        } label: {
          Ph.xCircle.fill
            .frame(width: 18, height: 18)
            .frame(width: 28, height: 28)
            .contentShape(Circle().inset(by: -8))
        }
        .buttonStyle(.plain)
        .padding(.trailing, -4)
        .accessibilityLabel(Text("Clear search"))
      }
    }
    .foregroundStyle(Color.labelSecondary)
    .padding(.horizontal, 8)
    .frame(height: 36)
    .background(Color.control, in: RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    .padding(.horizontal, 16)
    .padding(.bottom, 8)
    .visualEffect { view, proxy in
      let height = proxy.size.height
      let top = proxy.frame(in: .scrollView).minY
      return view.opacity(height > 0 ? min(max(1 + top / height, 0), 1) : 1)
    }
    .background {
      GeometryReader { proxy in
        Color.clear.preference(
          key: SearchRevealFieldKey.self,
          value: SearchRevealFieldInfo(height: proxy.size.height, hasQuery: !text.wrappedValue.isEmpty)
        )
      }
    }
    .id(SearchRevealAnchor.field)
    .onChange(of: focused) { _, value in
      if value { reveal?.reveal() }
    }
  }
}

public struct SearchRevealContent<Content: View>: View {
  let content: Content

  @Environment(\.searchReveal) private var reveal

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    VStack(spacing: 0) {
      content
    }
    .frame(maxWidth: .infinity, minHeight: reveal?.viewport, alignment: .top)
    .id(SearchRevealAnchor.content)
  }
}
```

```swift title="swift/Components/TextVariant.swift"
import SwiftUI

public enum TextVariant: CaseIterable, Sendable {
  case `default`, h1, h2, h3, h4, p, blockquote, code, lead, large, small, muted

  var style: TextStyle {
    switch self {
    case .h1: .xl3
    case .h2: .xl2
    case .h3: .xl
    case .h4, .lead, .large: .lg
    case .code, .small, .muted: .sm
    default: .base
    }
  }

  var weight: Font.Weight {
    switch self {
    case .h1, .h2: .bold
    case .h3, .h4, .large, .code: .semibold
    case .small: .medium
    default: .regular
    }
  }

  var color: Color {
    switch self {
    case .lead, .muted: .labelSecondary
    default: .label
    }
  }

  var isHeading: Bool {
    switch self {
    case .h1, .h2, .h3, .h4: true
    default: false
    }
  }
}

private struct TextVariantModifier: ViewModifier {
  let variant: TextVariant

  func body(content: Content) -> some View {
    switch variant {
    case .blockquote:
      styled(content)
        .italic()
        .padding(.leading, 12)
        .overlay(alignment: .leading) {
          Rectangle().fill(Color.separator).frame(width: 2)
        }
        .padding(.top, 16)
    case .code:
      styled(content)
        .monospaced()
        .padding(.horizontal, 4)
        .padding(.vertical, 2)
        .background(Color.surfaceSecondary, in: RoundedRectangle(cornerRadius: Radius.sm, style: .continuous))
    case .p:
      styled(content).padding(.top, 12)
    default:
      styled(content)
    }
  }

  private func styled(_ content: Content) -> some View {
    content
      .scaledTextStyle(variant.style, weight: variant.weight)
      .foregroundStyle(variant.color)
      .accessibilityAddTraits(variant.isHeading ? .isHeader : [])
  }
}

extension View {
  public func textVariant(_ variant: TextVariant) -> some View {
    modifier(TextVariantModifier(variant: variant))
  }
}

private struct ScaledTextStyleModifier: ViewModifier {
  let style: TextStyle
  let weight: Font.Weight

  @ScaledMetric(relativeTo: .body) private var scale: CGFloat = 1

  func body(content: Content) -> some View {
    let size = style.size * scale
    let lineSpacing = max(0, style.lineHeight * scale - UIFont.systemFont(ofSize: size).lineHeight)
    content
      .font(.system(size: size, weight: weight))
      .tracking(style.letterSpacing)
      .lineSpacing(lineSpacing)
      .padding(.vertical, lineSpacing / 2)
  }
}

extension View {
  func scaledTextStyle(_ style: TextStyle, weight: Font.Weight = .regular) -> some View {
    modifier(ScaledTextStyleModifier(style: style, weight: weight))
  }

  func scaledFont(_ style: TextStyle, weight: Font.Weight = .regular) -> some View {
    modifier(ScaledFontModifier(style: style, weight: weight))
  }
}

private struct ScaledFontModifier: ViewModifier {
  let style: TextStyle
  let weight: Font.Weight

  @ScaledMetric(relativeTo: .body) private var scale: CGFloat = 1

  func body(content: Content) -> some View {
    content
      .font(.system(size: style.size * scale, weight: weight))
      .tracking(style.letterSpacing)
  }
}
```

5. Add the files to your app target.

**Jetpack Compose**

1. Set `minSdk` to 24 or higher and add the dependencies:

```kotlin title="build.gradle.kts"
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.ui:ui")
implementation("com.adamglin:phosphor-icon-android:1.0.0")
```

2. Copy the theme files every view uses:

```kt title="kotlin/theme/Theme.kt"
package com.esuiss.ui.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.dropShadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.shadow.Shadow as DropShadow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp

internal fun textStyle(size: Double, lineHeight: Double, letterSpacing: Double) = TextStyle(
    fontSize = size.sp,
    lineHeight = lineHeight.sp,
    letterSpacing = letterSpacing.em,
    lineHeightStyle = LineHeightStyle(
        alignment = LineHeightStyle.Alignment.Center,
        trim = LineHeightStyle.Trim.None,
    ),
)

@Immutable
data class Shadow(
    val offsetX: Dp,
    val offsetY: Dp,
    val blur: Dp,
    val color: Color,
)

fun Modifier.shadow(shadow: Shadow, shape: Shape): Modifier = dropShadow(
    shape,
    DropShadow(
        radius = shadow.blur,
        color = shadow.color,
        offset = DpOffset(shadow.offsetX, shadow.offsetY),
    ),
)

val LocalColors = staticCompositionLocalOf { LightColors }

object EsuissTheme {
    val colors: Colors
        @Composable get() = LocalColors.current

    val typography: Typography
        get() = Typography

    val radius: Radius
        get() = Radius

    val shadows: Shadows
        get() = Shadows
}

@Composable
fun EsuissTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit,
) {
    CompositionLocalProvider(
        LocalColors provides if (darkTheme) DarkColors else LightColors,
        content = content,
    )
}
```

```kt title="kotlin/theme/Tokens.kt"
package com.esuiss.ui.theme

import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Immutable
data class Colors(
    val surface: Color,
    val surfaceSecondary: Color,
    val surfaceTertiary: Color,
    val surfaceRaised: Color,
    val label: Color,
    val labelSecondary: Color,
    val labelTertiary: Color,
    val labelQuaternary: Color,
    val control: Color,
    val controlPressed: Color,
    val controlSelected: Color,
    val controlDisabled: Color,
    val onControlSelected: Color,
    val itemPressed: Color,
    val itemSelected: Color,
    val separator: Color,
    val separatorStrong: Color,
    val accent: Color,
    val accentPressed: Color,
    val accentSelected: Color,
    val accentDisabled: Color,
    val onAccent: Color,
    val accentSurface: Color,
    val accentSurfacePressed: Color,
    val link: Color,
    val focus: Color,
    val scrim: Color,
    val media: Color,
    val onMedia: Color,
    val danger: Color,
    val dangerSurface: Color,
    val dangerSurfacePressed: Color,
    val success: Color,
    val successSurface: Color,
    val warning: Color,
    val warningSurface: Color,
    val blue: Color,
    val green: Color,
    val orange: Color,
    val red: Color,
    val yellow: Color,
    val purple: Color,
    val pink: Color,
    val indigo: Color,
    val teal: Color,
    val mint: Color,
    val cyan: Color,
    val brown: Color,
    val gray: Color,
    val isDark: Boolean,
)

val LightColors = Colors(
    surface = Color(0xFFFFFFFF),
    surfaceSecondary = Color(0xFFF5F5F7),
    surfaceTertiary = Color(0xFFE8E8ED),
    surfaceRaised = Color(0xFFFFFFFF),
    label = Color(0xFF1D1D1F),
    labelSecondary = Color(0xFF6E6E73),
    labelTertiary = Color(0xFF86868B),
    labelQuaternary = Color(0xFFD2D2D7),
    control = Color(0xFF000000).copy(alpha = 0.04f),
    controlPressed = Color(0xFF000000).copy(alpha = 0.12f),
    controlSelected = Color(0xFF1D1D1F),
    controlDisabled = Color(0xFF000000).copy(alpha = 0.03f),
    onControlSelected = Color(0xFFFFFFFF),
    itemPressed = Color(0xFF000000).copy(alpha = 0.08f),
    itemSelected = Color(0xFF000000).copy(alpha = 0.06f),
    separator = Color(0xFFD2D2D7),
    separatorStrong = Color(0xFF86868B),
    accent = Color(0xFF0071E3),
    accentPressed = Color(0xFF005BB8),
    accentSelected = Color(0xFF0071E3),
    accentDisabled = Color(0xFF0071E3).copy(alpha = 0.4f),
    onAccent = Color(0xFFFFFFFF),
    accentSurface = Color(0xFF0071E3).copy(alpha = 0.09f),
    accentSurfacePressed = Color(0xFF0071E3).copy(alpha = 0.18f),
    link = Color(0xFF0066CC),
    focus = Color(0xFF0071E3),
    scrim = Color(0xFF000000).copy(alpha = 0.48f),
    media = Color(0xFF000000),
    onMedia = Color(0xFFFFFFFF),
    danger = Color(0xFFD0000A),
    dangerSurface = Color(0xFFD70015).copy(alpha = 0.08f),
    dangerSurfacePressed = Color(0xFFD70015).copy(alpha = 0.16f),
    success = Color(0xFF008009),
    successSurface = Color(0xFFEFFAF1),
    warning = Color(0xFFB64400),
    warningSurface = Color(0xFFFFF5EA),
    blue = Color(0xFF007AFF),
    green = Color(0xFF34C759),
    orange = Color(0xFFFF9500),
    red = Color(0xFFFF3B30),
    yellow = Color(0xFFFFCC00),
    purple = Color(0xFFAF52DE),
    pink = Color(0xFFFF2D55),
    indigo = Color(0xFF5856D6),
    teal = Color(0xFF30B0C7),
    mint = Color(0xFF00C7BE),
    cyan = Color(0xFF32ADE6),
    brown = Color(0xFFA2845E),
    gray = Color(0xFF8E8E93),
    isDark = false,
)

val DarkColors = Colors(
    surface = Color(0xFF000000),
    surfaceSecondary = Color(0xFF161617),
    surfaceTertiary = Color(0xFF2C2C2E),
    surfaceRaised = Color(0xFF1D1D1F),
    label = Color(0xFFF5F5F7),
    labelSecondary = Color(0xFFA1A1A6),
    labelTertiary = Color(0xFF86868B),
    labelQuaternary = Color(0xFF424245),
    control = Color(0xFFFFFFFF).copy(alpha = 0.1f),
    controlPressed = Color(0xFFFFFFFF).copy(alpha = 0.22f),
    controlSelected = Color(0xFFF5F5F7),
    controlDisabled = Color(0xFFFFFFFF).copy(alpha = 0.05f),
    onControlSelected = Color(0xFF000000),
    itemPressed = Color(0xFFFFFFFF).copy(alpha = 0.12f),
    itemSelected = Color(0xFFFFFFFF).copy(alpha = 0.1f),
    separator = Color(0xFF424245),
    separatorStrong = Color(0xFF6E6E73),
    accent = Color(0xFF0071E3),
    accentPressed = Color(0xFF004D9E),
    accentSelected = Color(0xFF0071E3),
    accentDisabled = Color(0xFF0071E3).copy(alpha = 0.4f),
    onAccent = Color(0xFFFFFFFF),
    accentSurface = Color(0xFF0071E3).copy(alpha = 0.18f),
    accentSurfacePressed = Color(0xFF0071E3).copy(alpha = 0.3f),
    link = Color(0xFF2997FF),
    focus = Color(0xFF0071E3),
    scrim = Color(0xFF000000).copy(alpha = 0.48f),
    media = Color(0xFF000000),
    onMedia = Color(0xFFFFFFFF),
    danger = Color(0xFFFF5447),
    dangerSurface = Color(0xFFFF453A).copy(alpha = 0.2f),
    dangerSurfacePressed = Color(0xFFFF453A).copy(alpha = 0.36f),
    success = Color(0xFF30D158),
    successSurface = Color(0xFF30D158).copy(alpha = 0.16f),
    warning = Color(0xFFFF9F0A),
    warningSurface = Color(0xFFFF9F0A).copy(alpha = 0.16f),
    blue = Color(0xFF0A84FF),
    green = Color(0xFF30D158),
    orange = Color(0xFFFF9F0A),
    red = Color(0xFFFF453A),
    yellow = Color(0xFFFFD60A),
    purple = Color(0xFFBF5AF2),
    pink = Color(0xFFFF375F),
    indigo = Color(0xFF5E5CE6),
    teal = Color(0xFF40C8E0),
    mint = Color(0xFF66D4CF),
    cyan = Color(0xFF64D2FF),
    brown = Color(0xFFAC8E68),
    gray = Color(0xFF8E8E93),
    isDark = true,
)

object Radius {
    val xs = 3.dp
    val sm = 5.dp
    val md = 8.dp
    val lg = 10.dp
    val xl = 12.dp
    val xl2 = 18.dp
    val xl3 = 28.dp
    val full = 9999.dp
}

object Typography {
    val xs3 = textStyle(11.0, 13.0, 0.006)
    val xs2 = textStyle(12.0, 16.0, 0.0)
    val xs = textStyle(13.0, 18.0, -0.006)
    val sm = textStyle(15.0, 20.0, -0.016)
    val md = textStyle(16.0, 21.0, -0.02)
    val base = textStyle(17.0, 22.0, -0.026)
    val lg = textStyle(20.0, 25.0, -0.023)
    val xl = textStyle(22.0, 28.0, -0.012)
    val xl2 = textStyle(28.0, 34.0, 0.014)
    val xl3 = textStyle(34.0, 41.0, 0.012)

    val all = listOf(xs3, xs2, xs, sm, md, base, lg, xl, xl2, xl3)
}

object Shadows {
    val md = Shadow(2.dp, 4.dp, 12.dp, Color.Black.copy(alpha = 0.08f))
    val lg = Shadow(0.dp, 4.dp, 24.dp, Color.Black.copy(alpha = 0.12f))
}
```

3. Copy the source and every file it uses:

```kt title="kotlin/interactions/SearchReveal.kt"
package com.esuiss.ui.interactions

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.fill.XCircle
import com.adamglin.phosphoricons.regular.MagnifyingGlass
import com.esuiss.ui.components.Icon
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest

private const val SettleDelay = 140L

@Stable
private class SearchRevealContext(val scroll: ScrollState) {
    var fieldHeight by mutableIntStateOf(0)
    var viewportHeight by mutableIntStateOf(0)
    var hasQuery by mutableStateOf(false)
    var positioned = false

    val reveal: Float
        get() = if (fieldHeight == 0) 1f else (1f - scroll.value.toFloat() / fieldHeight).coerceIn(0f, 1f)
}

private val LocalSearchReveal = staticCompositionLocalOf<SearchRevealContext?> { null }

@Composable
fun SearchReveal(
    modifier: Modifier = Modifier,
    content: @Composable ColumnScope.() -> Unit,
) {
    val scroll = rememberScrollState()
    val context = remember(scroll) { SearchRevealContext(scroll) }
    LaunchedEffect(context, context.fieldHeight) {
        val height = context.fieldHeight
        if (height == 0 || context.positioned) return@LaunchedEffect
        context.positioned = true
        scroll.scrollTo(if (context.hasQuery) 0 else height)
    }
    LaunchedEffect(context) {
        snapshotFlow { scroll.isScrollInProgress }.collectLatest { scrolling ->
            if (scrolling) return@collectLatest
            delay(SettleDelay)
            val top = scroll.value
            val size = context.fieldHeight
            if (top <= 0 || top >= size) return@collectLatest
            scroll.animateScrollTo(if (top < size / 2 || context.hasQuery) 0 else size)
        }
    }
    CompositionLocalProvider(LocalSearchReveal provides context) {
        Column(
            modifier = modifier
                .onSizeChanged { context.viewportHeight = it.height }
                .verticalScroll(scroll),
            content = content,
        )
    }
}

@Composable
fun SearchRevealField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    placeholder: String = "Search",
    enabled: Boolean = true,
) {
    val context = LocalSearchReveal.current
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val focused by interaction.collectIsFocusedAsState()
    val focus = remember { FocusRequester() }
    SideEffect { context?.hasQuery = value.isNotEmpty() }
    LaunchedEffect(focused) {
        if (focused) context?.scroll?.animateScrollTo(0)
    }
    val textStyle = Typography.base.copy(color = colors.label)
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .onSizeChanged { context?.fieldHeight = it.height }
            .graphicsLayer { alpha = context?.reveal ?: 1f }
            .padding(start = 16.dp, end = 16.dp, bottom = 8.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(36.dp)
                .background(colors.control, RoundedCornerShape(Radius.lg))
                .padding(horizontal = 8.dp),
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(PhosphorIcons.Regular.MagnifyingGlass, contentDescription = null, size = 18.dp, tint = colors.labelSecondary)
            CompositionLocalProvider(
                LocalTextSelectionColors provides TextSelectionColors(colors.accent, colors.accent.copy(alpha = 0.3f)),
            ) {
                BasicTextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = modifier
                        .weight(1f)
                        .focusRequester(focus)
                        .semantics { contentDescription = placeholder },
                    enabled = enabled,
                    singleLine = true,
                    textStyle = textStyle,
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                    interactionSource = interaction,
                    cursorBrush = SolidColor(colors.accent),
                    decorationBox = { inner ->
                        Box(contentAlignment = Alignment.CenterStart) {
                            if (value.isEmpty()) {
                                BasicText(placeholder, style = textStyle.copy(color = colors.labelSecondary), maxLines = 1)
                            }
                            inner()
                        }
                    },
                )
            }
            if (value.isNotEmpty()) {
                Box(
                    modifier = Modifier
                        .size(28.dp)
                        .clickable(
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null,
                            role = Role.Button,
                            onClickLabel = null,
                        ) {
                            onValueChange("")
                            focus.requestFocus()
                        }
                        .semantics { contentDescription = "Clear search" },
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(PhosphorIcons.Fill.XCircle, contentDescription = null, size = 18.dp, tint = colors.labelSecondary)
                }
            }
        }
    }
}

@Composable
fun SearchRevealContent(
    modifier: Modifier = Modifier,
    content: @Composable ColumnScope.() -> Unit,
) {
    val context = LocalSearchReveal.current
    val minHeight = with(LocalDensity.current) { (context?.viewportHeight ?: 0).toDp() }
    Column(
        modifier = modifier
            .fillMaxWidth()
            .heightIn(min = minHeight),
        content = content,
    )
}
```

```kt title="kotlin/components/Content.kt"
package com.esuiss.ui.components

import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

val LocalContentStyle = compositionLocalOf { TextStyle.Default }

val LocalContentColor = compositionLocalOf { Color.Unspecified }

val LocalIconSize = compositionLocalOf { 20.dp }
```

```kt title="kotlin/components/Icon.kt"
package com.esuiss.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import com.esuiss.ui.theme.EsuissTheme

@Composable
fun Icon(
    imageVector: ImageVector,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    size: Dp = LocalIconSize.current,
    tint: Color = LocalContentColor.current.takeOrElse { EsuissTheme.colors.label },
) {
    Image(
        imageVector = imageVector,
        contentDescription = contentDescription,
        modifier = modifier.size(size),
        colorFilter = ColorFilter.tint(tint),
    )
}
```

4. Update the `com.esuiss.ui` package names to match your project.

## Usage

```tsx
import { SearchReveal, SearchRevealField, SearchRevealContent } from "@/components/interactions/search-reveal"
```

```tsx
<NotesExample count={12} />
```

Put a `SearchRevealField` first, then the list inside a `SearchRevealContent`, all inside `SearchReveal`. The field is controlled: pass `value` and update it in `onValueChange`, then filter your list with it.

`SearchRevealContent` is at least as tall as the scroll view, so the field can be hidden even when the list is short. Other `ScrollView` props, except `onScroll`, pass through to `SearchReveal`, and other `TextInput` props pass through to the field.

## Examples

### Short list

A three-item list that still hides the field.

![Preview](https://uim.suiss.app/previews/interactions-search-reveal--short-list.light.webp)

```tsx
import * as React from "react"
import { Pressable, View } from "react-native"
import { SearchReveal, SearchRevealContent, SearchRevealField } from "@/components/interactions/search-reveal"
import { Text } from "@/components/ui/text"

const allNotes = [
  { id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee" },
  { id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road" },
  { id: 3, title: "Book list", preview: "Three novels for the summer" },
  { id: 4, title: "Meeting notes", preview: "Ship the beta on Friday" },
  { id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf" },
  { id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry" },
  { id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday" },
  {
    id: 8,
    title: "Movies to watch",
    preview: "Two documentaries and a classic",
  },
  { id: 9, title: "Garden", preview: "Plant tomatoes after the frost" },
  { id: 10, title: "Packing list", preview: "Charger, passport, rain jacket" },
  { id: 11, title: "Podcast notes", preview: "Episode about city design" },
  { id: 12, title: "Budget", preview: "Rent, groceries, savings" },
]

function NotesExample({
  count,
  defaultQuery = "",
}: {
  count: number
  defaultQuery?: string
}) {
  const [query, setQuery] = React.useState(defaultQuery)
  const notes = allNotes
    .slice(0, count)
    .filter((note) =>
      `${note.title} ${note.preview}`
        .toLowerCase()
        .includes(query.trim().toLowerCase())
    )

  return (
    <View className="flex-1 overflow-hidden rounded-2xl border border-separator">
      <Text variant="h1" className="px-4 pt-4 pb-2">
        Notes
      </Text>
      <SearchReveal>
        <SearchRevealField value={query} onValueChange={setQuery} />
        <SearchRevealContent>
          {notes.length === 0 ? (
            <Text className="px-4 py-16 text-center text-sm text-label-secondary">
              No results for “{query}”
            </Text>
          ) : (
            <View className="mx-4 overflow-hidden rounded-xl bg-surface-secondary">
              {notes.map((note, index) => (
                <Pressable
                  key={note.id}
                  className={
                    index > 0
                      ? "border-t border-separator px-4 py-3 active:bg-item-pressed"
                      : "px-4 py-3 active:bg-item-pressed"
                  }
                >
                  <Text numberOfLines={1} className="font-semibold">
                    {note.title}
                  </Text>
                  <Text
                    numberOfLines={1}
                    className="text-sm text-label-secondary"
                  >
                    {note.preview}
                  </Text>
                </Pressable>
              ))}
            </View>
          )}
          <Text className="px-4 py-3 text-center text-xs text-label-secondary">
            {notes.length} {notes.length === 1 ? "note" : "notes"}
          </Text>
        </SearchRevealContent>
      </SearchReveal>
    </View>
  )
}

export function SearchRevealShortListExample() {
  return (
    <NotesExample count={3} />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct SearchRevealShortListExample: View {
  var body: some View {
    SearchRevealNotes(count: 3)
  }
}

struct SearchRevealNote: Identifiable {
  let id: Int
  let title: String
  let preview: String
}

let searchRevealNotes = [
  SearchRevealNote(id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee"),
  SearchRevealNote(id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road"),
  SearchRevealNote(id: 3, title: "Book list", preview: "Three novels for the summer"),
  SearchRevealNote(id: 4, title: "Meeting notes", preview: "Ship the beta on Friday"),
  SearchRevealNote(id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf"),
  SearchRevealNote(id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry"),
  SearchRevealNote(id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday"),
  SearchRevealNote(id: 8, title: "Movies to watch", preview: "Two documentaries and a classic"),
  SearchRevealNote(id: 9, title: "Garden", preview: "Plant tomatoes after the frost"),
  SearchRevealNote(id: 10, title: "Packing list", preview: "Charger, passport, rain jacket"),
  SearchRevealNote(id: 11, title: "Podcast notes", preview: "Episode about city design"),
  SearchRevealNote(id: 12, title: "Budget", preview: "Rent, groceries, savings"),
]

struct SearchRevealNotes: View {
  let count: Int

  @State private var query: String

  init(count: Int, query: String = "") {
    self.count = count
    _query = State(initialValue: query)
  }

  var notes: [SearchRevealNote] {
    let needle = query.trimmingCharacters(in: .whitespaces).lowercased()
    return searchRevealNotes.prefix(count).filter { note in
      needle.isEmpty || "\(note.title) \(note.preview)".lowercased().contains(needle)
    }
  }

  var body: some View {
    let notes = notes
    let shape = RoundedRectangle(cornerRadius: Radius.xl2, style: .continuous)
    VStack(alignment: .leading, spacing: 0) {
      Text("Notes")
        .textVariant(.h1)
        .padding(.horizontal, 16)
        .padding(.top, 16)
        .padding(.bottom, 8)
      SearchReveal {
        SearchRevealField(text: $query)
        SearchRevealContent {
          if notes.isEmpty {
            Text(verbatim: "No results for “\(query)”")
              .textStyle(.sm)
              .foregroundStyle(Color.labelSecondary)
              .multilineTextAlignment(.center)
              .padding(.horizontal, 16)
              .padding(.vertical, 64)
              .frame(maxWidth: .infinity)
          } else {
            VStack(spacing: 0) {
              ForEach(Array(notes.enumerated()), id: \.element.id) { index, note in
                Button {} label: {
                  VStack(alignment: .leading, spacing: 0) {
                    Text(verbatim: note.title)
                      .textStyle(.base, weight: .semibold)
                      .foregroundStyle(Color.label)
                      .lineLimit(1)
                    Text(verbatim: note.preview)
                      .textStyle(.sm)
                      .foregroundStyle(Color.labelSecondary)
                      .lineLimit(1)
                  }
                  .padding(.horizontal, 16)
                  .padding(.vertical, 12)
                  .frame(maxWidth: .infinity, alignment: .leading)
                  .contentShape(Rectangle())
                }
                .buttonStyle(SearchRevealRowStyle())
                .overlay(alignment: .top) {
                  if index > 0 {
                    Color.separator.frame(height: 1)
                  }
                }
              }
            }
            .background(Color.surfaceSecondary)
            .clipShape(RoundedRectangle(cornerRadius: Radius.xl, style: .continuous))
            .padding(.horizontal, 16)
          }
          Text(verbatim: "\(notes.count) \(notes.count == 1 ? "note" : "notes")")
            .textStyle(.xs)
            .foregroundStyle(Color.labelSecondary)
            .multilineTextAlignment(.center)
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
            .frame(maxWidth: .infinity)
        }
      }
    }
    .clipShape(shape)
    .overlay { shape.strokeBorder(Color.separator) }
    .containerRelativeFrame(.vertical) { height, _ in height - 32 }
  }
}

struct SearchRevealRowStyle: ButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .background(configuration.isPressed ? Color.itemPressed : .clear)
  }
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.TextVariant
import com.esuiss.ui.interactions.SearchReveal
import com.esuiss.ui.interactions.SearchRevealContent
import com.esuiss.ui.interactions.SearchRevealField
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

@Composable
fun SearchRevealShortListExample() {
    SearchRevealNotes(count = 3)
}

class SearchRevealNote(val id: Int, val title: String, val preview: String)

val searchRevealAllNotes = listOf(
    SearchRevealNote(1, "Groceries", "Milk, eggs, bread, coffee"),
    SearchRevealNote(2, "Trip ideas", "Lisbon, Porto, the coast road"),
    SearchRevealNote(3, "Book list", "Three novels for the summer"),
    SearchRevealNote(4, "Meeting notes", "Ship the beta on Friday"),
    SearchRevealNote(5, "Gift ideas", "Headphones, a plant, a scarf"),
    SearchRevealNote(6, "Recipes", "Lemon pasta and a quick curry"),
    SearchRevealNote(7, "Workout plan", "Run on Monday, swim on Thursday"),
    SearchRevealNote(8, "Movies to watch", "Two documentaries and a classic"),
    SearchRevealNote(9, "Garden", "Plant tomatoes after the frost"),
    SearchRevealNote(10, "Packing list", "Charger, passport, rain jacket"),
    SearchRevealNote(11, "Podcast notes", "Episode about city design"),
    SearchRevealNote(12, "Budget", "Rent, groceries, savings"),
)

@Composable
fun SearchRevealNotes(count: Int, defaultQuery: String = "") {
    val colors = EsuissTheme.colors
    var query by rememberSaveable { mutableStateOf(defaultQuery) }
    val needle = query.trim().lowercase()
    val notes = searchRevealAllNotes.take(count).filter { "${it.title} ${it.preview}".lowercase().contains(needle) }
    val shape = RoundedCornerShape(Radius.xl2)
    Column(
        Modifier
            .fillMaxWidth()
            .height(600.dp)
            .clip(shape)
            .border(1.dp, colors.separator, shape),
    ) {
        Text("Notes", modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp), variant = TextVariant.H1)
        SearchReveal(Modifier.weight(1f)) {
            SearchRevealField(value = query, onValueChange = { query = it })
            SearchRevealContent {
                if (notes.isEmpty()) {
                    Text(
                        "No results for “$query”",
                        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 64.dp),
                        style = Typography.sm.copy(color = colors.labelSecondary),
                        textAlign = TextAlign.Center,
                    )
                } else {
                    Column(
                        Modifier
                            .padding(horizontal = 16.dp)
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(Radius.xl))
                            .background(colors.surfaceSecondary),
                    ) {
                        notes.forEachIndexed { index, note ->
                            if (index > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(colors.separator))
                            SearchRevealRow(note)
                        }
                    }
                }
                Text(
                    "${notes.size} ${if (notes.size == 1) "note" else "notes"}",
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
                    style = Typography.xs.copy(color = colors.labelSecondary),
                    textAlign = TextAlign.Center,
                )
            }
        }
    }
}

@Composable
fun SearchRevealRow(note: SearchRevealNote) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    Column(
        Modifier
            .fillMaxWidth()
            .background(if (pressed) colors.itemPressed else Color.Transparent)
            .clickable(interactionSource = interaction, indication = null, role = Role.Button) {}
            .padding(horizontal = 16.dp, vertical = 12.dp),
    ) {
        Text(
            note.title,
            style = Typography.base.copy(fontWeight = FontWeight.SemiBold),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Text(
            note.preview,
            style = Typography.sm.copy(color = colors.labelSecondary),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}
```

### With query

Starts with a query, so the field is visible and the list is filtered.

![Preview](https://uim.suiss.app/previews/interactions-search-reveal--with-query.light.webp)

```tsx
import * as React from "react"
import { Pressable, View } from "react-native"
import { SearchReveal, SearchRevealContent, SearchRevealField } from "@/components/interactions/search-reveal"
import { Text } from "@/components/ui/text"

const allNotes = [
  { id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee" },
  { id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road" },
  { id: 3, title: "Book list", preview: "Three novels for the summer" },
  { id: 4, title: "Meeting notes", preview: "Ship the beta on Friday" },
  { id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf" },
  { id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry" },
  { id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday" },
  {
    id: 8,
    title: "Movies to watch",
    preview: "Two documentaries and a classic",
  },
  { id: 9, title: "Garden", preview: "Plant tomatoes after the frost" },
  { id: 10, title: "Packing list", preview: "Charger, passport, rain jacket" },
  { id: 11, title: "Podcast notes", preview: "Episode about city design" },
  { id: 12, title: "Budget", preview: "Rent, groceries, savings" },
]

function NotesExample({
  count,
  defaultQuery = "",
}: {
  count: number
  defaultQuery?: string
}) {
  const [query, setQuery] = React.useState(defaultQuery)
  const notes = allNotes
    .slice(0, count)
    .filter((note) =>
      `${note.title} ${note.preview}`
        .toLowerCase()
        .includes(query.trim().toLowerCase())
    )

  return (
    <View className="flex-1 overflow-hidden rounded-2xl border border-separator">
      <Text variant="h1" className="px-4 pt-4 pb-2">
        Notes
      </Text>
      <SearchReveal>
        <SearchRevealField value={query} onValueChange={setQuery} />
        <SearchRevealContent>
          {notes.length === 0 ? (
            <Text className="px-4 py-16 text-center text-sm text-label-secondary">
              No results for “{query}”
            </Text>
          ) : (
            <View className="mx-4 overflow-hidden rounded-xl bg-surface-secondary">
              {notes.map((note, index) => (
                <Pressable
                  key={note.id}
                  className={
                    index > 0
                      ? "border-t border-separator px-4 py-3 active:bg-item-pressed"
                      : "px-4 py-3 active:bg-item-pressed"
                  }
                >
                  <Text numberOfLines={1} className="font-semibold">
                    {note.title}
                  </Text>
                  <Text
                    numberOfLines={1}
                    className="text-sm text-label-secondary"
                  >
                    {note.preview}
                  </Text>
                </Pressable>
              ))}
            </View>
          )}
          <Text className="px-4 py-3 text-center text-xs text-label-secondary">
            {notes.length} {notes.length === 1 ? "note" : "notes"}
          </Text>
        </SearchRevealContent>
      </SearchReveal>
    </View>
  )
}

export function SearchRevealWithQueryExample() {
  return (
    <NotesExample count={12} defaultQuery="porto" />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct SearchRevealWithQueryExample: View {
  var body: some View {
    SearchRevealNotes(count: 12, query: "porto")
  }
}

struct SearchRevealNote: Identifiable {
  let id: Int
  let title: String
  let preview: String
}

let searchRevealNotes = [
  SearchRevealNote(id: 1, title: "Groceries", preview: "Milk, eggs, bread, coffee"),
  SearchRevealNote(id: 2, title: "Trip ideas", preview: "Lisbon, Porto, the coast road"),
  SearchRevealNote(id: 3, title: "Book list", preview: "Three novels for the summer"),
  SearchRevealNote(id: 4, title: "Meeting notes", preview: "Ship the beta on Friday"),
  SearchRevealNote(id: 5, title: "Gift ideas", preview: "Headphones, a plant, a scarf"),
  SearchRevealNote(id: 6, title: "Recipes", preview: "Lemon pasta and a quick curry"),
  SearchRevealNote(id: 7, title: "Workout plan", preview: "Run on Monday, swim on Thursday"),
  SearchRevealNote(id: 8, title: "Movies to watch", preview: "Two documentaries and a classic"),
  SearchRevealNote(id: 9, title: "Garden", preview: "Plant tomatoes after the frost"),
  SearchRevealNote(id: 10, title: "Packing list", preview: "Charger, passport, rain jacket"),
  SearchRevealNote(id: 11, title: "Podcast notes", preview: "Episode about city design"),
  SearchRevealNote(id: 12, title: "Budget", preview: "Rent, groceries, savings"),
]

struct SearchRevealNotes: View {
  let count: Int

  @State private var query: String

  init(count: Int, query: String = "") {
    self.count = count
    _query = State(initialValue: query)
  }

  var notes: [SearchRevealNote] {
    let needle = query.trimmingCharacters(in: .whitespaces).lowercased()
    return searchRevealNotes.prefix(count).filter { note in
      needle.isEmpty || "\(note.title) \(note.preview)".lowercased().contains(needle)
    }
  }

  var body: some View {
    let notes = notes
    let shape = RoundedRectangle(cornerRadius: Radius.xl2, style: .continuous)
    VStack(alignment: .leading, spacing: 0) {
      Text("Notes")
        .textVariant(.h1)
        .padding(.horizontal, 16)
        .padding(.top, 16)
        .padding(.bottom, 8)
      SearchReveal {
        SearchRevealField(text: $query)
        SearchRevealContent {
          if notes.isEmpty {
            Text(verbatim: "No results for “\(query)”")
              .textStyle(.sm)
              .foregroundStyle(Color.labelSecondary)
              .multilineTextAlignment(.center)
              .padding(.horizontal, 16)
              .padding(.vertical, 64)
              .frame(maxWidth: .infinity)
          } else {
            VStack(spacing: 0) {
              ForEach(Array(notes.enumerated()), id: \.element.id) { index, note in
                Button {} label: {
                  VStack(alignment: .leading, spacing: 0) {
                    Text(verbatim: note.title)
                      .textStyle(.base, weight: .semibold)
                      .foregroundStyle(Color.label)
                      .lineLimit(1)
                    Text(verbatim: note.preview)
                      .textStyle(.sm)
                      .foregroundStyle(Color.labelSecondary)
                      .lineLimit(1)
                  }
                  .padding(.horizontal, 16)
                  .padding(.vertical, 12)
                  .frame(maxWidth: .infinity, alignment: .leading)
                  .contentShape(Rectangle())
                }
                .buttonStyle(SearchRevealRowStyle())
                .overlay(alignment: .top) {
                  if index > 0 {
                    Color.separator.frame(height: 1)
                  }
                }
              }
            }
            .background(Color.surfaceSecondary)
            .clipShape(RoundedRectangle(cornerRadius: Radius.xl, style: .continuous))
            .padding(.horizontal, 16)
          }
          Text(verbatim: "\(notes.count) \(notes.count == 1 ? "note" : "notes")")
            .textStyle(.xs)
            .foregroundStyle(Color.labelSecondary)
            .multilineTextAlignment(.center)
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
            .frame(maxWidth: .infinity)
        }
      }
    }
    .clipShape(shape)
    .overlay { shape.strokeBorder(Color.separator) }
    .containerRelativeFrame(.vertical) { height, _ in height - 32 }
  }
}

struct SearchRevealRowStyle: ButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .background(configuration.isPressed ? Color.itemPressed : .clear)
  }
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.TextVariant
import com.esuiss.ui.interactions.SearchReveal
import com.esuiss.ui.interactions.SearchRevealContent
import com.esuiss.ui.interactions.SearchRevealField
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

@Composable
fun SearchRevealWithQueryExample() {
    SearchRevealNotes(count = 12, defaultQuery = "porto")
}

class SearchRevealNote(val id: Int, val title: String, val preview: String)

val searchRevealAllNotes = listOf(
    SearchRevealNote(1, "Groceries", "Milk, eggs, bread, coffee"),
    SearchRevealNote(2, "Trip ideas", "Lisbon, Porto, the coast road"),
    SearchRevealNote(3, "Book list", "Three novels for the summer"),
    SearchRevealNote(4, "Meeting notes", "Ship the beta on Friday"),
    SearchRevealNote(5, "Gift ideas", "Headphones, a plant, a scarf"),
    SearchRevealNote(6, "Recipes", "Lemon pasta and a quick curry"),
    SearchRevealNote(7, "Workout plan", "Run on Monday, swim on Thursday"),
    SearchRevealNote(8, "Movies to watch", "Two documentaries and a classic"),
    SearchRevealNote(9, "Garden", "Plant tomatoes after the frost"),
    SearchRevealNote(10, "Packing list", "Charger, passport, rain jacket"),
    SearchRevealNote(11, "Podcast notes", "Episode about city design"),
    SearchRevealNote(12, "Budget", "Rent, groceries, savings"),
)

@Composable
fun SearchRevealNotes(count: Int, defaultQuery: String = "") {
    val colors = EsuissTheme.colors
    var query by rememberSaveable { mutableStateOf(defaultQuery) }
    val needle = query.trim().lowercase()
    val notes = searchRevealAllNotes.take(count).filter { "${it.title} ${it.preview}".lowercase().contains(needle) }
    val shape = RoundedCornerShape(Radius.xl2)
    Column(
        Modifier
            .fillMaxWidth()
            .height(600.dp)
            .clip(shape)
            .border(1.dp, colors.separator, shape),
    ) {
        Text("Notes", modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp), variant = TextVariant.H1)
        SearchReveal(Modifier.weight(1f)) {
            SearchRevealField(value = query, onValueChange = { query = it })
            SearchRevealContent {
                if (notes.isEmpty()) {
                    Text(
                        "No results for “$query”",
                        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 64.dp),
                        style = Typography.sm.copy(color = colors.labelSecondary),
                        textAlign = TextAlign.Center,
                    )
                } else {
                    Column(
                        Modifier
                            .padding(horizontal = 16.dp)
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(Radius.xl))
                            .background(colors.surfaceSecondary),
                    ) {
                        notes.forEachIndexed { index, note ->
                            if (index > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(colors.separator))
                            SearchRevealRow(note)
                        }
                    }
                }
                Text(
                    "${notes.size} ${if (notes.size == 1) "note" else "notes"}",
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
                    style = Typography.xs.copy(color = colors.labelSecondary),
                    textAlign = TextAlign.Center,
                )
            }
        }
    }
}

@Composable
fun SearchRevealRow(note: SearchRevealNote) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    Column(
        Modifier
            .fillMaxWidth()
            .background(if (pressed) colors.itemPressed else Color.Transparent)
            .clickable(interactionSource = interaction, indication = null, role = Role.Button) {}
            .padding(horizontal = 16.dp, vertical = 12.dp),
    ) {
        Text(
            note.title,
            style = Typography.base.copy(fontWeight = FontWeight.SemiBold),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Text(
            note.preview,
            style = Typography.sm.copy(color = colors.labelSecondary),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}
```

## API Reference

### SearchReveal

The scroll view that hides and reveals the field.

### SearchRevealField

The search input with a clear button.

### SearchRevealContent

The list area, at least one screen tall.

## Accessibility

- The input has the `searchbox` role and is labelled by `placeholder`.
- The clear button is labelled `Clear search` and returns focus to the input.

## Notes

- The field uses `bg-control` with `label-secondary` placeholder and icons.
- Autocorrect and autocapitalization are off, and the return key reads `search`.
- Taps on the list work while the keyboard is open.
