first commit
This commit is contained in:
commit
b7b0f253ce
85 files changed
+7560
No files matched your search
@@ -0,0 +1,54 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { deleteImage } from "@/lib/files";
|
||||
import { optStr, revalidateBook, str } from "@/lib/form";
|
||||
import { requireBook, requireUser } from "@/lib/session";
|
||||
|
||||
export async function createBook(formData: FormData) {
|
||||
const user = await requireUser();
|
||||
const title = str(formData, "title", 200);
|
||||
if (!title) return;
|
||||
const book = await prisma.book.create({
|
||||
data: {
|
||||
ownerId: user.id,
|
||||
title,
|
||||
subtitle: optStr(formData, "subtitle", 200),
|
||||
genre: optStr(formData, "genre", 100),
|
||||
description: optStr(formData, "description"),
|
||||
},
|
||||
});
|
||||
revalidatePath("/");
|
||||
redirect(`/books/${book.id}`);
|
||||
}
|
||||
|
||||
export async function updateBook(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const title = str(formData, "title", 200);
|
||||
if (!title) return;
|
||||
await prisma.book.update({
|
||||
where: { id: book.id },
|
||||
data: {
|
||||
title,
|
||||
subtitle: optStr(formData, "subtitle", 200),
|
||||
genre: optStr(formData, "genre", 100),
|
||||
description: optStr(formData, "description"),
|
||||
},
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function deleteBook(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const [entities, maps] = await Promise.all([
|
||||
prisma.entity.findMany({ where: { bookId: book.id, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||
prisma.bookMap.findMany({ where: { bookId: book.id, imageFile: { not: null } }, select: { imageFile: true } }),
|
||||
]);
|
||||
await prisma.book.delete({ where: { id: book.id } });
|
||||
await Promise.all([...entities, ...maps].map((row) => deleteImage(row.imageFile)));
|
||||
revalidatePath("/");
|
||||
redirect("/");
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use server";
|
||||
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { deleteImage, isUpload, saveImage } from "@/lib/files";
|
||||
import { optStr, parseTags, revalidateBook, str } from "@/lib/form";
|
||||
import { KIND_INFO, parseKind } from "@/lib/kinds";
|
||||
import { requireBook, requireEntity } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
import { getLocale } from "@/i18n/server";
|
||||
|
||||
export async function saveEntity(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const id = str(formData, "id");
|
||||
const existing = id ? await requireEntity(book.id, id) : null;
|
||||
const kind = existing?.kind ?? parseKind(str(formData, "kind"));
|
||||
if (!kind) throw new Error("Invalid kind");
|
||||
|
||||
const name = str(formData, "name", 200);
|
||||
if (!name) throw new Error("Name is required");
|
||||
|
||||
const { fields } = await getTemplate(book.id, kind, await getLocale());
|
||||
const data: Record<string, unknown> = { ...((existing?.data as Record<string, unknown> | null) ?? {}) };
|
||||
for (const field of fields) {
|
||||
const name = `f_${field.key}`;
|
||||
if (field.type === "checkbox") {
|
||||
data[field.key] = formData.has(name);
|
||||
continue;
|
||||
}
|
||||
const raw = str(formData, name, 20000);
|
||||
if (raw === "") {
|
||||
delete data[field.key];
|
||||
} else if (field.type === "number") {
|
||||
const n = Number(raw.replace(",", "."));
|
||||
if (Number.isFinite(n)) data[field.key] = n;
|
||||
} else {
|
||||
data[field.key] = raw;
|
||||
}
|
||||
}
|
||||
|
||||
let imageFile = existing?.imageFile ?? null;
|
||||
const upload = formData.get("image");
|
||||
if (isUpload(upload)) {
|
||||
const saved = await saveImage(upload);
|
||||
await deleteImage(imageFile);
|
||||
imageFile = saved;
|
||||
} else if (formData.has("removeImage")) {
|
||||
await deleteImage(imageFile);
|
||||
imageFile = null;
|
||||
}
|
||||
|
||||
const values = {
|
||||
name,
|
||||
code: optStr(formData, "code", 50),
|
||||
summary: optStr(formData, "summary"),
|
||||
tags: parseTags(str(formData, "tags", 1000)),
|
||||
data: data as Prisma.InputJsonObject,
|
||||
imageFile,
|
||||
};
|
||||
|
||||
const saved = existing
|
||||
? await prisma.entity.update({ where: { id: existing.id }, data: values })
|
||||
: await prisma.entity.create({ data: { ...values, bookId: book.id, kind } });
|
||||
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/entity/${saved.id}`);
|
||||
}
|
||||
|
||||
export async function deleteEntity(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const entity = await requireEntity(book.id, str(formData, "id"));
|
||||
await prisma.entity.delete({ where: { id: entity.id } });
|
||||
await deleteImage(entity.imageFile);
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/e/${KIND_INFO[entity.kind].slug}`);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { deleteImage, isUpload, saveImage } from "@/lib/files";
|
||||
import { revalidateBook, str } from "@/lib/form";
|
||||
import { MARKER_COLORS } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
async function requireMap(bookId: string, mapId: string) {
|
||||
const book = await requireBook(bookId);
|
||||
const map = await prisma.bookMap.findFirst({ where: { id: mapId, bookId: book.id } });
|
||||
if (!map) throw new Error("Map not found");
|
||||
return { book, map };
|
||||
}
|
||||
|
||||
export async function createMap(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const name = str(formData, "name", 200);
|
||||
const kind = str(formData, "kind") === "IMAGE" ? "IMAGE" : "GEO";
|
||||
if (!name) return;
|
||||
|
||||
let imageFile: string | null = null;
|
||||
if (kind === "IMAGE") {
|
||||
const upload = formData.get("image");
|
||||
if (!isUpload(upload)) return;
|
||||
imageFile = await saveImage(upload);
|
||||
}
|
||||
|
||||
const map = await prisma.bookMap.create({ data: { bookId: book.id, name, kind, imageFile } });
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/maps/${map.id}`);
|
||||
}
|
||||
|
||||
export async function renameMap(formData: FormData) {
|
||||
const { book, map } = await requireMap(str(formData, "bookId"), str(formData, "mapId"));
|
||||
const name = str(formData, "name", 200);
|
||||
if (!name) return;
|
||||
await prisma.bookMap.update({ where: { id: map.id }, data: { name } });
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function deleteMap(formData: FormData) {
|
||||
const { book, map } = await requireMap(str(formData, "bookId"), str(formData, "mapId"));
|
||||
await prisma.bookMap.delete({ where: { id: map.id } });
|
||||
await deleteImage(map.imageFile);
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/maps`);
|
||||
}
|
||||
|
||||
export async function saveMapView(bookId: string, mapId: string, lat: number, lng: number, zoom: number) {
|
||||
const { book, map } = await requireMap(bookId, mapId);
|
||||
if (![lat, lng, zoom].every(Number.isFinite)) return;
|
||||
await prisma.bookMap.update({
|
||||
where: { id: map.id },
|
||||
data: { centerLat: lat, centerLng: lng, zoom: Math.round(zoom) },
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export type MarkerInput = {
|
||||
label: string;
|
||||
note: string;
|
||||
color: string;
|
||||
entityId: string | null;
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
|
||||
async function cleanMarker(bookId: string, input: MarkerInput) {
|
||||
const label = String(input.label ?? "").trim().slice(0, 200);
|
||||
if (!label) throw new Error("Label is required");
|
||||
if (!Number.isFinite(input.lat) || !Number.isFinite(input.lng)) throw new Error("Invalid position");
|
||||
const color = input.color in MARKER_COLORS ? input.color : "blue";
|
||||
let entityId: string | null = null;
|
||||
if (input.entityId) {
|
||||
const entity = await prisma.entity.findFirst({ where: { id: input.entityId, bookId }, select: { id: true } });
|
||||
entityId = entity?.id ?? null;
|
||||
}
|
||||
return {
|
||||
label,
|
||||
note: String(input.note ?? "").trim().slice(0, 5000) || null,
|
||||
color,
|
||||
entityId,
|
||||
lat: input.lat,
|
||||
lng: input.lng,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createMarker(bookId: string, mapId: string, input: MarkerInput) {
|
||||
const { book, map } = await requireMap(bookId, mapId);
|
||||
await prisma.marker.create({ data: { ...(await cleanMarker(book.id, input)), mapId: map.id } });
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function updateMarker(bookId: string, mapId: string, markerId: string, input: MarkerInput) {
|
||||
const { book, map } = await requireMap(bookId, mapId);
|
||||
await prisma.marker.updateMany({
|
||||
where: { id: markerId, mapId: map.id },
|
||||
data: await cleanMarker(book.id, input),
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function moveMarker(bookId: string, mapId: string, markerId: string, lat: number, lng: number) {
|
||||
const { book, map } = await requireMap(bookId, mapId);
|
||||
if (![lat, lng].every(Number.isFinite)) return;
|
||||
await prisma.marker.updateMany({ where: { id: markerId, mapId: map.id }, data: { lat, lng } });
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function deleteMarker(bookId: string, mapId: string, markerId: string) {
|
||||
const { book, map } = await requireMap(bookId, mapId);
|
||||
await prisma.marker.deleteMany({ where: { id: markerId, mapId: map.id } });
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use server";
|
||||
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { optStr, revalidateBook, str } from "@/lib/form";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
import { getLocale } from "@/i18n/server";
|
||||
|
||||
/** Extra deltagare från formuläret: bara poster i boken, utan dubbletter och utan from/to. */
|
||||
async function cleanMemberIds(bookId: string, formData: FormData, exclude: string[]): Promise<string[]> {
|
||||
const wanted = [...new Set(formData.getAll("memberIds").map(String))].filter((id) => id && !exclude.includes(id));
|
||||
if (wanted.length === 0) return [];
|
||||
const found = await prisma.entity.findMany({ where: { bookId, id: { in: wanted } }, select: { id: true } });
|
||||
return found.map((e) => e.id);
|
||||
}
|
||||
|
||||
export async function addRelation(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const fromId = str(formData, "fromId");
|
||||
const toId = str(formData, "toId");
|
||||
const type = str(formData, "type", 100);
|
||||
if (!fromId || !toId || !type || fromId === toId) return;
|
||||
|
||||
// Båda posterna måste höra till boken
|
||||
const count = await prisma.entity.count({ where: { bookId: book.id, id: { in: [fromId, toId] } } });
|
||||
if (count !== 2) return;
|
||||
|
||||
const memberIds = await cleanMemberIds(book.id, formData, [fromId, toId]);
|
||||
await prisma.relation.create({
|
||||
data: {
|
||||
bookId: book.id,
|
||||
fromId,
|
||||
toId,
|
||||
type,
|
||||
description: optStr(formData, "description", 2000),
|
||||
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
||||
},
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function saveRelation(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const relation = await prisma.relation.findFirst({ where: { id: str(formData, "id"), bookId: book.id } });
|
||||
if (!relation) throw new Error("Relation not found");
|
||||
const type = str(formData, "type", 100);
|
||||
if (!type) return;
|
||||
|
||||
const { fields } = await getTemplate(book.id, "RELATION", await getLocale());
|
||||
const data: Record<string, unknown> = { ...((relation.data as Record<string, unknown> | null) ?? {}) };
|
||||
for (const field of fields) {
|
||||
const name = `f_${field.key}`;
|
||||
if (field.type === "checkbox") {
|
||||
data[field.key] = formData.has(name);
|
||||
continue;
|
||||
}
|
||||
const raw = str(formData, name, 20000);
|
||||
if (raw === "") {
|
||||
delete data[field.key];
|
||||
} else if (field.type === "number") {
|
||||
const n = Number(raw.replace(",", "."));
|
||||
if (Number.isFinite(n)) data[field.key] = n;
|
||||
} else {
|
||||
data[field.key] = raw;
|
||||
}
|
||||
}
|
||||
|
||||
const memberIds = await cleanMemberIds(book.id, formData, [relation.fromId, relation.toId]);
|
||||
await prisma.$transaction([
|
||||
prisma.relationMember.deleteMany({ where: { relationId: relation.id } }),
|
||||
prisma.relation.update({
|
||||
where: { id: relation.id },
|
||||
data: {
|
||||
type,
|
||||
description: optStr(formData, "description", 2000),
|
||||
data: data as Prisma.InputJsonObject,
|
||||
members: { create: memberIds.map((entityId) => ({ entityId })) },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/relations/${relation.id}?saved=1`);
|
||||
}
|
||||
|
||||
export async function deleteRelation(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
await prisma.relation.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
|
||||
revalidateBook(book.id);
|
||||
if (formData.get("redirect") === "list") redirect(`/books/${book.id}/relations`);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { cookies } from "next/headers";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { isLocale } from "@/i18n/core";
|
||||
|
||||
export async function setLocale(formData: FormData) {
|
||||
const locale = formData.get("locale");
|
||||
if (!isLocale(locale)) return;
|
||||
(await cookies()).set("lang", locale, { path: "/", maxAge: 60 * 60 * 24 * 365, sameSite: "lax" });
|
||||
revalidatePath("/", "layout");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use server";
|
||||
|
||||
import type { WeekPattern } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { optStr, revalidateBook, str } from "@/lib/form";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
export async function addShifts(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const personId = str(formData, "personId");
|
||||
const workplaceId = str(formData, "workplaceId") || null;
|
||||
const startTime = str(formData, "startTime");
|
||||
const endTime = str(formData, "endTime");
|
||||
const weeksRaw = str(formData, "weeks");
|
||||
const weeks: WeekPattern = weeksRaw === "ODD" || weeksRaw === "EVEN" ? weeksRaw : "ALL";
|
||||
const days = [...new Set(formData.getAll("days").map((d) => Number(d)))].filter(
|
||||
(d) => Number.isInteger(d) && d >= 0 && d <= 6,
|
||||
);
|
||||
|
||||
if (!personId || days.length === 0 || !TIME.test(startTime) || !TIME.test(endTime)) return;
|
||||
|
||||
const ids = [personId, ...(workplaceId ? [workplaceId] : [])];
|
||||
const found = await prisma.entity.count({ where: { bookId: book.id, id: { in: ids } } });
|
||||
if (found !== ids.length) return;
|
||||
|
||||
const label = optStr(formData, "label", 100);
|
||||
await prisma.shift.createMany({
|
||||
data: days.map((weekday) => ({
|
||||
bookId: book.id,
|
||||
personId,
|
||||
workplaceId,
|
||||
weekday,
|
||||
startTime,
|
||||
endTime,
|
||||
weeks,
|
||||
label,
|
||||
})),
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
|
||||
export async function deleteShift(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
await prisma.shift.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
|
||||
revalidateBook(book.id);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"use server";
|
||||
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { revalidateBook, str } from "@/lib/form";
|
||||
import { parseTemplateKind, templateSlug } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { validateFields } from "@/lib/templates";
|
||||
|
||||
export async function saveTemplate(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const kind = parseTemplateKind(str(formData, "kind"));
|
||||
if (!kind) throw new Error("Invalid kind");
|
||||
const url = `/books/${book.id}/templates/${templateSlug(kind)}`;
|
||||
|
||||
let fields;
|
||||
try {
|
||||
fields = validateFields(JSON.parse(str(formData, "fields", 200000)));
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "unknown";
|
||||
redirect(`${url}?error=${encodeURIComponent(reason)}`);
|
||||
}
|
||||
|
||||
await prisma.template.upsert({
|
||||
where: { bookId_kind: { bookId: book.id, kind } },
|
||||
update: { fields: fields as unknown as Prisma.InputJsonArray },
|
||||
create: { bookId: book.id, kind, fields: fields as unknown as Prisma.InputJsonArray },
|
||||
});
|
||||
revalidateBook(book.id);
|
||||
redirect(`${url}?saved=1`);
|
||||
}
|
||||
|
||||
export async function resetTemplate(formData: FormData) {
|
||||
const book = await requireBook(str(formData, "bookId"));
|
||||
const kind = parseTemplateKind(str(formData, "kind"));
|
||||
if (!kind) throw new Error("Invalid kind");
|
||||
await prisma.template.deleteMany({ where: { bookId: book.id, kind } });
|
||||
revalidateBook(book.id);
|
||||
redirect(`/books/${book.id}/templates/${templateSlug(kind)}`);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Shell } from "@/components/shell";
|
||||
import { requireUser } from "@/lib/session";
|
||||
|
||||
export default async function MainLayout({ children }: { children: React.ReactNode }) {
|
||||
const user = await requireUser();
|
||||
return <Shell user={user}>{children}</Shell>;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Link from "next/link";
|
||||
import { IconBook2 } from "@tabler/icons-react";
|
||||
import { createBook } from "@/actions/books";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireUser } from "@/lib/session";
|
||||
|
||||
export const metadata = { title: "Mina böcker" };
|
||||
|
||||
export default async function BooksPage() {
|
||||
const user = await requireUser();
|
||||
const { t } = await getT();
|
||||
const books = await prisma.book.findMany({
|
||||
where: { ownerId: user.id },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
include: { _count: { select: { entities: true } } },
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("books.title")} />
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
{books.length === 0 ? (
|
||||
<EmptyState>{t("books.empty")}</EmptyState>
|
||||
) : (
|
||||
<div className="row row-cards">
|
||||
{books.map((book) => (
|
||||
<div className="col-md-6" key={book.id}>
|
||||
<Link href={`/books/${book.id}`} className="card card-link card-link-pop h-100">
|
||||
<div className="card-body">
|
||||
<div className="d-flex align-items-center gap-3 mb-2">
|
||||
<span className="avatar bg-primary-lt">
|
||||
<IconBook2 size={22} />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="card-title mb-0 text-truncate">{book.title}</div>
|
||||
{book.subtitle ? <div className="text-secondary text-truncate">{book.subtitle}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
{book.description ? <p className="text-secondary mb-2 text-truncate">{book.description}</p> : null}
|
||||
<div className="d-flex gap-2">
|
||||
{book.genre ? <span className="badge bg-azure-lt">{book.genre}</span> : null}
|
||||
<span className="badge">{t("books.items", { n: book._count.entities })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<form action={createBook} className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("books.new")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="mb-3">
|
||||
<label className="form-label required">{t("common.title")}</label>
|
||||
<input name="title" className="form-control" required maxLength={200} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">{t("books.subtitle")}</label>
|
||||
<input name="subtitle" className="form-control" maxLength={200} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">{t("books.genre")}</label>
|
||||
<input name="genre" className="form-control" maxLength={100} />
|
||||
</div>
|
||||
<div className="mb-0">
|
||||
<label className="form-label">{t("common.description")}</label>
|
||||
<textarea name="description" className="form-control" rows={3} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer text-end">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("books.create")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/auth";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { auth } from "@/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ bookId: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { bookId } = await params;
|
||||
const book = await prisma.book.findFirst({
|
||||
where: { id: bookId, ownerId: session.user.id },
|
||||
include: {
|
||||
entities: true,
|
||||
relations: { include: { members: true } },
|
||||
shifts: true,
|
||||
templates: true,
|
||||
maps: { include: { markers: true } },
|
||||
},
|
||||
});
|
||||
if (!book) return new Response("Not found", { status: 404 });
|
||||
|
||||
const safeName = book.title.replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "").slice(0, 60) || "book";
|
||||
return new Response(JSON.stringify({ exportedAt: new Date().toISOString(), book }, null, 2), {
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="${safeName}.json"; filename*=UTF-8''${encodeURIComponent(safeName)}.json`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { auth } from "@/auth";
|
||||
import { CONTENT_TYPES, FILE_NAME_PATTERN, UPLOAD_DIR } from "@/lib/files";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ name: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { name } = await params;
|
||||
if (!FILE_NAME_PATTERN.test(name)) return new Response("Not found", { status: 404 });
|
||||
|
||||
try {
|
||||
const data = await readFile(path.join(UPLOAD_DIR, name));
|
||||
const ext = name.split(".").pop() ?? "";
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: {
|
||||
"Content-Type": CONTENT_TYPES[ext] ?? "application/octet-stream",
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
return Response.json({ status: "ok" });
|
||||
} catch {
|
||||
return Response.json({ status: "error" }, { status: 503 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { saveEntity } from "@/actions/entities";
|
||||
import { EntityForm } from "@/components/entity-form";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { KIND_BY_SLUG } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
|
||||
export default async function NewEntityPage({ params }: { params: Promise<{ bookId: string; kind: string }> }) {
|
||||
const { bookId, kind: slug } = await params;
|
||||
await requireBook(bookId);
|
||||
const info = KIND_BY_SLUG.get(slug);
|
||||
if (!info) notFound();
|
||||
const { t, locale } = await getT();
|
||||
const { fields } = await getTemplate(bookId, info.kind, locale);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t(`kind.${info.kind}.new`)} pretitle={t(`kind.${info.kind}.other`)} />
|
||||
<PageBody>
|
||||
<EntityForm
|
||||
action={saveEntity}
|
||||
bookId={bookId}
|
||||
kind={info.kind}
|
||||
fields={fields}
|
||||
cancelHref={`/books/${bookId}/e/${slug}`}
|
||||
t={t}
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { IconPlus, IconSearch } from "@tabler/icons-react";
|
||||
import { kindIcons } from "@/components/kind-icons";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { fileUrl } from "@/lib/files";
|
||||
import { KIND_BY_SLUG } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export default async function EntityListPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string; kind: string }>;
|
||||
searchParams: Promise<{ q?: string; tag?: string }>;
|
||||
}) {
|
||||
const { bookId, kind: slug } = await params;
|
||||
const { q, tag } = await searchParams;
|
||||
await requireBook(bookId);
|
||||
const info = KIND_BY_SLUG.get(slug);
|
||||
if (!info) notFound();
|
||||
const { t } = await getT();
|
||||
const Icon = kindIcons[info.kind];
|
||||
|
||||
const entities = await prisma.entity.findMany({
|
||||
where: {
|
||||
bookId,
|
||||
kind: info.kind,
|
||||
...(q
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: q, mode: "insensitive" } },
|
||||
{ summary: { contains: q, mode: "insensitive" } },
|
||||
{ code: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
...(tag ? { tags: { has: tag } } : {}),
|
||||
},
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
const base = `/books/${bookId}/e/${slug}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t(`kind.${info.kind}.other`)}
|
||||
actions={
|
||||
<Link href={`${base}/new`} className="btn btn-primary">
|
||||
<IconPlus size={18} className="me-1" />
|
||||
{t(`kind.${info.kind}.new`)}
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
<PageBody>
|
||||
<div className="card">
|
||||
<div className="card-body border-bottom py-3">
|
||||
<form className="d-flex gap-2 align-items-center">
|
||||
<div className="input-icon flex-grow-1">
|
||||
<span className="input-icon-addon">
|
||||
<IconSearch size={18} />
|
||||
</span>
|
||||
<input name="q" defaultValue={q} className="form-control" placeholder={t("entity.search")} />
|
||||
</div>
|
||||
{tag ? <input type="hidden" name="tag" value={tag} /> : null}
|
||||
<button className="btn" type="submit">
|
||||
{t("common.search")}
|
||||
</button>
|
||||
</form>
|
||||
{tag ? (
|
||||
<div className="mt-2">
|
||||
<Link href={base} className="badge bg-primary-lt text-decoration-none">
|
||||
{t("entity.filterTag", { tag })} ×
|
||||
</Link>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{entities.length === 0 ? (
|
||||
<div className="card-body">
|
||||
<EmptyState>{q || tag ? t("common.noResults") : t("entity.empty")}</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<tbody>
|
||||
{entities.map((entity) => {
|
||||
const image = fileUrl(entity.imageFile);
|
||||
return (
|
||||
<tr key={entity.id}>
|
||||
<td className="w-1">
|
||||
{image ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={image} alt="" className="bm-thumb" />
|
||||
) : (
|
||||
<span className={`avatar bg-${info.color}-lt`}>
|
||||
<Icon size={20} />
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<Link href={`/books/${bookId}/entity/${entity.id}`} className="fw-bold bm-table-link">
|
||||
{entity.name}
|
||||
</Link>
|
||||
{entity.code ? <span className="badge ms-2">{entity.code}</span> : null}
|
||||
{entity.summary ? (
|
||||
<div className="text-secondary text-truncate" style={{ maxWidth: "36rem" }}>
|
||||
{entity.summary}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td>
|
||||
{entity.tags.map((tagName) => (
|
||||
<Link
|
||||
key={tagName}
|
||||
href={`${base}?tag=${encodeURIComponent(tagName)}`}
|
||||
className="badge bg-azure-lt me-1 text-decoration-none"
|
||||
>
|
||||
{tagName}
|
||||
</Link>
|
||||
))}
|
||||
</td>
|
||||
<td className="text-end w-1">
|
||||
<Link href={`/books/${bookId}/entity/${entity.id}/edit`} className="btn btn-sm">
|
||||
{t("common.edit")}
|
||||
</Link>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { saveEntity } from "@/actions/entities";
|
||||
import { EntityForm } from "@/components/entity-form";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { requireEntity } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
|
||||
export default async function EditEntityPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
|
||||
const { bookId, entityId } = await params;
|
||||
const entity = await requireEntity(bookId, entityId);
|
||||
const { t, locale } = await getT();
|
||||
const { fields } = await getTemplate(bookId, entity.kind, locale);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("entity.editTitle", { name: entity.name })} pretitle={t(`kind.${entity.kind}.one`)} />
|
||||
<PageBody>
|
||||
<EntityForm
|
||||
action={saveEntity}
|
||||
bookId={bookId}
|
||||
kind={entity.kind}
|
||||
entity={entity}
|
||||
fields={fields}
|
||||
cancelHref={`/books/${bookId}/entity/${entity.id}`}
|
||||
t={t}
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import Link from "next/link";
|
||||
import { IconMapPin, IconPencil, IconTrash, IconX } from "@tabler/icons-react";
|
||||
import { deleteEntity } from "@/actions/entities";
|
||||
import { deleteRelation } from "@/actions/relations";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { kindIcons } from "@/components/kind-icons";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { RelationForm } from "@/components/relation-form";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { fileUrl } from "@/lib/files";
|
||||
import { KIND_INFO, WORKPLACE_KINDS } from "@/lib/kinds";
|
||||
import { requireEntity } from "@/lib/session";
|
||||
import { formatFieldValue, getTemplate, type FieldDef } from "@/lib/templates";
|
||||
|
||||
type Group = { section?: string; items: { field: FieldDef; value: string }[] };
|
||||
|
||||
function groupFields(fields: FieldDef[], data: Record<string, unknown>): Group[] {
|
||||
const groups: Group[] = [];
|
||||
let current: Group = { items: [] };
|
||||
for (const field of fields) {
|
||||
if (field.section) {
|
||||
if (current.items.length > 0) groups.push(current);
|
||||
current = { section: field.section, items: [] };
|
||||
}
|
||||
const value = formatFieldValue(field, data[field.key]);
|
||||
if (value) current.items.push({ field, value });
|
||||
}
|
||||
if (current.items.length > 0) groups.push(current);
|
||||
return groups;
|
||||
}
|
||||
|
||||
export default async function EntityPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
|
||||
const { bookId, entityId } = await params;
|
||||
const base = await requireEntity(bookId, entityId);
|
||||
const { t, locale } = await getT();
|
||||
|
||||
const [entity, template, allEntities, maps] = await Promise.all([
|
||||
prisma.entity.findUniqueOrThrow({
|
||||
where: { id: base.id },
|
||||
include: {
|
||||
outgoing: { include: { to: true, members: { include: { entity: true } } }, orderBy: { createdAt: "asc" } },
|
||||
incoming: { include: { from: true, members: { include: { entity: true } } }, orderBy: { createdAt: "asc" } },
|
||||
memberOf: {
|
||||
include: { relation: { include: { from: true, to: true, members: { include: { entity: true } } } } },
|
||||
},
|
||||
markers: { include: { map: true } },
|
||||
shifts: { include: { workplace: true }, orderBy: [{ weekday: "asc" }, { startTime: "asc" }] },
|
||||
hostedShifts: { include: { person: true }, orderBy: [{ weekday: "asc" }, { startTime: "asc" }] },
|
||||
},
|
||||
}),
|
||||
getTemplate(bookId, base.kind, locale),
|
||||
prisma.entity.findMany({
|
||||
where: { bookId },
|
||||
select: { id: true, name: true, kind: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.bookMap.findMany({ where: { bookId }, orderBy: { name: "asc" } }),
|
||||
]);
|
||||
|
||||
const info = KIND_INFO[entity.kind];
|
||||
const Icon = kindIcons[entity.kind];
|
||||
const image = fileUrl(entity.imageFile);
|
||||
const groups = groupFields(template.fields, (entity.data ?? {}) as Record<string, unknown>);
|
||||
const isWorkplace = WORKPLACE_KINDS.includes(entity.kind);
|
||||
type Person = { id: string; name: string };
|
||||
type RelationItem = {
|
||||
id: string;
|
||||
type: string;
|
||||
description: string | null;
|
||||
// outgoing/incoming: vanlig relation sedd från den här posten. group: posten är med i en grupp.
|
||||
layout: "outgoing" | "incoming" | "group";
|
||||
others: Person[];
|
||||
createdAt: Date;
|
||||
};
|
||||
const relationItems: RelationItem[] = [
|
||||
...entity.outgoing.map((r): RelationItem => {
|
||||
const group = r.members.length > 0;
|
||||
return {
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
description: r.description,
|
||||
layout: group ? "group" : "outgoing",
|
||||
others: [r.to, ...r.members.map((m) => m.entity)],
|
||||
createdAt: r.createdAt,
|
||||
};
|
||||
}),
|
||||
...entity.incoming.map((r): RelationItem => {
|
||||
const group = r.members.length > 0;
|
||||
return {
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
description: r.description,
|
||||
layout: group ? "group" : "incoming",
|
||||
others: [r.from, ...r.members.map((m) => m.entity)],
|
||||
createdAt: r.createdAt,
|
||||
};
|
||||
}),
|
||||
...entity.memberOf.map(({ relation: r }): RelationItem => ({
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
description: r.description,
|
||||
layout: "group",
|
||||
others: [r.from, r.to, ...r.members.map((m) => m.entity).filter((e) => e.id !== entity.id)],
|
||||
createdAt: r.createdAt,
|
||||
})),
|
||||
].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
||||
const hasRelations = relationItems.length > 0;
|
||||
const entityHref = (id: string) => `/books/${bookId}/entity/${id}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
pretitle={
|
||||
<Link href={`/books/${bookId}/e/${info.slug}`} className="text-reset">
|
||||
{t(`kind.${entity.kind}.other`)}
|
||||
</Link>
|
||||
}
|
||||
title={
|
||||
<span className="d-flex align-items-center gap-2">
|
||||
<Icon size={26} className={`text-${info.color}`} />
|
||||
{entity.name}
|
||||
{entity.code ? <span className="badge fs-5 ms-1">{entity.code}</span> : null}
|
||||
</span>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Link href={`${entityHref(entity.id)}/edit`} className="btn">
|
||||
<IconPencil size={18} className="me-1" />
|
||||
{t("common.edit")}
|
||||
</Link>
|
||||
<form action={deleteEntity}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={entity.id} />
|
||||
<ConfirmSubmit className="btn btn-outline-danger">
|
||||
<IconTrash size={18} className="me-1" />
|
||||
{t("common.delete")}
|
||||
</ConfirmSubmit>
|
||||
</form>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
{entity.tags.length > 0 || entity.summary ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-body">
|
||||
{entity.tags.length > 0 ? (
|
||||
<div className="mb-2">
|
||||
{entity.tags.map((tag) => (
|
||||
<Link
|
||||
key={tag}
|
||||
href={`/books/${bookId}/e/${info.slug}?tag=${encodeURIComponent(tag)}`}
|
||||
className="badge bg-azure-lt me-1 text-decoration-none"
|
||||
>
|
||||
{tag}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{entity.summary ? <div className="bm-prewrap">{entity.summary}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.details")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{groups.length === 0 ? (
|
||||
<div className="text-secondary">{t("entity.noDetails")}</div>
|
||||
) : (
|
||||
groups.map((group, i) => (
|
||||
<div key={i} className={i > 0 ? "mt-4" : ""}>
|
||||
{group.section ? <h4 className="subheader border-bottom pb-2 mb-3">{group.section}</h4> : null}
|
||||
<dl className="mb-0">
|
||||
{group.items.map(({ field, value }) => (
|
||||
<div className="row mb-2" key={field.key}>
|
||||
<dt className="col-sm-4 text-secondary fw-normal">{field.label}</dt>
|
||||
<dd className={`col-sm-8 mb-0 ${field.type === "textarea" ? "bm-prewrap" : ""}`}>
|
||||
{field.type === "url" ? (
|
||||
<a href={value} target="_blank" rel="noopener noreferrer nofollow">
|
||||
{value}
|
||||
</a>
|
||||
) : (
|
||||
value
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
{image ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-body p-2">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={image} alt={entity.name} className="bm-portrait" />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.relations")}</h3>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{!hasRelations ? <div className="list-group-item text-secondary">{t("entity.noRelations")}</div> : null}
|
||||
{relationItems.map((item) => (
|
||||
<div className="list-group-item d-flex align-items-center gap-2" key={item.id}>
|
||||
<div className="flex-fill min-w-0">
|
||||
{item.layout === "outgoing" ? (
|
||||
<>
|
||||
<Link href={`/books/${bookId}/relations/${item.id}`} className="text-secondary">
|
||||
{item.type}
|
||||
</Link>{" "}
|
||||
<EntityLinks bookId={bookId} entities={item.others} />
|
||||
</>
|
||||
) : item.layout === "incoming" ? (
|
||||
<>
|
||||
<EntityLinks bookId={bookId} entities={item.others} />{" "}
|
||||
<Link href={`/books/${bookId}/relations/${item.id}`} className="text-secondary">
|
||||
{item.type}
|
||||
</Link>{" "}
|
||||
{entity.name}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link href={`/books/${bookId}/relations/${item.id}`} className="text-secondary">
|
||||
{item.type}:
|
||||
</Link>{" "}
|
||||
<EntityLinks bookId={bookId} entities={item.others} />
|
||||
</>
|
||||
)}
|
||||
{item.description ? <div className="text-secondary small">{item.description}</div> : null}
|
||||
</div>
|
||||
<RemoveRelation bookId={bookId} id={item.id} label={t("common.delete")} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="card-body border-top">
|
||||
<RelationForm bookId={bookId} entities={allEntities} fixedFromId={entity.id} t={t} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entity.kind === "CHARACTER" ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.schedule")}</h3>
|
||||
<div className="card-actions">
|
||||
<Link href={`/books/${bookId}/schedules?person=${entity.id}`} className="btn btn-sm">
|
||||
{t("nav.schedules")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{entity.shifts.length === 0 ? <div className="list-group-item text-secondary">{t("entity.noShifts")}</div> : null}
|
||||
{entity.shifts.map((s) => (
|
||||
<div className="list-group-item" key={s.id}>
|
||||
<span className="fw-bold">{t(`day.short.${s.weekday}`)}</span> {s.startTime}–{s.endTime}
|
||||
{s.weeks !== "ALL" ? <span className="badge ms-1">{t(`schedule.weeks.${s.weeks}`)}</span> : null}
|
||||
<div className="text-secondary small">
|
||||
{[s.workplace?.name, s.label].filter(Boolean).join(" · ")}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isWorkplace ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.workers")}</h3>
|
||||
<div className="card-actions">
|
||||
<Link href={`/books/${bookId}/schedules?workplace=${entity.id}`} className="btn btn-sm">
|
||||
{t("nav.schedules")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{entity.hostedShifts.length === 0 ? <div className="list-group-item text-secondary">{t("entity.noWorkers")}</div> : null}
|
||||
{entity.hostedShifts.map((s) => (
|
||||
<div className="list-group-item" key={s.id}>
|
||||
<Link href={entityHref(s.person.id)} className="fw-bold">
|
||||
{s.person.name}
|
||||
</Link>
|
||||
<div className="text-secondary small">
|
||||
{t(`day.short.${s.weekday}`)} {s.startTime}–{s.endTime}
|
||||
{s.label ? ` · ${s.label}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.onMap")}</h3>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{entity.markers.length === 0 ? <div className="list-group-item text-secondary">{t("entity.noMarkers")}</div> : null}
|
||||
{entity.markers.map((m) => (
|
||||
<Link
|
||||
key={m.id}
|
||||
href={`/books/${bookId}/maps/${m.mapId}?marker=${m.id}`}
|
||||
className="list-group-item list-group-item-action d-flex align-items-center gap-2"
|
||||
>
|
||||
<IconMapPin size={18} />
|
||||
<span>{m.map.name}</span>
|
||||
<span className="text-secondary">· {m.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
{maps.map((map) => (
|
||||
<Link
|
||||
key={map.id}
|
||||
href={`/books/${bookId}/maps/${map.id}?place=${entity.id}`}
|
||||
className="list-group-item list-group-item-action text-primary"
|
||||
>
|
||||
{t("entity.placeOnMap")}: {map.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoveRelation({ bookId, id, label }: { bookId: string; id: string; label: string }) {
|
||||
return (
|
||||
<form action={deleteRelation}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={id} />
|
||||
<button type="submit" className="btn btn-icon btn-sm btn-ghost-secondary" title={label} aria-label={label}>
|
||||
<IconX size={16} />
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function EntityLinks({ bookId, entities }: { bookId: string; entities: { id: string; name: string }[] }) {
|
||||
return (
|
||||
<>
|
||||
{entities.map((e, i) => (
|
||||
<span key={e.id}>
|
||||
{i > 0 ? ", " : ""}
|
||||
<Link href={`/books/${bookId}/entity/${e.id}`} className="fw-bold">
|
||||
{e.name}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Shell } from "@/components/shell";
|
||||
import { requireBook, requireUser } from "@/lib/session";
|
||||
|
||||
export default async function BookLayout({
|
||||
children,
|
||||
params,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ bookId: string }>;
|
||||
}) {
|
||||
const { bookId } = await params;
|
||||
const user = await requireUser();
|
||||
const book = await requireBook(bookId);
|
||||
return (
|
||||
<Shell user={user} book={{ id: book.id, title: book.title }}>
|
||||
{children}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { deleteMap, renameMap } from "@/actions/maps";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { MapLoader } from "@/components/map-loader";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { fileUrl } from "@/lib/files";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
// Standard är OpenStreetMaps publika tjänster. Byt via miljövariabler vid tyngre användning.
|
||||
const TILE_URL = process.env.MAP_TILE_URL ?? "https://tile.openstreetmap.org/{z}/{x}/{y}.png";
|
||||
const TILE_ATTRIBUTION = process.env.MAP_TILE_ATTRIBUTION ?? "© OpenStreetMap-bidragsgivare";
|
||||
const GEOCODER_URL = process.env.MAP_GEOCODER_URL ?? "https://nominatim.openstreetmap.org/search";
|
||||
|
||||
export default async function MapPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string; mapId: string }>;
|
||||
searchParams: Promise<{ place?: string; marker?: string }>;
|
||||
}) {
|
||||
const { bookId, mapId } = await params;
|
||||
const { place, marker } = await searchParams;
|
||||
await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
|
||||
const [map, entities] = await Promise.all([
|
||||
prisma.bookMap.findFirst({ where: { id: mapId, bookId }, include: { markers: { orderBy: { createdAt: "asc" } } } }),
|
||||
prisma.entity.findMany({ where: { bookId }, select: { id: true, name: true, kind: true }, orderBy: { name: "asc" } }),
|
||||
]);
|
||||
if (!map) notFound();
|
||||
|
||||
const center: [number, number] | null =
|
||||
map.centerLat !== null && map.centerLng !== null ? [map.centerLat, map.centerLng] : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={map.name} pretitle={t("map.title")} />
|
||||
<PageBody>
|
||||
<MapLoader
|
||||
bookId={bookId}
|
||||
mapId={map.id}
|
||||
kind={map.kind}
|
||||
imageUrl={fileUrl(map.imageFile)}
|
||||
center={center}
|
||||
zoom={map.zoom}
|
||||
markers={map.markers.map((m) => ({
|
||||
id: m.id,
|
||||
label: m.label,
|
||||
note: m.note,
|
||||
color: m.color,
|
||||
lat: m.lat,
|
||||
lng: m.lng,
|
||||
entityId: m.entityId,
|
||||
}))}
|
||||
entities={entities}
|
||||
tileUrl={TILE_URL}
|
||||
tileAttribution={TILE_ATTRIBUTION}
|
||||
geocoderUrl={GEOCODER_URL}
|
||||
preselectEntityId={entities.some((e) => e.id === place) ? (place ?? null) : null}
|
||||
initialMarkerId={marker ?? null}
|
||||
/>
|
||||
|
||||
<div className="card mt-4">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("map.settings")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
<div className="col-md-6">
|
||||
<form action={renameMap} className="input-group">
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="mapId" value={map.id} />
|
||||
<input name="name" className="form-control" defaultValue={map.name} required maxLength={200} aria-label={t("map.rename")} />
|
||||
<button type="submit" className="btn">
|
||||
{t("map.rename")}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div className="col-md-6 d-flex align-items-center gap-3">
|
||||
<form action={deleteMap}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="mapId" value={map.id} />
|
||||
<ConfirmSubmit className="btn btn-outline-danger">{t("map.deleteMap")}</ConfirmSubmit>
|
||||
</form>
|
||||
<span className="text-secondary small">{t("map.deleteMapHelp")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import Link from "next/link";
|
||||
import { IconMap2, IconPhoto } from "@tabler/icons-react";
|
||||
import { createMap } from "@/actions/maps";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export const metadata = { title: "Kartor" };
|
||||
|
||||
export default async function MapsPage({ params }: { params: Promise<{ bookId: string }> }) {
|
||||
const { bookId } = await params;
|
||||
await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
const maps = await prisma.bookMap.findMany({
|
||||
where: { bookId },
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: { _count: { select: { markers: true } } },
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("map.title")} />
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
{maps.length === 0 ? (
|
||||
<EmptyState>{t("map.empty")}</EmptyState>
|
||||
) : (
|
||||
<div className="row row-cards">
|
||||
{maps.map((map) => (
|
||||
<div className="col-md-6" key={map.id}>
|
||||
<Link href={`/books/${bookId}/maps/${map.id}`} className="card card-link card-link-pop h-100">
|
||||
<div className="card-body d-flex align-items-center gap-3">
|
||||
<span className={`avatar ${map.kind === "GEO" ? "bg-green-lt" : "bg-purple-lt"}`}>
|
||||
{map.kind === "GEO" ? <IconMap2 size={22} /> : <IconPhoto size={22} />}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="fw-bold text-truncate">{map.name}</div>
|
||||
<div className="text-secondary">
|
||||
{t(`map.kind.${map.kind}`)} · {t("map.markerCount", { n: map._count.markers })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<form action={createMap} className="card">
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("map.new")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="mb-3">
|
||||
<label className="form-label required">{t("common.name")}</label>
|
||||
<input name="name" className="form-control" required maxLength={200} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">{t("common.type")}</label>
|
||||
<select name="kind" className="form-select" defaultValue="GEO">
|
||||
<option value="GEO">{t("map.kind.GEO")}</option>
|
||||
<option value="IMAGE">{t("map.kind.IMAGE")}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="mb-0">
|
||||
<label className="form-label">{t("map.image")}</label>
|
||||
<input type="file" name="image" className="form-control" accept="image/png,image/jpeg,image/webp,image/gif" />
|
||||
<div className="form-hint">{t("map.imageHelp")}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer text-end">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.create")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import Link from "next/link";
|
||||
import { IconPlus } from "@tabler/icons-react";
|
||||
import { kindIcons } from "@/components/kind-icons";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { KIND_INFO, KINDS } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export default async function BookDashboard({ params }: { params: Promise<{ bookId: string }> }) {
|
||||
const { bookId } = await params;
|
||||
const book = await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
|
||||
const [counts, recent] = await Promise.all([
|
||||
prisma.entity.groupBy({ by: ["kind"], where: { bookId }, _count: true }),
|
||||
prisma.entity.findMany({ where: { bookId }, orderBy: { updatedAt: "desc" }, take: 8 }),
|
||||
]);
|
||||
const countOf = Object.fromEntries(counts.map((c) => [c.kind, c._count]));
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={book.title}
|
||||
pretitle={[book.subtitle, book.genre].filter(Boolean).join(" · ") || undefined}
|
||||
/>
|
||||
<PageBody>
|
||||
{book.description ? <p className="text-secondary bm-prewrap mb-4">{book.description}</p> : null}
|
||||
|
||||
<div className="row row-cards mb-4">
|
||||
{KINDS.map(({ kind, slug, color }) => {
|
||||
const Icon = kindIcons[kind];
|
||||
return (
|
||||
<div className="col-6 col-md-4 col-xl-3" key={kind}>
|
||||
<div className="card card-sm">
|
||||
<div className="card-body">
|
||||
<div className="row align-items-center">
|
||||
<div className="col-auto">
|
||||
<span className={`avatar bg-${color}-lt`}>
|
||||
<Icon size={22} />
|
||||
</span>
|
||||
</div>
|
||||
<div className="col">
|
||||
<Link href={`/books/${bookId}/e/${slug}`} className="fw-bold text-reset stretched-link">
|
||||
{t(`kind.${kind}.other`)}
|
||||
</Link>
|
||||
<div className="text-secondary">{countOf[kind] ?? 0}</div>
|
||||
</div>
|
||||
<div className="col-auto position-relative" style={{ zIndex: 2 }}>
|
||||
<Link
|
||||
href={`/books/${bookId}/e/${slug}/new`}
|
||||
className="btn btn-icon btn-sm btn-ghost-secondary"
|
||||
title={t(`kind.${kind}.new`)}
|
||||
aria-label={t(`kind.${kind}.new`)}
|
||||
>
|
||||
<IconPlus size={18} />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("dashboard.recent")}</h3>
|
||||
</div>
|
||||
{recent.length === 0 ? (
|
||||
<div className="card-body">
|
||||
<EmptyState>{t("dashboard.emptyRecent")}</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="list-group list-group-flush">
|
||||
{recent.map((entity) => {
|
||||
const Icon = kindIcons[entity.kind];
|
||||
return (
|
||||
<Link
|
||||
key={entity.id}
|
||||
href={`/books/${bookId}/entity/${entity.id}`}
|
||||
className="list-group-item list-group-item-action d-flex align-items-center gap-3"
|
||||
>
|
||||
<span className={`avatar avatar-sm bg-${KIND_INFO[entity.kind].color}-lt`}>
|
||||
<Icon size={16} />
|
||||
</span>
|
||||
<span className="fw-bold">{entity.name}</span>
|
||||
<span className="text-secondary">{t(`kind.${entity.kind}.one`)}</span>
|
||||
<span className="ms-auto text-secondary small">{entity.updatedAt.toLocaleDateString()}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Fragment } from "react";
|
||||
import { IconTrash } from "@tabler/icons-react";
|
||||
import { deleteRelation, saveRelation } from "@/actions/relations";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { EntitySelect } from "@/components/entity-select";
|
||||
import { FieldInput } from "@/components/entity-form";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
|
||||
export default async function RelationPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string; relationId: string }>;
|
||||
searchParams: Promise<{ saved?: string }>;
|
||||
}) {
|
||||
const { bookId, relationId } = await params;
|
||||
const { saved } = await searchParams;
|
||||
await requireBook(bookId);
|
||||
const { t, locale } = await getT();
|
||||
|
||||
const relation = await prisma.relation.findFirst({
|
||||
where: { id: relationId, bookId },
|
||||
include: { from: true, to: true, members: { include: { entity: true } } },
|
||||
});
|
||||
if (!relation) notFound();
|
||||
const candidates = await prisma.entity.findMany({
|
||||
where: { bookId, id: { notIn: [relation.fromId, relation.toId] } },
|
||||
select: { id: true, name: true, kind: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
const memberEntities = relation.members.map((m) => m.entity);
|
||||
const isGroup = memberEntities.length > 0;
|
||||
const { fields } = await getTemplate(bookId, "RELATION", locale);
|
||||
const data = (relation.data ?? {}) as Record<string, unknown>;
|
||||
const suggestions = t("relation.suggestions").split(",");
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
pretitle={
|
||||
<Link href={`/books/${bookId}/relations`} className="text-reset">
|
||||
{t("relation.title")}
|
||||
</Link>
|
||||
}
|
||||
title={
|
||||
isGroup ? (
|
||||
<span>
|
||||
{[relation.from, relation.to, ...memberEntities].map((e, i) => (
|
||||
<span key={e.id}>
|
||||
{i > 0 ? ", " : ""}
|
||||
<Link href={`/books/${bookId}/entity/${e.id}`} className="text-reset">
|
||||
{e.name}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
<span className="text-secondary fw-normal"> · {relation.type}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span>
|
||||
<Link href={`/books/${bookId}/entity/${relation.fromId}`} className="text-reset">
|
||||
{relation.from.name}
|
||||
</Link>
|
||||
<span className="text-secondary fw-normal"> · {relation.type} · </span>
|
||||
<Link href={`/books/${bookId}/entity/${relation.toId}`} className="text-reset">
|
||||
{relation.to.name}
|
||||
</Link>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
actions={
|
||||
<form action={deleteRelation}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={relation.id} />
|
||||
<input type="hidden" name="redirect" value="list" />
|
||||
<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}
|
||||
<form action={saveRelation}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={relation.id} />
|
||||
<div className="card mb-3">
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
<div className="col-md-6">
|
||||
<label className="form-label required">{t("relation.type")}</label>
|
||||
<input name="type" className="form-control" list="relation-types" required maxLength={100} defaultValue={relation.type} />
|
||||
<datalist id="relation-types">
|
||||
{suggestions.map((s) => (
|
||||
<option key={s} value={s} />
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("common.note")}</label>
|
||||
<input name="description" className="form-control" maxLength={2000} defaultValue={relation.description ?? ""} />
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label">{t("relation.members")}</label>
|
||||
<EntitySelect
|
||||
name="memberIds"
|
||||
entities={candidates}
|
||||
t={t}
|
||||
multiple
|
||||
defaultValues={memberEntities.map((e) => e.id)}
|
||||
/>
|
||||
<div className="form-hint">{t("relation.membersHelp")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{fields.length > 0 ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.details")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
{fields.map((field) => (
|
||||
<Fragment key={field.key}>
|
||||
{field.section ? (
|
||||
<div className="col-12">
|
||||
<h4 className="subheader border-bottom pb-2 mb-0 mt-2">{field.section}</h4>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={field.type === "textarea" ? "col-12" : "col-md-6"}>
|
||||
{field.type !== "checkbox" ? <label className="form-label">{field.label}</label> : null}
|
||||
<FieldInput field={field} value={data[field.key]} />
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="d-flex justify-content-end gap-2">
|
||||
<Link href={`/books/${bookId}/relations`} className="btn">
|
||||
{t("common.back")}
|
||||
</Link>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import Link from "next/link";
|
||||
import { IconX } from "@tabler/icons-react";
|
||||
import { deleteRelation } from "@/actions/relations";
|
||||
import { EntitySelect } from "@/components/entity-select";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import { RelationForm } from "@/components/relation-form";
|
||||
import { RelationGraph } from "@/components/relation-graph";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export const metadata = { title: "Relationer" };
|
||||
|
||||
export default async function RelationsPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string }>;
|
||||
searchParams: Promise<{ entity?: string }>;
|
||||
}) {
|
||||
const { bookId } = await params;
|
||||
const { entity: entityFilter } = await searchParams;
|
||||
await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
|
||||
const [entities, relations] = await Promise.all([
|
||||
prisma.entity.findMany({ where: { bookId }, select: { id: true, name: true, kind: true }, orderBy: { name: "asc" } }),
|
||||
prisma.relation.findMany({
|
||||
where: {
|
||||
bookId,
|
||||
...(entityFilter
|
||||
? { OR: [{ fromId: entityFilter }, { toId: entityFilter }, { members: { some: { entityId: entityFilter } } }] }
|
||||
: {}),
|
||||
},
|
||||
include: { from: true, to: true, members: { include: { entity: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
const nodeMap = new Map<string, { id: string; name: string; kind: (typeof entities)[number]["kind"] }>();
|
||||
for (const r of relations) {
|
||||
nodeMap.set(r.from.id, r.from);
|
||||
nodeMap.set(r.to.id, r.to);
|
||||
for (const m of r.members) nodeMap.set(m.entity.id, m.entity);
|
||||
}
|
||||
const nodes = [...nodeMap.values()];
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("relation.title")} />
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("relation.diagram")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{relations.length === 0 ? (
|
||||
<EmptyState>{t("relation.empty")}</EmptyState>
|
||||
) : nodes.length > 40 ? null : (
|
||||
<RelationGraph
|
||||
bookId={bookId}
|
||||
nodes={nodes}
|
||||
edges={relations.map((r) => ({
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
participantIds: [r.fromId, r.toId, ...r.members.map((m) => m.entityId)],
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("relation.all")}</h3>
|
||||
<div className="card-actions">
|
||||
<form className="d-flex gap-2">
|
||||
<EntitySelect
|
||||
name="entity"
|
||||
entities={entities}
|
||||
t={t}
|
||||
defaultValue={entityFilter}
|
||||
emptyLabel={t("relation.filter")}
|
||||
className="form-select form-select-sm"
|
||||
/>
|
||||
<button className="btn btn-sm" type="submit">
|
||||
{t("common.search")}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{relations.length === 0 ? null : (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<tbody>
|
||||
{relations.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td>
|
||||
<Link href={`/books/${bookId}/entity/${r.fromId}`} className="fw-bold">
|
||||
{r.from.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td>
|
||||
<Link href={`/books/${bookId}/relations/${r.id}`} className="text-secondary" title={t("common.edit")}>
|
||||
{r.type}
|
||||
</Link>
|
||||
</td>
|
||||
<td>
|
||||
{[r.to, ...r.members.map((m) => m.entity)].map((e, i) => (
|
||||
<span key={e.id}>
|
||||
{i > 0 ? ", " : ""}
|
||||
<Link href={`/books/${bookId}/entity/${e.id}`} className="fw-bold">
|
||||
{e.name}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
</td>
|
||||
<td className="text-secondary">{r.description}</td>
|
||||
<td className="w-1">
|
||||
<form action={deleteRelation}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={r.id} />
|
||||
<button type="submit" className="btn btn-icon btn-sm btn-ghost-secondary" aria-label={t("common.delete")} title={t("common.delete")}>
|
||||
<IconX size={16} />
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("relation.add")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<RelationForm bookId={bookId} entities={entities} t={t} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import Link from "next/link";
|
||||
import { IconX } from "@tabler/icons-react";
|
||||
import { addShifts, deleteShift } from "@/actions/shifts";
|
||||
import { EntitySelect } from "@/components/entity-select";
|
||||
import { EmptyState, PageBody, PageHeader } from "@/components/page";
|
||||
import type { TFunction } from "@/i18n/core";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { WORKPLACE_KINDS } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export const metadata = { title: "Scheman" };
|
||||
|
||||
const DAYS = [0, 1, 2, 3, 4, 5, 6];
|
||||
|
||||
type ShiftRow = {
|
||||
id: string;
|
||||
weekday: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
weeks: "ALL" | "ODD" | "EVEN";
|
||||
label: string | null;
|
||||
person: { id: string; name: string };
|
||||
workplace: { id: string; name: string } | null;
|
||||
};
|
||||
|
||||
function ShiftChip({
|
||||
shift,
|
||||
bookId,
|
||||
t,
|
||||
showPerson,
|
||||
}: {
|
||||
shift: ShiftRow;
|
||||
bookId: string;
|
||||
t: TFunction;
|
||||
showPerson?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="d-flex align-items-start gap-1 border rounded px-2 py-1 mb-1">
|
||||
<div className="flex-fill min-w-0 small">
|
||||
<div className="fw-bold">
|
||||
{showPerson ? (
|
||||
<Link href={`/books/${bookId}/entity/${shift.person.id}`} className="text-reset">
|
||||
{shift.person.name}
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
{shift.startTime}–{shift.endTime}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-secondary">
|
||||
{showPerson ? `${shift.startTime}–${shift.endTime}` : null}
|
||||
{[
|
||||
shift.workplace?.name,
|
||||
shift.label,
|
||||
shift.weeks !== "ALL" ? t(`schedule.weeks.${shift.weeks}`) : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.map((part, i) => (
|
||||
<span key={i}>
|
||||
{showPerson || i > 0 ? " · " : ""}
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<form action={deleteShift}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="id" value={shift.id} />
|
||||
<button type="submit" className="btn btn-icon btn-sm btn-ghost-secondary" title={t("common.delete")} aria-label={t("common.delete")}>
|
||||
<IconX size={14} />
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function SchedulesPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string }>;
|
||||
searchParams: Promise<{ view?: string; range?: string; person?: string; workplace?: string }>;
|
||||
}) {
|
||||
const { bookId } = await params;
|
||||
const { view = "person", range: rangeParam, person, workplace } = await searchParams;
|
||||
const range = rangeParam === "night" ? "night" : "day";
|
||||
await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
|
||||
const [people, workplaces, shifts] = await Promise.all([
|
||||
prisma.entity.findMany({
|
||||
where: { bookId, kind: { in: ["CHARACTER"] } },
|
||||
select: { id: true, name: true, kind: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.entity.findMany({
|
||||
where: { bookId, kind: { in: WORKPLACE_KINDS } },
|
||||
select: { id: true, name: true, kind: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.shift.findMany({
|
||||
where: {
|
||||
bookId,
|
||||
...(person ? { personId: person } : {}),
|
||||
...(workplace ? { workplaceId: workplace } : {}),
|
||||
},
|
||||
include: { person: { select: { id: true, name: true } }, workplace: { select: { id: true, name: true } } },
|
||||
orderBy: [{ startTime: "asc" }],
|
||||
}),
|
||||
]);
|
||||
|
||||
const byDay = view === "day";
|
||||
const byGrid = view === "grid";
|
||||
const queryFor = (v: string, r: string = range) => {
|
||||
const q = new URLSearchParams({ view: v });
|
||||
if (v === "grid") q.set("range", r);
|
||||
if (person) q.set("person", person);
|
||||
if (workplace) q.set("workplace", workplace);
|
||||
return `?${q}`;
|
||||
};
|
||||
|
||||
// Timrutnät som i dag- och nattscheman: dag 06–18, natt 18–06. Natten hör till dagen den började.
|
||||
const gridHours = range === "day" ? [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] : [18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5];
|
||||
const toHours = (time: string) => {
|
||||
const [h, m] = time.split(":").map(Number);
|
||||
return h + m / 60;
|
||||
};
|
||||
const covers = (s: (typeof shifts)[number], column: number, hour: number) => {
|
||||
const slot = range === "night" && hour < 6 ? (column + 1) * 24 + hour : column * 24 + hour;
|
||||
const start = s.weekday * 24 + toHours(s.startTime);
|
||||
let end = s.weekday * 24 + toHours(s.endTime);
|
||||
if (end <= start) end += 24;
|
||||
return [slot - 168, slot, slot + 168].some((a) => start < a + 1 && end > a);
|
||||
};
|
||||
|
||||
// Rader per person, i kolumnordning efter namn
|
||||
const personRows = people
|
||||
.map((p) => ({ person: p, shifts: shifts.filter((s) => s.personId === p.id) }))
|
||||
.filter((row) => row.shifts.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("schedule.title")}
|
||||
actions={
|
||||
<>
|
||||
{byGrid ? (
|
||||
<div className="btn-group">
|
||||
<Link href={queryFor("grid", "day")} className={`btn ${range === "day" ? "active" : ""}`}>
|
||||
{t("schedule.rangeDay")}
|
||||
</Link>
|
||||
<Link href={queryFor("grid", "night")} className={`btn ${range === "night" ? "active" : ""}`}>
|
||||
{t("schedule.rangeNight")}
|
||||
</Link>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="btn-group">
|
||||
<Link href={queryFor("person")} className={`btn ${!byDay && !byGrid ? "active" : ""}`}>
|
||||
{t("schedule.viewPerson")}
|
||||
</Link>
|
||||
<Link href={queryFor("day")} className={`btn ${byDay ? "active" : ""}`}>
|
||||
{t("schedule.viewDay")}
|
||||
</Link>
|
||||
<Link href={queryFor("grid")} className={`btn ${byGrid ? "active" : ""}`}>
|
||||
{t("schedule.viewGrid")}
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-12">
|
||||
<div className="card">
|
||||
<div className="card-body py-3">
|
||||
<form className="row g-2 align-items-center">
|
||||
<input type="hidden" name="view" value={view} />
|
||||
{byGrid ? <input type="hidden" name="range" value={range} /> : null}
|
||||
<div className="col-md-5">
|
||||
<EntitySelect
|
||||
name="person"
|
||||
entities={people}
|
||||
t={t}
|
||||
defaultValue={person}
|
||||
emptyLabel={t("schedule.filterPerson")}
|
||||
className="form-select form-select-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-5">
|
||||
<EntitySelect
|
||||
name="workplace"
|
||||
entities={workplaces}
|
||||
t={t}
|
||||
defaultValue={workplace}
|
||||
emptyLabel={t("schedule.filterWorkplace")}
|
||||
className="form-select form-select-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-2 d-flex gap-2">
|
||||
<button className="btn btn-sm" type="submit">
|
||||
{t("common.search")}
|
||||
</button>
|
||||
{person || workplace ? (
|
||||
<Link href={`?view=${view}`} className="btn btn-sm btn-ghost-secondary">
|
||||
{t("common.clear")}
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-12">
|
||||
<div className="card">
|
||||
{shifts.length === 0 ? (
|
||||
<div className="card-body">
|
||||
<EmptyState>{t("schedule.empty")}</EmptyState>
|
||||
</div>
|
||||
) : byGrid ? (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter table-bordered card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-1" />
|
||||
{DAYS.map((d) => (
|
||||
<th key={d} className="bm-week-cell">
|
||||
{t(`day.short.${d}`)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{gridHours.map((hour) => (
|
||||
<tr key={hour}>
|
||||
<td className="text-secondary text-nowrap">{String(hour).padStart(2, "0")}:00</td>
|
||||
{DAYS.map((d) => {
|
||||
const here = shifts.filter((s) => covers(s, d, hour));
|
||||
return (
|
||||
<td key={d} className="bm-week-cell py-1">
|
||||
{here.map((s) => (
|
||||
<Link
|
||||
key={s.id}
|
||||
href={`/books/${bookId}/entity/${s.person.id}`}
|
||||
className="badge bg-blue-lt me-1 mb-1 text-decoration-none"
|
||||
title={[s.workplace?.name, `${s.startTime}–${s.endTime}`, s.label].filter(Boolean).join(" · ")}
|
||||
>
|
||||
{s.person.name}
|
||||
</Link>
|
||||
))}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : byDay ? (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{DAYS.map((d) => (
|
||||
<th key={d} className="bm-week-cell">{t(`day.${d}`)}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
{DAYS.map((d) => (
|
||||
<td key={d} className="bm-week-cell">
|
||||
{shifts
|
||||
.filter((s) => s.weekday === d)
|
||||
.map((s) => (
|
||||
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} showPerson />
|
||||
))}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th />
|
||||
{DAYS.map((d) => (
|
||||
<th key={d} className="bm-week-cell">{t(`day.short.${d}`)}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{personRows.map(({ person: p, shifts: rowShifts }) => (
|
||||
<tr key={p.id}>
|
||||
<td className="fw-bold">
|
||||
<Link href={`/books/${bookId}/entity/${p.id}`} className="text-reset">
|
||||
{p.name}
|
||||
</Link>
|
||||
</td>
|
||||
{DAYS.map((d) => (
|
||||
<td key={d} className="bm-week-cell">
|
||||
{rowShifts
|
||||
.filter((s) => s.weekday === d)
|
||||
.map((s) => (
|
||||
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} />
|
||||
))}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-8">
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("schedule.add")}</h3>
|
||||
</div>
|
||||
{people.length === 0 ? (
|
||||
<div className="card-body text-secondary">{t("schedule.noPeople")}</div>
|
||||
) : (
|
||||
<form action={addShifts}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
<div className="col-md-6">
|
||||
<label className="form-label required">{t("schedule.person")}</label>
|
||||
<EntitySelect name="personId" entities={people} t={t} required defaultValue={person} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("schedule.workplace")}</label>
|
||||
<EntitySelect
|
||||
name="workplaceId"
|
||||
entities={workplaces}
|
||||
t={t}
|
||||
emptyLabel={t("schedule.noWorkplace")}
|
||||
defaultValue={workplace}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label required">{t("schedule.days")}</label>
|
||||
<div className="d-flex flex-wrap gap-3">
|
||||
{DAYS.map((d) => (
|
||||
<label className="form-check" key={d}>
|
||||
<input type="checkbox" name="days" value={d} className="form-check-input" defaultChecked={d < 5} />
|
||||
<span className="form-check-label">{t(`day.${d}`)}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-6 col-md-3">
|
||||
<label className="form-label required">{t("schedule.start")}</label>
|
||||
<input type="time" name="startTime" className="form-control" required defaultValue="08:00" />
|
||||
</div>
|
||||
<div className="col-6 col-md-3">
|
||||
<label className="form-label required">{t("schedule.end")}</label>
|
||||
<input type="time" name="endTime" className="form-control" required defaultValue="16:00" />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label">{t("schedule.weeks")}</label>
|
||||
<select name="weeks" className="form-select" defaultValue="ALL">
|
||||
{(["ALL", "ODD", "EVEN"] as const).map((w) => (
|
||||
<option key={w} value={w}>
|
||||
{t(`schedule.weeks.${w}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label">{t("schedule.label")}</label>
|
||||
<input name="label" className="form-control" maxLength={100} placeholder={t("schedule.labelHelp")} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer text-end">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.add")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { IconDownload } from "@tabler/icons-react";
|
||||
import { deleteBook, updateBook } from "@/actions/books";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { requireBook } from "@/lib/session";
|
||||
|
||||
export const metadata = { title: "Bokinställningar" };
|
||||
|
||||
export default async function SettingsPage({ params }: { params: Promise<{ bookId: string }> }) {
|
||||
const { bookId } = await params;
|
||||
const book = await requireBook(bookId);
|
||||
const { t } = await getT();
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("settings.title")} />
|
||||
<PageBody>
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
<form action={updateBook} className="card">
|
||||
<input type="hidden" name="bookId" value={book.id} />
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
<div className="col-md-6">
|
||||
<label className="form-label required">{t("common.title")}</label>
|
||||
<input name="title" className="form-control" required maxLength={200} defaultValue={book.title} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("books.subtitle")}</label>
|
||||
<input name="subtitle" className="form-control" maxLength={200} defaultValue={book.subtitle ?? ""} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("books.genre")}</label>
|
||||
<input name="genre" className="form-control" maxLength={100} defaultValue={book.genre ?? ""} />
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label">{t("common.description")}</label>
|
||||
<textarea name="description" className="form-control" rows={4} defaultValue={book.description ?? ""} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer text-end">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<div className="card mb-3">
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">{t("settings.exportHelp")}</p>
|
||||
<a className="btn" href={`/api/books/${book.id}/export`}>
|
||||
<IconDownload size={18} className="me-1" />
|
||||
{t("settings.export")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card border-danger">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title text-danger">{t("settings.danger")}</h3>
|
||||
</div>
|
||||
<form action={deleteBook} className="card-body">
|
||||
<input type="hidden" name="bookId" value={book.id} />
|
||||
<p className="text-secondary">{t("settings.deleteBookHelp")}</p>
|
||||
<ConfirmSubmit>{t("settings.deleteBook")}</ConfirmSubmit>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { TemplateEditor } from "@/components/template-editor";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { templateKindFromSlug } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getPresets, getTemplate } from "@/lib/templates";
|
||||
|
||||
export default async function TemplateEditPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ bookId: string; kind: string }>;
|
||||
searchParams: Promise<{ error?: string; saved?: string }>;
|
||||
}) {
|
||||
const { bookId, kind: slug } = await params;
|
||||
const { error, saved } = await searchParams;
|
||||
await requireBook(bookId);
|
||||
const kind = templateKindFromSlug(slug);
|
||||
if (!kind) notFound();
|
||||
const { t, locale } = await getT();
|
||||
const { fields, custom } = await getTemplate(bookId, kind, locale);
|
||||
const presets = getPresets(kind, locale).map((p) => ({ ...p, label: t(`template.preset.${p.id}`) }));
|
||||
const kindLabel = kind === "RELATION" ? t("relation.one") : t(`kind.${kind}.one`);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={`${t("template.edit")}: ${kindLabel}`}
|
||||
pretitle={t("template.title")}
|
||||
actions={<span className={`badge ${custom ? "bg-green-lt" : ""}`}>{custom ? t("template.custom") : t("template.standard")}</span>}
|
||||
/>
|
||||
<PageBody>
|
||||
{error ? <div className="alert alert-danger">{t("template.invalid", { reason: error })}</div> : null}
|
||||
{saved ? <div className="alert alert-success">{t("common.saved")}</div> : null}
|
||||
<TemplateEditor bookId={bookId} kind={kind} initialFields={fields} custom={custom} presets={presets} />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import Link from "next/link";
|
||||
import { IconChartDots3 } from "@tabler/icons-react";
|
||||
import { kindIcons } from "@/components/kind-icons";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { KINDS, templateSlug, type TemplateKind } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
|
||||
export const metadata = { title: "Mallar" };
|
||||
|
||||
export default async function TemplatesPage({ params }: { params: Promise<{ bookId: string }> }) {
|
||||
const { bookId } = await params;
|
||||
await requireBook(bookId);
|
||||
const { t, locale } = await getT();
|
||||
|
||||
const kinds: { kind: TemplateKind; color: string }[] = [
|
||||
...KINDS.map(({ kind, color }) => ({ kind: kind as TemplateKind, color })),
|
||||
{ kind: "RELATION", color: "azure" },
|
||||
];
|
||||
const templates = await Promise.all(kinds.map(async (k) => ({ ...k, ...(await getTemplate(bookId, k.kind, locale)) })));
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("template.title")} />
|
||||
<PageBody>
|
||||
<p className="text-secondary">{t("template.intro")}</p>
|
||||
<div className="row row-cards">
|
||||
{templates.map(({ kind, color, fields, custom }) => {
|
||||
const Icon = kind === "RELATION" ? IconChartDots3 : kindIcons[kind];
|
||||
return (
|
||||
<div className="col-md-6 col-xl-4" key={kind}>
|
||||
<Link href={`/books/${bookId}/templates/${templateSlug(kind)}`} className="card card-link card-link-pop h-100">
|
||||
<div className="card-body d-flex align-items-center gap-3">
|
||||
<span className={`avatar bg-${color}-lt`}>
|
||||
<Icon size={22} />
|
||||
</span>
|
||||
<div>
|
||||
<div className="fw-bold">{kind === "RELATION" ? t("relation.one") : t(`kind.${kind}.one`)}</div>
|
||||
<div className="text-secondary">{t("template.fields", { n: fields.length })}</div>
|
||||
</div>
|
||||
<span className={`badge ms-auto ${custom ? "bg-green-lt" : ""}`}>
|
||||
{custom ? t("template.custom") : t("template.standard")}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
:root {
|
||||
--tblr-font-sans-serif: "Inter Variable", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.bm-prewrap {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.bm-thumb {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
object-fit: cover;
|
||||
border-radius: var(--tblr-border-radius);
|
||||
}
|
||||
|
||||
.bm-portrait {
|
||||
width: 100%;
|
||||
max-height: 22rem;
|
||||
object-fit: cover;
|
||||
border-radius: var(--tblr-border-radius);
|
||||
}
|
||||
|
||||
.bm-table-link {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.bm-table-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Kartor */
|
||||
.bm-map {
|
||||
height: 70vh;
|
||||
min-height: 26rem;
|
||||
border-radius: var(--tblr-border-radius);
|
||||
border: 1px solid var(--tblr-border-color);
|
||||
background: var(--tblr-bg-surface-secondary);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.bm-map.bm-adding {
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.bm-map.bm-adding .leaflet-grab,
|
||||
.bm-map.bm-adding .leaflet-interactive {
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.bm-pin-wrap {
|
||||
background: none;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.bm-pin {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
margin: 2px 1px;
|
||||
background: var(--c);
|
||||
border: 2px solid #fff;
|
||||
border-radius: 50% 50% 50% 0;
|
||||
transform: rotate(-45deg);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.bm-pin::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 7px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.bm-pin.bm-selected {
|
||||
outline: 3px solid rgba(32, 107, 196, 0.55);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.bm-pin.bm-draft {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.bm-marker-list {
|
||||
max-height: 22rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.bm-graph text {
|
||||
font-size: 13px;
|
||||
fill: var(--tblr-body-color);
|
||||
}
|
||||
|
||||
.bm-graph .bm-edge-label {
|
||||
font-size: 11px;
|
||||
fill: var(--tblr-secondary);
|
||||
paint-order: stroke;
|
||||
stroke: var(--tblr-bg-surface);
|
||||
stroke-width: 3px;
|
||||
}
|
||||
|
||||
.bm-graph line {
|
||||
stroke: var(--tblr-border-color-translucent, #adb5bd);
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
|
||||
.bm-week-cell {
|
||||
min-width: 9rem;
|
||||
vertical-align: top;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#206bc4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6l0 13"/><path d="M12 6l0 13"/><path d="M21 6l0 13"/></svg>
|
||||
|
After Width: | Height: | Size: 314 B |
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import "@fontsource-variable/inter";
|
||||
import "@tabler/core/dist/css/tabler.min.css";
|
||||
import "./globals.css";
|
||||
import { I18nProvider } from "@/i18n/client";
|
||||
import { dictionaries } from "@/i18n/core";
|
||||
import { getLocale } from "@/i18n/server";
|
||||
import { TablerJs } from "@/components/tabler-js";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Bokplanerare", template: "%s · Bokplanerare" },
|
||||
description: "Planeringsverktyg för författare",
|
||||
};
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const locale = await getLocale();
|
||||
const theme = (await cookies()).get("theme")?.value === "dark" ? "dark" : "light";
|
||||
|
||||
return (
|
||||
<html lang={locale} data-bs-theme={theme}>
|
||||
<body>
|
||||
<I18nProvider locale={locale} dict={dictionaries[locale]}>
|
||||
<TablerJs />
|
||||
{children}
|
||||
</I18nProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { IconBook2 } from "@tabler/icons-react";
|
||||
import { auth, signIn } from "@/auth";
|
||||
import { authentikEnabled, devLoginEnabled } from "@/auth.config";
|
||||
import { getT } from "@/i18n/server";
|
||||
|
||||
export const metadata = { title: "Logga in" };
|
||||
|
||||
export default async function LoginPage() {
|
||||
if ((await auth())?.user) redirect("/");
|
||||
const { t } = await getT();
|
||||
|
||||
return (
|
||||
<div className="page page-center">
|
||||
<div className="container container-tight py-4">
|
||||
<div className="text-center mb-4">
|
||||
<span className="navbar-brand navbar-brand-autodark d-inline-flex align-items-center gap-2 fs-2">
|
||||
<IconBook2 size={34} />
|
||||
{t("app.name")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="card card-md">
|
||||
<div className="card-body">
|
||||
<h2 className="h2 text-center mb-2">{t("login.title")}</h2>
|
||||
<p className="text-secondary text-center mb-4">{t("login.subtitle")}</p>
|
||||
{authentikEnabled ? (
|
||||
<form
|
||||
action={async () => {
|
||||
"use server";
|
||||
await signIn("authentik", { redirectTo: "/" });
|
||||
}}
|
||||
>
|
||||
<button type="submit" className="btn btn-primary w-100">
|
||||
{t("login.button")}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="alert alert-warning mb-0">{t("login.notConfigured")}</div>
|
||||
)}
|
||||
|
||||
{devLoginEnabled ? (
|
||||
<>
|
||||
<div className="hr-text">{t("login.dev")}</div>
|
||||
<form
|
||||
action={async (formData: FormData) => {
|
||||
"use server";
|
||||
await signIn("dev", { name: String(formData.get("name") ?? ""), redirectTo: "/" });
|
||||
}}
|
||||
className="d-flex gap-2"
|
||||
>
|
||||
<input name="name" className="form-control" placeholder={t("login.devName")} defaultValue="dev" />
|
||||
<button type="submit" className="btn flex-shrink-0 text-nowrap">
|
||||
{t("login.devButton")}
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { NextAuthConfig } from "next-auth";
|
||||
import Authentik from "next-auth/providers/authentik";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
|
||||
// Endast för lokal utveckling utan Authentik. Aktiveras aldrig i produktionsbygget.
|
||||
export const devLoginEnabled = process.env.AUTH_DEV_LOGIN === "true" && process.env.NODE_ENV !== "production";
|
||||
|
||||
export const authentikEnabled = Boolean(process.env.AUTHENTIK_ISSUER);
|
||||
|
||||
// Edge-säker konfiguration (används av middleware). Inga databasanrop här.
|
||||
export default {
|
||||
providers: [
|
||||
...(authentikEnabled
|
||||
? [
|
||||
Authentik({
|
||||
clientId: process.env.AUTHENTIK_CLIENT_ID,
|
||||
clientSecret: process.env.AUTHENTIK_CLIENT_SECRET,
|
||||
issuer: process.env.AUTHENTIK_ISSUER,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(devLoginEnabled
|
||||
? [
|
||||
Credentials({
|
||||
id: "dev",
|
||||
name: "Dev",
|
||||
credentials: { name: {} },
|
||||
authorize: async (credentials) => {
|
||||
const name = String(credentials?.name ?? "").trim() || "dev";
|
||||
return { id: `dev-${name.toLowerCase()}`, name };
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
pages: { signIn: "/login" },
|
||||
session: { strategy: "jwt" },
|
||||
callbacks: {
|
||||
authorized({ auth, request }) {
|
||||
if (request.nextUrl.pathname.startsWith("/login")) return true;
|
||||
return !!auth?.user;
|
||||
},
|
||||
session({ session, token }) {
|
||||
if (token.uid && session.user) session.user.id = token.uid as string;
|
||||
return session;
|
||||
},
|
||||
},
|
||||
} satisfies NextAuthConfig;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import NextAuth, { type DefaultSession } from "next-auth";
|
||||
import authConfig from "./auth.config";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
declare module "next-auth" {
|
||||
interface Session {
|
||||
user: { id: string } & DefaultSession["user"];
|
||||
}
|
||||
}
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
async jwt({ token, user, account }) {
|
||||
// Vid inloggning: koppla Authentik-kontot till en användare i databasen.
|
||||
if (account && user) {
|
||||
const externalId = `${account.provider}:${account.providerAccountId}`;
|
||||
const dbUser = await prisma.user.upsert({
|
||||
where: { externalId },
|
||||
update: { name: user.name ?? undefined, email: user.email ?? undefined },
|
||||
create: { externalId, name: user.name ?? null, email: user.email ?? null },
|
||||
});
|
||||
token.uid = dbUser.id;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useT } from "@/i18n/client";
|
||||
|
||||
// Skickaknapp som frågar innan formuläret skickas, t.ex. vid borttagning.
|
||||
export function ConfirmSubmit({
|
||||
children,
|
||||
className = "btn btn-danger",
|
||||
message,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
message?: string;
|
||||
title?: string;
|
||||
}) {
|
||||
const t = useT();
|
||||
return (
|
||||
<button
|
||||
type="submit"
|
||||
className={className}
|
||||
title={title}
|
||||
onClick={(event) => {
|
||||
if (!window.confirm(message ?? t("common.confirmDelete"))) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Fragment } from "react";
|
||||
import Link from "next/link";
|
||||
import type { Entity, EntityKind } from "@prisma/client";
|
||||
import type { TFunction } from "@/i18n/core";
|
||||
import { fileUrl } from "@/lib/files";
|
||||
import type { FieldDef } from "@/lib/templates";
|
||||
|
||||
export function FieldInput({ field, value }: { field: FieldDef; value: unknown }) {
|
||||
const name = `f_${field.key}`;
|
||||
const text = value === null || value === undefined ? "" : String(value);
|
||||
|
||||
switch (field.type) {
|
||||
case "textarea":
|
||||
return <textarea name={name} className="form-control" rows={4} defaultValue={text} />;
|
||||
case "number":
|
||||
return <input type="number" step="any" name={name} className="form-control" defaultValue={text} />;
|
||||
case "date":
|
||||
return <input type="date" name={name} className="form-control" defaultValue={text} />;
|
||||
case "url":
|
||||
return <input type="url" name={name} className="form-control" defaultValue={text} placeholder="https://" />;
|
||||
case "checkbox":
|
||||
return (
|
||||
<label className="form-check form-switch">
|
||||
<input type="checkbox" name={name} className="form-check-input" defaultChecked={value === true} />
|
||||
<span className="form-check-label">{field.label}</span>
|
||||
</label>
|
||||
);
|
||||
case "select": {
|
||||
const options = field.options ?? [];
|
||||
const extra = text && !options.includes(text) ? [text] : [];
|
||||
return (
|
||||
<select name={name} className="form-select" defaultValue={text}>
|
||||
<option value="" />
|
||||
{[...options, ...extra].map((o) => (
|
||||
<option key={o} value={o}>
|
||||
{o}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return <input type="text" name={name} className="form-control" defaultValue={text} maxLength={500} />;
|
||||
}
|
||||
}
|
||||
|
||||
export function EntityForm({
|
||||
action,
|
||||
bookId,
|
||||
kind,
|
||||
entity,
|
||||
fields,
|
||||
cancelHref,
|
||||
t,
|
||||
}: {
|
||||
action: (formData: FormData) => Promise<void>;
|
||||
bookId: string;
|
||||
kind: EntityKind;
|
||||
entity?: Entity;
|
||||
fields: FieldDef[];
|
||||
cancelHref: string;
|
||||
t: TFunction;
|
||||
}) {
|
||||
const data = (entity?.data ?? {}) as Record<string, unknown>;
|
||||
const image = fileUrl(entity?.imageFile);
|
||||
|
||||
return (
|
||||
<form action={action}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="kind" value={kind} />
|
||||
{entity ? <input type="hidden" name="id" value={entity.id} /> : null}
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
<div className="col-md-6">
|
||||
<label className="form-label required">{t("common.name")}</label>
|
||||
<input name="name" className="form-control" required maxLength={200} defaultValue={entity?.name} autoFocus />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("common.code")}</label>
|
||||
<input name="code" className="form-control" maxLength={50} defaultValue={entity?.code ?? ""} />
|
||||
<div className="form-hint">{t("common.codeHelp")}</div>
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("common.tags")}</label>
|
||||
<input name="tags" className="form-control" defaultValue={entity?.tags.join(", ")} />
|
||||
<div className="form-hint">{t("common.tagsHelp")}</div>
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label">{t("common.summary")}</label>
|
||||
<textarea name="summary" className="form-control" rows={3} defaultValue={entity?.summary ?? ""} />
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label">{t("common.image")}</label>
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
{image ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={image} alt="" className="bm-thumb" />
|
||||
) : null}
|
||||
<input type="file" name="image" accept="image/png,image/jpeg,image/webp,image/gif" className="form-control" />
|
||||
</div>
|
||||
{image ? (
|
||||
<label className="form-check mt-2">
|
||||
<input type="checkbox" name="removeImage" className="form-check-input" />
|
||||
<span className="form-check-label">{t("common.removeImage")}</span>
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{fields.length > 0 ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.details")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="row g-3">
|
||||
{fields.map((field) => (
|
||||
<Fragment key={field.key}>
|
||||
{field.section ? (
|
||||
<div className="col-12">
|
||||
<h4 className="subheader border-bottom pb-2 mb-0 mt-2">{field.section}</h4>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={field.type === "textarea" ? "col-12" : "col-md-6"}>
|
||||
{field.type !== "checkbox" ? <label className="form-label">{field.label}</label> : null}
|
||||
<FieldInput field={field} value={data[field.key]} />
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="d-flex justify-content-end gap-2">
|
||||
<Link href={cancelHref} className="btn">
|
||||
{t("common.cancel")}
|
||||
</Link>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { EntityKind } from "@prisma/client";
|
||||
import type { TFunction } from "@/i18n/core";
|
||||
import { KINDS } from "@/lib/kinds";
|
||||
|
||||
export type EntityOption = { id: string; name: string; kind: EntityKind };
|
||||
|
||||
/** <select> med poster grupperade efter typ. Med `multiple` kan flera väljas. */
|
||||
export function EntitySelect({
|
||||
name,
|
||||
entities,
|
||||
t,
|
||||
required,
|
||||
defaultValue,
|
||||
defaultValues,
|
||||
multiple,
|
||||
emptyLabel,
|
||||
className = "form-select",
|
||||
}: {
|
||||
name: string;
|
||||
entities: EntityOption[];
|
||||
t: TFunction;
|
||||
required?: boolean;
|
||||
defaultValue?: string;
|
||||
defaultValues?: string[];
|
||||
multiple?: boolean;
|
||||
emptyLabel?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<select
|
||||
name={name}
|
||||
className={className}
|
||||
required={required}
|
||||
multiple={multiple}
|
||||
size={multiple ? 6 : undefined}
|
||||
defaultValue={multiple ? (defaultValues ?? []) : (defaultValue ?? "")}
|
||||
>
|
||||
{multiple ? null : <option value="">{emptyLabel ?? t("common.choose")}</option>}
|
||||
{KINDS.map(({ kind }) => {
|
||||
const group = entities.filter((e) => e.kind === kind);
|
||||
if (group.length === 0) return null;
|
||||
return (
|
||||
<optgroup key={kind} label={t(`kind.${kind}.other`)}>
|
||||
{group.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {
|
||||
IconBuildingSkyscraper,
|
||||
IconBuildingStore,
|
||||
IconHome,
|
||||
IconMapPin,
|
||||
IconMovie,
|
||||
IconPaw,
|
||||
IconSchool,
|
||||
IconUser,
|
||||
type Icon,
|
||||
} from "@tabler/icons-react";
|
||||
import type { EntityKind } from "@prisma/client";
|
||||
|
||||
export const kindIcons: Record<EntityKind, Icon> = {
|
||||
CHARACTER: IconUser,
|
||||
PET: IconPaw,
|
||||
HOME: IconHome,
|
||||
PLACE: IconMapPin,
|
||||
COMPANY: IconBuildingSkyscraper,
|
||||
PREMISES: IconBuildingStore,
|
||||
EDUCATION: IconSchool,
|
||||
SCENARIO: IconMovie,
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useT } from "@/i18n/client";
|
||||
import type { MapViewProps } from "./map-view";
|
||||
|
||||
// Leaflet använder window och får därför inte renderas på servern.
|
||||
const MapView = dynamic(() => import("./map-view"), {
|
||||
ssr: false,
|
||||
loading: () => <MapLoading />,
|
||||
});
|
||||
|
||||
function MapLoading() {
|
||||
const t = useT();
|
||||
return <div className="text-secondary p-4">{t("common.loading")}</div>;
|
||||
}
|
||||
|
||||
export function MapLoader(props: MapViewProps) {
|
||||
return <MapView {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import L from "leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import { IconCurrentLocation, IconPlus, IconSearch, IconX } from "@tabler/icons-react";
|
||||
import { createMarker, deleteMarker, moveMarker, saveMapView, updateMarker } from "@/actions/maps";
|
||||
import { useT } from "@/i18n/client";
|
||||
import { KINDS, MARKER_COLORS } from "@/lib/kinds";
|
||||
|
||||
export type MarkerDTO = {
|
||||
id: string;
|
||||
label: string;
|
||||
note: string | null;
|
||||
color: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
entityId: string | null;
|
||||
};
|
||||
|
||||
export type EntityOpt = { id: string; name: string; kind: string };
|
||||
|
||||
export type MapViewProps = {
|
||||
bookId: string;
|
||||
mapId: string;
|
||||
kind: "GEO" | "IMAGE";
|
||||
imageUrl: string | null;
|
||||
center: [number, number] | null;
|
||||
zoom: number | null;
|
||||
markers: MarkerDTO[];
|
||||
entities: EntityOpt[];
|
||||
tileUrl: string;
|
||||
tileAttribution: string;
|
||||
geocoderUrl: string;
|
||||
preselectEntityId: string | null;
|
||||
initialMarkerId: string | null;
|
||||
};
|
||||
|
||||
type Draft = {
|
||||
id: string | null;
|
||||
label: string;
|
||||
note: string;
|
||||
color: string;
|
||||
entityId: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
|
||||
type GeoHit = { name: string; lat: number; lng: number };
|
||||
|
||||
const DEFAULT_CENTER: [number, number] = [59.3293, 18.0686];
|
||||
|
||||
function pinIcon(color: string, highlight = false) {
|
||||
const hex = MARKER_COLORS[color] ?? MARKER_COLORS.blue;
|
||||
return L.divIcon({
|
||||
className: "bm-pin-wrap",
|
||||
html: `<span class="bm-pin${highlight ? " bm-selected" : ""}" style="--c:${hex}"></span>`,
|
||||
iconSize: [32, 40],
|
||||
iconAnchor: [16, 38],
|
||||
});
|
||||
}
|
||||
|
||||
export default function MapView(props: MapViewProps) {
|
||||
const { bookId, mapId, kind, imageUrl, markers, entities } = props;
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const mapRef = useRef<L.Map | null>(null);
|
||||
const layersRef = useRef(new Map<string, L.Marker>());
|
||||
const draftMarkerRef = useRef<L.Marker | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [viewSaved, setViewSaved] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [hits, setHits] = useState<GeoHit[] | null>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
|
||||
// Hanterare som alltid ser senaste props/state, används från Leaflet-händelser
|
||||
const handlers = useRef({
|
||||
mapClick: (_lat: number, _lng: number) => {},
|
||||
openMarker: (_id: string) => {},
|
||||
moveMarker: (_id: string, _lat: number, _lng: number) => {},
|
||||
});
|
||||
const initial = useRef({ center: props.center, zoom: props.zoom, marker: props.initialMarkerId, place: props.preselectEntityId });
|
||||
|
||||
const entityName = (id: string) => entities.find((e) => e.id === id)?.name ?? "";
|
||||
|
||||
handlers.current.mapClick = (lat, lng) => {
|
||||
if (!adding) return;
|
||||
const pre = initial.current.place ?? "";
|
||||
setDraft({ id: null, label: pre ? entityName(pre) : "", note: "", color: "blue", entityId: pre, lat, lng });
|
||||
setAdding(false);
|
||||
};
|
||||
handlers.current.openMarker = (id) => {
|
||||
const m = markers.find((x) => x.id === id);
|
||||
if (!m) return;
|
||||
setAdding(false);
|
||||
setDraft({ id: m.id, label: m.label, note: m.note ?? "", color: m.color, entityId: m.entityId ?? "", lat: m.lat, lng: m.lng });
|
||||
};
|
||||
handlers.current.moveMarker = (id, lat, lng) => {
|
||||
setDraft((d) => (d && d.id === id ? { ...d, lat, lng } : d));
|
||||
startTransition(async () => {
|
||||
await moveMarker(bookId, mapId, id, lat, lng);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
// Skapa kartan
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
let cancelled = false;
|
||||
let map: L.Map | null = null;
|
||||
|
||||
async function init() {
|
||||
if (!el) return;
|
||||
if (kind === "GEO") {
|
||||
const view = initial.current;
|
||||
map = L.map(el).setView(view.center ?? DEFAULT_CENTER, view.zoom ?? 11);
|
||||
L.tileLayer(props.tileUrl, { attribution: props.tileAttribution, maxZoom: 19 }).addTo(map);
|
||||
} else {
|
||||
const img = new Image();
|
||||
await new Promise<void>((resolve) => {
|
||||
img.onload = () => resolve();
|
||||
img.onerror = () => resolve();
|
||||
img.src = imageUrl ?? "";
|
||||
});
|
||||
if (cancelled) return;
|
||||
const w = img.naturalWidth || 1000;
|
||||
const h = img.naturalHeight || 1000;
|
||||
const bounds = L.latLngBounds([0, 0], [h, w]);
|
||||
map = L.map(el, { crs: L.CRS.Simple, minZoom: -5, maxZoom: 4, zoomSnap: 0.25, attributionControl: false });
|
||||
L.imageOverlay(imageUrl ?? "", bounds).addTo(map);
|
||||
map.fitBounds(bounds);
|
||||
map.setMaxBounds(bounds.pad(0.5));
|
||||
}
|
||||
map.on("click", (e: L.LeafletMouseEvent) => handlers.current.mapClick(e.latlng.lat, e.latlng.lng));
|
||||
mapRef.current = map;
|
||||
setReady(true);
|
||||
}
|
||||
void init();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
map?.remove();
|
||||
mapRef.current = null;
|
||||
layersRef.current.clear();
|
||||
draftMarkerRef.current = null;
|
||||
setReady(false);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [kind, imageUrl, props.tileUrl, props.tileAttribution]);
|
||||
|
||||
// Synka sparade markeringar med kartan
|
||||
const draftId = draft?.id ?? null;
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!ready || !map) return;
|
||||
const layers = layersRef.current;
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const m of markers) {
|
||||
seen.add(m.id);
|
||||
const icon = pinIcon(m.color, m.id === draftId);
|
||||
let lm = layers.get(m.id);
|
||||
if (!lm) {
|
||||
const created = L.marker([m.lat, m.lng], { icon, draggable: true, autoPan: true }).addTo(map);
|
||||
created.on("click", () => handlers.current.openMarker(m.id));
|
||||
created.on("dragend", () => {
|
||||
const p = created.getLatLng();
|
||||
handlers.current.moveMarker(m.id, p.lat, p.lng);
|
||||
});
|
||||
layers.set(m.id, created);
|
||||
lm = created;
|
||||
} else {
|
||||
lm.setLatLng([m.lat, m.lng]);
|
||||
lm.setIcon(icon);
|
||||
}
|
||||
const tip = document.createElement("span");
|
||||
tip.textContent = m.label;
|
||||
lm.unbindTooltip();
|
||||
lm.bindTooltip(tip, { direction: "top", offset: [0, -34] });
|
||||
}
|
||||
for (const [id, lm] of layers) {
|
||||
if (!seen.has(id)) {
|
||||
lm.remove();
|
||||
layers.delete(id);
|
||||
}
|
||||
}
|
||||
}, [ready, markers, draftId]);
|
||||
|
||||
// Tillfällig markering för en ny post
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!ready || !map) return;
|
||||
if (draft && draft.id === null) {
|
||||
if (!draftMarkerRef.current) {
|
||||
const dm = L.marker([draft.lat, draft.lng], { icon: pinIcon(draft.color, true), draggable: true, zIndexOffset: 1000 }).addTo(map);
|
||||
dm.on("dragend", () => {
|
||||
const p = dm.getLatLng();
|
||||
setDraft((d) => (d && d.id === null ? { ...d, lat: p.lat, lng: p.lng } : d));
|
||||
});
|
||||
draftMarkerRef.current = dm;
|
||||
} else {
|
||||
draftMarkerRef.current.setLatLng([draft.lat, draft.lng]);
|
||||
draftMarkerRef.current.setIcon(pinIcon(draft.color, true));
|
||||
}
|
||||
} else if (draftMarkerRef.current) {
|
||||
draftMarkerRef.current.remove();
|
||||
draftMarkerRef.current = null;
|
||||
}
|
||||
}, [ready, draft]);
|
||||
|
||||
// Markörläge ändrar muspekaren
|
||||
useEffect(() => {
|
||||
containerRef.current?.classList.toggle("bm-adding", adding);
|
||||
}, [adding]);
|
||||
|
||||
// Startläge från länkar: ?place=<postId> startar placering, ?marker=<id> öppnar en markering
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!ready || !map) return;
|
||||
const { marker, place } = initial.current;
|
||||
if (marker) {
|
||||
const m = markers.find((x) => x.id === marker);
|
||||
if (m) {
|
||||
map.setView([m.lat, m.lng], Math.max(map.getZoom(), kind === "GEO" ? 15 : map.getZoom()));
|
||||
handlers.current.openMarker(m.id);
|
||||
}
|
||||
} else if (place) {
|
||||
setAdding(true);
|
||||
}
|
||||
initial.current.marker = null;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ready]);
|
||||
|
||||
function focusMarker(m: MarkerDTO) {
|
||||
mapRef.current?.setView([m.lat, m.lng], Math.max(mapRef.current.getZoom(), kind === "GEO" ? 15 : mapRef.current.getZoom()));
|
||||
handlers.current.openMarker(m.id);
|
||||
}
|
||||
|
||||
function submitDraft(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!draft || !draft.label.trim()) return;
|
||||
const input = {
|
||||
label: draft.label,
|
||||
note: draft.note,
|
||||
color: draft.color,
|
||||
entityId: draft.entityId || null,
|
||||
lat: draft.lat,
|
||||
lng: draft.lng,
|
||||
};
|
||||
startTransition(async () => {
|
||||
if (draft.id) await updateMarker(bookId, mapId, draft.id, input);
|
||||
else await createMarker(bookId, mapId, input);
|
||||
setDraft(null);
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
function removeDraft() {
|
||||
if (!draft?.id || !window.confirm(t("common.confirmDelete"))) return;
|
||||
const id = draft.id;
|
||||
startTransition(async () => {
|
||||
await deleteMarker(bookId, mapId, id);
|
||||
setDraft(null);
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
function persistView() {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
const c = map.getCenter();
|
||||
startTransition(async () => {
|
||||
await saveMapView(bookId, mapId, c.lat, c.lng, map.getZoom());
|
||||
setViewSaved(true);
|
||||
setTimeout(() => setViewSaved(false), 2000);
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
async function search(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!query.trim()) return;
|
||||
setSearching(true);
|
||||
try {
|
||||
const url = `${props.geocoderUrl}?format=jsonv2&limit=5&q=${encodeURIComponent(query.trim())}`;
|
||||
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
||||
const data = (await res.json()) as { display_name: string; lat: string; lon: string }[];
|
||||
setHits(data.map((r) => ({ name: r.display_name, lat: Number(r.lat), lng: Number(r.lon) })));
|
||||
} catch {
|
||||
setHits([]);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}
|
||||
|
||||
function chooseHit(hit: GeoHit) {
|
||||
mapRef.current?.setView([hit.lat, hit.lng], 16);
|
||||
setAdding(false);
|
||||
setDraft({ id: null, label: hit.name.split(",")[0], note: "", color: "blue", entityId: "", lat: hit.lat, lng: hit.lng });
|
||||
setHits(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
<div ref={containerRef} className="bm-map" />
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
<div className="card mb-3">
|
||||
<div className="card-body d-flex flex-wrap gap-2 align-items-center">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${adding ? "btn-warning" : "btn-primary"}`}
|
||||
onClick={() => {
|
||||
setDraft(null);
|
||||
setAdding((v) => !v);
|
||||
}}
|
||||
>
|
||||
{adding ? <IconX size={18} className="me-1" /> : <IconPlus size={18} className="me-1" />}
|
||||
{adding ? t("map.cancelAdd") : t("map.addMarker")}
|
||||
</button>
|
||||
{kind === "GEO" ? (
|
||||
<button type="button" className="btn" onClick={persistView} disabled={pending}>
|
||||
<IconCurrentLocation size={18} className="me-1" />
|
||||
{viewSaved ? t("map.viewSaved") : t("map.saveView")}
|
||||
</button>
|
||||
) : null}
|
||||
<div className="w-100 text-secondary small">{adding ? t("map.addHint") : t("map.dragHint")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{kind === "GEO" ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-body">
|
||||
<form onSubmit={search} className="input-group">
|
||||
<input
|
||||
className="form-control"
|
||||
placeholder={t("map.search")}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
<button className="btn btn-icon" type="submit" aria-label={t("common.search")} disabled={searching}>
|
||||
<IconSearch size={18} />
|
||||
</button>
|
||||
</form>
|
||||
{searching ? <div className="text-secondary small mt-2">{t("map.searching")}</div> : null}
|
||||
{hits ? (
|
||||
<div className="list-group list-group-flush mt-2">
|
||||
{hits.length === 0 ? <div className="text-secondary small">{t("map.noHits")}</div> : null}
|
||||
{hits.map((hit, i) => (
|
||||
<button key={i} type="button" className="list-group-item list-group-item-action small text-start" onClick={() => chooseHit(hit)}>
|
||||
{hit.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{draft ? (
|
||||
<form onSubmit={submitDraft} className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{draft.id ? t("map.editMarker") : t("map.newMarker")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="mb-3">
|
||||
<label className="form-label required">{t("map.markerLabel")}</label>
|
||||
<input
|
||||
className="form-control"
|
||||
value={draft.label}
|
||||
maxLength={200}
|
||||
required
|
||||
autoFocus
|
||||
onChange={(e) => setDraft({ ...draft, label: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">{t("map.linkedTo")}</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={draft.entityId}
|
||||
onChange={(e) => {
|
||||
const entityId = e.target.value;
|
||||
setDraft({ ...draft, entityId, label: draft.label.trim() || !entityId ? draft.label : entityName(entityId) });
|
||||
}}
|
||||
>
|
||||
<option value="">{t("map.noLink")}</option>
|
||||
{KINDS.map(({ kind: k }) => {
|
||||
const group = entities.filter((e) => e.kind === k);
|
||||
if (group.length === 0) return null;
|
||||
return (
|
||||
<optgroup key={k} label={t(`kind.${k}.other`)}>
|
||||
{group.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label">{t("common.color")}</label>
|
||||
<div className="d-flex flex-wrap gap-2">
|
||||
{Object.entries(MARKER_COLORS).map(([name, hex]) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
title={t(`color.${name}`)}
|
||||
aria-label={t(`color.${name}`)}
|
||||
aria-pressed={draft.color === name}
|
||||
onClick={() => setDraft({ ...draft, color: name })}
|
||||
className="btn btn-icon btn-sm"
|
||||
style={{
|
||||
background: hex,
|
||||
borderColor: draft.color === name ? "var(--tblr-body-color)" : "transparent",
|
||||
borderWidth: 2,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-0">
|
||||
<label className="form-label">{t("common.note")}</label>
|
||||
<textarea className="form-control" rows={3} value={draft.note} onChange={(e) => setDraft({ ...draft, note: e.target.value })} />
|
||||
</div>
|
||||
{draft.entityId ? (
|
||||
<div className="mt-3">
|
||||
<Link href={`/books/${bookId}/entity/${draft.entityId}`}>{t("map.openEntity", { name: entityName(draft.entityId) })}</Link>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="card-footer d-flex gap-2">
|
||||
{draft.id ? (
|
||||
<button type="button" className="btn btn-outline-danger" onClick={removeDraft} disabled={pending}>
|
||||
{t("common.delete")}
|
||||
</button>
|
||||
) : null}
|
||||
<button type="button" className="btn ms-auto" onClick={() => setDraft(null)}>
|
||||
{t("common.cancel")}
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary" disabled={pending}>
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("map.markers")}</h3>
|
||||
<div className="card-actions">
|
||||
<span className="badge">{markers.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="list-group list-group-flush bm-marker-list">
|
||||
{markers.length === 0 ? <div className="list-group-item text-secondary">{t("map.noMarkers")}</div> : null}
|
||||
{markers.map((m) => (
|
||||
<button key={m.id} type="button" className="list-group-item list-group-item-action d-flex align-items-center gap-2" onClick={() => focusMarker(m)}>
|
||||
<span className="badge" style={{ background: MARKER_COLORS[m.color] ?? MARKER_COLORS.blue }}>
|
||||
|
||||
</span>
|
||||
<span className="flex-fill text-start">
|
||||
{m.label}
|
||||
{m.entityId ? <span className="text-secondary"> · {entityName(m.entityId)}</span> : null}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export function NavLink({
|
||||
href,
|
||||
icon,
|
||||
exact = false,
|
||||
children,
|
||||
}: {
|
||||
href: string;
|
||||
icon: ReactNode;
|
||||
exact?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const active = exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
|
||||
return (
|
||||
<li className={`nav-item${active ? " active" : ""}`}>
|
||||
<Link className="nav-link" href={href}>
|
||||
<span className="nav-link-icon d-md-none d-lg-inline-block">{icon}</span>
|
||||
<span className="nav-link-title">{children}</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
pretitle,
|
||||
actions,
|
||||
}: {
|
||||
title: ReactNode;
|
||||
pretitle?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="page-header d-print-none">
|
||||
<div className="container-xl">
|
||||
<div className="row g-2 align-items-center">
|
||||
<div className="col">
|
||||
{pretitle ? <div className="page-pretitle">{pretitle}</div> : null}
|
||||
<h2 className="page-title">{title}</h2>
|
||||
</div>
|
||||
{actions ? <div className="col-auto ms-auto d-print-none"><div className="btn-list">{actions}</div></div> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageBody({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="page-body">
|
||||
<div className="container-xl">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<p className="empty-title text-secondary fs-4 fw-normal">{children}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { addRelation } from "@/actions/relations";
|
||||
import type { TFunction } from "@/i18n/core";
|
||||
import { EntitySelect, type EntityOption } from "./entity-select";
|
||||
|
||||
export function RelationForm({
|
||||
bookId,
|
||||
entities,
|
||||
fixedFromId,
|
||||
t,
|
||||
}: {
|
||||
bookId: string;
|
||||
entities: EntityOption[];
|
||||
fixedFromId?: string;
|
||||
t: TFunction;
|
||||
}) {
|
||||
const suggestions = t("relation.suggestions").split(",");
|
||||
const listId = `relation-types-${fixedFromId ?? "all"}`;
|
||||
const others = fixedFromId ? entities.filter((e) => e.id !== fixedFromId) : entities;
|
||||
|
||||
return (
|
||||
<form action={addRelation} className="row g-2 align-items-end">
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
{fixedFromId ? (
|
||||
<input type="hidden" name="fromId" value={fixedFromId} />
|
||||
) : (
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("relation.from")}</label>
|
||||
<EntitySelect name="fromId" entities={entities} t={t} required />
|
||||
</div>
|
||||
)}
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("relation.type")}</label>
|
||||
<input name="type" className="form-control" list={listId} required maxLength={100} />
|
||||
<datalist id={listId}>
|
||||
{suggestions.map((s) => (
|
||||
<option key={s} value={s} />
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("relation.to")}</label>
|
||||
<EntitySelect name="toId" entities={others} t={t} required />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label">{t("common.note")}</label>
|
||||
<input name="description" className="form-control" maxLength={2000} />
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label">{t("relation.members")}</label>
|
||||
<EntitySelect name="memberIds" entities={others} 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("relation.add")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import Link from "next/link";
|
||||
import type { EntityKind } from "@prisma/client";
|
||||
import { KIND_INFO } from "@/lib/kinds";
|
||||
|
||||
type Node = { id: string; name: string; kind: EntityKind };
|
||||
// Två deltagare ritas som en linje, fler (en grupp) som ett nav med linjer till varje deltagare.
|
||||
type Edge = { id: string; type: string; participantIds: string[] };
|
||||
|
||||
const W = 760;
|
||||
const H = 520;
|
||||
|
||||
/** Enkelt relationsdiagram: noderna placeras i en cirkel. Renderas på servern som ren SVG. */
|
||||
export function RelationGraph({ nodes, edges, bookId }: { nodes: Node[]; edges: Edge[]; bookId: string }) {
|
||||
const cx = W / 2;
|
||||
const cy = H / 2;
|
||||
const radius = Math.min(W, H) / 2 - 70;
|
||||
const pos = new Map(
|
||||
nodes.map((n, i) => {
|
||||
const angle = (2 * Math.PI * i) / Math.max(nodes.length, 1) - Math.PI / 2;
|
||||
const r = nodes.length === 1 ? 0 : radius;
|
||||
return [n.id, { x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle) }];
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${W} ${H}`} className="bm-graph w-100" role="img">
|
||||
{edges.map((e) => {
|
||||
const points = e.participantIds.map((id) => pos.get(id)).filter((p): p is { x: number; y: number } => !!p);
|
||||
if (points.length < 2) return null;
|
||||
|
||||
if (points.length === 2) {
|
||||
const [a, b] = points;
|
||||
return (
|
||||
<g key={e.id}>
|
||||
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} />
|
||||
<text className="bm-edge-label" x={(a.x + b.x) / 2} y={(a.y + b.y) / 2} textAnchor="middle">
|
||||
{e.type}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
// Grupp: nav i mitten av deltagarna
|
||||
const hub = {
|
||||
x: points.reduce((sum, p) => sum + p.x, 0) / points.length,
|
||||
y: points.reduce((sum, p) => sum + p.y, 0) / points.length,
|
||||
};
|
||||
return (
|
||||
<g key={e.id}>
|
||||
{points.map((p, i) => (
|
||||
<line key={i} x1={hub.x} y1={hub.y} x2={p.x} y2={p.y} />
|
||||
))}
|
||||
<rect x={hub.x - 5} y={hub.y - 5} width={10} height={10} rx={2} style={{ fill: "var(--tblr-secondary)" }} />
|
||||
<text className="bm-edge-label" x={hub.x} y={hub.y - 10} textAnchor="middle">
|
||||
{e.type}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{nodes.map((n) => {
|
||||
const p = pos.get(n.id)!;
|
||||
return (
|
||||
<Link key={n.id} href={`/books/${bookId}/entity/${n.id}`}>
|
||||
<circle cx={p.x} cy={p.y} r={14} style={{ fill: `var(--tblr-${KIND_INFO[n.kind].color})` }} />
|
||||
<text x={p.x} y={p.y + 30} textAnchor="middle">
|
||||
{n.name}
|
||||
</text>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import Link from "next/link";
|
||||
import {
|
||||
IconArrowLeft,
|
||||
IconBook2,
|
||||
IconCalendarWeek,
|
||||
IconChartDots3,
|
||||
IconLayoutDashboard,
|
||||
IconLogout,
|
||||
IconMap2,
|
||||
IconSettings,
|
||||
IconTemplate,
|
||||
IconBooks,
|
||||
} from "@tabler/icons-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { signOut } from "@/auth";
|
||||
import { setLocale } from "@/actions/settings";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { LOCALES } from "@/i18n/core";
|
||||
import { KINDS } from "@/lib/kinds";
|
||||
import { kindIcons } from "./kind-icons";
|
||||
import { NavLink } from "./nav-link";
|
||||
import { ThemeToggle } from "./theme-toggle";
|
||||
|
||||
type ShellProps = {
|
||||
user: { name?: string | null; email?: string | null };
|
||||
book?: { id: string; title: string };
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export async function Shell({ user, book, children }: ShellProps) {
|
||||
const { t, locale } = await getT();
|
||||
const base = book ? `/books/${book.id}` : "";
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<aside className="navbar navbar-vertical navbar-expand-lg" data-bs-theme="dark">
|
||||
<div className="container-fluid">
|
||||
<button
|
||||
className="navbar-toggler"
|
||||
type="button"
|
||||
data-bs-toggle="collapse"
|
||||
data-bs-target="#sidebar-menu"
|
||||
aria-controls="sidebar-menu"
|
||||
aria-expanded="false"
|
||||
aria-label={t("nav.openMenu")}
|
||||
>
|
||||
<span className="navbar-toggler-icon" />
|
||||
</button>
|
||||
<h1 className="navbar-brand navbar-brand-autodark">
|
||||
<Link href="/" className="d-flex align-items-center gap-2">
|
||||
<IconBook2 size={26} />
|
||||
<span>{t("app.name")}</span>
|
||||
</Link>
|
||||
</h1>
|
||||
|
||||
<div className="collapse navbar-collapse" id="sidebar-menu">
|
||||
<ul className="navbar-nav pt-lg-3">
|
||||
{book ? (
|
||||
<>
|
||||
<li className="nav-item">
|
||||
<Link className="nav-link" href="/">
|
||||
<span className="nav-link-icon d-md-none d-lg-inline-block">
|
||||
<IconArrowLeft size={20} />
|
||||
</span>
|
||||
<span className="nav-link-title">{t("nav.books")}</span>
|
||||
</Link>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<div className="nav-link text-truncate fw-bold text-white" title={book.title}>
|
||||
<span className="nav-link-icon d-md-none d-lg-inline-block">
|
||||
<IconBook2 size={20} />
|
||||
</span>
|
||||
<span className="nav-link-title">{book.title}</span>
|
||||
</div>
|
||||
</li>
|
||||
<NavLink href={base} exact icon={<IconLayoutDashboard size={20} />}>
|
||||
{t("nav.overview")}
|
||||
</NavLink>
|
||||
|
||||
<li className="nav-item mt-2">
|
||||
<div className="nav-link text-uppercase small text-secondary disabled">{t("nav.world")}</div>
|
||||
</li>
|
||||
{KINDS.map(({ kind, slug }) => {
|
||||
const Icon = kindIcons[kind];
|
||||
return (
|
||||
<NavLink key={kind} href={`${base}/e/${slug}`} icon={<Icon size={20} />}>
|
||||
{t(`kind.${kind}.other`)}
|
||||
</NavLink>
|
||||
);
|
||||
})}
|
||||
|
||||
<li className="nav-item mt-2">
|
||||
<div className="nav-link text-uppercase small text-secondary disabled">{t("nav.planning")}</div>
|
||||
</li>
|
||||
<NavLink href={`${base}/relations`} icon={<IconChartDots3 size={20} />}>
|
||||
{t("nav.relations")}
|
||||
</NavLink>
|
||||
<NavLink href={`${base}/schedules`} icon={<IconCalendarWeek size={20} />}>
|
||||
{t("nav.schedules")}
|
||||
</NavLink>
|
||||
<NavLink href={`${base}/maps`} icon={<IconMap2 size={20} />}>
|
||||
{t("nav.maps")}
|
||||
</NavLink>
|
||||
<NavLink href={`${base}/templates`} icon={<IconTemplate size={20} />}>
|
||||
{t("nav.templates")}
|
||||
</NavLink>
|
||||
<NavLink href={`${base}/settings`} icon={<IconSettings size={20} />}>
|
||||
{t("nav.settings")}
|
||||
</NavLink>
|
||||
</>
|
||||
) : (
|
||||
<NavLink href="/" exact icon={<IconBooks size={20} />}>
|
||||
{t("nav.books")}
|
||||
</NavLink>
|
||||
)}
|
||||
</ul>
|
||||
|
||||
<div className="mt-auto pt-4 pb-2 d-flex flex-column gap-2">
|
||||
<div className="d-flex align-items-center gap-2">
|
||||
<form action={setLocale} className="btn-group" aria-label={t("nav.language")}>
|
||||
{LOCALES.map((l) => (
|
||||
<button
|
||||
key={l}
|
||||
type="submit"
|
||||
name="locale"
|
||||
value={l}
|
||||
className={`btn btn-sm ${l === locale ? "btn-primary" : "btn-outline-secondary"}`}
|
||||
>
|
||||
{l.toUpperCase()}
|
||||
</button>
|
||||
))}
|
||||
</form>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
<div className="d-flex align-items-center justify-content-between gap-2">
|
||||
<span className="text-truncate text-secondary small" title={user.email ?? undefined}>
|
||||
{user.name ?? user.email}
|
||||
</span>
|
||||
<form
|
||||
action={async () => {
|
||||
"use server";
|
||||
await signOut({ redirectTo: "/login" });
|
||||
}}
|
||||
>
|
||||
<button type="submit" className="btn btn-icon btn-ghost-secondary" title={t("nav.logout")} aria-label={t("nav.logout")}>
|
||||
<IconLogout size={18} />
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div className="page-wrapper">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
// Tablers JavaScript (Bootstrap) ger meny som fälls ut, dropdowns och tooltips.
|
||||
export function TablerJs() {
|
||||
useEffect(() => {
|
||||
// @ts-expect-error Tabler levererar ingen typdeklaration för sin JS-bundle
|
||||
void import("@tabler/core/dist/js/tabler.min.js");
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { IconArrowDown, IconArrowUp, IconPlus, IconX } from "@tabler/icons-react";
|
||||
import type { TemplateKind } from "@/lib/kinds";
|
||||
import { resetTemplate, saveTemplate } from "@/actions/templates";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { useT } from "@/i18n/client";
|
||||
import { FIELD_TYPES, type FieldDef, type FieldType } from "@/lib/templates";
|
||||
|
||||
type Row = FieldDef & { optionsText: string; rowId: number };
|
||||
|
||||
function slugify(label: string): string {
|
||||
const base = label
|
||||
.toLowerCase()
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, " ")
|
||||
.trim()
|
||||
.split(" ")
|
||||
.map((w, i) => (i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)))
|
||||
.join("");
|
||||
return /^[a-z]/.test(base) ? base.slice(0, 40) : `field${base}`.slice(0, 40);
|
||||
}
|
||||
|
||||
export function TemplateEditor({
|
||||
bookId,
|
||||
kind,
|
||||
initialFields,
|
||||
custom,
|
||||
presets,
|
||||
}: {
|
||||
bookId: string;
|
||||
kind: TemplateKind;
|
||||
initialFields: FieldDef[];
|
||||
custom: boolean;
|
||||
presets: { id: string; label: string; fields: FieldDef[] }[];
|
||||
}) {
|
||||
const t = useT();
|
||||
const [nextId, setNextId] = useState(initialFields.length);
|
||||
const [rows, setRows] = useState<Row[]>(() =>
|
||||
initialFields.map((f, i) => ({ ...f, optionsText: (f.options ?? []).join(", "), rowId: i })),
|
||||
);
|
||||
const [json, setJson] = useState("");
|
||||
const [jsonError, setJsonError] = useState("");
|
||||
|
||||
const toFields = (list: Row[]): FieldDef[] =>
|
||||
list.map(({ optionsText, rowId, ...f }) => {
|
||||
void rowId;
|
||||
const field: FieldDef = { key: f.key, label: f.label, type: f.type };
|
||||
if (f.type === "select") {
|
||||
field.options = optionsText
|
||||
.split(",")
|
||||
.map((o) => o.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (f.section) field.section = f.section;
|
||||
return field;
|
||||
});
|
||||
|
||||
const update = (rowId: number, patch: Partial<Row>) =>
|
||||
setRows((list) => list.map((r) => (r.rowId === rowId ? { ...r, ...patch } : r)));
|
||||
|
||||
const move = (index: number, delta: number) =>
|
||||
setRows((list) => {
|
||||
const target = index + delta;
|
||||
if (target < 0 || target >= list.length) return list;
|
||||
const copy = [...list];
|
||||
[copy[index], copy[target]] = [copy[target], copy[index]];
|
||||
return copy;
|
||||
});
|
||||
|
||||
const addRow = () => {
|
||||
setRows((list) => [...list, { key: `field${nextId + 1}`, label: "", type: "text", optionsText: "", rowId: nextId }]);
|
||||
setNextId(nextId + 1);
|
||||
};
|
||||
|
||||
const loadFields = (list: FieldDef[]) => {
|
||||
let id = nextId;
|
||||
setRows(
|
||||
list.map((f) => ({
|
||||
key: String(f.key ?? ""),
|
||||
label: String(f.label ?? ""),
|
||||
type: FIELD_TYPES.includes(f.type) ? f.type : "text",
|
||||
section: f.section,
|
||||
optionsText: Array.isArray(f.options) ? f.options.join(", ") : "",
|
||||
rowId: id++,
|
||||
})),
|
||||
);
|
||||
setNextId(id);
|
||||
};
|
||||
|
||||
const applyJson = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(json);
|
||||
if (!Array.isArray(parsed)) throw new Error("array");
|
||||
loadFields(parsed as FieldDef[]);
|
||||
setJsonError("");
|
||||
} catch (error) {
|
||||
setJsonError(t("template.invalid", { reason: error instanceof Error ? error.message : "JSON" }));
|
||||
}
|
||||
};
|
||||
|
||||
const fieldsJson = JSON.stringify(toFields(rows));
|
||||
|
||||
return (
|
||||
<>
|
||||
<form action={saveTemplate}>
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="kind" value={kind} />
|
||||
<input type="hidden" name="fields" value={fieldsJson} />
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="list-group list-group-flush">
|
||||
{rows.length === 0 ? <div className="list-group-item text-secondary">{t("template.empty")}</div> : null}
|
||||
{rows.map((row, index) => (
|
||||
<div className="list-group-item" key={row.rowId}>
|
||||
<div className="row g-2 align-items-end">
|
||||
<div className="col-md-3">
|
||||
<label className="form-label">{t("template.fieldLabel")}</label>
|
||||
<input
|
||||
className="form-control"
|
||||
value={row.label}
|
||||
onChange={(e) => {
|
||||
const label = e.target.value;
|
||||
// Nya fält får nyckel utifrån namnet tills nyckeln ändrats för hand
|
||||
const auto = row.key === slugify(row.label) || /^field\d+$/.test(row.key);
|
||||
update(row.rowId, { label, ...(auto && label ? { key: slugify(label) } : {}) });
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-2">
|
||||
<label className="form-label">{t("template.fieldKey")}</label>
|
||||
<input className="form-control" value={row.key} onChange={(e) => update(row.rowId, { key: e.target.value })} required />
|
||||
</div>
|
||||
<div className="col-md-2">
|
||||
<label className="form-label">{t("template.fieldType")}</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={row.type}
|
||||
onChange={(e) => update(row.rowId, { type: e.target.value as FieldType })}
|
||||
>
|
||||
{FIELD_TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{t(`template.type.${type}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label">{row.type === "select" ? t("template.fieldOptions") : t("template.fieldSection")}</label>
|
||||
{row.type === "select" ? (
|
||||
<input className="form-control" value={row.optionsText} onChange={(e) => update(row.rowId, { optionsText: e.target.value })} />
|
||||
) : (
|
||||
<input className="form-control" value={row.section ?? ""} onChange={(e) => update(row.rowId, { section: e.target.value })} />
|
||||
)}
|
||||
</div>
|
||||
<div className="col-md-2 d-flex gap-1 justify-content-end">
|
||||
<button type="button" className="btn btn-icon btn-sm" onClick={() => move(index, -1)} title={t("common.moveUp")} aria-label={t("common.moveUp")}>
|
||||
<IconArrowUp size={16} />
|
||||
</button>
|
||||
<button type="button" className="btn btn-icon btn-sm" onClick={() => move(index, 1)} title={t("common.moveDown")} aria-label={t("common.moveDown")}>
|
||||
<IconArrowDown size={16} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon btn-sm btn-outline-danger"
|
||||
onClick={() => setRows((list) => list.filter((r) => r.rowId !== row.rowId))}
|
||||
title={t("common.delete")}
|
||||
aria-label={t("common.delete")}
|
||||
>
|
||||
<IconX size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{row.type === "select" ? (
|
||||
<div className="mt-2">
|
||||
<label className="form-label">{t("template.fieldSection")}</label>
|
||||
<input className="form-control" value={row.section ?? ""} onChange={(e) => update(row.rowId, { section: e.target.value })} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="card-footer d-flex flex-wrap gap-2 justify-content-between">
|
||||
<div className="d-flex flex-wrap gap-2">
|
||||
<button type="button" className="btn" onClick={addRow}>
|
||||
<IconPlus size={18} className="me-1" />
|
||||
{t("template.addField")}
|
||||
</button>
|
||||
{presets.map((preset) => (
|
||||
<button key={preset.id} type="button" className="btn" onClick={() => loadFields(preset.fields)}>
|
||||
{preset.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="row row-cards">
|
||||
<div className="col-lg-8">
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("template.json")}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">{t("template.jsonHelp")}</p>
|
||||
<textarea
|
||||
className="form-control font-monospace"
|
||||
rows={8}
|
||||
value={json}
|
||||
onChange={(e) => setJson(e.target.value)}
|
||||
placeholder={'[{"key":"nickname","label":"Smeknamn","type":"text"}]'}
|
||||
/>
|
||||
{jsonError ? <div className="text-danger mt-2">{jsonError}</div> : null}
|
||||
</div>
|
||||
<div className="card-footer d-flex gap-2">
|
||||
<button type="button" className="btn" onClick={() => setJson(JSON.stringify(toFields(rows), null, 2))}>
|
||||
{t("common.export")}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={applyJson} disabled={!json.trim()}>
|
||||
{t("template.jsonApply")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{custom ? (
|
||||
<div className="col-lg-4">
|
||||
<form action={resetTemplate} className="card">
|
||||
<input type="hidden" name="bookId" value={bookId} />
|
||||
<input type="hidden" name="kind" value={kind} />
|
||||
<div className="card-body">
|
||||
<ConfirmSubmit className="btn btn-outline-danger" message={t("template.resetConfirm")}>
|
||||
{t("template.reset")}
|
||||
</ConfirmSubmit>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { IconMoon, IconSun } from "@tabler/icons-react";
|
||||
import { useT } from "@/i18n/client";
|
||||
|
||||
export function ThemeToggle() {
|
||||
const t = useT();
|
||||
|
||||
function toggle() {
|
||||
const root = document.documentElement;
|
||||
const next = root.getAttribute("data-bs-theme") === "dark" ? "light" : "dark";
|
||||
root.setAttribute("data-bs-theme", next);
|
||||
document.cookie = `theme=${next}; path=/; max-age=31536000; samesite=lax`;
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon btn-ghost-secondary"
|
||||
onClick={toggle}
|
||||
title={t("nav.theme")}
|
||||
aria-label={t("nav.theme")}
|
||||
>
|
||||
<IconMoon size={18} className="hide-theme-dark" />
|
||||
<IconSun size={18} className="hide-theme-light" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useMemo, type ReactNode } from "react";
|
||||
import { makeT, type Dict, type Locale, type TFunction } from "./core";
|
||||
|
||||
type Ctx = { locale: Locale; t: TFunction };
|
||||
const I18nContext = createContext<Ctx | null>(null);
|
||||
|
||||
export function I18nProvider({
|
||||
locale,
|
||||
dict,
|
||||
children,
|
||||
}: {
|
||||
locale: Locale;
|
||||
dict: Dict;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const value = useMemo(() => ({ locale, t: makeT(dict) }), [locale, dict]);
|
||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||
}
|
||||
|
||||
export function useI18n(): Ctx {
|
||||
const ctx = useContext(I18nContext);
|
||||
if (!ctx) throw new Error("useI18n måste användas inom I18nProvider");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function useT(): TFunction {
|
||||
return useI18n().t;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { sv } from "./sv";
|
||||
import { en } from "./en";
|
||||
|
||||
export type Locale = "sv" | "en";
|
||||
export const LOCALES: Locale[] = ["sv", "en"];
|
||||
export const DEFAULT_LOCALE: Locale = "sv";
|
||||
export type Dict = Record<string, string>;
|
||||
export type TFunction = (key: string, vars?: Record<string, string | number>) => string;
|
||||
|
||||
export const dictionaries: Record<Locale, Dict> = { sv, en };
|
||||
|
||||
export function isLocale(value: unknown): value is Locale {
|
||||
return value === "sv" || value === "en";
|
||||
}
|
||||
|
||||
export function makeT(dict: Dict): TFunction {
|
||||
return (key, vars) => {
|
||||
let text = dict[key] ?? sv[key as keyof typeof sv] ?? key;
|
||||
if (vars) {
|
||||
for (const [name, value] of Object.entries(vars)) {
|
||||
text = text.replaceAll(`{${name}}`, String(value));
|
||||
}
|
||||
}
|
||||
return text;
|
||||
};
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
import type { sv } from "./sv";
|
||||
|
||||
export const en: Record<keyof typeof sv, string> = {
|
||||
"app.name": "Story Planner",
|
||||
|
||||
"common.save": "Save",
|
||||
"common.code": "ID / code",
|
||||
"common.codeHelp": "Optional, e.g. K001. For cross-referencing between documents.",
|
||||
"common.saved": "Saved.",
|
||||
"common.cancel": "Cancel",
|
||||
"common.delete": "Delete",
|
||||
"common.edit": "Edit",
|
||||
"common.create": "Create",
|
||||
"common.add": "Add",
|
||||
"common.back": "Back",
|
||||
"common.search": "Search",
|
||||
"common.name": "Name",
|
||||
"common.summary": "Summary",
|
||||
"common.tags": "Tags",
|
||||
"common.tagsHelp": "Comma separated, e.g. protagonist, thriller",
|
||||
"common.image": "Image",
|
||||
"common.removeImage": "Remove image",
|
||||
"common.description": "Description",
|
||||
"common.none": "None",
|
||||
"common.confirmDelete": "Are you sure? This cannot be undone.",
|
||||
"common.updated": "Updated",
|
||||
"common.actions": "Actions",
|
||||
"common.noResults": "Nothing found.",
|
||||
"common.export": "Export",
|
||||
"common.type": "Type",
|
||||
"common.note": "Note",
|
||||
"common.color": "Colour",
|
||||
"common.yes": "Yes",
|
||||
"common.no": "No",
|
||||
"common.choose": "Choose…",
|
||||
"common.open": "Open",
|
||||
"common.all": "All",
|
||||
"common.title": "Title",
|
||||
"common.loading": "Loading…",
|
||||
"common.moveUp": "Move up",
|
||||
"common.moveDown": "Move down",
|
||||
"common.clear": "Clear",
|
||||
|
||||
"nav.books": "My books",
|
||||
"nav.overview": "Overview",
|
||||
"nav.world": "World",
|
||||
"nav.planning": "Planning",
|
||||
"nav.relations": "Relationships",
|
||||
"nav.schedules": "Schedules",
|
||||
"nav.maps": "Maps",
|
||||
"nav.templates": "Templates",
|
||||
"nav.settings": "Book settings",
|
||||
"nav.logout": "Log out",
|
||||
"nav.theme": "Toggle theme",
|
||||
"nav.language": "Language",
|
||||
"nav.openMenu": "Open menu",
|
||||
|
||||
"login.title": "Sign in",
|
||||
"login.subtitle": "Use your Authentik account to continue.",
|
||||
"login.button": "Sign in with Authentik",
|
||||
"login.notConfigured": "Authentik is not configured. Set AUTHENTIK_ISSUER, AUTHENTIK_CLIENT_ID and AUTHENTIK_CLIENT_SECRET.",
|
||||
"login.dev":"Developer login (local only)",
|
||||
"login.devName": "Name",
|
||||
"login.devButton": "Continue as developer",
|
||||
|
||||
"books.title": "My books",
|
||||
"books.empty": "You have no books yet. Create your first one!",
|
||||
"books.new": "New book",
|
||||
"books.subtitle": "Subtitle",
|
||||
"books.genre": "Genre",
|
||||
"books.items": "{n} items",
|
||||
"books.create": "Create book",
|
||||
|
||||
"dashboard.recent": "Recently changed",
|
||||
"dashboard.emptyRecent": "Nothing yet. Start with a character or a place.",
|
||||
"dashboard.quickAdd": "Create new",
|
||||
|
||||
"kind.CHARACTER.one": "Character",
|
||||
"kind.CHARACTER.other": "Characters",
|
||||
"kind.CHARACTER.new": "New character",
|
||||
"kind.HOME.one": "Home",
|
||||
"kind.HOME.other": "Homes",
|
||||
"kind.HOME.new": "New home",
|
||||
"kind.PLACE.one": "Place",
|
||||
"kind.PLACE.other": "Places",
|
||||
"kind.PLACE.new": "New place",
|
||||
"kind.COMPANY.one": "Company",
|
||||
"kind.COMPANY.other": "Companies",
|
||||
"kind.COMPANY.new": "New company",
|
||||
"kind.PREMISES.one": "Premises",
|
||||
"kind.PREMISES.other": "Premises",
|
||||
"kind.PREMISES.new": "New premises",
|
||||
"kind.EDUCATION.one": "Education",
|
||||
"kind.EDUCATION.other": "Education",
|
||||
"kind.EDUCATION.new": "New education",
|
||||
"kind.SCENARIO.one": "Scenario",
|
||||
"kind.SCENARIO.other": "Scenarios",
|
||||
"kind.SCENARIO.new": "New scenario",
|
||||
"kind.PET.one": "Pet",
|
||||
"kind.PET.other": "Pets",
|
||||
"kind.PET.new": "New pet",
|
||||
|
||||
"entity.search": "Search by name or summary…",
|
||||
"entity.empty": "Nothing here yet. Create the first one!",
|
||||
"entity.details": "Details",
|
||||
"entity.noDetails": "No details filled in yet.",
|
||||
"entity.relations": "Relationships",
|
||||
"entity.noRelations": "No relationships yet.",
|
||||
"entity.onMap": "Location on map",
|
||||
"entity.noMarkers": "Not placed on any map yet.",
|
||||
"entity.placeOnMap": "Place on map",
|
||||
"entity.schedule": "Work schedule",
|
||||
"entity.noShifts": "No shifts added.",
|
||||
"entity.workers": "Works here",
|
||||
"entity.noWorkers": "Nobody has shifts here yet.",
|
||||
"entity.filterTag": "Tag: {tag}",
|
||||
"entity.selectOne": "Choose an item…",
|
||||
"entity.editTitle": "Edit {name}",
|
||||
|
||||
"relation.title": "Relationships",
|
||||
"relation.members": "More participants",
|
||||
"relation.membersHelp": "Optional. Pick several for e.g. a friend group (hold Ctrl/Cmd).",
|
||||
"relation.one": "Relationship",
|
||||
"relation.add": "Add relationship",
|
||||
"relation.type": "Relationship",
|
||||
"relation.typeHelp": "Type freely or pick a suggestion, e.g. “Sibling of”.",
|
||||
"relation.from": "From",
|
||||
"relation.to": "To",
|
||||
"relation.diagram": "Relationship diagram",
|
||||
"relation.all": "All relationships",
|
||||
"relation.empty": "No relationships yet.",
|
||||
"relation.filter": "Show relationships for",
|
||||
"relation.suggestions": "Partner of,Parent of,Child of,Sibling of,Friend of,Colleague of,Boss of,Enemy of,Neighbour of,Lives at,Works at,Owns,Owned by,Pet of,Involved in,Affected by,Student at,Teacher at",
|
||||
"relation.sameEntity": "An item cannot have a relationship with itself.",
|
||||
|
||||
"schedule.title": "Schedules",
|
||||
"schedule.add": "Add shift",
|
||||
"schedule.person": "Person",
|
||||
"schedule.workplace": "Workplace",
|
||||
"schedule.noWorkplace": "No workplace",
|
||||
"schedule.days": "Days",
|
||||
"schedule.start": "Starts",
|
||||
"schedule.end": "Ends",
|
||||
"schedule.weeks": "Weeks",
|
||||
"schedule.weeks.ALL": "Every week",
|
||||
"schedule.weeks.ODD": "Odd weeks",
|
||||
"schedule.weeks.EVEN": "Even weeks",
|
||||
"schedule.label": "Description",
|
||||
"schedule.labelHelp": "e.g. Evening shift",
|
||||
"schedule.viewPerson": "By person",
|
||||
"schedule.viewDay": "By day",
|
||||
"schedule.viewGrid": "Hour grid",
|
||||
"schedule.rangeDay": "Day 06–18",
|
||||
"schedule.rangeNight": "Night 18–06",
|
||||
"schedule.empty": "No shifts yet.",
|
||||
"schedule.filterWorkplace": "Filter by workplace",
|
||||
"schedule.filterPerson": "Filter by person",
|
||||
"schedule.needDays": "Choose at least one day.",
|
||||
"schedule.noPeople": "Create a character first to be able to add schedules.",
|
||||
"day.0": "Monday",
|
||||
"day.1": "Tuesday",
|
||||
"day.2": "Wednesday",
|
||||
"day.3": "Thursday",
|
||||
"day.4": "Friday",
|
||||
"day.5": "Saturday",
|
||||
"day.6": "Sunday",
|
||||
"day.short.0": "Mon",
|
||||
"day.short.1": "Tue",
|
||||
"day.short.2": "Wed",
|
||||
"day.short.3": "Thu",
|
||||
"day.short.4": "Fri",
|
||||
"day.short.5": "Sat",
|
||||
"day.short.6": "Sun",
|
||||
|
||||
"map.title": "Maps",
|
||||
"map.new": "New map",
|
||||
"map.kind.GEO": "Real map (OpenStreetMap)",
|
||||
"map.kind.IMAGE": "Custom map image",
|
||||
"map.image": "Map image",
|
||||
"map.imageHelp": "PNG, JPG, WebP or GIF, max 15 MB.",
|
||||
"map.imageRequired": "Upload an image for the map.",
|
||||
"map.empty": "No maps yet. Create a real map or upload your own image.",
|
||||
"map.markers": "Markers",
|
||||
"map.markerCount": "{n} markers",
|
||||
"map.noMarkers": "No markers yet.",
|
||||
"map.addMarker": "Add marker",
|
||||
"map.addHint": "Click the map where the marker should go.",
|
||||
"map.cancelAdd": "Cancel placing",
|
||||
"map.markerLabel": "Label",
|
||||
"map.linkedTo": "Linked to",
|
||||
"map.noLink": "No link",
|
||||
"map.editMarker": "Edit marker",
|
||||
"map.newMarker": "New marker",
|
||||
"map.dragHint": "Drag a marker to move it.",
|
||||
"map.saveView": "Save view",
|
||||
"map.viewSaved": "View saved",
|
||||
"map.search": "Search address or place…",
|
||||
"map.searching": "Searching…",
|
||||
"map.noHits": "No results.",
|
||||
"map.settings": "Map settings",
|
||||
"map.rename": "Rename",
|
||||
"map.deleteMap": "Delete map",
|
||||
"map.deleteMapHelp": "Removes the map and all markers on it.",
|
||||
"map.openEntity": "Open {name}",
|
||||
"map.viewOnMap": "View on map",
|
||||
"color.blue": "Blue",
|
||||
"color.red": "Red",
|
||||
"color.green": "Green",
|
||||
"color.orange": "Orange",
|
||||
"color.purple": "Purple",
|
||||
"color.pink": "Pink",
|
||||
"color.teal": "Teal",
|
||||
"color.yellow": "Yellow",
|
||||
|
||||
"template.title": "Templates",
|
||||
"template.intro": "Each type has a template that decides which fields the form has. Customise the templates for this book or paste your own as JSON.",
|
||||
"template.standard": "Standard template",
|
||||
"template.custom": "Custom template",
|
||||
"template.edit": "Edit template",
|
||||
"template.fields": "{n} fields",
|
||||
"template.fieldLabel": "Field name",
|
||||
"template.fieldKey": "Key",
|
||||
"template.fieldType": "Field type",
|
||||
"template.fieldOptions": "Options (comma separated)",
|
||||
"template.fieldSection": "Start new section with heading",
|
||||
"template.addField": "Add field",
|
||||
"template.preset.short": "Load short template",
|
||||
"template.reset": "Reset to standard",
|
||||
"template.resetConfirm": "Reset to the standard template? Data already filled in is kept.",
|
||||
"template.json": "Advanced: JSON",
|
||||
"template.jsonHelp": "Copy the template or paste your own. Each field has key, label, type and optionally options and section.",
|
||||
"template.jsonApply": "Use JSON",
|
||||
"template.invalid": "Invalid template: {reason}",
|
||||
"template.type.text": "Text",
|
||||
"template.type.textarea": "Text area",
|
||||
"template.type.number": "Number",
|
||||
"template.type.date": "Date",
|
||||
"template.type.select": "Choice",
|
||||
"template.type.checkbox": "Checkbox",
|
||||
"template.type.url": "Link",
|
||||
"template.empty": "The template has no fields yet.",
|
||||
|
||||
"settings.title": "Book settings",
|
||||
"settings.danger": "Danger zone",
|
||||
"settings.deleteBook": "Delete book",
|
||||
"settings.deleteBookHelp": "Permanently deletes the book and all its content. Export first if you want a copy.",
|
||||
"settings.export": "Export as JSON",
|
||||
"settings.exportHelp": "Downloads all items, relationships, schedules, maps and templates in the book.",
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { DEFAULT_LOCALE, dictionaries, isLocale, makeT, type Locale } from "./core";
|
||||
|
||||
export async function getLocale(): Promise<Locale> {
|
||||
const value = (await cookies()).get("lang")?.value;
|
||||
return isLocale(value) ? value : DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
export async function getT() {
|
||||
const locale = await getLocale();
|
||||
return { locale, t: makeT(dictionaries[locale]) };
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
export const sv = {
|
||||
"app.name": "Bokplanerare",
|
||||
|
||||
"common.save": "Spara",
|
||||
"common.code": "ID / kod",
|
||||
"common.codeHelp": "Valfritt, t.ex. K001. För att hänvisa mellan dokument.",
|
||||
"common.saved": "Sparat.",
|
||||
"common.cancel": "Avbryt",
|
||||
"common.delete": "Ta bort",
|
||||
"common.edit": "Redigera",
|
||||
"common.create": "Skapa",
|
||||
"common.add": "Lägg till",
|
||||
"common.back": "Tillbaka",
|
||||
"common.search": "Sök",
|
||||
"common.name": "Namn",
|
||||
"common.summary": "Sammanfattning",
|
||||
"common.tags": "Taggar",
|
||||
"common.tagsHelp": "Kommaseparerade, t.ex. huvudperson, deckare",
|
||||
"common.image": "Bild",
|
||||
"common.removeImage": "Ta bort bild",
|
||||
"common.description": "Beskrivning",
|
||||
"common.none": "Ingen",
|
||||
"common.confirmDelete": "Är du säker? Detta kan inte ångras.",
|
||||
"common.updated": "Uppdaterad",
|
||||
"common.actions": "Åtgärder",
|
||||
"common.noResults": "Inget hittades.",
|
||||
"common.export": "Exportera",
|
||||
"common.type": "Typ",
|
||||
"common.note": "Anteckning",
|
||||
"common.color": "Färg",
|
||||
"common.yes": "Ja",
|
||||
"common.no": "Nej",
|
||||
"common.choose": "Välj…",
|
||||
"common.open": "Öppna",
|
||||
"common.all": "Alla",
|
||||
"common.title": "Titel",
|
||||
"common.loading": "Laddar…",
|
||||
"common.moveUp": "Flytta upp",
|
||||
"common.moveDown": "Flytta ner",
|
||||
"common.clear": "Rensa",
|
||||
|
||||
"nav.books": "Mina böcker",
|
||||
"nav.overview": "Översikt",
|
||||
"nav.world": "Världen",
|
||||
"nav.planning": "Planering",
|
||||
"nav.relations": "Relationer",
|
||||
"nav.schedules": "Scheman",
|
||||
"nav.maps": "Kartor",
|
||||
"nav.templates": "Mallar",
|
||||
"nav.settings": "Bokinställningar",
|
||||
"nav.logout": "Logga ut",
|
||||
"nav.theme": "Växla tema",
|
||||
"nav.language": "Språk",
|
||||
"nav.openMenu": "Öppna meny",
|
||||
|
||||
"login.title": "Logga in",
|
||||
"login.subtitle": "Använd ditt Authentik-konto för att fortsätta.",
|
||||
"login.button": "Logga in med Authentik",
|
||||
"login.notConfigured": "Authentik är inte konfigurerat. Sätt AUTHENTIK_ISSUER, AUTHENTIK_CLIENT_ID och AUTHENTIK_CLIENT_SECRET.",
|
||||
"login.dev":"Utvecklarinloggning (endast lokalt)",
|
||||
"login.devName": "Namn",
|
||||
"login.devButton": "Fortsätt som utvecklare",
|
||||
|
||||
"books.title": "Mina böcker",
|
||||
"books.empty": "Du har inga böcker ännu. Skapa din första!",
|
||||
"books.new": "Ny bok",
|
||||
"books.subtitle": "Undertitel",
|
||||
"books.genre": "Genre",
|
||||
"books.items": "{n} poster",
|
||||
"books.create": "Skapa bok",
|
||||
|
||||
"dashboard.recent": "Senast ändrat",
|
||||
"dashboard.emptyRecent": "Inget skapat ännu. Börja med en karaktär eller en plats.",
|
||||
"dashboard.quickAdd": "Skapa nytt",
|
||||
|
||||
"kind.CHARACTER.one": "Karaktär",
|
||||
"kind.CHARACTER.other": "Karaktärer",
|
||||
"kind.CHARACTER.new": "Ny karaktär",
|
||||
"kind.HOME.one": "Bostad",
|
||||
"kind.HOME.other": "Bostäder",
|
||||
"kind.HOME.new": "Ny bostad",
|
||||
"kind.PLACE.one": "Plats",
|
||||
"kind.PLACE.other": "Platser",
|
||||
"kind.PLACE.new": "Ny plats",
|
||||
"kind.COMPANY.one": "Företag",
|
||||
"kind.COMPANY.other": "Företag",
|
||||
"kind.COMPANY.new": "Nytt företag",
|
||||
"kind.PREMISES.one": "Lokal",
|
||||
"kind.PREMISES.other": "Lokaler",
|
||||
"kind.PREMISES.new": "Ny lokal",
|
||||
"kind.EDUCATION.one": "Utbildning",
|
||||
"kind.EDUCATION.other": "Utbildningar",
|
||||
"kind.EDUCATION.new": "Ny utbildning",
|
||||
"kind.SCENARIO.one": "Scenario",
|
||||
"kind.SCENARIO.other": "Scenarier",
|
||||
"kind.SCENARIO.new": "Nytt scenario",
|
||||
"kind.PET.one": "Husdjur",
|
||||
"kind.PET.other": "Husdjur",
|
||||
"kind.PET.new": "Nytt husdjur",
|
||||
|
||||
"entity.search": "Sök på namn eller sammanfattning…",
|
||||
"entity.empty": "Inget här ännu. Skapa det första!",
|
||||
"entity.details": "Detaljer",
|
||||
"entity.noDetails": "Inga detaljer ifyllda ännu.",
|
||||
"entity.relations": "Relationer",
|
||||
"entity.noRelations": "Inga relationer ännu.",
|
||||
"entity.onMap": "Placering på karta",
|
||||
"entity.noMarkers": "Inte placerad på någon karta ännu.",
|
||||
"entity.placeOnMap": "Placera på karta",
|
||||
"entity.schedule": "Arbetsschema",
|
||||
"entity.noShifts": "Inga arbetspass inlagda.",
|
||||
"entity.workers": "Arbetar här",
|
||||
"entity.noWorkers": "Ingen har pass här ännu.",
|
||||
"entity.filterTag": "Tagg: {tag}",
|
||||
"entity.selectOne": "Välj en post…",
|
||||
"entity.editTitle": "Redigera {name}",
|
||||
|
||||
"relation.title": "Relationer",
|
||||
"relation.members": "Fler deltagare",
|
||||
"relation.membersHelp": "Valfritt. Välj flera för t.ex. en vännergrupp (håll ner Ctrl/Cmd).",
|
||||
"relation.one": "Relation",
|
||||
"relation.add": "Lägg till relation",
|
||||
"relation.type": "Relation",
|
||||
"relation.typeHelp": "Skriv fritt eller välj ett förslag, t.ex. ”Syskon till”.",
|
||||
"relation.from": "Från",
|
||||
"relation.to": "Till",
|
||||
"relation.diagram": "Relationsdiagram",
|
||||
"relation.all": "Alla relationer",
|
||||
"relation.empty": "Inga relationer ännu.",
|
||||
"relation.filter": "Visa relationer för",
|
||||
"relation.suggestions": "Partner till,Förälder till,Barn till,Syskon till,Vän till,Kollega till,Chef över,Ovän till,Granne till,Bor på,Jobbar på,Äger,Ägs av,Husdjur till,Involverad i,Berörd av,Elev på,Lärare på",
|
||||
"relation.sameEntity": "En post kan inte ha en relation till sig själv.",
|
||||
|
||||
"schedule.title": "Scheman",
|
||||
"schedule.add": "Lägg till arbetspass",
|
||||
"schedule.person": "Person",
|
||||
"schedule.workplace": "Arbetsplats",
|
||||
"schedule.noWorkplace": "Ingen arbetsplats",
|
||||
"schedule.days": "Dagar",
|
||||
"schedule.start": "Börjar",
|
||||
"schedule.end": "Slutar",
|
||||
"schedule.weeks": "Veckor",
|
||||
"schedule.weeks.ALL": "Alla veckor",
|
||||
"schedule.weeks.ODD": "Udda veckor",
|
||||
"schedule.weeks.EVEN": "Jämna veckor",
|
||||
"schedule.label": "Beskrivning",
|
||||
"schedule.labelHelp": "t.ex. Kvällspass",
|
||||
"schedule.viewPerson": "Per person",
|
||||
"schedule.viewDay": "Per dag",
|
||||
"schedule.viewGrid": "Timrutnät",
|
||||
"schedule.rangeDay": "Dag 06–18",
|
||||
"schedule.rangeNight": "Natt 18–06",
|
||||
"schedule.empty": "Inga arbetspass ännu.",
|
||||
"schedule.filterWorkplace": "Filtrera på arbetsplats",
|
||||
"schedule.filterPerson": "Filtrera på person",
|
||||
"schedule.needDays": "Välj minst en dag.",
|
||||
"schedule.noPeople": "Skapa en karaktär först för att kunna lägga in scheman.",
|
||||
"day.0": "Måndag",
|
||||
"day.1": "Tisdag",
|
||||
"day.2": "Onsdag",
|
||||
"day.3": "Torsdag",
|
||||
"day.4": "Fredag",
|
||||
"day.5": "Lördag",
|
||||
"day.6": "Söndag",
|
||||
"day.short.0": "Mån",
|
||||
"day.short.1": "Tis",
|
||||
"day.short.2": "Ons",
|
||||
"day.short.3": "Tors",
|
||||
"day.short.4": "Fre",
|
||||
"day.short.5": "Lör",
|
||||
"day.short.6": "Sön",
|
||||
|
||||
"map.title": "Kartor",
|
||||
"map.new": "Ny karta",
|
||||
"map.kind.GEO": "Riktig karta (OpenStreetMap)",
|
||||
"map.kind.IMAGE": "Egen kartbild",
|
||||
"map.image": "Kartbild",
|
||||
"map.imageHelp": "PNG, JPG, WebP eller GIF, max 15 MB.",
|
||||
"map.imageRequired": "Ladda upp en bild till kartan.",
|
||||
"map.empty": "Inga kartor ännu. Skapa en riktig karta eller ladda upp en egen bild.",
|
||||
"map.markers": "Markeringar",
|
||||
"map.markerCount": "{n} markeringar",
|
||||
"map.noMarkers": "Inga markeringar ännu.",
|
||||
"map.addMarker": "Lägg till markering",
|
||||
"map.addHint": "Klicka på kartan där markeringen ska sitta.",
|
||||
"map.cancelAdd": "Avbryt placering",
|
||||
"map.markerLabel": "Etikett",
|
||||
"map.linkedTo": "Kopplad till",
|
||||
"map.noLink": "Ingen koppling",
|
||||
"map.editMarker": "Redigera markering",
|
||||
"map.newMarker": "Ny markering",
|
||||
"map.dragHint": "Dra en markering för att flytta den.",
|
||||
"map.saveView": "Spara vy",
|
||||
"map.viewSaved": "Vyn sparad",
|
||||
"map.search": "Sök adress eller plats…",
|
||||
"map.searching": "Söker…",
|
||||
"map.noHits": "Inga träffar.",
|
||||
"map.settings": "Kartinställningar",
|
||||
"map.rename": "Byt namn",
|
||||
"map.deleteMap": "Ta bort kartan",
|
||||
"map.deleteMapHelp": "Tar bort kartan och alla markeringar på den.",
|
||||
"map.openEntity": "Öppna {name}",
|
||||
"map.viewOnMap": "Visa på karta",
|
||||
"color.blue": "Blå",
|
||||
"color.red": "Röd",
|
||||
"color.green": "Grön",
|
||||
"color.orange": "Orange",
|
||||
"color.purple": "Lila",
|
||||
"color.pink": "Rosa",
|
||||
"color.teal": "Turkos",
|
||||
"color.yellow": "Gul",
|
||||
|
||||
"template.title": "Mallar",
|
||||
"template.intro": "Varje typ har en mall som bestämmer vilka fält som finns i formuläret. Anpassa mallarna för just den här boken eller klistra in dina egna som JSON.",
|
||||
"template.standard": "Standardmall",
|
||||
"template.custom": "Egen mall",
|
||||
"template.edit": "Redigera mall",
|
||||
"template.fields": "{n} fält",
|
||||
"template.fieldLabel": "Fältnamn",
|
||||
"template.fieldKey": "Nyckel",
|
||||
"template.fieldType": "Fälttyp",
|
||||
"template.fieldOptions": "Alternativ (kommaseparerade)",
|
||||
"template.fieldSection": "Ny sektion med rubrik",
|
||||
"template.addField": "Lägg till fält",
|
||||
"template.preset.short": "Ladda kort mall",
|
||||
"template.reset": "Återställ till standard",
|
||||
"template.resetConfirm": "Återställa standardmallen? Ifylld data i fälten finns kvar.",
|
||||
"template.json": "Avancerat: JSON",
|
||||
"template.jsonHelp": "Kopiera mallen eller klistra in en egen. Varje fält har key, label, type och valfritt options och section.",
|
||||
"template.jsonApply": "Använd JSON",
|
||||
"template.invalid": "Ogiltig mall: {reason}",
|
||||
"template.type.text": "Text",
|
||||
"template.type.textarea": "Textruta",
|
||||
"template.type.number": "Tal",
|
||||
"template.type.date": "Datum",
|
||||
"template.type.select": "Val",
|
||||
"template.type.checkbox": "Kryssruta",
|
||||
"template.type.url": "Länk",
|
||||
"template.empty": "Mallen har inga fält ännu.",
|
||||
|
||||
"settings.title": "Bokinställningar",
|
||||
"settings.danger": "Farlig zon",
|
||||
"settings.deleteBook": "Ta bort boken",
|
||||
"settings.deleteBookHelp": "Raderar boken och allt innehåll permanent. Exportera först om du vill spara en kopia.",
|
||||
"settings.export": "Exportera som JSON",
|
||||
"settings.exportHelp": "Laddar ner alla poster, relationer, scheman, kartor och mallar i boken.",
|
||||
} as const;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,50 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
const EXTENSIONS: Record<string, string> = {
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/webp": "webp",
|
||||
"image/gif": "gif",
|
||||
};
|
||||
|
||||
export const CONTENT_TYPES: Record<string, string> = {
|
||||
png: "image/png",
|
||||
jpg: "image/jpeg",
|
||||
webp: "image/webp",
|
||||
gif: "image/gif",
|
||||
};
|
||||
|
||||
export const FILE_NAME_PATTERN = /^[a-f0-9-]{36}\.(png|jpg|webp|gif)$/;
|
||||
|
||||
export function isUpload(value: FormDataEntryValue | null): value is File {
|
||||
return typeof value === "object" && value !== null && value.size > 0;
|
||||
}
|
||||
|
||||
/** Sparar en uppladdad bild och returnerar filnamnet. Kastar vid fel typ eller storlek. */
|
||||
export async function saveImage(file: File): Promise<string> {
|
||||
const ext = EXTENSIONS[file.type];
|
||||
if (!ext) throw new Error("Unsupported image type");
|
||||
if (file.size > MAX_UPLOAD_BYTES) throw new Error("Image is too large");
|
||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
||||
const name = `${randomUUID()}.${ext}`;
|
||||
await writeFile(path.join(UPLOAD_DIR, name), Buffer.from(await file.arrayBuffer()));
|
||||
return name;
|
||||
}
|
||||
|
||||
export async function deleteImage(name: string | null | undefined) {
|
||||
if (!name || !FILE_NAME_PATTERN.test(name)) return;
|
||||
try {
|
||||
await unlink(path.join(UPLOAD_DIR, name));
|
||||
} catch {
|
||||
// filen kan redan vara borta
|
||||
}
|
||||
}
|
||||
|
||||
export function fileUrl(name: string | null | undefined): string | null {
|
||||
return name ? `/api/files/${name}` : null;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export function str(formData: FormData, key: string, max = 2000): string {
|
||||
const value = formData.get(key);
|
||||
return typeof value === "string" ? value.trim().slice(0, max) : "";
|
||||
}
|
||||
|
||||
export function optStr(formData: FormData, key: string, max = 20000): string | null {
|
||||
return str(formData, key, max) || null;
|
||||
}
|
||||
|
||||
export function parseTags(input: string): string[] {
|
||||
const tags = input
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean)
|
||||
.map((t) => t.slice(0, 40));
|
||||
return [...new Set(tags)].slice(0, 30);
|
||||
}
|
||||
|
||||
export function revalidateBook(bookId: string) {
|
||||
revalidatePath(`/books/${bookId}`, "layout");
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { EntityKind } from "@prisma/client";
|
||||
|
||||
export type KindInfo = {
|
||||
kind: EntityKind;
|
||||
slug: string;
|
||||
color: string;
|
||||
};
|
||||
|
||||
// Ordningen styr menyer och översikt.
|
||||
export const KINDS: KindInfo[] = [
|
||||
{ kind: "CHARACTER", slug: "characters", color: "blue" },
|
||||
{ kind: "PET", slug: "pets", color: "orange" },
|
||||
{ kind: "HOME", slug: "homes", color: "green" },
|
||||
{ kind: "PLACE", slug: "places", color: "red" },
|
||||
{ kind: "COMPANY", slug: "companies", color: "purple" },
|
||||
{ kind: "PREMISES", slug: "premises", color: "teal" },
|
||||
{ kind: "EDUCATION", slug: "education", color: "cyan" },
|
||||
{ kind: "SCENARIO", slug: "scenarios", color: "pink" },
|
||||
];
|
||||
|
||||
export const KIND_BY_SLUG = new Map(KINDS.map((k) => [k.slug, k]));
|
||||
export const KIND_INFO = Object.fromEntries(KINDS.map((k) => [k.kind, k])) as Record<EntityKind, KindInfo>;
|
||||
|
||||
export function parseKind(value: unknown): EntityKind | null {
|
||||
return typeof value === "string" && value in KIND_INFO ? (value as EntityKind) : null;
|
||||
}
|
||||
|
||||
// Mallar finns för alla typer och dessutom för relationer.
|
||||
export type TemplateKind = EntityKind | "RELATION";
|
||||
export const RELATION_SLUG = "relations";
|
||||
|
||||
export function parseTemplateKind(value: unknown): TemplateKind | null {
|
||||
return value === "RELATION" ? "RELATION" : parseKind(value);
|
||||
}
|
||||
|
||||
export function templateSlug(kind: TemplateKind): string {
|
||||
return kind === "RELATION" ? RELATION_SLUG : KIND_INFO[kind].slug;
|
||||
}
|
||||
|
||||
export function templateKindFromSlug(slug: string): TemplateKind | null {
|
||||
return slug === RELATION_SLUG ? "RELATION" : (KIND_BY_SLUG.get(slug)?.kind ?? null);
|
||||
}
|
||||
|
||||
// Typer som kan ha arbetsplats i scheman
|
||||
export const WORKPLACE_KINDS: EntityKind[] = ["COMPANY", "PREMISES", "PLACE", "EDUCATION"];
|
||||
|
||||
export const MARKER_COLORS: Record<string, string> = {
|
||||
blue: "#206bc4",
|
||||
red: "#d63939",
|
||||
green: "#2fb344",
|
||||
orange: "#f76707",
|
||||
purple: "#ae3ec9",
|
||||
pink: "#d6336c",
|
||||
teal: "#0ca678",
|
||||
yellow: "#f59f00",
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { auth } from "@/auth";
|
||||
import { prisma } from "./db";
|
||||
|
||||
export async function requireUser() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
return session.user;
|
||||
}
|
||||
|
||||
/** Hämtar boken om den tillhör inloggad användare, annars 404. */
|
||||
export async function requireBook(bookId: string) {
|
||||
const user = await requireUser();
|
||||
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id } });
|
||||
if (!book) notFound();
|
||||
return book;
|
||||
}
|
||||
|
||||
/** Hämtar en post i boken, annars 404. */
|
||||
export async function requireEntity(bookId: string, entityId: string) {
|
||||
await requireBook(bookId);
|
||||
const entity = await prisma.entity.findFirst({ where: { id: entityId, bookId } });
|
||||
if (!entity) notFound();
|
||||
return entity;
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { prisma } from "./db";
|
||||
import type { Locale } from "@/i18n/core";
|
||||
import type { TemplateKind } from "./kinds";
|
||||
|
||||
export type FieldType = "text" | "textarea" | "number" | "date" | "select" | "checkbox" | "url";
|
||||
|
||||
export const FIELD_TYPES: FieldType[] = ["text", "textarea", "number", "date", "select", "checkbox", "url"];
|
||||
|
||||
export type FieldDef = {
|
||||
key: string;
|
||||
label: string;
|
||||
type: FieldType;
|
||||
options?: string[];
|
||||
// Ett fält med section startar en ny rubrik i formuläret och på sidan.
|
||||
section?: string;
|
||||
};
|
||||
|
||||
type L = [string, string]; // [svenska, engelska]
|
||||
type Spec = { k: string; l: L; t?: FieldType; o?: [string[], string[]]; s?: L };
|
||||
|
||||
const f = (k: string, l: L, t: FieldType = "text", s?: L, o?: [string[], string[]]): Spec => ({ k, l, t, s, o });
|
||||
const yes = (k: string, l: L, s?: L): Spec => f(k, l, "checkbox", s);
|
||||
const area = (k: string, l: L, s?: L): Spec => f(k, l, "textarea", s);
|
||||
const pick = (k: string, l: L, sv: string[], en: string[], s?: L): Spec => f(k, l, "select", s, [sv, en]);
|
||||
|
||||
const NOTES: Spec = area("notes", ["Övrigt", "Other"]);
|
||||
|
||||
// Standardmallarna följer författarens Word-mallar. Poster har dessutom ett eget ID/kod-fält,
|
||||
// och kopplingar till andra poster (anställd hos, ägare, boende ...) görs som relationer.
|
||||
const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
CHARACTER: [
|
||||
f("nickname", ["Smeknamn", "Nickname"], "text", ["Grunduppgifter", "Basics"]),
|
||||
f("age", ["Ålder", "Age"], "number"),
|
||||
f("birthDate", ["Födelsedatum", "Date of birth"], "date"),
|
||||
f("height", ["Längd", "Height"]),
|
||||
f("gender", ["Kön", "Gender"]),
|
||||
f("orientation", ["Läggning", "Orientation"]),
|
||||
f("occupation", ["Yrke", "Occupation"]),
|
||||
area("appearance", ["Utseende", "Appearance"], ["Beskrivning", "Description"]),
|
||||
area("personality", ["Personlighet", "Personality"]),
|
||||
area("interests", ["Intressen", "Interests"]),
|
||||
area("vocabulary", ["Ordförråd (världsspråk och fackspråk)", "Vocabulary (general and technical)"], ["Språk", "Language"]),
|
||||
area("speechHabits", ["Språkvanor (speciellt uttal på ord m.m.)", "Speech habits (special pronunciation etc.)"]),
|
||||
area("slang", ["Slang", "Slang"]),
|
||||
area("overusedWords", ["Överanvända ord", "Overused words"]),
|
||||
area("motivationInternal", ["Intern motivation", "Internal motivation"], ["Drivkrafter", "Drives"]),
|
||||
area("motivationExternal", ["Extern motivation", "External motivation"]),
|
||||
area("traitsPositive", ["Positiva egenskaper", "Positive traits"]),
|
||||
area("traitsNegative", ["Negativa egenskaper", "Negative traits"]),
|
||||
area("fears", ["Rädslor", "Fears"]),
|
||||
area("humor", ["Humor", "Humour"]),
|
||||
area("conflictStyle", ["Hur agerar personen i en konflikt", "How the person acts in a conflict"], ["Värderingar", "Values"]),
|
||||
area("philosophy", ["Livsfilosofi / motto", "Life philosophy / motto"]),
|
||||
area("viewOnLove", ["Syn på kärleksrelationer", "View on romantic relationships"]),
|
||||
area("partnerSeeks", ["Vad letar karaktären efter hos en partner", "What the character looks for in a partner"]),
|
||||
area("background", ["Bakgrund", "Background"], ["Historia", "History"]),
|
||||
NOTES,
|
||||
],
|
||||
PET: [
|
||||
pick("category", ["Djurkategori", "Category"], ["Husdjur", "Gårdsdjur", "Annat"], ["Pet", "Farm animal", "Other"], ["Grunduppgifter", "Basics"]),
|
||||
f("nickname", ["Smeknamn", "Nickname"]),
|
||||
f("species", ["Djurtyp (hund, katt, häst ...)", "Type (dog, cat, horse ...)"]),
|
||||
f("breed", ["Ras", "Breed"]),
|
||||
f("age", ["Ålder", "Age"], "number"),
|
||||
pick("sex", ["Kön", "Sex"], ["Hona", "Hane"], ["Female", "Male"]),
|
||||
f("coat", ["Päls-, hud- eller fjäderfärg", "Fur, skin or feather colour"]),
|
||||
f("weight", ["Vikt", "Weight"]),
|
||||
f("length", ["Längd", "Length"]),
|
||||
f("height", ["Höjd", "Height"]),
|
||||
area("appearance", ["Utseende i detalj", "Appearance in detail"], ["Beskrivning", "Description"]),
|
||||
area("personality", ["Personlighet", "Personality"]),
|
||||
area("background", ["Bakgrund", "Background"]),
|
||||
NOTES,
|
||||
],
|
||||
HOME: [
|
||||
pick("homeType", ["Bostadstyp", "Home type"], ["Hyresrätt", "Bostadsrätt", "Villa"], ["Rental", "Condominium", "House"], ["Grunduppgifter", "Basics"]),
|
||||
f("address", ["Adress", "Address"]),
|
||||
f("rooms", ["Antal rum", "Number of rooms"], "number"),
|
||||
f("livingArea", ["Boarea (m²)", "Living area (m²)"], "number"),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
area("buildingLook", ["Byggnadsutseende", "Building appearance"], ["Byggnaden", "The building"]),
|
||||
area("buildingHistory", ["Byggnadsinformation (historia)", "Building information (history)"]),
|
||||
f("floor", ["Våning", "Floor"], "text", ["Lägenhet och hus", "Apartment and building"]),
|
||||
yes("balcony", ["Balkong", "Balcony"]),
|
||||
f("apartmentCount", ["Antal lägenheter i huset", "Apartments in the building"], "number"),
|
||||
yes("attic", ["Finns vind", "Has attic"]),
|
||||
yes("basement", ["Finns källare", "Has basement"]),
|
||||
f("tenantCount", ["Antal hyresgäster", "Number of tenants"], "number"),
|
||||
f("rentFee", ["Hyra lägenhet", "Rent"], "text", ["Om hyresrätt", "If rental"]),
|
||||
f("parkingRent", ["Hyra parkeringsplats", "Parking rent"]),
|
||||
f("landlord", ["Hyresvärd", "Landlord"]),
|
||||
f("monthlyFee", ["Avgift lägenhet", "Monthly fee"], "text", ["Om bostadsrätt", "If condominium"]),
|
||||
f("parkingFee", ["Avgift parkeringsplats", "Parking fee"]),
|
||||
f("association", ["Bostadsrättsförening", "Housing association"]),
|
||||
f("laundry", ["Tvättstuga (var)", "Laundry room (where)"], "text", ["Gemensamma utrymmen", "Shared facilities"]),
|
||||
f("waste", ["Sophantering", "Waste handling"]),
|
||||
f("bikeStorage", ["Cykelförråd", "Bike storage"]),
|
||||
f("storage", ["Förråd", "Storage"]),
|
||||
f("partyRoom", ["Festlokal (att låna)", "Party room (to borrow)"]),
|
||||
f("guestApartment", ["Övernattningslägenhet (att låna)", "Guest apartment (to borrow)"]),
|
||||
f("sharedGarage", ["Garage", "Garage"]),
|
||||
f("houseCount", ["Antal hus på tomten", "Houses on the plot"], "number", ["Om villa", "If house"]),
|
||||
f("houseFloors", ["Antal våningar", "Number of floors"], "number"),
|
||||
f("plotSize", ["Tomtstorlek", "Plot size"]),
|
||||
yes("hasGarage", ["Finns garage", "Has garage"]),
|
||||
f("garageSpots", ["Antal platser i garage", "Garage spaces"], "number"),
|
||||
f("driveSpots", ["Antal platser på uppfarten", "Driveway spaces"], "number"),
|
||||
yes("patio", ["Finns uteplats/terrass", "Has patio/terrace"]),
|
||||
pick("glazedPatio", ["Är uteplatsen inglasad", "Is the patio glazed"], ["Ja", "Delvis", "Nej"], ["Yes", "Partly", "No"]),
|
||||
yes("pool", ["Finns pool", "Has pool"]),
|
||||
yes("spa", ["Finns spabad", "Has hot tub"]),
|
||||
yes("fireplace", ["Finns eldstad", "Has fireplace"]),
|
||||
yes("forest", ["Angränsar tomten till skogen", "Plot borders forest"]),
|
||||
area("nearby", ["Närliggande (företag, offentliga platser m.m.)", "Nearby (businesses, public places etc.)"], ["Omgivning", "Surroundings"]),
|
||||
NOTES,
|
||||
],
|
||||
PLACE: [
|
||||
pick(
|
||||
"placeType",
|
||||
["Platstyp", "Place type"],
|
||||
["Stad", "Stadsdel", "Park", "Café", "Restaurang", "Skola", "Sjukhus", "Natur", "Annat"],
|
||||
["City", "District", "Park", "Café", "Restaurant", "School", "Hospital", "Nature", "Other"],
|
||||
["Grunduppgifter", "Basics"],
|
||||
),
|
||||
f("address", ["Adress", "Address"]),
|
||||
area("atmosphere", ["Stämning", "Atmosphere"], ["Beskrivning", "Description"]),
|
||||
area("significance", ["Betydelse för berättelsen", "Significance to the story"]),
|
||||
NOTES,
|
||||
],
|
||||
COMPANY: [
|
||||
f("industry", ["Bransch", "Industry"], "text", ["Grunduppgifter", "Basics"]),
|
||||
yes("hasSketches", ["Finns skisser", "Has sketches"]),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
yes("workplaceForCharacters", ["Arbetsplats för karaktärer", "Workplace for characters"], ["Annan information", "Other information"]),
|
||||
yes("socialPlace", ["Plats för karaktärerna att umgås", "Place for the characters to socialise"]),
|
||||
yes("alcohol", ["Alkoholservering (restaurang/hotell)", "Serves alcohol (restaurant/hotel)"]),
|
||||
yes("food", ["Matservering (restaurang/hotell)", "Serves food (restaurant/hotel)"]),
|
||||
yes("bossCares", ["Bryr sig chefen om de anställda", "The boss cares about the employees"]),
|
||||
pick("satisfaction", ["Generell nöjdhet bland de anställda", "General employee satisfaction"], ["Bra", "Dåligt"], ["Good", "Poor"]),
|
||||
f("hotelRooms", ["Antal rum (hotell)", "Number of rooms (hotel)"], "number"),
|
||||
yes("signOutside", ["Skyltat utomhus", "Sign outdoors"]),
|
||||
yes("signWindow", ["Skyltat i fönstret", "Sign in the window"]),
|
||||
yes("outdoorSeating", ["Finns uteservering (restaurang)", "Has outdoor seating (restaurant)"]),
|
||||
area("workEnvironment", ["Arbetsmiljö", "Work environment"], ["Beskrivningar", "Descriptions"]),
|
||||
area("premisesAndSurroundings", ["Lokalen och omgivningen", "The premises and surroundings"]),
|
||||
area("colleagueDynamics", ["Dynamiken bland kollegorna", "Dynamics among colleagues"]),
|
||||
NOTES,
|
||||
],
|
||||
PREMISES: [
|
||||
f("address", ["Adress", "Address"], "text", ["Grunduppgifter", "Basics"]),
|
||||
f("placementId", ["Placerings-ID", "Placement ID"]),
|
||||
f("industryFit", ["Branschanpassning", "Industry adaptation"]),
|
||||
f("rooms", ["Antal rum", "Number of rooms"], "number"),
|
||||
f("area", ["Yta (m²)", "Area (m²)"], "number"),
|
||||
pick("tenure", ["Ägande", "Ownership"], ["Hyr", "Äga"], ["Rent", "Own"]),
|
||||
f("floors", ["Antal våningar", "Number of floors"], "number"),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
f("owner", ["Ägare", "Owner"]),
|
||||
yes("loadingDock", ["Lastkaj", "Loading dock"], ["Faciliteter", "Facilities"]),
|
||||
yes("coldStorage", ["Kyl och frys", "Cold storage"]),
|
||||
yes("elevator", ["Hiss", "Elevator"]),
|
||||
yes("basement", ["Källare", "Basement"]),
|
||||
yes("attic", ["Vind", "Attic"]),
|
||||
area("usage", ["Användningsområde", "Intended use"], ["Beskrivning", "Description"]),
|
||||
area("interior", ["Insidan av lokalen", "Interior"]),
|
||||
area("exterior", ["Utsidan av lokalen", "Exterior"]),
|
||||
NOTES,
|
||||
],
|
||||
EDUCATION: [
|
||||
pick(
|
||||
"educationType",
|
||||
["Utbildningstyp", "Type of education"],
|
||||
["Förskola", "Lågstadium", "Mellanstadium", "Högstadium", "Gymnasium", "Högskola", "Yrkeshögskola", "Komvux"],
|
||||
["Preschool", "Lower primary", "Middle school", "Lower secondary", "Upper secondary", "University", "Vocational college", "Adult education"],
|
||||
["Grunduppgifter", "Basics"],
|
||||
),
|
||||
f("program", ["Linje (gymnasium eller högre)", "Programme (upper secondary or higher)"]),
|
||||
f("class", ["Klass", "Class"]),
|
||||
f("scheduleId", ["Schema-ID", "Schedule ID"]),
|
||||
f("homeroom", ["Hemklassrum", "Homeroom"]),
|
||||
area("classDescription", ["Beskriv klassen (mobbning, kärlek m.m.)", "Describe the class (bullying, romance etc.)"], ["Klassen", "The class"]),
|
||||
pick("ownership", ["Ägande", "Ownership"], ["Kommunal", "Privat"], ["Public", "Private"], ["Om skolan", "About the school"]),
|
||||
f("grades", ["Årskurs", "Grades"]),
|
||||
f("classCount", ["Antal klasser", "Number of classes"], "number"),
|
||||
f("premisesId", ["Lokal-ID", "Premises ID"]),
|
||||
f("companyId", ["Företags-ID (om privat)", "Company ID (if private)"]),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
yes("cafeteria", ["Finns cafeteria", "Has cafeteria"]),
|
||||
yes("youthCentre", ["Finns fritidsgård", "Has youth centre"]),
|
||||
area("computerUse", ["Hur används datorer", "How computers are used"]),
|
||||
area("building", ["Beskriv skolbyggnaden", "Describe the school building"]),
|
||||
NOTES,
|
||||
],
|
||||
SCENARIO: [
|
||||
pick(
|
||||
"scenarioType",
|
||||
["Scenariotyp", "Scenario type"],
|
||||
["Bråk", "Olycka", "Dödsfall", "Otrohet", "Brott", "Övrigt"],
|
||||
["Argument", "Accident", "Death", "Infidelity", "Crime", "Other"],
|
||||
["Grunduppgifter", "Basics"],
|
||||
),
|
||||
f("linkedId", ["Kopplat ID", "Linked ID"]),
|
||||
f("when", ["När (tid i berättelsen)", "When (story time)"]),
|
||||
area("description", ["Beskriv scenariot", "Describe the scenario"], ["Innehåll", "Content"]),
|
||||
area("impactDuring", ["Hur påverkas karaktärerna under scenariot", "How the characters are affected during"]),
|
||||
area("impactAfter", ["Hur påverkas karaktärerna efter scenariot", "How the characters are affected afterwards"]),
|
||||
area("notes", ["Övrig information", "Other information"]),
|
||||
],
|
||||
RELATION: [
|
||||
pick(
|
||||
"category",
|
||||
["Relationstyp", "Relationship type"],
|
||||
["Vännergrupp", "Partner", "Familj", "Kollegor"],
|
||||
["Friend group", "Partner", "Family", "Colleagues"],
|
||||
["Grunduppgifter", "Basics"],
|
||||
),
|
||||
yes("healthy", ["Relationen är hälsosam", "The relationship is healthy"]),
|
||||
pick("active", ["Är relationen aktiv", "Is the relationship active"], ["Ja", "Nej", "Blivande"], ["Yes", "No", "Upcoming"]),
|
||||
area("howItWorks", ["Hur fungerar relationen (känsligt, gammalt bråk)", "How it works (sensitive topics, old quarrels)"], ["Beskrivning", "Description"]),
|
||||
area("background", ["Bakgrund (hur träffades de m.m.)", "Background (how they met etc.)"]),
|
||||
area("speechHabits", ["Språkvanor (speciella ord och uttryck)", "Speech habits (special words and expressions)"]),
|
||||
area("contributions", ["Egenskaper personerna bidrar med", "Qualities the people contribute"]),
|
||||
area("activities", ["Vad brukar göras vid umgänge", "What they usually do together"]),
|
||||
area("whyFailed", ["Varför fungerade inte relationen (om inte aktiv)", "Why it did not work (if not active)"]),
|
||||
area("whyUnhealthy", ["Varför är relationen inte hälsosam", "Why it is not healthy"]),
|
||||
NOTES,
|
||||
],
|
||||
};
|
||||
|
||||
function build(specs: Spec[], locale: Locale): FieldDef[] {
|
||||
const i = locale === "sv" ? 0 : 1;
|
||||
return specs.map((s) => ({
|
||||
key: s.k,
|
||||
label: s.l[i],
|
||||
type: s.t ?? "text",
|
||||
...(s.o ? { options: s.o[i] } : {}),
|
||||
...(s.s ? { section: s.s[i] } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function getDefaultTemplate(kind: TemplateKind, locale: Locale): FieldDef[] {
|
||||
return build(SPECS[kind], locale);
|
||||
}
|
||||
|
||||
// Förslag att ladda i mallredigeraren. Karaktärsmallen finns även i en kort variant.
|
||||
const SHORT_CHARACTER_KEYS = ["nickname", "age", "birthDate", "height", "gender", "orientation", "occupation", "appearance", "personality", "notes"];
|
||||
|
||||
export function getPresets(kind: TemplateKind, locale: Locale): { id: string; fields: FieldDef[] }[] {
|
||||
if (kind !== "CHARACTER") return [];
|
||||
const short = SPECS.CHARACTER.filter((s) => SHORT_CHARACTER_KEYS.includes(s.k)).map((s) =>
|
||||
s.k === "appearance" ? { ...s, s: undefined } : s,
|
||||
);
|
||||
// Första fältet startar alltid avsnittet Grunduppgifter
|
||||
const fields = build(short, locale);
|
||||
return [{ id: "short", fields }];
|
||||
}
|
||||
|
||||
/** Kontrollerar och rensar en mall. Kastar Error med läsbar orsak. */
|
||||
export function validateFields(input: unknown): FieldDef[] {
|
||||
if (!Array.isArray(input)) throw new Error("not an array");
|
||||
if (input.length > 100) throw new Error("max 100 fields");
|
||||
const seen = new Set<string>();
|
||||
return input.map((raw, index) => {
|
||||
if (typeof raw !== "object" || raw === null) throw new Error(`field ${index + 1}`);
|
||||
const r = raw as Record<string, unknown>;
|
||||
const key = String(r.key ?? "").trim();
|
||||
const label = String(r.label ?? "").trim();
|
||||
const type = String(r.type ?? "text") as FieldType;
|
||||
if (!/^[A-Za-z][A-Za-z0-9_]{0,40}$/.test(key)) throw new Error(`key “${key}”`);
|
||||
if (seen.has(key)) throw new Error(`duplicate key “${key}”`);
|
||||
seen.add(key);
|
||||
if (!label) throw new Error(`label (${key})`);
|
||||
if (!FIELD_TYPES.includes(type)) throw new Error(`type (${key})`);
|
||||
const field: FieldDef = { key, label: label.slice(0, 160), type };
|
||||
if (type === "select") {
|
||||
const options = Array.isArray(r.options) ? r.options.map((o) => String(o).trim()).filter(Boolean) : [];
|
||||
field.options = options.slice(0, 50);
|
||||
}
|
||||
const section = typeof r.section === "string" ? r.section.trim() : "";
|
||||
if (section) field.section = section.slice(0, 120);
|
||||
return field;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTemplate(
|
||||
bookId: string,
|
||||
kind: TemplateKind,
|
||||
locale: Locale,
|
||||
): Promise<{ fields: FieldDef[]; custom: boolean }> {
|
||||
const row = await prisma.template.findUnique({ where: { bookId_kind: { bookId, kind } } });
|
||||
if (row) {
|
||||
try {
|
||||
return { fields: validateFields(row.fields), custom: true };
|
||||
} catch {
|
||||
// trasig mall i databasen: fall tillbaka på standard
|
||||
}
|
||||
}
|
||||
return { fields: getDefaultTemplate(kind, locale), custom: false };
|
||||
}
|
||||
|
||||
export function formatFieldValue(field: FieldDef, value: unknown): string {
|
||||
if (value === null || value === undefined || value === "") return "";
|
||||
if (field.type === "checkbox") return value ? "✓" : "";
|
||||
return String(value);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import NextAuth from "next-auth";
|
||||
import authConfig from "./auth.config";
|
||||
|
||||
export const { auth: middleware } = NextAuth(authConfig);
|
||||
|
||||
export const config = {
|
||||
// Allt kräver inloggning utom Auth.js egna routes, hälsokontrollen och statiska filer.
|
||||
matcher: ["/((?!api/auth|api/health|_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
Reference in new issue
Block a user