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
+2285
-25
No files matched your search
@@ -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 { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||
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";
|
||||
|
||||
/** Skickar exporten genom samma zip-format som exportknappen och läser tillbaka den. */
|
||||
@@ -136,9 +136,9 @@ describeDb("export och import", () => {
|
||||
const data = validExport({
|
||||
entities: [entityRow("a", "CHARACTER", "Anna", { image: "saknas.png" }), entityRow("b", "CHARACTER", "Bo", { image: "skräp.png" })],
|
||||
relations: [
|
||||
{ id: "r1", code: null, fromId: "a", toId: "b", type: "Vänner", description: null, data: {}, members: ["finns-inte"] },
|
||||
{ id: "r2", code: null, fromId: "a", toId: "okänd", type: "Fiende", description: null, data: {}, members: [] },
|
||||
{ id: "r3", code: null, fromId: "a", toId: "a", type: "Självrelation", description: null, data: {}, members: [] },
|
||||
relationRow("r1", "a", "b", "Vänner", { members: ["finns-inte"] }),
|
||||
relationRow("r2", "a", "okänd", "Fiende"),
|
||||
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 }],
|
||||
});
|
||||
|
||||
+16
-3
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
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 { prisma } from "@/lib/db";
|
||||
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({
|
||||
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 },
|
||||
entities: [],
|
||||
relations: [],
|
||||
events: [],
|
||||
shifts: [],
|
||||
maps: [],
|
||||
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 };
|
||||
}
|
||||
|
||||
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. */
|
||||
export async function makeImage(
|
||||
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