refactor: search input (#1205)

This commit is contained in:
Whitewater
2023-02-27 18:08:06 +08:00
committed by GitHub
parent b41c8130bf
commit b6cb52f702
6 changed files with 192 additions and 246 deletions
@@ -6,10 +6,22 @@ import React from 'react';
import { usePageHelper } from '@/hooks/use-page-helper'; import { usePageHelper } from '@/hooks/use-page-helper';
import { StyledModalFooterContent } from './style'; import { StyledModalFooterContent } from './style';
export const Footer = (props: { query: string; onClose: () => void }) => {
const MAX_QUERY_SHOW_LENGTH = 20;
export const Footer = ({
query,
onClose,
}: {
query: string;
onClose: () => void;
}) => {
const { openPage, createPage } = usePageHelper(); const { openPage, createPage } = usePageHelper();
const { t } = useTranslation(); const { t } = useTranslation();
const { query, onClose } = props; const normalizedQuery =
query.length > MAX_QUERY_SHOW_LENGTH
? query.slice(0, MAX_QUERY_SHOW_LENGTH) + '...'
: query;
return ( return (
<Command.Item <Command.Item
@@ -25,7 +37,7 @@ export const Footer = (props: { query: string; onClose: () => void }) => {
<StyledModalFooterContent> <StyledModalFooterContent>
<PlusIcon /> <PlusIcon />
{query ? ( {query ? (
<span>{t('New Keyword Page', { query: query })}</span> <span>{t('New Keyword Page', { query: normalizedQuery })}</span>
) : ( ) : (
<span>{t('New Page')}</span> <span>{t('New Page')}</span>
)} )}
@@ -1,100 +0,0 @@
import { useTranslation } from '@affine/i18n';
import { SearchIcon } from '@blocksuite/icons';
import { Command } from 'cmdk';
import React, {
Dispatch,
SetStateAction,
useEffect,
useRef,
useState,
} from 'react';
import { StyledInputContent, StyledLabel } from './style';
export const Input = (props: {
open: boolean;
query: string;
setQuery: Dispatch<SetStateAction<string>>;
setLoading: Dispatch<SetStateAction<boolean>>;
isPublic: boolean;
publishWorkspaceName: string | undefined;
}) => {
const { open, query, setQuery, setLoading, isPublic, publishWorkspaceName } =
props;
const [isComposition, setIsComposition] = useState(false);
const [inputValue, setInputValue] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const { t } = useTranslation();
useEffect(() => {
if (open) {
const inputElement = inputRef.current;
return inputElement?.focus();
}
}, [open]);
useEffect(() => {
const inputElement = inputRef.current;
if (!open) {
return;
}
const handleFocus = () => {
inputElement?.focus();
};
inputElement?.addEventListener('blur', handleFocus, true);
return () => inputElement?.removeEventListener('blur', handleFocus, true);
}, [inputRef, open]);
useEffect(() => {
setInputValue(query);
}, [query]);
return (
<StyledInputContent>
<StyledLabel htmlFor=":r5:">
<SearchIcon />
</StyledLabel>
<Command.Input
ref={inputRef}
value={inputValue}
onCompositionStart={() => {
setIsComposition(true);
}}
onCompositionEnd={e => {
setQuery(e.data);
setIsComposition(false);
if (!query) {
setLoading(true);
}
}}
onValueChange={str => {
setInputValue(str);
if (!isComposition) {
setQuery(str);
if (!query) {
setLoading(true);
}
}
}}
onKeyDown={(e: React.KeyboardEvent) => {
if (e.key === 'a' && e.metaKey) {
e.stopPropagation();
inputRef.current?.select();
return;
}
if (isComposition) {
if (
e.key === 'ArrowDown' ||
e.key === 'ArrowUp' ||
e.key === 'Enter'
) {
e.stopPropagation();
}
}
}}
placeholder={
isPublic
? t('Quick search placeholder2', {
workspace: publishWorkspaceName,
})
: t('Quick search placeholder')
}
/>
</StyledInputContent>
);
};
@@ -12,18 +12,17 @@ import { useGlobalState } from '@/store/app';
import { NoResultSVG } from './NoResultSVG'; import { NoResultSVG } from './NoResultSVG';
import { StyledListItem, StyledNotFound } from './style'; import { StyledListItem, StyledNotFound } from './style';
export const PublishedResults = (props: { export const PublishedResults = ({
query,
onClose,
setPublishWorkspaceName,
}: {
query: string; query: string;
loading: boolean;
setLoading: Dispatch<SetStateAction<boolean>>;
setPublishWorkspaceName: Dispatch<SetStateAction<string>>; setPublishWorkspaceName: Dispatch<SetStateAction<string>>;
onClose: () => void; onClose: () => void;
}) => { }) => {
const [workspace, setWorkspace] = useState<Workspace>(); const [workspace, setWorkspace] = useState<Workspace>();
const { query, loading, setLoading, onClose, setPublishWorkspaceName } =
props;
const { search } = usePageHelper(); const { search } = usePageHelper();
const [results, setResults] = useState(new Map<string, string | undefined>());
const dataCenter = useGlobalState(store => store.dataCenter); const dataCenter = useGlobalState(store => store.dataCenter);
const router = useRouter(); const router = useRouter();
const [pageList, setPageList] = useState<PageMeta[]>([]); const [pageList, setPageList] = useState<PageMeta[]>([]);
@@ -42,57 +41,49 @@ export const PublishedResults = (props: {
}); });
}, [router, dataCenter, setPublishWorkspaceName]); }, [router, dataCenter, setPublishWorkspaceName]);
const { t } = useTranslation(); const { t } = useTranslation();
useEffect(() => {
setResults(search(query, workspace)); if (!query) {
setLoading(false); return <></>;
//Save the Map<BlockId, PageId> obtained from the search as state }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, setResults, setLoading]); const results = search(query, workspace);
const pageIds = [...results.values()]; const pageIds = [...results.values()];
const resultsPageMeta = pageList.filter( const resultsPageMeta = pageList.filter(
page => pageIds.indexOf(page.id) > -1 && !page.trash page => pageIds.indexOf(page.id) > -1 && !page.trash
); );
return loading ? null : ( if (!resultsPageMeta.length) {
<> return (
{query ? ( <StyledNotFound>
resultsPageMeta.length ? ( <span>{t('Find 0 result')}</span>
<Command.Group <NoResultSVG />
heading={t('Find results', { number: resultsPageMeta.length })} </StyledNotFound>
> );
{resultsPageMeta.map(result => { }
return (
<Command.Item return (
key={result.id} <Command.Group
onSelect={() => { heading={t('Find results', { number: resultsPageMeta.length })}
router.push( >
`/public-workspace/${router.query.workspaceId}/${result.id}` {resultsPageMeta.map(result => {
); return (
onClose(); <Command.Item
}} key={result.id}
value={result.id} onSelect={() => {
> router.push(
<StyledListItem> `/public-workspace/${router.query.workspaceId}/${result.id}`
{result.mode === 'edgeless' ? (
<EdgelessIcon />
) : (
<PaperIcon />
)}
<span>{result.title}</span>
</StyledListItem>
</Command.Item>
); );
})} onClose();
</Command.Group> }}
) : ( value={result.id}
<StyledNotFound> >
<span>{t('Find 0 result')}</span> <StyledListItem>
<NoResultSVG /> {result.mode === 'edgeless' ? <EdgelessIcon /> : <PaperIcon />}
</StyledNotFound> <span>{result.title}</span>
) </StyledListItem>
) : ( </Command.Item>
<></> );
)} })}
</> </Command.Group>
); );
}; };
@@ -2,13 +2,7 @@ import { useTranslation } from '@affine/i18n';
import { EdgelessIcon, PaperIcon } from '@blocksuite/icons'; import { EdgelessIcon, PaperIcon } from '@blocksuite/icons';
import { Command } from 'cmdk'; import { Command } from 'cmdk';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { import { Dispatch, SetStateAction, useCallback, useEffect } from 'react';
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react';
import usePageHelper from '@/hooks/use-page-helper'; import usePageHelper from '@/hooks/use-page-helper';
import { useGlobalState } from '@/store/app'; import { useGlobalState } from '@/store/app';
@@ -16,14 +10,16 @@ import { useGlobalState } from '@/store/app';
import { useSwitchToConfig } from './config'; import { useSwitchToConfig } from './config';
import { NoResultSVG } from './NoResultSVG'; import { NoResultSVG } from './NoResultSVG';
import { StyledListItem, StyledNotFound } from './style'; import { StyledListItem, StyledNotFound } from './style';
export const Results = (props: {
export const Results = ({
query,
setShowCreatePage,
onClose,
}: {
query: string; query: string;
loading: boolean;
onClose: () => void; onClose: () => void;
setLoading: Dispatch<SetStateAction<boolean>>;
setShowCreatePage: Dispatch<SetStateAction<boolean>>; setShowCreatePage: Dispatch<SetStateAction<boolean>>;
}) => { }) => {
const { query, loading, setLoading, setShowCreatePage, onClose } = props;
const { openPage } = usePageHelper(); const { openPage } = usePageHelper();
const router = useRouter(); const router = useRouter();
const currentWorkspace = useGlobalState( const currentWorkspace = useGlobalState(
@@ -34,80 +30,74 @@ export const Results = (props: {
); );
const { search } = usePageHelper(); const { search } = usePageHelper();
const List = useSwitchToConfig(currentWorkspace?.id); const List = useSwitchToConfig(currentWorkspace?.id);
const [results, setResults] = useState(new Map<string, string | undefined>());
const { t } = useTranslation(); const { t } = useTranslation();
useEffect(() => {
setResults(search(query));
setLoading(false);
//Save the Map<BlockId, PageId> obtained from the search as state
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, setResults, setLoading]);
const pageIds = [...results.values()];
const results = search(query);
const pageIds = [...results.values()];
const resultsPageMeta = pageList.filter( const resultsPageMeta = pageList.filter(
page => pageIds.indexOf(page.id) > -1 && !page.trash page => pageIds.indexOf(page.id) > -1 && !page.trash
); );
// TODO lift this state up and remove this effect!
useEffect(() => { useEffect(() => {
setShowCreatePage(!resultsPageMeta.length); setShowCreatePage(!resultsPageMeta.length);
//Determine whether to display the + New page //Determine whether to display the + New page
}, [resultsPageMeta, setShowCreatePage]); }, [resultsPageMeta, setShowCreatePage]);
return loading ? null : (
<> if (!query) {
{query ? ( return (
resultsPageMeta.length ? ( <Command.Group heading={t('Jump to')}>
<Command.Group {List.map(link => {
heading={t('Find results', { number: resultsPageMeta.length })} return (
<Command.Item
key={link.title}
value={link.title}
onSelect={() => {
onClose();
router.push(link.href);
}}
>
<StyledListItem>
<link.icon />
<span>{link.title}</span>
</StyledListItem>
</Command.Item>
);
})}
</Command.Group>
);
}
if (!resultsPageMeta.length) {
return (
<StyledNotFound>
<span>{t('Find 0 result')}</span>
<NoResultSVG />
</StyledNotFound>
);
}
return (
<Command.Group
heading={t('Find results', { number: resultsPageMeta.length })}
>
{resultsPageMeta.map(result => {
return (
<Command.Item
key={result.id}
onSelect={() => {
onClose();
openPage(result.id);
}}
value={result.id}
> >
{resultsPageMeta.map(result => { <StyledListItem>
return ( {result.mode === 'edgeless' ? <EdgelessIcon /> : <PaperIcon />}
<Command.Item <span>{result.title}</span>
key={result.id} </StyledListItem>
onSelect={() => { </Command.Item>
onClose(); );
openPage(result.id); })}
}} </Command.Group>
value={result.id}
>
<StyledListItem>
{result.mode === 'edgeless' ? (
<EdgelessIcon />
) : (
<PaperIcon />
)}
<span>{result.title}</span>
</StyledListItem>
</Command.Item>
);
})}
</Command.Group>
) : (
<StyledNotFound>
<span>{t('Find 0 result')}</span>
<NoResultSVG />
</StyledNotFound>
)
) : (
<Command.Group heading={t('Jump to')}>
{List.map(link => {
return (
<Command.Item
key={link.title}
value={link.title}
onSelect={() => {
onClose();
router.push(link.href);
}}
>
<StyledListItem>
<link.icon />
<span>{link.title}</span>
</StyledListItem>
</Command.Item>
);
})}
</Command.Group>
)}
</>
); );
}; };
@@ -0,0 +1,33 @@
import { SearchIcon } from '@blocksuite/icons';
import { Command } from 'cmdk';
import { forwardRef } from 'react';
import { StyledInputContent, StyledLabel } from './style';
export const SearchInput = forwardRef<
HTMLInputElement,
Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'value' | 'onChange' | 'type'
> & {
/**
* Optional controlled state for the value of the search input.
*/
value?: string;
/**
* Event handler called when the search value changes.
*/
onValueChange?: (search: string) => void;
} & React.RefAttributes<HTMLInputElement>
>((props, ref) => {
return (
<StyledInputContent>
<StyledLabel htmlFor=":r5:">
<SearchIcon />
</StyledLabel>
<Command.Input ref={ref} {...props} />
</StyledInputContent>
);
});
SearchInput.displayName = 'SearchInput';
+36 -16
View File
@@ -1,15 +1,16 @@
import { Modal, ModalWrapper } from '@affine/component'; import { Modal, ModalWrapper } from '@affine/component';
import { useTranslation } from '@affine/i18n';
import { Command } from 'cmdk'; import { Command } from 'cmdk';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useModal } from '@/store/globalModal'; import { useModal } from '@/store/globalModal';
import { getUaHelper } from '@/utils'; import { getUaHelper } from '@/utils';
import { Footer } from './Footer'; import { Footer } from './Footer';
import { Input } from './Input';
import { PublishedResults } from './PublishedResults'; import { PublishedResults } from './PublishedResults';
import { Results } from './Results'; import { Results } from './Results';
import { SearchInput } from './SearchInput';
import { import {
StyledContent, StyledContent,
StyledModalDivider, StyledModalDivider,
@@ -17,10 +18,12 @@ import {
StyledModalHeader, StyledModalHeader,
StyledShortcut, StyledShortcut,
} from './style'; } from './style';
type TransitionsModalProps = { type TransitionsModalProps = {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
}; };
const isMac = () => { const isMac = () => {
return getUaHelper().isMacOs; return getUaHelper().isMacOs;
}; };
@@ -28,8 +31,9 @@ const isMac = () => {
// fixme(himself65): support ssr // fixme(himself65): support ssr
export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => { export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => {
const router = useRouter(); const router = useRouter();
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [loading, setLoading] = useState(true);
const [isPublic, setIsPublic] = useState(false); const [isPublic, setIsPublic] = useState(false);
const [publishWorkspaceName, setPublishWorkspaceName] = useState(''); const [publishWorkspaceName, setPublishWorkspaceName] = useState('');
const [showCreatePage, setShowCreatePage] = useState(true); const [showCreatePage, setShowCreatePage] = useState(true);
@@ -38,7 +42,6 @@ export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => {
return isPublic && query.length === 0; return isPublic && query.length === 0;
}; };
const handleClose = () => { const handleClose = () => {
setQuery('');
onClose(); onClose();
}; };
// Add ‘⌘+K shortcut keys as switches // Add ‘⌘+K shortcut keys as switches
@@ -73,10 +76,19 @@ export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => {
}, [router]); }, [router]);
useEffect(() => { useEffect(() => {
if (router.pathname.startsWith('/404')) { if (router.pathname.startsWith('/404')) {
return onClose(); onClose();
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => {
if (open) {
// Waiting for DOM rendering
requestAnimationFrame(() => {
const inputElement = inputRef.current;
inputElement?.focus();
});
}
}, [open]);
return ( return (
<Modal <Modal
@@ -108,13 +120,25 @@ export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => {
}} }}
> >
<StyledModalHeader> <StyledModalHeader>
<Input <SearchInput
open={open} ref={inputRef}
query={query} onValueChange={value => {
setQuery={setQuery} setQuery(value);
setLoading={setLoading} }}
isPublic={isPublic} onKeyDown={e => {
publishWorkspaceName={publishWorkspaceName} // Avoid triggering the cmdk onSelect event when the input method is in use
if (e.nativeEvent.isComposing) {
e.stopPropagation();
return;
}
}}
placeholder={
isPublic
? t('Quick search placeholder2', {
workspace: publishWorkspaceName,
})
: t('Quick search placeholder')
}
/> />
<StyledShortcut>{isMac() ? '⌘ + K' : 'Ctrl + K'}</StyledShortcut> <StyledShortcut>{isMac() ? '⌘ + K' : 'Ctrl + K'}</StyledShortcut>
</StyledModalHeader> </StyledModalHeader>
@@ -128,16 +152,12 @@ export const QuickSearch = ({ open, onClose }: TransitionsModalProps) => {
{!isPublic ? ( {!isPublic ? (
<Results <Results
query={query} query={query}
loading={loading}
setLoading={setLoading}
onClose={handleClose} onClose={handleClose}
setShowCreatePage={setShowCreatePage} setShowCreatePage={setShowCreatePage}
/> />
) : ( ) : (
<PublishedResults <PublishedResults
query={query} query={query}
loading={loading}
setLoading={setLoading}
onClose={handleClose} onClose={handleClose}
setPublishWorkspaceName={setPublishWorkspaceName} setPublishWorkspaceName={setPublishWorkspaceName}
data-testid="publishedSearchResults" data-testid="publishedSearchResults"