|
| 1 | +import { SearchIcon } from '@storybook/icons'; |
| 2 | +import * as React from 'react'; |
| 3 | +import { IconButton } from 'storybook/internal/components'; |
| 4 | +import { addons, types } from 'storybook/manager-api'; |
| 5 | + |
| 6 | +const ADDON_ID = 'content-search'; |
| 7 | +const TOOL_ID = `${ADDON_ID}/toolbar`; |
| 8 | +const isMac = navigator.platform.toUpperCase().includes('MAC'); |
| 9 | +const shortcut = isMac ? '⌘⇧F' : 'Ctrl+Shift+F'; |
| 10 | + |
| 11 | +function SearchButton() { |
| 12 | + const openSearch = React.useCallback(() => { |
| 13 | + const dialog = document.getElementById('pagefind-search-container'); |
| 14 | + if (dialog && dialog instanceof HTMLDialogElement && !dialog.open) { |
| 15 | + dialog.showModal(); |
| 16 | + setTimeout(() => dialog.querySelector<HTMLInputElement>('.pagefind-ui__search-input')?.focus(), 50); |
| 17 | + } |
| 18 | + }, []); |
| 19 | + |
| 20 | + React.useEffect(() => { |
| 21 | + const handleKeydown = (e: KeyboardEvent) => { |
| 22 | + if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'f') { |
| 23 | + e.preventDefault(); |
| 24 | + openSearch(); |
| 25 | + } |
| 26 | + }; |
| 27 | + document.addEventListener('keydown', handleKeydown); |
| 28 | + return () => document.removeEventListener('keydown', handleKeydown); |
| 29 | + }, [openSearch]); |
| 30 | + |
| 31 | + return ( |
| 32 | + <IconButton key={TOOL_ID} title={`Search docs (${shortcut})`} style={{ order: -2 }} onClick={openSearch}> |
| 33 | + <SearchIcon /> |
| 34 | + Search Docs (Beta) |
| 35 | + </IconButton> |
| 36 | + ); |
| 37 | +} |
| 38 | + |
| 39 | +addons.register(ADDON_ID, () => { |
| 40 | + addons.add(TOOL_ID, { |
| 41 | + type: types.TOOLEXTRA, |
| 42 | + title: 'Search documentation content', |
| 43 | + render: () => <SearchButton />, |
| 44 | + }); |
| 45 | +}); |
0 commit comments