suiss/ui ยท Interaction
Image Viewer
A full-screen photo viewer with swipe paging, pinch and double-tap zoom, and swipe down to close.
Image Viewer is an open-source interaction from suiss/ui for React Native, SwiftUI and Jetpack Compose. The @esuiss/ui CLI copies its source into your project, so you own the code.


import { Image, View } from "react-native"
import {
ImageViewer,
ImageViewerContent,
type ImageViewerImage,
ImageViewerTrigger,
} from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",
},import { Image, View } from "react-native"
import {
ImageViewer,
ImageViewerContent,
type ImageViewerImage,
ImageViewerTrigger,
} from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
import { radius, useTheme } from "@/components/ui/theme"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",import SwiftUI
import UIKit
struct ImageViewerOpenByDefaultExample: View {
var body: some View {
ImageViewerGallery(open: true, index: 1)
}
}
struct ImageViewerPhoto {
let url: URL
let label: String
}
@MainActor let imageViewerPhotos = [
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80")!, label: "Mountain lake at sunrise"),import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValueImageViewer opens a set of images full screen on a black background, starting at the pressed thumbnail. A counter such as 2 of 5 and a close button sit at the top, below the safe area.
Swipe sideways to page between images, with resistance at the first and last image. Pinch to zoom between 1x and 4x around the fingers, double-tap to zoom to 2.5x at the tapped point or back to 1x, and drag to pan while zoomed. Swiping up or down far enough closes the viewer, and a single tap toggles the controls.
Installation
$ pnpm dlx shadcn@latest add @esuiss/image-viewerSee Installation for the components.json setup. Or use the suiss/ui CLI:
$ pnpm dlx @esuiss/ui@latest add interactions image-viewer$ pnpm dlx shadcn@latest add @esuiss/image-viewerSee Installation for the components.json setup. Or use the suiss/ui CLI:
$ pnpm dlx @esuiss/ui@latest add interactions image-viewer --platform swift$ pnpm dlx shadcn@latest add @esuiss/image-viewerSee Installation for the components.json setup. Or use the suiss/ui CLI:
$ pnpm dlx @esuiss/ui@latest add interactions image-viewer --platform kotlin- Install the following dependencies:
npx expo install cn phosphor-react-native react-native-gesture-handler react-native-reanimated react-native-safe-area-context react-native-screens react-native-svg react-native-worklets-
Copy the animated view into
components/ui/animated-view.tsx:
import { Pressable } from "react-native"
import Animated from "react-native-reanimated"
const AnimatedPressable = Animated.createAnimatedComponent(Pressable)
type AnimatedViewProps =
| (React.ComponentProps<typeof Animated.View> &
React.RefAttributes<React.ComponentRef<typeof Animated.View>> & {
as?: "View"
})
| (React.ComponentProps<typeof AnimatedPressable> &
React.RefAttributes<React.ComponentRef<typeof AnimatedPressable>> & {
as: "Pressable"
})
function AnimatedView(props: AnimatedViewProps) {- Copy the primitives it uses into
components/primitives:
import type { HostInstance } from "react-native"
import type {
BaseUIChangeEventDetails,
BaseUIGenericEventDetails,
ChangeEvent,
} from "./types"
const REASONS = {
none: "none",
triggerPress: "trigger-press",
triggerLongPress: "trigger-long-press",
outsidePress: "outside-press",
itemPress: "item-press",
closePress: "close-press",
backPress: "back-press",
accessibilityEscape: "accessibility-escape",import * as React from "react"
type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"
type HapticsNotificationType = "success" | "warning" | "error"
interface HapticsAdapter {
impact(style: HapticsImpactStyle): void
selection(): void
notification(type: HapticsNotificationType): void
}
interface HapticsContextValue {
adapter: HapticsAdapter | null
enabled: boolean
}import * as React from "react"
import { BackHandler } from "react-native"
function useEffectEvent<TArgs extends readonly unknown[], TResult>(
callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
const callbackRef = React.useRef(callback)
React.useLayoutEffect(() => {
callbackRef.current = callback
})
return React.useCallback(
(...args: TArgs): TResult => callbackRef.current(...args),
[]
)import * as React from "react"
import {
type AccessibilityActionEvent,
type GestureResponderEvent,
Image,
type ImageLoadEvent,
type ImageSourcePropType,
Pressable,
StyleSheet,
useWindowDimensions,
View,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
ReduceMotion,
type SharedValue,type AnyProps = Record<string, unknown>
type PropsGetter = (previous: AnyProps) => object
type MergePropsInput = object | PropsGetter | null | undefined
type Handler = (...args: unknown[]) => unknown
type StyleCallback = (state: never) => unknown
const EMPTY_PROPS: AnyProps = {}
function isEventHandler(key: string, value: unknown) {
const code0 = key.charCodeAt(0)
const code1 = key.charCodeAt(1)
const code2 = key.charCodeAt(2)import * as React from "react"
import { HapticsContext } from "./haptics"
const DEFAULT_PORTAL_HOST = "INTERNAL_PRIMITIVE_DEFAULT_HOST_NAME"
type PortalEntries = ReadonlyMap<string, React.ReactNode>
const EMPTY_ENTRIES: PortalEntries = new Map()
let hosts: ReadonlyMap<string, PortalEntries> = new Map()
const listeners = new Set<() => void>()
function emit() {
for (const listener of listeners) listener()
}import type * as React from "react"
import type {
GestureResponderEvent,
HostInstance,
NativeSyntheticEvent,
StyleProp,
ViewStyle,
} from "react-native"
type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"
type ComponentRenderFn<Props, State> = (
props: Props,
state: Stateimport * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"
interface CancelableDetails {
readonly isCanceled: boolean
}
interface UseControllableStateParameters<
T,
Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
value?: T | undefined
defaultValue: T
onChange?: ((value: T, details: Details) => void) | undefined
}import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"
type AnyProps = Record<string, unknown>
type RefInput<T> = React.Ref<T> | undefined
interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
defaultComponent?: React.ElementType | undefined
render?: RenderProp<Props, State> | undefined
props?: object | readonly (object | null | undefined)[] | undefined
state?: State | undefined
ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
className?: ClassNameProp<State>- Copy and paste the following code into
components/interactions/image-viewer.tsx:
import { cn } from "cn"
import { XIcon } from "phosphor-react-native"
import * as React from "react"
import { Platform, View } from "react-native"
import { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { FullWindowOverlay as RNFullWindowOverlay } from "react-native-screens"
import * as ImageViewerPrimitive from "@/components/primitives/image-viewer"
import { resolveClassName } from "@/components/primitives/use-render"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
type ImageViewerImage = ImageViewerPrimitive.ImageViewerImage
const FullWindowOverlay =- Update the import paths to match your project setup.
- Install the following dependencies:
npx expo install cn phosphor-react-native react-native-gesture-handler react-native-reanimated react-native-safe-area-context react-native-screens react-native-svg react-native-worklets-
Copy the animated view into
components/ui/animated-view.tsx:
import { Pressable } from "react-native"
import Animated from "react-native-reanimated"
const AnimatedPressable = Animated.createAnimatedComponent(Pressable)
type AnimatedViewProps =
| (React.ComponentProps<typeof Animated.View> &
React.RefAttributes<React.ComponentRef<typeof Animated.View>> & {
as?: "View"
})
| (React.ComponentProps<typeof AnimatedPressable> &
React.RefAttributes<React.ComponentRef<typeof AnimatedPressable>> & {
as: "Pressable"
})
function AnimatedView(props: AnimatedViewProps) {- Copy the primitives it uses into
components/primitives:
import type { HostInstance } from "react-native"
import type {
BaseUIChangeEventDetails,
BaseUIGenericEventDetails,
ChangeEvent,
} from "./types"
const REASONS = {
none: "none",
triggerPress: "trigger-press",
triggerLongPress: "trigger-long-press",
outsidePress: "outside-press",
itemPress: "item-press",
closePress: "close-press",
backPress: "back-press",
accessibilityEscape: "accessibility-escape",import * as React from "react"
type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"
type HapticsNotificationType = "success" | "warning" | "error"
interface HapticsAdapter {
impact(style: HapticsImpactStyle): void
selection(): void
notification(type: HapticsNotificationType): void
}
interface HapticsContextValue {
adapter: HapticsAdapter | null
enabled: boolean
}import * as React from "react"
import { BackHandler } from "react-native"
function useEffectEvent<TArgs extends readonly unknown[], TResult>(
callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
const callbackRef = React.useRef(callback)
React.useLayoutEffect(() => {
callbackRef.current = callback
})
return React.useCallback(
(...args: TArgs): TResult => callbackRef.current(...args),
[]
)import * as React from "react"
import {
type AccessibilityActionEvent,
type GestureResponderEvent,
Image,
type ImageLoadEvent,
type ImageSourcePropType,
Pressable,
StyleSheet,
useWindowDimensions,
View,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
ReduceMotion,
type SharedValue,type AnyProps = Record<string, unknown>
type PropsGetter = (previous: AnyProps) => object
type MergePropsInput = object | PropsGetter | null | undefined
type Handler = (...args: unknown[]) => unknown
type StyleCallback = (state: never) => unknown
const EMPTY_PROPS: AnyProps = {}
function isEventHandler(key: string, value: unknown) {
const code0 = key.charCodeAt(0)
const code1 = key.charCodeAt(1)
const code2 = key.charCodeAt(2)import * as React from "react"
import { HapticsContext } from "./haptics"
const DEFAULT_PORTAL_HOST = "INTERNAL_PRIMITIVE_DEFAULT_HOST_NAME"
type PortalEntries = ReadonlyMap<string, React.ReactNode>
const EMPTY_ENTRIES: PortalEntries = new Map()
let hosts: ReadonlyMap<string, PortalEntries> = new Map()
const listeners = new Set<() => void>()
function emit() {
for (const listener of listeners) listener()
}import type * as React from "react"
import type {
GestureResponderEvent,
HostInstance,
NativeSyntheticEvent,
StyleProp,
ViewStyle,
} from "react-native"
type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"
type ComponentRenderFn<Props, State> = (
props: Props,
state: Stateimport * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"
interface CancelableDetails {
readonly isCanceled: boolean
}
interface UseControllableStateParameters<
T,
Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
value?: T | undefined
defaultValue: T
onChange?: ((value: T, details: Details) => void) | undefined
}import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"
type AnyProps = Record<string, unknown>
type RefInput<T> = React.Ref<T> | undefined
interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
defaultComponent?: React.ElementType | undefined
render?: RenderProp<Props, State> | undefined
props?: object | readonly (object | null | undefined)[] | undefined
state?: State | undefined
ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
className?: ClassNameProp<State>- Copy and paste the following code into
components/interactions/image-viewer.tsx:
import { cn } from "cn"
import { XIcon } from "phosphor-react-native"
import * as React from "react"
import { Platform, View } from "react-native"
import { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { FullWindowOverlay as RNFullWindowOverlay } from "react-native-screens"
import * as ImageViewerPrimitive from "@/components/primitives/image-viewer"
import { resolveClassName } from "@/components/primitives/use-render"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
type ImageViewerImage = ImageViewerPrimitive.ImageViewerImage
const FullWindowOverlay =- Update the import paths to match your project setup.
- Install the following dependencies:
npx expo install phosphor-react-native react-native-gesture-handler react-native-reanimated react-native-safe-area-context react-native-screens react-native-svg react-native-worklets-
Copy the animated view into
components/ui/animated-view.tsx:
import { Pressable } from "react-native"
import Animated from "react-native-reanimated"
const AnimatedPressable = Animated.createAnimatedComponent(Pressable)
type AnimatedViewProps =
| (React.ComponentProps<typeof Animated.View> &
React.RefAttributes<React.ComponentRef<typeof Animated.View>> & {
as?: "View"
})
| (React.ComponentProps<typeof AnimatedPressable> &
React.RefAttributes<React.ComponentRef<typeof AnimatedPressable>> & {
as: "Pressable"
})
function AnimatedView(props: AnimatedViewProps) {- Copy the primitives it uses into
components/primitives:
import type { HostInstance } from "react-native"
import type {
BaseUIChangeEventDetails,
BaseUIGenericEventDetails,
ChangeEvent,
} from "./types"
const REASONS = {
none: "none",
triggerPress: "trigger-press",
triggerLongPress: "trigger-long-press",
outsidePress: "outside-press",
itemPress: "item-press",
closePress: "close-press",
backPress: "back-press",
accessibilityEscape: "accessibility-escape",import * as React from "react"
type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"
type HapticsNotificationType = "success" | "warning" | "error"
interface HapticsAdapter {
impact(style: HapticsImpactStyle): void
selection(): void
notification(type: HapticsNotificationType): void
}
interface HapticsContextValue {
adapter: HapticsAdapter | null
enabled: boolean
}import * as React from "react"
import { BackHandler } from "react-native"
function useEffectEvent<TArgs extends readonly unknown[], TResult>(
callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
const callbackRef = React.useRef(callback)
React.useLayoutEffect(() => {
callbackRef.current = callback
})
return React.useCallback(
(...args: TArgs): TResult => callbackRef.current(...args),
[]
)import * as React from "react"
import {
type AccessibilityActionEvent,
type GestureResponderEvent,
Image,
type ImageLoadEvent,
type ImageSourcePropType,
Pressable,
StyleSheet,
useWindowDimensions,
View,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
ReduceMotion,
type SharedValue,type AnyProps = Record<string, unknown>
type PropsGetter = (previous: AnyProps) => object
type MergePropsInput = object | PropsGetter | null | undefined
type Handler = (...args: unknown[]) => unknown
type StyleCallback = (state: never) => unknown
const EMPTY_PROPS: AnyProps = {}
function isEventHandler(key: string, value: unknown) {
const code0 = key.charCodeAt(0)
const code1 = key.charCodeAt(1)
const code2 = key.charCodeAt(2)import * as React from "react"
import { HapticsContext } from "./haptics"
const DEFAULT_PORTAL_HOST = "INTERNAL_PRIMITIVE_DEFAULT_HOST_NAME"
type PortalEntries = ReadonlyMap<string, React.ReactNode>
const EMPTY_ENTRIES: PortalEntries = new Map()
let hosts: ReadonlyMap<string, PortalEntries> = new Map()
const listeners = new Set<() => void>()
function emit() {
for (const listener of listeners) listener()
}import type * as React from "react"
import type {
GestureResponderEvent,
HostInstance,
NativeSyntheticEvent,
StyleProp,
ViewStyle,
} from "react-native"
type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"
type ComponentRenderFn<Props, State> = (
props: Props,
state: Stateimport * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"
interface CancelableDetails {
readonly isCanceled: boolean
}
interface UseControllableStateParameters<
T,
Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
value?: T | undefined
defaultValue: T
onChange?: ((value: T, details: Details) => void) | undefined
}import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"
type AnyProps = Record<string, unknown>
type RefInput<T> = React.Ref<T> | undefined
interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
defaultComponent?: React.ElementType | undefined
render?: RenderProp<Props, State> | undefined
props?: object | readonly (object | null | undefined)[] | undefined
state?: State | undefined
ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
className?: ClassNameProp<State>- Copy and paste the following code into
components/interactions/image-viewer.tsx:
import { XIcon } from "phosphor-react-native"
import * as React from "react"
import {
Platform,
Pressable,
StyleSheet,
View,
type ViewStyle,
} from "react-native"
import { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { FullWindowOverlay as RNFullWindowOverlay } from "react-native-screens"
import * as ImageViewerPrimitive from "@/components/primitives/image-viewer"
import { resolveStyle } from "@/components/primitives/use-render"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"- Update the import paths to match your project setup.
-
Target iOS 17 or later.
-
Add the Swift package to your app:
.package(url: "https://github.com/phosphor-icons/swift", from: "2.1.0")- Copy the theme files every view uses:
import CoreText
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
}import SwiftUI
public enum EsuissColor {
public static let background = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
public static let foreground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
public static let card = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
public static let cardForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
public static let popover = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
public static let popoverForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
public static let primary = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0A84FF))
public static let primaryForeground = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
public static let secondary = Color.adaptive(light: .init(0x000000, 0.04), dark: .init(0xFFFFFF, 0.1))
public static let secondaryForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
public static let muted = Color.adaptive(light: .init(0xF5F5F7), dark: .init(0x161617))
public static let mutedForeground = Color.adaptive(light: .init(0x6E6E73), dark: .init(0x86868B))
public static let accent = Color.adaptive(light: .init(0x000000, 0.06), dark: .init(0xFFFFFF, 0.1))- Copy the source and every file it uses:
import PhosphorSwift
import SwiftUI
enum ImageViewerMath {
static let minScale: CGFloat = 1
static let maxScale: CGFloat = 4
static let doubleTapScale: CGFloat = 2.5
static let dismissDistance: CGFloat = 120
static let fadeDistance: CGFloat = 300
static func clampScale(_ scale: CGFloat) -> CGFloat {
min(max(scale, minScale), maxScale)
}
static func clampOffset(_ offset: CGSize, scale: CGFloat, size: CGSize) -> CGSize {
let limitX = max(0, (size.width * scale - size.width) / 2)import SwiftUI
public struct VariantButtonStyle: ButtonStyle {
public enum Variant: CaseIterable, Sendable {
case `default`, outline, secondary, tinted, ghost, plain, destructive, link
}
public enum Size: CaseIterable, Sendable {
case `default`, xs, sm, lg, xl, form, icon, iconXs, iconSm, iconLg, iconXl
var height: CGFloat {
switch self {
case .xs, .iconXs: Metrics.Height.buttonXs
case .sm, .iconSm: Metrics.Height.buttonSm
case .default, .icon: Metrics.Height.button
case .lg, .iconLg: Metrics.Height.buttonLgimport SwiftUI
extension EnvironmentValues {
@Entry var buttonGroup: Axis? = nil
@Entry var buttonGroupSize: CGSize = .zero
}
enum ButtonGroupSpace: Hashable {
case group
}
struct ButtonGroupFrame {
let bounds: Anchor<CGRect>
let outlined: Bool
}import PhosphorSwift
import SwiftUI
public enum CarouselOrientation: CaseIterable, Sendable {
case horizontal, vertical
}
public enum CarouselDotsVariant: CaseIterable, Sendable {
case `default`, plain
}
let carouselAnimation = Animation.timingCurve(0.32, 0.72, 0, 1, duration: 0.5)
enum CarouselMath {
static func clamp(_ index: Int, count: Int) -> Int {
count == 0 ? 0 : min(max(index, 0), count - 1)import Observation
import PhosphorSwift
import SwiftUI
public enum PopupAlignment: Sendable, CaseIterable {
case start, center, end
}
struct OverlayDismiss: Sendable {
let action: @MainActor @Sendable () -> Void
@MainActor func callAsFunction() {
action()
}
}- Add the files to your app target.
- Apply the Compose compiler plugin, enable Compose, set
compileSdkto 37 or higher andminSdkto 24 or higher, and add the dependencies:
plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
android {
compileSdk = 37
defaultConfig { minSdk = 24 }
buildFeatures { compose = true }
}
dependencies {
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")
}- Copy the theme files every view uses:
package com.esuiss.ui.theme
import android.content.res.AssetManager
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.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Fontpackage com.esuiss.ui.theme
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
@Immutable
data class Colors(
val background: Color,
val foreground: Color,
val card: Color,
val cardForeground: Color,
val popover: Color,
val popoverForeground: Color,
val primary: Color,- Copy the source and every file it uses:
package com.esuiss.ui.interactions
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculateCentroid
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Rowpackage com.esuiss.ui.components
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.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextpackage com.esuiss.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutablepackage 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 }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,package com.esuiss.ui.components
import android.os.Build
import android.view.Window
import android.view.WindowManager
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.EnterExitState
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideIn- Update the
com.esuiss.uipackage names to match your project.
Usage
import { Image, View } from "react-native"
import { ImageViewer, ImageViewerContent, type ImageViewerImage, ImageViewerTrigger } from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",
},
{
source: {
uri: "https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1200&q=80",
},
accessibilityLabel: "Valley with a river",
},
{
source: {
uri: "https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1200&q=80",
},
accessibilityLabel: "Lake between mountains",
},
{
source: {
uri: "https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&q=80",
},
accessibilityLabel: "Foggy hills",
},
{
source: {
uri: "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1200&q=80",
},
accessibilityLabel: "Forest path",
},
]
function Gallery({
defaultOpen,
defaultIndex,
}: {
defaultOpen?: boolean
defaultIndex?: number
}) {
return (
<ImageViewer
images={images}
defaultOpen={defaultOpen}
defaultIndex={defaultIndex}
>
<View className="gap-3">
<View className="flex-row flex-wrap gap-2">
{images.map((image, index) => (
<ImageViewerTrigger
key={image.accessibilityLabel}
index={index}
accessibilityLabel={image.accessibilityLabel}
className="aspect-square w-[31%] overflow-hidden rounded-xl bg-muted"
>
<Image source={image.source} className="h-full w-full" />
</ImageViewerTrigger>
))}
</View>
<Text variant="muted">
Tap a photo. Pinch or double-tap to zoom, swipe down to close.
</Text>
</View>
<ImageViewerContent />
</ImageViewer>
)
}
export function ImageViewerExample() {
return (
<Gallery />
)
}import { Image, View } from "react-native"
import { ImageViewer, ImageViewerContent, type ImageViewerImage, ImageViewerTrigger } from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
import { radius, useTheme } from "@/components/ui/theme"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",
},
{
source: {
uri: "https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1200&q=80",
},
accessibilityLabel: "Valley with a river",
},
{
source: {
uri: "https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1200&q=80",
},
accessibilityLabel: "Lake between mountains",
},
{
source: {
uri: "https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&q=80",
},
accessibilityLabel: "Foggy hills",
},
{
source: {
uri: "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1200&q=80",
},
accessibilityLabel: "Forest path",
},
]
function Gallery({
defaultOpen,
defaultIndex,
}: {
defaultOpen?: boolean
defaultIndex?: number
}) {
const { colors } = useTheme()
return (
<ImageViewer
images={images}
defaultOpen={defaultOpen}
defaultIndex={defaultIndex}
>
<View style={{ gap: 12 }}>
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
{images.map((image, index) => (
<ImageViewerTrigger
key={image.accessibilityLabel}
index={index}
accessibilityLabel={image.accessibilityLabel}
style={{ aspectRatio: 1, width: "31%", overflow: "hidden", borderRadius: radius.xl, backgroundColor: colors.muted }}
>
<Image source={image.source} style={{ height: "100%", width: "100%" }} />
</ImageViewerTrigger>
))}
</View>
<Text variant="muted">
Tap a photo. Pinch or double-tap to zoom, swipe down to close.
</Text>
</View>
<ImageViewerContent />
</ImageViewer>
)
}
export function ImageViewerExample() {
return (
<Gallery />
)
}import SwiftUI
import UIKit
struct ImageViewerPhoto {
let url: URL
let label: String
}
@MainActor let imageViewerPhotos = [
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80")!, label: "Mountain lake at sunrise"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1200&q=80")!, label: "Valley with a river"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1200&q=80")!, label: "Lake between mountains"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&q=80")!, label: "Foggy hills"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1200&q=80")!, label: "Forest path"),
]
struct ImageViewerGallery: View {
@State private var open: Bool
@State private var index: Int
@State private var loaded: [Int: UIImage] = [:]
init(open: Bool = false, index: Int = 0) {
_open = State(initialValue: open)
_index = State(initialValue: index)
}
var images: [Image] {
imageViewerPhotos.indices.map { page in
let photo = imageViewerPhotos[page]
if let cgImage = loaded[page]?.cgImage {
return Image(cgImage, scale: 1, orientation: .up, label: Text(verbatim: photo.label))
}
return Image(uiImage: UIImage())
}
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
GeometryReader { proxy in
let side = ((proxy.size.width - 16) / 3).rounded(.down)
FlowRow(spacing: 8) {
ForEach(imageViewerPhotos.indices, id: \.self) { page in
Button {
index = page
open = true
} label: {
thumbnail(page)
.frame(width: side, height: side)
.background(EsuissColor.muted)
.clipShape(RoundedRectangle(cornerRadius: Radius.xl, style: .continuous))
}
.buttonStyle(.plain)
.accessibilityLabel(Text(verbatim: imageViewerPhotos[page].label))
}
}
}
.aspectRatio(3 / 2, contentMode: .fit)
Text("Tap a photo. Pinch or double-tap to zoom, swipe down to close.")
.textVariant(.muted)
}
.imageViewer(isPresented: $open, images: images, index: $index)
.task {
await load()
}
}
@ViewBuilder
func thumbnail(_ page: Int) -> some View {
if let image = loaded[page] {
Image(uiImage: image)
.resizable()
.scaledToFill()
} else {
EsuissColor.muted
}
}
func load() async {
await withTaskGroup(of: (Int, UIImage?).self) { group in
for (page, photo) in imageViewerPhotos.enumerated() {
group.addTask {
guard let (data, _) = try? await URLSession.shared.data(from: photo.url) else { return (page, nil) }
return (page, UIImage(data: data))
}
}
for await (page, image) in group {
if let image { loaded[page] = image }
}
}
}
}
struct FlowRow: Layout {
var spacing: CGFloat = 12
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews)
let width = rows.map(\.width).max() ?? 0
let height = rows.map(\.height).reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0))
return CGSize(width: width, height: height)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
var y = bounds.minY
for row in arrange(width: bounds.width, subviews: subviews) {
var x = bounds.minX
for index in row.indices {
let size = subviews[index].sizeThatFits(.unspecified)
subviews[index].place(
at: CGPoint(x: x, y: y + (row.height - size.height) / 2),
proposal: ProposedViewSize(size)
)
x += size.width + spacing
}
y += row.height + spacing
}
}
struct Row {
var indices: [Int] = []
var width: CGFloat = 0
var height: CGFloat = 0
}
func arrange(width: CGFloat, subviews: Subviews) -> [Row] {
var rows: [Row] = []
var row = Row()
for index in subviews.indices {
let size = subviews[index].sizeThatFits(.unspecified)
let next = row.indices.isEmpty ? size.width : row.width + spacing + size.width
if next > width && !row.indices.isEmpty {
rows.append(row)
row = Row()
}
row.width = row.indices.isEmpty ? size.width : row.width + spacing + size.width
row.height = max(row.height, size.height)
row.indices.append(index)
}
if !row.indices.isEmpty { rows.append(row) }
return rows
}
}import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.TextVariant
import com.esuiss.ui.interactions.ImageViewer
import com.esuiss.ui.interactions.ImageViewerImage
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
@Composable
fun ImageViewerExample() {
ImageViewerGallery(defaultOpen = false, defaultIndex = 0)
}
class ImageViewerGradient(private val from: Color, private val to: Color, private val size: Size) : Painter() {
override val intrinsicSize: Size
get() = size
override fun DrawScope.onDraw() {
drawRect(Brush.linearGradient(listOf(from, to), start = Offset.Zero, end = Offset(this.size.width, this.size.height)))
}
}
val imageViewerLabels = listOf(
"Mountain lake at sunrise",
"Valley with a river",
"Lake between mountains",
"Foggy hills",
"Forest path",
)
@Composable
fun ImageViewerGallery(defaultOpen: Boolean, defaultIndex: Int) {
val colors = EsuissTheme.colors
var open by rememberSaveable { mutableStateOf(defaultOpen) }
var index by rememberSaveable { mutableIntStateOf(defaultIndex) }
val tones = listOf(
Palette.orange500 to Palette.pink500,
Palette.teal500 to Palette.blue500,
Palette.indigo500 to Palette.cyan500,
Palette.zinc500 to Palette.teal400,
Palette.green500 to Palette.amber500,
)
val images = remember(tones) {
imageViewerLabels.mapIndexed { position, label ->
val (from, to) = tones[position]
ImageViewerImage(ImageViewerGradient(from, to, Size(1200f, 800f)), contentDescription = label)
}
}
val shape = RoundedCornerShape(Radius.xl)
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
images.forEachIndexed { position, image ->
Image(
painter = image.painter,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth(0.31f)
.aspectRatio(1f)
.clip(shape)
.background(colors.muted, shape)
.semantics { contentDescription = imageViewerLabels[position] }
.clickable(role = Role.Button) {
index = position
open = true
},
)
}
}
Text("Tap a photo. Pinch or double-tap to zoom, swipe down to close.", variant = TextVariant.Muted)
}
ImageViewer(
open = open,
onOpenChange = { open = it },
images = images,
index = index,
onIndexChange = { index = it },
)
}Examples
Default


import { Image, View } from "react-native"
import {
ImageViewer,
ImageViewerContent,
type ImageViewerImage,
ImageViewerTrigger,
} from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",
},import { Image, View } from "react-native"
import {
ImageViewer,
ImageViewerContent,
type ImageViewerImage,
ImageViewerTrigger,
} from "@/components/interactions/image-viewer"
import { Text } from "@/components/ui/text"
import { radius, useTheme } from "@/components/ui/theme"
const images: ImageViewerImage[] = [
{
source: {
uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80",
},
accessibilityLabel: "Mountain lake at sunrise",import SwiftUI
import UIKit
struct ImageViewerPhoto {
let url: URL
let label: String
}
@MainActor let imageViewerPhotos = [
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=1200&q=80")!, label: "Mountain lake at sunrise"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1200&q=80")!, label: "Valley with a river"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1200&q=80")!, label: "Lake between mountains"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&q=80")!, label: "Foggy hills"),
ImageViewerPhoto(url: URL(string: "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1200&q=80")!, label: "Forest path"),
]import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValueAccessibility
- The viewer is modal for screen readers, and the escape gesture closes it.
- The current page is
adjustable: swiping up or down with a screen reader moves between images. It is labelled by the image'saccessibilityLabel, orImage n, with the counter as its value. - Triggers have the
buttonrole and expose theirexpandedstate.
API Reference
ImageViewer
The root that holds the images, open state and current index.
| Prop | Type | Default |
|---|---|---|
onOpenChange | (open: boolean) => void | - |
onIndexChange | (index: number) => void | - |
Also accepts the props of React.ComponentProps<typeof ImageViewerPrimitive.Root>.
Pass images to ImageViewer, wrap each thumbnail in an ImageViewerTrigger with its index, and render one ImageViewerContent. Give each image an accessibilityLabel. The ImageViewerImage type is exported.
Open state and the current image can be uncontrolled with defaultOpen and defaultIndex, or controlled with open, onOpenChange, index and onIndexChange. onIndexChange is called with the new index after paging. useImageViewer returns open, index, count and images.
ImageViewerTrigger
A pressable thumbnail that opens the viewer at its index.
Also accepts the props of React.ComponentProps<typeof ImageViewerPrimitive.Trigger>.
ImageViewerContent
The full-screen viewer with the pages, counter and close button.
| Prop | Type | Default |
|---|---|---|
portalHost | string | - |
closeLabel | string | "Close" |
indexLabel | (index: number, count: number) => string | defaultIndexLabel |
className | string | - |
portalHost names a portal host to render into. closeLabel is the accessibility label of the close button, and indexLabel formats the counter from the index and count, as n of count by default. The viewer fades in and out, and paging and zoom animations respect the system reduce motion setting. It stays dark in light mode. On iOS it renders in a full-window overlay so it appears above native screens.
.imageViewer
| Parameter | Type | Default |
|---|---|---|
isPresented | Binding<Bool> | - |
images | [Image] | - |
index | Binding<Int> | - |
ImageViewer
The root that holds the images, open state and current index.
| Parameter | Type | Default |
|---|---|---|
images | [Image] | - |
index | Binding<Int> | - |
ImageViewerImage
| Parameter | Type | Default |
|---|---|---|
painter | Painter | - |
contentDescription | String? | null |
ImageViewer
The root that holds the images, open state and current index.
| Parameter | Type | Default |
|---|---|---|
open | Boolean | - |
onOpenChange | (Boolean) -> Unit | - |
images | List<ImageViewerImage> | - |
index | Int | - |
onIndexChange | (Int) -> Unit | - |
modifier | Modifier | Modifier |
closeLabel | String | "Close" |
indexLabel | (index: Int, count: Int) -> String | { current, count -> "${current + 1} of $count" } |