diff --git a/README.md b/README.md index 22855b3..f8ac078 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,12 @@ Under **Mallar** kan du ändra fält, ordning, rubriker och fälttyper (text, te ] ``` +### Kopplingar till andra poster + +Fälttypen **Koppling till post** pekar direkt på en annan post, till exempel *Lokal* i en företagsmall. Du väljer den i mallredigeraren och anger vilken posttyp som får väljas (eller alla). I formuläret blir fältet en rullista med posterna och deras ID, och på postens sida visas länken. På den kopplade posten visas var den används, till exempel vilka företag och skolor som använder en lokal (*Används av*). Till skillnad från en relation är det ett fält i mallen, med en tydlig roll som *Lokal*, *Skiss* eller *Ägare*. + +Standardmallarna använder det för Lokal och Skiss i Företag, Lokal, Bostad och Utbildning, Företag i Utbildning, Ägare och Referens i Fordon och Kopplat till i Scenario. I JSON ser ett sådant fält ut så här: `{ "key": "premises", "label": "Lokal", "type": "reference", "refKind": "PREMISES" }` (utan `refKind` kan alla typer väljas). + Ändrar du en mall försvinner ingen data: värden för borttagna fält finns kvar i databasen. ## Automatiska ID diff --git a/src/actions/entities.ts b/src/actions/entities.ts index 71eb584..8886441 100644 --- a/src/actions/entities.ts +++ b/src/actions/entities.ts @@ -5,6 +5,7 @@ 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 { collectFieldData } from "@/lib/field-values"; import { KIND_INFO, parseKind } from "@/lib/kinds"; import { nextEntityCode } from "@/lib/ids"; import { requireBook, requireEntity } from "@/lib/session"; @@ -22,23 +23,7 @@ export async function saveEntity(formData: FormData) { if (!name) throw new Error("Name is required"); const { fields } = await getTemplate(book.id, kind, await getLocale()); - const data: Record = { ...((existing?.data as Record | 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 data = await collectFieldData(book.id, fields, formData, (existing?.data as Record | null) ?? null); let imageFile = existing?.imageFile ?? null; const upload = formData.get("image"); diff --git a/src/actions/relations.ts b/src/actions/relations.ts index 9eaf9d6..663d905 100644 --- a/src/actions/relations.ts +++ b/src/actions/relations.ts @@ -4,6 +4,7 @@ import type { Prisma } from "@prisma/client"; import { redirect } from "next/navigation"; import { prisma } from "@/lib/db"; import { optStr, revalidateBook, str } from "@/lib/form"; +import { collectFieldData } from "@/lib/field-values"; import { nextRelationCode } from "@/lib/ids"; import { requireBook } from "@/lib/session"; import { getTemplate } from "@/lib/templates"; @@ -53,23 +54,7 @@ export async function saveRelation(formData: FormData) { if (!type) return; const { fields } = await getTemplate(book.id, "RELATION", await getLocale()); - const data: Record = { ...((relation.data as Record | 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 data = await collectFieldData(book.id, fields, formData, (relation.data as Record | null) ?? null); const memberIds = await cleanMemberIds(book.id, formData, [relation.fromId, relation.toId]); await prisma.$transaction([ diff --git a/src/app/books/[bookId]/e/[kind]/new/page.tsx b/src/app/books/[bookId]/e/[kind]/new/page.tsx index a29cfce..e92c315 100644 --- a/src/app/books/[bookId]/e/[kind]/new/page.tsx +++ b/src/app/books/[bookId]/e/[kind]/new/page.tsx @@ -3,6 +3,7 @@ import { saveEntity } from "@/actions/entities"; import { EntityForm } from "@/components/entity-form"; import { PageBody, PageHeader } from "@/components/page"; import { getT } from "@/i18n/server"; +import { prisma } from "@/lib/db"; import { KIND_BY_SLUG } from "@/lib/kinds"; import { requireBook } from "@/lib/session"; import { getTemplate } from "@/lib/templates"; @@ -21,6 +22,11 @@ export default async function NewEntityPage({ if (!info) notFound(); const { t, locale } = await getT(); const { fields } = await getTemplate(bookId, info.kind, locale); + const refEntities = await prisma.entity.findMany({ + where: { bookId }, + select: { id: true, name: true, kind: true, code: true }, + orderBy: { name: "asc" }, + }); return ( <> @@ -31,6 +37,7 @@ export default async function NewEntityPage({ bookId={bookId} kind={info.kind} fields={fields} + refEntities={refEntities} defaultName={name?.slice(0, 200)} cancelHref={`/books/${bookId}/e/${slug}`} t={t} diff --git a/src/app/books/[bookId]/entity/[entityId]/edit/page.tsx b/src/app/books/[bookId]/entity/[entityId]/edit/page.tsx index 1f2d277..d556951 100644 --- a/src/app/books/[bookId]/entity/[entityId]/edit/page.tsx +++ b/src/app/books/[bookId]/entity/[entityId]/edit/page.tsx @@ -2,6 +2,7 @@ import { saveEntity } from "@/actions/entities"; import { EntityForm } from "@/components/entity-form"; import { PageBody, PageHeader } from "@/components/page"; import { getT } from "@/i18n/server"; +import { prisma } from "@/lib/db"; import { requireEntity } from "@/lib/session"; import { getTemplate } from "@/lib/templates"; @@ -10,6 +11,11 @@ export default async function EditEntityPage({ params }: { params: Promise<{ boo const entity = await requireEntity(bookId, entityId); const { t, locale } = await getT(); const { fields } = await getTemplate(bookId, entity.kind, locale); + const refEntities = await prisma.entity.findMany({ + where: { bookId }, + select: { id: true, name: true, kind: true, code: true }, + orderBy: { name: "asc" }, + }); return ( <> @@ -21,6 +27,7 @@ export default async function EditEntityPage({ params }: { params: Promise<{ boo kind={entity.kind} entity={entity} fields={fields} + refEntities={refEntities} cancelHref={`/books/${bookId}/entity/${entity.id}`} t={t} /> diff --git a/src/app/books/[bookId]/entity/[entityId]/page.tsx b/src/app/books/[bookId]/entity/[entityId]/page.tsx index 1a1f26f..43033d8 100644 --- a/src/app/books/[bookId]/entity/[entityId]/page.tsx +++ b/src/app/books/[bookId]/entity/[entityId]/page.tsx @@ -13,9 +13,10 @@ 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 }[] }; +type RefTarget = { id: string; name: string; code: string | null }; +type Group = { section?: string; items: { field: FieldDef; value: string; target?: RefTarget }[] }; -function groupFields(fields: FieldDef[], data: Record): Group[] { +function groupFields(fields: FieldDef[], data: Record, byId: Map): Group[] { const groups: Group[] = []; let current: Group = { items: [] }; for (const field of fields) { @@ -23,6 +24,11 @@ function groupFields(fields: FieldDef[], data: Record): Group[] if (current.items.length > 0) groups.push(current); current = { section: field.section, items: [] }; } + if (field.type === "reference") { + const target = typeof data[field.key] === "string" ? byId.get(data[field.key] as string) : undefined; + if (target) current.items.push({ field, value: target.name, target }); + continue; + } const value = formatFieldValue(field, data[field.key]); if (value) current.items.push({ field, value }); } @@ -35,7 +41,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: const base = await requireEntity(bookId, entityId); const { t, locale } = await getT(); - const [entity, template, allEntities, maps] = await Promise.all([ + const [entity, template, bookEntities, maps] = await Promise.all([ prisma.entity.findUniqueOrThrow({ where: { id: base.id }, include: { @@ -52,7 +58,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: getTemplate(bookId, base.kind, locale), prisma.entity.findMany({ where: { bookId }, - select: { id: true, name: true, kind: true }, + select: { id: true, name: true, kind: true, code: true, data: true }, orderBy: { name: "asc" }, }), prisma.bookMap.findMany({ where: { bookId }, orderBy: { name: "asc" } }), @@ -61,7 +67,27 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: 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); + const allEntities = bookEntities.map(({ data: _data, ...rest }) => rest); + const groups = groupFields( + template.fields, + (entity.data ?? {}) as Record, + new Map(allEntities.map((e) => [e.id, e])), + ); + + // Poster som pekar hit via ett kopplingsfält i sin mall, t.ex. företag som använder den här lokalen + const referencing = bookEntities.filter( + (e) => e.id !== entity.id && Object.values((e.data ?? {}) as Record).some((v) => v === entity.id), + ); + const referencingTemplates = new Map( + await Promise.all( + [...new Set(referencing.map((e) => e.kind))].map(async (kind) => [kind, (await getTemplate(bookId, kind, locale)).fields] as const), + ), + ); + const backlinks = referencing.map((e) => { + const data = (e.data ?? {}) as Record; + const field = (referencingTemplates.get(e.kind) ?? []).find((f) => f.type === "reference" && data[f.key] === entity.id); + return { entity: e, label: field?.label ?? null }; + }); const isWorkplace = WORKPLACE_KINDS.includes(entity.kind); type Person = { id: string; name: string }; type RelationItem = { @@ -176,11 +202,16 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
0 ? "mt-4" : ""}> {group.section ?

{group.section}

: null}
- {group.items.map(({ field, value }) => ( + {group.items.map(({ field, value, target }) => (
{field.label}
- {field.type === "url" ? ( + {target ? ( + + {target.code ? {target.code} : null} + {target.name} + + ) : field.type === "url" ? ( {value} @@ -196,6 +227,23 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: )}
+ {backlinks.length > 0 ? ( +
+
+

{t("entity.referencedBy")}

+
+
+ {backlinks.map(({ entity: e, label }) => ( + + {e.code ? {e.code} : null} + {e.name} + {t(`kind.${e.kind}.one`)} + {label ? {label} : null} + + ))} +
+
+ ) : null}
diff --git a/src/app/books/[bookId]/relations/[relationId]/page.tsx b/src/app/books/[bookId]/relations/[relationId]/page.tsx index 0df8f7c..6d585f8 100644 --- a/src/app/books/[bookId]/relations/[relationId]/page.tsx +++ b/src/app/books/[bookId]/relations/[relationId]/page.tsx @@ -34,6 +34,11 @@ export default async function RelationPage({ select: { id: true, name: true, kind: true }, orderBy: { name: "asc" }, }); + const refEntities = await prisma.entity.findMany({ + where: { bookId }, + select: { id: true, name: true, kind: true, code: true }, + orderBy: { name: "asc" }, + }); const memberEntities = relation.members.map((m) => m.entity); const isGroup = memberEntities.length > 0; const { fields } = await getTemplate(bookId, "RELATION", locale); @@ -139,7 +144,7 @@ export default async function RelationPage({ ) : null}
{field.type !== "checkbox" ? : null} - +
))} diff --git a/src/components/entity-form.tsx b/src/components/entity-form.tsx index 38bf5ce..9cd4d00 100644 --- a/src/components/entity-form.tsx +++ b/src/components/entity-form.tsx @@ -4,9 +4,23 @@ import type { Entity, EntityKind } from "@prisma/client"; import type { TFunction } from "@/i18n/core"; import { NameFill } from "./name-fill"; import { fileUrl } from "@/lib/files"; +import { KINDS } from "@/lib/kinds"; import type { FieldDef } from "@/lib/templates"; -export function FieldInput({ field, value }: { field: FieldDef; value: unknown }) { +export type RefOption = { id: string; name: string; kind: EntityKind; code: string | null }; + +const refLabel = (e: RefOption) => (e.code ? `${e.code} · ${e.name}` : e.name); + +export function FieldInput({ + field, + value, + refs, +}: { + field: FieldDef; + value: unknown; + // Poster som kan väljas i fält av typen reference + refs?: { entities: RefOption[]; t: TFunction }; +}) { const name = `f_${field.key}`; const text = value === null || value === undefined ? "" : String(value); @@ -26,6 +40,34 @@ export function FieldInput({ field, value }: { field: FieldDef; value: unknown } {field.label} ); + case "reference": { + const candidates = (refs?.entities ?? []).filter((e) => !field.refKind || e.kind === field.refKind); + const selected = typeof value === "string" ? value : ""; + return ( + + ); + } case "select": { const options = field.options ?? []; const extra = text && !options.includes(text) ? [text] : []; @@ -53,6 +95,7 @@ export function EntityForm({ fields, cancelHref, defaultName, + refEntities, t, }: { action: (formData: FormData) => Promise; @@ -62,6 +105,7 @@ export function EntityForm({ fields: FieldDef[]; cancelHref: string; defaultName?: string; + refEntities: RefOption[]; t: TFunction; }) { const data = (entity?.data ?? {}) as Record; @@ -139,7 +183,11 @@ export function EntityForm({ ) : null}
{field.type !== "checkbox" ? : null} - + e.id !== entity?.id), t }} + />
))} diff --git a/src/components/template-editor.tsx b/src/components/template-editor.tsx index 2c6d881..0a6a78a 100644 --- a/src/components/template-editor.tsx +++ b/src/components/template-editor.tsx @@ -6,6 +6,7 @@ import type { TemplateKind } from "@/lib/kinds"; import { resetTemplate, saveTemplate } from "@/actions/templates"; import { ConfirmSubmit } from "@/components/confirm-submit"; import { useT } from "@/i18n/client"; +import { KINDS, parseKind } from "@/lib/kinds"; import { FIELD_TYPES, type FieldDef, type FieldType } from "@/lib/templates"; type Row = FieldDef & { optionsText: string; rowId: number }; @@ -54,6 +55,7 @@ export function TemplateEditor({ .map((o) => o.trim()) .filter(Boolean); } + if (f.type === "reference" && f.refKind) field.refKind = f.refKind; if (f.section) field.section = f.section; return field; }); @@ -83,6 +85,7 @@ export function TemplateEditor({ label: String(f.label ?? ""), type: FIELD_TYPES.includes(f.type) ? f.type : "text", section: f.section, + refKind: parseKind(f.refKind) ?? undefined, optionsText: Array.isArray(f.options) ? f.options.join(", ") : "", rowId: id++, })), @@ -149,9 +152,24 @@ export function TemplateEditor({
- + {row.type === "select" ? ( update(row.rowId, { optionsText: e.target.value })} /> + ) : row.type === "reference" ? ( + ) : ( update(row.rowId, { section: e.target.value })} /> )} @@ -174,7 +192,7 @@ export function TemplateEditor({
- {row.type === "select" ? ( + {row.type === "select" || row.type === "reference" ? (
update(row.rowId, { section: e.target.value })} /> diff --git a/src/i18n/en.ts b/src/i18n/en.ts index b73a5d4..73ef045 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -304,6 +304,10 @@ export const en: Record = { "template.type.select": "Choice", "template.type.checkbox": "Checkbox", "template.type.url": "Link", + "template.type.reference": "Link to item", + "template.refKind": "Points to type", + "template.refKind.any": "All types", + "entity.referencedBy": "Used by", "template.empty": "The template has no fields yet.", "settings.title": "Book settings", diff --git a/src/i18n/sv.ts b/src/i18n/sv.ts index ce97ad0..bc370dd 100644 --- a/src/i18n/sv.ts +++ b/src/i18n/sv.ts @@ -302,6 +302,10 @@ export const sv = { "template.type.select": "Val", "template.type.checkbox": "Kryssruta", "template.type.url": "Länk", + "template.type.reference": "Koppling till post", + "template.refKind": "Pekar på typ", + "template.refKind.any": "Alla typer", + "entity.referencedBy": "Används av", "template.empty": "Mallen har inga fält ännu.", "settings.title": "Bokinställningar", diff --git a/src/lib/field-values.ts b/src/lib/field-values.ts new file mode 100644 index 0000000..7223d0a --- /dev/null +++ b/src/lib/field-values.ts @@ -0,0 +1,46 @@ +import { prisma } from "./db"; +import { str } from "./form"; +import type { FieldDef } from "./templates"; + +/** + * Läser mallfälten (f_) ur ett formulär och lägger dem ovanpå befintlig data. + * Data för fält som inte finns i mallen lämnas orörd. Kopplingar till poster kontrolleras: + * posten måste finnas i boken och vara av rätt typ, annars sparas ingen koppling. + */ +export async function collectFieldData( + bookId: string, + fields: FieldDef[], + formData: FormData, + existing: Record | null, +): Promise> { + const data: Record = { ...(existing ?? {}) }; + + 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 refFields = fields.filter((f) => f.type === "reference" && typeof data[f.key] === "string"); + if (refFields.length > 0) { + const ids = [...new Set(refFields.map((f) => data[f.key] as string))]; + const found = await prisma.entity.findMany({ where: { bookId, id: { in: ids } }, select: { id: true, kind: true } }); + const kindOf = new Map(found.map((e) => [e.id, e.kind])); + for (const field of refFields) { + const kind = kindOf.get(data[field.key] as string); + if (!kind || (field.refKind && kind !== field.refKind)) delete data[field.key]; + } + } + return data; +} diff --git a/src/lib/templates.ts b/src/lib/templates.ts index 62280c7..ade2412 100644 --- a/src/lib/templates.ts +++ b/src/lib/templates.ts @@ -1,24 +1,29 @@ import { prisma } from "./db"; +import type { EntityKind } from "@prisma/client"; import type { Locale } from "@/i18n/core"; -import type { TemplateKind } from "./kinds"; +import { parseKind, type TemplateKind } from "./kinds"; -export type FieldType = "text" | "textarea" | "number" | "date" | "select" | "checkbox" | "url"; +// reference = koppling till en annan post (t.ex. en lokal). Värdet är postens id. +export type FieldType = "text" | "textarea" | "number" | "date" | "select" | "checkbox" | "url" | "reference"; -export const FIELD_TYPES: FieldType[] = ["text", "textarea", "number", "date", "select", "checkbox", "url"]; +export const FIELD_TYPES: FieldType[] = ["text", "textarea", "number", "date", "select", "checkbox", "url", "reference"]; export type FieldDef = { key: string; label: string; type: FieldType; options?: string[]; + // För reference: vilken typ av post som kan väljas. Saknas den kan alla typer väljas. + refKind?: EntityKind; // 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 }; +type Spec = { k: string; l: L; t?: FieldType; o?: [string[], string[]]; s?: L; r?: EntityKind }; const f = (k: string, l: L, t: FieldType = "text", s?: L, o?: [string[], string[]]): Spec => ({ k, l, t, s, o }); +const ref = (k: string, l: L, r?: EntityKind, s?: L): Spec => ({ ...f(k, l, "reference", s), r }); 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]); @@ -77,7 +82,7 @@ const SPECS: Record = { 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"]), + ref("sketch", ["Skiss", "Sketch"], "SKETCH"), 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"]), @@ -129,8 +134,9 @@ const SPECS: Record = { ], COMPANY: [ f("industry", ["Bransch", "Industry"], "text", ["Grunduppgifter", "Basics"]), + ref("premises", ["Lokal", "Premises"], "PREMISES"), yes("hasSketches", ["Finns skisser", "Has sketches"]), - f("sketchId", ["Skiss-ID", "Sketch ID"]), + ref("sketch", ["Skiss", "Sketch"], "SKETCH"), 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)"]), @@ -154,7 +160,7 @@ const SPECS: Record = { 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"]), + ref("sketch", ["Skiss", "Sketch"], "SKETCH"), f("owner", ["Ägare", "Owner"]), yes("loadingDock", ["Lastkaj", "Loading dock"], ["Faciliteter", "Facilities"]), yes("coldStorage", ["Kyl och frys", "Cold storage"]), @@ -182,9 +188,9 @@ const SPECS: Record = { 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"]), + ref("premises", ["Lokal", "Premises"], "PREMISES"), + ref("company", ["Företag (om privat)", "Company (if private)"], "COMPANY"), + ref("sketch", ["Skiss", "Sketch"], "SKETCH"), yes("cafeteria", ["Finns cafeteria", "Has cafeteria"]), yes("youthCentre", ["Finns fritidsgård", "Has youth centre"]), area("computerUse", ["Hur används datorer", "How computers are used"]), @@ -199,7 +205,7 @@ const SPECS: Record = { ["Argument", "Accident", "Death", "Infidelity", "Crime", "Other"], ["Grunduppgifter", "Basics"], ), - f("linkedId", ["Kopplat ID", "Linked ID"]), + ref("linkedEntity", ["Kopplat till (post)", "Linked to (item)"]), 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"]), @@ -208,6 +214,8 @@ const SPECS: Record = { ], VEHICLE: [ f("model", ["Märke och modell", "Make and model"], "text", ["Grunduppgifter", "Basics"]), + ref("owner", ["Ägare", "Owner"], "CHARACTER"), + ref("reference", ["Referens", "Reference"], "REFERENCE"), pick("fuel", ["Drivmedel", "Fuel"], ["Bensin", "Diesel", "El"], ["Petrol", "Diesel", "Electric"]), area("description", ["Beskrivning", "Description"]), NOTES, @@ -258,6 +266,7 @@ function build(specs: Spec[], locale: Locale): FieldDef[] { label: s.l[i], type: s.t ?? "text", ...(s.o ? { options: s.o[i] } : {}), + ...(s.r ? { refKind: s.r } : {}), ...(s.s ? { section: s.s[i] } : {}), })); } @@ -300,6 +309,11 @@ export function validateFields(input: unknown): FieldDef[] { const options = Array.isArray(r.options) ? r.options.map((o) => String(o).trim()).filter(Boolean) : []; field.options = options.slice(0, 50); } + if (type === "reference" && r.refKind) { + const refKind = parseKind(r.refKind); + if (!refKind) throw new Error(`refKind (${key})`); + field.refKind = refKind; + } const section = typeof r.section === "string" ? r.section.trim() : ""; if (section) field.section = section.slice(0, 120); return field; @@ -325,5 +339,6 @@ export async function getTemplate( export function formatFieldValue(field: FieldDef, value: unknown): string { if (value === null || value === undefined || value === "") return ""; if (field.type === "checkbox") return value ? "✓" : ""; + if (field.type === "reference") return ""; // visas som länk, se postsidan return String(value); }