v0.1 public beta early access on GitHub
Home / Screens / chat-new-message
Screen template

New Message Screen

Contact picker sheet with a search field, new-group row, and recent plus alphabetically sectioned contacts with sticky headers and presence dots

pro Expo Go ✓ iosandroid gestures: tap · scroll haptics: light
$ npx lumioui add chat-new-message
import { NewMessageScreen } from "@/screens/chat/new-message";
Native packages installed6
@lumioui/ui@latest@lumioui/core@latestreact-native-safe-area-context@*react-native-reanimated@*react-native-svg@*nativewind@*
chat/new-message.tsxsource · yours to edit
import * as React from "react";
import { useMemo, useState } from "react";
import { View, SectionList, ScrollView, TextInput } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
  Easing,
  runOnJS,
  useSharedValue,
  useAnimatedStyle,
  withDelay,
  withTiming,
} from "react-native-reanimated";
import { Avatar, Button, EmptyState, Glass, Icon, Text } from "@lumioui/ui";
import { Press } from "../shared";
import { AnimatedPressable, ease, timing, useHaptic, usePressAnimation, useReducedMotion, } from "@lumioui/core";

export interface Contact {
  id: string;
  name: string;
  /** Handle or phone line under the name — "@diegoruiz", "+1 415…". */
  handle?: string;
  avatarUrl?: string;
  online?: boolean;
}

export interface NewMessageScreenProps {
  contacts?: Contact[];
  /** IDs repeated in a "Recent" section above the alphabetical list —
   *  contacts still appear in their letter group (iOS Favorites idiom). */
  recentIds?: string[];
  onContactPress?: (contact: Contact) => void;
  /** "New group" row pinned under the search field. */
  onNewGroup?: () => void;
  onSearch?: (query: string) => void;
  /** Sheet-style close affordance in the top-left. */
  onCancel?: () => void;
}

const DEFAULT_CONTACTS: Contact[] = [
  { id: "amara", name: "Amara Chen", handle: "@amarachen", online: true, avatarUrl: "https://i.pravatar.cc/150?img=9" },
  { id: "ava", name: "Ava Martinez", handle: "@avamartinez", online: true, avatarUrl: "https://i.pravatar.cc/150?img=44" },
  { id: "diego", name: "Diego Ruiz", handle: "@diegoruiz", online: true, avatarUrl: "https://i.pravatar.cc/150?img=53" },
  { id: "jonah", name: "Jonah Reyes", handle: "@jonahreyes", avatarUrl: "https://i.pravatar.cc/150?img=11" },
  { id: "kai", name: "Kai Tanaka", handle: "@kaitanaka", avatarUrl: "https://i.pravatar.cc/150?img=33" },
  { id: "leo", name: "Leo Fischer", handle: "@leofischer", online: true, avatarUrl: "https://i.pravatar.cc/150?img=15" },
  { id: "maya", name: "Maya Chen", handle: "@mayachen", online: true, avatarUrl: "https://i.pravatar.cc/150?img=47" },
  { id: "nina", name: "Nina Petrova", handle: "@ninapetrova", avatarUrl: "https://i.pravatar.cc/150?img=20" },
  { id: "priya", name: "Priya Nair", handle: "@priyanair", avatarUrl: "https://i.pravatar.cc/150?img=32" },
  { id: "sakura", name: "Sakura Ramen", handle: "Business · deliveries", avatarUrl: "https://images.unsplash.com/photo-1569718212165-3a8278d5f624?w=150&h=150&fit=crop&q=70&auto=format" },
  { id: "sam", name: "Sam Okafor", handle: "@samokafor", avatarUrl: "https://i.pravatar.cc/150?img=59" },
  { id: "tom", name: "Tom Reed", handle: "@tomreed", online: true, avatarUrl: "https://i.pravatar.cc/150?img=12" },
];

const DEFAULT_RECENT_IDS = ["maya", "diego", "tom"];

/** Staggered mount — rows rise and fade in sequence. Choreography data
 *  (like EmptyState's 90ms cadence), capped so lazily-mounted rows never
 *  wait on a deep index. */
const MOUNT_STAGGER = 40;
const MOUNT_MAX_DELAY = 280;
const MOUNT_TIMING = { duration: timing.normal.duration, easing: Easing.bezier(...ease.out) };

/** Fade + small rise on mount, delayed by index. Reduced motion: fade only. */
function MountIn({
  index,
  className,
  children,
}: {
  index: number;
  className?: string;
  children: React.ReactNode;
}) {
  const reduce = useReducedMotion();
  const t = useSharedValue(reduce ? 1 : 0);
  React.useEffect(() => {
    if (reduce) {
      t.value = 1;
      return;
    }
    t.value = withDelay(
      Math.min(index * MOUNT_STAGGER, MOUNT_MAX_DELAY),
      withTiming(1, MOUNT_TIMING)
    );
  }, [index, reduce, t]);
  const style = useAnimatedStyle(() => ({
    opacity: t.value,
    transform: [{ translateY: (1 - t.value) * 10 }],
  }));
  return (
    <Animated.View style={style} className={className}>
      {children}
    </Animated.View>
  );
}

