Mantine Scheme Transition

Logo

@gfazioli/mantine-scheme-transition

The light and dark switch of a Mantine app as a view transition that starts from the button you pressed: circle, wipe, curtain or dissolve, with a ready-made SchemeToggle and a headless hook.

Installation

yarn add @gfazioli/mantine-scheme-transition

After installation import package styles at the root of your application:

import '@gfazioli/mantine-scheme-transition/styles.css';

You can import styles within a layer @layer mantine-scheme-transition by importing @gfazioli/mantine-scheme-transition/styles.layer.css file.

import '@gfazioli/mantine-scheme-transition/styles.layer.css';

The stylesheet draws the transitions: without it the switch is still animated, but as the browser's plain cross-fade.

Usage

SchemeToggle switches Mantine's colour scheme with a view transition: the new scheme spreads across the page from the point you clicked. Every demo on this page switches the scheme of the whole page, the header included: that is the point. The header toggle of this site is a SchemeToggle too, and ⌘ J / Ctrl J reveals from it.

Duration
Size
Radius
Color
import { SchemeToggle } from '@gfazioli/mantine-scheme-transition';

function Demo() {
  return <SchemeToggle />;
}

SchemeToggle is an ActionIcon: every ActionIcon prop applies, variant, color, radius, gradient, loading and disabled included, and so does its theme. The props tab lists only the props SchemeToggle adds.

Video tutorial

06 · Add an animated dark mode toggle

Install Scheme Transition, put SchemeToggle in your header, pick a transition (circle, wipe, curtain, dissolve or none), switch from any button with the useColorSchemeTransition hook, share one controller with a hotkey and choose what reduced motion gets.

Mantine Extensions Tutorial 06 · 2:11 · v1.0.0 · All the tutorials

Transitions

Four transitions ship with the package. In each one the new scheme is the layer that moves, on the way to dark and on the way back to light; dissolve is the exception, where the old scheme fades out over the new one. Click each to compare them.

  • circle (default): a circle grows from the pointer until it passes the farthest corner of the viewport.
  • wipe: a slanted edge sweeps across the page, entering from the side the pointer is on.
  • curtain: a band opens at the pointer's column and reaches both edges at the same moment.
  • dissolve: a plain cross-fade, 300 ms by default; the pointer does not matter.
circle
wipe
curtain
dissolve
import { SchemeToggle } from '@gfazioli/mantine-scheme-transition';
import { Code, Group, Stack } from '@mantine/core';

function Demo() {
  return (
    <Group>
      {(['circle', 'wipe', 'curtain', 'dissolve'] as const).map((transition) => (
        <Stack key={transition} align="center" gap={4}>
          <SchemeToggle transition={transition} size="xl" />
          <Code>{transition}</Code>
        </Stack>
      ))}
    </Group>
  );
}

transition="none" switches at once, as Mantine does: useful when a SchemeToggle should not animate in some part of an app.

The hook

useColorSchemeTransition holds the engine. It returns Mantine's colour scheme functions wrapped in the transition, so any trigger can use them: pass the click event and the reveal starts at the pointer.

import { useColorSchemeTransition } from '@gfazioli/mantine-scheme-transition';
import { Button, Group, SegmentedControl, type MantineColorScheme } from '@mantine/core';
import { useMounted } from '@mantine/hooks';

function Demo() {
  // The stored scheme is unknown on the server: render the control once mounted
  const mounted = useMounted();
  const { colorScheme, toggle, setColorScheme, ref } = useColorSchemeTransition({
    transition: 'wipe',
  });

  return (
    <Group>
      <Button variant="default" onClick={toggle}>
        Switch scheme
      </Button>
      {mounted && (
        // onChange has no event: the reveal starts from the element holding ref
        <SegmentedControl
          ref={ref}
          value={colorScheme}
          onChange={(value) => setColorScheme(value as MantineColorScheme)}
          data={['light', 'dark', 'auto']}
        />
      )}
    </Group>
  );
}

The hook takes the same transition options as SchemeToggle:

NameTypeDescription
transition'circle' | 'wipe' | 'curtain' | 'dissolve' | 'none' | (string & {})

How the new scheme is revealed. A name the package does not know is written to the page as it is, for your own CSS to draw

durationnumber

Duration of the reveal in ms

easingstring

Any CSS easing function

reducedMotion'instant' | 'dissolve' | 'animate'

What happens when the user asks for reduced motion: Mantine's instant switch, a cross-fade of 200 ms at most, or the transition anyway

keepTransitionsboolean

Forwarded to Mantine's useMantineColorScheme: keep the page's own CSS transitions during the change

onTransitionStart(colorScheme: 'light' | 'dark') => void

Called when a reveal starts, with the scheme being revealed. Not called for an instant switch

onTransitionEnd(colorScheme: 'light' | 'dark') => void

Called once for every onTransitionStart, when the reveal has finished or was cut short by a newer one

