Spotlight

Command center for your application
Import
License

Installation

Package depends on @mantine/core and @mantine/hooks.

Install with yarn:

yarn add @mantine/spotlight

Install with npm:

npm install @mantine/spotlight

Usage

Spotlight component let you build a popup search interface which can be triggered with keyboard shortcut or programmatically from anywhere inside your application. To get started, wrap your application with SpotlightProvider component:

import { Button, Group } from '@mantine/core';
import { SpotlightProvider, openSpotlight } from '@mantine/spotlight';
import type { SpotlightAction } from '@mantine/spotlight';
import { IconHome, IconDashboard, IconFileText, IconSearch } from '@tabler/icons';
function SpotlightControl() {
return (
<Group position="center">
<Button onClick={() => openSpotlight()}>Open spotlight</Button>
</Group>
);
}
const actions: SpotlightAction[] = [
{
title: 'Home',
description: 'Get to home page',
onTrigger: () => console.log('Home'),
icon: <IconHome size={18} />,
},
{
title: 'Dashboard',
description: 'Get full information about current system status',
onTrigger: () => console.log('Dashboard'),
icon: <IconDashboard size={18} />,
},
{
title: 'Documentation',
description: 'Visit documentation to lean more about all features',
onTrigger: () => console.log('Documentation'),
icon: <IconFileText size={18} />,
},
];
function Demo() {
return (
<SpotlightProvider
actions={actions}
searchIcon={<IconSearch size={18} />}
searchPlaceholder="Search..."
shortcut="mod + shift + 1"
nothingFoundMessage="Nothing found..."
>
<SpotlightControl />
</SpotlightProvider>
);
}

Note that if you are using MantineProvider, SpotlightProvider must be used as its child:

import { MantineProvider } from '@mantine/core';
import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<MantineProvider>
<SpotlightProvider actions={[]}>
<App />
</SpotlightProvider>
</MantineProvider>
);
}

Keyboard shortcuts

SpotlightProvider uses use-hotkeys hook to add keyboard shortcuts, the default shortcut to trigger popup is mod + K, it means that it will be shown when users press ⌘ + K on MacOS and Ctrl + K on any other os.

You can setup multiple shortcuts, for example, Mantine documentation uses the following setup:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider shortcut={['mod + P', 'mod + K', '/']} actions={[]}>
<App />
</SpotlightProvider>
);
}

It means that user will be able to open documentation search with the following shortcuts:

  • ⌘ + K / Ctrl + K
  • ⌘ + P / Ctrl + P
  • / – single keys are also supported

Note that provided shortcuts will prevent the default behavior, for example, mod + P will disable "Print page" native browser function, choose those shortcuts that will not interfere with desired default browser behavior.

Keyboard shortcuts will not work if:

  • focus is not on current page
  • input, textarea or select elements are focused (these can be overriden with the tagsToIgnore arg)
  • elements have contentEditable=true (can be overriden with the triggerOnContentEditable arg)

To disabled keyboard shortcuts set shortcut={null}:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider shortcut={null} actions={[]}>
<App />
</SpotlightProvider>
);
}

use-spotlight hook

useSpotlight hook lets you control spotlight from anywhere in your application. For example, it can be used to open spotlight with button click:

import { useSpotlight } from '@mantine/spotlight';
import { Button, Group } from '@mantine/core';
function SpotlightControl() {
const spotlight = useSpotlight();
return (
<Group position="center">
<Button onClick={() => spotlight.openSpotlight()}>Open spotlight</Button>
</Group>
);
}

useSpotlight returns an object with the following properties:

interface UseSpotlight {
/** Opens spotlight */
openSpotlight(): void;
/** Closes spotlight */
closeSpotlight(): void;
/** Toggles spotlight opened state */
toggleSpotlight(): void;
/** Triggers action with given id */
triggerAction(actionId: string): void;
/** Registers additional actions */
registerActions(action: SpotlightAction[]): void;
/** Removes actions with given ids */
removeActions(actionIds: string[]): void;
/** Current opened state */
opened: boolean;
/** List of registered actions */
actions: SpotlightAction[];
/** Search query */
query: string;
}

Event based functions

@mantine/spotlight exports several functions which can be used to perform certain actions from any part of your application:

