From e03f43ad2894a00f672b97d4d4677a5654c305df Mon Sep 17 00:00:00 2001 From: XLor Date: Thu, 1 Jun 2023 21:35:52 +0800 Subject: [PATCH] feat(app): init search command --- packages/animegarden/src/garden.ts | 2 +- packages/app/src/components/Search.tsx | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/animegarden/src/garden.ts b/packages/animegarden/src/garden.ts index 67034917..9b579e35 100644 --- a/packages/animegarden/src/garden.ts +++ b/packages/animegarden/src/garden.ts @@ -90,7 +90,7 @@ export interface FetchResourceDetailOptions { retry?: number; } -interface SearchParams { +export interface SearchParams { search: string[]; include: string[][]; diff --git a/packages/app/src/components/Search.tsx b/packages/app/src/components/Search.tsx index 919a1f74..a78dbe58 100644 --- a/packages/app/src/components/Search.tsx +++ b/packages/app/src/components/Search.tsx @@ -1,3 +1,5 @@ +import type { SearchParams } from 'animegarden'; + import useSWR from 'swr'; import { Command } from 'cmdk'; import { tradToSimple } from 'simptrad'; @@ -47,6 +49,10 @@ const useActiveElement = () => { }; }; +const initialized = { + url: location as Location | undefined +}; + export default function Search() { const ref = useRef(null); const inputRef = useRef(null); @@ -55,6 +61,17 @@ export default function Search() { const [input, setInput] = useState(''); const [search, setSearch] = useState(''); + // Init search input + if (initialized.url !== undefined) { + const searchParams = new URLSearchParams(initialized.url.search); + const cmd = searchParams.get('cmd'); + if (cmd !== undefined && typeof cmd === 'string') { + setInput(cmd); + setSearch(cmd); + } + initialized.url = undefined; + } + const setDebounceSearch = debounce((value: string) => { if (value !== search) { setSearch(value); @@ -214,6 +231,11 @@ export default function Search() { ); } +function stringifySearch(search: SearchParams | undefined) { + if (!search) return ''; + return `${search.search.join(' ')}`; +} + function parseSearch(search: string) { const splitted = search .split(' ') @@ -309,6 +331,7 @@ function goToSearch(search: string) { if (after !== undefined) { query.push(`after=${after.toISOString()}`); } + query.push(`cmd=${encodeURIComponent(search)}`); goTo(`/resources/1?${query.join('&')}`); } }