Files
sorsfonalak/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx
T
fecoandClaude Opus 5.5 8b8285b5d2
CI / test (push) Successful in 1m41s
CI / build (push) Successful in 5m22s
CI / deploy (push) Skipped
No browser storage for referrals; the birth chart opens at the drawn chart
The share page stores nothing in the browser any more: the shared link
that brought a visitor travels in its login link (/belepes?ref=...) to
the Google, Apple and password sign-up. The backend counts the same
visitor of a link once in half an hour, instead of a sessionStorage flag.

The public birth chart scrolls to the drawn chart after a calculation
and when coming back to the page. Tabs scrolled to themselves on every
re-render of their parent when the address had a tab (#bolygok); they
now react only to the tab ids and hash changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-21 21:13:41 +00:00

453 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { CountrySelect, PlaceSearch } from "@/app/profil/BirthForm";
import { AspectGrid, AspectList, BigThree, PositionTables } from "@/components/ChartTables";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { Tabs } from "@/components/Tabs";
import { ZODIAC_BY_ID } from "@/content/zodiac";
import { ApiError, api, errorText } from "@/lib/api";
import { ASPECTS, countryName, formatBirthDate } from "@/lib/astro";
import { BIRTH_DRAFT_KEY, MONTHS, type BirthDraft, composeDate, composeTime, daysIn } from "@/lib/birth";
import type { BirthData, Chart, ChartResult, Place } from "@/lib/types";
interface Result {
highlights: Chart["highlights"];
/** Without a birth time: the sign may have been the neighbouring one at the start or end of the day. */
uncertain: { sun: boolean; moon: boolean };
chart: ChartResult;
}
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.",
too_many_requests: "Erről a címről most túl sok számítás érkezett. Próbáld újra egy óra múlva.",
};
const GRID_LEGEND = ["conjunction", "sextile", "square", "trine", "opposition"];
/**
* The calculated chart and the typed birth data, kept for this browser tab
* only (sessionStorage: not a cookie, gone when the tab is closed), so they
* are there again after visiting another page, and the profile can offer the
* birth data after signing up in the same tab. Storage that only keeps what
* the visitor typed, for the session, needs no consent. Nothing of this is
* stored on the server.
*/
const CHART_KEY = "sf_public_chart";
type Saved = { result: Result; birth: BirthData };
/** Links to the sign pages of the Sun, Moon and Ascendant. */
function SignLinks({ result }: { result: Result }) {
const links: [string, string | null, string, boolean][] = [
["Napjegy", result.highlights.sun, "nap", result.uncertain.sun],
["Holdjegy", result.highlights.moon, "hold", result.uncertain.moon],
["Aszcendens", result.highlights.time_known ? result.highlights.ascendant : null, "aszcendens", false],
];
return (
<div className="card calc-links">
<span className="eyebrow">Mit jelentenek?</span>
<ul>
{links.map(([label, sign, anchor, uncertain]) => {
const z = sign ? ZODIAC_BY_ID.get(sign) : undefined;
return (
<li key={anchor}>
{z ? (
<Link href={`/csillagjegyek/${z.slug}#${anchor}`}>
{label}: {z.name} →
</Link>
) : (
<span className="muted">{label}: pontos születési idő kell hozzá</span>
)}
{uncertain && <span className="hint"> (a születési idő nélkül a szomszédos jegy is lehet)</span>}
</li>
);
})}
</ul>
</div>
);
}
/** The calculated chart: the wheel and the tables of the chart pages, without the AI parts. */
function ChartView({ result, birth }: { result: Result; birth: BirthData }) {
const r = result.chart;
const timeKnown = result.highlights.time_known;
const chart: Chart = {
id: "",
label: "Születési horoszkóp",
is_primary: false,
kind: "person",
editable_until: null,
birth_data: birth,
highlights: result.highlights,
chart: r,
created_at: "",
};
const place = r.location.place;
const country = place?.country_code ?? birth.country;
return (
<>
<div className="page-head calc-result-head">
<h2>A születési horoszkópod</h2>
<p className="muted">
{formatBirthDate(birth.date)}
{timeKnown
? `, ${r.time.local.slice(11, 16)} (UTC${r.time.utc_offset}${r.time.dst ? ", nyári idő" : ""})`
: ", ismeretlen időpont"}
{" · "}
{place?.name ?? "–"}
{country ? `, ${countryName(country)}` : ""}
</p>
</div>
<section className="chart-layout" aria-label="Képletrajz">
<div className="card chart-wheel-card">
<ChartWheel chart={r} timeKnown={timeKnown} />
<WheelLegend />
</div>
<div className="field chart-side">
<BigThree chart={chart} />
<SignLinks result={result} />
<div className="card calc-save">
<strong>A rövid összefoglalóhoz lépj be</strong>
<p className="muted" style={{ margin: 0 }}>
A képletedhez ingyen írunk egy rövid, személyre szabott összefoglalót, ehhez azonban be kell jelentkezned.
Belépés után a képleted is megmarad: a most megadott születési adataidat áthozzuk.
</p>
<Link href="/belepes?vissza=/profil" className="btn btn-primary">
Belépés és ingyenes összefoglaló
</Link>
</div>
</div>
</section>
<section className="card chart-tabs" aria-label="A képlet részletei">
<Tabs
label="A képlet részletei"
tabs={[
{ id: "bolygok", label: "Bolygók", content: <PositionTables chart={chart} /> },
{
id: "matrix",
label: "Mátrix",
content: (
<div className="field" style={{ gap: 16 }}>
<AspectGrid chart={chart} />
<ul className="grid-legend" aria-label="Jelmagyarázat">
{GRID_LEGEND.map((k) => (
<li key={k}>
<span className={`sym asp asp-${k}`} aria-hidden="true">
{ASPECTS[k]?.glyph}
</span>{" "}
{ASPECTS[k]?.hu}
</li>
))}
</ul>
</div>
),
},
{ id: "reszletek", label: "Fényszögek", content: <AspectList chart={chart} /> },
]}
/>
</section>
</>
);
}
/** The public birth chart: a calculation only, nothing is saved and no AI is used. */
export function PublicChart() {
const [year, setYear] = useState("");
const [month, setMonth] = useState("");
const [day, setDay] = useState("");
const [hour, setHour] = useState("");
const [minute, setMinute] = useState("");
const [timeUnknown, setTimeUnknown] = useState(false);
const [country, setCountry] = useState("HU");
const [place, setPlace] = useState<Place | null>(null);
const [ambiguous, setAmbiguous] = useState(false);
const [ambiguity, setAmbiguity] = useState<"earlier" | "later">("earlier");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<Saved | null>(null);
const [stored, setStored] = useState(false);
/** After a calculation (smooth) or on coming back (at once): show the drawn chart. */
const [reveal, setReveal] = useState<ScrollBehavior | null>(null);
const minuteRef = useRef<HTMLInputElement>(null);
const resultRef = useRef<HTMLDivElement>(null);
const today = useMemo(() => new Date().toISOString().slice(0, 10), []);
// Back on the page: the birth data typed earlier and, in this tab, the chart.
useEffect(() => {
let draft: BirthDraft | null = null;
let saved: Saved | null = null;
try {
draft = JSON.parse(sessionStorage.getItem(BIRTH_DRAFT_KEY) ?? "null");
saved = JSON.parse(sessionStorage.getItem(CHART_KEY) ?? "null");
} catch {
return;
}
if (draft && /^\d{4}-\d{2}-\d{2}$/.test(draft.date) && draft.geonames_id) {
setYear(draft.date.slice(0, 4));
setMonth(String(Number(draft.date.slice(5, 7))));
setDay(String(Number(draft.date.slice(8, 10))));
setHour(draft.time ? draft.time.slice(0, 2) : "");
setMinute(draft.time ? 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,
});
setStored(true);
}
if (saved?.result?.chart && saved.birth?.date) {
setResult(saved);
setStored(true);
setReveal("instant");
}
}, []);
// Scrolls to the drawn chart, once it is on the page. An old tab in the
// address (#bolygok) would pull the page down to the tables instead.
useEffect(() => {
if (!reveal || !result) return;
if (window.location.hash) history.replaceState(null, "", window.location.pathname + window.location.search);
resultRef.current?.scrollIntoView({ behavior: reveal, block: "start" });
setReveal(null);
}, [reveal, result]);
/** Forgets the birth data and the chart in this browser. */
function clear() {
try {
sessionStorage.removeItem(BIRTH_DRAFT_KEY);
sessionStorage.removeItem(CHART_KEY);
} catch {
// storage blocked
}
setYear("");
setMonth("");
setDay("");
setHour("");
setMinute("");
setTimeUnknown(false);
setCountry("HU");
setPlace(null);
setAmbiguous(false);
setResult(null);
setError(null);
setStored(false);
}
async function submit(e: React.FormEvent) {
e.preventDefault();
setError(null);
const date = composeDate(year, month, day);
const time = composeTime(hour, minute);
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 && !time)
return setError("Add meg a születési időt (óra 0–23, perc 0–59), 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 {
const birth = {
date,
...(timeUnknown ? {} : { time }),
country,
geonames_id: place.geonames_id,
};
const r = await api<Result>("/public/chart", {
body: { ...birth, ...(ambiguous ? { ambiguous_time: ambiguity } : {}) },
});
setResult({ result: r, birth });
// Kept in this browser only: for coming back to the page, and for the profile after sign-up.
const draft: BirthDraft = { ...birth, time: birth.time ?? null, placeName: place.name, region: place.region };
try {
sessionStorage.setItem(BIRTH_DRAFT_KEY, JSON.stringify(draft));
sessionStorage.setItem(CHART_KEY, JSON.stringify({ result: r, birth }));
setStored(true);
} catch {
// storage blocked or full: the chart is still shown
}
setReveal("smooth");
} 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.",
);
} else {
setError(err instanceof ApiError ? (ERRORS[err.code] ?? errorText(err)) : errorText(err));
}
} finally {
setBusy(false);
}
}
return (
<>
<form onSubmit={submit} className="card field calc-form" style={{ gap: 18 }} noValidate>
<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="calc-year">
Év
</label>
<input
id="calc-year"
className="inp birth-year"
inputMode="numeric"
placeholder="év"
maxLength={4}
value={year}
onChange={(e) => setYear(e.target.value.replace(/\D/g, ""))}
/>
<label className="sr-only" htmlFor="calc-month">
Hónap
</label>
<select
id="calc-month"
className="inp birth-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="calc-day">
Nap
</label>
<select id="calc-day" className="inp birth-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="calc-hour">
Óra
</label>
<input
id="calc-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);
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="calc-minute">
Perc
</label>
<input
id="calc-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}
geoBase="/api/v1/public/geo"
onChange={(c) => {
setCountry(c);
setPlace(null);
}}
/>
<PlaceSearch country={country} value={place} onChange={setPlace} geoBase="/api/v1/public/geo" />
</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="calc-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="calc-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" style={{ margin: 0 }}>
{error}
</p>
)}
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={busy}>
{busy ? "Számolás…" : "Elkészítem a horoszkópom"}
</button>
{stored && (
<button type="button" className="btn btn-ghost btn-sm" onClick={clear}>
Adatok törlése
</button>
)}
</div>
<p className="hint" style={{ margin: 0 }}>
Ingyenes, belépés nélkül. Az adataidat a szerveren nem tároljuk: csak ebben a böngészőlapban maradnak meg,
hogy oldalváltáskor ne vesszenek el, és a lap bezárásakor törlődnek.
</p>
</form>
{result && (
<section ref={resultRef} className="calc-result" aria-live="polite" aria-label="A születési horoszkópod">
<ChartView result={result.result} birth={result.birth} />
</section>
)}
</>
);
}