Skip to content

Commit ca186f2

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 3b6c81a commit ca186f2

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) {
@@ -302,6 +328,24 @@ export const InlineSearch = () => {
302328
color: 'var(--ifm-font-color-base)'
303329
}}
304330
/>
331+
{!isExpanded && (
332+
<div
333+
style={{
334+
display: 'flex',
335+
alignItems: 'center',
336+
gap: '0.25rem',
337+
fontSize: '0.85rem',
338+
color: 'var(--ifm-color-emphasis-500)',
339+
opacity: 0.6,
340+
fontFamily: 'monospace',
341+
padding: '0.25rem 0.5rem',
342+
border: '1px solid var(--ifm-color-emphasis-300)',
343+
borderRadius: '4px'
344+
}}
345+
>
346+
{isMac ? '⌘K' : 'Ctrl+K'}
347+
</div>
348+
)}
305349
{isExpanded && (
306350
<button
307351
onClick={() => {

0 commit comments

Comments
 (0)