/** Contact row — avatar with presence dot, name, handle. Dips like an
 *  iOS cell so the feedback still lands under a scrolling thumb. */
function ContactRow({
  contact,
  onPress,
}: {
  contact: Contact;
  onPress?: (c: Contact) => void;
}) {
  const haptics = useHaptic();
  const press = usePressAnimation({ pressedScale: 0.98, pressedOpacity: 0.75, fast: true });
  return (
    <AnimatedPressable
      onPress={() => {
        haptics.light();
        onPress?.(contact);
      }}
      onPressIn={press.onPressIn}
      onPressOut={press.onPressOut}
      style={press.animatedStyle}
      accessibilityRole="button"
      accessibilityLabel={`Message ${contact.name}${contact.online ? ", online" : ""}`}
      className="flex-row items-center gap-3 px-6 py-2.5"
    >
      <Avatar
        size="md"
        source={contact.avatarUrl ? { uri: contact.avatarUrl } : undefined}
        fallback={contact.name}
        status={contact.online ? "online" : undefined}
        alt={`${contact.name}'s avatar`}
      />
      <View className="flex-1 gap-0.5">
        <Text variant="small" numberOfLines={1} className="font-medium">
          {contact.name}
        </Text>
        {contact.handle ? (
          <Text variant="muted" numberOfLines={1} className="text-xs">
            {contact.handle}
          </Text>
        ) : null}
      </View>
    </AnimatedPressable>
  );
}

interface ContactSection {
  title: string;
  data: Contact[];
}

/** Groups contacts into A–Z letter buckets. Recents live in the avatar
 *  rail above the list, not a duplicated section. */
function groupContacts(contacts: Contact[], recentIds: string[]): ContactSection[] {
  const sections: ContactSection[] = [];

  const letters = new Map<string, Contact[]>();
  const recentSet = new Set(recentIds);
  for (const c of [...contacts]
    .filter((c) => !recentSet.has(c.id))
    .sort((a, b) => a.name.localeCompare(b.name))) {
    const letter = (c.name.trim()[0] ?? "#").toUpperCase();
    const bucket = letters.get(letter);
    if (bucket) bucket.push(c);
    else letters.set(letter, [c]);
  }
  for (const [title, data] of [...letters.entries()].sort(([a], [b]) =>
    a.localeCompare(b)
  )) {
    sections.push({ title, data });
  }
  return sections;
}

/** Contact rail chip — large avatar + first name, press feedback via the
 *  shared press animation. Sits above the indexed list. */
function RecentChip({
  contact,
  onPress,
}: {
  contact: Contact;
  onPress?: (c: Contact) => void;
}) {
  const haptics = useHaptic();
  const press = usePressAnimation({ pressedScale: 0.94, pressedOpacity: 0.8, fast: true });
  return (
    <AnimatedPressable
      onPress={() => {
        haptics.light();
        onPress?.(contact);
      }}
      onPressIn={press.onPressIn}
      onPressOut={press.onPressOut}
      style={press.animatedStyle}
      accessibilityRole="button"
      accessibilityLabel={`Message ${contact.name}${contact.online ? ", online" : ""}`}
      className="w-16 items-center gap-1.5"
    >
      <Avatar
        size="xl"
        source={contact.avatarUrl ? { uri: contact.avatarUrl } : undefined}
        fallback={contact.name}
        status={contact.online ? "online" : undefined}
        alt={`${contact.name}'s avatar`}
      />
      <Text variant="muted" numberOfLines={1} className="text-xs">
        {contact.name.split(" ")[0]}
      </Text>
    </AnimatedPressable>
  );
}
RecentChip.displayName = "RecentChip";

/** New message — a contact picker sheet: search field, "Recent" avatar
 *  rail, "New group" row, then alphabetically-sectioned contacts with
 *  presence dots. */
