0

Im trying to make an app that saves and reads teh familytree data automatically, so the familytree is the same anywhere youa access it. But I can't find a way to do that in plain js, according to balkan you can use npm but I am using flask.

I've tried this code but it doesnt seem to work

// JavaScript

var family = new FamilyTree(document.getElementById('tree'), {
    mouseScrool: FamilyTree.none, // Corrected typo: 'mouseScrool' to 'mouseScroll'
    mode: 'dark',
    template: 'hugo',
    roots: [1], // Corrected root ID to match the loaded data
    nodeMenu: {
        edit: { text: 'Edit' },
        details: { text: 'Details' },
    },
    nodeTreeMenu: true,
    nodeBinding: { // Corrected typo: 'nodeBinding' to 'nodeBindings'
        field_0: 'name',
        field_1: 'born',
        img_0: 'photo'
    },
    editForm: {
        titleBinding: "name",
        photoBinding: "photo",
        addMoreBtn: 'Add element',
        addMore: 'Add more elements',
        addMoreFieldName: 'Element name',
        generateElementsFromFields: false,
        elements: [
            { type: 'textbox', label: 'Full Name', binding: 'name' },
            { type: 'textbox', label: 'Email Address', binding: 'email' },
            [
                { type: 'textbox', label: 'Phone', binding: 'phone' },
                { type: 'date', label: 'Date Of Birth', binding: 'born' }
            ],
            [
                { type: 'select', options: [{ value: 'bg', text: 'Bulgaria' }, { value: 'ru', text: 'Russia' }, { value: 'gr', text: 'Greece' }], label: 'Country', binding: 'country' },
                { type: 'textbox', label: 'City', binding: 'city' },
            ],
            { type: 'textbox', label: 'Photo Url', binding: 'photo', btn: 'Upload' },
        ]
    },
});

family.on('field', function (sender, args) {
    if (args.name === 'born') {
        var date = new Date(args.value);
        args.value = date.toLocaleDateString();
    }
});


family.onUpdateNode((args) => {
    fetch('/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(args)
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
  });

// Initialize an empty data array
let data = [];

// Asynchronous function to fetch JSON data
async function fetchJson(filePath) {
  try {
    const response = await fetch(filePath);
    return await response.json();
  } catch (error) {
    console.error("Error fetching JSON:", error);
    return null;
  }
}

// File path to the JSON data
const jsonFilePath = "../static/dba.json";

// IIFE (Immediately Invoked Function Expression) to load and process JSON data
(async () => {
  data = await fetchJson(jsonFilePath);
  if (data !== null) {
    processData(data);
  } else {
    console.log("Failed to fetch or process JSON data.");
  }
})();

// Dictionary to store nodes using their IDs
const nodesDictionary = {};

// Helper function to get the next available ID
let nextId = 1;
function getNextId() {
  return nextId++;
}

// Process data function
function processData(data) {
  data.forEach(entry => {
    const nodesData = entry.updateNodesData || entry.addNodesData;
    if (nodesData) {
      nodesData.forEach(node => {
        const requiredFields = [
          "born", "city", "country", "email",
          "gender", "name", "phone", "photo"
        ];
        const hasAllFields = requiredFields.every(field => node[field] !== undefined);
        if (hasAllFields) {
          nodesDictionary[node.id] = node;
        }
      });
    }

    if (entry.removeNodeId) {
      delete nodesDictionary[entry.removeNodeId];
    }
  });

  // Update IDs to be non-repetitive
  for (const nodeId in nodesDictionary) {
    nodesDictionary[nodeId].id = getNextId();
  }

  console.log(nodesDictionary);

  const nodesArray = Object.values(nodesDictionary);

  console.log(nodesArray);

  family.load(nodesArray); // Assuming 'family.load' is a valid function call
}


i expect it to read every time I do something on the family tree and put that in (../static/)dba.json. Then when loading the family tree, it sees any repeated data, removes it and loads each member of the family tree

1 Answers1

0

You need to use the file API to read and write to local files. Here is an example of how it is used to read and write to CSV. You can test here how it works.

Zorry
  • 91
  • 6