VolkovLabs / volkovlabs-dynamictext-panel

Business Text Panel for @grafana
https://docs.volkovlabs.io
Apache License 2.0
78 stars 14 forks source link

Panel does not show content instantly (HTML + CSS + JS) #205

Closed fredbrasils closed 11 months ago

fredbrasils commented 11 months ago

Hi,

I have this situation:

HTML:

  • D
  • L
  • M
  • M
  • J
  • V
  • S

    {{showdata data}}

    #####################################

    JS Code:

    handlebars.registerHelper("showdata", (json) => load(json));

    function load(json) { const jsonData = json; const day = document.querySelector(".days");

    if (day == null) { console.log('Not found element .days'); return; }

    let dateactuel = jsonData.length > 0 ? jsonData[0].day : ""; let datesplit = dateactuel.split('-');

    let date = new Date(dateactuel) !== 'NaN' ? new Date(datesplit[0], datesplit[1] - 1, datesplit[2]) : new Date(); // creates a new date object with the current date and time let year = date.getFullYear(); let month = date.getMonth();

    const manipulate = () => { let dayone = new Date(year, month, 1).getDay(); let lastdate = new Date(year, month + 1, 0).getDate(); let dayend = new Date(year, month, lastdate).getDay(); let monthlastdate = new Date(year, month, 0).getDate(); let lit = ""; for (let i = dayone; i > 0; i--) { lit += <li>${monthlastdate - i + 1}</li>; }

    for (let i = 1; i <= lastdate; i++) {
      let className = getValueFromJson(i, jsonData);
      lit += `<li class="${className}">${i}</li>`;
    }
    
    for (let i = dayend; i < 6; i++) {
      lit += `<li>${i - dayend + 1}</li>`
    }
    
    day.innerHTML = lit;
    // console.log(day);
    
    // const css = document.querySelector(".css-18my9cq");
    // console.log(css);

    }

    manipulate();

    }

    function getValueFromJson(day, jsonData) { let response = "none-active";

    if (jsonData != null && jsonData.length > 0) { jsonData.forEach((item) => { let dayJson = new Date(item["day"]).getUTCDate(); if (dayJson === day) { response = item["threshold"]; } }); }

    return response; }

    #############################################

    The idea is show this:

    image

    The problem is: The panel show the html correctly only when I refresh the dashboard. I don't see what is wrong.

    Could you have an idea ?

    Thank you

    mikhail-vl commented 11 months ago

    @fredbrasils You have a race condition. Element document.querySelector(".days"); is not rendered when the handlebars helper is executed.

    You can use timeout, which works, but I recommend rewriting the function to return a list element instead of accessing it.

    handlebars.registerHelper("showdata", (json) => setTimeout(() => load(json), 100));

    There are various examples of Handlebars Helpers in the documentation:

    https://volkovlabs.io/plugins/volkovlabs-dynamictext-panel/code/

    fredbrasils commented 11 months ago

    Thanks @mikhail-vl ! I will try that.