# useTilt
Package: @mantine/hooks
Import: import { useTilt } from '@mantine/hooks';

## Usage

`use-tilt` returns `roll` and `tilt` values based on the pointer position over the target
element or, on mobile devices, the device orientation. Map them to CSS transforms to create
a tilt effect. Assign `ref` to a static wrapper and transform its child: an element that
rotates itself flickers near its edges.

If you need a ready-to-use component with glare and layers, use [Tilt](https://alpha.mantine.dev/llms/core-tilt.md):

```tsx
import { Box, Stack, Text, Title } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt, source } = useTilt<HTMLDivElement>();

  return (
    <Box ref={ref} style={{ perspective: 800, display: 'inline-block' }}>
      <Stack
        align="center"
        justify="center"
        gap={4}
        p="xl"
        style={{
          width: 320,
          height: 220,
          borderRadius: 'var(--mantine-radius-lg)',
          color: 'var(--mantine-color-white)',
          backgroundImage:
            'linear-gradient(135deg, var(--mantine-color-indigo-6), var(--mantine-color-grape-6))',
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
          transition: 'transform 100ms ease-out',
        }}
      >
        <Title order={3}>Move your cursor</Title>
        <Text>The edge under the pointer moves away from you</Text>
        <Text size="sm" opacity={0.8}>
          source: {source} · roll: {roll.toFixed(2)} · tilt: {tilt.toFixed(2)}
        </Text>
      </Stack>
    </Box>
  );
}
```


## Definition

```tsx
interface UseTiltOptions {
  /** If set, the hook reacts to the pointer position anywhere on the page instead of only
   *  when the target element is hovered, false by default */
  trackWindow?: boolean;

  /** If set, roll and tilt reset to 0 when the pointer leaves the target element.
   *  Ignored when the trackWindow option is set to true, true by default */
  resetOnLeave?: boolean;

  /** Adjusts normalized device orientation roll value before it is returned */
  deviceOrientationRollAdjust?: (value: number) => number;

  /** Adjusts normalized device orientation tilt value before it is returned */
  deviceOrientationTiltAdjust?: (value: number) => number;

  /** Adjusts normalized mouse roll value before it is returned */
  mouseRollAdjust?: (value: number) => number;

  /** Adjusts normalized mouse tilt value before it is returned */
  mouseTiltAdjust?: (value: number) => number;
}

interface UseTiltReturnValue<T extends HTMLElement = any> {
  /** Ref callback that must be assigned to the target element */
  ref: React.RefCallback<T | null>;

  /** Vertical tilt normalized to `[-0.5, 0.5]` for mouse input, positive when the pointer is above the center of the element */
  roll: number;

  /** Horizontal tilt normalized to `[-0.5, 0.5]` for mouse input, positive when the pointer is right of the center of the element */
  tilt: number;

  /** Input source that produced the current `roll` and `tilt` values */
  source: 'mouse' | 'deviceOrientation';
}

function useTilt<T extends HTMLElement = any>(
  options?: UseTiltOptions,
): UseTiltReturnValue<T>;
```

## roll and tilt values

`roll` is the vertical tilt and `tilt` is the horizontal tilt. Both are `0` at the center of
the element and reach `-0.5` and `0.5` at its edges. `roll` is positive above the center,
`tilt` is positive to the right of it.

Multiply the values by the number of degrees you need. With `rotateX(roll)` and `rotateY(tilt)`,
the edge under the pointer moves away from the viewer:

```tsx
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>();

  return (
    <div ref={ref} style={{ perspective: 800 }}>
      <div
        style={{
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
        }}
      >
        Tilting card
      </div>
    </div>
  );
}
```

## Example: 3D card

Nested layers with different multipliers create depth:

```tsx
import { Box, Group, Stack, Text } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>();

  // Animate 2x slower when the card returns to its neutral position
  const isNeutral = roll === 0 && tilt === 0;
  const transition = `transform ${isNeutral ? 300 : 150}ms ease-out`;

  return (
    <Box ref={ref} style={{ perspective: 1000, display: 'inline-block' }}>
      <Box
        style={{
          position: 'relative',
          overflow: 'hidden',
          width: 340,
          height: 214,
          padding: 'var(--mantine-spacing-xl)',
          borderRadius: 'var(--mantine-radius-lg)',
          color: 'var(--mantine-color-white)',
          backgroundImage: 'linear-gradient(135deg, #4263eb 0%, #7048e8 55%, #ae3ec9 100%)',
          boxShadow: 'var(--mantine-shadow-xl)',
          transform: `rotateX(${roll * 18}deg) rotateY(${tilt * 18}deg)`,
          transition,
        }}
      >
        <Box
          style={{
            position: 'absolute',
            inset: 0,
            pointerEvents: 'none',
            background:
              'radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.45), rgba(255, 255, 255, 0) 55%)',
            transform: `translate(${tilt * 55}%, ${-roll * 55}%)`,
            transition,
          }}
        />

        <Stack justify="space-between" h="100%" gap={0} style={{ position: 'relative' }}>
          <Group justify="space-between" align="flex-start">
            <Box
              style={{
                width: 44,
                height: 32,
                borderRadius: 6,
                backgroundImage: 'linear-gradient(135deg, #ffd43b, #f59f00)',
              }}
            />
            <Text fw={700} fz="lg" fs="italic">
              VISA
            </Text>
          </Group>

          <Text fz="md" ff="monospace" style={{ letterSpacing: 1, whiteSpace: 'nowrap' }}>
            4242 4242 4242 4242
          </Text>

          <Group justify="space-between">
            <Stack gap={2}>
              <Text fz={10} opacity={0.7} tt="uppercase">Card holder</Text>
              <Text fw={500}>Jane Cooper</Text>
            </Stack>
            <Stack gap={2}>
              <Text fz={10} opacity={0.7} tt="uppercase">Expires</Text>
              <Text fw={500}>08 / 28</Text>
            </Stack>
          </Group>
        </Stack>
      </Box>
    </Box>
  );
}
```


## Reset on leave

By default, `roll` and `tilt` reset to `0` when the pointer leaves the target element.
Set `resetOnLeave: false` to keep the last values:

```tsx
import { useTilt } from '@mantine/hooks';

function Demo() {
  // The element keeps its last tilt after the cursor leaves
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({ resetOnLeave: false });
  // ...
}
```

## React to the whole page

By default, the values change only while the target element is hovered. Set `trackWindow: true`
to react to the pointer anywhere on the page. The values are then not clamped: they grow the
further the cursor is from the element.

```tsx
import { Box, Text } from '@mantine/core';
import { clamp, useTilt } from '@mantine/hooks';

function Demo() {
  // With trackWindow: true the effect follows the cursor everywhere on the page,
  // not only while the element is hovered
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({ trackWindow: true });

  return (
    <Box
      style={{
        perspective: 1000,
        minHeight: 260,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Box ref={ref} style={{ display: 'inline-block' }}>
        <Box
          style={{
            transform: `rotateX(${clamp(roll, -0.5, 0.5) * 30}deg) rotateY(${clamp(tilt, -0.5, 0.5) * 30}deg)`,
            transition: 'transform 120ms ease-out',
            width: 200,
            height: 200,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            textAlign: 'center',
            padding: 'var(--mantine-spacing-md)',
            fontWeight: 600,
            color: 'var(--mantine-color-white)',
            borderRadius: 'var(--mantine-radius-lg)',
            backgroundImage: 'radial-gradient(circle at 30% 30%, #4dabf7, #1971c2)',
            boxShadow: 'var(--mantine-shadow-lg)',
          }}
        >
          <Text inherit>Move your cursor anywhere on the page</Text>
        </Box>
      </Box>
    </Box>
  );
}
```


## Adjusting values

Use the adjust options to amplify, dampen, clamp or invert the values of each input source.
In this example, the mouse values are inverted and amplified, so the edge under the cursor
moves towards the viewer:

```tsx
import { Box, Stack, Text } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({
    mouseRollAdjust: (value) => -value * 1.6,
    mouseTiltAdjust: (value) => -value * 1.6,
  });

  return (
    <Box ref={ref} style={{ perspective: 800, display: 'inline-block' }}>
      <Stack
        align="center"
        justify="center"
        gap={4}
        p="xl"
        style={{
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
          transition: 'transform 100ms ease-out',
          width: 320,
          height: 220,
          color: 'var(--mantine-color-white)',
          borderRadius: 'var(--mantine-radius-lg)',
          backgroundImage:
            'linear-gradient(135deg, var(--mantine-color-teal-6), var(--mantine-color-cyan-7))',
        }}
      >
        <Text fw={600} fz="lg">
          The edge under the cursor lifts towards you
        </Text>
        <Text size="sm" opacity={0.8}>
          roll: {roll.toFixed(2)} · tilt: {tilt.toFixed(2)}
        </Text>
      </Stack>
    </Box>
  );
}
```


```tsx
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({
    // Amplify the mouse effect
    mouseRollAdjust: (value) => value * 2,
    mouseTiltAdjust: (value) => value * 2,
    // Invert the device orientation effect
    deviceOrientationRollAdjust: (value) => -value,
    deviceOrientationTiltAdjust: (value) => -value,
  });

  // ...
}
```

## Source selection

`source` is the active input, `'mouse'` or `'deviceOrientation'`.
Once the device reports orientation data, the hook switches to it and stays there.
Use `source` to show a hint:

```tsx
import { Box, Text } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, source } = useTilt<HTMLDivElement>();

  return (
    <Box ref={ref} p="xl">
      <Text>
        {source === 'deviceOrientation' ? 'Tilt your device' : 'Move your cursor'}
      </Text>
    </Box>
  );
}
```

## Device orientation permission

On iOS, device orientation requires a permission. `use-tilt` does not request it: call
`DeviceOrientationEvent.requestPermission()` from a user event, for example a button click.
Until the permission is granted, the hook uses the pointer position:

```tsx
async function requestOrientationPermission() {
  const DeviceOrientationEventTyped = DeviceOrientationEvent as unknown as {
    requestPermission?: () => Promise<'granted' | 'denied'>;
  };

  if (typeof DeviceOrientationEventTyped.requestPermission === 'function') {
    await DeviceOrientationEventTyped.requestPermission();
  }
}
```

## Exported types

`UseTiltOptions`, `UseTiltReturnValue` and `UseTiltSource` types are exported from
the `@mantine/hooks` package:

```tsx
import type {
  UseTiltOptions,
  UseTiltReturnValue,
  UseTiltSource,
} from '@mantine/hooks';
```