export function NewMessageScreen({
  contacts = DEFAULT_CONTACTS,
  recentIds = DEFAULT_RECENT_IDS,
  onContactPress,
  onNewGroup,
  onSearch,
  onCancel,
}: NewMessageScreenProps) {
  const haptics = useHaptic();
  const insets = useSafeAreaInsets();
  const [query, setQuery] = useState("");
  const groupPress = usePressAnimation({ pressedScale: 0.98, pressedOpacity: 0.75, fast: true });
  // Header search — the icon pill expands leftward into a full search
  // bar; `open` drives the width, `searchOpen` keeps it mounted until
  // the collapse finishes.
  const [searchOpen, setSearchOpen] = useState(false);
  const [rowW, setRowW] = useState(0);
  const open = useSharedValue(0);
  const inputRef = React.useRef<TextInput>(null);

  const openSearch = () => {
    setSearchOpen(true);
    open.value = withTiming(1, { duration: 300, easing: Easing.out(Easing.cubic) });
  };
  const closeSearch = () => {
    inputRef.current?.blur();
    setQuery("");
    onSearch?.("");
    open.value = withTiming(0, { duration: 260, easing: Easing.in(Easing.cubic) }, (finished) => {
      if (finished) runOnJS(setSearchOpen)(false);
    });
  };
  const searchStyle = useAnimatedStyle(() => ({ width: rowW * open.value }));
  const chromeStyle = useAnimatedStyle(() => ({ opacity: 1 - open.value }));

  React.useEffect(() => {
    if (searchOpen) inputRef.current?.focus();
  }, [searchOpen]);

  const q = query.trim().toLowerCase();
  const searching = q.length > 0;
  const visible = useMemo(
    () =>
      searching
        ? contacts.filter(
            (c) =>
              c.name.toLowerCase().includes(q) ||
              (c.handle ?? "").toLowerCase().includes(q)
          )
        : contacts,
    [searching, q, contacts]
  );

  // Searching flattens to one unsectioned result list — match order is the
  // ranking, letter buckets would just add noise.
  const sections = useMemo(
    () =>
      searching
        ? [{ title: "Contacts", data: visible }]
        : groupContacts(visible, recentIds),
    [searching, visible, recentIds]
  );

  return (
    <SafeAreaView className="flex-1 bg-[#F4F5F9] dark:bg-[#111114]" edges={["top"]}>
      <SectionList
        sections={sections}
        keyExtractor={(item) => `${item.id}`}
        className="flex-1"
        contentContainerStyle={{ paddingTop: insets.top + 60, paddingBottom: insets.bottom + 16 }}
        ListHeaderComponent={
          <View>
            {/* Recents rail — the people you actually message, as big
                horizontally-scrolling avatars. The 2024+ contact-picker idiom
                (iMessage / WhatsApp share sheet) replaces a duplicate "Recent"
                list section. */}
            {!searching && recentIds.length > 0 ? (
              <View className="pb-1">
                <Text
                  variant="muted"
                  className="px-6 pb-2 pt-1 text-xs font-semibold uppercase tracking-wider"
                  accessibilityRole="header"
                >
                  Recent
                </Text>
                <ScrollView
                  horizontal
                  showsHorizontalScrollIndicator={false}
                  contentContainerClassName="gap-4 px-6"
                >
                  {recentIds
                    .map((id) => contacts.find((c) => c.id === id))
                    .filter((c): c is Contact => !!c)
                    .map((c) => (
                      <RecentChip key={c.id} contact={c} onPress={onContactPress} />
                    ))}
                </ScrollView>
              </View>
            ) : null}

            {/* New group — pinned action above the contact sections. */}
            {onNewGroup ? (
              <AnimatedPressable
                onPress={() => {
                  haptics.light();
                  onNewGroup();
                }}
                onPressIn={groupPress.onPressIn}
                onPressOut={groupPress.onPressOut}
                style={groupPress.animatedStyle}
                accessibilityRole="button"
                accessibilityLabel="Start a new group"
                className="flex-row items-center gap-3 px-6 py-3"
              >
                <View className="h-10 w-10 items-center justify-center rounded-full bg-[#BEF04C]">
                  <Icon name="users" size="md" color="#1B1B26" />
                </View>
                <Text variant="small" className="flex-1 font-semibold">
                  New group
                </Text>
                <Icon name="chevron-right" size="sm" color="mutedForeground" />
              </AnimatedPressable>
            ) : null}
          </View>
        }
        showsVerticalScrollIndicator={false}
        // Letter headers pin while you scroll — the iOS Contacts idiom.
        stickySectionHeadersEnabled
        keyboardShouldPersistTaps="handled"
        renderSectionHeader={({ section }) =>
          // Skip the bare "Contacts" label that wraps flattened search hits.
          searching ? null : (
            <Text
              variant="muted"
              // Sticky headers must paint the flow canvas — bg-background
              // ignores the chat World's tint and reads as a stray band.
              className="bg-[#F4F5F9] px-6 pb-1 pt-4 text-xs font-semibold uppercase tracking-wider dark:bg-[#111114]"
              accessibilityRole="header"
            >
              {section.title}
            </Text>
          )
        }
        ItemSeparatorComponent={() => (
          // Align with the text column: px-6 (1.5rem) + avatar h-10
          // (2.5rem) + gap-3 (0.75rem) = 4.75rem.
          <View className="ml-[4.75rem] h-px bg-border" accessible={false} />
        )}
        ListEmptyComponent={
          <EmptyState
            variant={searching ? "search" : "default"}
            title={searching ? "No contacts found" : "No contacts"}
            description={
              searching
                ? `Nobody matches "${query.trim()}".`
                : "People you add will appear here."
            }
          />
        }
        ListFooterComponent={
          // Invite footer — contact pickers always end with the
          // "your friend isn't here yet" escape hatch.
          <View className="mx-6 mt-4 flex-row items-center gap-3 overflow-hidden rounded-2xl px-4 py-3.5">
            <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
            <View className="h-10 w-10 items-center justify-center rounded-full bg-[#BEF04C]">
              <Icon name="user-plus" size="sm" color="#1B1B26" />
            </View>
            <View className="flex-1">
              <Text variant="small" className="font-medium">
                Invite friends to Lumio
              </Text>
              <Text variant="muted" className="text-xs">
                Share a link — they join your contacts when they sign up.
              </Text>
            </View>
            <Icon name="chevron-right" size="sm" color="mutedForeground" />
          </View>
        }
        renderItem={({ item, index }) => (
          <MountIn index={index}>
            <ContactRow contact={item} onPress={onContactPress} />
          </MountIn>
        )}
      />

      {/* Floating chrome — three frosted pills on one line: close, title,
          search icon. Tapping search expands the right pill leftward into
          a full search bar; the list scrolls underneath. */}
      <View
        className="absolute inset-x-4 z-10"
        style={{ top: insets.top + 8 }}
        pointerEvents="box-none"
        onLayout={(e) => setRowW(e.nativeEvent.layout.width)}
      >
        <Animated.View style={chromeStyle} className="flex-row items-center justify-between gap-2">
          {onCancel ? (
            <Glass
              effect="regular"
              className="h-11 w-11 items-center justify-center rounded-full"
            >
              <Button
                variant="ghost"
                size="icon"
                haptic="light"
                onPress={onCancel}
                accessibilityLabel="Cancel"
                className="h-9 w-9"
              >
                <Icon name="x" size="md" color="foreground" />
              </Button>
            </Glass>
          ) : (
            <View className="w-11" />
          )}
          <Glass
            effect="regular"
            className="h-11 w-11 items-center justify-center rounded-full"
          >
            <Press
              haptic="light"
              onPress={openSearch}
              accessibilityRole="button"
              accessibilityLabel="Search contacts"
              className="h-11 w-11 items-center justify-center"
            >
              <Icon name="search" size="sm" color="foreground" />
            </Press>
          </Glass>
        </Animated.View>
        <Animated.View style={chromeStyle} pointerEvents="none" className="absolute inset-0 items-center justify-center">
          <Glass
            effect="regular"
            className="h-11 flex-row items-center justify-center rounded-full px-5"
          >
            <Text accessibilityRole="header" className="text-sm font-bold tracking-tight">
              New Message
            </Text>
          </Glass>
        </Animated.View>

        {/* Expanding search bar — grows leftward out of the icon pill,
            covers the row, and takes focus while the list filters live. */}
        {searchOpen ? (
          <Animated.View
            style={searchStyle}
            className="absolute right-0 top-0 h-11 overflow-hidden"
          >
            <View className="h-11 flex-row items-center gap-2" style={{ width: rowW }}>
              {/* Solid surface, not Glass — a real input behind the
                  backdrop-filter material paints its text smeared. */}
              <View className="h-11 flex-1 flex-row items-center rounded-full bg-white px-3 dark:bg-[#1A1A20]">
                <Icon name="search" size="sm" color="mutedForeground" />
                <TextInput
                  ref={inputRef}
                  value={query}
                  onChangeText={(text) => {
                    setQuery(text);
                    onSearch?.(text);
                  }}
                  placeholder="Search name or handle…"
                  placeholderTextColor="#8A8A93"
                  returnKeyType="search"
                  accessibilityLabel="Search contacts"
                  autoFocus
                  className="flex-1 px-2 text-base text-foreground outline-none"
                />
              </View>
              <View className="h-11 w-11 items-center justify-center rounded-full bg-white dark:bg-[#1A1A20]">
                <Press
                  haptic="light"
                  onPress={closeSearch}
                  accessibilityRole="button"
                  accessibilityLabel="Close search"
                  className="h-11 w-11 items-center justify-center"
                >
                  <Icon name="x" size="sm" color="foreground" />
                </Press>
              </View>
            </View>
          </Animated.View>
        ) : null}
      </View>
    </SafeAreaView>
  );
}
NewMessageScreen.displayName = "NewMessageScreen";
agent prompt — paste into Claude Code, Cursor, Devin…
Recreate the "New Message Screen" screen in React Native using LumioUI.