It returns a controller. toggle, setColorScheme, clearColorScheme and ref keep their identity across renders, so they are safe in effect dependencies and in useHotkeys.

NameTypeDescription
colorScheme *'light' | 'dark' | 'auto'

The stored value, as Mantine returns it

toggle *(origin?: SchemeTransitionOrigin) => void

Switches between light and dark. Pass the event, as in onClick={toggle}, an element or a point { x, y }

setColorScheme *(value: 'light' | 'dark' | 'auto', origin?: SchemeTransitionOrigin) => void

Sets a value, with the reveal when it changes what is on screen

clearColorScheme *(origin?: SchemeTransitionOrigin) => void

Mantine's clearColorScheme, with the reveal when it changes what is on screen

transitioning *boolean

True from the call to the end of the reveal this controller started

ref *React.RefObject<HTMLElement | null>

Put it on the trigger: calls without a position start from the centre of this element. SchemeToggle sets it

Where the reveal starts

toggle, setColorScheme and clearColorScheme take an optional origin as their last argument:

  • an event: its pointer position. A click made with the keyboard, a screen reader or element.click() has no position, so the reveal starts from the centre of the element that received it;
  • an element: the centre of its box;
  • a point { x, y }, in CSS pixels from the top left of the viewport;
  • nothing: the centre of the element holding the controller's ref, else the centre of the viewport.
import { useRef } from 'react';
import { useColorSchemeTransition } from '@gfazioli/mantine-scheme-transition';
import { Button, Group, ThemeIcon } from '@mantine/core';
import { IconSparkles } from '@tabler/icons-react';

function Demo() {
  const logoRef = useRef<HTMLDivElement>(null);
  const { toggle } = useColorSchemeTransition();

  return (
    <Group>
      <ThemeIcon ref={logoRef} size="xl" radius="xl" variant="light">
        <IconSparkles />
      </ThemeIcon>
      {/* The event: from the pointer, or from the button with the keyboard */}
      <Button variant="default" onClick={toggle}>
        From the pointer
      </Button>
      {/* An element: from its centre */}
      <Button variant="default" onClick={() => toggle(logoRef.current)}>
        From the icon
      </Button>
      {/* A point of the viewport, in CSS pixels */}
      <Button variant="default" onClick={() => toggle({ x: 0, y: 0 })}>
        From the corner
      </Button>
    </Group>
  );
}

One engine, several triggers

Pass the controller to SchemeToggle with the controller prop and the button registers itself as the controller's ref. A menu item, a hotkey or any code that calls the same toggle without a pointer then reveals from that button. With a controller, the transition props of the SchemeToggle itself are not used.

or press ⌘ / Ctrl + Shift + U

import { SchemeToggle, useColorSchemeTransition } from '@gfazioli/mantine-scheme-transition';
import { Button, Group, Kbd, Menu, Text } from '@mantine/core';
import { useHotkeys } from '@mantine/hooks';

function Demo() {
  const controller = useColorSchemeTransition({ transition: 'curtain' });
  // A KeyboardEvent has no pointer: the reveal starts from the toggle, which holds the ref
  useHotkeys([['mod + shift + U', controller.toggle]]);

  return (
    <Group>
      <SchemeToggle controller={controller} />
      <Menu>
        <Menu.Target>
          <Button variant="default">Menu</Button>
        </Menu.Target>
        <Menu.Dropdown>
          <Menu.Item leftSection={<SchemeToggle.Icon />} onClick={controller.toggle}>
            Toggle color scheme
          </Menu.Item>
        </Menu.Dropdown>
      </Menu>
      <Text size="sm" c="dimmed">
        or press <Kbd>⌘</Kbd> / <Kbd>Ctrl</Kbd> + <Kbd>Shift</Kbd> + <Kbd>U</Kbd>
      </Text>
    </Group>
  );
}

Icons

The toggle shows the icon of the scheme you are in: a sun in light, a moon in dark. Swap lightIcon and darkIcon to show the scheme you would get instead, as Mantine's own docs do. children replaces the pair altogether, and SchemeToggle.Icon is the pair on its own, for a Button, a Menu.Item or a NavLink.

Both icons are always rendered and CSS shows the right one, so the server never has to know the scheme and nothing changes on hydration. While a reveal runs, the two icons swap with a short turn; under reduced motion they fade.

import { SchemeToggle, useColorSchemeTransition } from '@gfazioli/mantine-scheme-transition';
import { Button, Group } from '@mantine/core';
import { IconMoonStars, IconSunHigh } from '@tabler/icons-react';

function Demo() {
  const { toggle } = useColorSchemeTransition();

  return (
    <Group>
      {/* Your own icons: the sun shows in light, the moon in dark */}
      <SchemeToggle
        lightIcon={<IconSunHigh stroke={1.5} />}
        darkIcon={<IconMoonStars stroke={1.5} />}
      />

      {/* Swapped: the icon of the scheme you would get, as in Mantine's docs */}
      <SchemeToggle
        variant="light"
        lightIcon={<IconMoonStars stroke={1.5} />}
        darkIcon={<IconSunHigh stroke={1.5} />}
      />

      {/* Any content in place of the icons */}
      <SchemeToggle variant="outline" size="xl" radius="xl" fw={700}>
        Aa
      </SchemeToggle>

      {/* The pair alone, in another trigger */}
      <Button variant="default" leftSection={<SchemeToggle.Icon />} onClick={toggle}>
        Color scheme
      </Button>
    </Group>
  );
}

