327 lines
10 KiB
TypeScript
327 lines
10 KiB
TypeScript
"use client";
|
|||
|
|
|
||
|
|
import { useRouter } from "next/navigation";
|
||
|
|
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||
|
|
|
||
|
|
import { ApiError, api, errorText } from "@/lib/api";
|
||
|
|
import { countryName } from "@/lib/astro";
|
||
|
|
import type { BirthData, Country, Place } from "@/lib/types";
|
||
|
|
|
||
|
|
type Initial = (BirthData & { placeName: string | null; region: string | null }) | null;
|
||
|
|
type Ambiguity = "earlier" | "later";
|
||
|
|
|
||
|
|
const ERRORS: Record<string, string> = {
|
||
|
|
place_not_found: "Nem találjuk ezt a települést. Válassz a listából.",
|
||
|
|
nonexistent_local_time:
|
||
|
|
"Ez az időpont az óraátállítás miatt nem létezett ezen a napon (az órát előreállították). Ellenőrizd a születési időt.",
|
||
|
|
invalid_date: "Érvénytelen dátum.",
|
||
|
|
};
|
||
|
|
|
||
|
|
export function BirthForm({
|
||
|
|
initial,
|
||
|
|
onCancel,
|
||
|
|
onSaved,
|
||
|
|
}: {
|
||
|
|
initial: Initial;
|
||
|
|
onCancel?: () => void;
|
||
|
|
onSaved: () => void;
|
||
|
|
}) {
|
||
|
|
const router = useRouter();
|
||
|
|
const [date, setDate] = useState(initial?.date ?? "");
|
||
|
|
const [time, setTime] = useState(initial?.time?.slice(0, 5) ?? "");
|
||
|
|
const [timeUnknown, setTimeUnknown] = useState(initial ? !initial.time : false);
|
||
|
|
const [country, setCountry] = useState(initial?.country ?? "HU");
|
||
|
|
const [place, setPlace] = useState<Place | null>(
|
||
|
|
initial?.geonames_id && initial.placeName
|
||
|
|
? {
|
||
|
|
geonames_id: initial.geonames_id,
|
||
|
|
name: initial.placeName,
|
||
|
|
region: initial.region,
|
||
|
|
population: null,
|
||
|
|
country_code: initial.country ?? "HU",
|
||
|
|
}
|
||
|
|
: null,
|
||
|
|
);
|
||
|
|
const [ambiguous, setAmbiguous] = useState(false);
|
||
|
|
const [ambiguity, setAmbiguity] = useState<Ambiguity>("earlier");
|
||
|
|
const [error, setError] = useState<string | null>(null);
|
||
|
|
const [busy, setBusy] = useState(false);
|
||
|
|
const today = useMemo(() => new Date().toISOString().slice(0, 10), []);
|
||
|
|
|
||
|
|
async function submit(e: React.FormEvent) {
|
||
|
|
e.preventDefault();
|
||
|
|
setError(null);
|
||
|
|
if (!date) return setError("Add meg a születési dátumot.");
|
||
|
|
if (!timeUnknown && !time) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod.");
|
||
|
|
if (!place) return setError("Válaszd ki a születési helyet a listából.");
|
||
|
|
setBusy(true);
|
||
|
|
try {
|
||
|
|
await api("/charts", {
|
||
|
|
body: {
|
||
|
|
label: "Saját képlet",
|
||
|
|
is_primary: true,
|
||
|
|
birth: {
|
||
|
|
date,
|
||
|
|
...(timeUnknown ? {} : { time }),
|
||
|
|
country,
|
||
|
|
geonames_id: place.geonames_id,
|
||
|
|
...(ambiguous ? { ambiguous_time: ambiguity } : {}),
|
||
|
|
},
|
||
|
|
},
|
||
|
|
});
|
||
|
|
onSaved();
|
||
|
|
router.refresh();
|
||
|
|
} catch (err) {
|
||
|
|
if (err instanceof ApiError && err.code === "ambiguous_local_time") {
|
||
|
|
setAmbiguous(true);
|
||
|
|
setError(
|
||
|
|
"Ez az időpont az óraátállítás miatt kétszer is előfordult ezen a napon. Válaszd ki, melyikben születtél, és mentsd újra.",
|
||
|
|
);
|
||
|
|
} else {
|
||
|
|
setError(err instanceof ApiError ? (ERRORS[err.code] ?? errorText(err)) : errorText(err));
|
||
|
|
}
|
||
|
|
} finally {
|
||
|
|
setBusy(false);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return (
|
||
|
|
<form onSubmit={submit} className="field" style={{ gap: 18 }} noValidate>
|
||
|
|
<div className="grid-2">
|
||
|
|
<div className="field">
|
||
|
|
<label htmlFor="birth-date">Születési dátum</label>
|
||
|
|
<input
|
||
|
|
id="birth-date"
|
||
|
|
type="date"
|
||
|
|
className="inp"
|
||
|
|
min="1000-01-01"
|
||
|
|
max={today}
|
||
|
|
value={date}
|
||
|
|
onChange={(e) => setDate(e.target.value)}
|
||
|
|
required
|
||
|
|
/>
|
||
|
|
</div>
|
||
|
|
<div className="field">
|
||
|
|
<label htmlFor="birth-time">Születési idő (helyi idő)</label>
|
||
|
|
<input
|
||
|
|
id="birth-time"
|
||
|
|
type="time"
|
||
|
|
className="inp"
|
||
|
|
value={timeUnknown ? "" : time}
|
||
|
|
disabled={timeUnknown}
|
||
|
|
onChange={(e) => {
|
||
|
|
setTime(e.target.value);
|
||
|
|
setAmbiguous(false);
|
||
|
|
}}
|
||
|
|
/>
|
||
|
|
<label className="check">
|
||
|
|
<input type="checkbox" checked={timeUnknown} onChange={(e) => setTimeUnknown(e.target.checked)} />
|
||
|
|
Nem tudom a születési időt
|
||
|
|
</label>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
|
||
|
|
<div className="grid-2">
|
||
|
|
<CountrySelect
|
||
|
|
value={country}
|
||
|
|
onChange={(c) => {
|
||
|
|
setCountry(c);
|
||
|
|
setPlace(null);
|
||
|
|
}}
|
||
|
|
/>
|
||
|
|
<PlaceSearch country={country} value={place} onChange={setPlace} />
|
||
|
|
</div>
|
||
|
|
|
||
|
|
{ambiguous && (
|
||
|
|
<fieldset className="field" style={{ border: 0, padding: 0, margin: 0 }}>
|
||
|
|
<legend className="label" style={{ marginBottom: 8 }}>
|
||
|
|
Melyik időpontban születtél?
|
||
|
|
</legend>
|
||
|
|
<label className="check">
|
||
|
|
<input type="radio" name="ambiguity" checked={ambiguity === "earlier"} onChange={() => setAmbiguity("earlier")} />
|
||
|
|
Az elsőben, még nyári időszámítás szerint
|
||
|
|
</label>
|
||
|
|
<label className="check">
|
||
|
|
<input type="radio" name="ambiguity" checked={ambiguity === "later"} onChange={() => setAmbiguity("later")} />
|
||
|
|
A másodikban, már téli időszámítás szerint
|
||
|
|
</label>
|
||
|
|
</fieldset>
|
||
|
|
)}
|
||
|
|
|
||
|
|
{error && (
|
||
|
|
<p className="msg msg-error" role="alert">
|
||
|
|
{error}
|
||
|
|
</p>
|
||
|
|
)}
|
||
|
|
<div className="form-actions">
|
||
|
|
<button type="submit" className="btn btn-primary" disabled={busy}>
|
||
|
|
{busy ? "Számolás…" : "Mentés és képlet számítása"}
|
||
|
|
</button>
|
||
|
|
{onCancel && (
|
||
|
|
<button type="button" className="btn btn-ghost" onClick={onCancel} disabled={busy}>
|
||
|
|
Mégse
|
||
|
|
</button>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
</form>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
function CountrySelect({ value, onChange }: { value: string; onChange: (iso2: string) => void }) {
|
||
|
|
const [countries, setCountries] = useState<Country[]>([]);
|
||
|
|
useEffect(() => {
|
||
|
|
fetch("/api/geo/countries")
|
||
|
|
.then((r) => (r.ok ? r.json() : { countries: [] }))
|
||
|
|
.then((d: { countries: Country[] }) => {
|
||
|
|
const named = d.countries.map((c) => ({ iso2: c.iso2, name: countryName(c.iso2, c.name) }));
|
||
|
|
named.sort((a, b) => a.name.localeCompare(b.name, "hu"));
|
||
|
|
setCountries(named);
|
||
|
|
})
|
||
|
|
.catch(() => setCountries([]));
|
||
|
|
}, []);
|
||
|
|
return (
|
||
|
|
<div className="field">
|
||
|
|
<label htmlFor="birth-country">Ország</label>
|
||
|
|
<select id="birth-country" className="inp" value={value} onChange={(e) => onChange(e.target.value)}>
|
||
|
|
{countries.length === 0 && <option value={value}>{countryName(value)}</option>}
|
||
|
|
{countries.map((c) => (
|
||
|
|
<option key={c.iso2} value={c.iso2}>
|
||
|
|
{c.name}
|
||
|
|
</option>
|
||
|
|
))}
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
function PlaceSearch({
|
||
|
|
country,
|
||
|
|
value,
|
||
|
|
onChange,
|
||
|
|
}: {
|
||
|
|
country: string;
|
||
|
|
value: Place | null;
|
||
|
|
onChange: (p: Place | null) => void;
|
||
|
|
}) {
|
||
|
|
const listId = useId();
|
||
|
|
const [query, setQuery] = useState(value?.name ?? "");
|
||
|
|
const [results, setResults] = useState<Place[]>([]);
|
||
|
|
const [open, setOpen] = useState(false);
|
||
|
|
const [active, setActive] = useState(0);
|
||
|
|
const [loading, setLoading] = useState(false);
|
||
|
|
const seq = useRef(0);
|
||
|
|
|
||
|
|
// A new country starts a new search.
|
||
|
|
const firstCountry = useRef(country);
|
||
|
|
useEffect(() => {
|
||
|
|
if (country === firstCountry.current) return;
|
||
|
|
firstCountry.current = country;
|
||
|
|
setQuery("");
|
||
|
|
setResults([]);
|
||
|
|
}, [country]);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const q = query.trim();
|
||
|
|
if (q.length < 2 || (value && value.name === query)) {
|
||
|
|
setResults([]);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
const id = ++seq.current;
|
||
|
|
setLoading(true);
|
||
|
|
const timer = setTimeout(async () => {
|
||
|
|
try {
|
||
|
|
const res = await fetch(`/api/geo/places?country=${country}&q=${encodeURIComponent(q)}&limit=8`);
|
||
|
|
const data = res.ok ? ((await res.json()) as { places: Place[] }) : { places: [] };
|
||
|
|
if (id === seq.current) {
|
||
|
|
setResults(data.places);
|
||
|
|
setActive(0);
|
||
|
|
setOpen(true);
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
if (id === seq.current) setResults([]);
|
||
|
|
} finally {
|
||
|
|
if (id === seq.current) setLoading(false);
|
||
|
|
}
|
||
|
|
}, 250);
|
||
|
|
return () => clearTimeout(timer);
|
||
|
|
}, [query, country, value]);
|
||
|
|
|
||
|
|
function choose(p: Place) {
|
||
|
|
onChange(p);
|
||
|
|
setQuery(p.name);
|
||
|
|
setOpen(false);
|
||
|
|
}
|
||
|
|
|
||
|
|
function onKey(e: React.KeyboardEvent) {
|
||
|
|
if (!open || results.length === 0) return;
|
||
|
|
if (e.key === "ArrowDown") {
|
||
|
|
e.preventDefault();
|
||
|
|
setActive((a) => (a + 1) % results.length);
|
||
|
|
} else if (e.key === "ArrowUp") {
|
||
|
|
e.preventDefault();
|
||
|
|
setActive((a) => (a - 1 + results.length) % results.length);
|
||
|
|
} else if (e.key === "Enter") {
|
||
|
|
e.preventDefault();
|
||
|
|
choose(results[active]);
|
||
|
|
} else if (e.key === "Escape") {
|
||
|
|
setOpen(false);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const showList = open && results.length > 0;
|
||
|
|
return (
|
||
|
|
<div className="field">
|
||
|
|
<label htmlFor="birth-place">Település</label>
|
||
|
|
<div className="combo">
|
||
|
|
<input
|
||
|
|
id="birth-place"
|
||
|
|
className="inp"
|
||
|
|
role="combobox"
|
||
|
|
aria-expanded={showList}
|
||
|
|
aria-controls={listId}
|
||
|
|
aria-autocomplete="list"
|
||
|
|
aria-activedescendant={showList ? `${listId}-${active}` : undefined}
|
||
|
|
autoComplete="off"
|
||
|
|
placeholder="Kezdd el gépelni, pl. Szeged"
|
||
|
|
value={query}
|
||
|
|
onChange={(e) => {
|
||
|
|
setQuery(e.target.value);
|
||
|
|
if (value) onChange(null);
|
||
|
|
}}
|
||
|
|
onKeyDown={onKey}
|
||
|
|
onFocus={() => results.length > 0 && setOpen(true)}
|
||
|
|
onBlur={() => setTimeout(() => setOpen(false), 150)}
|
||
|
|
/>
|
||
|
|
{showList && (
|
||
|
|
<ul className="combo-list" id={listId} role="listbox">
|
||
|
|
{results.map((p, i) => (
|
||
|
|
<li key={p.geonames_id} role="presentation">
|
||
|
|
<button
|
||
|
|
type="button"
|
||
|
|
id={`${listId}-${i}`}
|
||
|
|
role="option"
|
||
|
|
aria-selected={i === active}
|
||
|
|
tabIndex={-1}
|
||
|
|
onMouseDown={(e) => e.preventDefault()}
|
||
|
|
onClick={() => choose(p)}
|
||
|
|
>
|
||
|
|
{p.name} {p.region && <small>· {p.region}</small>}
|
||
|
|
</button>
|
||
|
|
</li>
|
||
|
|
))}
|
||
|
|
</ul>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
<span className="hint" aria-live="polite">
|
||
|
|
{value
|
||
|
|
? `Kiválasztva: ${value.name}${value.region ? `, ${value.region}` : ""}`
|
||
|
|
: loading
|
||
|
|
? "Keresés…"
|
||
|
|
: query.trim().length >= 2 && results.length === 0
|
||
|
|
? "Nincs találat ebben az országban."
|
||
|
|
: "Válassz a listából."}
|
||
|
|
</span>
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|