Goal: Contact picker sheet with a search field, new-group row, and recent plus alphabetically sectioned contacts with sticky headers and presence dots Match the reference implementation's layout, behavior, and motion exactly — this is a production screen, not a mockup.

## Setup

Fastest path — install the screen plus its component deps:

```bash
npx lumioui add chat-new-message
```

Or pull just the components: `npx lumioui add avatar button empty-state icon search-input text`

Native packages:
- @lumioui/ui@latest
- @lumioui/core@latest
- react-native-safe-area-context@*
- react-native-reanimated@*
- react-native-svg@*
- nativewind@*

Stack assumptions: Expo SDK 54 / RN 0.81, Reanimated 4, NativeWind v4, TypeScript strict, Expo Go compatible.

## Components — how, where, when

### `avatar` — Circular user image with fallback initials and status dot.
- `<Avatar>` ×2

### `button` — Tactile pill button with press spring, ink wash and async loading.
- `<Button>` ×1

### `empty-state` — Illustrated placeholder with title, copy and action slot.
- `<EmptyState>` ×1

### `icon` — Lucide icon set mapped to theme colors and sizes.
- `<Icon>` ×8

### `search-input` — Search field with clear button, debounce, focus halo — plus a glass capsule mode that floats over content like iOS 26
- imported but not rendered directly — likely used through a sibling or as a utility

