Refactor comments and structure in Script.js

Refactor comments and improve code readability.
This commit is contained in:
Anaru 2025-11-24 18:13:58 +01:00 committed by GitHub
parent be192fa01d
commit f88286c720
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,12 +3,12 @@ import { getAuth, onAuthStateChanged, signOut } from "https://www.gstatic.com/fi
import { getFirestore, collection, addDoc, updateDoc, doc, onSnapshot, query } from "https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore.js"; import { getFirestore, collection, addDoc, updateDoc, doc, onSnapshot, query } from "https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore.js";
import { firebaseConfig } from "./config.js"; import { firebaseConfig } from "./config.js";
// Start // --- INIT ---
const app = initializeApp(firebaseConfig); const app = initializeApp(firebaseConfig);
const auth = getAuth(app); const auth = getAuth(app);
const db = getFirestore(app); const db = getFirestore(app);
// Variabler // --- VARIABLER ---
let currentUser = null; let currentUser = null;
let people = []; let people = [];
let focusPersonId = null; let focusPersonId = null;
@ -16,17 +16,19 @@ let currentScale = 1.0;
let modalAction = null; let modalAction = null;
let modalMode = 'new'; let modalMode = 'new';
// --- SIKKERHETSSJEKK --- // --- SIKKERHETSSJEKK (Kjøres med en gang) ---
onAuthStateChanged(auth, (user) => { onAuthStateChanged(auth, (user) => {
if (user) { if (user) {
// Bruker er logget inn
currentUser = user; currentUser = user;
startDataListener(); startDataListener();
} else { } else {
// Hvis man ikke er logget inn, send tilbake til start // Ingen bruker -> Kast tilbake til logg inn
window.location.href = "index.html"; window.location.href = "index.html";
} }
}); });
// Logg ut knapp
const logoutBtn = document.getElementById('btn-logout'); const logoutBtn = document.getElementById('btn-logout');
if (logoutBtn) { if (logoutBtn) {
logoutBtn.addEventListener('click', () => { logoutBtn.addEventListener('click', () => {
@ -36,13 +38,17 @@ if (logoutBtn) {
}); });
} }
// --- DATA --- // --- DATABASE LYTTER ---
function startDataListener() { function startDataListener() {
// Henter alle familiemedlemmer i sanntid
const q = query(collection(db, 'familyMembers')); const q = query(collection(db, 'familyMembers'));
onSnapshot(q, (snapshot) => { onSnapshot(q, (snapshot) => {
people = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); people = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// Hvis vi ikke har valgt en person å fokusere på ennå:
if (!focusPersonId && people.length > 0) { if (!focusPersonId && people.length > 0) {
// Prøv å finne "Eivind" eller "Meg" som startperson
const me = people.find(p => p.name && (p.name.toLowerCase().includes('eivind') || p.name.toLowerCase() === 'meg')); const me = people.find(p => p.name && (p.name.toLowerCase().includes('eivind') || p.name.toLowerCase() === 'meg'));
focusPersonId = me ? me.id : people[0].id; focusPersonId = me ? me.id : people[0].id;
} }
@ -50,19 +56,21 @@ function startDataListener() {
}); });
} }
// --- RENDERING --- // --- TEGNE TREET (RENDERING) ---
function renderTree() { function renderTree() {
const rowParents = document.getElementById('row-parents'); const rowParents = document.getElementById('row-parents');
const rowFocus = document.getElementById('row-focus'); const rowFocus = document.getElementById('row-focus');
const rowChildren = document.getElementById('row-children'); const rowChildren = document.getElementById('row-children');
// Sjekk at elementene finnes før vi prøver å bruke dem
if(!rowParents || !rowFocus || !rowChildren) return; if(!rowParents || !rowFocus || !rowChildren) return;
// Tøm // Tøm alt innhold først
rowParents.innerHTML = ''; rowParents.innerHTML = '';
rowFocus.innerHTML = ''; rowFocus.innerHTML = '';
rowChildren.innerHTML = ''; rowChildren.innerHTML = '';
// Hvis databasen er tom
if (people.length === 0) { if (people.length === 0) {
rowFocus.innerHTML = `<button class="btn-primary" onclick="window.openModal('create-first')">Start familietreet</button>`; rowFocus.innerHTML = `<button class="btn-primary" onclick="window.openModal('create-first')">Start familietreet</button>`;
return; return;
@ -71,29 +79,29 @@ function renderTree() {
const focusPerson = people.find(p => p.id === focusPersonId); const focusPerson = people.find(p => p.id === focusPersonId);
if (!focusPerson) return; if (!focusPerson) return;
// A. Foreldre // A. Foreldre (Over)
const father = people.find(p => p.id === focusPerson.fatherId); const father = people.find(p => p.id === focusPerson.fatherId);
const mother = people.find(p => p.id === focusPerson.motherId); const mother = people.find(p => p.id === focusPerson.motherId);
rowParents.appendChild(createSlot(father, 'Far', 'add-parent-m')); rowParents.appendChild(createSlot(father, 'Far', 'add-parent-m'));
rowParents.appendChild(createSlot(mother, 'Mor', 'add-parent-f')); rowParents.appendChild(createSlot(mother, 'Mor', 'add-parent-f'));
// B. Partner // B. Partner (Ved siden av)
const partner = people.find(p => p.id === focusPerson.partnerId); const partner = people.find(p => p.id === focusPerson.partnerId);
if (partner) { if (partner) {
const pCard = createCard(partner); const pCard = createCard(partner);
pCard.onclick = () => { focusPersonId = partner.id; renderTree(); }; pCard.onclick = () => { focusPersonId = partner.id; renderTree(); };
rowFocus.appendChild(pCard); rowFocus.appendChild(pCard);
// Hjerte // Hjerte mellom dem
const heart = document.createElement('div'); const heart = document.createElement('div');
heart.innerHTML = '<i class="ph-fill ph-heart" style="color:var(--female-color); font-size:1.5rem;"></i>'; heart.innerHTML = '<i class="ph-fill ph-heart" style="color:var(--female-color); font-size:1.5rem;"></i>';
rowFocus.appendChild(heart); rowFocus.appendChild(heart);
} }
// C. Fokus Person // C. Fokus Person (Midten)
rowFocus.appendChild(createCard(focusPerson, true)); rowFocus.appendChild(createCard(focusPerson, true));
// D. Barn // D. Barn (Under)
const children = people.filter(p => p.fatherId === focusPersonId || p.motherId === focusPersonId); const children = people.filter(p => p.fatherId === focusPersonId || p.motherId === focusPersonId);
children.forEach(child => { children.forEach(child => {
const cCard = createCard(child); const cCard = createCard(child);
@ -102,7 +110,7 @@ function renderTree() {
}); });
} }
// Hjelper: Lag Kort // --- HJELPER: LAG KORT ---
function createCard(person, isFocus = false) { function createCard(person, isFocus = false) {
const el = document.createElement('div'); const el = document.createElement('div');
el.className = `card ${isFocus ? 'focus' : ''} ${person.gender === 'F' ? 'female' : 'male'}`; el.className = `card ${isFocus ? 'focus' : ''} ${person.gender === 'F' ? 'female' : 'male'}`;
@ -117,16 +125,19 @@ function createCard(person, isFocus = false) {
${person.description ? '<span class="info-badge">Info</span>' : ''} ${person.description ? '<span class="info-badge">Info</span>' : ''}
`; `;
// Hvis dette er hovedkortet, legg til små pluss-knapper
if (isFocus) { if (isFocus) {
const actions = document.createElement('div'); const actions = document.createElement('div');
actions.className = 'focus-actions'; actions.className = 'focus-actions';
// Legg til barn (knapp nede)
const btnChild = document.createElement('button'); const btnChild = document.createElement('button');
btnChild.className = 'btn-mini-add add-child'; btnChild.className = 'btn-mini-add add-child';
btnChild.innerHTML = '<i class="ph-bold ph-plus"></i>'; btnChild.innerHTML = '<i class="ph-bold ph-plus"></i>';
btnChild.onclick = (e) => { e.stopPropagation(); window.openModal('add-child'); }; btnChild.onclick = (e) => { e.stopPropagation(); window.openModal('add-child'); };
actions.appendChild(btnChild); actions.appendChild(btnChild);
// Legg til partner (knapp til høyre) hvis mangler
if (!person.partnerId) { if (!person.partnerId) {
const btnPartner = document.createElement('button'); const btnPartner = document.createElement('button');
btnPartner.className = 'btn-mini-add add-partner'; btnPartner.className = 'btn-mini-add add-partner';
@ -139,6 +150,7 @@ function createCard(person, isFocus = false) {
return el; return el;
} }
// --- HJELPER: LAG SLOT (Tom plass eller kort) ---
function createSlot(person, label, actionType) { function createSlot(person, label, actionType) {
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.className = 'slot-container'; wrapper.className = 'slot-container';
@ -158,22 +170,34 @@ function createSlot(person, label, actionType) {
return wrapper; return wrapper;
} }
// --- MODAL & LAGRING --- // --- MODAL & LAGRING (Popups) ---
// Gjør funksjonen tilgjengelig i HTML (window.openModal)
window.openModal = (action) => { window.openModal = (action) => {
modalAction = action; modalAction = action;
const overlay = document.getElementById('modal-overlay'); const overlay = document.getElementById('modal-overlay');
if(overlay) overlay.classList.remove('hidden'); if(overlay) overlay.classList.remove('hidden');
// Nullstill skjema
const inpName = document.getElementById('inp-name'); const inpName = document.getElementById('inp-name');
if(inpName) inpName.value = ''; if(inpName) inpName.value = '';
document.getElementById('inp-birth').value = '';
document.getElementById('inp-death').value = ''; const inpBirth = document.getElementById('inp-birth');
document.getElementById('inp-desc').value = ''; if(inpBirth) inpBirth.value = '';
document.getElementById('selected-existing-id').value = '';
const inpDeath = document.getElementById('inp-death');
if(inpDeath) inpDeath.value = '';
const inpDesc = document.getElementById('inp-desc');
if(inpDesc) inpDesc.value = '';
const selExist = document.getElementById('selected-existing-id');
if(selExist) selExist.value = '';
const title = document.getElementById('modal-title'); const title = document.getElementById('modal-title');
const genderRadios = document.getElementsByName('gender'); const genderRadios = document.getElementsByName('gender');
// Hjelper for å sette kjønn
const setGender = (val, disabled) => { const setGender = (val, disabled) => {
genderRadios.forEach(r => { genderRadios.forEach(r => {
r.disabled = disabled; r.disabled = disabled;
@ -181,6 +205,7 @@ window.openModal = (action) => {
}); });
}; };
// Tilpass tittel og kjønn basert på hva vi legger til
if (action === 'add-parent-m') { title.textContent = "Legg til Far"; setGender('M', true); } if (action === 'add-parent-m') { title.textContent = "Legg til Far"; setGender('M', true); }
else if (action === 'add-parent-f') { title.textContent = "Legg til Mor"; setGender('F', true); } else if (action === 'add-parent-f') { title.textContent = "Legg til Mor"; setGender('F', true); }
else if (action === 'add-child') { title.textContent = "Legg til Barn"; setGender(null, false); } else if (action === 'add-child') { title.textContent = "Legg til Barn"; setGender(null, false); }
@ -191,9 +216,11 @@ window.openModal = (action) => {
renderExistingList(); renderExistingList();
}; };
// Lukk modal knapp
const closeBtn = document.getElementById('btn-close-modal'); const closeBtn = document.getElementById('btn-close-modal');
if(closeBtn) closeBtn.onclick = () => document.getElementById('modal-overlay').classList.add('hidden'); if(closeBtn) closeBtn.onclick = () => document.getElementById('modal-overlay').classList.add('hidden');
// Lagre knapp
const saveBtn = document.getElementById('btn-save'); const saveBtn = document.getElementById('btn-save');
if(saveBtn) { if(saveBtn) {
saveBtn.onclick = async () => { saveBtn.onclick = async () => {
@ -201,6 +228,7 @@ if(saveBtn) {
const focusP = people.find(p => p.id === focusPersonId); const focusP = people.find(p => p.id === focusPersonId);
let targetId = null; let targetId = null;
// 1. Enten lag ny person
if (modalMode === 'new') { if (modalMode === 'new') {
const newPerson = { const newPerson = {
name: document.getElementById('inp-name').value, name: document.getElementById('inp-name').value,
@ -211,10 +239,12 @@ if(saveBtn) {
fatherId: null, motherId: null, partnerId: null fatherId: null, motherId: null, partnerId: null
}; };
// Auto-koble foreldre hvis vi legger til et barn
if (modalAction === 'add-child' && focusP) { if (modalAction === 'add-child' && focusP) {
if (focusP.gender === 'M') newPerson.fatherId = focusP.id; if (focusP.gender === 'M') newPerson.fatherId = focusP.id;
else newPerson.motherId = focusP.id; else newPerson.motherId = focusP.id;
// Hvis fokuset har en partner, sett den som den andre forelderen
if (focusP.partnerId) { if (focusP.partnerId) {
const part = people.find(p=>p.id === focusP.partnerId); const part = people.find(p=>p.id === focusP.partnerId);
if(part) { if(part.gender==='M') newPerson.fatherId=part.id; else newPerson.motherId=part.id; } if(part) { if(part.gender==='M') newPerson.fatherId=part.id; else newPerson.motherId=part.id; }
@ -223,12 +253,16 @@ if(saveBtn) {
const docRef = await addDoc(collection(db, 'familyMembers'), newPerson); const docRef = await addDoc(collection(db, 'familyMembers'), newPerson);
targetId = docRef.id; targetId = docRef.id;
// Hvis dette var første person i treet
if(modalAction === 'create-first') focusPersonId = targetId; if(modalAction === 'create-first') focusPersonId = targetId;
} else { } else {
// 2. Eller velg eksisterende
targetId = document.getElementById('selected-existing-id').value; targetId = document.getElementById('selected-existing-id').value;
} }
// 3. Opprett relasjoner (linker) i databasen
if(focusP && targetId) { if(focusP && targetId) {
const col = collection(db, 'familyMembers'); const col = collection(db, 'familyMembers');
const updates = []; const updates = [];
@ -250,6 +284,7 @@ if(saveBtn) {
}; };
} }
// Bytt mellom "Ny" og "Eksisterende" fane i modal
function setMode(mode) { function setMode(mode) {
modalMode = mode; modalMode = mode;
document.querySelectorAll('.toggle-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.toggle-btn').forEach(b => b.classList.remove('active'));
@ -263,6 +298,7 @@ document.querySelectorAll('.toggle-btn').forEach(btn => {
btn.onclick = () => setMode(btn.dataset.mode); btn.onclick = () => setMode(btn.dataset.mode);
}); });
// Liste over eksisterende personer (for valg)
function renderExistingList() { function renderExistingList() {
const list = document.getElementById('existing-list'); const list = document.getElementById('existing-list');
if(!list) return; if(!list) return;
@ -281,6 +317,7 @@ function renderExistingList() {
}); });
} }
// --- ZOOM FUNKSJONALITET ---
const zoomIn = document.getElementById('btn-zoom-in'); const zoomIn = document.getElementById('btn-zoom-in');
if(zoomIn) zoomIn.onclick = () => { if(zoomIn) zoomIn.onclick = () => {
currentScale += 0.1; currentScale += 0.1;