Släktträd och tidslinje

Relationer får ett släktband (förälder, partner, syskon) och en period.
Nytt släktträd som ritas av släktbanden, och en tidslinje som samlar
födelse och död, scenarier, egna händelser och relationsperioder med
ålder vid varje tillfälle. Datum skrivs som ÅÅÅÅ, ÅÅÅÅ-MM eller
ÅÅÅÅ-MM-DD. Följer med i export, import och papperskorg. Migreringen
0006 ger gamla relationer som "Förälder till" rätt släktband.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 23:54:27 +01:00
1 parent dcb5d43429
commit bd269d70a5
32 files changed
+2285 -25

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
"use server";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { optStr, revalidateBook, str } from "@/lib/form";
import { requireBook } from "@/lib/session";
import { compareStoryDates, normalizeStoryDate } from "@/lib/story-date";
/** Titel, datum och deltagare ur formuläret. error är satt om datumet är ogiltigt. */
async function readEvent(bookId: string, formData: FormData) {
const title = str(formData, "title", 200);
const date = normalizeStoryDate(str(formData, "date", 20));
const endRaw = str(formData, "endDate", 20);
const endDate = endRaw ? normalizeStoryDate(endRaw) : null;
const badDate = !date || (endRaw !== "" && !endDate);
const wanted = [...new Set(formData.getAll("participantIds").map(String))].filter(Boolean);
const found = wanted.length > 0 ? await prisma.entity.findMany({ where: { bookId, id: { in: wanted } }, select: { id: true } }) : [];
return {
title,
date: date ?? "",
// Ett slutdatum före startdatumet ignoreras
endDate: endDate && date && compareStoryDates(endDate, date) >= 0 ? endDate : null,
description: optStr(formData, "description", 5000),
participantIds: found.map((e) => e.id),
badDate,
};
}
export async function addEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const event = await readEvent(book.id, formData);
if (!event.title) return;
if (event.badDate) redirect(`/books/${book.id}/timeline?error=date`);
await prisma.storyEvent.create({
data: {
bookId: book.id,
title: event.title,
date: event.date,
endDate: event.endDate,
description: event.description,
participants: { create: event.participantIds.map((entityId) => ({ entityId })) },
},
});
revalidateBook(book.id);
redirect(`/books/${book.id}/timeline`);
}
export async function saveEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const id = str(formData, "id");
const existing = await prisma.storyEvent.findFirst({ where: { id, bookId: book.id }, select: { id: true } });
if (!existing) throw new Error("Event not found");
const event = await readEvent(book.id, formData);
if (!event.title) return;
if (event.badDate) redirect(`/books/${book.id}/timeline/${id}?error=date`);
await prisma.$transaction([
prisma.eventParticipant.deleteMany({ where: { eventId: id } }),
prisma.storyEvent.update({
where: { id },
data: {
title: event.title,
date: event.date,
endDate: event.endDate,
description: event.description,
participants: { create: event.participantIds.map((entityId) => ({ entityId })) },
},
}),
]);
revalidateBook(book.id);
redirect(`/books/${book.id}/timeline/${id}?saved=1`);
}
export async function deleteEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
await prisma.storyEvent.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
revalidateBook(book.id);
redirect(`/books/${book.id}/timeline`);
}
+27 -5
View File
@@ -3,12 +3,14 @@
import type { Prisma } from "@prisma/client";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { parseBond } from "@/lib/family";
import { optStr, revalidateBook, str } from "@/lib/form";
import { collectFieldData } from "@/lib/field-values";
import { nextRelationCode } from "@/lib/ids";
import { requireBook } from "@/lib/session";
import { normalizeStoryDate } from "@/lib/story-date";
import { getTemplate } from "@/lib/templates";
import { getLocale } from "@/i18n/server";
import { getLocale, getT } from "@/i18n/server";
/** Extra deltagare från formuläret: bara poster i boken, utan dubbletter och utan from/to. */
async function cleanMemberIds(bookId: string, formData: FormData, exclude: string[]): Promise<string[]> {
@@ -18,12 +20,26 @@ async function cleanMemberIds(bookId: string, formData: FormData, exclude: strin
return found.map((e) => e.id);
}
/** Släktband och period ur formuläret. ok är falskt om ett datum är ifyllt men ogiltigt. */
async function bondAndDates(formData: FormData) {
const bond = parseBond(str(formData, "bond"));
const start = str(formData, "startDate", 20);
const end = str(formData, "endDate", 20);
const startDate = start ? normalizeStoryDate(start) : null;
const endDate = end ? normalizeStoryDate(end) : null;
const ok = (!start || startDate !== null) && (!end || endDate !== null);
// Tom relationstext får släktbandets namn
const { t } = await getT();
const type = str(formData, "type", 100) || (bond ? t(`relation.bond.${bond}`) : "");
return { ok, bond, startDate, endDate, type };
}
export async function addRelation(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const fromId = str(formData, "fromId");
const toId = str(formData, "toId");
const type = str(formData, "type", 100);
if (!fromId || !toId || !type || fromId === toId) return;
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
if (!fromId || !toId || !type || fromId === toId || !ok) return;
// Båda posterna måste höra till boken
const count = await prisma.entity.count({ where: { bookId: book.id, id: { in: [fromId, toId] } } });
@@ -38,6 +54,9 @@ export async function addRelation(formData: FormData) {
fromId,
toId,
type,
bond,
startDate,
endDate,
description: optStr(formData, "description", 2000),
members: { create: memberIds.map((entityId) => ({ entityId })) },
},
@@ -50,8 +69,8 @@ export async function saveRelation(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const relation = await prisma.relation.findFirst({ where: { id: str(formData, "id"), bookId: book.id } });
if (!relation) throw new Error("Relation not found");
const type = str(formData, "type", 100);
if (!type) return;
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
if (!type || !ok) return;
const { fields } = await getTemplate(book.id, "RELATION", await getLocale());
const data = await collectFieldData(book.id, fields, formData, (relation.data as Record<string, unknown> | null) ?? null);
@@ -63,6 +82,9 @@ export async function saveRelation(formData: FormData) {
where: { id: relation.id },
data: {
type,
bond,
startDate,
endDate,
description: optStr(formData, "description", 2000),
data: data as Prisma.InputJsonObject,
members: { create: memberIds.map((entityId) => ({ entityId })) },
+104
View File
@@ -0,0 +1,104 @@
import Link from "next/link";
import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { FamilyTree } from "@/components/family-tree";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { familyComponent, layoutFamily, parseBond, type FamilyBondInput, type FamilyPerson } from "@/lib/family";
import { requireBook } from "@/lib/session";
import { storyYear } from "@/lib/story-date";
export const metadata = { title: "Släktträd" };
export default async function FamilyPage({
params,
searchParams,
}: {
params: Promise<{ bookId: string }>;
searchParams: Promise<{ root?: string }>;
}) {
const { bookId } = await params;
const { root } = await searchParams;
await requireBook(bookId);
const { t } = await getT();
const relations = await prisma.relation.findMany({
where: { bookId, bond: { not: null } },
include: {
from: { select: { id: true, name: true, data: true } },
to: { select: { id: true, name: true, data: true } },
members: { include: { entity: { select: { id: true, name: true, data: true } } } },
},
orderBy: { createdAt: "asc" },
});
const year = (data: unknown, key: string) => {
const value = (data as Record<string, unknown> | null)?.[key];
return typeof value === "string" ? storyYear(value) : null;
};
const everyone = new Map<string, FamilyPerson>();
const bonds: FamilyBondInput[] = [];
for (const r of relations) {
const bond = parseBond(r.bond);
if (!bond) continue;
for (const e of [r.from, r.to, ...r.members.map((m) => m.entity)]) {
if (everyone.has(e.id)) continue;
const born = year(e.data, "birthDate");
const died = year(e.data, "deathDate");
const subtitle = born && died ? `${born}–${died}` : born ? t("family.born", { year: born }) : died ? t("family.died", { year: died }) : null;
everyone.set(e.id, { id: e.id, name: e.name, subtitle });
}
bonds.push({ bond, fromId: r.fromId, toId: r.toId, memberIds: r.members.map((m) => m.entityId) });
}
const options = [...everyone.values()].sort((a, b) => a.name.localeCompare(b.name, "sv"));
const focus = root && everyone.has(root) ? familyComponent(bonds, root) : null;
const shownBonds = focus ? bonds.filter((b) => focus.has(b.fromId)) : bonds;
const layout = layoutFamily(focus ? options.filter((p) => focus.has(p.id)) : options, shownBonds);
return (
<>
<PageHeader
title={t("family.title")}
actions={
<Link href={`/books/${bookId}/relations`} className="btn btn-primary">
{t("family.addBond")}
</Link>
}
/>
<PageBody>
{options.length === 0 ? (
<div className="card">
<div className="card-body">
<EmptyState>{t("family.empty")}</EmptyState>
<p className="text-secondary text-center mb-0">{t("family.help")}</p>
</div>
</div>
) : (
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("family.people", { count: layout.nodes.length })}</h3>
<div className="card-actions">
<form className="d-flex gap-2">
<select name="root" className="form-select form-select-sm" defaultValue={root ?? ""} aria-label={t("family.around")}>
<option value="">{t("family.everyone")}</option>
{options.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
<button className="btn btn-sm" type="submit">
{t("timeline.show")}
</button>
</form>
</div>
</div>
<div className="card-body">
<FamilyTree bookId={bookId} layout={layout} />
</div>
</div>
)}
</PageBody>
</>
);
}
@@ -6,6 +6,7 @@ import { deleteRelation, saveRelation } from "@/actions/relations";
import { ConfirmSubmit } from "@/components/confirm-submit";
import { EntitySelect } from "@/components/entity-select";
import { FieldInput } from "@/components/entity-form";
import { RelationBondFields } from "@/components/relation-bond-fields";
import { PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
@@ -102,7 +103,7 @@ export default async function RelationPage({
<div className="row g-3">
<div className="col-md-6">
<label className="form-label required">{t("relation.type")}</label>
<input name="type" className="form-control" list="relation-types" required maxLength={100} defaultValue={relation.type} />
<input name="type" className="form-control" list="relation-types" maxLength={100} defaultValue={relation.type} />
<datalist id="relation-types">
{suggestions.map((s) => (
<option key={s} value={s} />
@@ -124,6 +125,7 @@ export default async function RelationPage({
/>
<div className="form-hint">{t("relation.membersHelp")}</div>
</div>
<RelationBondFields t={t} bond={relation.bond} startDate={relation.startDate} endDate={relation.endDate} />
</div>
</div>
</div>
@@ -107,6 +107,11 @@ export default async function RelationsPage({
{r.type}
</Link>
{r.code ? <span className="badge ms-2">{r.code}</span> : null}
{r.startDate || r.endDate ? (
<span className="text-secondary small ms-2">
{r.startDate ?? ""}–{r.endDate ?? ""}
</span>
) : null}
</td>
<td>
{[r.to, ...r.members.map((m) => m.entity)].map((e, i) => (
@@ -0,0 +1,95 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { IconTrash } from "@tabler/icons-react";
import { deleteEvent, saveEvent } from "@/actions/events";
import { ConfirmSubmit } from "@/components/confirm-submit";
import { EntitySelect } from "@/components/entity-select";
import { PageBody, PageHeader } from "@/components/page";
import { StoryDateInput } from "@/components/story-date-input";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { requireBook } from "@/lib/session";
export default async function EventPage({
params,
searchParams,
}: {
params: Promise<{ bookId: string; eventId: string }>;
searchParams: Promise<{ saved?: string; error?: string }>;
}) {
const { bookId, eventId } = await params;
const { saved, error } = await searchParams;
await requireBook(bookId);
const { t } = await getT();
const event = await prisma.storyEvent.findFirst({ where: { id: eventId, bookId }, include: { participants: true } });
if (!event) notFound();
const entities = await prisma.entity.findMany({ where: { bookId }, select: { id: true, name: true, kind: true }, orderBy: { name: "asc" } });
return (
<>
<PageHeader
pretitle={
<Link href={`/books/${bookId}/timeline`} className="text-reset">
{t("timeline.title")}
</Link>
}
title={event.title}
actions={
<form action={deleteEvent}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={event.id} />
<ConfirmSubmit className="btn btn-outline-danger">
<IconTrash size={18} className="me-1" />
{t("common.delete")}
</ConfirmSubmit>
</form>
}
/>
<PageBody>
{saved ? <div className="alert alert-success">{t("common.saved")}</div> : null}
{error === "date" ? <div className="alert alert-danger">{t("timeline.invalidDate")}</div> : null}
<form action={saveEvent}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={event.id} />
<div className="card mb-3">
<div className="card-body">
<div className="row g-3">
<div className="col-12">
<label className="form-label required">{t("timeline.eventTitle")}</label>
<input name="title" className="form-control" required maxLength={200} defaultValue={event.title} />
</div>
<div className="col-md-6">
<label className="form-label required">{t("timeline.date")}</label>
<StoryDateInput name="date" required defaultValue={event.date} />
</div>
<div className="col-md-6">
<label className="form-label">{t("timeline.endDate")}</label>
<StoryDateInput name="endDate" defaultValue={event.endDate} />
</div>
<div className="col-12 form-hint mt-0">{t("timeline.dateHelp")}</div>
<div className="col-12">
<label className="form-label">{t("common.description")}</label>
<textarea name="description" className="form-control" rows={4} maxLength={5000} defaultValue={event.description ?? ""} />
</div>
<div className="col-12">
<label className="form-label">{t("timeline.participants")}</label>
<EntitySelect name="participantIds" entities={entities} t={t} multiple defaultValues={event.participants.map((p) => p.entityId)} />
<div className="form-hint">{t("relation.membersHelp")}</div>
</div>
</div>
</div>
</div>
<div className="d-flex justify-content-end gap-2">
<Link href={`/books/${bookId}/timeline`} className="btn">
{t("common.back")}
</Link>
<button type="submit" className="btn btn-primary">
{t("common.save")}
</button>
</div>
</form>
</PageBody>
</>
);
}
+230
View File
@@ -0,0 +1,230 @@
import Link from "next/link";
import { addEvent } from "@/actions/events";
import { EntitySelect } from "@/components/entity-select";
import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { StoryDateInput } from "@/components/story-date-input";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { requireBook } from "@/lib/session";
import { storyYear } from "@/lib/story-date";
import { loadTimeline, TIMELINE_KINDS, type TimelineItem, type TimelineKind } from "@/lib/timeline";
export const metadata = { title: "Tidslinje" };
const KIND_COLOR: Record<TimelineKind, string> = {
birth: "green",
death: "dark",
scenario: "pink",
event: "blue",
relation: "azure",
};
export default async function TimelinePage({
params,
searchParams,
}: {
params: Promise<{ bookId: string }>;
searchParams: Promise<{ person?: string; kind?: string | string[]; error?: string }>;
}) {
const { bookId } = await params;
const { person, kind, error } = await searchParams;
await requireBook(bookId);
const { t } = await getT();
const wanted = (Array.isArray(kind) ? kind : kind ? [kind] : []).filter((k): k is TimelineKind => (TIMELINE_KINDS as string[]).includes(k));
const kinds = new Set<TimelineKind>(wanted.length > 0 ? wanted : TIMELINE_KINDS);
const [entities, timeline] = await Promise.all([
prisma.entity.findMany({ where: { bookId }, select: { id: true, name: true, kind: true }, orderBy: { name: "asc" } }),
loadTimeline(bookId, kinds, person || undefined),
]);
const people = entities.filter((e) => e.kind === "CHARACTER" || e.kind === "PET");
const byYear = new Map<number, TimelineItem[]>();
for (const item of timeline.items) {
const year = storyYear(item.date)!;
byYear.set(year, [...(byYear.get(year) ?? []), item]);
}
const title = (item: TimelineItem) => {
const who = item.people.map((p) => p.name).join(", ");
switch (item.kind) {
case "birth":
return t("timeline.born", { name: item.title });
case "death":
return t("timeline.died", { name: item.title });
case "relation":
return item.endOnly ? t("timeline.relationEnds", { type: `${who} · ${item.title}` }) : `${who ? `${who} · ` : ""}${item.title}`;
default:
return item.title;
}
};
const when = (item: TimelineItem) => (item.endDate ? `${item.date} – ${item.endDate}` : item.date);
// Perioder (händelser och relationer med slutdatum) som staplar på en gemensam årsaxel
const periods = timeline.items.filter((i) => i.endDate);
const spanStart = Math.min(...periods.map((i) => storyYear(i.date)!));
const spanEnd = Math.max(...periods.map((i) => storyYear(i.endDate!)!));
const span = Math.max(spanEnd - spanStart + 1, 1);
return (
<>
<PageHeader title={t("timeline.title")} />
<PageBody>
{error === "date" ? <div className="alert alert-danger">{t("timeline.invalidDate")}</div> : null}
<div className="row row-cards">
<div className="col-lg-8">
<div className="card mb-3">
<div className="card-body">
<form className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">{t("timeline.person")}</label>
<EntitySelect name="person" entities={people} t={t} defaultValue={person} emptyLabel={t("timeline.everyone")} />
</div>
<div className="col-md-8">
<div className="d-flex flex-wrap gap-3 align-items-center">
{TIMELINE_KINDS.map((k) => (
<label key={k} className="form-check mb-0">
<input type="checkbox" className="form-check-input" name="kind" value={k} defaultChecked={kinds.has(k)} />
<span className="form-check-label">{t(`timeline.kind.${k}`)}</span>
</label>
))}
<button className="btn btn-sm ms-auto" type="submit">
{t("timeline.show")}
</button>
</div>
</div>
</form>
</div>
</div>
<div className="card mb-3">
{timeline.items.length === 0 ? (
<div className="card-body">
<EmptyState>{t("timeline.empty")}</EmptyState>
<p className="text-secondary text-center mb-0">{t("timeline.help")}</p>
</div>
) : (
<div className="list-group list-group-flush">
{[...byYear.entries()].map(([year, items]) => (
<div key={year} className="list-group-item">
<div className="row">
<div className="col-auto" style={{ width: "5rem" }}>
<div className="h2 mb-0">{year}</div>
</div>
<div className="col">
{items.map((item) => (
<div key={item.id} className="d-flex align-items-start gap-2 py-1">
<span className={`badge bg-${KIND_COLOR[item.kind]}-lt mt-1`} style={{ minWidth: "5.5rem" }}>
{t(`timeline.kind.${item.kind}`)}
</span>
<div>
<Link href={`/books/${bookId}/${item.link}`} className="fw-bold">
{title(item)}
</Link>
<span className="text-secondary ms-2">{when(item)}</span>
{item.detail ? <div className="text-secondary small">{item.detail}</div> : null}
{item.ages.length > 0 ? (
<div className="text-secondary small">{item.ages.map((a) => t("timeline.age", { name: a.name, age: a.age })).join(" · ")}</div>
) : null}
</div>
</div>
))}
</div>
</div>
</div>
))}
</div>
)}
</div>
{periods.length > 0 ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">{t("timeline.periods")}</h3>
<div className="card-actions text-secondary small">
{spanStart} – {spanEnd}
</div>
</div>
<div className="card-body">
{periods.map((item) => {
const from = storyYear(item.date)!;
const to = storyYear(item.endDate!)!;
return (
<div key={item.id} className="mb-2">
<div className="small">
<Link href={`/books/${bookId}/${item.link}`}>{title(item)}</Link> <span className="text-secondary">{when(item)}</span>
</div>
<div className="position-relative bg-body-secondary rounded" style={{ height: "0.75rem" }}>
<div
className={`position-absolute top-0 bottom-0 rounded bg-${KIND_COLOR[item.kind]}`}
style={{ left: `${((from - spanStart) / span) * 100}%`, width: `${Math.max(((to - from + 1) / span) * 100, 1)}%` }}
/>
</div>
</div>
);
})}
</div>
</div>
) : null}
{timeline.undated.length > 0 ? (
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("timeline.undated")}</h3>
</div>
<div className="list-group list-group-flush">
{timeline.undated.map((u) => (
<Link key={u.id} href={`/books/${bookId}/${u.link}`} className="list-group-item list-group-item-action">
{u.title}
</Link>
))}
</div>
</div>
) : null}
</div>
<div className="col-lg-4">
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("timeline.addEvent")}</h3>
</div>
<div className="card-body">
<form action={addEvent} className="row g-2">
<input type="hidden" name="bookId" value={bookId} />
<div className="col-12">
<label className="form-label required">{t("timeline.eventTitle")}</label>
<input name="title" className="form-control" required maxLength={200} />
</div>
<div className="col-12">
<label className="form-label required">{t("timeline.date")}</label>
<StoryDateInput name="date" required />
</div>
<div className="col-12">
<label className="form-label">{t("timeline.endDate")}</label>
<StoryDateInput name="endDate" />
</div>
<div className="col-12 form-hint mt-0">{t("timeline.dateHelp")}</div>
<div className="col-12">
<label className="form-label">{t("common.description")}</label>
<textarea name="description" className="form-control" rows={3} maxLength={5000} />
</div>
<div className="col-12">
<label className="form-label">{t("timeline.participants")}</label>
<EntitySelect name="participantIds" entities={entities} t={t} multiple />
<div className="form-hint">{t("relation.membersHelp")}</div>
</div>
<div className="col-12 text-end">
<button type="submit" className="btn btn-primary">
{t("timeline.addEvent")}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</PageBody>
</>
);
}
+2 -1
View File
@@ -3,6 +3,7 @@ import Link from "next/link";
import type { Entity, EntityKind } from "@prisma/client";
import type { TFunction } from "@/i18n/core";
import { NameFill } from "./name-fill";
import { StoryDateInput } from "./story-date-input";
import { fileUrl } from "@/lib/files";
import { KINDS } from "@/lib/kinds";
import type { FieldDef } from "@/lib/templates";
@@ -30,7 +31,7 @@ export function FieldInput({
case "number":
return <input type="number" step="any" name={name} className="form-control" defaultValue={text} />;
case "date":
return <input type="date" name={name} className="form-control" defaultValue={text} />;
return <StoryDateInput name={name} defaultValue={text} />;
case "url":
return <input type="url" name={name} className="form-control" defaultValue={text} placeholder="https://" />;
case "checkbox":
+68
View File
@@ -0,0 +1,68 @@
import Link from "next/link";
import { GAP_Y, NODE_HEIGHT, NODE_WIDTH, type FamilyLayout } from "@/lib/family";
const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
const line = { stroke: "var(--tblr-secondary, #667382)", strokeWidth: 1.5, fill: "none" } as const;
/** Ritar ett släktträd som SVG. Layouten kommer från layoutFamily. */
export function FamilyTree({ bookId, layout }: { bookId: string; layout: FamilyLayout }) {
const node = new Map(layout.nodes.map((n) => [n.id, n]));
const midOf = (id: string) => node.get(id)!.x + NODE_WIDTH / 2;
const partnerPairs = new Set(layout.partners.map(([a, b]) => `${a}|${b}`));
const paths: string[] = [];
for (const { childId, parentIds } of layout.children) {
const child = node.get(childId);
const parents = parentIds.filter((id) => node.has(id));
if (!child || parents.length === 0) continue;
const cx = child.x + NODE_WIDTH / 2;
const busY = child.y - GAP_Y / 2;
const pair = parents.length === 2 && (partnerPairs.has(`${parents[0]}|${parents[1]}`) || partnerPairs.has(`${parents[1]}|${parents[0]}`));
const sources: { x: number; y: number }[] = pair
? [{ x: (midOf(parents[0]) + midOf(parents[1])) / 2, y: node.get(parents[0])!.y + NODE_HEIGHT / 2 }]
: parents.map((id) => ({ x: midOf(id), y: node.get(id)!.y + NODE_HEIGHT }));
for (const s of sources) paths.push(`M${s.x} ${s.y}V${busY}`);
const xs = [cx, ...sources.map((s) => s.x)];
paths.push(`M${Math.min(...xs)} ${busY}H${Math.max(...xs)}`, `M${cx} ${busY}V${child.y}`);
}
const partnerLines = layout.partners.flatMap(([a, b]) => {
const left = node.get(a);
const right = node.get(b);
if (!left || !right || left.y !== right.y) return [];
const [first, second] = left.x <= right.x ? [left, right] : [right, left];
return [`M${first.x + NODE_WIDTH} ${first.y + NODE_HEIGHT / 2}H${second.x}`];
});
return (
<div className="overflow-auto">
<svg width={layout.width} height={layout.height} viewBox={`0 0 ${layout.width} ${layout.height}`} role="img" aria-label="Family tree">
<path d={paths.join("")} style={line} />
<path d={partnerLines.join("")} style={{ ...line, strokeWidth: 3 }} />
{layout.nodes.map((n) => (
<Link key={n.id} href={`/books/${bookId}/entity/${n.id}`}>
<title>{n.name}</title>
<rect
x={n.x}
y={n.y}
width={NODE_WIDTH}
height={NODE_HEIGHT}
rx={6}
style={{ fill: "var(--tblr-bg-surface, #fff)", stroke: "var(--tblr-border-color, #dadfe5)", strokeWidth: 1.5 }}
/>
<text x={n.x + NODE_WIDTH / 2} y={n.y + (n.subtitle ? 20 : 29)} textAnchor="middle" style={{ fill: "var(--tblr-body-color, #1d273b)", fontSize: 13, fontWeight: 600 }}>
{clip(n.name, 21)}
</text>
{n.subtitle ? (
<text x={n.x + NODE_WIDTH / 2} y={n.y + 37} textAnchor="middle" style={{ fill: "var(--tblr-secondary, #667382)", fontSize: 11 }}>
{n.subtitle}
</text>
) : null}
</Link>
))}
</svg>
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
import type { TFunction } from "@/i18n/core";
import { FAMILY_BONDS, type FamilyBondKind } from "@/lib/family";
import { StoryDateInput } from "./story-date-input";
/** Släktband och period för en relation. Används av formuläret för ny relation och av redigeringssidan. */
export function RelationBondFields({
t,
bond,
startDate,
endDate,
}: {
t: TFunction;
bond?: FamilyBondKind | null;
startDate?: string | null;
endDate?: string | null;
}) {
return (
<>
<div className="col-12">
<label className="form-label">{t("relation.bond")}</label>
<select name="bond" className="form-select" defaultValue={bond ?? ""}>
<option value="">{t("relation.bondNone")}</option>
{FAMILY_BONDS.map((b) => (
<option key={b} value={b}>
{t(`relation.bond.${b}`)}
</option>
))}
</select>
<div className="form-hint">{t("relation.bondHelp")}</div>
</div>
<div className="col-md-6">
<label className="form-label">{t("relation.startDate")}</label>
<StoryDateInput name="startDate" defaultValue={startDate} />
</div>
<div className="col-md-6">
<label className="form-label">{t("relation.endDate")}</label>
<StoryDateInput name="endDate" defaultValue={endDate} />
</div>
<div className="col-12 form-hint mt-0">{t("relation.datesHelp")}</div>
</>
);
}
+3 -1
View File
@@ -1,6 +1,7 @@
import { addRelation } from "@/actions/relations";
import type { TFunction } from "@/i18n/core";
import { EntitySelect, type EntityOption } from "./entity-select";
import { RelationBondFields } from "./relation-bond-fields";
export function RelationForm({
bookId,
@@ -30,7 +31,7 @@ export function RelationForm({
)}
<div className="col-md-6">
<label className="form-label">{t("relation.type")}</label>
<input name="type" className="form-control" list={listId} required maxLength={100} />
<input name="type" className="form-control" list={listId} maxLength={100} />
<datalist id={listId}>
{suggestions.map((s) => (
<option key={s} value={s} />
@@ -50,6 +51,7 @@ export function RelationForm({
<EntitySelect name="memberIds" entities={others} t={t} multiple />
<div className="form-hint">{t("relation.membersHelp")}</div>
</div>
<RelationBondFields t={t} />
<div className="col-12 text-end">
<button type="submit" className="btn btn-primary">
{t("relation.add")}
+10
View File
@@ -11,6 +11,8 @@ import {
IconMap2,
IconServerCog,
IconSettings,
IconSitemap,
IconTimeline,
IconTrash,
IconTemplate,
IconBooks,
@@ -47,6 +49,8 @@ export async function Shell({ user, book, children }: ShellProps) {
{ label: t("nav.overview"), href: base },
...KINDS.map((k) => ({ label: t(`kind.${k.kind}.other`), href: `${base}/e/${k.slug}` })),
{ label: t("nav.relations"), href: `${base}/relations` },
{ label: t("nav.family"), href: `${base}/family` },
{ label: t("nav.timeline"), href: `${base}/timeline` },
{ label: t("nav.schedules"), href: `${base}/schedules` },
{ label: t("nav.maps"), href: `${base}/maps` },
{ label: t("nav.names"), href: `${base}/names` },
@@ -142,6 +146,12 @@ export async function Shell({ user, book, children }: ShellProps) {
<NavLink href={`${base}/relations`} icon={<IconChartDots3 size={20} />}>
{t("nav.relations")}
</NavLink>
<NavLink href={`${base}/family`} icon={<IconSitemap size={20} />}>
{t("nav.family")}
</NavLink>
<NavLink href={`${base}/timeline`} icon={<IconTimeline size={20} />}>
{t("nav.timeline")}
</NavLink>
<NavLink href={`${base}/schedules`} icon={<IconCalendarWeek size={20} />}>
{t("nav.schedules")}
</NavLink>
+29
View File
@@ -0,0 +1,29 @@
// Datumfält för berättelsens tid. Året räcker ("1987"), månad och dag är valfria. Se src/lib/story-date.ts.
export function StoryDateInput({
name,
defaultValue,
required,
id,
}: {
name: string;
defaultValue?: string | null;
required?: boolean;
id?: string;
}) {
return (
<input
type="text"
id={id}
name={name}
className="form-control"
defaultValue={defaultValue ?? ""}
required={required}
inputMode="numeric"
maxLength={10}
placeholder="1987-03-04"
pattern="\d{1,4}(-\d{1,2}(-\d{1,2})?)?"
title="ÅÅÅÅ, ÅÅÅÅ-MM eller ÅÅÅÅ-MM-DD / YYYY, YYYY-MM or YYYY-MM-DD"
autoComplete="off"
/>
);
}
+48 -1
View File
@@ -45,6 +45,8 @@ export const en: Record<keyof typeof sv, string> = {
"nav.world": "World",
"nav.planning": "Planning",
"nav.relations": "Relationships",
"nav.family": "Family tree",
"nav.timeline": "Timeline",
"nav.schedules": "Schedules",
"nav.maps": "Maps",
"nav.templates": "Templates",
@@ -273,7 +275,52 @@ export const en: Record<keyof typeof sv, string> = {
"relation.empty": "No relationships yet.",
"relation.filter": "Show relationships for",
"relation.suggestions": "Partner of,Parent of,Child of,Sibling of,Friend of,Colleague of,Boss of,Enemy of,Neighbour of,Lives at,Works at,Owns,Owned by,Pet of,Involved in,Affected by,Student at,Teacher at",
"relation.sameEntity": "An item cannot have a relationship with itself.",
"relation.bond": "Family bond",
"relation.bondNone": "None (ordinary relationship)",
"relation.bondHelp": "Used by the family tree. Parent of goes from the first to the second and the extra participants; partner and sibling apply to everyone. If the relationship is left empty it gets the name of the bond.",
"relation.bond.PARENT": "Parent of",
"relation.bond.PARTNER": "Partner of",
"relation.bond.SIBLING": "Sibling of",
"relation.startDate": "Valid from",
"relation.endDate": "Valid until",
"relation.datesHelp": "Optional. The year is enough, e.g. 2004, 2004-06 or 2004-06-12. Shown on the timeline.",
"family.title": "Family tree",
"family.help": "The family tree is drawn from relationships with a family bond (parent, partner or sibling). Add them under Relationships.",
"family.empty": "No family bonds yet. Create a relationship and choose a family bond to build the tree.",
"family.around": "Show the family around",
"family.everyone": "All families",
"family.born": "b. {year}",
"family.died": "d. {year}",
"family.people": "{count} people",
"family.addBond": "Add family bond",
"timeline.title": "Timeline",
"timeline.help": "Collects dates from the whole book: births and deaths, scenarios, your own events and relationships with a start or end date.",
"timeline.empty": "Nothing to show yet. Fill in birth dates, dates on scenarios or add an event.",
"timeline.person": "Show events for",
"timeline.everyone": "Everyone",
"timeline.show": "Show",
"timeline.kind.birth": "Births",
"timeline.kind.death": "Deaths",
"timeline.kind.scenario": "Scenarios",
"timeline.kind.event": "Events",
"timeline.kind.relation": "Relationships",
"timeline.born": "{name} is born",
"timeline.died": "{name} dies",
"timeline.relationEnds": "{type} ends",
"timeline.age": "{name} {age} years",
"timeline.undated": "Scenarios without a date",
"timeline.periods": "Periods",
"timeline.addEvent": "Add event",
"timeline.editEvent": "Edit event",
"timeline.eventTitle": "Title",
"timeline.date": "Date",
"timeline.endDate": "End date (optional)",
"timeline.dateHelp": "The year is enough, e.g. 1987, 1987-03 or 1987-03-04.",
"timeline.participants": "Participants",
"timeline.invalidDate": "The date is invalid. Write YYYY, YYYY-MM or YYYY-MM-DD.",
"relation.sameEntity":"An item cannot have a relationship with itself.",
"schedule.title": "Schedules",
"schedule.add": "Add shift",
+47
View File
@@ -43,6 +43,8 @@ export const sv = {
"nav.world": "Världen",
"nav.planning": "Planering",
"nav.relations": "Relationer",
"nav.family": "Släktträd",
"nav.timeline": "Tidslinje",
"nav.schedules": "Scheman",
"nav.maps": "Kartor",
"nav.templates": "Mallar",
@@ -272,6 +274,51 @@ export const sv = {
"relation.filter": "Visa relationer för",
"relation.suggestions": "Partner till,Förälder till,Barn till,Syskon till,Vän till,Kollega till,Chef över,Ovän till,Granne till,Bor på,Jobbar på,Äger,Ägs av,Husdjur till,Involverad i,Berörd av,Elev på,Lärare på",
"relation.sameEntity": "En post kan inte ha en relation till sig själv.",
"relation.bond": "Släktband",
"relation.bondNone": "Inget (vanlig relation)",
"relation.bondHelp": "Används av släktträdet. Förälder till gäller från den första till den andra och de extra deltagarna, partner och syskon gäller alla. Lämnas relationen tom får den släktbandets namn.",
"relation.bond.PARENT": "Förälder till",
"relation.bond.PARTNER": "Partner till",
"relation.bond.SIBLING": "Syskon till",
"relation.startDate": "Gäller från",
"relation.endDate": "Gäller till",
"relation.datesHelp": "Valfritt. Året räcker, t.ex. 2004, 2004-06 eller 2004-06-12. Visas på tidslinjen.",
"family.title": "Släktträd",
"family.help": "Släktträdet ritas av relationer med ett släktband (förälder, partner eller syskon). Lägg till dem under Relationer.",
"family.empty": "Inga släktband ännu. Skapa en relation och välj ett släktband för att bygga trädet.",
"family.around": "Visa släkten kring",
"family.everyone": "Alla släkter",
"family.born": "f. {year}",
"family.died": "d. {year}",
"family.people": "{count} personer",
"family.addBond": "Lägg till släktband",
"timeline.title": "Tidslinje",
"timeline.help": "Samlar datum från hela boken: födelse och död, scenarier, egna händelser och relationer med start- eller slutdatum.",
"timeline.empty": "Inget att visa ännu. Fyll i födelsedatum, datum på scenarier eller lägg till en händelse.",
"timeline.person": "Visa händelser för",
"timeline.everyone": "Alla",
"timeline.show": "Visa",
"timeline.kind.birth": "Födelser",
"timeline.kind.death": "Dödsfall",
"timeline.kind.scenario": "Scenarier",
"timeline.kind.event": "Händelser",
"timeline.kind.relation": "Relationer",
"timeline.born": "{name} föds",
"timeline.died": "{name} dör",
"timeline.relationEnds": "{type} tar slut",
"timeline.age": "{name} {age} år",
"timeline.undated": "Scenarier utan datum",
"timeline.periods": "Perioder",
"timeline.addEvent": "Lägg till händelse",
"timeline.editEvent": "Redigera händelse",
"timeline.eventTitle": "Rubrik",
"timeline.date": "Datum",
"timeline.endDate": "Slutdatum (valfritt)",
"timeline.dateHelp": "Året räcker, t.ex. 1987, 1987-03 eller 1987-03-04.",
"timeline.participants": "Deltagare",
"timeline.invalidDate": "Datumet är ogiltigt. Skriv ÅÅÅÅ, ÅÅÅÅ-MM eller ÅÅÅÅ-MM-DD.",
"schedule.title": "Scheman",
"schedule.add": "Lägg till arbetspass",
+58
View File
@@ -1,6 +1,8 @@
import { randomUUID } from "node:crypto";
import { strFromU8, unzipSync } from "fflate";
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
import { parseBond, type FamilyBondKind } from "./family";
import { normalizeStoryDate } from "./story-date";
import { prisma } from "./db";
import { deleteImage, readImageBytes, saveImageBytes } from "./files";
import type { ImageKind } from "./images";
@@ -57,6 +59,16 @@ export type ExportData = {
description: string | null;
data: Record<string, Json>;
members: string[];
bond: FamilyBondKind | null;
startDate: string | null;
endDate: string | null;
}[];
events: {
title: string;
date: string;
endDate: string | null;
description: string | null;
participants: string[];
}[];
shifts: {
personId: string;
@@ -98,6 +110,7 @@ export async function buildExport(bookId: string, withImages: boolean) {
include: {
entities: { orderBy: { createdAt: "asc" } },
relations: { orderBy: { createdAt: "asc" }, include: { members: true } },
events: { orderBy: { createdAt: "asc" }, include: { participants: true } },
shifts: { orderBy: { createdAt: "asc" } },
maps: { orderBy: { createdAt: "asc" }, include: { markers: { orderBy: { createdAt: "asc" } } } },
templates: true,
@@ -166,6 +179,16 @@ export async function buildExport(bookId: string, withImages: boolean) {
description: r.description,
data: (r.data ?? {}) as Record<string, Json>,
members: r.members.map((m) => m.entityId),
bond: r.bond,
startDate: r.startDate,
endDate: r.endDate,
})),
events: book.events.map((e) => ({
title: e.title,
date: e.date,
endDate: e.endDate,
description: e.description,
participants: e.participants.map((p) => p.entityId),
})),
shifts: book.shifts.map((s) => ({
personId: s.personId,
@@ -246,6 +269,22 @@ export function parseExport(raw: unknown): ExportData {
description: text(item.description, 2000),
data: object(item.data),
members: Array.isArray(item.members) ? item.members.map((m) => text(m, 100)).filter((m): m is string => !!m) : [],
bond: parseBond(item.bond),
startDate: normalizeStoryDate(item.startDate),
endDate: normalizeStoryDate(item.endDate),
};
});
const events = list(raw.events, "events").map((item, i): ExportData["events"][number] => {
if (!isObj(item)) throw new ImportError("invalid", `events[${i}]`);
const date = normalizeStoryDate(item.date);
if (!date) throw new ImportError("invalid", `events[${i}].date`);
return {
title: required(item.title, 200, `events[${i}].title`),
date,
endDate: normalizeStoryDate(item.endDate),
description: text(item.description, 5000),
participants: Array.isArray(item.participants) ? item.participants.map((m) => text(m, 100)).filter((m): m is string => !!m) : [],
};
});
@@ -324,6 +363,7 @@ export function parseExport(raw: unknown): ExportData {
},
entities,
relations,
events,
shifts,
maps,
templates,
@@ -379,6 +419,7 @@ export type ImportResult = {
bookId: string;
entities: number;
relations: number;
events: number;
maps: number;
markers: number;
shifts: number;
@@ -535,6 +576,9 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
type: r.type,
description: r.description,
data: remapIds(r.data, entityIds) as Prisma.InputJsonObject,
bond: r.bond,
startDate: r.startDate,
endDate: r.endDate,
})),
});
await tx.relationMember.createMany({
@@ -545,6 +589,19 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
),
});
for (const e of data.events) {
await tx.storyEvent.create({
data: {
bookId,
title: e.title,
date: e.date,
endDate: e.endDate,
description: e.description,
participants: { create: [...new Set(e.participants)].filter((p) => entityIds.has(p)).map((p) => ({ entityId: sid(p) })) },
},
});
}
await tx.shift.createMany({
data: groupList.flatMap((g) =>
g.shifts.map((s) => ({
@@ -606,6 +663,7 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
bookId,
entities: entities.length,
relations: relations.length,
events: data.events.length,
maps: maps.length,
markers: markers.length,
shifts: shiftsIn.length,
+265
View File
@@ -0,0 +1,265 @@
// Släktträdets layout. Släktband kommer från relationer med ett släktband (förälder, partner eller syskon).
// Layouten är ren beräkning utan databas: generationer räknas fram, partner läggs bredvid varandra och barn
// placeras under sina föräldrar. Själva ritningen sker i komponenten FamilyTree.
export type FamilyBondKind = "PARENT" | "PARTNER" | "SIBLING";
export const FAMILY_BONDS: FamilyBondKind[] = ["PARENT", "PARTNER", "SIBLING"];
export function parseBond(value: unknown): FamilyBondKind | null {
return typeof value === "string" && (FAMILY_BONDS as string[]).includes(value) ? (value as FamilyBondKind) : null;
}
export type FamilyBondInput = {
bond: FamilyBondKind;
fromId: string;
toId: string;
memberIds: string[];
};
export type FamilyPerson = { id: string; name: string; subtitle?: string | null };
export type FamilyNode = FamilyPerson & { x: number; y: number; generation: number };
export type FamilyLayout = {
nodes: FamilyNode[];
/** Partnerlinjer mellan två grannar i samma rad */
partners: [string, string][];
/** Ett barn med sina föräldrar (bara de som finns i trädet) */
children: { childId: string; parentIds: string[] }[];
width: number;
height: number;
};
export const NODE_WIDTH = 160;
export const NODE_HEIGHT = 48;
export const GAP_X = 28;
export const GAP_Y = 76;
const MARGIN = 16;
/** Alla som hör till samma släkt som rootId, via vilket släktband som helst. */
export function familyComponent(bonds: FamilyBondInput[], rootId: string): Set<string> {
const adjacent = new Map<string, Set<string>>();
const link = (a: string, b: string) => {
if (!adjacent.has(a)) adjacent.set(a, new Set());
adjacent.get(a)!.add(b);
};
for (const b of bonds) {
const all = [b.fromId, b.toId, ...b.memberIds];
for (const x of all) for (const y of all) if (x !== y) link(x, y);
}
const seen = new Set([rootId]);
const queue = [rootId];
while (queue.length > 0) {
for (const next of adjacent.get(queue.shift()!) ?? []) {
if (!seen.has(next)) {
seen.add(next);
queue.push(next);
}
}
}
return seen;
}
type Unit = { members: string[]; generation: number };
const mean = (values: number[]) => values.reduce((sum, v) => sum + v, 0) / values.length;
export function layoutFamily(people: FamilyPerson[], bonds: FamilyBondInput[]): FamilyLayout {
const known = new Map(people.map((p) => [p.id, p]));
const involved = new Set<string>();
const parentsOf = new Map<string, Set<string>>();
const partnerEdges = new Map<string, Set<string>>();
const siblingEdges = new Map<string, Set<string>>();
const addEdge = (edges: Map<string, Set<string>>, a: string, b: string) => {
if (!edges.has(a)) edges.set(a, new Set());
if (!edges.has(b)) edges.set(b, new Set());
edges.get(a)!.add(b);
edges.get(b)!.add(a);
};
for (const b of bonds) {
const all = [...new Set([b.fromId, b.toId, ...b.memberIds])].filter((id) => known.has(id));
if (b.bond === "PARENT") {
if (!known.has(b.fromId)) continue;
for (const child of [b.toId, ...b.memberIds]) {
if (!known.has(child) || child === b.fromId) continue;
involved.add(b.fromId).add(child);
if (!parentsOf.has(child)) parentsOf.set(child, new Set());
parentsOf.get(child)!.add(b.fromId);
}
} else {
const edges = b.bond === "PARTNER" ? partnerEdges : siblingEdges;
for (let i = 0; i < all.length; i++) {
involved.add(all[i]);
for (let j = i + 1; j < all.length; j++) addEdge(edges, all[i], all[j]);
}
}
}
const ids = [...involved].sort((a, b) => known.get(a)!.name.localeCompare(known.get(b)!.name, "sv") || a.localeCompare(b));
if (ids.length === 0) return { nodes: [], partners: [], children: [], width: 0, height: 0 };
// Partner och syskon hör till samma generation
const root = new Map(ids.map((id) => [id, id]));
const find = (id: string): string => {
let r = id;
while (root.get(r) !== r) r = root.get(r)!;
root.set(id, r);
return r;
};
for (const edges of [partnerEdges, siblingEdges]) {
for (const [a, others] of edges) for (const b of others) root.set(find(a), find(b));
}
// Generation = längsta kedjan av föräldrar ovanför. Begränsningen gör att cirkulära släktband inte kan hänga sig.
const generation = new Map<string, number>();
for (const id of ids) generation.set(find(id), 0);
for (let round = 0; round <= ids.length; round++) {
let changed = false;
for (const [child, parents] of parentsOf) {
for (const parent of parents) {
const need = generation.get(find(parent))! + 1;
if (find(child) !== find(parent) && generation.get(find(child))! < need && need <= ids.length) {
generation.set(find(child), need);
changed = true;
}
}
}
if (!changed) break;
}
const genOf = (id: string) => generation.get(find(id))!;
// Partner bildar en enhet som ritas bredvid varandra, i ordning längs partnerkedjan
const unitOf = new Map<string, Unit>();
const units: Unit[] = [];
for (const id of ids) {
if (unitOf.has(id)) continue;
const members: string[] = [];
if (partnerEdges.has(id)) {
const component = new Set<string>();
const stack = [id];
while (stack.length > 0) {
const cur = stack.pop()!;
if (component.has(cur)) continue;
component.add(cur);
for (const next of partnerEdges.get(cur) ?? []) stack.push(next);
}
// Starta i en ände av kedjan (den med färst partner), annars först i namnordning
const start = ids.filter((m) => component.has(m)).sort((a, b) => partnerEdges.get(a)!.size - partnerEdges.get(b)!.size)[0];
const walked = new Set<string>();
const walk = (cur: string) => {
walked.add(cur);
members.push(cur);
for (const next of [...partnerEdges.get(cur)!].sort((a, b) => ids.indexOf(a) - ids.indexOf(b))) if (!walked.has(next)) walk(next);
};
walk(start);
} else {
members.push(id);
}
const unit: Unit = { members, generation: Math.max(...members.map(genOf)) };
units.push(unit);
for (const m of members) unitOf.set(m, unit);
}
const maxGen = Math.max(...units.map((u) => u.generation));
const rows: Unit[][] = Array.from({ length: maxGen + 1 }, () => []);
for (const unit of units) rows[unit.generation].push(unit);
const unitWidth = (u: Unit) => u.members.length * NODE_WIDTH + (u.members.length - 1) * GAP_X;
const left = new Map<Unit, number>();
const center = (u: Unit) => left.get(u)! + unitWidth(u) / 2;
const nodeCenter = (id: string) => {
const u = unitOf.get(id)!;
return left.get(u)! + u.members.indexOf(id) * (NODE_WIDTH + GAP_X) + NODE_WIDTH / 2;
};
const childrenOf = new Map<string, string[]>();
for (const [child, parents] of parentsOf) for (const p of parents) childrenOf.set(p, [...(childrenOf.get(p) ?? []), child]);
/** Läser av grannarnas lägen: föräldrar, annars syskon, annars barn. */
const anchor = (u: Unit, useChildren: boolean): number | undefined => {
const parents = u.members.flatMap((m) => [...(parentsOf.get(m) ?? [])]);
const kids = u.members.flatMap((m) => childrenOf.get(m) ?? []);
const siblings = u.members.flatMap((m) => [...(siblingEdges.get(m) ?? [])]).filter((s) => unitOf.get(s) !== u);
const placed = (list: string[]) => list.filter((id) => left.has(unitOf.get(id)!)).map(nodeCenter);
const order = useChildren ? [kids, parents, siblings] : [parents, siblings, kids];
for (const list of order) {
const xs = placed(list);
if (xs.length > 0) return mean(xs);
}
return undefined;
};
/** Ordnar och packar en rad så att enheter hamnar nära sina grannar utan att överlappa. */
const arrange = (row: Unit[], useChildren: boolean) => {
const wanted = new Map<Unit, number | undefined>(row.map((u) => [u, anchor(u, useChildren)]));
const index = new Map(row.map((u, i) => [u, i]));
const sorted = [...row].sort((a, b) => {
const ka = wanted.get(a) ?? left.get(a) ?? 0;
const kb = wanted.get(b) ?? left.get(b) ?? 0;
return ka - kb || index.get(a)! - index.get(b)!;
});
row.splice(0, row.length, ...sorted);
let cursor = Number.NEGATIVE_INFINITY;
for (const u of row) {
const width = unitWidth(u);
const target = wanted.get(u);
let x = target === undefined ? (cursor === Number.NEGATIVE_INFINITY ? 0 : cursor + GAP_X) : target - width / 2;
if (cursor !== Number.NEGATIVE_INFINITY) x = Math.max(x, cursor + GAP_X);
left.set(u, x);
cursor = x + width;
}
// Flytta hela raden så att den i genomsnitt hamnar mitt under det den sitter ihop med
const offsets = row.filter((u) => wanted.get(u) !== undefined).map((u) => wanted.get(u)! - center(u));
if (offsets.length > 0) {
const shift = mean(offsets);
for (const u of row) left.set(u, left.get(u)! + shift);
}
};
// Första raden i namnordning, sedan några svep nedåt och uppåt
let cursor = 0;
for (const u of rows[0]) {
left.set(u, cursor);
cursor += unitWidth(u) + GAP_X;
}
for (let g = 1; g <= maxGen; g++) arrange(rows[g], false);
for (let pass = 0; pass < 3; pass++) {
for (let g = maxGen - 1; g >= 0; g--) arrange(rows[g], true);
for (let g = 1; g <= maxGen; g++) arrange(rows[g], false);
}
const nodes: FamilyNode[] = [];
for (const u of units) {
for (const [i, id] of u.members.entries()) {
const person = known.get(id)!;
nodes.push({ ...person, x: left.get(u)! + i * (NODE_WIDTH + GAP_X), y: u.generation * (NODE_HEIGHT + GAP_Y), generation: u.generation });
}
}
const minX = Math.min(...nodes.map((n) => n.x));
for (const n of nodes) {
n.x = Math.round(n.x - minX + MARGIN);
n.y += MARGIN;
}
const partners: [string, string][] = [];
for (const u of units) {
for (let i = 0; i + 1 < u.members.length; i++) {
if (partnerEdges.get(u.members[i])?.has(u.members[i + 1])) partners.push([u.members[i], u.members[i + 1]]);
}
}
const children = [...parentsOf]
.map(([childId, parents]) => ({ childId, parentIds: [...parents].sort() }))
.sort((a, b) => a.childId.localeCompare(b.childId));
return {
nodes,
partners,
children,
width: Math.max(...nodes.map((n) => n.x + NODE_WIDTH)) + MARGIN,
height: Math.max(...nodes.map((n) => n.y + NODE_HEIGHT)) + MARGIN,
};
}
+5
View File
@@ -1,5 +1,6 @@
import { prisma } from "./db";
import { str } from "./form";
import { normalizeStoryDate } from "./story-date";
import type { FieldDef } from "./templates";
/**
@@ -24,6 +25,10 @@ export async function collectFieldData(
const raw = str(formData, name, 20000);
if (raw === "") {
delete data[field.key];
} else if (field.type === "date") {
// Året räcker; ett ogiltigt datum ändrar ingenting
const date = normalizeStoryDate(raw);
if (date) data[field.key] = date;
} else if (field.type === "number") {
const n = Number(raw.replace(",", "."));
if (Number.isFinite(n)) data[field.key] = n;
+64
View File
@@ -0,0 +1,64 @@
// Datum i berättelsen. De skrivs som "ÅÅÅÅ", "ÅÅÅÅ-MM" eller "ÅÅÅÅ-MM-DD", så att man kan nöja sig med året när
// resten inte är bestämt. Berättelsens tid kan ligga var som helst, därför används inte Date (som bara klarar riktiga tidpunkter).
export type StoryDate = { year: number; month?: number; day?: number };
const PATTERN = /^(\d{1,4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?$/;
const daysInMonth = (year: number, month: number) => {
if (month === 2) return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
return [4, 6, 9, 11].includes(month) ? 30 : 31;
};
export function parseStoryDate(raw: unknown): StoryDate | null {
if (typeof raw !== "string") return null;
const match = PATTERN.exec(raw.trim());
if (!match) return null;
const year = Number(match[1]);
const month = match[2] === undefined ? undefined : Number(match[2]);
const day = match[3] === undefined ? undefined : Number(match[3]);
if (year < 1) return null;
if (month !== undefined && (month < 1 || month > 12)) return null;
if (month !== undefined && day !== undefined && (day < 1 || day > daysInMonth(year, month))) return null;
return { year, ...(month === undefined ? {} : { month }), ...(day === undefined ? {} : { day }) };
}
/** Skriver ett datum i fast form (ÅÅÅÅ, ÅÅÅÅ-MM eller ÅÅÅÅ-MM-DD), eller null om det inte är ett giltigt datum. */
export function normalizeStoryDate(raw: unknown): string | null {
const d = parseStoryDate(raw);
if (!d) return null;
const parts = [String(d.year).padStart(4, "0")];
if (d.month !== undefined) parts.push(String(d.month).padStart(2, "0"));
if (d.day !== undefined) parts.push(String(d.day).padStart(2, "0"));
return parts.join("-");
}
/** Sorteringsvärde. Ett årtal hamnar före datumen samma år. */
export function storyDateKey(date: string | StoryDate): number {
const d = typeof date === "string" ? parseStoryDate(date) : date;
if (!d) return Number.NaN;
return d.year * 10000 + (d.month ?? 0) * 100 + (d.day ?? 0);
}
export function compareStoryDates(a: string, b: string): number {
return storyDateKey(a) - storyDateKey(b);
}
/** Ålder i hela år vid ett datum, eller null om något datum saknas eller personen inte är född än. */
export function ageAt(birth: string, at: string): number | null {
const b = parseStoryDate(birth);
const d = parseStoryDate(at);
if (!b || !d) return null;
let age = d.year - b.year;
// Födelsedagen räknas bara in när båda datumen är kända ner till månad
if (b.month !== undefined && d.month !== undefined) {
const passed = d.month > b.month || (d.month === b.month && (b.day === undefined || d.day === undefined || d.day >= b.day));
if (!passed) age -= 1;
}
return age < 0 ? null : age;
}
/** Året som tal, för tidslinjens axel. */
export function storyYear(date: string): number | null {
return parseStoryDate(date)?.year ?? null;
}
+3 -1
View File
@@ -37,6 +37,7 @@ const SPECS: Record<TemplateKind, Spec[]> = {
f("nickname", ["Smeknamn", "Nickname"], "text", ["Grunduppgifter", "Basics"]),
f("age", ["Ålder", "Age"], "number"),
f("birthDate", ["Födelsedatum", "Date of birth"], "date"),
f("deathDate", ["Dödsdatum", "Date of death"], "date"),
f("height", ["Längd", "Height"]),
f("gender", ["Kön", "Gender"]),
f("orientation", ["Läggning", "Orientation"]),
@@ -206,7 +207,8 @@ const SPECS: Record<TemplateKind, Spec[]> = {
["Grunduppgifter", "Basics"],
),
ref("linkedEntity", ["Kopplat till (post)", "Linked to (item)"]),
f("when", ["När (tid i berättelsen)", "When (story time)"]),
f("date", ["Datum i berättelsen", "Date in the story"], "date"),
f("when", ["När (fritext)", "When (free text)"]),
area("description", ["Beskriv scenariot", "Describe the scenario"], ["Innehåll", "Content"]),
area("impactDuring", ["Hur påverkas karaktärerna under scenariot", "How the characters are affected during"]),
area("impactAfter", ["Hur påverkas karaktärerna efter scenariot", "How the characters are affected afterwards"]),
+182
View File
@@ -0,0 +1,182 @@
import { prisma } from "./db";
import { ageAt, compareStoryDates, normalizeStoryDate, parseStoryDate } from "./story-date";
// Tidslinjen samlar datum från hela boken: födelse och död (karaktärernas fält), scenarier, egna händelser
// och relationer med start- eller slutdatum. buildTimeline är ren beräkning, loadTimeline hämtar underlaget.
export type TimelineKind = "birth" | "death" | "scenario" | "event" | "relation";
export const TIMELINE_KINDS: TimelineKind[] = ["birth", "death", "scenario", "event", "relation"];
type Person = { id: string; name: string };
export type TimelineInput = {
/** Karaktärer med födelse- och dödsdatum ur sina mallfält (birthDate och deathDate) */
characters: (Person & { birthDate?: string | null; deathDate?: string | null })[];
scenarios: (Person & { date?: string | null; type?: string | null; people: Person[] })[];
events: { id: string; title: string; date: string; endDate?: string | null; description?: string | null; people: Person[] }[];
relations: { id: string; type: string; startDate?: string | null; endDate?: string | null; people: Person[] }[];
};
export type TimelineItem = {
id: string;
kind: TimelineKind;
/** Startdatum (eller enda datum) i fast form */
date: string;
endDate: string | null;
title: string;
detail: string | null;
/** Relation som bara har ett slutdatum: datumet är då slutet, inte början */
endOnly: boolean;
/** Länk inom boken, t.ex. "entity/abc" */
link: string;
people: Person[];
/** Ålder vid händelsen för de som har födelsedatum och inte hunnit dö */
ages: { id: string; name: string; age: number }[];
};
export type Timeline = { items: TimelineItem[]; undated: { id: string; title: string; link: string }[] };
const clean = (value: unknown) => normalizeStoryDate(value);
export function buildTimeline(input: TimelineInput, kinds: ReadonlySet<TimelineKind> = new Set(TIMELINE_KINDS), onlyPerson?: string): Timeline {
const born = new Map<string, string>();
const died = new Map<string, string>();
for (const c of input.characters) {
const b = clean(c.birthDate);
const d = clean(c.deathDate);
if (b) born.set(c.id, b);
if (d) died.set(c.id, d);
}
const items: TimelineItem[] = [];
const undated: Timeline["undated"] = [];
const push = (item: Omit<TimelineItem, "ages" | "endDate" | "endOnly"> & { endDate?: string | null; endOnly?: boolean }, withAges = true) => {
const ages: TimelineItem["ages"] = [];
if (withAges) {
for (const p of item.people) {
const birth = born.get(p.id);
const death = died.get(p.id);
if (!birth || (death && compareStoryDates(death, item.date) < 0)) continue;
const age = ageAt(birth, item.date);
if (age !== null) ages.push({ id: p.id, name: p.name, age });
}
}
items.push({ ...item, endDate: item.endDate ?? null, endOnly: item.endOnly ?? false, ages });
};
for (const c of input.characters) {
const who = [{ id: c.id, name: c.name }];
const b = born.get(c.id);
const d = died.get(c.id);
if (b) push({ id: `birth-${c.id}`, kind: "birth", date: b, title: c.name, detail: null, link: `entity/${c.id}`, people: who }, false);
if (d) push({ id: `death-${c.id}`, kind: "death", date: d, title: c.name, detail: null, link: `entity/${c.id}`, people: who });
}
for (const s of input.scenarios) {
const date = clean(s.date);
if (!date) {
undated.push({ id: s.id, title: s.name, link: `entity/${s.id}` });
continue;
}
push({ id: `scenario-${s.id}`, kind: "scenario", date, title: s.name, detail: s.type ?? null, link: `entity/${s.id}`, people: s.people });
}
for (const e of input.events) {
const date = clean(e.date);
if (!date) continue;
push({ id: `event-${e.id}`, kind: "event", date, endDate: clean(e.endDate), title: e.title, detail: e.description ?? null, link: `timeline/${e.id}`, people: e.people });
}
for (const r of input.relations) {
const start = clean(r.startDate);
const end = clean(r.endDate);
const date = start ?? end;
if (!date) continue;
push({
id: `relation-${r.id}`,
kind: "relation",
date,
endDate: start ? end : null,
title: r.type,
detail: null,
endOnly: !start,
link: `relations/${r.id}`,
people: r.people,
});
}
const shown = items
.filter((i) => kinds.has(i.kind) && (!onlyPerson || i.people.some((p) => p.id === onlyPerson)))
.sort((a, b) => compareStoryDates(a.date, b.date) || a.kind.localeCompare(b.kind) || a.title.localeCompare(b.title, "sv"));
return { items: shown, undated: kinds.has("scenario") && !onlyPerson ? undated : [] };
}
/** Datum i mallfält kan vara skrivna för hand; bara giltiga datum används. */
const fieldDate = (data: unknown, key: string): string | null => {
const value = (data as Record<string, unknown> | null)?.[key];
return typeof value === "string" && parseStoryDate(value) ? value : null;
};
export async function loadTimeline(bookId: string, kinds?: ReadonlySet<TimelineKind>, onlyPerson?: string): Promise<Timeline> {
const [characters, scenarios, events, relations] = await Promise.all([
prisma.entity.findMany({ where: { bookId, kind: "CHARACTER" }, select: { id: true, name: true, data: true } }),
prisma.entity.findMany({ where: { bookId, kind: "SCENARIO" }, select: { id: true, name: true, data: true } }),
prisma.storyEvent.findMany({ where: { bookId }, include: { participants: { include: { entity: { select: { id: true, name: true } } } } } }),
prisma.relation.findMany({
where: { bookId },
include: { from: { select: { id: true, name: true, kind: true } }, to: { select: { id: true, name: true, kind: true } }, members: { include: { entity: { select: { id: true, name: true, kind: true } } } } },
}),
]);
const scenarioIds = new Set(scenarios.map((s) => s.id));
const participantsOf = (r: (typeof relations)[number]) => [r.from, r.to, ...r.members.map((m) => m.entity)];
// Personer i ett scenario: de som är kopplade till det via en relation, eller via scenariots koppling till en post
const peopleInScenario = new Map<string, Person[]>();
for (const r of relations) {
const all = participantsOf(r);
for (const scenario of all.filter((e) => scenarioIds.has(e.id))) {
const others = all.filter((e) => e.kind === "CHARACTER").map(({ id, name }) => ({ id, name }));
peopleInScenario.set(scenario.id, [...(peopleInScenario.get(scenario.id) ?? []), ...others]);
}
}
const characterNames = new Map(characters.map((c) => [c.id, c.name]));
for (const s of scenarios) {
const linked = (s.data as Record<string, unknown> | null)?.linkedEntity;
if (typeof linked === "string" && characterNames.has(linked)) {
peopleInScenario.set(s.id, [...(peopleInScenario.get(s.id) ?? []), { id: linked, name: characterNames.get(linked)! }]);
}
}
const unique = (list: Person[]) => [...new Map(list.map((p) => [p.id, p])).values()];
return buildTimeline(
{
characters: characters.map((c) => ({ id: c.id, name: c.name, birthDate: fieldDate(c.data, "birthDate"), deathDate: fieldDate(c.data, "deathDate") })),
scenarios: scenarios.map((s) => ({
id: s.id,
name: s.name,
date: fieldDate(s.data, "date"),
type: typeof (s.data as Record<string, unknown> | null)?.scenarioType === "string" ? String((s.data as Record<string, unknown>).scenarioType) : null,
people: unique(peopleInScenario.get(s.id) ?? []),
})),
events: events.map((e) => ({
id: e.id,
title: e.title,
date: e.date,
endDate: e.endDate,
description: e.description,
people: e.participants.map((p) => p.entity),
})),
relations: relations.map((r) => ({
id: r.id,
type: r.type,
startDate: r.startDate,
endDate: r.endDate,
people: participantsOf(r).filter((e) => e.kind === "CHARACTER" || e.kind === "PET").map(({ id, name }) => ({ id, name })),
})),
},
kinds,
onlyPerson,
);
}
+19 -1
View File
@@ -1,7 +1,7 @@
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { strToU8, zipSync, type Zippable } from "fflate";
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
import type { EntityKind, FamilyBond, Prisma, WeekPattern } from "@prisma/client";
import { buildExport, importBook, readImportFile } from "./book-transfer";
import { prisma } from "./db";
import { deleteImage } from "./files";
@@ -35,8 +35,13 @@ type Snapshot = {
description: string | null;
data: Prisma.JsonValue;
members: string[];
// Saknas i ögonblicksbilder från före släktträdet och tidslinjen
bond?: FamilyBond | null;
startDate?: string | null;
endDate?: string | null;
}[];
memberOf: string[]; // relationer som posten deltog i som extra deltagare
eventIds?: string[]; // tidslinjens händelser som posten deltog i
shifts: {
workplaceId: string | null;
weekday: number;
@@ -60,6 +65,7 @@ export async function trashEntity(ownerId: string, bookId: string, entityId: str
outgoing: { include: { members: true } },
incoming: { include: { members: true } },
memberOf: true,
events: { select: { eventId: true } },
shifts: true,
hostedShifts: { select: { id: true } },
markers: { select: { id: true } },
@@ -87,8 +93,12 @@ export async function trashEntity(ownerId: string, bookId: string, entityId: str
description: r.description,
data: r.data,
members: r.members.map((m) => m.entityId),
bond: r.bond,
startDate: r.startDate,
endDate: r.endDate,
})),
memberOf: entity.memberOf.map((m) => m.relationId),
eventIds: entity.events.map((e) => e.eventId),
shifts: entity.shifts.map((s) => ({
workplaceId: s.workplaceId,
weekday: s.weekday,
@@ -165,6 +175,9 @@ export async function restoreEntity(ownerId: string, trashId: string): Promise<{
toId: r.toId,
type: r.type,
description: r.description,
bond: r.bond ?? null,
startDate: r.startDate ?? null,
endDate: r.endDate ?? null,
data: (r.data ?? {}) as Prisma.InputJsonObject,
members: { create: r.members.filter((m) => others.has(m) && m !== r.fromId && m !== r.toId).map((entityId) => ({ entityId })) },
},
@@ -178,6 +191,11 @@ export async function restoreEntity(ownerId: string, trashId: string): Promise<{
}
}
if (snap.eventIds?.length) {
const events = await tx.storyEvent.findMany({ where: { id: { in: snap.eventIds }, bookId }, select: { id: true } });
await tx.eventParticipant.createMany({ data: events.map((e) => ({ eventId: e.id, entityId: snap.entity.id })), skipDuplicates: true });
}
for (const s of snap.shifts) {
await tx.shift.create({
data: {