### `text` — Themed type scale from caption to display.
- `<Text>` ×9

## Conventions (non-negotiable)

- Styling via NativeWind `className` with semantic tokens only: `bg-background`, `text-foreground`, `bg-card`, `text-card-foreground`, `bg-secondary`, `bg-muted`, `text-muted-foreground`, `bg-accent`, `bg-destructive`, `border-border`. Hard-coded colors only inside media overlays (`text-white`, `bg-black/N`).
- Motion via the token presets from `@lumioui/core` (`spring.press`, `spring.surface`, `spring.glide`, `timing.fast`, `timing.slow`, …) — no bespoke spring configs or durations.
- Gate transform motion behind `useReducedMotion()`; keep opacity/color feedback, drop travel and overshoot.
- Haptics via `useHaptic()`: `light` on press, `selection` on toggle/select, `warning` on invalid input. Never import expo-haptics directly.
- Press feedback via `usePressAnimation()` (~0.97 scale), not `activeOpacity` tricks.
- a11y: `accessibilityRole` + `accessibilityLabel` on every control, touch targets ≥44pt.
- Entrance choreography: staggered `Mount` wrappers (delay 0/60/120…) so regions land in sequence instead of popping in at once.
- Wrap the screen in `SafeAreaView`; keep dark mode working via the semantic tokens.

## Deliverable

One file: `screens/chat/new-message.tsx` exporting NewMessageScreen. Preserve the props interface — the host app wires the callbacks (navigation, submit handlers) through them.

## Reference implementation

The LumioUI source for this screen — reproduce it faithfully:

```tsx
import * as React from "react";
import { useMemo, useState } from "react";
import { View, SectionList, ScrollView, TextInput } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
  Easing,
  runOnJS,
  useSharedValue,
  useAnimatedStyle,
  withDelay,
  withTiming,
} from "react-native-reanimated";
import { Avatar, Button, EmptyState, Glass, Icon, Text } from "@lumioui/ui";
import { Press } from "../shared";
import { AnimatedPressable, ease, timing, useHaptic, usePressAnimation, useReducedMotion, } from "@lumioui/core";

export interface Contact {
  id: string;
  name: string;
  /** Handle or phone line under the name — "@diegoruiz", "+1 415…". */
  handle?: string;
  avatarUrl?: string;
  online?: boolean;
}

export interface NewMessageScreenProps {
  contacts?: Contact[];
  /** IDs repeated in a "Recent" section above the alphabetical list —
   *  contacts still appear in their letter group (iOS Favorites idiom). */
  recentIds?: string[];
  onContactPress?: (contact: Contact) => void;
  /** "New group" row pinned under the search field. */
  onNewGroup?: () => void;
  onSearch?: (query: string) => void;
  /** Sheet-style close affordance in the top-left. */
  onCancel?: () => void;
}

const DEFAULT_CONTACTS: Contact[] = [
  { id: "amara", name: "Amara Chen", handle: "@amarachen", online: true, avatarUrl: "https://i.pravatar.cc/150?img=9" },
  { id: "ava", name: "Ava Martinez", handle: "@avamartinez", online: true, avatarUrl: "https://i.pravatar.cc/150?img=44" },
  { id: "diego", name: "Diego Ruiz", handle: "@diegoruiz", online: true, avatarUrl: "https://i.pravatar.cc/150?img=53" },
  { id: "jonah", name: "Jonah Reyes", handle: "@jonahreyes", avatarUrl: "https://i.pravatar.cc/150?img=11" },
  { id: "kai", name: "Kai Tanaka", handle: "@kaitanaka", avatarUrl: "https://i.pravatar.cc/150?img=33" },
  { id: "leo", name: "Leo Fischer", handle: "@leofischer", online: true, avatarUrl: "https://i.pravatar.cc/150?img=15" },
  { id: "maya", name: "Maya Chen", handle: "@mayachen", online: true, avatarUrl: "https://i.pravatar.cc/150?img=47" },
  { id: "nina", name: "Nina Petrova", handle: "@ninapetrova", avatarUrl: "https://i.pravatar.cc/150?img=20" },
  { id: "priya", name: "Priya Nair", handle: "@priyanair", avatarUrl: "https://i.pravatar.cc/150?img=32" },
  { id: "sakura", name: "Sakura Ramen", handle: "Business · deliveries", avatarUrl: "https://images.unsplash.com/photo-1569718212165-3a8278d5f624?w=150&h=150&fit=crop&q=70&auto=format" },
  { id: "sam", name: "Sam Okafor", handle: "@samokafor", avatarUrl: "https://i.pravatar.cc/150?img=59" },
  { id: "tom", name: "Tom Reed", handle: "@tomreed", online: true, avatarUrl: "https://i.pravatar.cc/150?img=12" },
];

const DEFAULT_RECENT_IDS = ["maya", "diego", "tom"];

/** Staggered mount — rows rise and fade in sequence. Choreography data
 *  (like EmptyState's 90ms cadence), capped so lazily-mounted rows never
 *  wait on a deep index. */
const MOUNT_STAGGER = 40;
const MOUNT_MAX_DELAY = 280;
const MOUNT_TIMING = { duration: timing.normal.duration, easing: Easing.bezier(...ease.out) };

/** Fade + small rise on mount, delayed by index. Reduced motion: fade only. */
function MountIn({
  index,
  className,
  children,
}: {
  index: number;
  className?: string;
  children: React.ReactNode;
}) {
  const reduce = useReducedMotion();
  const t = useSharedValue(reduce ? 1 : 0);
  React.useEffect(() => {
    if (reduce) {
      t.value = 1;
      return;
    }
    t.value = withDelay(
      Math.min(index * MOUNT_STAGGER, MOUNT_MAX_DELAY),
      withTiming(1, MOUNT_TIMING)
    );
  }, [index, reduce, t]);
  const style = useAnimatedStyle(() => ({
    opacity: t.value,
    transform: [{ translateY: (1 - t.value) * 10 }],
  }));
  return (
    <Animated.View style={style} className={className}>
      {children}
    </Animated.View>
  );
}

/** Contact row — avatar with presence dot, name, handle. Dips like an
 *  iOS cell so the feedback still lands under a scrolling thumb. */
function ContactRow({
  contact,
  onPress,
}: {
  contact: Contact;
  onPress?: (c: Contact) => void;
}) {
  const haptics = useHaptic();
  const press = usePressAnimation({ pressedScale: 0.98, pressedOpacity: 0.75, fast: true });
  return (
    <AnimatedPressable
      onPress={() => {
        haptics.light();
        onPress?.(contact);
      }}
      onPressIn={press.onPressIn}
      onPressOut={press.onPressOut}
      style={press.animatedStyle}
      accessibilityRole="button"
      accessibilityLabel={`Message ${contact.name}${contact.online ? ", online" : ""}`}
      className="flex-row items-center gap-3 px-6 py-2.5"
    >
      <Avatar
        size="md"
        source={contact.avatarUrl ? { uri: contact.avatarUrl } : undefined}
        fallback={contact.name}
        status={contact.online ? "online" : undefined}
        alt={`${contact.name}'s avatar`}
      />
      <View className="flex-1 gap-0.5">
        <Text variant="small" numberOfLines={1} className="font-medium">
          {contact.name}
        </Text>
        {contact.handle ? (
          <Text variant="muted" numberOfLines={1} className="text-xs">
            {contact.handle}
          </Text>
        ) : null}
      </View>
    </AnimatedPressable>
  );
}

