Primitives
Animated Number Avatar Badge Button Button Group Toggle Toggle Group Checkbox Chip Countdown Divider Fab Grid Icon Image Input Search Input Textarea Label Loader Marquee Masked Input Message Bubble Notification Banner Offline Banner Progress Progress Ring Radio Group Range Slider Rating Separator Skeleton Slider Stack Stepper Switch Text Theme Toggle Ticker Typing IndicatorComposed
Accordion Achievement Badge Action Bar Action Sheet Action Swap Activity Rings Add to Cart Button Address Card Agenda List Alert Amount Keypad Animated Icons App Bar Audio Message Audio Recorder Autocomplete Avatar Group Balance Display Bar List Barcode Before After Biometric Gate Bloom Menu Bottom Sheet Paywall Sheet Side Sheet Breadcrumb Calendar Calendar Strip Card Carousel Cart Item Character Charts Chat Composer Chat List Item Choice Card Circle Reveal Coach Marks Collapsible Collapsible Header Color Picker Combobox Command Palette Comment Thread Confetti Consent Sheet Context Menu Copy Field Country Picker Coupon Input Currency Input Data Table Date Range Picker Day Schedule Dialog Dock Donut Chart Drawer Driver Card Dropdown Menu Drum Picker Emoji Picker Empty State Error State Event Card Expandable Control Fader Feature Gate File Picker Filter Bar Follow Button Form Gauge Glass Glass Cluster Glass Dock Morph Glass Fab Morph Glass Lab Glass Orb Glass Search Morph Glass Sheet Edge Gradient Button Headline New Heatmap Image Cropper Image Viewer Kanban Card Keyboard Avoiding Keyboard Toolbar Leaderboard Level Progress Lightbox Like Button Line Chart List Reorderable List Swipeable Row Location Card Location Search Map Sheet Map View Markdown View Media Controls Media Picker Media Tile Mention Input Meter Bar Mini Player Mood Slider Morphing Modal Multi Select Navigation Rail Notification Item Number Input Onboarding Pager Order Card Order Summary OTP Input Pagination Paper Clip New Parallax Header Pass Card Password Strength Payment Button Payment Card Payment Method Permission Primer Phone Input PIN Pad Polaroid New Poll Popover Post Card Postage Stamp New Price Tag Pricing Table Product Card Product Gallery Profile Header Promo Banner Prompt Input Property Card Pull To Refresh QR Code Quick Actions Quick Replies Rating Summary Reaction Picker Resend Timer Review Card Review Prompt Ride Option Save Button Scan Frame Scroll Spy Tabs Seat Map Section Header Section Index Segmented Control Select Share Button Share Sheet Shutter Button Signature Pad Slide to Confirm Slot Picker Smart Banner Social Login Button Sparkline Splash Screen Split Button Stat Card Stateful Button Status Dot Step Flow Steps Sticker New Stopwatch Stories Progress Stories Viewer Story Ring Streak Counter Streaming Text Success Seal Swipe Deck Tabs Tag Input Tape New Text Reveal Thinking Indicator Time Picker Timeline Timer Ring Tip Selector Toast Toolbar Tooltip Track Row Transaction Row Trip Progress Variant Picker Video Controls Waveform Weather Card Weekday Picker Zoom TransitionScreens
Account Switcher Biometric Setup Delete Account Forgot Password Grow Auth Login Login — Dark Stage Login — Dense Work Login — Editorial Login — Illustrated Login — Minimal Ink Login — Social Login — Video Loop Food Onboarding Onboarding Onboarding Dark Objects Onboarding Editorial Onboarding Illustrated Onboarding Personalize Onboarding Photo Carousel OTP Verification Passkey — Create Password Reset Permission — Notifications Phone Verification Onboarding Quiz Session Devices Signup Sign-up Chat Sign-up Photo Sheet Social Auth Split Auth Verify Identity Welcome AI Chat AI Assistant Channels List Chat Info Chat List Chat Media Chat Thread Create Group Group Info Message Requests New Message Kept Messages Accessibility Activity Log Appearance Authenticator Blocked Accounts Export Your Data Downloads Edit Profile Edit Profile — Rows Emergency Call Empty States Set Error State Send Feedback Device Locator Help Center Home — Bento Home — Dark Home — Editorial Home Feed Invite Friends Language & Region Linked Accounts Not Found (404) Notification Settings Notifications Password Vault Paywall Paywall — Comparison Paywall — Dark Stage Paywall — Editorial Paywall — Photo Paywall — Trial Timeline Privacy Profile Profile — Gamified Profile — Minimal Profile — Photo Hero QR Scanner Report Issue Saved Items Phone Time Search Search — Command Palette Search — Visual Account Health Settings Settings — Dark Device Settings — Search Storage & Data Terms & Privacy Dating Chat Dating Filters Profile Discover Its A Match Into You Matches Profile Detail Profile Editor Courier Matching Delivery History Delivery Support Package Schedule Parcel Tracking Proof Of Delivery Quick Aisle Quick Home Send Package Substitutions Add Payment Address Book Cart Categories Checkout Checkout — Steps Checkout Success Delivery Filters & Sort Flash Sale Gift Cards Loyalty Points Order Cancel Order Detail Orders Pay Later Checkout Payment Methods Product Detail Product Detail — Hero Product Grid Product Reviews Promo Codes Recently Viewed Return Items Search Results Shop Assistant Store Home Tip & Rate Courier Order Tracking Wishlist Write a Review Event Checkin Event Hero Events Discover My Tickets Seat Selection Ticket Checkout Add Card Bank Accounts Dashboard — Bento Bill Pay Budgets Card Details Crypto Portfolio Finance Dashboard Dashboard — Dark Exchange Currency Expense List Invoice Detail Manage Cards Plan Management Savings Goals Send Money Spending Analytics Split Bill Subscriptions Token Detail Token Swap Transactions Wallet Home Wallet Movers Courier Tracking Food Cart Food Home Food Orders Grocery List Recipe Detail Restaurant — Dark Restaurant Detail Activity Rings Fitness Home Habit Quest Habit Tracker Meal Planner Med Store Meditation Player Mood Check-in Nutrition Home Period Tracker Prior Auth Prior Auth Cases Quest Complete Run Tracking Rx Scan Sleep Tracker Telehealth Booking Walk Map Water Tracker Workout Complete Workout Detail Workout Session Applications Apply Company Interview Schedule Job Detail Job Feed Resume Saved Jobs Create Listing Item Chat Listing Detail Make Offer Market Checkout Market Home Market Search My Listings Offers Inbox Seller Profile Audiobook Player Camera Gallery Albums Game Store Mini Player Music Player Photo Editor Photo Gallery Playlist Detail Podcast Player Clips Feed Serene Home Sound Mixer Stories Video Call Video Player Article Reader Course Detail Event Detail Memory Onboarding Icon Lab Leaderboard Lesson Player Match Detail News Editorial News Home Plant Care Prediction Live Prediction Welcome Smart Home Standings Ticket Wallet Topics Follow Weather Detail Add Task Sheet Alarm Clock Calendar Day Calendar Month Doc Scanner File Manager Focus Timer Journal Kanban Board Mail Inbox Mail Thread Note Editor Notes List Reminders Task List Time Blocks Agent Profile Compare Homes Mortgage Calculator Property Detail Rental Application Saved Homes Schedule Tour Search List Search Map Complete Destination Driver Arriving Ev Charging History Home In Trip Matching Options Parking Receipt Safety Schedule Scooter Unlock Booking Confirmed Booking Review Booking Slots My Bookings Pro On The Way Provider Detail Provider List Rate Service Services Home Arc Create Arc Detail Arc Onboarding Avatar Creator Comments Sheet Create Post Explore Grid Followers List Hashtag Feed Mentions Post Detail Post Hero Social Profile Boarding Pass Booking Confirm Car Rental Trip Discover Flight Live Flight Preferences Flight Results Flight Search Hotel Detail Live Transit Trip — Map Day Trip — Rideshare Request Seat Select Travel Home Trip Itinerary Trip OnboardingNothing matches — try another word.
Like Button
Heart toggle for social feeds that fills from the bottom up with a soft glow and updates the count in place. It fills however the post gets liked, including a double-tap on the photo.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { Pressable, View, type PressableProps } from "react-native";
import Animated, {
Easing,
interpolate,
useAnimatedStyle,
useSharedValue,
withDelay,
withSequence,
withSpring,
withTiming,
} from "react-native-reanimated";
import Svg, { Path } from "react-native-svg";
import {
LightPool,
cn,
createVariant,
ease,
spring,
tempo,
timing,
useHaptic,
usePressAnimation,
useReducedMotion,
useTheme,
type ColorTokens,
} from "@lumioui/core";
/**
* LikeButton — the social heart. Tap to like: the outline heart dips, then
* light rises through it from the bottom up until it is full, a small pool of
* the like colour brightens under it and settles away, and the count swaps in
* place one step up. Unlike drains the fill downward, with no light. Controlled
* or uncontrolled; the moment plays on every false → true change whatever its
* source, so a double-tap on a photo fills the button too.
*
* <LikeButton defaultLiked={false} count={1284} />
* <LikeButton variant="overlay" liked={liked} onLikedChange={setLiked} count={48200} />
*
* Expo Go compatible.
*/
// The heart on the 24 grid — the outline and the fill share one path so the
// fill covers the outline exactly as it rises.
const HEART = "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z";
/** The social red. Content colour, not chrome — pass `color="primary"` to
* follow the surrounding <Accent> instead. */
const LIKE_RED = "#FF3040";
const GLYPH = { sm: 20, md: 24, lg: 28 } as const;
const OVERLAY_GLYPH = { sm: 28, md: 32, lg: 36 } as const;
// Count line height — the swap layers stack inside it.
const LINE = { sm: 18, md: 20, lg: 22 } as const;
/** The outline heart dips this far before the light rises through it. */
const DIP = 0.86;
/** Light rising through the heart — the same length as a check drawing on, so
* the fill reads as one stroke of light rather than a pop. */
const FILL_RISE = { duration: 240, easing: Easing.bezier(...ease.out) };
/** Unlike — the light drains out the bottom faster than it rose. */
const FILL_DRAIN = { ...timing.recede, easing: Easing.bezier(...ease.in) };
/** The outline hands over to the fill only over the last stretch of the rise,
* so no dark rim shows while the light is still climbing. */
const OUTLINE_HANDOFF = 0.7;
/** The pool brightens and settles (LightPool's own peak + settle), then goes
* out — an event under the heart, never a resting halo. */
const POOL_MS = timing.slow.duration + tempo.roll;
/** Pool diameter as a multiple of the glyph, and its peak alpha. */
const POOL_SCALE = 3;
const POOL_STRENGTH = 0.3;
/** Count swap travel — direction carries meaning (up on like, down on unlike). */
const COUNT_TRAVEL = 6;
const SWAP_SCALE = 0.96;
const rootVariants = createVariant({
base: "flex-row items-center",
variants: {
variant: {
plain: "min-h-[44px] gap-1.5",
pill: "h-9 gap-1.5 rounded-full border border-border bg-card px-3",
overlay: "min-w-[44px] flex-col gap-1",
},
size: { sm: "", md: "", lg: "" },
},
compoundVariants: [
{ variant: "pill", size: "sm", class: "h-8 px-2.5" },
{ variant: "pill", size: "lg", class: "h-11 px-4" },
],
defaultVariants: { variant: "plain", size: "md" },
});
const countVariants = createVariant({
base: "tabular-nums",
variants: {
variant: {
plain: "font-semibold text-foreground",
pill: "font-medium text-foreground",
overlay: "font-semibold text-white",
},
size: { sm: "text-sm", md: "text-[15px]", lg: "text-base" },
},
compoundVariants: [{ variant: "overlay", size: "sm", class: "text-xs" }, { variant: "overlay", size: "md", class: "text-[13px]" }],
defaultVariants: { variant: "plain", size: "md" },
});
/** 1,284 · 12.4K · 482K · 1.2M — the compact form feeds and reels use. */
export function formatLikeCount(n: number): string {
const abs = Math.abs(n);
const unit = (v: number, s: string) => {
const fixed = v < 10 ? v.toFixed(1) : Math.floor(v).toString();
return `${fixed.replace(/\.0$/, "")}${s}`;
};
if (abs >= 1_000_000) return unit(Math.floor(n / 100_000) / 10, "M");
if (abs >= 10_000) return unit(Math.floor(n / 100) / 10, "K");
return n.toLocaleString("en-US");
}
export interface LikeButtonProps
extends Omit<PressableProps, "onPress" | "children" | "style" | "accessibilityRole"> {
/** Controlled liked state. Omit and use `defaultLiked` for uncontrolled. */
liked?: boolean;
/** Uncontrolled initial state. Default false. */
defaultLiked?: boolean;
/** Fires with the next state on every tap. */
onLikedChange?: (liked: boolean) => void;
/** Likes from everyone else. The viewer's own like is added on top, so
* toggling never needs the parent to recompute the total. Omit to hide the count. */
count?: number;
/** Count formatter. Default `formatLikeCount` (1,284 · 12.4K · 1.2M). */
formatCount?: (n: number) => string;
/** Hide the count even when `count` is set. */
hideCount?: boolean;
/** plain — icon + inline count (feeds). pill — bordered chip (comments,
* reactions). overlay — white stacked icon over video/photo (reels). */
variant?: "plain" | "pill" | "overlay";
/** Glyph + count scale. Default "md". */
size?: "sm" | "md" | "lg";
/** Liked fill colour: a theme token ("primary", "destructive"…) or any
* colour. Default the social red. */
color?: keyof ColorTokens | (string & {});
/** Skip the light pool under the heart — for dense rows (comments, lists).
* The rising fill and the count swap stay. */
noBurst?: boolean;
/** Haptic on like. Default true. */
haptic?: boolean;
disabled?: boolean;
/** Screen-reader name. Default "Like". */
accessibilityLabel?: string;
className?: string;
/** Extra classes for the count text. */
countClassName?: string;
}
export const LikeButton = forwardRef<React.ElementRef<typeof Pressable>, LikeButtonProps>(
function LikeButton(
{
liked: controlledLiked,
defaultLiked = false,
onLikedChange,
count,
formatCount = formatLikeCount,
hideCount = false,
variant = "plain",
size = "md",
color = LIKE_RED,
noBurst = false,
haptic = true,
disabled,
accessibilityLabel = "Like",
className,
countClassName,
onPressIn,
onPressOut,
...props
},
ref
) {
const { colors } = useTheme();
const haptics = useHaptic(haptic);
const reduce = useReducedMotion();
// Icon-sized press — light enough that the like dip still reads after it.
const press = usePressAnimation({ pressedScale: 0.94, disabled });
const [internal, setInternal] = React.useState(defaultLiked);
const liked = controlledLiked ?? internal;
const tint = (color in colors ? colors[color as keyof ColorTokens] : color) as string;
const overlay = variant === "overlay";
const glyph = overlay ? OVERLAY_GLYPH[size] : GLYPH[size];
const idleStroke = overlay ? "#FFFFFF" : colors.foreground;
const strokeWidth = overlay ? 2.2 : 2;
// rise: how far the light has climbed through the heart, 0 empty … 1 full.
// lit: brightness of the fill layer (reduced motion crossfades on this).
const rise = useSharedValue(liked ? 1 : 0);
const lit = useSharedValue(liked ? 1 : 0);
const dip = useSharedValue(1);
const [pool, setPool] = React.useState(false);
const poolTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
React.useEffect(
() => () => {
if (poolTimer.current) clearTimeout(poolTimer.current);
},
[]
);
// Animate on real transitions only — first paint lands settled.
const prevLiked = React.useRef(liked);
React.useEffect(() => {
if (prevLiked.current === liked) return;
prevLiked.current = liked;
if (poolTimer.current) clearTimeout(poolTimer.current);
if (!liked) {
// Unlike: the light drains out downward. No pool, no dip.
setPool(false);
if (reduce) {
lit.value = withTiming(0, timing.recede);
} else {
lit.value = 1;
rise.value = withTiming(0, FILL_DRAIN);
}
return;
}
// Like: the pool is light, not travel — it plays under reduced motion too.
if (!noBurst) {
setPool(true);
poolTimer.current = setTimeout(() => setPool(false), POOL_MS);
}
if (reduce) {
rise.value = 1;
lit.value = withTiming(1, timing.fast);
return;
}
lit.value = 1;
rise.value = 0;
rise.value = withDelay(timing.instant.duration, withTiming(1, FILL_RISE));
dip.value = withSequence(withTiming(DIP, timing.instant), withSpring(1, spring.pop));
}, [liked, reduce, noBurst, rise, lit, dip]);
const toggle = () => {
if (disabled) return;
const next = !liked;
if (next) haptics.light();
else haptics.selection();
if (controlledLiked === undefined) setInternal(next);
onLikedChange?.(next);
};
const outlineStyle = useAnimatedStyle(() => ({
opacity: 1 - lit.value * interpolate(rise.value, [OUTLINE_HANDOFF, 1], [0, 1], "clamp"),
}));
// The fill sits in a window that slides up from below while the heart
// inside counter-slides, so the heart stays put and is revealed bottom-up.
const windowStyle = useAnimatedStyle(
() => ({ opacity: lit.value, transform: [{ translateY: (1 - rise.value) * glyph }] }),
[glyph]
);
const fillStyle = useAnimatedStyle(() => ({ transform: [{ translateY: -(1 - rise.value) * glyph }] }), [glyph]);
const dipStyle = useAnimatedStyle(() => ({ transform: [{ scale: dip.value }] }));
const total = (count ?? 0) + (liked ? 1 : 0);
const showCount = count !== undefined && !hideCount;
const label = formatCount(total);
// Pill: the liked state tints the chip with the heart colour.
const hex = /^#[0-9a-fA-F]{6}$/.test(tint) ? tint : null;
const pillStyle =
variant === "pill" && liked && hex ? { borderColor: `${hex}55`, backgroundColor: `${hex}14` } : undefined;
const poolSize = glyph * POOL_SCALE;
return (
<Pressable
ref={ref}
onPress={toggle}
onPressIn={(e) => {
press.onPressIn();
onPressIn?.(e);
}}
onPressOut={(e) => {
press.onPressOut();
onPressOut?.(e);
}}
disabled={disabled}
hitSlop={variant === "plain" ? { left: 10, right: 10 } : 6}
className={cn(rootVariants({ variant, size }), disabled && "opacity-50", className)}
style={pillStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
accessibilityState={{ selected: liked, disabled: !!disabled }}
accessibilityValue={showCount ? { text: `${total.toLocaleString("en-US")} likes` } : undefined}
aria-pressed={liked}
{...props}
>
<Animated.View style={[{ width: glyph, height: glyph }, press.animatedStyle]}>
{!noBurst ? (
<LightPool
on={pool}
color={tint}
size={poolSize}
strength={POOL_STRENGTH}
style={{ position: "absolute", left: (glyph - poolSize) / 2, top: (glyph - poolSize) / 2 }}
/>
) : null}
<Animated.View style={dipStyle}>
<Animated.View style={outlineStyle}>
<Svg width={glyph} height={glyph} viewBox="0 0 24 24">
<Path
d={HEART}
stroke={idleStroke}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
fill={overlay ? "rgba(0,0,0,0.12)" : "none"}
/>
</Svg>
</Animated.View>
<View pointerEvents="none" style={{ position: "absolute", left: 0, top: 0, width: glyph, height: glyph, overflow: "hidden" }}>
<Animated.View style={[{ width: glyph, height: glyph, overflow: "hidden" }, windowStyle]}>
<Animated.View style={fillStyle}>
<Svg width={glyph} height={glyph} viewBox="0 0 24 24">
<Path d={HEART} fill={tint} stroke={tint} strokeWidth={strokeWidth} strokeLinejoin="round" />
</Svg>
</Animated.View>
</Animated.View>
</View>
</Animated.View>
</Animated.View>
{showCount ? (
<SwapCount
value={total}
text={label}
lineHeight={LINE[size]}
reduce={reduce}
className={cn(countVariants({ variant, size }), countClassName)}
shadow={overlay}
/>
) : null}
</Pressable>
);
}
);
LikeButton.displayName = "LikeButton";
// --- Count swap ----------------------------------------------------------------
interface SwapState {
key: number;
value: number;
text: string;
prev: string | null;
dir: 1 | -1;
}
/** The count swaps in place: the outgoing figure dims and lifts away, the
* incoming one ignites from a few points below (reversed on unlike). */
function SwapCount({
value,
text,
lineHeight,
reduce,
className,
shadow,
}: {
value: number;
text: string;
lineHeight: number;
reduce: boolean;
className?: string;
shadow?: boolean;
}) {
const [swap, setSwap] = React.useState<SwapState>({ key: 0, value, text, prev: null, dir: 1 });
// Derive the next layer pair during render (no passive-effect lag).
if (swap.text !== text) {
setSwap({ key: swap.key + 1, value, text, prev: swap.text, dir: value >= swap.value ? 1 : -1 });
}
const textShadow = shadow
? { textShadowColor: "rgba(0,0,0,0.45)", textShadowRadius: 4, textShadowOffset: { width: 0, height: 1 } }
: null;
return (
<View style={{ height: lineHeight }} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
{swap.prev !== null ? (
<SwapLayer
key={`out-${swap.key}`}
mode="out"
dir={swap.dir}
reduce={reduce}
className={className}
style={[{ position: "absolute", left: 0, top: 0, lineHeight }, textShadow]}
>
{swap.prev}
</SwapLayer>
) : null}
<SwapLayer
key={`in-${swap.key}`}
mode="in"
animate={swap.key > 0}
dir={swap.dir}
reduce={reduce}
className={className}
style={[{ lineHeight }, textShadow]}
>
{text}
</SwapLayer>
</View>
);
}
const IGNITE = { ...timing.fast, easing: Easing.bezier(...ease.out) };
const DIM = { ...timing.recede, easing: Easing.bezier(...ease.in) };
function SwapLayer({
mode,
animate = true,
dir,
reduce,
className,
style,
children,
}: {
mode: "in" | "out";
animate?: boolean;
dir: 1 | -1;
reduce: boolean;
className?: string;
style?: React.ComponentProps<typeof Animated.Text>["style"];
children: string;
}) {
// Each layer mounts fresh at its own start value — no one-frame flash of
// the settled state before the swap begins.
const settled = mode === "in" ? !animate : true;
const opacity = useSharedValue(settled ? 1 : 0);
// move: 0 at rest; 1 = displaced by COUNT_TRAVEL and SWAP_SCALE.
const move = useSharedValue(mode === "in" && animate ? 1 : 0);
React.useEffect(() => {
if (mode === "in") {
if (!animate) return;
opacity.value = withTiming(1, IGNITE);
move.value = reduce ? 0 : withSpring(0, spring.swap);
} else {
opacity.value = withTiming(0, DIM);
move.value = reduce ? 0 : withTiming(1, DIM);
}
}, [mode, animate, reduce, opacity, move]);
const animated = useAnimatedStyle(() => {
const m = reduce ? 0 : move.value;
// In: arrives from below (count up) or above (count down). Out: leaves the other way.
const y = (mode === "in" ? 1 : -1) * dir * COUNT_TRAVEL * m;
return {
opacity: opacity.value,
transform: [{ translateY: y }, { scale: 1 - (1 - SWAP_SCALE) * m }],
};
}, [mode, reduce, dir]);
return (
<Animated.Text className={className} style={[style, animated]} numberOfLines={1}>
{children}
</Animated.Text>
);
}
export { rootVariants as likeButtonVariants }; import { LikeButton } from "@/components/ui/like-button/like-button";
export function Example() {
return (
<LikeButton />
);
} Installation
Install the dependencies
npx expo install react-native-reanimated react-native-svgCopy the source from the Code tab into your project
components/ui/like-button/like-button.tsxcomponents/ui/like-button/index.tsUpdate the import paths to match your project setup.
Usage
import { formatLikeCount, LikeButton } from "@/components/ui/like-button/like-button"; <LikeButton /> Also exported: formatLikeCount.
Examples
A photo post in a feed.
import * as React from "react";
import { Image, Pressable, View, type LayoutRectangle } from "react-native";
import Animated, {
interpolate,
runOnJS,
useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
withDelay,
withSequence,
withSpring,
withTiming,
} from "react-native-reanimated";
import Svg, { Path } from "react-native-svg";
import { spring, timing, useReducedMotion } from "@lumioui/core";
import { LikeButton } from "../like-button";
import { Avatar } from "../../avatar/avatar";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const PHOTO = "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=900&h=1100&fit=crop&q=80&auto=format";
const HEART = "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z";
// Two taps inside this window count as a double-tap (platforms use ~250–300ms).
const DOUBLE_TAP_MS = 280;
// Act, hold, resolve: the big heart rests on the photo before it travels.
const HEART_HOLD_MS = 520;
const BIG = 96;
// The action-row heart (LikeButton plain md glyph).
const SMALL = 24;
// The small heart fills once the big one is this far into its flight — the
// moment it visually lands, before the calm spring finishes settling.
const ARRIVE_AT = 0.9;
/** LikeButtonFeed — a photo post in a feed. Tap the heart, or double-tap the
* photo: a big heart lands on the image, holds, then travels down into the
* action-row heart, which fills with light the moment it arrives. */
export function LikeButtonFeed() {
const reduce = useReducedMotion();
const [liked, setLiked] = React.useState(false);
const [saved, setSaved] = React.useState(false);
const lastTap = React.useRef(0);
// Layout of the photo, the action row and the like button inside it — the
// flight runs from the photo's centre to the button's glyph.
const [photo, setPhoto] = React.useState<LayoutRectangle | null>(null);
const [row, setRow] = React.useState<LayoutRectangle | null>(null);
const [like, setLike] = React.useState<LayoutRectangle | null>(null);
const land = useSharedValue(0); // 0 hidden … 1 landed on the photo
const fly = useSharedValue(0); // 0 on the photo … 1 at the button
const armed = useSharedValue(0); // 1 while a flight is waiting to arrive
const arrive = React.useCallback(() => setLiked(true), []);
useAnimatedReaction(
() => fly.value,
(v) => {
if (armed.value === 1 && v >= ARRIVE_AT) {
armed.value = 0;
runOnJS(arrive)();
}
}
);
const onPhotoPress = () => {
const now = Date.now();
if (now - lastTap.current >= DOUBLE_TAP_MS) {
lastTap.current = now;
return;
}
lastTap.current = 0;
// Double-tap only ever likes — it never un-likes.
if (reduce) {
// No travel: the heart ignites, holds, dims in place, and the button fills.
fly.value = 0;
armed.value = 0;
land.value = withSequence(withTiming(1, timing.fast), withDelay(HEART_HOLD_MS, withTiming(0, timing.recede)));
setTimeout(arrive, timing.fast.duration + HEART_HOLD_MS);
return;
}
fly.value = 0;
land.value = 0;
land.value = withSpring(1, spring.pop);
armed.value = 1;
fly.value = withDelay(HEART_HOLD_MS, withSpring(1, spring.surface));
};
// Flight vector from the big heart's centre to the small heart's centre.
const dx = photo && like ? like.x + SMALL / 2 - (photo.x + photo.width / 2) : 0;
const dy = photo && row && like ? row.y + like.y + like.height / 2 - (photo.y + photo.height / 2) : 0;
const bigStyle = useAnimatedStyle(() => {
const f = Math.min(1, fly.value);
// It dims as it goes and is out by the time it reaches the button.
const dim = interpolate(f, [0, ARRIVE_AT], [1, 0.2], "clamp") * (f >= ARRIVE_AT ? 0 : 1);
const lift = reduce ? 1 : 0.4 + land.value * 0.6;
const shrink = reduce ? 1 : interpolate(f, [0, 1], [1, SMALL / BIG]);
return {
opacity: Math.min(1, land.value * 1.4) * dim,
transform: [{ translateX: reduce ? 0 : dx * f }, { translateY: reduce ? 0 : dy * f }, { scale: lift * shrink }],
};
}, [reduce, dx, dy]);
return (
<View className="w-full gap-3">
<View className="flex-row items-center gap-3">
<Avatar size="md" source={{ uri: "https://i.pravatar.cc/150?img=12" }} fallback="TV" alt="Tomás Vidal" />
<View className="flex-1">
<Text className="text-[15px] font-semibold">tomas.vidal</Text>
<Text variant="muted" numberOfLines={1}>Laguna de los Tres, Patagonia</Text>
</View>
<Icon name="more-horizontal" color="mutedForeground" accessibilityLabel="More options" />
</View>
<Pressable
onPress={onPhotoPress}
onLayout={(e) => setPhoto(e.nativeEvent.layout)}
accessibilityRole="image"
accessibilityLabel="Sunrise over granite peaks above a glacial lake. Double-tap to like."
className="overflow-hidden rounded-2xl bg-muted"
style={{ aspectRatio: 4 / 5 }}
>
<Image source={{ uri: PHOTO }} style={{ width: "100%", height: "100%" }} resizeMode="cover" />
</Pressable>
<View className="flex-row items-center gap-4" onLayout={(e) => setRow(e.nativeEvent.layout)}>
<LikeButton liked={liked} onLikedChange={setLiked} count={1283} onLayout={(e) => setLike(e.nativeEvent.layout)} />
<View className="min-h-[44px] flex-row items-center gap-1.5">
<Icon name="message-circle" />
<Text className="text-[15px] font-semibold tabular-nums">46</Text>
</View>
<View className="min-h-[44px] flex-row items-center gap-1.5">
<Icon name="send" />
<Text className="text-[15px] font-semibold tabular-nums">12</Text>
</View>
<View className="flex-1" />
<Pressable
onPress={() => setSaved((s) => !s)}
hitSlop={10}
accessibilityRole="button"
accessibilityLabel="Save"
accessibilityState={{ selected: saved }}
className="min-h-[44px] justify-center"
>
<Icon name="bookmark" filled={saved} />
</Pressable>
</View>
<View className="gap-1">
<Text className="text-[15px] leading-snug">
<Text className="text-[15px] font-semibold">tomas.vidal </Text>
First light on Fitz Roy at 5:12am, three hours of switchbacks in the dark. Worth every one.
</Text>
<Text className="text-xs text-muted-foreground">2 hours ago</Text>
</View>
{/* The big heart flies above the column so it is never clipped by the photo. */}
{photo ? (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{ position: "absolute", left: photo.x + photo.width / 2 - BIG / 2, top: photo.y + photo.height / 2 - BIG / 2 }}
>
<Animated.View style={bigStyle}>
<Svg width={BIG} height={BIG} viewBox="0 0 24 24">
<Path d={HEART} fill="#FFFFFF" />
</Svg>
</Animated.View>
</View>
) : null}
</View>
);
} The overlay variant on a vertical video.
import * as React from "react";
import { Image, Pressable, Text as RNText, View, type LayoutRectangle } from "react-native";
import Animated, {
interpolate,
runOnJS,
useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
withDelay,
withSequence,
withSpring,
withTiming,
} from "react-native-reanimated";
import Svg, { Defs, LinearGradient, Path, Rect, Stop } from "react-native-svg";
import { spring, timing, useReducedMotion } from "@lumioui/core";
import { LikeButton } from "../like-button";
import { Avatar } from "../../avatar/avatar";
import { Icon, type IconName } from "../../icon/icon";
const FRAME = "https://images.unsplash.com/photo-1469334031218-e382a71b716b?w=900&h=1600&fit=crop&q=75&auto=format";
const HEART = "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z";
// Two taps inside this window count as a double-tap.
const DOUBLE_TAP_MS = 280;
// Act, hold, resolve: the big heart rests on the frame before it travels.
const HEART_HOLD_MS = 520;
const BIG = 104;
// The rail heart (LikeButton overlay md glyph).
const SMALL = 32;
// The rail heart fills once the big one is this far into its flight — the
// moment it visually lands, before the calm spring finishes settling.
const ARRIVE_AT = 0.9;
const SHADOW = { textShadowColor: "rgba(0,0,0,0.45)", textShadowRadius: 4, textShadowOffset: { width: 0, height: 1 } };
function RailAction({ icon, label, a11y }: { icon: IconName; label?: string; a11y: string }) {
return (
<Pressable accessibilityRole="button" accessibilityLabel={a11y} className="min-w-[44px] items-center gap-1">
<Icon name={icon} size="lg" color="#FFFFFF" />
{label ? (
<RNText className="text-[13px] font-semibold text-white tabular-nums" style={SHADOW}>
{label}
</RNText>
) : null}
</Pressable>
);
}
/** LikeButtonReels — the overlay variant on a vertical video. The white rail
* sits on the right edge over a bottom scrim. Double-tap the frame: a white
* heart lands, holds, then travels into the rail heart, which fills as it
* arrives and 48.2K swaps up to 48.3K. */
export function LikeButtonReels() {
const reduce = useReducedMotion();
const [liked, setLiked] = React.useState(false);
const lastTap = React.useRef(0);
// Frame size, the rail, and the like button inside the rail — the flight
// runs from the frame's centre to the rail heart's glyph.
const [frame, setFrame] = React.useState<{ width: number; height: number } | null>(null);
const [rail, setRail] = React.useState<LayoutRectangle | null>(null);
const [like, setLike] = React.useState<LayoutRectangle | null>(null);
const land = useSharedValue(0); // 0 hidden … 1 landed on the frame
const fly = useSharedValue(0); // 0 on the frame … 1 at the rail heart
const armed = useSharedValue(0); // 1 while a flight is waiting to arrive
const arrive = React.useCallback(() => setLiked(true), []);
useAnimatedReaction(
() => fly.value,
(v) => {
if (armed.value === 1 && v >= ARRIVE_AT) {
armed.value = 0;
runOnJS(arrive)();
}
}
);
const onFramePress = () => {
const now = Date.now();
if (now - lastTap.current >= DOUBLE_TAP_MS) {
lastTap.current = now;
return;
}
lastTap.current = 0;
// Double-tap only ever likes — it never un-likes.
if (reduce) {
fly.value = 0;
armed.value = 0;
land.value = withSequence(withTiming(1, timing.fast), withDelay(HEART_HOLD_MS, withTiming(0, timing.recede)));
setTimeout(arrive, timing.fast.duration + HEART_HOLD_MS);
return;
}
fly.value = 0;
land.value = 0;
land.value = withSpring(1, spring.pop);
armed.value = 1;
fly.value = withDelay(HEART_HOLD_MS, withSpring(1, spring.surface));
};
const dx = frame && rail && like ? rail.x + like.x + like.width / 2 - frame.width / 2 : 0;
const dy = frame && rail && like ? rail.y + like.y + SMALL / 2 - frame.height / 2 : 0;
const bigStyle = useAnimatedStyle(() => {
const f = Math.min(1, fly.value);
// It dims as it goes and is out by the time it reaches the rail.
const dim = interpolate(f, [0, ARRIVE_AT], [1, 0.3], "clamp") * (f >= ARRIVE_AT ? 0 : 1);
const lift = reduce ? 1 : 0.4 + land.value * 0.6;
const shrink = reduce ? 1 : interpolate(f, [0, 1], [1, SMALL / BIG]);
return {
opacity: Math.min(1, land.value * 1.4) * dim,
transform: [{ translateX: reduce ? 0 : dx * f }, { translateY: reduce ? 0 : dy * f }, { scale: lift * shrink }],
};
}, [reduce, dx, dy]);
return (
<View
className="w-full overflow-hidden rounded-3xl bg-neutral-900"
style={{ height: 600 }}
onLayout={(e) => setFrame({ width: e.nativeEvent.layout.width, height: e.nativeEvent.layout.height })}
>
<Pressable onPress={onFramePress} className="absolute inset-0" accessibilityRole="image" accessibilityLabel="Video. Double-tap to like.">
<Image source={{ uri: FRAME }} style={{ width: "100%", height: "100%" }} resizeMode="cover" />
{/* Scrim only where the white type sits — the frame keeps its colour. */}
<Svg style={{ position: "absolute", left: 0, right: 0, bottom: 0 }} width="100%" height={280} pointerEvents="none">
<Defs>
<LinearGradient id="reel-scrim" x1="0" y1="0" x2="0" y2="1">
<Stop offset="0" stopColor="#000" stopOpacity={0} />
<Stop offset="1" stopColor="#000" stopOpacity={0.62} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill="url(#reel-scrim)" />
</Svg>
</Pressable>
<View
className="absolute bottom-6 right-3 items-center gap-5"
pointerEvents="box-none"
onLayout={(e) => setRail(e.nativeEvent.layout)}
>
<LikeButton
variant="overlay"
liked={liked}
onLikedChange={setLiked}
count={48299}
onLayout={(e) => setLike(e.nativeEvent.layout)}
/>
<RailAction icon="message-circle" label="1,093" a11y="Comments, 1,093" />
<RailAction icon="send" label="2,410" a11y="Share" />
<RailAction icon="more-horizontal" a11y="More" />
</View>
<View className="absolute bottom-6 left-4 right-20 gap-2" pointerEvents="box-none">
<View className="flex-row items-center gap-2">
<Avatar size="sm" source={{ uri: "https://i.pravatar.cc/150?img=47" }} fallback="JO" alt="Juno Okafor" />
<RNText className="text-[15px] font-semibold text-white" style={SHADOW}>
juno.styles
</RNText>
<View className="rounded-lg border border-white/60 px-2 py-0.5">
<RNText className="text-[13px] font-semibold text-white">Follow</RNText>
</View>
</View>
<RNText className="text-[15px] leading-snug text-white" style={SHADOW} numberOfLines={2}>
Three ways to wear one linen overshirt this spring. Number two is the keeper.
</RNText>
<View className="flex-row items-center gap-1.5">
<Icon name="music" size="sm" color="#FFFFFF" />
<RNText className="text-[13px] text-white" style={SHADOW} numberOfLines={1}>
Sundays at Ochre · Pale Coast
</RNText>
</View>
</View>
{frame ? (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{ position: "absolute", left: frame.width / 2 - BIG / 2, top: frame.height / 2 - BIG / 2 }}
>
<Animated.View style={bigStyle}>
<Svg width={BIG} height={BIG} viewBox="0 0 24 24">
<Path d={HEART} fill="#FFFFFF" />
</Svg>
</Animated.View>
</View>
) : null}
</View>
);
} Save-to-library hearts on an album tracklist.
import * as React from "react";
import { Image, View } from "react-native";
import { Accent } from "@lumioui/core";
import { LikeButton } from "../like-button";
import { Text } from "../../text/text";
const COVER = "https://images.unsplash.com/photo-1541701494587-cb58502866ab?w=320&h=320&fit=crop&q=70&auto=format";
const TRACKS = [
{ title: "Salt in the Gutters", length: "3:41" },
{ title: "Low Tide Hours", length: "4:12", explicit: true },
{ title: "Paper Lanterns, Pier 9", length: "3:58" },
{ title: "Halyard", length: "2:47" },
{ title: "Come Back Brighter", length: "5:06" },
{ title: "The Long Way Round", length: "4:30" },
];
/** LikeButtonTracks — save-to-library hearts on an album tracklist. Count-less
* small hearts in the pink media accent; the saved tally under the header
* follows each tap. */
export function LikeButtonTracks() {
const [saved, setSaved] = React.useState<Record<number, boolean>>({ 1: true });
const savedCount = Object.values(saved).filter(Boolean).length;
return (
<Accent color="pink" className="w-full">
<View className="w-full gap-5">
<View className="flex-row items-center gap-4">
<Image source={{ uri: COVER }} className="h-24 w-24 rounded-xl bg-muted" accessibilityIgnoresInvertColors />
<View className="flex-1 gap-1">
<Text className="text-xl font-bold tracking-tight" numberOfLines={1}>Low Tide Hours</Text>
<Text className="text-[15px] text-muted-foreground">Marrow & Vale</Text>
<Text className="text-xs text-muted-foreground tabular-nums">
Album · 2024 · {savedCount === 0 ? "None saved" : `${savedCount} of ${TRACKS.length} saved`}
</Text>
</View>
</View>
<View className="overflow-hidden rounded-2xl bg-card">
{TRACKS.map((t, i) => (
<View key={t.title}>
{i > 0 ? <View className="ml-12 h-px bg-border" /> : null}
<View className="min-h-[56px] flex-row items-center pl-4 pr-2">
<Text className="w-8 text-[15px] text-muted-foreground tabular-nums">{i + 1}</Text>
<View className="flex-1 gap-0.5">
<Text className="text-base font-medium" numberOfLines={1}>{t.title}</Text>
<View className="flex-row items-center gap-1.5">
{t.explicit ? (
<View className="h-4 w-4 items-center justify-center rounded-sm bg-muted-foreground">
<Text className="text-xs font-bold leading-none text-card">E</Text>
</View>
) : null}
<Text className="text-sm text-muted-foreground tabular-nums">{t.length}</Text>
</View>
</View>
<LikeButton
size="sm"
color="primary"
className="w-11 justify-center"
liked={!!saved[i]}
onLikedChange={(v) => setSaved((s) => ({ ...s, [i]: v }))}
accessibilityLabel={`Save ${t.title}`}
/>
</View>
</View>
))}
</View>
</View>
</Accent>
);
} API reference
liked boolean Controlled liked state. Omit and use defaultLiked for uncontrolled.
defaultLiked boolean Uncontrolled initial state. Default false.
false onLikedChange (liked: boolean) => void Fires with the next state on every tap.
—count number Likes from everyone else. The viewer's own like is added on top, so toggling never needs the parent to recompute the total. Omit to hide the count.
—formatCount (n: number) => string Count formatter. Default formatLikeCount (1,284 · 12.4K · 1.2M).
formatLikeCount hideCount boolean Hide the count even when count is set.
false variant "plain" | "pill" | "overlay" plain — icon + inline count (feeds). pill — bordered chip (comments, reactions). overlay — white stacked icon over video/photo (reels).
"plain" size "sm" | "md" | "lg" Glyph + count scale. Default "md".
"md" color keyof ColorTokens | (string & {}) Liked fill colour: a theme token ("primary", "destructive"…) or any colour. Default the social red.
LIKE_RED noBurst boolean Skip the light pool under the heart — for dense rows (comments, lists). The rising fill and the count swap stay.
false haptic boolean Haptic on like. Default true.
true disabled boolean — accessibilityLabel string Screen-reader name. Default "Like".
"Like" className string — countClassName string Extra classes for the count text.
—