Chart page with a drawn wheel; reuse saved charts for identical birth data

- New /kepletek/[id] page: chart wheel (SVG), big three, elements,
  modalities, moon phase, positions and an aspects table. /keplet opens
  the user's own chart; the home page goes there after login.
- The profile only shows the birth data, with a link to the chart.
- Saving the same birth data again returns the stored chart (200)
  instead of calculating a new one.
- Charts without a birth time (angles null) render without houses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-16 06:37:59 +00:00
co-authored by Claude Opus 5.5
parent 1f177f859e
commit e789e5a981
15 changed files with 675 additions and 93 deletions
+38 -6
View File
@@ -106,22 +106,54 @@ pub struct CreateChart {
/// Calculates a chart from birth data; the `name` field is dropped so no
/// personal name reaches the calculation (or, later, the LLM).
pub async fn calculate(state: &AppState, birth: Value) -> Result<(Value, Value, String), ApiError> {
let Value::Object(mut birth) = birth else {
return Err(ApiError::BadRequest("birth must be an object".into()));
};
birth.remove("name");
let birth = Value::Object(birth);
let birth = clean_birth(birth)?;
let result = state.horoscope.natal(&birth).await?;
let hash = chart_hash(&result);
Ok((birth, result, hash))
}
fn clean_birth(birth: Value) -> Result<Value, ApiError> {
let Value::Object(mut birth) = birth else {
return Err(ApiError::BadRequest("birth must be an object".into()));
};
birth.remove("name");
Ok(Value::Object(birth))
}
/// Saves a new chart. If the user already has a chart with exactly the same
/// birth data, that one is returned (and made primary if asked) instead of
/// calculating it again.
pub async fn create(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<CreateChart>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let label = clean_label(&req.label)?;
let birth = clean_birth(req.birth)?;
let existing: Option<ChartRow> =
sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 AND birth_data = $2 LIMIT 1"))
.bind(auth.id())
.bind(&birth)
.fetch_optional(&state.db)
.await?;
if let Some(chart) = existing {
if req.is_primary && !chart.is_primary {
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary")
.bind(auth.id())
.execute(&mut *tx)
.await?;
let row: ChartRow = sqlx::query_as(&format!(
"UPDATE charts SET is_primary = true, updated_at = now() WHERE id = $1 RETURNING {CHART_COLUMNS}"
))
.bind(chart.id)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
return Ok((StatusCode::OK, Json(row.owner_view())));
}
return Ok((StatusCode::OK, Json(chart.owner_view())));
}
let (count,): (i64,) =
sqlx::query_as("SELECT count(*) FROM charts WHERE owner_id = $1").bind(auth.id()).fetch_one(&state.db).await?;
if count >= state.config.max_charts_per_user {
@@ -130,7 +162,7 @@ pub async fn create(
format!("at most {} charts can be saved", state.config.max_charts_per_user),
));
}
let (birth, result, hash) = calculate(&state, req.birth).await?;
let (birth, result, hash) = calculate(&state, birth).await?;
let mut tx = state.db.begin().await?;
if req.is_primary {
+19
View File
@@ -358,6 +358,25 @@ async fn charts_are_private(pool: PgPool) {
assert_eq!(list["charts"][0]["id"], other["id"]); // the new primary first
assert_eq!(list["charts"][1]["is_primary"], false);
// the same birth data again: the saved chart is reused, not calculated again
let r = app
.post(
"/v1/charts",
Some(&anna),
json!({"label": "Újra", "is_primary": true,
"birth": {"date": "1990-03-15", "time": "14:30", "country": "HU", "place": "Szeged"}}),
)
.await;
assert_eq!((r.status, r.body["id"].as_str(), &r.body["is_primary"]), (StatusCode::OK, Some(id), &json!(true)));
assert_eq!(app.get("/v1/charts", Some(&anna)).await.body["charts"].as_array().unwrap().len(), 2);
app.call(
"PATCH",
&format!("/v1/charts/{}", other["id"].as_str().unwrap()),
Some(&anna),
Some(json!({"is_primary": true})),
)
.await;
assert_eq!(app.get(&format!("/v1/charts/{id}"), Some(&bela)).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.call("DELETE", &format!("/v1/charts/{id}"), Some(&bela), None).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/charts/not-a-uuid", Some(&anna)).await.status, StatusCode::BAD_REQUEST);
+1 -1
View File
@@ -13,7 +13,7 @@ export const metadata: Metadata = { title: "Belépés" };
/** Only local paths, so the login cannot redirect to another site. */
function safeTarget(value: string | string[] | undefined): string {
const v = Array.isArray(value) ? value[0] : value;
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/profil";
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/";
}
async function loadConfig(): Promise<PublicConfig | null> {
+49 -1
View File
@@ -13,6 +13,8 @@
--gold-ink: #141a2c;
--danger: #f2a0a0;
--ok: #9fd8b0;
--harmonic: #7fb0e0;
--tense: #e38b8b;
--radius: 10px;
--font-display: var(--font-cormorant), "Cormorant Garamond", Georgia, serif;
--font-body: var(--font-inter), Inter, system-ui, sans-serif;
@@ -145,6 +147,51 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.tagline { font-family: var(--font-display); font-size: 36px; font-weight: 600; line-height: 1.1; }
.gsi-slot { min-height: 44px; display: flex; justify-content: center; }
/* Chart page */
.chart-layout { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, 1fr); gap: 24px; align-items: start; }
.chart-wheel-card { padding: 16px; gap: 10px; }
.chart-wheel { width: 100%; height: auto; display: block; max-width: 680px; margin: 0 auto; }
.chart-layout .big3 { grid-template-columns: 1fr; }
.wheel-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; justify-content: center; }
.legend-line { display: inline-block; width: 22px; height: 2px; border-radius: 1px; margin-left: 6px; }
.legend-harmonic { background: var(--harmonic); }
.legend-tense { background: var(--tense); }
.aspect-tag { white-space: nowrap; }
.aspect-harmonic { color: var(--harmonic); }
.aspect-tense { color: var(--tense); }
.aspect-neutral { color: var(--gold); }
.w-ring { fill: none; stroke: var(--line-2); stroke-width: 1.2; }
.w-faint { stroke: var(--line); }
.w-inner { fill: var(--panel-2); }
.w-sign { stroke: var(--line-2); stroke-width: 1; }
.w-fire { fill: rgba(227, 139, 106, 0.09); }
.w-earth { fill: rgba(159, 216, 176, 0.07); }
.w-air { fill: rgba(217, 180, 106, 0.08); }
.w-water { fill: rgba(127, 176, 224, 0.09); }
.w-sign-glyph { fill: var(--gold); font-family: var(--font-symbols); font-size: 22px; }
.w-tick { stroke: var(--line-2); stroke-width: 1; }
.w-cusp { stroke: var(--line-2); stroke-width: 1; }
.w-axis { stroke: var(--gold); stroke-width: 1.8; }
.w-axis-label { fill: var(--gold); font: 600 14px var(--font-body); letter-spacing: 0.5px; }
.w-house-num { fill: var(--muted); font: 500 12px var(--font-body); }
.w-aspect { stroke-linecap: round; }
.w-harmonic { stroke: var(--harmonic); }
.w-tense { stroke: var(--tense); }
.w-neutral { stroke: var(--gold); }
.w-point-tick { stroke: var(--ink); stroke-width: 1.6; }
.w-leader { stroke: var(--muted); stroke-width: 0.7; stroke-opacity: 0.6; }
.w-point-glyph { fill: var(--ink); font-family: var(--font-symbols); font-size: 22px; }
.w-point-deg { fill: var(--muted); font: 500 10.5px var(--font-body); }
.w-end { fill: var(--ink-2); }
.w-point-glyph, .w-point-deg, .w-house-num, .w-axis-label { paint-order: stroke; stroke: var(--panel); stroke-width: 4px; stroke-linejoin: round; }
.w-point:hover .w-point-glyph { fill: var(--gold); }
@media (max-width: 900px) {
.chart-layout { grid-template-columns: 1fr; }
.chart-layout .big3 { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 640px) {
h1 { font-size: 32px; }
.site-header { padding: 10px 16px; gap: 12px; }
@@ -152,7 +199,8 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.card { padding: 18px; }
.auth-aside { padding: 28px 20px; min-height: 0; }
.wheel { width: 60%; }
.big3 { grid-template-columns: 1fr; }
.big3, .chart-layout .big3 { grid-template-columns: 1fr; }
.chart-wheel-card { padding: 8px; }
}
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@@ -0,0 +1,9 @@
import { redirect } from "next/navigation";
import { requireMe } from "@/lib/server";
// The user's own chart; without birth data the profile asks for it.
export default async function MyChart() {
const me = await requireMe("/keplet");
redirect(me.primary_chart_id ? `/kepletek/${me.primary_chart_id}` : "/profil#birth");
}
@@ -0,0 +1,113 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { BigThree, ChartTables } from "@/components/ChartTables";
import { ChartWheel } from "@/components/ChartWheel";
import { ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
import { backendGet, requireMe } from "@/lib/server";
import type { Chart } from "@/lib/types";
export const metadata: Metadata = { title: "Képlet" };
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** One saved chart: the wheel and the tables, read from the database (not recalculated). */
export default async function ChartPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
await requireMe(`/kepletek/${id}`);
if (!UUID.test(id)) notFound();
const chart = await backendGet<Chart>(`/v1/charts/${id}`);
if (!chart) notFound();
const result = chart.chart;
const timeKnown = chart.highlights.time_known;
const place = result.location.place;
const country = place?.country_code ?? chart.birth_data.country;
const elements = result.summary?.elements;
const modalities = result.summary?.modalities;
const phase = result.moon_phase;
return (
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<h1>{chart.is_primary ? "Születési képletem" : chart.label}</h1>
<p className="muted">
{formatBirthDate(chart.birth_data.date)}
{timeKnown ? `, ${result.time.local.slice(11, 16)} (UTC${result.time.utc_offset}${result.time.dst ? ", nyári idő" : ""})` : ", ismeretlen időpont"}
{" · "}
{place?.name ?? chart.birth_data.place ?? "–"}
{country ? `, ${countryName(country)}` : ""}
{chart.is_primary && (
<>
{" · "}
<Link href="/profil#birth">adatok javítása</Link>
</>
)}
</p>
</div>
<section className="chart-layout" aria-label="Képletrajz">
<div className="card chart-wheel-card">
<ChartWheel chart={result} timeKnown={timeKnown} />
<p className="hint wheel-legend">
<span className="legend-line legend-harmonic" aria-hidden="true" /> harmonikus (trigon, szextil)
<span className="legend-line legend-tense" aria-hidden="true" /> feszült (kvadrát, szembenállás)
</p>
</div>
<div className="field" style={{ gap: 16 }}>
<BigThree chart={chart} />
{(elements || modalities || phase) && (
<div className="card" style={{ gap: 12 }}>
<dl className="facts">
{elements && (
<>
<dt>Elemek</dt>
<dd>
{Object.entries(elements)
.map(([k, v]) => `${ELEMENTS[k] ?? k} ${v.count}`)
.join(" · ")}
</dd>
</>
)}
{modalities && (
<>
<dt>Minőségek</dt>
<dd>
{Object.entries(modalities)
.map(([k, v]) => `${MODALITIES[k] ?? k} ${v.count}`)
.join(" · ")}
</dd>
</>
)}
{phase && (
<>
<dt>Holdfázis</dt>
<dd>
{MOON_PHASES[phase.phase] ?? phase.phase}, {Math.round(phase.illumination * 100)}%
</dd>
</>
)}
</dl>
{elements && (
<p className="hint">
Az elemek és minőségek a tíz bolygóból számolva:{" "}
{Object.entries(elements)
.filter(([, v]) => v.count > 0)
.map(([k, v]) => `${ELEMENTS[k] ?? k}: ${v.points.map(pointName).join(", ")}`)
.join("; ")}
.
</p>
)}
</div>
)}
</div>
</section>
<section className="card" aria-labelledby="positions">
<h2 id="positions">Pozíciók</h2>
<ChartTables chart={chart} />
</section>
</main>
);
}
+4 -2
View File
@@ -2,7 +2,9 @@ import { redirect } from "next/navigation";
import { getMe } from "@/lib/server";
// No home page yet: logged-in users go to their profile, others to login.
// No home page yet: logged-in users go to their chart (or to the profile to enter
// their birth data), others to login.
export default async function Home() {
redirect((await getMe()) ? "/profil" : "/belepes");
const me = await getMe();
redirect(!me ? "/belepes" : me.primary_chart_id ? "/keplet" : "/profil");
}
@@ -1,5 +1,7 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { countryName, formatBirthDate } from "@/lib/astro";
@@ -17,8 +19,9 @@ export interface SavedBirth {
dst: boolean;
}
/** Shows the saved birth data (and the chart tables), or the form to enter or correct it. */
export function BirthEditor({ chart, children }: { chart: SavedBirth | null; children: React.ReactNode }) {
/** Shows the saved birth data, or the form to enter or correct it. Saving opens the chart page. */
export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; chartId: string | null }) {
const router = useRouter();
const [editing, setEditing] = useState(chart === null);
if (editing || !chart) {
@@ -38,7 +41,7 @@ export function BirthEditor({ chart, children }: { chart: SavedBirth | null; chi
<BirthForm
initial={chart ? { ...chart.birth, placeName: chart.placeName, region: chart.region } : null}
onCancel={chart ? () => setEditing(false) : undefined}
onSaved={() => setEditing(false)}
onSaved={(id) => router.push(`/kepletek/${id}`)}
/>
</div>
);
@@ -47,7 +50,7 @@ export function BirthEditor({ chart, children }: { chart: SavedBirth | null; chi
const { birth } = chart;
const country = chart.countryCode ?? birth.country;
return (
<div className="field" style={{ gap: 24 }}>
<div className="field">
<div className="card-head" style={{ alignItems: "flex-start" }}>
<dl className="facts">
<dt>Dátum</dt>
@@ -73,11 +76,17 @@ export function BirthEditor({ chart, children }: { chart: SavedBirth | null; chi
{country && <span className="muted">, {countryName(country)}</span>}
</dd>
</dl>
<button type="button" className="btn" onClick={() => setEditing(true)}>
Adatok javítása
</button>
<div className="row">
{chartId && (
<Link href={`/kepletek/${chartId}`} className="btn btn-primary">
Képlet megnyitása
</Link>
)}
<button type="button" className="btn" onClick={() => setEditing(true)}>
Adatok javítása
</button>
</div>
</div>
{children}
</div>
);
}
@@ -1,6 +1,5 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { ApiError, api, errorText } from "@/lib/api";
@@ -24,9 +23,8 @@ export function BirthForm({
}: {
initial: Initial;
onCancel?: () => void;
onSaved: () => void;
onSaved: (chartId: string) => 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);
@@ -56,7 +54,7 @@ export function BirthForm({
if (!place) return setError("Válaszd ki a születési helyet a listából.");
setBusy(true);
try {
await api("/charts", {
const saved = await api<{ id: string }>("/charts", {
body: {
label: "Saját képlet",
is_primary: true,
@@ -69,8 +67,7 @@ export function BirthForm({
},
},
});
onSaved();
router.refresh();
onSaved(saved.id);
} catch (err) {
if (err instanceof ApiError && err.code === "ambiguous_local_time") {
setAmbiguous(true);
+3 -5
View File
@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { ChartTables } from "@/components/ChartTables";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
import { backendGet, requireMe } from "@/lib/server";
import type { Chart } from "@/lib/types";
@@ -21,7 +20,7 @@ export default async function ProfilePage() {
<main className="page">
<div className="page-head">
<h1>Profil</h1>
<p className="muted">A fiókod adatai és a saját születési képleted.</p>
<p className="muted">A fiókod és a születési adataid.</p>
</div>
<section className="card" aria-labelledby="account">
@@ -71,9 +70,8 @@ export default async function ProfilePage() {
}
: null
}
>
{chart && <ChartTables chart={chart} />}
</BirthEditor>
chartId={chart?.id ?? null}
/>
</section>
</main>
);
@@ -1,4 +1,4 @@
import { ANGLES, POINTS, SIGNS, dms, signName } from "@/lib/astro";
import { ANGLES, ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
import type { Chart, Position } from "@/lib/types";
function Pos({ p }: { p: Position }) {
@@ -9,45 +9,55 @@ function Pos({ p }: { p: Position }) {
);
}
/** The big three and the positions of a natal chart. */
/** Sun, Moon and Ascendant signs. */
export function BigThree({ chart }: { chart: Chart }) {
const result = chart.chart;
const timeKnown = chart.highlights.time_known;
const sun = result.points.find((p) => p.id === "sun");
const moon = result.points.find((p) => p.id === "moon");
const asc = result.angles?.ascendant;
return (
<div className="big3">
<div>
<span className="muted">Nap</span>
<span className="glyph sym">{SIGNS[chart.highlights.sun ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.sun)}</strong>
{sun && <span className="muted num">{dms(sun.degree_in_sign_dms)}</span>}
</div>
<div>
<span className="muted">Hold{!timeKnown && " (közelítő)"}</span>
<span className="glyph sym">{SIGNS[chart.highlights.moon ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.moon)}</strong>
{moon && <span className="muted num">{dms(moon.degree_in_sign_dms)}</span>}
</div>
<div>
<span className="muted">Aszcendens</span>
{timeKnown ? (
<>
<span className="glyph sym">{SIGNS[chart.highlights.ascendant ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.ascendant)}</strong>
{typeof asc === "object" && asc && <span className="muted num">{dms(asc.degree_in_sign_dms)}</span>}
</>
) : (
<strong className="muted">–</strong>
)}
</div>
</div>
);
}
/** Positions, angles, house cusps and aspects of a natal chart. */
export function ChartTables({ chart }: { chart: Chart }) {
const result = chart.chart;
const timeKnown = chart.highlights.time_known;
const angles = ANGLES.map(([key, label]) => [label, result.angles[key]] as const).filter(
const angles = ANGLES.map(([key, label]) => [label, result.angles?.[key]] as const).filter(
(a): a is readonly [string, Position] => typeof a[1] === "object" && a[1] !== null,
);
const fortune = result.lots?.fortune;
const sun = result.points.find((p) => p.id === "sun");
const moon = result.points.find((p) => p.id === "moon");
const aspects = [...(result.aspects ?? [])].sort((a, b) => a.orb - b.orb);
return (
<div className="field" style={{ gap: 24 }}>
<div className="big3">
<div>
<span className="muted">Nap</span>
<span className="glyph sym">{SIGNS[chart.highlights.sun ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.sun)}</strong>
{sun && <span className="muted num">{dms(sun.degree_in_sign_dms)}</span>}
</div>
<div>
<span className="muted">Hold{!timeKnown && " (közelítő)"}</span>
<span className="glyph sym">{SIGNS[chart.highlights.moon ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.moon)}</strong>
{moon && <span className="muted num">{dms(moon.degree_in_sign_dms)}</span>}
</div>
<div>
<span className="muted">Aszcendens</span>
{timeKnown ? (
<>
<span className="glyph sym">{SIGNS[chart.highlights.ascendant ?? ""]?.glyph}</span>
<strong>{signName(chart.highlights.ascendant)}</strong>
</>
) : (
<strong className="muted">–</strong>
)}
</div>
</div>
<div className="grid-2" style={{ alignItems: "start" }}>
<div className="table-wrap">
<h3 style={{ marginBottom: 8 }}>Bolygók és pontok</h3>
@@ -129,6 +139,51 @@ export function ChartTables({ chart }: { chart: Chart }) {
</div>
)}
</div>
{aspects.length > 0 && (
<div className="table-wrap">
<h3 style={{ marginBottom: 8 }}>Fényszögek</h3>
<table>
<thead>
<tr>
<th scope="col">Fényszög</th>
<th scope="col">Orbisz</th>
<th scope="col">
<span className="sr-only">Közeledő vagy távolodó</span>
</th>
</tr>
</thead>
<tbody>
{aspects.map((a) => {
const info = ASPECTS[a.aspect];
return (
<tr key={`${a.point1}-${a.point2}-${a.aspect}`}>
<td>
<span className="sym" aria-hidden="true">
{POINTS[a.point1]?.glyph}
</span>{" "}
{pointName(a.point1)}{" "}
<span className={`aspect-tag aspect-${info?.kind ?? "neutral"}`}>
<span className="sym" aria-hidden="true">
{info?.glyph}
</span>{" "}
{info?.hu ?? a.aspect}
</span>{" "}
<span className="sym" aria-hidden="true">
{POINTS[a.point2]?.glyph}
</span>{" "}
{pointName(a.point2)}
</td>
<td className="num">{orbText(a.orb)}</td>
<td className="muted" style={{ fontSize: 13 }}>
{a.applying === true ? "közeledő" : a.applying === false ? "távolodó" : ""}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{!timeKnown && (
<p className="hint">
Születési idő nélkül a házak, a tengelyek és az Aszcendens nem számolhatók; a Hold helyzete a nap folyamán akár
@@ -0,0 +1,240 @@
import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
import type { ChartResult, Position } from "@/lib/types";
// Radii of the rings (viewBox is SIZE × SIZE, centre C).
const SIZE = 680;
const C = SIZE / 2;
const R_LABEL = 322; // ASC / MC labels
const R_OUT = 300; // outer edge of the zodiac ring
const R_ZOD = 254; // inner edge of the zodiac ring
const R_GLYPH = 222; // planet glyphs
const R_DEG = 188; // planet degrees
const R_HOUSE = 172; // outer edge of the house-number ring
const R_INNER = 146; // aspect circle
// Points drawn on the wheel; the asteroids and the south node are only in the tables.
const WHEEL_POINTS = [
"sun",
"moon",
"mercury",
"venus",
"mars",
"jupiter",
"saturn",
"uranus",
"neptune",
"pluto",
"north_node",
"lilith",
"chiron",
];
const SIGN_ORDER = Object.keys(SIGNS);
const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
const ANGLE_LABELS: [string, string][] = [
["ascendant", "ASC"],
["midheaven", "MC"],
["descendant", "DSC"],
["imum_coeli", "IC"],
];
/** Screen point of an ecliptic longitude: the ascendant (or 0° Aries) is on the left. */
function xy(lon: number, r: number, start: number): [number, number] {
const a = ((180 + lon - start) * Math.PI) / 180;
return [C + r * Math.cos(a), C - r * Math.sin(a)];
}
const f = (n: number) => n.toFixed(2);
/** Pushes glyphs apart so that neighbours are at least `min` degrees from each other. */
function spread(lons: number[], min: number): number[] {
const n = lons.length;
const order = lons.map((_, i) => i).sort((a, b) => lons[a] - lons[b]);
const pos = order.map((i) => lons[i]);
for (let iter = 0; iter < 200 && n > 1; iter++) {
let moved = false;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
const gap = pos[j] - pos[i] + (j === 0 ? 360 : 0);
if (gap < min - 0.01) {
const d = (min - gap) / 2;
pos[i] -= d;
pos[j] += d;
moved = true;
}
}
if (!moved) break;
}
const out = new Array<number>(n);
order.forEach((orig, k) => (out[orig] = pos[k]));
return out;
}
function arcPath(r1: number, r2: number, from: number, to: number, start: number): string {
const [x1, y1] = xy(from, r2, start);
const [x2, y2] = xy(to, r2, start);
const [x3, y3] = xy(to, r1, start);
const [x4, y4] = xy(from, r1, start);
// Increasing longitude runs counter-clockwise on screen (sweep flag 0).
return `M${f(x1)} ${f(y1)} A${r2} ${r2} 0 0 0 ${f(x2)} ${f(y2)} L${f(x3)} ${f(y3)} A${r1} ${r1} 0 0 1 ${f(x4)} ${f(y4)} Z`;
}
/** The natal chart as a wheel: zodiac, houses, planets and aspect lines. */
export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown: boolean }) {
const angle = (key: string): Position | null => {
const a = chart.angles?.[key];
return typeof a === "object" && a !== null ? a : null;
};
const asc = timeKnown ? angle("ascendant") : null;
const start = asc?.longitude ?? 0;
const cusps = timeKnown ? (chart.houses?.cusps ?? []) : [];
const points = WHEEL_POINTS.map((id) => chart.points.find((p) => p.id === id)).filter((p) => p !== undefined);
const placed = spread(
points.map((p) => p.longitude),
9,
);
// Longitudes for the aspect line ends (planets and, with a known time, the angles).
const ends = new Map<string, number>(points.map((p) => [p.id, p.longitude]));
if (timeKnown) {
for (const [key] of ANGLE_LABELS) {
const a = angle(key);
if (a) ends.set(key, a.longitude);
}
}
const aspects = (chart.aspects ?? []).filter(
(a) => a.aspect !== "conjunction" && ends.has(a.point1) && ends.has(a.point2),
);
const description = points
.map((p) => `${pointName(p.id)} ${signName(p.sign)} ${dms(p.degree_in_sign_dms)}`)
.join(", ");
return (
<svg
className="chart-wheel"
viewBox={`0 0 ${SIZE} ${SIZE}`}
role="img"
aria-labelledby="wheel-title wheel-desc"
>
<title id="wheel-title">Születési képlet</title>
<desc id="wheel-desc">
{timeKnown && asc ? `Aszcendens ${signName(asc.sign)}. ` : "Születési idő nélkül, házak nélkül. "}
{description}
</desc>
{/* Zodiac ring */}
<circle cx={C} cy={C} r={R_OUT} className="w-ring" />
{SIGN_ORDER.map((sign, i) => {
const [gx, gy] = xy(i * 30 + 15, (R_OUT + R_ZOD) / 2, start);
return (
<g key={sign}>
<path d={arcPath(R_ZOD, R_OUT, i * 30, i * 30 + 30, start)} className={`w-sign w-${SIGN_ELEMENT[i % 4]}`} />
<text x={f(gx)} y={f(gy)} className="w-sign-glyph" dominantBaseline="central" textAnchor="middle">
<title>{SIGNS[sign].hu}</title>
{SIGNS[sign].glyph}
</text>
</g>
);
})}
{Array.from({ length: 360 }, (_, d) => {
const len = d % 10 === 0 ? 9 : d % 5 === 0 ? 6 : 3;
const [x1, y1] = xy(d, R_ZOD, start);
const [x2, y2] = xy(d, R_ZOD + len, start);
return <line key={d} x1={f(x1)} y1={f(y1)} x2={f(x2)} y2={f(y2)} className="w-tick" />;
})}
<circle cx={C} cy={C} r={R_ZOD} className="w-ring" />
{/* Houses */}
{cusps.length === 12 && (
<g>
<circle cx={C} cy={C} r={R_HOUSE} className="w-ring w-faint" />
{cusps.map((c, i) => {
const isAngle = i % 3 === 0;
const [x1, y1] = xy(c.longitude, R_INNER, start);
const [x2, y2] = xy(c.longitude, isAngle ? R_OUT : R_ZOD, start);
const next = cusps[(i + 1) % 12].longitude;
const mid = c.longitude + (((next - c.longitude + 360) % 360) / 2);
const [nx, ny] = xy(mid, (R_HOUSE + R_INNER) / 2, start);
return (
<g key={c.house}>
<line x1={f(x1)} y1={f(y1)} x2={f(x2)} y2={f(y2)} className={isAngle ? "w-axis" : "w-cusp"} />
<text x={f(nx)} y={f(ny)} className="w-house-num" dominantBaseline="central" textAnchor="middle">
{c.house}
</text>
</g>
);
})}
{ANGLE_LABELS.map(([key, label]) => {
const a = angle(key);
if (!a) return null;
const [x, y] = xy(a.longitude, R_LABEL, start);
return (
<text key={key} x={f(x)} y={f(y)} className="w-axis-label" dominantBaseline="central" textAnchor="middle">
<title>
{pointName(key)}: {dms(a.degree_in_sign_dms)} {signName(a.sign)}
</title>
{label}
</text>
);
})}
</g>
)}
{/* Aspects */}
<circle cx={C} cy={C} r={R_INNER} className="w-ring w-inner" />
{aspects.map((a) => {
const [x1, y1] = xy(ends.get(a.point1)!, R_INNER, start);
const [x2, y2] = xy(ends.get(a.point2)!, R_INNER, start);
const kind = ASPECTS[a.aspect]?.kind ?? "neutral";
const strength = a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5;
return (
<line
key={`${a.point1}-${a.point2}-${a.aspect}`}
x1={f(x1)}
y1={f(y1)}
x2={f(x2)}
y2={f(y2)}
className={`w-aspect w-${kind}`}
strokeOpacity={(0.3 + 0.7 * strength).toFixed(2)}
strokeWidth={(0.8 + 1.4 * strength).toFixed(2)}
>
<title>
{pointName(a.point1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {pointName(a.point2)} (orbis{" "}
{orbText(a.orb)})
</title>
</line>
);
})}
{/* Planets */}
{points.map((p, i) => {
const [t1x, t1y] = xy(p.longitude, R_ZOD, start);
const [t2x, t2y] = xy(p.longitude, R_ZOD - 8, start);
const [lx, ly] = xy(placed[i], R_GLYPH + 14, start);
const [gx, gy] = xy(placed[i], R_GLYPH, start);
const [dx, dy] = xy(placed[i], R_DEG, start);
const [ex, ey] = xy(p.longitude, R_INNER, start);
const deg = Number.parseInt(p.degree_in_sign_dms, 10);
return (
<g key={p.id} className="w-point">
<title>
{pointName(p.id)}: {dms(p.degree_in_sign_dms)} {signName(p.sign)}
{p.retrograde ? ", retrográd" : ""}
{timeKnown && p.house ? `, ${p.house}. ház` : ""}
</title>
<line x1={f(t1x)} y1={f(t1y)} x2={f(t2x)} y2={f(t2y)} className="w-point-tick" />
<line x1={f(t2x)} y1={f(t2y)} x2={f(lx)} y2={f(ly)} className="w-leader" />
<text x={f(gx)} y={f(gy)} className="w-point-glyph" dominantBaseline="central" textAnchor="middle">
{POINTS[p.id]?.glyph ?? p.id}
</text>
<text x={f(dx)} y={f(dy)} className="w-point-deg" dominantBaseline="central" textAnchor="middle">
{deg}°{p.retrograde ? "℞" : ""}
</text>
<circle cx={f(ex)} cy={f(ey)} r={2.2} className="w-end" />
</g>
);
})}
</svg>
);
}
@@ -14,7 +14,10 @@ export function Logo() {
}
export function SiteHeader({ me }: { me: Me }) {
const links = [{ href: "/profil", label: "Profil" }];
const links = [
{ href: "/keplet", label: "Képletem" },
{ href: "/profil", label: "Profil" },
];
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
return (
<header className="site-header">
+72 -31
View File
@@ -1,39 +1,40 @@
// Hungarian names and glyphs for the chart tables.
// Hungarian names and glyphs for the chart pages.
// Glyphs end in U+FE0E so phones show them as text, not as emoji.
export const SIGNS: Record<string, { hu: string; glyph: string }> = {
aries: { hu: "Kos", glyph: "♈" },
taurus: { hu: "Bika", glyph: "♉" },
gemini: { hu: "Ikrek", glyph: "♊" },
cancer: { hu: "Rák", glyph: "♋" },
leo: { hu: "Oroszlán", glyph: "♌" },
virgo: { hu: "Szűz", glyph: "♍" },
libra: { hu: "Mérleg", glyph: "♎" },
scorpio: { hu: "Skorpió", glyph: "♏" },
sagittarius: { hu: "Nyilas", glyph: "♐" },
capricorn: { hu: "Bak", glyph: "♑" },
aquarius: { hu: "Vízöntő", glyph: "♒" },
pisces: { hu: "Halak", glyph: "♓" },
aries: { hu: "Kos", glyph: "♈\uFE0E" },
taurus: { hu: "Bika", glyph: "♉\uFE0E" },
gemini: { hu: "Ikrek", glyph: "♊\uFE0E" },
cancer: { hu: "Rák", glyph: "♋\uFE0E" },
leo: { hu: "Oroszlán", glyph: "♌\uFE0E" },
virgo: { hu: "Szűz", glyph: "♍\uFE0E" },
libra: { hu: "Mérleg", glyph: "♎\uFE0E" },
scorpio: { hu: "Skorpió", glyph: "♏\uFE0E" },
sagittarius: { hu: "Nyilas", glyph: "♐\uFE0E" },
capricorn: { hu: "Bak", glyph: "♑\uFE0E" },
aquarius: { hu: "Vízöntő", glyph: "♒\uFE0E" },
pisces: { hu: "Halak", glyph: "♓\uFE0E" },
};
export const POINTS: Record<string, { hu: string; glyph: string }> = {
sun: { hu: "Nap", glyph: "☉" },
moon: { hu: "Hold", glyph: "☽" },
mercury: { hu: "Merkúr", glyph: "☿" },
venus: { hu: "Vénusz", glyph: "♀" },
mars: { hu: "Mars", glyph: "♂" },
jupiter: { hu: "Jupiter", glyph: "♃" },
saturn: { hu: "Szaturnusz", glyph: "♄" },
uranus: { hu: "Uránusz", glyph: "♅" },
neptune: { hu: "Neptunusz", glyph: "♆" },
pluto: { hu: "Plútó", glyph: "♇" },
north_node: { hu: "Észak-Holdcsomópont", glyph: "☊" },
south_node: { hu: "Dél-Holdcsomópont", glyph: "☋" },
lilith: { hu: "Lilith", glyph: "⚸" },
chiron: { hu: "Kiron", glyph: "⚷" },
ceres: { hu: "Ceres", glyph: "⚳" },
pallas: { hu: "Pallas", glyph: "⚴" },
juno: { hu: "Juno", glyph: "⚵" },
vesta: { hu: "Vesta", glyph: "⚶" },
sun: { hu: "Nap", glyph: "☉\uFE0E" },
moon: { hu: "Hold", glyph: "☽\uFE0E" },
mercury: { hu: "Merkúr", glyph: "☿\uFE0E" },
venus: { hu: "Vénusz", glyph: "♀\uFE0E" },
mars: { hu: "Mars", glyph: "♂\uFE0E" },
jupiter: { hu: "Jupiter", glyph: "♃\uFE0E" },
saturn: { hu: "Szaturnusz", glyph: "♄\uFE0E" },
uranus: { hu: "Uránusz", glyph: "♅\uFE0E" },
neptune: { hu: "Neptunusz", glyph: "♆\uFE0E" },
pluto: { hu: "Plútó", glyph: "♇\uFE0E" },
north_node: { hu: "Észak-Holdcsomópont", glyph: "☊\uFE0E" },
south_node: { hu: "Dél-Holdcsomópont", glyph: "☋\uFE0E" },
lilith: { hu: "Lilith", glyph: "⚸\uFE0E" },
chiron: { hu: "Kiron", glyph: "⚷\uFE0E" },
ceres: { hu: "Ceres", glyph: "⚳\uFE0E" },
pallas: { hu: "Pallas", glyph: "⚴\uFE0E" },
juno: { hu: "Juno", glyph: "⚵\uFE0E" },
vesta: { hu: "Vesta", glyph: "⚶\uFE0E" },
};
export const ANGLES: [string, string][] = [
@@ -90,3 +91,43 @@ export function formatBirthDate(date: string): string {
new Date(Date.UTC(y, m - 1, d)),
);
}
export const ASPECTS: Record<string, { hu: string; glyph: string; kind: "harmonic" | "tense" | "neutral" }> = {
conjunction: { hu: "együttállás", glyph: "☌", kind: "neutral" },
opposition: { hu: "szembenállás", glyph: "☍", kind: "tense" },
trine: { hu: "trigon", glyph: "△", kind: "harmonic" },
square: { hu: "kvadrát", glyph: "□", kind: "tense" },
sextile: { hu: "szextil", glyph: "⚹", kind: "harmonic" },
quincunx: { hu: "kvinkunx", glyph: "⚻", kind: "tense" },
semisextile: { hu: "félszextil", glyph: "⚺", kind: "harmonic" },
semisquare: { hu: "félkvadrát", glyph: "∠", kind: "tense" },
sesquiquadrate: { hu: "másfélkvadrát", glyph: "⚼", kind: "tense" },
quintile: { hu: "kvintil", glyph: "Q", kind: "harmonic" },
biquintile: { hu: "bikvintil", glyph: "bQ", kind: "harmonic" },
};
export const ELEMENTS: Record<string, string> = { fire: "Tűz", earth: "Föld", air: "Levegő", water: "Víz" };
export const MODALITIES: Record<string, string> = { cardinal: "Kardinális", fixed: "Fix", mutable: "Változó" };
export const MOON_PHASES: Record<string, string> = {
new_moon: "Újhold",
waxing_crescent: "Növő holdsarló",
first_quarter: "Első negyed",
waxing_gibbous: "Növő hold",
full_moon: "Telihold",
waning_gibbous: "Fogyó hold",
last_quarter: "Utolsó negyed",
waning_crescent: "Fogyó holdsarló",
};
/** Name of a point or angle for labels (`midheaven` → `MC`). */
export function pointName(id: string): string {
return POINTS[id]?.hu ?? ANGLES.find(([k]) => k === id)?.[1] ?? id;
}
/** Orb in degrees and minutes: `2.25` → `2°15′`. */
export function orbText(orb: number): string {
const d = Math.floor(orb);
const m = Math.round((orb - d) * 60);
return m === 60 ? `${d + 1}°00′` : `${d}°${String(m).padStart(2, "0")}′`;
}
+17 -1
View File
@@ -29,6 +29,7 @@ export interface PublicConfig {
}
export interface Position {
longitude: number;
sign: string;
degree_in_sign_dms: string;
house?: number | null;
@@ -37,13 +38,28 @@ export interface Position {
export interface ChartPoint extends Position {
id: string;
kind?: string;
}
export interface Aspect {
point1: string;
point2: string;
aspect: string;
orb: number;
max_orb: number;
applying?: boolean | null;
}
type Groups = Record<string, { count: number; points: string[] }>;
export interface ChartResult {
points: ChartPoint[];
angles: Record<string, Position | number>;
angles: Record<string, Position | number> | null;
houses?: { cusps: (Position & { house: number })[] } | null;
lots?: Record<string, Position> | null;
aspects?: Aspect[];
summary?: { elements?: Groups; modalities?: Groups } | null;
moon_phase?: { phase: string; illumination: number; waxing: boolean } | null;
time: { time_known: boolean; local: string; zone: string; utc_offset: string; dst: boolean };
location: { place?: { name: string; region?: string | null; country_code: string } | null; latitude: number; longitude: number };
}