Responsive size

size takes the sizes of ActionIcon (xs to xl, input-xs to input-xl), a number or any CSS length, and an object of breakpoints. The responsive value is written as CSS media queries, with no re-render.

Resize the window: md on small screens, xl from the sm breakpoint

import { SchemeToggle } from '@gfazioli/mantine-scheme-transition';
import { Group, Text } from '@mantine/core';

function Demo() {
  return (
    <Group>
      <SchemeToggle size={{ base: 'md', sm: 'xl' }} />
      <Text size="sm">Resize the window: md on small screens, xl from the sm breakpoint</Text>
    </Group>
  );
}

Custom transitions

A transition the package does not know is written to the page as it is, and your stylesheet draws it. While a reveal runs, these attributes and variables are on the html element, and nowhere else at any other time:

On the html elementValue
data-scheme-transitionThe transition name
data-scheme-transition-tolight or dark, the scheme being revealed, once the change is applied
data-scheme-transition-sideleft or right, the half of the viewport the origin is in
--scheme-transition-x, --scheme-transition-yThe origin, in px from the top left of the viewport
--scheme-transition-radiusThe distance in px from the origin to the farthest corner of the viewport
--scheme-transition-duration, --scheme-transition-easingThe duration and the easing of this reveal

The old page is ::view-transition-old(root) and the live new page is ::view-transition-new(root), on top of it; the package has already switched off the browser's default cross-fade on both. Animate one of them, as this diamond does with the new page. In a CSS module, wrap the whole selector in :global(...), pseudo-element included: some compilers would otherwise rename root as if it were a local name, and the rule would match nothing.

A transition the package does not know, drawn by the CSS in Demo.module.css

import { SchemeToggle } from '@gfazioli/mantine-scheme-transition';
import { Group, Text } from '@mantine/core';
import './Demo.module.css';

function Demo() {
  return (
    <Group>
      <SchemeToggle transition="diamond" duration={700} size="xl" />
      <Text size="sm">
        A transition the package does not know, drawn by the CSS in Demo.module.css
      </Text>
    </Group>
  );
}

Styles API

SchemeToggle and SchemeToggle.Icon support Styles API: you can add styles to any inner element with the classNames prop. SchemeToggle has a single selector, root, which is the ActionIcon root; hover the selectors below to see the three parts of SchemeToggle.Icon. Style the icon of a SchemeToggle through its iconProps.

Component Styles API

Hover over selectors to highlight corresponding elements

/*
 * Hover over selectors to apply outline styles
 *
 */

Browser support

The reveal uses same-document view transitions (document.startViewTransition). Where the browser does not have them, the toggle calls Mantine's setColorScheme and nothing more: the same result and the same stored value, without the animation, a polyfill or an error.

BrowserAnimated fromBefore that
Chrome, Edge111Instant switch
Safari (macOS, iOS)18.0Instant switch
Firefox144Instant switch
Opera97Instant switch
Samsung Internet23Instant switch

Sources: MDN browser compatibility data and Can I use.

Reduced motion

When the user asks the operating system for reduced motion, reducedMotion decides what happens:

  • instant (default): Mantine's switch, with no animation at all.
  • dissolve: whatever the transition, a cross-fade of 200 ms at most, with no shape and no movement. The gentle middle, when the change should still be felt.
  • animate: the transition runs anyway. A reveal covers the whole screen, so keep this for a transition that does not move, such as your own fade.

The setting is read at each click, so a change in the system settings applies at once. It does not depend on theme.respectReducedMotion, which is about Mantine's small component transitions.

Good to know

  • During a reveal the page does not react to the pointer: clicks land on the transition layer, never on the page below. This is how the browser runs a view transition of the whole page; keep durations short. The keyboard still works, and a second toggle during a reveal cuts the first one short and starts again, so the scheme always matches the number of presses.
  • forceColorScheme: where the MantineProvider forces the scheme, the toggle changes nothing and shows no animation. Hide or disable it there.
  • keepTransitions: Mantine switches the page's CSS transitions off for an instant during every scheme change, and so does this package by default, so the new scheme appears in its final colours with a crisp edge. With keepTransitions, the page's own colour transitions play inside the revealed area.
  • Your own view transitions are untouched: the package's styles apply only while one of its reveals runs. For the length of a reveal, elements you named with view-transition-name join the single snapshot of the page.
  • Server rendering works: the components are client components, and the icons need no scheme on the server.
  • Import the stylesheet, or the reveal is the browser's plain cross-fade.