interface ContactSection {
  title: string;
  data: Contact[];
}

/** Groups contacts into A–Z letter buckets. Recents live in the avatar
 *  rail above the list, not a duplicated section. */
function groupContacts(contacts: Contact[], recentIds: string[]): ContactSection[] {
  const sections: ContactSection[] = [];

  const letters = new Map<string, Contact[]>();
  const recentSet = new Set(recentIds);
  for (const c of [...contacts]
    .filter((c) => !recentSet.has(c.id))
    .sort((a, b) => a.name.localeCompare(b.name))) {
    const letter = (c.name.trim()[0] ?? "#").toUpperCase();
    const bucket = letters.get(letter);
    if (bucket) bucket.push(c);
    else letters.set(letter, [c]);
  }
  for (const [title, data] of [...letters.entries()].sort(([a], [b]) =>
    a.localeCompare(b)
  )) {
    sections.push({ title, data });
  }
  return sections;
}

/** Contact rail chip — large avatar + first name, press feedback via the
 *  shared press animation. Sits above the indexed list. */
function RecentChip({
  contact,
  onPress,
}: {
  contact: Contact;
  onPress?: (c: Contact) => void;
}) {
  const haptics = useHaptic();
  const press = usePressAnimation({ pressedScale: 0.94, pressedOpacity: 0.8, fast: true });
  return (
    <AnimatedPressable
      onPress={() => {
        haptics.light();
        onPress?.(contact);
      }}
      onPressIn={press.onPressIn}
      onPressOut={press.onPressOut}
      style={press.animatedStyle}
      accessibilityRole="button"
      accessibilityLabel={`Message ${contact.name}${contact.online ? ", online" : ""}`}
      className="w-16 items-center gap-1.5"
    >
      <Avatar
        size="xl"
        source={contact.avatarUrl ? { uri: contact.avatarUrl } : undefined}
        fallback={contact.name}
        status={contact.online ? "online" : undefined}
        alt={`${contact.name}'s avatar`}
      />
      <Text variant="muted" numberOfLines={1} className="text-xs">
        {contact.name.split(" ")[0]}
      </Text>
    </AnimatedPressable>
  );
}
RecentChip.displayName = "RecentChip";

/** New message — a contact picker sheet: search field, "Recent" avatar
 *  rail, "New group" row, then alphabetically-sectioned contacts with
 *  presence dots. */
