import { asc } from 'drizzle-orm'; import { db } from './db'; import { pages } from './db/schema'; export type TreeRow = { id: number; parentId: number | null; title: string; slug: string; icon: string; color: string; published: boolean; depth: number; first: boolean; last: boolean; }; /** Alle Seiten als eingerückte, sortierte Liste (Baum in Lesereihenfolge). */ export function pageTree(): TreeRow[] { const all = db.select().from(pages).orderBy(asc(pages.sortOrder), asc(pages.title)).all(); const byParent = new Map(); for (const p of all) { const key = p.parentId && all.some((x) => x.id === p.parentId) ? p.parentId : null; byParent.set(key, [...(byParent.get(key) ?? []), p]); } const out: TreeRow[] = []; const walk = (parent: number | null, depth: number) => { const kids = byParent.get(parent) ?? []; kids.forEach((p, i) => { out.push({ id: p.id, parentId: p.parentId, title: p.title, slug: p.slug, icon: p.icon, color: p.color, published: p.published, depth, first: i === 0, last: i === kids.length - 1 }); if (depth < 12) walk(p.id, depth + 1); }); }; walk(null, 0); return out; } /** IDs einer Seite und aller Unterseiten (damit man nichts in sich selbst verschiebt). */ export function descendantsOf(id: number): Set { const tree = pageTree(); const result = new Set([id]); let changed = true; while (changed) { changed = false; for (const r of tree) { if (r.parentId && result.has(r.parentId) && !result.has(r.id)) { result.add(r.id); changed = true; } } } return result; }