Datatables filter checkbox – How to uncheck by default?

I am working on a project with datatable that has checkbox filtering on top. I found the example on Datatables.net. It works fine, however here is what I need –

By default the checkboxes should be unchecked (instead of checked) and display results for Techinical Author, Software Engineer and Architect.
When I click on Techinical Author checkbox, it should only display results for Techinical Author.
When I click on Software Engineer checkbox, it should only display results for Software Engineeer.
When all 3 checkboxes are checked, it should display results for everything.

I feel like I am missing something simple. Here is the code I am using. Thanks.

https://live.datatables.net/fofimale/49/edit

var filtered = ["Technical Author", "Software Engineer", "System Architect"];

$(document).ready( function () {


  
  var table = $('#example').DataTable({
    initComplete: function () {
      $.fn.dataTable.ext.search.push(
        function( settings, searchData, index, rowData, counter ) {
            // Don't display rows if nothing is checked
            if (filtered.length === 0) {
                return false;
            }
      
            if (filtered.includes(searchData[1])) {
                 return true;
            }
            return false;
        }
      );
    }
  });
  
  $('.filter').on('change', function() {
    var val = $(this).val();
    var checked = $(this).prop('checked');
    var index = filtered.indexOf( val );
    
    if (checked && index === -1) {
      filtered.push(val);
    } else if (!checked && index > -1) {
      filtered.splice(index, 2);
    }
    //console.log(filtered);
    table.draw();
  });
} );
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <div class="container">
      <label><input type="checkbox" class="filter" value="Technical Author" checked />Technical Author</label>
      <label><input type="checkbox" class="filter" value="Software Engineer" checked />Software Engineer</label>
      <label><input type="checkbox" class="filter" value="System Architect" checked />System Architect</label>

      <table id="example" class="display nowrap" width="100%">
        <thead>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
          </tr>
        </thead>

        <tfoot>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
          </tr>
        </tfoot>

        <tbody>
          <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Garrett Winters</td>
            <td>Director</td>
            <td>Edinburgh</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Ashton Cox</td>
            <td>Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>2009/01/12</td>
            <td>$4,800</td>
          </tr>
          <tr>
            <td>Cedric Kelly</td>
            <td>Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2012/03/29</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Jenna Elliott</td>
            <td>Financial Controller</td>
            <td>Edinburgh</td>
            <td>33</td>
            <td>2008/11/28</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>2012/12/02</td>
            <td>$4,525</td>
          </tr>
          <tr>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>2012/08/06</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Edinburgh</td>
            <td>55</td>
            <td>2010/10/14</td>
            <td>$6,730</td>
          </tr>
          <tr>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>2009/09/15</td>
            <td>$5,000</td>
          </tr>
          <tr>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>2008/12/13</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Jena Gaines</td>
            <td>System Architect</td>
            <td>London</td>
            <td>30</td>
            <td>2008/12/19</td>
            <td>$5,000</td>
          </tr>
          <tr>
            <td>Quinn Flynn</td>
            <td>Financial Controller</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2013/03/03</td>
            <td>$4,200</td>
          </tr>
          <tr>
            <td>Charde Marshall</td>
            <td>Regional Director</td>
            <td>San Francisco</td>
            <td>36</td>
            <td>2008/10/16</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Haley Kennedy</td>
            <td>Senior Marketing Designer</td>
            <td>London</td>
            <td>43</td>
            <td>2012/12/18</td>
            <td>$4,800</td>
          </tr>
          <tr>
            <td>Tatyana Fitzpatrick</td>
            <td>Regional Director</td>
            <td>London</td>
            <td>19</td>
            <td>2010/03/17</td>
            <td>$2,875</td>
          </tr>
          <tr>
            <td>Michael Silva</td>
            <td>Senior Marketing Designer</td>
            <td>London</td>
            <td>66</td>
            <td>2012/11/27</td>
            <td>$3,750</td>
          </tr>
          <tr>
            <td>Paul Byrd</td>
            <td>Javascript Developer</td>
            <td>New York</td>
            <td>64</td>
            <td>2010/06/09</td>
            <td>$5,000</td>
          </tr>
          <tr>
            <td>Gloria Little</td>
            <td>Systems Administrator</td>
            <td>New York</td>
            <td>59</td>
            <td>2009/04/10</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Bradley Greer</td>
            <td>Software Engineer</td>
            <td>London</td>
            <td>41</td>
            <td>2012/10/13</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Dai Rios</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>35</td>
            <td>2012/09/26</td>
            <td>$4,200</td>
          </tr>
          <tr>
            <td>Jenette Caldwell</td>
            <td>Financial Controller</td>
            <td>New York</td>
            <td>30</td>
            <td>2011/09/03</td>
            <td>$4,965</td>
          </tr>
          <tr>
            <td>Yuri Berry</td>
            <td>System Architect</td>
            <td>New York</td>
            <td>40</td>
            <td>2009/06/25</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Caesar Vance</td>
            <td>Technical Author</td>
            <td>New York</td>
            <td>21</td>
            <td>2011/12/12</td>
            <td>$4,965</td>
          </tr>
          <tr>
            <td>Doris Wilder</td>
            <td>Sales Assistant</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>2010/09/20</td>
            <td>$4,965</td>
          </tr>
          <tr>
            <td>Angelica Ramos</td>
            <td>System Architect</td>
            <td>London</td>
            <td>36</td>
            <td>2009/10/09</td>
            <td>$2,875</td>
          </tr>
          <tr>
            <td>Gavin Joyce</td>
            <td>Developer</td>
            <td>Edinburgh</td>
            <td>42</td>
            <td>2010/12/22</td>
            <td>$4,525</td>
          </tr>
          <tr>
            <td>Jennifer Chang</td>
            <td>Regional Director</td>
            <td>London</td>
            <td>28</td>
            <td>2010/11/14</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Brenden Wagner</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>18</td>
            <td>2011/06/07</td>
            <td>$3,750</td>
          </tr>
          <tr>
            <td>Ebony Grimes</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>48</td>
            <td>2010/03/11</td>
            <td>$2,875</td>
          </tr>
          <tr>
            <td>Russell Chavez</td>
            <td>Director</td>
            <td>Edinburgh</td>
            <td>20</td>
            <td>2011/08/14</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Michelle House</td>
            <td>Integration Specialist</td>
            <td>Edinburgh</td>
            <td>37</td>
            <td>2011/06/02</td>
            <td>$3,750</td>
          </tr>
          <tr>
            <td>Suki Burks</td>
            <td>Developer</td>
            <td>London</td>
            <td>53</td>
            <td>2009/10/22</td>
            <td>$2,875</td>
          </tr>
          <tr>
            <td>Prescott Bartlett</td>
            <td>Technical Author</td>
            <td>London</td>
            <td>27</td>
            <td>2011/05/07</td>
            <td>$6,730</td>
          </tr>
          <tr>
            <td>Gavin Cortez</td>
            <td>Technical Author</td>
            <td>San Francisco</td>
            <td>22</td>
            <td>2008/10/26</td>
            <td>$6,730</td>
          </tr>
          <tr>
            <td>Martena Mccray</td>
            <td>Integration Specialist</td>
            <td>Edinburgh</td>
            <td>46</td>
            <td>2011/03/09</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Unity Butler</td>
            <td>Senior Marketing Designer</td>
            <td>San Francisco</td>
            <td>47</td>
            <td>2009/12/09</td>
            <td>$3,750</td>
          </tr>
          <tr>
            <td>Howard Hatfield</td>
            <td>Financial Controller</td>
            <td>San Francisco</td>
            <td>51</td>
            <td>2008/12/16</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Hope Fuentes</td>
            <td>Financial Controller</td>
            <td>San Francisco</td>
            <td>41</td>
            <td>2010/02/12</td>
            <td>$4,200</td>
          </tr>
          <tr>
            <td>Vivian Harrell</td>
            <td>System Architect</td>
            <td>San Francisco</td>
            <td>62</td>
            <td>2009/02/14</td>
            <td>$4,965</td>
          </tr>
          <tr>
            <td>Timothy Mooney</td>
            <td>Financial Controller</td>
            <td>London</td>
            <td>37</td>
            <td>2008/12/11</td>
            <td>$4,200</td>
          </tr>
          <tr>
            <td>Jackson Bradshaw</td>
            <td>Director</td>
            <td>New York</td>
            <td>65</td>
            <td>2008/09/26</td>
            <td>$5,000</td>
          </tr>
          <tr>
            <td>Miriam Weiss</td>
            <td>Support Engineer</td>
            <td>Edinburgh</td>
            <td>64</td>
            <td>2011/02/03</td>
            <td>$4,965</td>
          </tr>
          <tr>
            <td>Bruno Nash</td>
            <td>Software Engineer</td>
            <td>London</td>
            <td>38</td>
            <td>2011/05/03</td>
            <td>$4,200</td>
          </tr>
          <tr>
            <td>Odessa Jackson</td>
            <td>Support Engineer</td>
            <td>Edinburgh</td>
            <td>37</td>
            <td>2009/08/19</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Thor Walton</td>
            <td>Developer</td>
            <td>New York</td>
            <td>61</td>
            <td>2013/08/11</td>
            <td>$3,600</td>
          </tr>
          <tr>
            <td>Finn Camacho</td>
            <td>Support Engineer</td>
            <td>San Francisco</td>
            <td>47</td>
            <td>2009/07/07</td>
            <td>$4,800</td>
          </tr>
          <tr>
            <td>Elton Baldwin</td>
            <td>Data Coordinator</td>
            <td>Edinburgh</td>
            <td>64</td>
            <td>2012/04/09</td>
            <td>$6,730</td>
          </tr>
          <tr>
            <td>Zenaida Frank</td>
            <td>Software Engineer</td>
            <td>New York</td>
            <td>63</td>
            <td>2010/01/04</td>
            <td>$4,800</td>
          </tr>
          <tr>
            <td>Zorita Serrano</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>56</td>
            <td>2012/06/01</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Jennifer Acosta</td>
            <td>Javascript Developer</td>
            <td>Edinburgh</td>
            <td>43</td>
            <td>2013/02/01</td>
            <td>$2,875</td>
          </tr>
          <tr>
            <td>Cara Stevens</td>
            <td>Sales Assistant</td>
            <td>New York</td>
            <td>46</td>
            <td>2011/12/06</td>
            <td>$4,800</td>
          </tr>
          <tr>
            <td>Hermione Butler</td>
            <td>Director</td>
            <td>London</td>
            <td>47</td>
            <td>2011/03/21</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Lael Greer</td>
            <td>Systems Administrator</td>
            <td>London</td>
            <td>21</td>
            <td>2009/02/27</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Jonas Alexander</td>
            <td>Developer</td>
            <td>San Francisco</td>
            <td>30</td>
            <td>2010/07/14</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Shad Decker</td>
            <td>Regional Director</td>
            <td>Edinburgh</td>
            <td>51</td>
            <td>2008/11/13</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Michael Bruce</td>
            <td>Javascript Developer</td>
            <td>Edinburgh</td>
            <td>29</td>
            <td>2011/06/27</td>
            <td>$4,080</td>
          </tr>
          <tr>
            <td>Donna Snider</td>
            <td>System Architect</td>
            <td>New York</td>
            <td>27</td>
            <td>2011/01/25</td>
            <td>$3,120</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