// All functions can be called from anywhere (not only from components)
import {
openSpotlight,
closeSpotlight,
toggleSpotlight,
triggerSpotlightAction,
registerSpotlightActions,
removeSpotlightActions,
} from '@mantine/spotlight';
// Opens spotlight
openSpotlight();
// Closes spotlight
closeSpotlight();
// Toggles spotlight opened state
toggleSpotlight();
// triggers action with given id
triggerSpotlightAction('action-id');
// registers additional actions
registerSpotlightActions([
{
id: 'secret-action-1',
title: 'Secret action',
onTrigger: () => console.log('Secret'),
},
{
id: 'secret-action-2',
title: 'Another secret action',
onTrigger: () => console.log('Secret'),
},
]);
// removes actions
removeSpotlightActions(['secret-action-1', 'secret-action-2']);

Spotlight actions

actions is the only required prop of SpotlightProvider. Action shape:

interface SpotlightAction {
/** Action id, may be used to trigger action or find it in actions array,
* if not provided random string will be generated instead */
id?: string;
/** Action title, topmost large text, used for filtering */
title: string;
/** Action description, small text displayed after title, used for filtering */
description?: string;
/** Action group, used to render group label */
group?: string;
/** Keywords that are used for filtering, not displayed anywhere,
* can be a string: "react,router,javascript" or an array: ['react', 'router', 'javascript'] */
keywords?: string | string[];
/** Decorative icon */
icon?: ReactNode;
/** Function that is called when action is triggered */
onTrigger(action: SpotlightAction): void;
/** Any other properties that can be consumed by custom action component */
[key: string]: any;
}

You can import SpotlightAction type from @mantine/spotlight package:

import type { SpotlightAction } from '@mantine/spotlight';

Actions filtering

When user searches, spotlight actions are filtered based on the following action properties:

  • titlestring
  • descriptionstring
  • keywordsstring | string[]

You can change filtering logic by setting filter prop on SpotlightProvider. The following example filters actions only by title:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider
shortcut="mod + alt + V"
nothingFoundMessage="Nothing found..."
filter={(query, actions) =>
actions.filter((action) => action.title.toLowerCase().includes(query.toLowerCase()))
}
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

Actions limit

If you have a large list of actions, most of them won't be presented in the initial list (when user have not entered any text yet). You can control how many actions are displayed at a time with the limit prop:

import { SpotlightProvider } from '@mantine/spotlight';
import type { SpotlightAction } from '@mantine/spotlight';
const actions: SpotlightAction[] = Array(100)
.fill(0)
.map((_, index) => ({
title: `Action ${index}`,
onTrigger: () => console.log(`Action ${index}`),
}));
function Demo() {
return (
<SpotlightProvider
actions={actions}
limit={7}
searchPlaceholder="Search..."
shortcut="mod + shift + H"
>
<App />
</SpotlightProvider>
);
}

Register additional actions

You can register any amount of additional actions with registerActions function on useSpotlight hook. To remove actions from the list use removeActions function:

import { useState } from 'react';
import { Group, Button } from '@mantine/core';
import { SpotlightProvider, registerSpotlightActions, openSpotlight, removeSpotlightActions } from '@mantine/spotlight';
import { IconAlien, IconSearch } from '@tabler/icons';
function SpotlightControls() {
const [registered, setRegistered] = useState(false);
const spotlight = useSpotlight();
return (
<Group position="center">
<Button onClick={() => openSpotlight()}>Open spotlight</Button>
{registered ? (
<Button
variant="outline"
color="red"
onClick={() => {
setRegistered(false);
removeSpotlightActions(['secret-action-1', 'secret-action-2']);
}}
>
Remove extra actions
</Button>
) : (
<Button
variant="outline"
onClick={() => {
setRegistered(true);
registerSpotlightActions([
{
id: 'secret-action-1',
title: 'Secret action',
description: 'It was registered with a button click',
icon: <IconAlien size={18} />,
onTrigger: () => console.log('Secret'),
},
{
id: 'secret-action-2',
title: 'Another secret action',
description: 'You can register multiple actions with just one command',
icon: <IconAlien size={18} />,
onTrigger: () => console.log('Secret'),
},
]);
}}
>
Register extra actions
</Button>
)}
</Group>
);
}
const actions = [/* ... see in previous demos */];
export function Demo() {
return (
<SpotlightProvider
actions={actions}
searchIcon={<IconSearch size={18} />}
searchPlaceholder="Search..."
shortcut="mod + shift + C"
>
<SpotlightControls />
</SpotlightProvider>
);
}

Group actions

