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:
1 parent
dcb5d43429
commit
bd269d70a5
32 files changed
+2284
-24
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
# Bokplanerare
|
# Bokplanerare
|
||||||
|
|
||||||
Webbaserat planeringsverktyg för författare. Flera böcker, var och en med karaktärer, husdjur, bostäder, platser, företag, lokaler, scenarier, relationer, arbetsscheman och kartor med markeringar.
|
Webbaserat planeringsverktyg för författare. Flera böcker, var och en med karaktärer, husdjur, bostäder, platser, företag, lokaler, scenarier, relationer, släktträd, tidslinje, arbetsscheman och kartor med markeringar.
|
||||||
|
|
||||||
- **Next.js 15** (App Router, TypeScript) med utseende från **Tabler**
|
- **Next.js 15** (App Router, TypeScript) med utseende från **Tabler**
|
||||||
- **PostgreSQL** via Prisma
|
- **PostgreSQL** via Prisma
|
||||||
@@ -117,6 +117,26 @@ Standardmallarna använder det för Lokal och Skiss i Företag, Lokal, Bostad oc
|
|||||||
|
|
||||||
Ändrar du en mall försvinner ingen data: värden för borttagna fält finns kvar i databasen.
|
Ändrar du en mall försvinner ingen data: värden för borttagna fält finns kvar i databasen.
|
||||||
|
|
||||||
|
## Släktträd och tidslinje
|
||||||
|
|
||||||
|
**Datum.** Datum i berättelsen skrivs som `ÅÅÅÅ`, `ÅÅÅÅ-MM` eller `ÅÅÅÅ-MM-DD`, så att året räcker när resten inte är bestämt. Berättelsens tid kan ligga var som helst, även före år 1900 eller i framtiden. Gäller alla datumfält i mallarna, relationernas period och händelser. Åldern räknas i hela år när månad och dag är kända, annars som skillnaden i år.
|
||||||
|
|
||||||
|
**Släktträd** (menyn *Planering*). Trädet ritas av relationer som har ett **släktband**, som du väljer när du skapar eller ändrar en relation:
|
||||||
|
|
||||||
|
- *Förälder till*: gäller från den första till den andra och de extra deltagarna, så en förälder med flera barn blir en relation.
|
||||||
|
- *Partner till* och *Syskon till*: gäller alla deltagare. Partner ritas bredvid varandra och syskon hamnar i samma generation.
|
||||||
|
|
||||||
|
Generationerna räknas ut automatiskt, partner ritas bredvid varandra och barn mitt under sina föräldrar. Under rullistan kan du visa bara släkten kring en person. Relationer som redan hette ”Förälder till”, ”Barn till”, ”Partner till” eller ”Syskon till” (och motsvarande på engelska) får rätt släktband automatiskt vid uppdateringen. ”Barn till” vänds då till ”Förälder till” åt andra hållet. Lämnar du relationstexten tom får relationen släktbandets namn.
|
||||||
|
|
||||||
|
**Tidslinje** (menyn *Planering*). Samlar datum från hela boken i en lista per år, med ålder vid varje tillfälle:
|
||||||
|
|
||||||
|
- Födelse och död, från fälten *Födelsedatum* och *Dödsdatum* i karaktärsmallen. (Har du en egen karaktärsmall, lägg till ett datumfält med nyckeln `deathDate`.)
|
||||||
|
- Scenarier, från det nya fältet *Datum i berättelsen*. Scenarier utan datum listas för sig. Deltagare är de karaktärer som är kopplade till scenariot via en relation eller via fältet *Kopplat till*.
|
||||||
|
- Egna händelser med datum, valfritt slutdatum, beskrivning och deltagare. De läggs till på tidslinjens sida.
|
||||||
|
- Relationer med *Gäller från* och *Gäller till*, till exempel ett äktenskap 2004–2011.
|
||||||
|
|
||||||
|
Händelser och relationer med slutdatum visas dessutom som staplar under *Perioder*. Du kan filtrera på person och på typ av händelse.
|
||||||
|
|
||||||
## Export och import
|
## Export och import
|
||||||
|
|
||||||
Under *Bokinställningar* exporterar du hela boken:
|
Under *Bokinställningar* exporterar du hela boken:
|
||||||
@@ -124,7 +144,7 @@ Under *Bokinställningar* exporterar du hela boken:
|
|||||||
- **Med bilder (.zip):** innehåller `book.json` och alla bilder i `files/`. Det är den fullständiga säkerhetskopian.
|
- **Med bilder (.zip):** innehåller `book.json` och alla bilder i `files/`. Det är den fullständiga säkerhetskopian.
|
||||||
- **Bara data (.json):** samma innehåll utan bilder, för snabb jämförelse eller redigering.
|
- **Bara data (.json):** samma innehåll utan bilder, för snabb jämförelse eller redigering.
|
||||||
|
|
||||||
Exporten innehåller poster (med ID, taggar och mallfält), relationer med deltagare, scheman, kartor med markeringar, mallar och bilderna.
|
Exporten innehåller poster (med ID, taggar och mallfält), relationer med deltagare, släktband och perioder, händelser, scheman, kartor med markeringar, mallar och bilderna.
|
||||||
|
|
||||||
På startsidan *Mina böcker* importerar du en exportfil (.zip eller .json). Importen **skapar alltid en ny bok** och skriver aldrig över något. Alla poster får nya interna id, och kopplingar mellan dem (relationer, kopplingsfält i mallar, markeringar och scheman) pekar om till de nya. ID som KI-0001 behålls, och räknarna fortsätter därefter. Finns redan en bok med samma titel får den nya tillägget *(import)*. Poster, bilder och kopplingar som saknas eller är ogiltiga i filen hoppas över, och antalet visas efteråt. Filen kan flyttas mellan installationer, till exempel från dev till prod.
|
På startsidan *Mina böcker* importerar du en exportfil (.zip eller .json). Importen **skapar alltid en ny bok** och skriver aldrig över något. Alla poster får nya interna id, och kopplingar mellan dem (relationer, kopplingsfält i mallar, markeringar och scheman) pekar om till de nya. ID som KI-0001 behålls, och räknarna fortsätter därefter. Finns redan en bok med samma titel får den nya tillägget *(import)*. Poster, bilder och kopplingar som saknas eller är ogiltiga i filen hoppas över, och antalet visas efteråt. Filen kan flyttas mellan installationer, till exempel från dev till prod.
|
||||||
|
|
||||||
@@ -158,7 +178,7 @@ Appar och Hemsidor har inget ID. Prefixen ligger samlade i `src/lib/ids.ts`. Sid
|
|||||||
|
|
||||||
**Säkerhetskopior.** Varje natt (klockan `BACKUP_HOUR`, standard 03:00 i `TZ`) sparas en zip per bok med bilder i `./data/backups/<tidpunkt>/`. De `BACKUP_KEEP` senaste körningarna (standard 14) behålls. Zip-filerna är samma format som exporten och importeras via *Importera bok*. Missade körningar tas igen vid nästa start. Administratören kan köra en säkerhetskopia direkt och ladda ner filerna på *Administration*. Kopiera gärna `backups/` till en annan maskin.
|
**Säkerhetskopior.** Varje natt (klockan `BACKUP_HOUR`, standard 03:00 i `TZ`) sparas en zip per bok med bilder i `./data/backups/<tidpunkt>/`. De `BACKUP_KEEP` senaste körningarna (standard 14) behålls. Zip-filerna är samma format som exporten och importeras via *Importera bok*. Missade körningar tas igen vid nästa start. Administratören kan köra en säkerhetskopia direkt och ladda ner filerna på *Administration*. Kopiera gärna `backups/` till en annan maskin.
|
||||||
|
|
||||||
**Papperskorg.** Borttagna poster och böcker flyttas till papperskorgen i `TRASH_DAYS` dagar (standard 30) och kan återställas. En post återställs med sina relationer, scheman och markeringar, och behåller sitt ID. En bok sparas som zip i `./data/trash` och återställs som en ny bok. Papperskorgen rensas automatiskt.
|
**Papperskorg.** Borttagna poster och böcker flyttas till papperskorgen i `TRASH_DAYS` dagar (standard 30) och kan återställas. En post återställs med sina relationer (med släktband och perioder), deltagande i händelser, scheman och markeringar, och behåller sitt ID. En bok sparas som zip i `./data/trash` och återställs som en ny bok. Papperskorgen rensas automatiskt.
|
||||||
|
|
||||||
**Ändringshistorik.** Varje ändring av en post sparar den tidigare versionen (de `MAX_VERSIONS` senaste, standard 30). *Historik* på postens sida visar skillnaderna fält för fält och kan återställa en tidigare version. Att återställa sparar först den nuvarande, så det går att ångra. Bilder ingår inte i historiken.
|
**Ändringshistorik.** Varje ändring av en post sparar den tidigare versionen (de `MAX_VERSIONS` senaste, standard 30). *Historik* på postens sida visar skillnaderna fält för fält och kan återställa en tidigare version. Att återställa sparar först den nuvarande, så det går att ångra. Bilder ingår inte i historiken.
|
||||||
|
|
||||||
@@ -198,10 +218,10 @@ Namnen viktas efter hur vanliga de var, så en man född 1960 blir oftare Anders
|
|||||||
|
|
||||||
## Tester
|
## Tester
|
||||||
|
|
||||||
Testerna körs med Vitest (`npm test`). Det finns cirka 170 tester:
|
Testerna körs med Vitest (`npm test`). Det finns cirka 240 tester:
|
||||||
|
|
||||||
- **Enhetstester utan databas** (`tests/unit`): mallar och deras validering, ID-prefix, hastighetsbegränsning, säkerhetsrubriker, namngenerering, historikens jämförelser, bildbehandling (storlek, EXIF-rotation, borttagen metadata) och läsning och kontroll av importfiler (inklusive skydd mot för stora filer).
|
- **Enhetstester utan databas** (`tests/unit`): datum och åldersberäkning, släktträdets layout, tidslinjens sammanställning, mallar och deras validering, ID-prefix, hastighetsbegränsning, säkerhetsrubriker, namngenerering, historikens jämförelser, bildbehandling (storlek, EXIF-rotation, borttagen metadata) och läsning och kontroll av importfiler (inklusive skydd mot för stora filer).
|
||||||
- **Databastester** (`tests/db`): löpande ID (även vid samtidiga anrop), export och import fram och tillbaka med bilder och kopplingar, papperskorg (poster och böcker), historikens gräns, fältvärden och kopplingskontroller, säkerhetskopiering (rensning, schema, att zip-filerna går att importera), lagringskvot, administratör och sök.
|
- **Databastester** (`tests/db`): löpande ID (även vid samtidiga anrop), export och import fram och tillbaka med bilder och kopplingar, släktband, perioder och händelser (även i papperskorgen), papperskorg (poster och böcker), historikens gräns, fältvärden och kopplingskontroller, säkerhetskopiering (rensning, schema, att zip-filerna går att importera), lagringskvot, administratör och sök.
|
||||||
|
|
||||||
Databastesterna behöver en PostgreSQL-databas och använder alltid en **egen testdatabas** vars namn slutar på `_test`. De tömmer den mellan testerna och vägrar köra mot en databas med något annat namn, så din riktiga data berörs aldrig. Databasen skapas och migreras automatiskt första gången.
|
Databastesterna behöver en PostgreSQL-databas och använder alltid en **egen testdatabas** vars namn slutar på `_test`. De tömmer den mellan testerna och vägrar köra mot en databas med något annat namn, så din riktiga data berörs aldrig. Databasen skapas och migreras automatiskt första gången.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "FamilyBond" AS ENUM ('PARENT', 'PARTNER', 'SIBLING');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Relation" ADD COLUMN "bond" "FamilyBond",
|
||||||
|
ADD COLUMN "endDate" TEXT,
|
||||||
|
ADD COLUMN "startDate" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "StoryEvent" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"bookId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"date" TEXT NOT NULL,
|
||||||
|
"endDate" TEXT,
|
||||||
|
"description" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "StoryEvent_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "EventParticipant" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"eventId" TEXT NOT NULL,
|
||||||
|
"entityId" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "EventParticipant_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "StoryEvent_bookId_idx" ON "StoryEvent"("bookId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "EventParticipant_entityId_idx" ON "EventParticipant"("entityId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "EventParticipant_eventId_entityId_key" ON "EventParticipant"("eventId", "entityId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "StoryEvent" ADD CONSTRAINT "StoryEvent_bookId_fkey" FOREIGN KEY ("bookId") REFERENCES "Book"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "EventParticipant" ADD CONSTRAINT "EventParticipant_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "StoryEvent"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "EventParticipant" ADD CONSTRAINT "EventParticipant_entityId_fkey" FOREIGN KEY ("entityId") REFERENCES "Entity"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Befintliga relationer med de vanliga förslagstexterna blir släktband
|
||||||
|
UPDATE "Relation" SET "bond" = 'PARENT' WHERE lower("type") IN ('förälder till', 'parent of');
|
||||||
|
UPDATE "Relation" SET "bond" = 'PARTNER' WHERE lower("type") IN ('partner till', 'partner of');
|
||||||
|
UPDATE "Relation" SET "bond" = 'SIBLING' WHERE lower("type") IN ('syskon till', 'sibling of');
|
||||||
|
|
||||||
|
-- "Barn till" vänds till "Förälder till" åt andra hållet (bara när relationen saknar extra deltagare)
|
||||||
|
UPDATE "Relation" r
|
||||||
|
SET "bond" = 'PARENT',
|
||||||
|
"fromId" = r."toId",
|
||||||
|
"toId" = r."fromId",
|
||||||
|
"type" = CASE WHEN lower(r."type") = 'child of' THEN 'Parent of' ELSE 'Förälder till' END
|
||||||
|
WHERE lower(r."type") IN ('barn till', 'child of')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM "RelationMember" m WHERE m."relationId" = r."id");
|
||||||
@@ -36,6 +36,14 @@ enum WeekPattern {
|
|||||||
EVEN
|
EVEN
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Släktband på en relation. PARENT: från-posten är förälder till till-posten (och till extra deltagare).
|
||||||
|
// PARTNER och SIBLING gäller alla deltagare i relationen.
|
||||||
|
enum FamilyBond {
|
||||||
|
PARENT
|
||||||
|
PARTNER
|
||||||
|
SIBLING
|
||||||
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
// "<provider>:<subject>", t.ex. "authentik:abc123"
|
// "<provider>:<subject>", t.ex. "authentik:abc123"
|
||||||
@@ -65,6 +73,7 @@ model Book {
|
|||||||
templates Template[]
|
templates Template[]
|
||||||
counters IdCounter[]
|
counters IdCounter[]
|
||||||
versions EntityVersion[]
|
versions EntityVersion[]
|
||||||
|
events StoryEvent[]
|
||||||
|
|
||||||
@@index([ownerId])
|
@@index([ownerId])
|
||||||
}
|
}
|
||||||
@@ -92,6 +101,7 @@ model Entity {
|
|||||||
hostedShifts Shift[] @relation("ShiftWorkplace")
|
hostedShifts Shift[] @relation("ShiftWorkplace")
|
||||||
markers Marker[]
|
markers Marker[]
|
||||||
memberOf RelationMember[]
|
memberOf RelationMember[]
|
||||||
|
events EventParticipant[]
|
||||||
|
|
||||||
@@unique([bookId, code])
|
@@unique([bookId, code])
|
||||||
@@index([bookId, kind])
|
@@index([bookId, kind])
|
||||||
@@ -106,6 +116,11 @@ model Relation {
|
|||||||
type String
|
type String
|
||||||
description String? @db.Text
|
description String? @db.Text
|
||||||
data Json @default("{}")
|
data Json @default("{}")
|
||||||
|
// Släktband för släktträdet, tomt för vanliga relationer
|
||||||
|
bond FamilyBond?
|
||||||
|
// Period som relationen gällde, "ÅÅÅÅ", "ÅÅÅÅ-MM" eller "ÅÅÅÅ-MM-DD" (se src/lib/story-date.ts)
|
||||||
|
startDate String?
|
||||||
|
endDate String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
|
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
|
||||||
@@ -210,6 +225,34 @@ model RelationMember {
|
|||||||
@@index([entityId])
|
@@index([entityId])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Händelse på tidslinjen. Datum skrivs som "ÅÅÅÅ", "ÅÅÅÅ-MM" eller "ÅÅÅÅ-MM-DD".
|
||||||
|
model StoryEvent {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
bookId String
|
||||||
|
title String
|
||||||
|
date String
|
||||||
|
endDate String?
|
||||||
|
description String? @db.Text
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
|
||||||
|
participants EventParticipant[]
|
||||||
|
|
||||||
|
@@index([bookId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model EventParticipant {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
eventId String
|
||||||
|
entityId String
|
||||||
|
|
||||||
|
event StoryEvent @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||||
|
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([eventId, entityId])
|
||||||
|
@@index([entityId])
|
||||||
|
}
|
||||||
|
|
||||||
// Löpande nummer per bok och ID-typ, t.ex. key "KI" eller "KD-R"
|
// Löpande nummer per bok och ID-typ, t.ex. key "KI" eller "KD-R"
|
||||||
model IdCounter {
|
model IdCounter {
|
||||||
bookId String
|
bookId String
|
||||||
|
|||||||
@@ -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`);
|
||||||
|
}
|
||||||
@@ -3,12 +3,14 @@
|
|||||||
import type { Prisma } from "@prisma/client";
|
import type { Prisma } from "@prisma/client";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
|
import { parseBond } from "@/lib/family";
|
||||||
import { optStr, revalidateBook, str } from "@/lib/form";
|
import { optStr, revalidateBook, str } from "@/lib/form";
|
||||||
import { collectFieldData } from "@/lib/field-values";
|
import { collectFieldData } from "@/lib/field-values";
|
||||||
import { nextRelationCode } from "@/lib/ids";
|
import { nextRelationCode } from "@/lib/ids";
|
||||||
import { requireBook } from "@/lib/session";
|
import { requireBook } from "@/lib/session";
|
||||||
|
import { normalizeStoryDate } from "@/lib/story-date";
|
||||||
import { getTemplate } from "@/lib/templates";
|
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. */
|
/** 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[]> {
|
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);
|
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) {
|
export async function addRelation(formData: FormData) {
|
||||||
const book = await requireBook(str(formData, "bookId"));
|
const book = await requireBook(str(formData, "bookId"));
|
||||||
const fromId = str(formData, "fromId");
|
const fromId = str(formData, "fromId");
|
||||||
const toId = str(formData, "toId");
|
const toId = str(formData, "toId");
|
||||||
const type = str(formData, "type", 100);
|
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
|
||||||
if (!fromId || !toId || !type || fromId === toId) return;
|
if (!fromId || !toId || !type || fromId === toId || !ok) return;
|
||||||
|
|
||||||
// Båda posterna måste höra till boken
|
// Båda posterna måste höra till boken
|
||||||
const count = await prisma.entity.count({ where: { bookId: book.id, id: { in: [fromId, toId] } } });
|
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,
|
fromId,
|
||||||
toId,
|
toId,
|
||||||
type,
|
type,
|
||||||
|
bond,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
description: optStr(formData, "description", 2000),
|
description: optStr(formData, "description", 2000),
|
||||||
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
||||||
},
|
},
|
||||||
@@ -50,8 +69,8 @@ export async function saveRelation(formData: FormData) {
|
|||||||
const book = await requireBook(str(formData, "bookId"));
|
const book = await requireBook(str(formData, "bookId"));
|
||||||
const relation = await prisma.relation.findFirst({ where: { id: str(formData, "id"), bookId: book.id } });
|
const relation = await prisma.relation.findFirst({ where: { id: str(formData, "id"), bookId: book.id } });
|
||||||
if (!relation) throw new Error("Relation not found");
|
if (!relation) throw new Error("Relation not found");
|
||||||
const type = str(formData, "type", 100);
|
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
|
||||||
if (!type) return;
|
if (!type || !ok) return;
|
||||||
|
|
||||||
const { fields } = await getTemplate(book.id, "RELATION", await getLocale());
|
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);
|
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 },
|
where: { id: relation.id },
|
||||||
data: {
|
data: {
|
||||||
type,
|
type,
|
||||||
|
bond,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
description: optStr(formData, "description", 2000),
|
description: optStr(formData, "description", 2000),
|
||||||
data: data as Prisma.InputJsonObject,
|
data: data as Prisma.InputJsonObject,
|
||||||
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
||||||
|
|||||||
@@ -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 { ConfirmSubmit } from "@/components/confirm-submit";
|
||||||
import { EntitySelect } from "@/components/entity-select";
|
import { EntitySelect } from "@/components/entity-select";
|
||||||
import { FieldInput } from "@/components/entity-form";
|
import { FieldInput } from "@/components/entity-form";
|
||||||
|
import { RelationBondFields } from "@/components/relation-bond-fields";
|
||||||
import { PageBody, PageHeader } from "@/components/page";
|
import { PageBody, PageHeader } from "@/components/page";
|
||||||
import { getT } from "@/i18n/server";
|
import { getT } from "@/i18n/server";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
@@ -102,7 +103,7 @@ export default async function RelationPage({
|
|||||||
<div className="row g-3">
|
<div className="row g-3">
|
||||||
<div className="col-md-6">
|
<div className="col-md-6">
|
||||||
<label className="form-label required">{t("relation.type")}</label>
|
<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">
|
<datalist id="relation-types">
|
||||||
{suggestions.map((s) => (
|
{suggestions.map((s) => (
|
||||||
<option key={s} value={s} />
|
<option key={s} value={s} />
|
||||||
@@ -124,6 +125,7 @@ export default async function RelationPage({
|
|||||||
/>
|
/>
|
||||||
<div className="form-hint">{t("relation.membersHelp")}</div>
|
<div className="form-hint">{t("relation.membersHelp")}</div>
|
||||||
</div>
|
</div>
|
||||||
|
<RelationBondFields t={t} bond={relation.bond} startDate={relation.startDate} endDate={relation.endDate} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -107,6 +107,11 @@ export default async function RelationsPage({
|
|||||||
{r.type}
|
{r.type}
|
||||||
</Link>
|
</Link>
|
||||||
{r.code ? <span className="badge ms-2">{r.code}</span> : null}
|
{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>
|
||||||
<td>
|
<td>
|
||||||
{[r.to, ...r.members.map((m) => m.entity)].map((e, i) => (
|
{[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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import Link from "next/link";
|
|||||||
import type { Entity, EntityKind } from "@prisma/client";
|
import type { Entity, EntityKind } from "@prisma/client";
|
||||||
import type { TFunction } from "@/i18n/core";
|
import type { TFunction } from "@/i18n/core";
|
||||||
import { NameFill } from "./name-fill";
|
import { NameFill } from "./name-fill";
|
||||||
|
import { StoryDateInput } from "./story-date-input";
|
||||||
import { fileUrl } from "@/lib/files";
|
import { fileUrl } from "@/lib/files";
|
||||||
import { KINDS } from "@/lib/kinds";
|
import { KINDS } from "@/lib/kinds";
|
||||||
import type { FieldDef } from "@/lib/templates";
|
import type { FieldDef } from "@/lib/templates";
|
||||||
@@ -30,7 +31,7 @@ export function FieldInput({
|
|||||||
case "number":
|
case "number":
|
||||||
return <input type="number" step="any" name={name} className="form-control" defaultValue={text} />;
|
return <input type="number" step="any" name={name} className="form-control" defaultValue={text} />;
|
||||||
case "date":
|
case "date":
|
||||||
return <input type="date" name={name} className="form-control" defaultValue={text} />;
|
return <StoryDateInput name={name} defaultValue={text} />;
|
||||||
case "url":
|
case "url":
|
||||||
return <input type="url" name={name} className="form-control" defaultValue={text} placeholder="https://" />;
|
return <input type="url" name={name} className="form-control" defaultValue={text} placeholder="https://" />;
|
||||||
case "checkbox":
|
case "checkbox":
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { addRelation } from "@/actions/relations";
|
import { addRelation } from "@/actions/relations";
|
||||||
import type { TFunction } from "@/i18n/core";
|
import type { TFunction } from "@/i18n/core";
|
||||||
import { EntitySelect, type EntityOption } from "./entity-select";
|
import { EntitySelect, type EntityOption } from "./entity-select";
|
||||||
|
import { RelationBondFields } from "./relation-bond-fields";
|
||||||
|
|
||||||
export function RelationForm({
|
export function RelationForm({
|
||||||
bookId,
|
bookId,
|
||||||
@@ -30,7 +31,7 @@ export function RelationForm({
|
|||||||
)}
|
)}
|
||||||
<div className="col-md-6">
|
<div className="col-md-6">
|
||||||
<label className="form-label">{t("relation.type")}</label>
|
<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}>
|
<datalist id={listId}>
|
||||||
{suggestions.map((s) => (
|
{suggestions.map((s) => (
|
||||||
<option key={s} value={s} />
|
<option key={s} value={s} />
|
||||||
@@ -50,6 +51,7 @@ export function RelationForm({
|
|||||||
<EntitySelect name="memberIds" entities={others} t={t} multiple />
|
<EntitySelect name="memberIds" entities={others} t={t} multiple />
|
||||||
<div className="form-hint">{t("relation.membersHelp")}</div>
|
<div className="form-hint">{t("relation.membersHelp")}</div>
|
||||||
</div>
|
</div>
|
||||||
|
<RelationBondFields t={t} />
|
||||||
<div className="col-12 text-end">
|
<div className="col-12 text-end">
|
||||||
<button type="submit" className="btn btn-primary">
|
<button type="submit" className="btn btn-primary">
|
||||||
{t("relation.add")}
|
{t("relation.add")}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import {
|
|||||||
IconMap2,
|
IconMap2,
|
||||||
IconServerCog,
|
IconServerCog,
|
||||||
IconSettings,
|
IconSettings,
|
||||||
|
IconSitemap,
|
||||||
|
IconTimeline,
|
||||||
IconTrash,
|
IconTrash,
|
||||||
IconTemplate,
|
IconTemplate,
|
||||||
IconBooks,
|
IconBooks,
|
||||||
@@ -47,6 +49,8 @@ export async function Shell({ user, book, children }: ShellProps) {
|
|||||||
{ label: t("nav.overview"), href: base },
|
{ label: t("nav.overview"), href: base },
|
||||||
...KINDS.map((k) => ({ label: t(`kind.${k.kind}.other`), href: `${base}/e/${k.slug}` })),
|
...KINDS.map((k) => ({ label: t(`kind.${k.kind}.other`), href: `${base}/e/${k.slug}` })),
|
||||||
{ label: t("nav.relations"), href: `${base}/relations` },
|
{ 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.schedules"), href: `${base}/schedules` },
|
||||||
{ label: t("nav.maps"), href: `${base}/maps` },
|
{ label: t("nav.maps"), href: `${base}/maps` },
|
||||||
{ label: t("nav.names"), href: `${base}/names` },
|
{ 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} />}>
|
<NavLink href={`${base}/relations`} icon={<IconChartDots3 size={20} />}>
|
||||||
{t("nav.relations")}
|
{t("nav.relations")}
|
||||||
</NavLink>
|
</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} />}>
|
<NavLink href={`${base}/schedules`} icon={<IconCalendarWeek size={20} />}>
|
||||||
{t("nav.schedules")}
|
{t("nav.schedules")}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|||||||
@@ -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
@@ -45,6 +45,8 @@ export const en: Record<keyof typeof sv, string> = {
|
|||||||
"nav.world": "World",
|
"nav.world": "World",
|
||||||
"nav.planning": "Planning",
|
"nav.planning": "Planning",
|
||||||
"nav.relations": "Relationships",
|
"nav.relations": "Relationships",
|
||||||
|
"nav.family": "Family tree",
|
||||||
|
"nav.timeline": "Timeline",
|
||||||
"nav.schedules": "Schedules",
|
"nav.schedules": "Schedules",
|
||||||
"nav.maps": "Maps",
|
"nav.maps": "Maps",
|
||||||
"nav.templates": "Templates",
|
"nav.templates": "Templates",
|
||||||
@@ -273,7 +275,52 @@ export const en: Record<keyof typeof sv, string> = {
|
|||||||
"relation.empty": "No relationships yet.",
|
"relation.empty": "No relationships yet.",
|
||||||
"relation.filter": "Show relationships for",
|
"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.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.title": "Schedules",
|
||||||
"schedule.add": "Add shift",
|
"schedule.add": "Add shift",
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ export const sv = {
|
|||||||
"nav.world": "Världen",
|
"nav.world": "Världen",
|
||||||
"nav.planning": "Planering",
|
"nav.planning": "Planering",
|
||||||
"nav.relations": "Relationer",
|
"nav.relations": "Relationer",
|
||||||
|
"nav.family": "Släktträd",
|
||||||
|
"nav.timeline": "Tidslinje",
|
||||||
"nav.schedules": "Scheman",
|
"nav.schedules": "Scheman",
|
||||||
"nav.maps": "Kartor",
|
"nav.maps": "Kartor",
|
||||||
"nav.templates": "Mallar",
|
"nav.templates": "Mallar",
|
||||||
@@ -272,6 +274,51 @@ export const sv = {
|
|||||||
"relation.filter": "Visa relationer för",
|
"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.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.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.title": "Scheman",
|
||||||
"schedule.add": "Lägg till arbetspass",
|
"schedule.add": "Lägg till arbetspass",
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { strFromU8, unzipSync } from "fflate";
|
import { strFromU8, unzipSync } from "fflate";
|
||||||
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
|
import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
|
||||||
|
import { parseBond, type FamilyBondKind } from "./family";
|
||||||
|
import { normalizeStoryDate } from "./story-date";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { deleteImage, readImageBytes, saveImageBytes } from "./files";
|
import { deleteImage, readImageBytes, saveImageBytes } from "./files";
|
||||||
import type { ImageKind } from "./images";
|
import type { ImageKind } from "./images";
|
||||||
@@ -57,6 +59,16 @@ export type ExportData = {
|
|||||||
description: string | null;
|
description: string | null;
|
||||||
data: Record<string, Json>;
|
data: Record<string, Json>;
|
||||||
members: string[];
|
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: {
|
shifts: {
|
||||||
personId: string;
|
personId: string;
|
||||||
@@ -98,6 +110,7 @@ export async function buildExport(bookId: string, withImages: boolean) {
|
|||||||
include: {
|
include: {
|
||||||
entities: { orderBy: { createdAt: "asc" } },
|
entities: { orderBy: { createdAt: "asc" } },
|
||||||
relations: { orderBy: { createdAt: "asc" }, include: { members: true } },
|
relations: { orderBy: { createdAt: "asc" }, include: { members: true } },
|
||||||
|
events: { orderBy: { createdAt: "asc" }, include: { participants: true } },
|
||||||
shifts: { orderBy: { createdAt: "asc" } },
|
shifts: { orderBy: { createdAt: "asc" } },
|
||||||
maps: { orderBy: { createdAt: "asc" }, include: { markers: { orderBy: { createdAt: "asc" } } } },
|
maps: { orderBy: { createdAt: "asc" }, include: { markers: { orderBy: { createdAt: "asc" } } } },
|
||||||
templates: true,
|
templates: true,
|
||||||
@@ -166,6 +179,16 @@ export async function buildExport(bookId: string, withImages: boolean) {
|
|||||||
description: r.description,
|
description: r.description,
|
||||||
data: (r.data ?? {}) as Record<string, Json>,
|
data: (r.data ?? {}) as Record<string, Json>,
|
||||||
members: r.members.map((m) => m.entityId),
|
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) => ({
|
shifts: book.shifts.map((s) => ({
|
||||||
personId: s.personId,
|
personId: s.personId,
|
||||||
@@ -246,6 +269,22 @@ export function parseExport(raw: unknown): ExportData {
|
|||||||
description: text(item.description, 2000),
|
description: text(item.description, 2000),
|
||||||
data: object(item.data),
|
data: object(item.data),
|
||||||
members: Array.isArray(item.members) ? item.members.map((m) => text(m, 100)).filter((m): m is string => !!m) : [],
|
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,
|
entities,
|
||||||
relations,
|
relations,
|
||||||
|
events,
|
||||||
shifts,
|
shifts,
|
||||||
maps,
|
maps,
|
||||||
templates,
|
templates,
|
||||||
@@ -379,6 +419,7 @@ export type ImportResult = {
|
|||||||
bookId: string;
|
bookId: string;
|
||||||
entities: number;
|
entities: number;
|
||||||
relations: number;
|
relations: number;
|
||||||
|
events: number;
|
||||||
maps: number;
|
maps: number;
|
||||||
markers: number;
|
markers: number;
|
||||||
shifts: number;
|
shifts: number;
|
||||||
@@ -535,6 +576,9 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
|
|||||||
type: r.type,
|
type: r.type,
|
||||||
description: r.description,
|
description: r.description,
|
||||||
data: remapIds(r.data, entityIds) as Prisma.InputJsonObject,
|
data: remapIds(r.data, entityIds) as Prisma.InputJsonObject,
|
||||||
|
bond: r.bond,
|
||||||
|
startDate: r.startDate,
|
||||||
|
endDate: r.endDate,
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
await tx.relationMember.createMany({
|
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({
|
await tx.shift.createMany({
|
||||||
data: groupList.flatMap((g) =>
|
data: groupList.flatMap((g) =>
|
||||||
g.shifts.map((s) => ({
|
g.shifts.map((s) => ({
|
||||||
@@ -606,6 +663,7 @@ export async function importBook(ownerId: string, data: ExportData, files: Map<s
|
|||||||
bookId,
|
bookId,
|
||||||
entities: entities.length,
|
entities: entities.length,
|
||||||
relations: relations.length,
|
relations: relations.length,
|
||||||
|
events: data.events.length,
|
||||||
maps: maps.length,
|
maps: maps.length,
|
||||||
markers: markers.length,
|
markers: markers.length,
|
||||||
shifts: shiftsIn.length,
|
shifts: shiftsIn.length,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { str } from "./form";
|
import { str } from "./form";
|
||||||
|
import { normalizeStoryDate } from "./story-date";
|
||||||
import type { FieldDef } from "./templates";
|
import type { FieldDef } from "./templates";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,6 +25,10 @@ export async function collectFieldData(
|
|||||||
const raw = str(formData, name, 20000);
|
const raw = str(formData, name, 20000);
|
||||||
if (raw === "") {
|
if (raw === "") {
|
||||||
delete data[field.key];
|
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") {
|
} else if (field.type === "number") {
|
||||||
const n = Number(raw.replace(",", "."));
|
const n = Number(raw.replace(",", "."));
|
||||||
if (Number.isFinite(n)) data[field.key] = n;
|
if (Number.isFinite(n)) data[field.key] = n;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -37,6 +37,7 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
|||||||
f("nickname", ["Smeknamn", "Nickname"], "text", ["Grunduppgifter", "Basics"]),
|
f("nickname", ["Smeknamn", "Nickname"], "text", ["Grunduppgifter", "Basics"]),
|
||||||
f("age", ["Ålder", "Age"], "number"),
|
f("age", ["Ålder", "Age"], "number"),
|
||||||
f("birthDate", ["Födelsedatum", "Date of birth"], "date"),
|
f("birthDate", ["Födelsedatum", "Date of birth"], "date"),
|
||||||
|
f("deathDate", ["Dödsdatum", "Date of death"], "date"),
|
||||||
f("height", ["Längd", "Height"]),
|
f("height", ["Längd", "Height"]),
|
||||||
f("gender", ["Kön", "Gender"]),
|
f("gender", ["Kön", "Gender"]),
|
||||||
f("orientation", ["Läggning", "Orientation"]),
|
f("orientation", ["Läggning", "Orientation"]),
|
||||||
@@ -206,7 +207,8 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
|||||||
["Grunduppgifter", "Basics"],
|
["Grunduppgifter", "Basics"],
|
||||||
),
|
),
|
||||||
ref("linkedEntity", ["Kopplat till (post)", "Linked to (item)"]),
|
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("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("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"]),
|
area("impactAfter", ["Hur påverkas karaktärerna efter scenariot", "How the characters are affected afterwards"]),
|
||||||
|
|||||||
@@ -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
@@ -1,7 +1,7 @@
|
|||||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { strToU8, zipSync, type Zippable } from "fflate";
|
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 { buildExport, importBook, readImportFile } from "./book-transfer";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { deleteImage } from "./files";
|
import { deleteImage } from "./files";
|
||||||
@@ -35,8 +35,13 @@ type Snapshot = {
|
|||||||
description: string | null;
|
description: string | null;
|
||||||
data: Prisma.JsonValue;
|
data: Prisma.JsonValue;
|
||||||
members: string[];
|
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
|
memberOf: string[]; // relationer som posten deltog i som extra deltagare
|
||||||
|
eventIds?: string[]; // tidslinjens händelser som posten deltog i
|
||||||
shifts: {
|
shifts: {
|
||||||
workplaceId: string | null;
|
workplaceId: string | null;
|
||||||
weekday: number;
|
weekday: number;
|
||||||
@@ -60,6 +65,7 @@ export async function trashEntity(ownerId: string, bookId: string, entityId: str
|
|||||||
outgoing: { include: { members: true } },
|
outgoing: { include: { members: true } },
|
||||||
incoming: { include: { members: true } },
|
incoming: { include: { members: true } },
|
||||||
memberOf: true,
|
memberOf: true,
|
||||||
|
events: { select: { eventId: true } },
|
||||||
shifts: true,
|
shifts: true,
|
||||||
hostedShifts: { select: { id: true } },
|
hostedShifts: { select: { id: true } },
|
||||||
markers: { select: { id: true } },
|
markers: { select: { id: true } },
|
||||||
@@ -87,8 +93,12 @@ export async function trashEntity(ownerId: string, bookId: string, entityId: str
|
|||||||
description: r.description,
|
description: r.description,
|
||||||
data: r.data,
|
data: r.data,
|
||||||
members: r.members.map((m) => m.entityId),
|
members: r.members.map((m) => m.entityId),
|
||||||
|
bond: r.bond,
|
||||||
|
startDate: r.startDate,
|
||||||
|
endDate: r.endDate,
|
||||||
})),
|
})),
|
||||||
memberOf: entity.memberOf.map((m) => m.relationId),
|
memberOf: entity.memberOf.map((m) => m.relationId),
|
||||||
|
eventIds: entity.events.map((e) => e.eventId),
|
||||||
shifts: entity.shifts.map((s) => ({
|
shifts: entity.shifts.map((s) => ({
|
||||||
workplaceId: s.workplaceId,
|
workplaceId: s.workplaceId,
|
||||||
weekday: s.weekday,
|
weekday: s.weekday,
|
||||||
@@ -165,6 +175,9 @@ export async function restoreEntity(ownerId: string, trashId: string): Promise<{
|
|||||||
toId: r.toId,
|
toId: r.toId,
|
||||||
type: r.type,
|
type: r.type,
|
||||||
description: r.description,
|
description: r.description,
|
||||||
|
bond: r.bond ?? null,
|
||||||
|
startDate: r.startDate ?? null,
|
||||||
|
endDate: r.endDate ?? null,
|
||||||
data: (r.data ?? {}) as Prisma.InputJsonObject,
|
data: (r.data ?? {}) as Prisma.InputJsonObject,
|
||||||
members: { create: r.members.filter((m) => others.has(m) && m !== r.fromId && m !== r.toId).map((entityId) => ({ entityId })) },
|
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) {
|
for (const s of snap.shifts) {
|
||||||
await tx.shift.create({
|
await tx.shift.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -0,0 +1,334 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { ImportError, buildExport, importBook, parseExport, readImportFile } from "@/lib/book-transfer";
|
||||||
|
import { collectFieldData } from "@/lib/field-values";
|
||||||
|
import { restoreBook, restoreEntity, trashBook, trashEntity } from "@/lib/trash";
|
||||||
|
import { loadTimeline } from "@/lib/timeline";
|
||||||
|
import { getTemplate } from "@/lib/templates";
|
||||||
|
import { strToU8, zipSync } from "fflate";
|
||||||
|
import { relationRow, validExport, entityRow } from "../helpers/fixtures";
|
||||||
|
import { describeDb, makeBook, makeEntity, makeEvent, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||||
|
|
||||||
|
// Åtgärderna (server actions) körs här utan webbserver: inloggning, cache och omdirigering ersätts
|
||||||
|
const session = vi.hoisted(() => ({ bookId: "", ownerId: "" }));
|
||||||
|
vi.mock("@/lib/session", () => ({
|
||||||
|
requireBook: async (id: string) => {
|
||||||
|
if (id !== session.bookId) throw new Error("Not your book");
|
||||||
|
return { id: session.bookId, ownerId: session.ownerId };
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("next/cache", () => ({ revalidatePath: () => undefined }));
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
redirect: (to: string) => {
|
||||||
|
throw new Error(`REDIRECT:${to}`);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@/i18n/server", async () => {
|
||||||
|
const core = await import("@/i18n/core");
|
||||||
|
return { getLocale: async () => "sv", getT: async () => ({ locale: "sv", t: core.makeT(core.dictionaries.sv) }) };
|
||||||
|
});
|
||||||
|
|
||||||
|
import { addEvent, deleteEvent, saveEvent } from "@/actions/events";
|
||||||
|
import { addRelation, saveRelation } from "@/actions/relations";
|
||||||
|
|
||||||
|
const form = (fields: Record<string, string | string[]>) => {
|
||||||
|
const data = new FormData();
|
||||||
|
for (const [key, value] of Object.entries(fields)) for (const v of Array.isArray(value) ? value : [value]) data.append(key, v);
|
||||||
|
return data;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Kör en åtgärd och returnerar vart den omdirigerade (eller null om den inte gjorde det). */
|
||||||
|
async function redirectedTo(run: () => Promise<unknown>): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
await run();
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "";
|
||||||
|
if (message.startsWith("REDIRECT:")) return message.slice(9);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describeDb("släktband, perioder och händelser", () => {
|
||||||
|
let ownerId: string;
|
||||||
|
let bookId: string;
|
||||||
|
let anna: { id: string };
|
||||||
|
let erik: { id: string };
|
||||||
|
let lisa: { id: string };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await resetAll();
|
||||||
|
ownerId = (await makeUser()).id;
|
||||||
|
bookId = (await makeBook(ownerId)).id;
|
||||||
|
session.bookId = bookId;
|
||||||
|
session.ownerId = ownerId;
|
||||||
|
anna = await makeEntity(bookId, "CHARACTER", "Anna", { data: { birthDate: "1960-05-10", deathDate: "2020" } });
|
||||||
|
erik = await makeEntity(bookId, "CHARACTER", "Erik", { data: { birthDate: "1990" } });
|
||||||
|
lisa = await makeEntity(bookId, "CHARACTER", "Lisa");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("relationer", () => {
|
||||||
|
it("sparar släktband och period, och normaliserar datumen", async () => {
|
||||||
|
await addRelation(form({ bookId, fromId: anna.id, toId: erik.id, type: "Mor till", bond: "PARENT", startDate: "1990-6-2", endDate: "2020" }));
|
||||||
|
const relation = await prisma.relation.findFirstOrThrow({ where: { bookId } });
|
||||||
|
expect(relation).toMatchObject({ type: "Mor till", bond: "PARENT", startDate: "1990-06-02", endDate: "2020" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tom relationstext får släktbandets namn", async () => {
|
||||||
|
await addRelation(form({ bookId, fromId: anna.id, toId: erik.id, type: "", bond: "PARTNER" }));
|
||||||
|
expect((await prisma.relation.findFirstOrThrow({ where: { bookId } })).type).toBe("Partner till");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kräver text eller släktband", async () => {
|
||||||
|
await addRelation(form({ bookId, fromId: anna.id, toId: erik.id, type: "" }));
|
||||||
|
expect(await prisma.relation.count()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sparar inte en relation med ogiltigt datum eller okänt släktband som släktband", async () => {
|
||||||
|
await addRelation(form({ bookId, fromId: anna.id, toId: erik.id, type: "Vänner", startDate: "förra året" }));
|
||||||
|
expect(await prisma.relation.count()).toBe(0);
|
||||||
|
await addRelation(form({ bookId, fromId: anna.id, toId: erik.id, type: "Vänner", bond: "FIENDE" }));
|
||||||
|
expect((await prisma.relation.findFirstOrThrow()).bond).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan ändra och ta bort släktband och period", async () => {
|
||||||
|
const relation = await makeRelation(bookId, anna.id, erik.id, "Mor till", [], { bond: "PARENT", startDate: "1990" });
|
||||||
|
const to = await redirectedTo(() => saveRelation(form({ bookId, id: relation.id, type: "Mor till", bond: "", startDate: "", endDate: "2000-01" })));
|
||||||
|
expect(to).toContain(`/relations/${relation.id}`);
|
||||||
|
expect(await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).toMatchObject({ bond: null, startDate: null, endDate: "2000-01" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ett ogiltigt datum vid ändring sparar ingenting", async () => {
|
||||||
|
const relation = await makeRelation(bookId, anna.id, erik.id, "Gift", [], { startDate: "2000" });
|
||||||
|
await saveRelation(form({ bookId, id: relation.id, type: "Skild", startDate: "2000", endDate: "snart" }));
|
||||||
|
expect((await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).type).toBe("Gift");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("händelser", () => {
|
||||||
|
it("skapar en händelse med deltagare från boken", async () => {
|
||||||
|
const other = await makeBook((await makeUser("Annan")).id, "Annan bok");
|
||||||
|
const stranger = await makeEntity(other.id, "CHARACTER", "Främling");
|
||||||
|
const to = await redirectedTo(() =>
|
||||||
|
addEvent(form({ bookId, title: "Bröllop", date: "1985-8-1", endDate: "1985-08-03", description: "Vid sjön", participantIds: [anna.id, erik.id, stranger.id, anna.id] })),
|
||||||
|
);
|
||||||
|
expect(to).toBe(`/books/${bookId}/timeline`);
|
||||||
|
const event = await prisma.storyEvent.findFirstOrThrow({ include: { participants: true } });
|
||||||
|
expect(event).toMatchObject({ title: "Bröllop", date: "1985-08-01", endDate: "1985-08-03", description: "Vid sjön" });
|
||||||
|
// Bara poster i den här boken, och ingen dubblett
|
||||||
|
expect(event.participants.map((p) => p.entityId).sort()).toEqual([anna.id, erik.id].sort());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ogiltigt datum skapar ingen händelse och visar ett fel", async () => {
|
||||||
|
const to = await redirectedTo(() => addEvent(form({ bookId, title: "Fel", date: "i går" })));
|
||||||
|
expect(to).toBe(`/books/${bookId}/timeline?error=date`);
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ett slutdatum före startdatumet ignoreras", async () => {
|
||||||
|
await redirectedTo(() => addEvent(form({ bookId, title: "Baklänges", date: "2000", endDate: "1990" })));
|
||||||
|
expect((await prisma.storyEvent.findFirstOrThrow()).endDate).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kräver en rubrik", async () => {
|
||||||
|
await addEvent(form({ bookId, title: "", date: "2000" }));
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan ändras och byta deltagare", async () => {
|
||||||
|
const event = await makeEvent(bookId, "Flytt", "2000", [anna.id]);
|
||||||
|
const to = await redirectedTo(() => saveEvent(form({ bookId, id: event.id, title: "Flytt till Lund", date: "2001-05", participantIds: [erik.id] })));
|
||||||
|
expect(to).toBe(`/books/${bookId}/timeline/${event.id}?saved=1`);
|
||||||
|
const saved = await prisma.storyEvent.findUniqueOrThrow({ where: { id: event.id }, include: { participants: true } });
|
||||||
|
expect(saved).toMatchObject({ title: "Flytt till Lund", date: "2001-05" });
|
||||||
|
expect(saved.participants.map((p) => p.entityId)).toEqual([erik.id]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan tas bort, men bara i den egna boken", async () => {
|
||||||
|
const event = await makeEvent(bookId, "Flytt", "2000", [anna.id]);
|
||||||
|
await redirectedTo(() => deleteEvent(form({ bookId, id: event.id })));
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(0);
|
||||||
|
expect(await prisma.eventParticipant.count()).toBe(0);
|
||||||
|
|
||||||
|
const otherBook = await makeBook(ownerId, "Bok två");
|
||||||
|
const foreign = await makeEvent(otherBook.id, "Annans", "2000");
|
||||||
|
await redirectedTo(() => deleteEvent(form({ bookId, id: foreign.id })));
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan inte ändra en annan boks händelse", async () => {
|
||||||
|
const otherBook = await makeBook(ownerId, "Bok två");
|
||||||
|
const foreign = await makeEvent(otherBook.id, "Annans", "2000");
|
||||||
|
await expect(saveEvent(form({ bookId, id: foreign.id, title: "Kapad", date: "2000" }))).rejects.toThrow("Event not found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tas bort tillsammans med deltagaren eller boken", async () => {
|
||||||
|
const event = await makeEvent(bookId, "Fest", "2000", [anna.id, erik.id]);
|
||||||
|
await prisma.entity.delete({ where: { id: anna.id } });
|
||||||
|
expect(await prisma.eventParticipant.count({ where: { eventId: event.id } })).toBe(1);
|
||||||
|
await prisma.book.delete({ where: { id: bookId } });
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("export och import", () => {
|
||||||
|
it("släktband, perioder och händelser följer med och pekar på de nya posterna", async () => {
|
||||||
|
await makeRelation(bookId, anna.id, erik.id, "Mor till", [lisa.id], { bond: "PARENT", startDate: "1990", endDate: "2020-01-02" });
|
||||||
|
await makeEvent(bookId, "Begravning", "2020-01-10", [erik.id, lisa.id], { endDate: "2020-01-11", description: "Kyrkan" });
|
||||||
|
|
||||||
|
const exported = await buildExport(bookId, false);
|
||||||
|
const entries = { "book.json": strToU8(JSON.stringify(exported.data)) };
|
||||||
|
const { data, files } = readImportFile(zipSync(entries));
|
||||||
|
const result = await importBook(ownerId, data, files);
|
||||||
|
expect(result).toMatchObject({ relations: 1, events: 1 });
|
||||||
|
|
||||||
|
const copy = await prisma.book.findUniqueOrThrow({
|
||||||
|
where: { id: result.bookId },
|
||||||
|
include: { entities: true, relations: true, events: { include: { participants: true } } },
|
||||||
|
});
|
||||||
|
const byName = Object.fromEntries(copy.entities.map((e) => [e.name, e.id]));
|
||||||
|
expect(copy.relations[0]).toMatchObject({ bond: "PARENT", startDate: "1990", endDate: "2020-01-02" });
|
||||||
|
expect(copy.events[0]).toMatchObject({ title: "Begravning", date: "2020-01-10", endDate: "2020-01-11", description: "Kyrkan" });
|
||||||
|
expect(copy.events[0].participants.map((p) => p.entityId).sort()).toEqual([byName.Erik, byName.Lisa].sort());
|
||||||
|
// Datumfälten i mallfälten följer med som vanligt
|
||||||
|
expect((copy.entities.find((e) => e.name === "Anna")!.data as Record<string, unknown>).birthDate).toBe("1960-05-10");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("äldre exportfiler utan släktband och händelser går att läsa", () => {
|
||||||
|
const old = validExport() as Record<string, unknown>;
|
||||||
|
delete old.events;
|
||||||
|
old.relations = [{ id: "r", fromId: "a", toId: "b", type: "Vänner" }];
|
||||||
|
const parsed = parseExport(JSON.parse(JSON.stringify(old)));
|
||||||
|
expect(parsed.events).toEqual([]);
|
||||||
|
expect(parsed.relations[0]).toMatchObject({ bond: null, startDate: null, endDate: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ogiltigt släktband eller datum på en relation blir tomt, men en händelse utan giltigt datum avvisar filen", () => {
|
||||||
|
const parsed = parseExport({ ...validExport(), relations: [{ id: "r", fromId: "a", toId: "b", type: "X", bond: "FIENDE", startDate: "nej", endDate: "2000-2-3" }] });
|
||||||
|
expect(parsed.relations[0]).toMatchObject({ bond: null, startDate: null, endDate: "2000-02-03" });
|
||||||
|
expect(() => parseExport({ ...validExport(), events: [{ title: "Fel", date: "nej" }] })).toThrow(ImportError);
|
||||||
|
expect(() => parseExport({ ...validExport(), events: [{ title: "", date: "2000" }] })).toThrow(ImportError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deltagare som inte finns i filen hoppas över", async () => {
|
||||||
|
const data = validExport({
|
||||||
|
entities: [entityRow("a", "CHARACTER", "Anna")],
|
||||||
|
relations: [relationRow("r", "a", "a", "x")],
|
||||||
|
events: [{ title: "Möte", date: "2001", endDate: null, description: null, participants: ["a", "finns-inte", "a"] }],
|
||||||
|
});
|
||||||
|
const result = await importBook(ownerId, data, new Map());
|
||||||
|
const event = await prisma.storyEvent.findFirstOrThrow({ where: { bookId: result.bookId }, include: { participants: true } });
|
||||||
|
expect(event.participants).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("en bok som läggs i papperskorgen och återställs behåller släktband och händelser", async () => {
|
||||||
|
await makeRelation(bookId, anna.id, erik.id, "Mor till", [], { bond: "PARENT", startDate: "1990" });
|
||||||
|
await makeEvent(bookId, "Fest", "2000", [anna.id]);
|
||||||
|
await trashBook(ownerId, bookId);
|
||||||
|
expect(await prisma.storyEvent.count()).toBe(0);
|
||||||
|
|
||||||
|
const item = await prisma.trashItem.findFirstOrThrow({ where: { kind: "book" } });
|
||||||
|
const restored = await restoreBook(ownerId, item.id);
|
||||||
|
const copy = await prisma.book.findUniqueOrThrow({
|
||||||
|
where: { id: restored! },
|
||||||
|
include: { relations: true, events: { include: { participants: { include: { entity: true } } } } },
|
||||||
|
});
|
||||||
|
expect(copy.relations[0]).toMatchObject({ bond: "PARENT", startDate: "1990" });
|
||||||
|
expect(copy.events[0].title).toBe("Fest");
|
||||||
|
expect(copy.events[0].participants.map((p) => p.entity.name)).toEqual(["Anna"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("papperskorgen", () => {
|
||||||
|
it("återställer släktband, period och deltagande i händelser", async () => {
|
||||||
|
const relation = await makeRelation(bookId, anna.id, erik.id, "Mor till", [], { bond: "PARENT", startDate: "1990", endDate: "2020" });
|
||||||
|
const event = await makeEvent(bookId, "Fest", "2000", [anna.id, erik.id]);
|
||||||
|
|
||||||
|
await trashEntity(ownerId, bookId, anna.id);
|
||||||
|
expect(await prisma.eventParticipant.count({ where: { eventId: event.id } })).toBe(1);
|
||||||
|
|
||||||
|
const [item] = await prisma.trashItem.findMany();
|
||||||
|
await restoreEntity(ownerId, item.id);
|
||||||
|
expect(await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).toMatchObject({ bond: "PARENT", startDate: "1990", endDate: "2020" });
|
||||||
|
const participants = await prisma.eventParticipant.findMany({ where: { eventId: event.id } });
|
||||||
|
expect(participants.map((p) => p.entityId).sort()).toEqual([anna.id, erik.id].sort());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("klarar ögonblicksbilder från före släktträdet", async () => {
|
||||||
|
const relation = await makeRelation(bookId, anna.id, erik.id, "Vänner");
|
||||||
|
await trashEntity(ownerId, bookId, anna.id);
|
||||||
|
const [item] = await prisma.trashItem.findMany();
|
||||||
|
// En gammal bild saknar bond, datum och eventIds
|
||||||
|
const snapshot = item.payload as { relations: Record<string, unknown>[]; eventIds?: string[] };
|
||||||
|
for (const r of snapshot.relations) {
|
||||||
|
delete r.bond;
|
||||||
|
delete r.startDate;
|
||||||
|
delete r.endDate;
|
||||||
|
}
|
||||||
|
delete snapshot.eventIds;
|
||||||
|
await prisma.trashItem.update({ where: { id: item.id }, data: { payload: snapshot as object } });
|
||||||
|
|
||||||
|
expect(await restoreEntity(ownerId, item.id)).not.toBeNull();
|
||||||
|
expect(await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).toMatchObject({ bond: null, startDate: null, endDate: null });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("fältvärden", () => {
|
||||||
|
it("datumfält sparas i fast form och ogiltiga datum ändrar ingenting", async () => {
|
||||||
|
const { fields } = await getTemplate(bookId, "CHARACTER", "sv");
|
||||||
|
expect(fields.find((f) => f.key === "deathDate")?.type).toBe("date");
|
||||||
|
const saved = await collectFieldData(bookId, fields, form({ f_birthDate: "1960-5-1", f_deathDate: "snart" }), { deathDate: "2020" });
|
||||||
|
expect(saved.birthDate).toBe("1960-05-01");
|
||||||
|
expect(saved.deathDate).toBe("2020");
|
||||||
|
const cleared = await collectFieldData(bookId, fields, form({ f_birthDate: "" }), { birthDate: "1960" });
|
||||||
|
expect(cleared.birthDate).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scenariomallen har ett datumfält", async () => {
|
||||||
|
const { fields } = await getTemplate(bookId, "SCENARIO", "sv");
|
||||||
|
expect(fields.find((f) => f.key === "date")?.type).toBe("date");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("tidslinjen", () => {
|
||||||
|
it("samlar datum från hela boken", async () => {
|
||||||
|
const olyckan = await makeEntity(bookId, "SCENARIO", "Olyckan", { data: { date: "1999-07-01", scenarioType: "Olycka", linkedEntity: lisa.id } });
|
||||||
|
const rymmen = await makeEntity(bookId, "SCENARIO", "Rymmen", { data: { when: "Någon gång" } });
|
||||||
|
await makeRelation(bookId, anna.id, olyckan.id, "Involverad i");
|
||||||
|
await makeRelation(bookId, erik.id, lisa.id, "Gift", [], { startDate: "2010", endDate: "2015" });
|
||||||
|
await makeEvent(bookId, "Fest", "2005-06", [erik.id]);
|
||||||
|
|
||||||
|
const { items, undated } = await loadTimeline(bookId);
|
||||||
|
expect(items.map((i) => `${i.date} ${i.kind} ${i.title}`)).toEqual([
|
||||||
|
"1960-05-10 birth Anna",
|
||||||
|
"1990 birth Erik",
|
||||||
|
"1999-07-01 scenario Olyckan",
|
||||||
|
"2005-06 event Fest",
|
||||||
|
"2010 relation Gift",
|
||||||
|
"2020 death Anna",
|
||||||
|
]);
|
||||||
|
expect(undated.map((u) => u.title)).toEqual(["Rymmen"]);
|
||||||
|
expect(rymmen.id).toBeTruthy();
|
||||||
|
|
||||||
|
// Scenariot knyts till personerna via relationen och via kopplingsfältet, med ålder vid tillfället
|
||||||
|
const scenario = items.find((i) => i.kind === "scenario")!;
|
||||||
|
expect(scenario.people.map((p) => p.name).sort()).toEqual(["Anna", "Lisa"]);
|
||||||
|
expect(scenario.ages).toEqual([{ id: anna.id, name: "Anna", age: 39 }]);
|
||||||
|
expect(items.find((i) => i.kind === "relation")).toMatchObject({ endDate: "2015", people: expect.arrayContaining([{ id: erik.id, name: "Erik" }]) });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filtrerar på person och hör bara till den egna boken", async () => {
|
||||||
|
const other = await makeBook(ownerId, "Bok två");
|
||||||
|
await makeEntity(other.id, "CHARACTER", "Främling", { data: { birthDate: "1900" } });
|
||||||
|
await makeEvent(bookId, "Fest", "2005", [erik.id]);
|
||||||
|
const { items } = await loadTimeline(bookId, undefined, erik.id);
|
||||||
|
expect(items.map((i) => i.title)).toEqual(["Erik", "Fest"]);
|
||||||
|
expect((await loadTimeline(bookId)).items.some((i) => i.title === "Främling")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignorerar ogiltiga datum i mallfält", async () => {
|
||||||
|
await prisma.entity.update({ where: { id: lisa.id }, data: { data: { birthDate: "oklart", deathDate: 1999 } } });
|
||||||
|
const { items } = await loadTimeline(bookId);
|
||||||
|
expect(items.some((i) => i.title === "Lisa")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,7 +5,7 @@ import { beforeEach, expect, it } from "vitest";
|
|||||||
import { buildExport, importBook, readImportFile } from "@/lib/book-transfer";
|
import { buildExport, importBook, readImportFile } from "@/lib/book-transfer";
|
||||||
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||||
import { nextMapCode, nextMarkerCode, nextScheduleCode } from "@/lib/ids";
|
import { nextMapCode, nextMarkerCode, nextScheduleCode } from "@/lib/ids";
|
||||||
import { entityRow, makeImage, validExport } from "../helpers/fixtures";
|
import { entityRow, makeImage, relationRow, validExport } from "../helpers/fixtures";
|
||||||
import { describeDb, filesIn, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
import { describeDb, filesIn, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||||
|
|
||||||
/** Skickar exporten genom samma zip-format som exportknappen och läser tillbaka den. */
|
/** Skickar exporten genom samma zip-format som exportknappen och läser tillbaka den. */
|
||||||
@@ -136,9 +136,9 @@ describeDb("export och import", () => {
|
|||||||
const data = validExport({
|
const data = validExport({
|
||||||
entities: [entityRow("a", "CHARACTER", "Anna", { image: "saknas.png" }), entityRow("b", "CHARACTER", "Bo", { image: "skräp.png" })],
|
entities: [entityRow("a", "CHARACTER", "Anna", { image: "saknas.png" }), entityRow("b", "CHARACTER", "Bo", { image: "skräp.png" })],
|
||||||
relations: [
|
relations: [
|
||||||
{ id: "r1", code: null, fromId: "a", toId: "b", type: "Vänner", description: null, data: {}, members: ["finns-inte"] },
|
relationRow("r1", "a", "b", "Vänner", { members: ["finns-inte"] }),
|
||||||
{ id: "r2", code: null, fromId: "a", toId: "okänd", type: "Fiende", description: null, data: {}, members: [] },
|
relationRow("r2", "a", "okänd", "Fiende"),
|
||||||
{ id: "r3", code: null, fromId: "a", toId: "a", type: "Självrelation", description: null, data: {}, members: [] },
|
relationRow("r3", "a", "a", "Självrelation"),
|
||||||
],
|
],
|
||||||
shifts: [{ personId: "okänd", workplaceId: null, weekday: 0, startTime: "08:00", endTime: "16:00", weeks: "ALL", label: null, scheduleCode: null }],
|
shifts: [{ personId: "okänd", workplaceId: null, weekday: 0, startTime: "08:00", endTime: "16:00", weeks: "ALL", label: null, scheduleCode: null }],
|
||||||
});
|
});
|
||||||
|
|||||||
+16
-3
@@ -1,6 +1,6 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { mkdir, readdir, rm } from "node:fs/promises";
|
import { mkdir, readdir, rm } from "node:fs/promises";
|
||||||
import type { EntityKind, Prisma } from "@prisma/client";
|
import type { EntityKind, FamilyBond, Prisma } from "@prisma/client";
|
||||||
import { describe } from "vitest";
|
import { describe } from "vitest";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { UPLOAD_DIR } from "@/lib/files";
|
import { UPLOAD_DIR } from "@/lib/files";
|
||||||
@@ -56,8 +56,21 @@ export async function makeEntity(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function makeRelation(bookId: string, fromId: string, toId: string, type = "Vänner", memberIds: string[] = []) {
|
export async function makeRelation(
|
||||||
|
bookId: string,
|
||||||
|
fromId: string,
|
||||||
|
toId: string,
|
||||||
|
type = "Vänner",
|
||||||
|
memberIds: string[] = [],
|
||||||
|
extra: { bond?: FamilyBond; startDate?: string; endDate?: string } = {},
|
||||||
|
) {
|
||||||
return prisma.relation.create({
|
return prisma.relation.create({
|
||||||
data: { bookId, fromId, toId, type, code: await nextRelationCode(bookId), members: { create: memberIds.map((entityId) => ({ entityId })) } },
|
data: { bookId, fromId, toId, type, ...extra, code: await nextRelationCode(bookId), members: { create: memberIds.map((entityId) => ({ entityId })) } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function makeEvent(bookId: string, title: string, date: string, participantIds: string[] = [], extra: { endDate?: string; description?: string } = {}) {
|
||||||
|
return prisma.storyEvent.create({
|
||||||
|
data: { bookId, title, date, ...extra, participants: { create: participantIds.map((entityId) => ({ entityId })) } },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,7 @@ export function validExport(overrides: Partial<ExportData> = {}): ExportData {
|
|||||||
book: { title: "Testbok", subtitle: null, genre: null, description: null },
|
book: { title: "Testbok", subtitle: null, genre: null, description: null },
|
||||||
entities: [],
|
entities: [],
|
||||||
relations: [],
|
relations: [],
|
||||||
|
events: [],
|
||||||
shifts: [],
|
shifts: [],
|
||||||
maps: [],
|
maps: [],
|
||||||
templates: [],
|
templates: [],
|
||||||
@@ -22,6 +23,10 @@ export function entityRow(id: string, kind: ExportData["entities"][number]["kind
|
|||||||
return { id, kind, name, code: null, summary: null, tags: [], data: {}, image: null, ...extra };
|
return { id, kind, name, code: null, summary: null, tags: [], data: {}, image: null, ...extra };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function relationRow(id: string, fromId: string, toId: string, type: string, extra: Partial<ExportData["relations"][number]> = {}): ExportData["relations"][number] {
|
||||||
|
return { id, code: null, fromId, toId, type, description: null, data: {}, members: [], bond: null, startDate: null, endDate: null, ...extra };
|
||||||
|
}
|
||||||
|
|
||||||
/** En riktig bild (PNG, JPEG eller WebP) av önskad storlek, för tester av bildbehandling och uppladdning. */
|
/** En riktig bild (PNG, JPEG eller WebP) av önskad storlek, för tester av bildbehandling och uppladdning. */
|
||||||
export async function makeImage(
|
export async function makeImage(
|
||||||
width: number,
|
width: number,
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { familyComponent, layoutFamily, parseBond, NODE_HEIGHT, NODE_WIDTH, GAP_X, type FamilyBondInput, type FamilyLayout, type FamilyPerson } from "@/lib/family";
|
||||||
|
|
||||||
|
const person = (id: string, name = id.toUpperCase()): FamilyPerson => ({ id, name });
|
||||||
|
const parent = (fromId: string, toId: string, ...memberIds: string[]): FamilyBondInput => ({ bond: "PARENT", fromId, toId, memberIds });
|
||||||
|
const partner = (fromId: string, toId: string, ...memberIds: string[]): FamilyBondInput => ({ bond: "PARTNER", fromId, toId, memberIds });
|
||||||
|
const sibling = (fromId: string, toId: string, ...memberIds: string[]): FamilyBondInput => ({ bond: "SIBLING", fromId, toId, memberIds });
|
||||||
|
|
||||||
|
const node = (layout: FamilyLayout, id: string) => layout.nodes.find((n) => n.id === id)!;
|
||||||
|
const centre = (layout: FamilyLayout, id: string) => node(layout, id).x + NODE_WIDTH / 2;
|
||||||
|
|
||||||
|
/** Ingen nod i samma rad överlappar en annan. */
|
||||||
|
function expectNoOverlap(layout: FamilyLayout) {
|
||||||
|
for (const a of layout.nodes) {
|
||||||
|
for (const b of layout.nodes) {
|
||||||
|
if (a.id < b.id && a.y === b.y) expect(Math.abs(a.x - b.x)).toBeGreaterThanOrEqual(NODE_WIDTH + GAP_X - 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("parseBond", () => {
|
||||||
|
it("godtar bara kända släktband", () => {
|
||||||
|
expect(parseBond("PARENT")).toBe("PARENT");
|
||||||
|
expect(parseBond("PARTNER")).toBe("PARTNER");
|
||||||
|
expect(parseBond("SIBLING")).toBe("SIBLING");
|
||||||
|
expect(parseBond("FRIEND")).toBeNull();
|
||||||
|
expect(parseBond(null)).toBeNull();
|
||||||
|
expect(parseBond(undefined)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("layoutFamily", () => {
|
||||||
|
it("ger tomt resultat utan släktband", () => {
|
||||||
|
expect(layoutFamily([person("a")], [])).toMatchObject({ nodes: [], partners: [], children: [], width: 0, height: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lägger barn en generation under föräldern", () => {
|
||||||
|
const layout = layoutFamily([person("mor"), person("barn")], [parent("mor", "barn")]);
|
||||||
|
expect(node(layout, "barn").generation).toBe(1);
|
||||||
|
expect(node(layout, "barn").y).toBeGreaterThan(node(layout, "mor").y);
|
||||||
|
expect(layout.children).toEqual([{ childId: "barn", parentIds: ["mor"] }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ritar partner bredvid varandra i samma rad och barnet mitt under dem", () => {
|
||||||
|
const people = ["far", "mor", "barn"].map((id) => person(id));
|
||||||
|
const layout = layoutFamily(people, [partner("far", "mor"), parent("far", "barn"), parent("mor", "barn")]);
|
||||||
|
|
||||||
|
expect(node(layout, "far").y).toBe(node(layout, "mor").y);
|
||||||
|
expect(Math.abs(node(layout, "far").x - node(layout, "mor").x)).toBe(NODE_WIDTH + GAP_X);
|
||||||
|
expect(layout.partners).toHaveLength(1);
|
||||||
|
expect(centre(layout, "barn")).toBeCloseTo((centre(layout, "far") + centre(layout, "mor")) / 2, 0);
|
||||||
|
expect(layout.children[0].parentIds).toEqual(["far", "mor"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tre generationer, syskon sida vid sida utan överlapp", () => {
|
||||||
|
const people = ["farfar", "far", "mor", "a", "b", "c"].map((id) => person(id));
|
||||||
|
const layout = layoutFamily(people, [
|
||||||
|
parent("farfar", "far"),
|
||||||
|
partner("far", "mor"),
|
||||||
|
parent("far", "a"),
|
||||||
|
parent("far", "b", "c"),
|
||||||
|
parent("mor", "a", "b", "c"),
|
||||||
|
]);
|
||||||
|
expect([node(layout, "farfar").generation, node(layout, "far").generation, node(layout, "a").generation]).toEqual([0, 1, 2]);
|
||||||
|
expect(node(layout, "mor").generation).toBe(1);
|
||||||
|
expect(new Set(["a", "b", "c"].map((id) => node(layout, id).y)).size).toBe(1);
|
||||||
|
expectNoOverlap(layout);
|
||||||
|
// Barnen sitter ihop under föräldrarna
|
||||||
|
const kids = ["a", "b", "c"].map((id) => centre(layout, id));
|
||||||
|
expect(Math.min(...kids)).toBeGreaterThanOrEqual(Math.min(centre(layout, "far"), centre(layout, "mor")) - NODE_WIDTH * 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("syskon utan kända föräldrar hamnar i samma generation", () => {
|
||||||
|
const layout = layoutFamily([person("a"), person("b"), person("c")], [sibling("a", "b"), parent("a", "c")]);
|
||||||
|
expect(node(layout, "a").generation).toBe(node(layout, "b").generation);
|
||||||
|
expect(node(layout, "c").generation).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("partner som gifts in följer med sin partners generation", () => {
|
||||||
|
// Anna har föräldrar, Bo har inga. Bo ska hamna i Annas generation, inte överst.
|
||||||
|
const people = ["mormor", "anna", "bo", "barn"].map((id) => person(id));
|
||||||
|
const layout = layoutFamily(people, [parent("mormor", "anna"), partner("anna", "bo"), parent("anna", "barn"), parent("bo", "barn")]);
|
||||||
|
expect(node(layout, "bo").generation).toBe(1);
|
||||||
|
expect(node(layout, "barn").generation).toBe(2);
|
||||||
|
expectNoOverlap(layout);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("två släkter som möts i ett barn", () => {
|
||||||
|
const people = ["a1", "a2", "b1", "b2", "ma", "mb", "barn"].map((id) => person(id));
|
||||||
|
const layout = layoutFamily(people, [
|
||||||
|
parent("a1", "ma"),
|
||||||
|
parent("a2", "ma"),
|
||||||
|
parent("b1", "mb"),
|
||||||
|
parent("b2", "mb"),
|
||||||
|
partner("ma", "mb"),
|
||||||
|
parent("ma", "barn"),
|
||||||
|
parent("mb", "barn"),
|
||||||
|
]);
|
||||||
|
expect(node(layout, "barn").generation).toBe(2);
|
||||||
|
expect(node(layout, "a1").generation).toBe(0);
|
||||||
|
expectNoOverlap(layout);
|
||||||
|
expect(layout.width).toBeGreaterThan(NODE_WIDTH * 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("flera partner i en kedja ritas bredvid varandra", () => {
|
||||||
|
const layout = layoutFamily([person("a"), person("b"), person("c")], [partner("a", "b"), partner("b", "c")]);
|
||||||
|
const xs = ["a", "b", "c"].map((id) => node(layout, id).x).sort((p, q) => p - q);
|
||||||
|
expect(xs[1] - xs[0]).toBe(NODE_WIDTH + GAP_X);
|
||||||
|
expect(xs[2] - xs[1]).toBe(NODE_WIDTH + GAP_X);
|
||||||
|
expect(layout.partners).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("partnergrupp med fler än två", () => {
|
||||||
|
const layout = layoutFamily(["a", "b", "c"].map((id) => person(id)), [partner("a", "b", "c")]);
|
||||||
|
expect(layout.nodes).toHaveLength(3);
|
||||||
|
expectNoOverlap(layout);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cirkulära släktband hänger inte och ger ändå en layout", () => {
|
||||||
|
const layout = layoutFamily(["a", "b", "c"].map((id) => person(id)), [parent("a", "b"), parent("b", "c"), parent("c", "a")]);
|
||||||
|
expect(layout.nodes).toHaveLength(3);
|
||||||
|
expect(layout.nodes.every((n) => Number.isFinite(n.x) && Number.isFinite(n.y))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("en person som är sin egen förälder ignoreras", () => {
|
||||||
|
const layout = layoutFamily([person("a"), person("b")], [parent("a", "a"), parent("a", "b")]);
|
||||||
|
expect(layout.children).toEqual([{ childId: "b", parentIds: ["a"] }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignorerar personer som inte finns i listan", () => {
|
||||||
|
const layout = layoutFamily([person("a")], [parent("a", "okänd"), parent("okänd", "a")]);
|
||||||
|
expect(layout.nodes).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("nodernas läge är inom bilden", () => {
|
||||||
|
const layout = layoutFamily(["a", "b", "c", "d"].map((id) => person(id)), [parent("a", "b"), parent("a", "c"), parent("b", "d")]);
|
||||||
|
for (const n of layout.nodes) {
|
||||||
|
expect(n.x).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(n.y).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(n.x + NODE_WIDTH).toBeLessThanOrEqual(layout.width);
|
||||||
|
expect(n.y + NODE_HEIGHT).toBeLessThanOrEqual(layout.height);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("samma indata ger samma layout", () => {
|
||||||
|
const people = ["a", "b", "c", "d", "e"].map((id) => person(id));
|
||||||
|
const bonds = [partner("a", "b"), parent("a", "c"), parent("b", "c"), parent("a", "d"), sibling("c", "e")];
|
||||||
|
expect(layoutFamily(people, bonds)).toEqual(layoutFamily([...people].reverse(), bonds));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("klarar en stor släkt snabbt", () => {
|
||||||
|
const people: FamilyPerson[] = [];
|
||||||
|
const bonds: FamilyBondInput[] = [];
|
||||||
|
// 5 generationer, varje person har tre barn
|
||||||
|
let current = ["p0"];
|
||||||
|
people.push(person("p0"));
|
||||||
|
let counter = 1;
|
||||||
|
for (let gen = 0; gen < 5; gen++) {
|
||||||
|
const next: string[] = [];
|
||||||
|
for (const p of current) {
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const id = `p${counter++}`;
|
||||||
|
people.push(person(id));
|
||||||
|
bonds.push(parent(p, id));
|
||||||
|
next.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
const started = Date.now();
|
||||||
|
const layout = layoutFamily(people, bonds);
|
||||||
|
expect(layout.nodes).toHaveLength(people.length);
|
||||||
|
expect(Date.now() - started).toBeLessThan(5000);
|
||||||
|
expectNoOverlap(layout);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("familyComponent", () => {
|
||||||
|
it("följer alla släktband åt alla håll", () => {
|
||||||
|
const bonds = [parent("farfar", "far"), partner("far", "mor"), parent("far", "barn"), parent("annan", "annanbarn")];
|
||||||
|
expect([...familyComponent(bonds, "barn")].sort()).toEqual(["barn", "far", "farfar", "mor"]);
|
||||||
|
expect([...familyComponent(bonds, "annanbarn")].sort()).toEqual(["annan", "annanbarn"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("en okänd person ger bara sig själv", () => {
|
||||||
|
expect([...familyComponent([parent("a", "b")], "x")]).toEqual(["x"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { ageAt, compareStoryDates, normalizeStoryDate, parseStoryDate, storyDateKey, storyYear } from "@/lib/story-date";
|
||||||
|
|
||||||
|
describe("parseStoryDate", () => {
|
||||||
|
it("läser år, månad och dag", () => {
|
||||||
|
expect(parseStoryDate("1987")).toEqual({ year: 1987 });
|
||||||
|
expect(parseStoryDate("1987-03")).toEqual({ year: 1987, month: 3 });
|
||||||
|
expect(parseStoryDate("1987-03-04")).toEqual({ year: 1987, month: 3, day: 4 });
|
||||||
|
expect(parseStoryDate(" 2004-6-2 ")).toEqual({ year: 2004, month: 6, day: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("avvisar ogiltiga datum", () => {
|
||||||
|
for (const bad of ["", "abc", "1987-13", "1987-00", "1987-02-30", "1987-04-31", "2023-02-29", "0000", "1987-03-04-05", "-5", 1987, null, undefined]) {
|
||||||
|
expect(parseStoryDate(bad)).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan skrivas utan att Date används, så att berättelsen får ligga var som helst", () => {
|
||||||
|
expect(parseStoryDate("0850")).toEqual({ year: 850 });
|
||||||
|
expect(parseStoryDate("2400-12-31")).toEqual({ year: 2400, month: 12, day: 31 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skottår stämmer", () => {
|
||||||
|
expect(parseStoryDate("2024-02-29")).not.toBeNull();
|
||||||
|
expect(parseStoryDate("1900-02-29")).toBeNull();
|
||||||
|
expect(parseStoryDate("2000-02-29")).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("normalizeStoryDate", () => {
|
||||||
|
it("skriver datum i fast form", () => {
|
||||||
|
expect(normalizeStoryDate("1987")).toBe("1987");
|
||||||
|
expect(normalizeStoryDate("987")).toBe("0987");
|
||||||
|
expect(normalizeStoryDate("2004-6-2")).toBe("2004-06-02");
|
||||||
|
expect(normalizeStoryDate("2004-6")).toBe("2004-06");
|
||||||
|
expect(normalizeStoryDate("nej")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sortering", () => {
|
||||||
|
it("ett årtal kommer före datumen samma år", () => {
|
||||||
|
expect(storyDateKey("1987")).toBeLessThan(storyDateKey("1987-01-01"));
|
||||||
|
expect(storyDateKey("1987-03")).toBeLessThan(storyDateKey("1987-03-04"));
|
||||||
|
expect(["1990", "1987-12-31", "1987", "1987-03"].sort(compareStoryDates)).toEqual(["1987", "1987-03", "1987-12-31", "1990"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ogiltigt datum ger NaN", () => {
|
||||||
|
expect(storyDateKey("x")).toBeNaN();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ageAt", () => {
|
||||||
|
it("räknar hela år med födelsedag", () => {
|
||||||
|
expect(ageAt("1990-06-15", "2020-06-14")).toBe(29);
|
||||||
|
expect(ageAt("1990-06-15", "2020-06-15")).toBe(30);
|
||||||
|
expect(ageAt("1990-06-15", "2020-12-31")).toBe(30);
|
||||||
|
expect(ageAt("1990-06-15", "2020-01-01")).toBe(29);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("räknar bara på år när månad saknas", () => {
|
||||||
|
expect(ageAt("1990", "2020-01-01")).toBe(30);
|
||||||
|
expect(ageAt("1990-06-15", "2020")).toBe(30);
|
||||||
|
expect(ageAt("1990-06", "2020-05")).toBe(29);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kan inte vara negativ", () => {
|
||||||
|
expect(ageAt("2000-01-01", "1999-12-31")).toBeNull();
|
||||||
|
expect(ageAt("2000", "1999")).toBeNull();
|
||||||
|
expect(ageAt("2000-01-01", "2000-01-01")).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ogiltiga datum ger null", () => {
|
||||||
|
expect(ageAt("x", "2000")).toBeNull();
|
||||||
|
expect(ageAt("2000", "y")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("storyYear", () => {
|
||||||
|
it("ger året", () => {
|
||||||
|
expect(storyYear("1987-03-04")).toBe(1987);
|
||||||
|
expect(storyYear("tomt")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { buildTimeline, TIMELINE_KINDS, type TimelineInput, type TimelineKind } from "@/lib/timeline";
|
||||||
|
|
||||||
|
const anna = { id: "anna", name: "Anna" };
|
||||||
|
const bo = { id: "bo", name: "Bo" };
|
||||||
|
|
||||||
|
const input = (overrides: Partial<TimelineInput> = {}): TimelineInput => ({
|
||||||
|
characters: [
|
||||||
|
{ ...anna, birthDate: "1960-05-10", deathDate: "2020-01-15" },
|
||||||
|
{ ...bo, birthDate: "1990" },
|
||||||
|
],
|
||||||
|
scenarios: [],
|
||||||
|
events: [],
|
||||||
|
relations: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildTimeline", () => {
|
||||||
|
it("tar födelse och död från karaktärernas datum, i datumordning", () => {
|
||||||
|
const { items } = buildTimeline(input());
|
||||||
|
expect(items.map((i) => [i.kind, i.title, i.date])).toEqual([
|
||||||
|
["birth", "Anna", "1960-05-10"],
|
||||||
|
["birth", "Bo", "1990"],
|
||||||
|
["death", "Anna", "2020-01-15"],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("räknar ut åldern vid varje händelse", () => {
|
||||||
|
const { items } = buildTimeline(
|
||||||
|
input({ events: [{ id: "e1", title: "Bröllop", date: "1985-08-01", people: [anna, bo] }, { id: "e2", title: "Fest", date: "2005", people: [anna, bo] }] }),
|
||||||
|
);
|
||||||
|
const wedding = items.find((i) => i.title === "Bröllop")!;
|
||||||
|
// Bo är inte född 1985
|
||||||
|
expect(wedding.ages).toEqual([{ id: "anna", name: "Anna", age: 25 }]);
|
||||||
|
const party = items.find((i) => i.title === "Fest")!;
|
||||||
|
// Bara året är känt för festen, så åldern blir skillnaden i år
|
||||||
|
expect(party.ages.map((a) => [a.name, a.age])).toEqual([
|
||||||
|
["Anna", 45],
|
||||||
|
["Bo", 15],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("visar ingen ålder för den som hunnit dö", () => {
|
||||||
|
const { items } = buildTimeline(input({ events: [{ id: "e", title: "Minnesstund", date: "2021", people: [anna, bo] }] }));
|
||||||
|
expect(items.find((i) => i.title === "Minnesstund")!.ages.map((a) => a.name)).toEqual(["Bo"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("visar ingen ålder vid födelsen själv", () => {
|
||||||
|
const { items } = buildTimeline(input());
|
||||||
|
expect(items.find((i) => i.kind === "birth")!.ages).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scenarier utan datum hamnar i en egen lista", () => {
|
||||||
|
const { items, undated } = buildTimeline(
|
||||||
|
input({
|
||||||
|
scenarios: [
|
||||||
|
{ id: "s1", name: "Olyckan", date: "1999-07-01", type: "Olycka", people: [anna] },
|
||||||
|
{ id: "s2", name: "Rymmen", date: null, people: [] },
|
||||||
|
{ id: "s3", name: "Trasigt", date: "inte ett datum", people: [] },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(items.filter((i) => i.kind === "scenario").map((i) => [i.title, i.detail])).toEqual([["Olyckan", "Olycka"]]);
|
||||||
|
expect(undated.map((u) => u.title)).toEqual(["Rymmen", "Trasigt"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("relationer med period visas från startdatumet", () => {
|
||||||
|
const { items } = buildTimeline(input({ relations: [{ id: "r", type: "Gift", startDate: "2004-06", endDate: "2011", people: [anna, bo] }] }));
|
||||||
|
const relation = items.find((i) => i.kind === "relation")!;
|
||||||
|
expect(relation).toMatchObject({ date: "2004-06", endDate: "2011", endOnly: false, title: "Gift" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("en relation med bara slutdatum markeras som ett slut", () => {
|
||||||
|
const { items } = buildTimeline(input({ relations: [{ id: "r", type: "Vänner", startDate: null, endDate: "2001", people: [anna, bo] }] }));
|
||||||
|
expect(items.find((i) => i.kind === "relation")).toMatchObject({ date: "2001", endDate: null, endOnly: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("relationer utan datum visas inte", () => {
|
||||||
|
const { items } = buildTimeline(input({ relations: [{ id: "r", type: "Vänner", people: [anna, bo] }] }));
|
||||||
|
expect(items.some((i) => i.kind === "relation")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ogiltiga datum ignoreras utan fel", () => {
|
||||||
|
const { items } = buildTimeline(input({ characters: [{ ...anna, birthDate: "förra veckan", deathDate: "1999-02-30" }], events: [{ id: "e", title: "X", date: "oklart", people: [] }] }));
|
||||||
|
expect(items).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filtrerar på typ", () => {
|
||||||
|
const events = [{ id: "e", title: "Flytt", date: "2000", people: [anna] }];
|
||||||
|
const only = (...kinds: TimelineKind[]) => buildTimeline(input({ events }), new Set(kinds)).items.map((i) => i.kind);
|
||||||
|
expect(only("event")).toEqual(["event"]);
|
||||||
|
expect(only("birth", "death")).toEqual(["birth", "birth", "death"]);
|
||||||
|
expect(buildTimeline(input({ events }), new Set(TIMELINE_KINDS)).items).toHaveLength(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filtrerar på person", () => {
|
||||||
|
const events = [{ id: "e1", title: "Flytt", date: "2000", people: [anna] }, { id: "e2", title: "Resa", date: "2001", people: [bo] }];
|
||||||
|
const { items, undated } = buildTimeline(input({ events, scenarios: [{ id: "s", name: "Utan datum", date: null, people: [] }] }), undefined, "bo");
|
||||||
|
expect(items.map((i) => i.title)).toEqual(["Bo", "Resa"]);
|
||||||
|
expect(undated).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorterar år före månader och dagar samma år", () => {
|
||||||
|
const { items } = buildTimeline(
|
||||||
|
input({
|
||||||
|
characters: [],
|
||||||
|
events: [
|
||||||
|
{ id: "1", title: "Dag", date: "2000-03-04", people: [] },
|
||||||
|
{ id: "2", title: "År", date: "2000", people: [] },
|
||||||
|
{ id: "3", title: "Månad", date: "2000-03", people: [] },
|
||||||
|
{ id: "4", title: "Tidigare", date: "1999-12-31", people: [] },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(items.map((i) => i.title)).toEqual(["Tidigare", "År", "Månad", "Dag"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normaliserar datum som skrivits för hand", () => {
|
||||||
|
const { items } = buildTimeline(input({ characters: [], events: [{ id: "1", title: "A", date: "2000-3-4", people: [] }] }));
|
||||||
|
expect(items[0].date).toBe("2000-03-04");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tom bok ger tom tidslinje", () => {
|
||||||
|
expect(buildTimeline({ characters: [], scenarios: [], events: [], relations: [] })).toEqual({ items: [], undated: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("länkar går till rätt sida", () => {
|
||||||
|
const { items } = buildTimeline(input({ events: [{ id: "e1", title: "Flytt", date: "2000", people: [] }], relations: [{ id: "r1", type: "Gift", startDate: "2000", people: [] }] }));
|
||||||
|
expect(items.find((i) => i.kind === "event")!.link).toBe("timeline/e1");
|
||||||
|
expect(items.find((i) => i.kind === "relation")!.link).toBe("relations/r1");
|
||||||
|
expect(items.find((i) => i.kind === "birth" && i.title === "Anna")!.link).toBe("entity/anna");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user