Skip to content

Commit ea48fa6

Browse files
committed
feat: context aware search key binding
Ctrl+k is a default algolia search shortcut. On the index page we intecept it to work with the main search instead.
1 parent 05b3669 commit ea48fa6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/index.mdx

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,38 @@ export const InlineSearch = () => {
2525
const debounceTimerRef = useRef(null);
2626
const dropdownSelections = useRef({});
2727

28+
// Detect Mac for keyboard shortcut hint
29+
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
30+
2831
useEffect(() => {
2932
if (isExpanded && inputRef.current) {
3033
inputRef.current.focus();
3134
}
3235
}, [isExpanded]);
3336

37+
// Keyboard shortcuts: Ctrl/Cmd+K to open, Esc to close
38+
useEffect(() => {
39+
const handleKeyDown = (e) => {
40+
// Ctrl+K or Cmd+K to open search
41+
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
42+
e.preventDefault();
43+
e.stopPropagation();
44+
setIsExpanded(true);
45+
}
46+
// Esc to close search
47+
if (e.key === 'Escape' && isExpanded) {
48+
e.preventDefault();
49+
setIsExpanded(false);
50+
setSearchQuery('');
51+
setIsIframeReady(false);
52+
dropdownSelections.current = {};
53+
}
54+
};
55+
56+
window.addEventListener('keydown', handleKeyDown, true);
57+
return () => window.removeEventListener('keydown', handleKeyDown, true);
58+
}, [isExpanded]);
59+
3460
// Debounce search query to avoid iframe reloading on every keystroke
3561
useEffect(() => {
3662
if (debounceTimerRef.current) {
@@ -301,6 +327,24 @@ export const InlineSearch = () => {
301327
color: 'var(--ifm-font-color-base)'
302328
}}
303329
/>
330+
{!isExpanded && (
331+
<div
332+
style={{
333+
display: 'flex',
334+
alignItems: 'center',
335+
gap: '0.25rem',
336+
fontSize: '0.85rem',
337+
color: 'var(--ifm-color-emphasis-500)',
338+
opacity: 0.6,
339+
fontFamily: 'monospace',
340+
padding: '0.25rem 0.5rem',
341+
border: '1px solid var(--ifm-color-emphasis-300)',
342+
borderRadius: '4px'
343+
}}
344+
>
345+
{isMac ? '⌘K' : 'Ctrl+K'}
346+
</div>
347+
)}
304348
{isExpanded && (
305349
<button
306350
onClick={() => {

0 commit comments

Comments
 (0)