import { SpotlightProvider, SpotlightAction } from '@mantine/spotlight';
const onTrigger = () => {};
const actions: SpotlightAction[] = [
{ title: 'Home', group: 'main', onTrigger },
{ title: 'Docs', group: 'main', onTrigger },
{ title: 'Dashboard', group: 'main', onTrigger },
{ title: 'Component: Tabs', group: 'search', onTrigger },
{ title: 'Component: SegmentedControl', group: 'search', onTrigger },
{ title: 'Component: Button', group: 'search', onTrigger },
];
function Demo() {
return (
<SpotlightProvider
actions={actions}
searchPlaceholder="Search..."
shortcut="mod + shift + V"
>
<App />
</SpotlightProvider>
);
}

Custom action component

You can provide custom component to render actions, this feature can be used to customize how actions are displayed:

import { createStyles, UnstyledButton, Group, Text, Image, Center, Badge } from '@mantine/core';
import { SpotlightProvider, SpotlightAction, SpotlightActionProps } from '@mantine/spotlight';
const actions: SpotlightAction[] = [
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
title: 'Bender Bending Rodríguez',
description: 'Fascinated with cooking, though has no sense of taste',
new: true,
onTrigger: () => {},
},
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
title: 'Carol Miller',
description: 'One of the richest people on Earth',
new: false,
onTrigger: () => {},
},
{
image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
title: 'Homer Simpson',
description: 'Overweight, lazy, and often ignorant',
new: false,
onTrigger: () => {},
},
{
image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
title: 'Spongebob Squarepants',
description: 'Not just a sponge',
new: false,
onTrigger: () => {},
},
];
const useStyles = createStyles((theme) => ({
action: {
position: 'relative',
display: 'block',
width: '100%',
padding: '10px 12px',
borderRadius: theme.radius.sm,
},
actionHovered: {
backgroundColor: theme.colorScheme === 'dark' ? theme.colors.dark[4] : theme.colors.gray[1],
},
}));
function CustomAction({
action,
styles,
classNames,
hovered,
onTrigger,
...others
}: SpotlightActionProps) {
const { classes, cx } = useStyles(null, { styles, classNames, name: 'Spotlight' });
return (
<UnstyledButton
className={cx(classes.action, { [classes.actionHovered]: hovered })}
tabIndex={-1}
onMouseDown={(event) => event.preventDefault()}
onClick={onTrigger}
{...others}
>
<Group noWrap>
{action.image && (
<Center>
<Image src={action.image} alt={action.title} width={50} height={50} />
</Center>
)}
<div style={{ flex: 1 }}>
<Text>{action.title}</Text>
{action.description && (
<Text color="dimmed" size="xs">
{action.description}
</Text>
)}
</div>
{action.new && <Badge>new</Badge>}
</Group>
</UnstyledButton>
);
}
function Demo() {
return (
<SpotlightProvider
actions={actions}
actionComponent={CustomAction}
searchPlaceholder="Search..."
shortcut="mod + shift + I"
>
<App />
</SpotlightProvider>
);
}

Custom actions wrapper component

With custom actions wrapper component you can customize how actions list is rendered, for example, you can add a footer:

import { SpotlightProvider } from '@mantine/spotlight';
import { Group, Text, Anchor } from '@mantine/core';
function ActionsWrapper({ children }: { children: React.ReactNode }) {
return (
<div>
{children}
<Group
position="apart"
px={15}
py="xs"
sx={(theme) => ({
borderTop: `1px solid ${
theme.colorScheme === 'dark' ? theme.colors.dark[4] : theme.colors.gray[2]
}`,
})}
>
<Text size="xs" color="dimmed">
Search powered by Mantine
</Text>
<Anchor size="xs" href="#">
Learn more
</Anchor>
</Group>
</div>
);
}
function Demo() {
return (
<SpotlightProvider
shortcut="mod + alt + T"
nothingFoundMessage="Nothing found..."
actionsWrapperComponent={ActionsWrapper}
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

Close spotlight on action trigger

By default, spotlight will be closed when any action is triggered with mouse click or Enter key. To change this behavior set closeOnActionTrigger={false} prop on SpotlightProvider:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider
shortcut="mod + shift + G"
closeOnActionTrigger={false}
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

Close spotlight on specific action trigger

Other than with the global closeOnActionTrigger property, the closeOnTrigger property can be defined for specific actions. The action will then ignore the closeOnActionTrigger property and use its own definition.

import { SpotlightProvider, SpotlightAction } from '@mantine/spotlight';
const onTrigger = () => {};
const actions: SpotlightAction[] = [
{ title: 'Will stay open', onTrigger, closeOnTrigger: false },
{ title: 'Will close', onTrigger, closeOnTrigger: true },
];
function Demo() {
return (
<SpotlightProvider
actions={actions}
searchPlaceholder="Search..."
shortcut="mod + shift + 5"
>
<App />
</SpotlightProvider>
);
}

Highlight query

Default action component supports highlighting search query with Highlight component. To enable this option set highlightQuery on SpotlightProvider:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider
shortcut="mod + alt + L"
highlightQuery
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

Change transitions

Component presence is animated with Transition component, it supports all premade and custom transitions. To change transition set the following properties:

  • transition – premade transition name or custom transition object
  • transitionDuration – transition duration in ms
import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider
shortcut="mod + shift + 2"
transitionDuration={300}
transition="slide-down"
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

To disable transitions set transitionDuration={0}:

import { SpotlightProvider } from '@mantine/spotlight';
function Demo() {
return (
<SpotlightProvider
shortcut="mod + shift + 2"
transitionDuration={0}
{...otherProps}
>
<App />
</SpotlightProvider>
);
}

SpotlightProvider component props

NameTypeDescription
actionComponent
FC<DefaultActionProps>
Component that is used to render actions
actions *
SpotlightAction[] | ((query: string) => SpotlightAction[])
Actions list
actionsWrapperComponent
string | FC<{ children: ReactNode; }>
Component that is used to wrap actions list
centered
boolean
Should spotlight be rendered in the center of the screen
children
ReactNode
Your application
cleanQueryOnClose
boolean
Should search be cleared when spotlight closes
closeOnActionTrigger
boolean
Should spotlight be closed when action is triggered
disabled
boolean
Spotlight will not render if disabled is set to true
filter
(query: string, actions: SpotlightAction[]) => SpotlightAction[]
Function used to determine how actions will be filtered based on user input
highlightColor
MantineColor
The highlight color
highlightQuery
boolean
Should user query be highlighted in actions title
limit
number
Number of actions displayed at a time
maxWidth
number
Max spotlight width
nothingFoundMessage
ReactNode
Message displayed when actions were not found
onQueryChange
(query: string) => void
Called when user enters text in search input
onSpotlightClose
() => void
Called when spotlight closes
onSpotlightOpen
() => void
Called when spotlight opens
overlayBlur
number
Backdrop overlay blur in px
overlayColor
string
Backdrop overlay color, e.g. #000
overlayOpacity
number
Backdrop overlay opacity (0-1), e.g. 0.65
radius
number | "xs" | "sm" | "md" | "lg" | "xl"
Radius from theme.radius, or number to set border-radius in px, defaults to theme.defaultRadius
searchIcon
ReactNode
Search input icon
searchInputProps
TextInputProps
Props spread to search input
searchPlaceholder
string
Search input placeholder
shadow
MantineShadow
Value from theme.shadows or any valid css box-shadow value
shortcut
string | string[]
Keyboard shortcut or list of shortcuts to trigger spotlight
tagsToIgnore
string[]
Tags to ignore shortcut hotkeys on.
topOffset
number
Top offset when spotlight is not centered
transition
MantineTransition
Premade transition or transition object
transitionDuration
number
Transition duration in ms, set to 0 to disable all transitions
triggerOnContentEditable
boolean
Whether shortcuts should trigger based on contentEditable.
withinPortal
boolean
Should spotlight be rendered within Portal
zIndex
ZIndex
Spotlight z-index

SpotlightProvider component Styles API

NameStatic selectorDescription
root.mantine-SpotlightProvider-rootRoot element
spotlight.mantine-SpotlightProvider-spotlightSpotlight itself
overlay.mantine-SpotlightProvider-overlayBackdrop overlay
inner.mantine-SpotlightProvider-innerInner element, used for spotlight positioning
searchInput.mantine-SpotlightProvider-searchInputSearch input
nothingFound.mantine-SpotlightProvider-nothingFoundNothing found message
actions.mantine-SpotlightProvider-actionsActions list
actionsGroup.mantine-SpotlightProvider-actionsGroupActions group label
action.mantine-SpotlightProvider-actionAction
actionHovered.mantine-SpotlightProvider-actionHoveredHovered action modifier
actionIcon.mantine-SpotlightProvider-actionIconAction icon wrapper
actionBody.mantine-SpotlightProvider-actionBodyAction body