</html>

Paginate Array of Objects Next and Previous Buttons JavaScript

I have an Array of Objects:

let myArray = [
    {objectName: "Object 1"},
    {objectName: "Object 2"},
    {objectName: "Object 3"},
    {objectName: "Object 4"},
    {objectName: "Object 5"},
];

I have paginated this Array of Objects using the following code:

// Set the number of products dislpayed per page
let page_size = 15;
// Set the current page number to 1
let page = 1;
let start = (page - 1) * page_size;
let end = start + page_size;
let shownElements = products.slice(start, end);

shownElements.forEach(item => {//Perform actions}

next.addEventListener('click', () => changePageNumber(page++)); // If the next button is clicked, run the 'changePageNumber' function passing in the next page number as the argument
prev.addEventListener('click', () => changePageNumber(page--)); // If the previous button is clicked, run the 'changePageNumber' function passing in the previous page number as the argument

I have created the numbered buttons using this code:

for (let i = 1; i <= last_page; i++) {
  let button = document.createElement('button');
  button.innerText = i;
  paginationButtons.appendChild(button);
  button.addEventListener('click', () => changePageNumber(i));
}

When I click the next button, the program will automatically go back to page 1, regardless of which page I am currently on. When I click the previous button, the code program will automatically go back to page 1, regardless of which page I am currently on.

I have found that the next and previous page buttons are not linked to the numbered buttons. How could I link the next and previous page buttons together, in order to display the correct page when the user clicks the next page button or previous page button.

Unable to detect manual URL change in address bar for SPA in jQuery

I’m trying to build a search engine UI as a single page application using jQuery.

I’m using fetch API for loading content and History API for navigation.

I want non-hashed urls.
I’m manually adding url params on search
which look this way

/?query=myQuery

If the user enters the URL themselves, I want to be able to detect the URL change and get the query value from params and fetch the results.

**I’ve tried using **

  1. popState event listeners – only detect back and forward button changes
  2. timeOut function to detect url changes – didn’t detect the manual entries

I can see that the browser loads when URL is manually entered and the browser console gets cleared as well.

Is there a way to detect that change? – $(document).ready() , window.on(‘load’) , beforeunload event listeners didn’t work. There is only one index.html file that is loaded and the content is being manipulated in it.

I want it to be like [qwant.com](qwant.com) – pl suggest other methods to implement its behaviour in jQuery

making an authentic click on a scrolling slider

*I try to avoid calculating the position of the mouse in relation to the objects because of their quantity and because in the future more objects need to be added, it can be a huge headache + a lot of unnecessarily code.

I’m trying to reach a situation where if the user clicks (and not drags) a normal click on the element will be performed, Then, for example, if one of the card was clicked, you would be catch it, or if the color picker was clicked, it would open properly.

  let sliderContainer = document.querySelector('.slider-container');
  let innerSlider = document.querySelector('.inner-slider');
 let pressed = false;
  let startX;
  let x;
  let drag = false;
  
sliderContainer.addEventListener("mousedown", (e) => {
    drag = false
    pressed = true;
    startX = e.offsetX - innerSlider.offsetLeft;
    
});

sliderContainer.addEventListener("mouseleave", () => {
    pressed = false;
});

sliderContainer.addEventListener("mouseup", (e) => {
    if(drag == false){
      console.log("click");
    }
    pressed = false;
});

sliderContainer.addEventListener("mousemove", (e) => {
    drag = true
    if (!pressed) return;
    x = e.offsetX;
    innerSlider.style.left = `${x - startX}px`;
    checkBoundary();

});

const checkBoundary = () => {
    let outer = sliderContainer.getBoundingClientRect();
    let inner = innerSlider.getBoundingClientRect();

    if (parseInt(innerSlider.style.left) > 0) {
        innerSlider.style.left = "0px";
    }

    if (inner.right < outer.right) {
      innerSlider.style.left = `-${inner.width - outer.width}px`;
    }
};
.card {
    height: 300px;
    width: 200px;
    border-radius: 5px;
}
.card:nth-child(odd) {
    background-color: blue;
}
.card:nth-child(even) {
    background-color: rgb(0, 183, 255);
}
.slider-container {
    width: 50%;
    height: 330px;
    position: relative;
    left: 50%;
    transform: translate(-50%);
    overflow: hidden;
}
.inner-slider {
    width: fit-content;
    display: flex;
    gap: 10px;
    pointer-events: none;
    position: absolute;
    top: 0;
    left: 0;
}
<div class="slider-container">
    <div class="inner-slider">
        <div class="card" id = "card_1"><input type="color" name="favcolor" value="#ff0000"></div>
        <div class="card" id = "card_2"></div>
        <div class="card" id = "card_3"></div>
        <div class="card" id = "card_4"></div>
    </div>
</div>

How to replace text in HTML using JavaScript without refreshing everything around it?

I made this simple line of JavaScript that just searches the HTML for a certain link and then replaces it with another, it works as intended but it refreshes everything around it.., quite literally breaking everything around it.

document.body.innerHTML = document.body.innerHTML.replace(/src="https://media.discordapp.net/attachments/g, 'src="https://cdn.discordapp.com/attachments');

I expected it to just replace the links and that is it… not refresh everything around it, making my solution useless. I’ve spent hours trying to find a solution.

Return the Maximum Depth of objects in a Nested Collection (JavaScript)

I looking for a suitable algorithm that will return the maximum depth of a collection of objects within a hierarchy of collections. I have a root object which may or may not contain a collection of objects of the same type, of variable number. Each of these child objects, themselves may contain a collection of the same type and variable number, and so-on, down to any depth. (see diagram).

Object hierarchy

I looking for the best algorithm that would return an integer that represents the level of the deepest collection in the hierarchy. (So in my diagram that would be 4.).

I’ve tried the following function recursively but it is always out by one.

 var getLevelFunc = function (composites) {
             var depth = 0
            for (var c = 0; c < composites.length; c++) {
                let composite = composites[c];
                if (composite.composites() != null && composite.composites().length > 0) {
                    var tempDepth = getLevelFunc(composite.composites());
                    if (tempDepth > depth) {
                        depth = tempDepth
                    }
                }
            }
            return 1 + depth;
        }

Many thanks

How can I integrate python into my javascript code?

I have programmed a ChatBot with Spacy in Python, which I now want to integrate somehow into my website (with HTML and JavaScript), as I have made an interface in HTML for the bot. But my webserver doesn’t support Python so I have to do it somehow via JavaScript or something. My code:

import spacy
import random

# load NLP model
nlp = spacy.load("en_core_news_sm")
nlp.max_length = 10000000

# load text from file
with open("deutsch_corpus.txt", encoding='utf-8') as f:
    text = f.read()

# parse text with NLP model
doc = nlp(text)

# define function to generate bot response
def generate_response(user_input):
    # parse user input with NLP model
    user_doc = nlp(user_input)

    # check if the user input contains information that should be stored
    remember = False
    remember_text = ""
    for sent in user_doc.sents:
        if any(word in sent.text.lower() for word in ["I am", "my friend", "my girlfriend", "I was", "I have", "I have", "my mother is", "my mother is", "I would be", "I find", "my name is"]):
            remember = True
            remember_text = sent.text
            break

    # If the user input contains information to remember, store it in the memory file
    if remember:
        remember_text = remember_text.lower()
        with open("german_corpus.txt", "a", encoding='utf-8') as f:
            f.write(remember_text.replace("ich bin", "Du bist").replace("mein", "Dein").replace("meine", "Deine").replace("meine mutter ist", "deine Mutter ist").replace("meine freundin ist", "deine Freundin ist"). replace("would have", "would have").replace("have", "have").replace("have", "have").replace("I would be", "you would be").replace("I find", "you find").replace("my name", "your name is").replace("my name is", "your name is") + "n")
        return "Ok, I'll remember that!"

    # search for sentences in the corpus that are similar to the user input
    similarity_scores = []
    for sentence in doc.sents:
        score = sentence.similarity(user_doc)
        similarity_scores.append((sentence, score))

    # sort sentences by similarity score
    similarity_scores.sort(key=lambda x: x[1], reverse=True)

    # if no similar sentence is found, a random answer is returned
    if similarity_scores[0][1] < 0.5:
        return "Sorry, I don't understand."

    # Return most similar sentence as bot response.
    return similarity_scores[0][0].text

… and my HTML Code:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TalkyAI</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="#">KI trainieren</a></li>
                <li><a href="#" class="active">Chat</a></li>
                <li><a href="#">Account</a></li>
            </ul>
            <div class="logout-btn"><a href="#">Abmelden</a></div>
        </nav>
    </header>
    <main>
        <div id="chat-container">
            <div id="chat-output"></div>
            <div id="chat-input">
                <input type="text" id="message-input" placeholder="Gib deine Nachricht ein...">
                <button id="send-btn">Senden</button>
            </div>
        </div>
    </main>
    <script>

    </script>



</body>
</html>

I already tried to translate my code to JavaScript, which all didn’t really work (NLP, Tensorflow, etc.) and my code doesn’t work like it does in Python.

JavaScript to change field color based on its value

Can’t get JavaScript script to work.

I have a pdf with 18 questions and those questions have 4 choices to select with radio buttons.
The code for the radio buttons work fine and will total to a field at the end of the form called “score”.
I have the below code in the “score” field using the validation tab in Adobe.

var fm = this.getField("score").value;
if (fm >= 1 && fm <= 26)
  event.target.fillColor = (0.537, 0.776, 0); //fill color red  
else if (fm >= 27 && fm <= 48)
  event.target.fillColor = (1, 0.804, 0.623); //fill color orange  
else if (fm >= 49 && fm <= 62)
  event.target.fillColor = (1, 0, 0.709); //fill color yellow
else if (fm >= 63 && fm <= 72)
  event.target.fillColor = (1, 1, 1); // fill color green
else
  event.target.fillColor = (1, 1, 1);

What am I doing wrong? Should this code be in the ‘Global’ section?
Please help.

Build bundler with Vite (and tree shaking on) __WEBPACK_IMPORTED_MODULE_0__.exports.shape is not a function

I’m working on a UI components library, and I’m bundling with Vite, the goal is to use it like an external library in other repo (with tree shaking on).

When I trying to install it in another existing repo and then run (that runs with webpack) there is on browser console this error:

WEBPACK_IMPORTED_MODULE_0.exports.shape is not a function

my vite configuration:

import { defineConfig } from 'vite'
import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig({
  build: {
    target: 'esnext',
    sourcemap: true,
    lib: {
      entry: 'lib/main.js',
      name: 'Components Library',
      fileName: 'web-components',
      formats: ['esm']
    },
    rollupOptions: {
      external: ['react'],
      preserveModules: true,
      output: {
        dir: 'dist',
        globals: {
          react: 'react'
        }
      }
    }
  },
  plugins: [
    viteStaticCopy({
      targets: [
        { src: 'resources', dest: './' },
        { src: 'src/sass', dest: './src' }
      ]
    })
  ]
})

Relevant part of package.json:

{
  "type": "module",
  "files": [
    "dist"
  ],
  "module": "dist/web-components.esm.js",
  "sideEffects": [
    "*.css",
    "*.png",
    "*.svg",
    "*.jpg",
    "*.jpeg"
  ],  "scripts": {
    "prebuild": "rimraf dist",
    "build": "vite build"
    }
 }

In various components I have something like:

ComponentName.propTypes = {
  className: PropTypes.string,
  items: PropTypes.arrayOf(PropTypes.shape({
    label: PropTypes.string,
    className: PropTypes.string,
    isActive: PropTypes.bool,
    onClick: PropTypes.func
  }))
}

I tried to remove them in the components sources but the problem persist.

Webpack.config file is too long to show here.

why won’t javascript won’t work (Rails 7 with esbuild)

I’m pretty new to Rails (version 7.0.4.2 with ruby 3.2.0, on an Intel-based Macbook Pro running Monterey 12.6). Here’s a minimal example causing me problems:

I start a new project by doing
rails new project_name --j esbuild -c bootstrap

After the installation completes I make a minimal bootstrap example (generated using chatgpt, so perhaps not so minimal). I run the server by doing ./bin/dev.

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Brand Name</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">About Us</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown Menu
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Action 1</a>
            <a class="dropdown-item" href="#">Action 2</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Separated link</a>
          </div>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Contact Us</a>
        </li>
      </ul>
    </div>
  </nav>



Unfortunately the dropdowns don’t work.
Even though the application.js file contains the line import * as bootstrap from "bootstrap", entering Chrome’s dev tools JS console, shows bootstrap to be an undefined reference.


It works if I explicitly import the necessary scripts in the page:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bootstrap Navbar with Dropdown Menu</title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
  
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Brand Name</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">About Us</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown Menu
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Action 1</a>
            <a class="dropdown-item" href="#">Action 2</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Separated link</a>
          </div>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Contact Us</a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- jQuery and Popper.js -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

  <!-- Bootstrap JS -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</body>
</html>

(I use render "viewname", layout: false to avoid the view being embedded in the layout file.)


Can someone help me figure out the problem?

SVG Pan Zoom Library

Refering to SVG Pan Zoom Library at here, there is a section for faster or slower zooming at here. I have created this zoom in and out with Pan Functionality at Codepen Working demo here, but the zooming in and out is not sensitive enough, may I know how to implement the above example in github to increase the zoom sensitivity? Any help will be very much appreciated 🙂

Well, I have tried to implement this zoomScaleSensitivity, but it seems to have no effect on increasing zoom sensitivity which is dissapointing 🙂

instance  = panzoom(area, { 
  bounds: false,
  zoomScaleSensitivity: 10,
  maxZoom: 10.55,
  minZoom: 0,
   zoomScaleSensitivity:0.8,
  zoomDoubleClickSpeed: 1
});

How do I decode form data sent via fetch POST request

I am sending form data with a basic POST request:

const formData = new FormData();
formData.append('id', '123');
const res = await fetch('./handler', { method: 'POST', body: formData });
const json = await res.json();

handler.js

export default async function handler(req, res) {
 console.log(req.body.id);
 ...
}

The code above will log undefined. When logging req.body the result is something that definitely needs decoding:

------WebKitFormBoundary
Content-Disposition: form-data; name="id"

123
------WebKitFormBoundary --

How do I read the data passed?

What’s the best way to transform Google Sheets data to an array of objects?

I am using Google Spreadsheets as a simple “backend” for a personal web application. Everything is working pretty well, but while developing this code, I had one doubt about performance.

This is not too much relevant to my application, but I wanted to understand what would be the best way to achieve what I did, or if I was actually doing this in a reasonably good fashion.

The problem:

Google sheets API returns me something like this as JSON:

 "values": [
    [
      "name",
      "country",
      "age"
    ],
    [
      "John",
      "Brazil",
      "21"
    ],
    [
      "Jane",
      "Canada",
      "27"
    ],
   ]

But I would prefer to have something like this, in the end:

"values": [
{ 
 "name": "John",
 "country": "Brazil",
 "age": "21",
},
{
 "name": "Jane",
 "country": "Canada",
 "age": "27",
}
]

This is the code I’m using to make that transformation:

const values = [
  [
    "name",
    "country",
    "age"
  ],
  [
    "John",
    "Brazil",
    "21"
  ],
  [
    "Jane",
    "Canada",
    "27"
  ],
];

const adjustValues = (array) => {
  const indexes = array.shift();
  const returnArray = [];
  array.forEach((value, index) => {
    const returnObject = {};
    value.forEach((column, index) => {
      returnObject[indexes[index]] = column;
    });
    returnArray.push(returnObject);
  });
  return returnArray;
}

console.log(adjustValues(values));

Is this a good way to transform that data? What would be the best way?