Files
sorsfonalak/services/frontend/src/app/profil/BirthForm.tsx
T

520 lines
18 KiB
TypeScript
Raw Normal View History

"use client";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { ApiError, api, errorText } from "@/lib/api";
import { countryName } from "@/lib/astro";
import { BIRTH_DRAFT_KEY, type BirthDraft, MONTHS, composeDate, composeTime, daysIn } from "@/lib/birth";
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.",
};
/** Someone else's chart: added with a name, or (with `chartId`) corrected. */
export type PersonTarget = { chartId?: string; name?: string };
/** The birth data the form sends (as `POST /v1/charts` takes it). */
export type BirthInput = {
date: string;
time?: string;
country: string;
geonames_id: number;
ambiguous_time?: Ambiguity;
};
export function BirthForm({
initial,
person,
save,
children,
onCancel,
onSaved,
}: {
initial: Initial;
/** Not given: the user's own birth data. */
person?: PersonTarget;
/**
* Saves somewhere else than the user's charts (e.g. a famous person); gets
* the birth data only when it changed. Its errors show in the form.
*/
save?: (name: string, birth: BirthInput | null) => Promise<{ id: string }>;
/** More fields, after the name. */
children?: React.ReactNode;
onCancel?: () => void;
onSaved: (chartId: string) => void;
}) {
const [name, setName] = useState(person?.name ?? "");
// Our own fields, not the browser's date and time inputs: those follow the
// operating system's or the browser's region (US order, AM/PM in Safari).
const [year, setYear] = useState(initial?.date?.slice(0, 4) ?? "");
const [month, setMonth] = useState(initial?.date ? String(Number(initial.date.slice(5, 7))) : "");
const [day, setDay] = useState(initial?.date ? String(Number(initial.date.slice(8, 10))) : "");
const [hour, setHour] = useState(initial?.time?.slice(0, 2) ?? "");
const [minute, setMinute] = useState(initial?.time?.slice(3, 5) ?? "");
const minuteRef = useRef<HTMLInputElement>(null);
const date = composeDate(year, month, day) ?? "";
const time = composeTime(hour, minute) ?? "";
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), []);
const [fromDraft, setFromDraft] = useState(false);
// The own birth data, not given yet: offer what the visitor typed into the
// public birth chart page before signing up.
useEffect(() => {
if (initial || person) return;
let draft: BirthDraft | null = null;
try {
draft = JSON.parse(sessionStorage.getItem(BIRTH_DRAFT_KEY) ?? "null");
} catch {
return;
}
if (!draft || !/^\d{4}-\d{2}-\d{2}$/.test(draft.date) || !draft.geonames_id) return;
setYear(draft.date.slice(0, 4));
setMonth(String(Number(draft.date.slice(5, 7))));
setDay(String(Number(draft.date.slice(8, 10))));
if (draft.time) {
setHour(draft.time.slice(0, 2));
setMinute(draft.time.slice(3, 5));
}
setTimeUnknown(!draft.time);
setCountry(draft.country);
setPlace({
geonames_id: draft.geonames_id,
name: draft.placeName,
region: draft.region,
population: null,
country_code: draft.country,
});
setFromDraft(true);
}, [initial, person]);
async function submit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (person && !name.trim()) return setError("Add meg a nevét.");
if (!year && !month && !day) return setError("Add meg a születési dátumot.");
if (!date) return setError("Ellenőrizd a dátumot: az év négy számjegy, és a nap legyen az adott hónapban.");
if (date > today) return setError("A születési dátum nem lehet a jövőben.");
if (!timeUnknown && !hour && !minute) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod.");
if (!timeUnknown && !time) return setError("Ellenőrizd az időt: óra 0–23, perc 0–59.");
if (!place) return setError("Válaszd ki a születési helyet a listából.");
setBusy(true);
try {
const birth: BirthInput = {
date,
...(timeUnknown ? {} : { time }),
country,
geonames_id: place.geonames_id,
...(ambiguous ? { ambiguous_time: ambiguity } : {}),
};
// Correcting a person: the birth data only when it changed, so a new
// name alone does not recalculate the chart or drop its analyses.
const birthChanged =
!initial ||
ambiguous ||
date !== initial.date ||
(timeUnknown ? null : time) !== (initial.time?.slice(0, 5) ?? null) ||
country !== (initial.country ?? "HU") ||
place.geonames_id !== initial.geonames_id;
const saved = save
? await save(name.trim(), birthChanged ? birth : null)
: person?.chartId
? await api<{ id: string }>(`/charts/${person.chartId}`, {
method: "PATCH",
body: birthChanged ? { label: name.trim(), birth } : { label: name.trim() },
})
: await api<{ id: string }>("/charts", {
body: person
? { label: name.trim(), is_primary: false, birth }
: { label: "Saját képlet", is_primary: true, birth },
});
try {
sessionStorage.removeItem(BIRTH_DRAFT_KEY);
} catch {
// storage blocked
}
onSaved(saved.id);
} 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>
{fromDraft && (
<p className="msg msg-ok" style={{ margin: 0 }}>
Áthoztuk az adatokat, amelyeket a születési horoszkópnál megadtál. Ellenőrizd, és mentsd el.
</p>
)}
{person && (
<div className="field" style={{ maxWidth: 420 }}>
<label htmlFor="person-name">Név</label>
<input
id="person-name"
className="inp"
value={name}
maxLength={100}
autoComplete="off"
onChange={(e) => setName(e.target.value)}
required
/>
</div>
)}
{children}
<div className="grid-2">
<fieldset className="field birth-fields">
<legend className="label">Születési dátum</legend>
<div className="birth-row">
<label className="sr-only" htmlFor="birth-year">
Év
</label>
<input
id="birth-year"
className="inp birth-year"
inputMode="numeric"
autoComplete="bday-year"
placeholder="év"
maxLength={4}
value={year}
onChange={(e) => setYear(e.target.value.replace(/\D/g, ""))}
/>
<label className="sr-only" htmlFor="birth-month">
Hónap
</label>
<select
id="birth-month"
className="inp birth-month"
autoComplete="bday-month"
value={month}
onChange={(e) => setMonth(e.target.value)}
>
<option value="">hónap</option>
{MONTHS.map((m, i) => (
<option key={m} value={i + 1}>
{m}
</option>
))}
</select>
<label className="sr-only" htmlFor="birth-day">
Nap
</label>
<select
id="birth-day"
className="inp birth-day"
autoComplete="bday-day"
value={day}
onChange={(e) => setDay(e.target.value)}
>
<option value="">nap</option>
{Array.from({ length: month ? daysIn(Number(year), Number(month)) : 31 }, (_, i) => (
<option key={i + 1} value={i + 1}>
{i + 1}.
</option>
))}
</select>
</div>
</fieldset>
<fieldset className="field birth-fields">
<legend className="label">Születési idő (helyi idő)</legend>
<div className="birth-row">
<label className="sr-only" htmlFor="birth-hour">
Óra
</label>
<input
id="birth-hour"
className="inp birth-time"
inputMode="numeric"
placeholder="óra"
maxLength={2}
value={timeUnknown ? "" : hour}
disabled={timeUnknown}
onChange={(e) => {
const v = e.target.value.replace(/\D/g, "");
setHour(v);
setAmbiguous(false);
// Two digits (or one that cannot start a valid hour): on to the minutes.
if (v.length === 2 || (v.length === 1 && Number(v) > 2)) minuteRef.current?.focus();
}}
/>
<span className="birth-colon" aria-hidden="true">
:
</span>
<label className="sr-only" htmlFor="birth-minute">
Perc
</label>
<input
id="birth-minute"
ref={minuteRef}
className="inp birth-time"
inputMode="numeric"
placeholder="perc"
maxLength={2}
value={timeUnknown ? "" : minute}
disabled={timeUnknown}
onChange={(e) => {
setMinute(e.target.value.replace(/\D/g, ""));
setAmbiguous(false);
}}
/>
</div>
<label className="check">
<input type="checkbox" checked={timeUnknown} onChange={(e) => setTimeUnknown(e.target.checked)} />
Nem tudom a születési időt
</label>
</fieldset>
</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 }}>
{person ? "Melyik időpontban született?" : "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…" : person?.chartId ? "Javítás mentése" : "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>
);
}
/** Where the country list and the place search come from: logged-in users, or the public calculator. */
export type GeoBase = "/api/geo" | "/api/v1/public/geo";
export function CountrySelect({
value,
onChange,
geoBase = "/api/geo",
}: {
value: string;
onChange: (iso2: string) => void;
geoBase?: GeoBase;
}) {
const [countries, setCountries] = useState<Country[]>([]);
useEffect(() => {
fetch(`${geoBase}/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([]));
}, [geoBase]);
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>
);
}
export function PlaceSearch({
country,
value,
onChange,
geoBase = "/api/geo",
}: {
country: string;
value: Place | null;
onChange: (p: Place | null) => void;
geoBase?: GeoBase;
}) {
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]);
// A place set from outside (e.g. brought over from the public chart page) shows its name.
useEffect(() => {
if (value) setQuery((q) => (q === value.name ? q : value.name));
}, [value]);
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(`${geoBase}/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, geoBase]);
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>
);
}