diff --git a/pages/[[...slug]].tsx b/pages/[[...slug]].tsx index beae4af..1f18253 100644 --- a/pages/[[...slug]].tsx +++ b/pages/[[...slug]].tsx @@ -1,36 +1,43 @@ -import { useState, useEffect, FC } from "react"; +import { useEffect, useReducer, FC, ChangeEvent } from "react"; import { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from "next"; import { useRouter } from "next/router"; import Error from "next/error"; import { googleScrape, extractSlug } from "../utils/translate"; import Languages from "../components/Languages"; import { languages, exceptions } from "../utils/languages.json"; +import langReducer, { Actions, initialState } from "../utils/reducer"; const Page: FC> = ({ translation, error, initial }) => { if (error) return - const router = useRouter(); + const [{ source, target, query }, dispatch] = useReducer(langReducer, initialState); - const [source, setSource] = useState("auto"); - const [target, setTarget] = useState("en"); - const [query, setQuery] = useState(""); + const handleChange = (e: ChangeEvent) => { + dispatch({ + type: Actions.SET_FIELD, + payload: { + key: e.target.id, + value: e.target.value + } + }); + }; + + const router = useRouter(); const updateTranslation = () => { query && router.push(`/${source}/${target}/${query}`); }; useEffect(() => { - initial?.source && setSource(initial.source); - initial?.target && setTarget(initial.target); - initial?.query && setQuery(initial.query); + initial && dispatch({ type: Actions.SET_ALL, payload: { state: initial }}); }, [initial]); useEffect(() => { if (!query || query === initial?.query) return; - const timeout = setTimeout(updateTranslation, 1500); + const timeout = setTimeout(updateTranslation, 1000); return () => clearTimeout(timeout); }, [query]); @@ -46,7 +53,7 @@ const Page: FC> = ({ translation, - @@ -54,7 +61,7 @@ const Page: FC> = ({ translation, - @@ -62,7 +69,7 @@ const Page: FC> = ({ translation, - setQuery(e.target.value)} /> +
{translation} diff --git a/utils/languages.json b/utils/languages.json index 7b70f70..68c2975 100644 --- a/utils/languages.json +++ b/utils/languages.json @@ -121,6 +121,7 @@ }, "mappings": { "target": { + "zh": "zh-CN", "zh_HANT": "zh-TW" } } diff --git a/utils/reducer.ts b/utils/reducer.ts new file mode 100644 index 0000000..27ea0ee --- /dev/null +++ b/utils/reducer.ts @@ -0,0 +1,37 @@ +export enum Actions { + "SET_FIELD", + "SET_ALL" +} + +export const initialState = { + source: "auto", + target: "en", + query: "" +} + +type Action = { + type: Actions.SET_FIELD, + payload: { + key: string, + value: string + } +} | { + type: Actions.SET_ALL, + payload: { + state: { + [key: string]: string + } + } +} + +export default function reducer(state: typeof initialState, action: Action) { + switch (action.type) { + case Actions.SET_FIELD: + const { key, value } = action.payload; + return { ...state, [key]: value }; + case Actions.SET_ALL: + return { ...state, ...action.payload.state }; + default: + return state; + } +}