import { useState, useEffect, useReducer, FC, ChangeEvent } from "react"; import { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from "next"; import Router from "next/router"; import Error from "next/error"; import { googleScrape, extractSlug } from "../utils/translate"; import Languages from "../components/Languages"; import { retrieveFiltered } from "../utils/language"; import langReducer, { Actions, initialState } from "../utils/reducer"; const Page: FC> = ({ translation, error, initial }) => { const [{ source, target, query }, dispatch] = useReducer(langReducer, initialState); const [encodedQuery, setEncodedQuery] = useState(""); const handleChange = (e: ChangeEvent) => { dispatch({ type: Actions.SET_FIELD, payload: { key: e.target.id, value: e.target.value } }); }; useEffect(() => { initial && dispatch({ type: Actions.SET_ALL, payload: { state: initial }}); }, [initial]); useEffect(() => { if (!query || query === initial?.query) return; const timeout = setTimeout(() => setEncodedQuery(encodeURIComponent(query)), 1000); return () => clearTimeout(timeout); }, [query, initial?.query]); useEffect(() => { encodedQuery && Router.push(`/${source}/${target}/${encodedQuery}`); }, [source, target, encodedQuery]); const { sourceLangs, targetLangs } = retrieveFiltered(source, target); return error ? ( ) : (
{translation}
); } export default Page; export const getStaticPaths: GetStaticPaths = async () => ({ paths: [ { params: { slug: [] } } ], fallback: true }); export const getStaticProps: GetStaticProps = async ({ params }) => { if (!params?.slug || !Array.isArray(params.slug)) return { props: {} }; const { source, target, query } = extractSlug(params.slug); if (!query) return { notFound: true }; if (!source || !target) return { redirect: { destination: `/${source ?? "auto"}/${target ?? "en"}/${query}`, permanent: true } } return { props: { ...await googleScrape(source, target, query), initial: { source, target, query } }, revalidate: 2 * 30 * 24 * 60 * 60 // 2 months }; }