export function NewMessageScreen({
  contacts = DEFAULT_CONTACTS,
  recentIds = DEFAULT_RECENT_IDS,
  onContactPress,
  onNewGroup,
  onSearch,
  onCancel,
}: NewMessageScreenProps) {
  const haptics = useHaptic();
  const insets = useSafeAreaInsets();
  const [query, setQuery] = useState("");
  const groupPress = usePressAnimation({ pressedScale: 0.98, pressedOpacity: 0.75, fast: true });
  // Header search — the icon pill expands leftward into a full search
  // bar; `open` drives the width, `searchOpen` keeps it mounted until
  // the collapse finishes.
  const [searchOpen, setSearchOpen] = useState(false);
  const [rowW, setRowW] = useState(0);
  const open = useSharedValue(0);
  const inputRef = React.useRef<TextInput>(null);

  const openSearch = () => {
    setSearchOpen(true);
    open.value = withTiming(1, { duration: 300, easing: Easing.out(Easing.cubic) });
  };
  const closeSearch = () => {
    inputRef.current?.blur();
    setQuery("");
    onSearch?.("");
    open.value = withTiming(0, { duration: 260, easing: Easing.in(Easing.cubic) }, (finished) => {
      if (finished) runOnJS(setSearchOpen)(false);
    });
  };
  const searchStyle = useAnimatedStyle(() => ({ width: rowW * open.value }));
  const chromeStyle = useAnimatedStyle(() => ({ opacity: 1 - open.value }));

  React.useEffect(() => {
    if (searchOpen) inputRef.current?.focus();
  }, [searchOpen]);

  const q = query.trim().toLowerCase();
  const searching = q.length > 0;
  const visible = useMemo(
    () =>
      searching
        ? contacts.filter(
            (c) =>
              c.name.toLowerCase().includes(q) ||
              (c.handle ?? "").toLowerCase().includes(q)
          )
        : contacts,
    [searching, q, contacts]
  );

  // Searching flattens to one unsectioned result list — match order is the
  // ranking, letter buckets would just add noise.
  const sections = useMemo(
    () =>
      searching
        ? [{ title: "Contacts", data: visible }]
        : groupContacts(visible, recentIds),
    [searching, visible, recentIds]
  );

  return (
    <SafeAreaView className="flex-1 bg-[#F4F5F9] dark:bg-[#111114]" edges={["top"]}>
      <SectionList
        sections={sections}
        keyExtractor={(item) => `${item.id}`}
        className="flex-1"
        contentContainerStyle={{ paddingTop: insets.top + 60, paddingBottom: insets.bottom + 16 }}
        ListHeaderComponent={
          <View>
            {/* Recents rail — the people you actually message, as big
                horizontally-scrolling avatars. The 2024+ contact-picker idiom
                (iMessage / WhatsApp share sheet) replaces a duplicate "Recent"
                list section. */}
            {!searching && recentIds.length > 0 ? (
              <View className="pb-1">
                <Text
                  variant="muted"
                  className="px-6 pb-2 pt-1 text-xs font-semibold uppercase tracking-wider"
                  accessibilityRole="header"
                >
                  Recent
                </Text>
                <ScrollView
                  horizontal
                  showsHorizontalScrollIndicator={false}
                  contentContainerClassName="gap-4 px-6"
                >
                  {recentIds
                    .map((id) => contacts.find((c) => c.id === id))
                    .filter((c): c is Contact => !!c)
                    .map((c) => (
                      <RecentChip key={c.id} contact={c} onPress={onContactPress} />
                    ))}
                </ScrollView>
              </View>
            ) : null}

            {/* New group — pinned action above the contact sections. */}
            {onNewGroup ? (
              <AnimatedPressable
                onPress={() => {
                  haptics.light();
                  onNewGroup();
                }}
                onPressIn={groupPress.onPressIn}
                onPressOut={groupPress.onPressOut}
                style={groupPress.animatedStyle}
                accessibilityRole="button"
                accessibilityLabel="Start a new group"
                className="flex-row items-center gap-3 px-6 py-3"
              >
                <View className="h-10 w-10 items-center justify-center rounded-full bg-[#BEF04C]">
                  <Icon name="users" size="md" color="#1B1B26" />
                </View>
                <Text variant="small" className="flex-1 font-semibold">
                  New group
                </Text>
                <Icon name="chevron-right" size="sm" color="mutedForeground" />
              </AnimatedPressable>
            ) : null}
          </View>
        }
        showsVerticalScrollIndicator={false}
        // Letter headers pin while you scroll — the iOS Contacts idiom.
        stickySectionHeadersEnabled
        keyboardShouldPersistTaps="handled"
        renderSectionHeader={({ section }) =>
          // Skip the bare "Contacts" label that wraps flattened search hits.
          searching ? null : (
            <Text
              variant="muted"
              // Sticky headers must paint the flow canvas — bg-background
              // ignores the chat World's tint and reads as a stray band.
              className="bg-[#F4F5F9] px-6 pb-1 pt-4 text-xs font-semibold uppercase tracking-wider dark:bg-[#111114]"
              accessibilityRole="header"
            >
              {section.title}
            </Text>
          )
        }
        ItemSeparatorComponent={() => (
          // Align with the text column: px-6 (1.5rem) + avatar h-10
          // (2.5rem) + gap-3 (0.75rem) = 4.75rem.
          <View className="ml-[4.75rem] h-px bg-border" accessible={false} />
        )}
        ListEmptyComponent={
          <EmptyState
            variant={searching ? "search" : "default"}
            title={searching ? "No contacts found" : "No contacts"}
            description={
              searching
                ? `Nobody matches "${query.trim()}".`
                : "People you add will appear here."
            }
          />
        }
        ListFooterComponent={
          // Invite footer — contact pickers always end with the
          // "your friend isn't here yet" escape hatch.
          <View className="mx-6 mt-4 flex-row items-center gap-3 overflow-hidden rounded-2xl px-4 py-3.5">
            <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
            <View className="h-10 w-10 items-center justify-center rounded-full bg-[#BEF04C]">
              <Icon name="user-plus" size="sm" color="#1B1B26" />
            </View>
            <View className="flex-1">
              <Text variant="small" className="font-medium">
                Invite friends to Lumio
              </Text>
              <Text variant="muted" className="text-xs">
                Share a link — they join your contacts when they sign up.
              </Text>
            </View>
            <Icon name="chevron-right" size="sm" color="mutedForeground" />
          </View>
        }
        renderItem={({ item, index }) => (
          <MountIn index={index}>
            <ContactRow contact={item} onPress={onContactPress} />
          </MountIn>
        )}
      />

      {/* Floating chrome — three frosted pills on one line: close, title,
          search icon. Tapping search expands the right pill leftward into
          a full search bar; the list scrolls underneath. */}
      <View
        className="absolute inset-x-4 z-10"
        style={{ top: insets.top + 8 }}
        pointerEvents="box-none"
        onLayout={(e) => setRowW(e.nativeEvent.layout.width)}
      >
        <Animated.View style={chromeStyle} className="flex-row items-center justify-between gap-2">
          {onCancel ? (
            <Glass
              effect="regular"
              className="h-11 w-11 items-center justify-center rounded-full"
            >
              <Button
                variant="ghost"
                size="icon"
                haptic="light"
                onPress={onCancel}
                accessibilityLabel="Cancel"
                className="h-9 w-9"
              >
                <Icon name="x" size="md" color="foreground" />
              </Button>
            </Glass>
          ) : (
            <View className="w-11" />
          )}
          <Glass
            effect="regular"
            className="h-11 w-11 items-center justify-center rounded-full"
          >
            <Press
              haptic="light"
              onPress={openSearch}
              accessibilityRole="button"
              accessibilityLabel="Search contacts"
              className="h-11 w-11 items-center justify-center"
            >
              <Icon name="search" size="sm" color="foreground" />
            </Press>
          </Glass>
        </Animated.View>
        <Animated.View style={chromeStyle} pointerEvents="none" className="absolute inset-0 items-center justify-center">
          <Glass
            effect="regular"
            className="h-11 flex-row items-center justify-center rounded-full px-5"
          >
            <Text accessibilityRole="header" className="text-sm font-bold tracking-tight">
              New Message
            </Text>
          </Glass>
        </Animated.View>

        {/* Expanding search bar — grows leftward out of the icon pill,
            covers the row, and takes focus while the list filters live. */}
        {searchOpen ? (
          <Animated.View
            style={searchStyle}
            className="absolute right-0 top-0 h-11 overflow-hidden"
          >
            <View className="h-11 flex-row items-center gap-2" style={{ width: rowW }}>
              {/* Solid surface, not Glass — a real input behind the
                  backdrop-filter material paints its text smeared. */}
              <View className="h-11 flex-1 flex-row items-center rounded-full bg-white px-3 dark:bg-[#1A1A20]">
                <Icon name="search" size="sm" color="mutedForeground" />
                <TextInput
                  ref={inputRef}
                  value={query}
                  onChangeText={(text) => {
                    setQuery(text);
                    onSearch?.(text);
                  }}
                  placeholder="Search name or handle…"
                  placeholderTextColor="#8A8A93"
                  returnKeyType="search"
                  accessibilityLabel="Search contacts"
                  autoFocus
                  className="flex-1 px-2 text-base text-foreground outline-none"
                />
              </View>
              <View className="h-11 w-11 items-center justify-center rounded-full bg-white dark:bg-[#1A1A20]">
                <Press
                  haptic="light"
                  onPress={closeSearch}
                  accessibilityRole="button"
                  accessibilityLabel="Close search"
                  className="h-11 w-11 items-center justify-center"
                >
                  <Icon name="x" size="sm" color="foreground" />
                </Press>
              </View>
            </View>
          </Animated.View>
        ) : null}
      </View>
    </SafeAreaView>
  );
}
NewMessageScreen.displayName = "NewMessageScreen";
```

Screen: https://lumioui.dev/screens/chat-new-message
Pixel 10 · Android
9:41
Live preview — the real screen via Expo Web · open full ↗