How to create a react layout component without using props?

I’ve seen the following pattern a lot in primitive components (like Radix UI) where layouts are rendered as custom children components. For example:

<List.Root>
    <List.Title>Hello!</List.Title>
    <List.Items>
        <List.Item>Item 1</List.Item>
        <List.Item>Item 2</List.Item>
        <List.Item>Item 3</List.Item>
    <List.Items>
<List.Root>

This will end up rendering some custom layout with styles, etc, like the following:

<div>
    <span>Hello!</span>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</div>

My question is: what even is the name of this pattern, and how would I achieve it using functional components? How would I pass states between each of the elements? I’ve looked at the source for some of the Radix components, but they all use some sort of abstracted primitives, and a lot of Contexts. The example above is pretty simple, but you can imagine each Item having some custom styling and positioning, and not just returning a <li>.

Any help would be appreciated!

Wix Custom element is working only when it keeps its standard tag “wix-default-custom-element”

So as you can read from the title, I have tried to use a Custom Element in WIX. When I used the template by wix, it worked perfectly well. When I just try to change the tag name however, the element doesn’t show anything afterwards. Changing text such as H2_TEXT works

Here is the code by wix if somebody needs it (this does work for me):

// To debug this code, open wixDefaultCustomElement.js in Developer Tools.

const IMAGE_URL = 'https://wix.to/vUBXBKU';
const H2_TEXT = 'This is a Custom Element';
const H3_1_TEXT = 'View its code by clicking the Settings button and pasting the Server URL into a new browser tab.';
const H3_2_TEXT = 'Explore this code and use it as a reference to create your own element.';
const DEBUG_TEXT = 'Loading the code for Custom Element 'wix-default-custom-element'. To debug this code, open wixDefaultCustomElement.js in Developer Tools.';

const createImage = () => {
  const imageElement = document.createElement('img');
  imageElement.src = IMAGE_URL;
  imageElement.id = 'wdce-image';
  return imageElement;
};

const createH2 = () => {
  const h2Element = document.createElement('h2');
  h2Element.textContent = H2_TEXT;
  h2Element.id = 'wdce-h2';
  return h2Element;
};

const createH3 = (id, text) => {
  const h3Element = document.createElement('h3');
  h3Element.id = id;
  h3Element.textContent = text;
  return h3Element;
};

const createTextContainer = () => {
  const textContainer = document.createElement('div');
  textContainer.id = 'wdce-text-container';
  textContainer.appendChild(createH2());
  textContainer.appendChild(createH3('wdce-h3-1', H3_1_TEXT));
  textContainer.appendChild(createH3('wdce-h3-2', H3_2_TEXT));
  return textContainer;
};

const createImageContainer = () => {
  const imageContainer = document.createElement('div');
  imageContainer.id = 'wdce-image-container';
  imageContainer.appendChild(createImage());
  return imageContainer;
};

const createStyle = () => {
  const styleElement = document.createElement('style');
  styleElement.innerHTML = `
    wix-default-custom-element {
        background-color: #f0f4f7;
        display: flex;
        width: 100%;
        justify-content: center;
      }

    #wdce-image-container {
        width: 35%;
        max-width: 165px;
        display: flex;
        margin: 0 20px 0 30px;
        overflow: hidden;
    }

    #wdce-image {
        width: 100%;
        min-width: 100px;
    }

    #wdce-text-container {
        display: flex;
        flex-direction: column;
        width: 65%;
        justify-content: center;
        max-width: 314px;
        min-width: 200px;
    }

    #wdce-h2 {
        font-family: 'HelveticaNeueW01-45Ligh, HelveticaNeueW02-45Ligh, HelveticaNeueW10-45Ligh, Helvetica Neue, Helvetica, Arial, メイリオ, meiryo, ヒラギノ角ゴ pro w3, hiragino kaku gothic pro, sans-serif',
        font-size: 16px;
        font-weight: 500;
        letter-spacing: 0.89px;
        color: #32536a;
        margin: 0 0 16px 0;
    }

    #wdce-h3-1, #wdce-h3-2 {
        font-family: 'HelveticaNeueW01-45Ligh, HelveticaNeueW02-45Ligh, HelveticaNeueW10-45Ligh, Helvetica Neue, Helvetica, Arial, メイリオ, meiryo, ヒラギノ角ゴ pro w3, hiragino kaku gothic pro, sans-serif',
        font-size: 14px;
        font-weight: 300;
        line-height: 1.43;
        color: #162d3d;
        margin: 0 0 8px 0;
    }
    `;
  return styleElement;
};

class WixDefaultCustomElement extends HTMLElement {
  constructor() {
    super();
    console.log(DEBUG_TEXT);
  }

  connectedCallback() {
    this.appendChild(createStyle());
    this.appendChild(createImageContainer());
    this.appendChild(createTextContainer());
  }
}
customElements.define('wix-default-custom-element', WixDefaultCustomElement);

Now you might say, “well, that’s easy: just change the tag name in customElements.define()”, but that doesn’t work. I have also tried changing the name in createStyle from wix-default-custom-element to custom-Output.

Like this (that doesn’t work):

const createStyle = () => {
  const styleElement = document.createElement('style');
  styleElement.innerHTML = `
    #custom-Output {       //doesn't work with #customElement1 (the id) either
        background-color: #f0f4f7;
        display: flex;
        width: 100%;
        justify-content: center;
      }

and

customElements.define('custom-Output', WixDefaultCustomElement);

Thank you for your time!

How to display the content of a JSON array?

My Django app sends through AJAX POST/GET communications arrays representing parts of my DB. As you can see on the picture, this is a typical array with all the objects. The objects represent a messages to integrate in a chat box. Just to clarify, the amount of objects might vary, so I need a loop function or smthg to display all the objects within the response array .

Therefore, I need to display these arrays, combining HTML and JS.

This is my exact AJAX Json response

HTML:

    <div id="display"></div>

JS:

<script>
    $(document).ready(function(){
    
    setInterval(function(){
        $.ajax({
            type: 'GET',
            url : "/checkview",
            success: function(response){
                console.log(response);
                $("#display").empty();
                for (var models_to_return in response.message)
                {
                    var temp="<div class='container darker'><b>"+response.messages[models_to_returney].user_id+"</b><p>"+response.messages[models_to_return].room+"</p><span class='time-left'>"+response.messages[models_to_return].datetime+"</span></div>";
                    $("#display").append(temp);
                }
            },
            error: function(response){
                //alert('An error occured')
            }
        });
    },1000);
    })
</script>

But nothing is displaying.

Library Client side test with local web server

I’m starting in JavaScript test environment. There are a lot of tools out there and I don’t really know what to chose for my needs.

I’m creating a library to download/upload files from browser with encryption feature.

I’ll the example of the upload test here. I need to test the upload function with a local server to upload the file then compare this file to the original one / decrypt it if the file is encrypted during the process to compare hashes.

I couldn’t find a simple way to actually run browser test and nodejs tests within the same test.

I came to the solution of running my server before launching the client and then send the results through http requests.

Is it a good test architecture or is there any better solution?

Thank you for your attention

How to style text dynamically only on the current index that is being typed?

I am trying to make a text editor and I am trying to make it so when I click on the “boldButton” it makes only the text that I am currently typing bold but all the text before clicking that button a normal font.

For my HTML I am using a div with a contenteditable=”true”. Example:

<div id="box-txt-input" class="box-txt" contenteditable="true" placeholder="Enter text here..."></div>

Now for my Javascript I made a variable called “index” that gets 1 added to it every time that you have an “input” event and was hoping to get only the current index typed to have the fontWeight of Bold. Example:

const boldButton = document.querySelector("#bold")
const textBox = document.querySelector(".box-txt")
let index = 0

textBox.addEventListener("input", function () {
    index++
    
    boldButton.addEventListener("click", function () {

        textBox[index].textContent.style.fontWeight = "Bold"
    })
})

Here is a codepen to what I am working on as well. Sorry that you can’t see the icons but the “Bold” button is all the way to the left of the grey bar above the text area. You can see a tooltip when you hover over it. Codepen: https://codepen.io/Chasehud26/pen/xxJjEVG

Get data Laravel 9 Vue js 3

I need to get data for status = 1 or status = 2 in a table. I have done for status = 1 .please instruct me to do this. My code is as follows.

public function depositAccountIndex()
    {
        $userId = Auth::id();
        return response()->json(Account::latest()->where('user', $userId)->where('status', 1 )->get());
    }

object HTMLDivElement to string

How can one convert “object HTMLDivElement” to a string?

let z = document.querySelector(".global_all_sessions"); console.log(z) // No string

Tried to do so: z = String(z) , but it didn’t work out.

Uncaught TypeError: Failed to resolve module specifier “@kurkle/color”. Relative references must start with either “/”, “./”, or “../”

I’m currently working on creating a Google Chrome extension in Manifest V3 and am attempting to import Chart.js. I am getting the following error in the console:

Uncaught TypeError: Failed to resolve module specifier “@kurkle/color”. Relative references must start with either “/”, “./”, or “../”.

The following are my files:

index.html

<html>
    <head>
        <link rel="stylesheet" href="styles.css">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap">
        <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
    </head>
    <body>
        <h4>GOOGLE CALENDAR</h4>
        <h5>Time Tracker</h5>
        <hr></hr>
        <div style="width: 800px;"><canvas id="chart"></canvas></div>
        <script type="module" src="src/donut_chart.js"></script>
    </body>
</html>

donut_chart.js

import Chart from "../Chart.js/node_modules/chart.js/auto/auto.js";

document.addEventListener('DOMContentLoaded', function()
{
    var ctx = document.getElementById("chart").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: [ 'a', 'b', 'c', 'd' ],
                datasets: [{
                backgroundColor: [
                    "#59be5b",
                    "#d56328",
                    "#ff1b2d",
                    "#0078d7"
                ],
                data: [ 1, 2, 3, 4 ]
            }]
        }
    });

    document.getElementById('test').textContent = 'SUCCEED';
});

manifest.json

{
    "manifest_version": 3,
    "name": "Google Calendar Time Tracker",
    "description": "Base Level Extension",
    "version": "1.0",
    "action": {
        "default_popup": "index.html",
        "default_icon": "hello_extensions.png"
    },
    "host_permissions": [
        "https://*/*",
        "http://*/*"
    ]
}

package.json

{
    "type": "module"
}

I’ve looked online for solutions to this, and haven’t really found anything much. All the solutions seem to suggest I use an HTML link instead of an import statement, but Manifest V3 doesn’t allow for any outside links to be included. Any sort of help would be much appreciated!

Is there anyway to show always rows modified in a FooTable

The system is made with php, mysql, javascript, jquery and what it does is show a list of products and the user chooses the amount and shows a total.

I want to make a function that when the user modifies the quantity of a row, the row is always displayed in the Table, no matter if they search for other products or change the page of the table

This is the code

  <table  class="table-striped footable-res footable metro-blue" data-page-size="36" data-filter="#filter" style="color: #666;" data-filter-exact-match="false" id="tb">
        <thead>
              <th width="5%">°</th>
              <th width="40%">Producto</th>
              <th width="15%">Precio</th>
              <th width="15%">Cantidad</th>
              <th width="15%">Total</th>
              <tr></tr>
        </thead>
        <tbody>
              <td colspan=5 data-value='Nombre de categoria'><b>Nombre de categoria</b></td><tr></tr>";
              <td>Contador 1</td>";
              <input type='text' name='seleccion1' value='IDPRODUCTO' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
              <td data-value='NOMBREPRODUCTO CATEGORIAID CATEGORIANOMBRE' data-type='text'>"PRODUCTONOMBRE"</td>";

              <td><input type='text' class='precio' name='precioIDPRODUCTO' id='precio' value='PR' style='color: black; background: transparent; border: 0; text-align: center;' readonly></td>";
              <td><input type='text' class='cantidad' name='cantidadIDPRODUCTO' id='cantidad' placeholder='0' placeholder='0' style='color: black;'></td>";
              <td><input type='text' class='total' name='totalIDPRODUCTO' id='total'  value='0' value='0' style='color: black;'></td>";
              <tr></tr>
              }
        }
              if (CONTADOR==0){
                    <td colspan='3'>No se han agregado productos aún.</td>";
              }
              echo "<input type='text' name='cod_bod' value='".$sel_bodega."' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
        }
  ?>
  </tbody>
  <tfoot>
        <style>
        .footable > tfoot > tr > th, .footable > tfoot > tr > td{ color: black; }
        input[type=text]{ color: black; }
        </style>

  <td colspan="4" align="right">Subtotal</td>
  <td><input type="text" class="subtotal" name="subtotal" id="subtotal" readonly placeholder="0"></td>
  <tr></tr>
  <td colspan="4" align="right">Descuento %<input type="text" id="discount" name="discount" class="discount" style="color: black; background: transparent; border: 0; text-align: center; width: 20px;" value="0"></td>
  <td><input type="text" class="descuento" class="descuento" name="descuento" id="descuento" readonly placeholder="0"></td>
  <tr></tr>
  <td colspan="4" align="right">Total</td>
  <td><input type="number" pattern="[0-9]{2}" min="50000" max="2000000" class="totales" id="totales" name="totales" readonly placeholder="0" ></td>
  <tr>
  <td colspan="5">
  <div class="pagination pagination-centered"></div>
  </td>
  </tr>
  </tfoot>
  </table>
  <script>
    //data-toggle="true"
    document.getElementById("tb").addEventListener("input", function(e) {
    const parent = e.target.closest("tr");
    const precio = parent.querySelector('[class=precio]').value;
    const cantidad = parent.querySelector('[class=cantidad]').value;
    const total = precio * cantidad;
    parent.querySelector('[class=total]').value = total;
    document.querySelector('[class=subtotal]').value = subtotal();
    document.querySelector('[class=discount]').value = discount();
    document.querySelector('[class=descuento]').value = dscto();
    document.querySelector('[class=totales]').value = totalfinal();
});

function subtotal(){
    var subtotal = 0;
    for(var x=0;x<document.querySelectorAll(".total").length;x++){
        subtotal += Number(document.querySelectorAll(".total")[x].value);
    }
    return subtotal;
}


function discount(){
    var subtotal = Number(document.getElementById("subtotal").value);
    var discount = 0;
    if(subtotal > 150000 && subtotal < 299999){
        discount = 3;
    }
    if(subtotal > 300000 && subtotal < 449999){
        discount = 4;
    }
    if(subtotal > 450000){
        discount = 5;
    }

    return discount;
}
function dscto(){
    var subtotal = Number(document.getElementById("subtotal").value);
    var descuento = 0;
    if(subtotal > 150000 && subtotal < 299999){
        descuento = subtotal * 0.03;
    }
    if(subtotal > 300000 && subtotal < 449999){
        descuento = subtotal * 0.04;
    }
    if(subtotal > 450000){
        descuento = subtotal * 0.05;
    }

    return descuento;
}



function totalfinal(){
    var subtotal2 = Number(document.getElementById("subtotal").value);
    var descuento2 = Number(document.getElementById("descuento").value);

    var totales = subtotal2 - descuento2;
    return totales;
}

How to get time with react-native-date-picker

I want to get the time with react-native-date-picker. So I set the mode as time. But this gives in this format, Here time is not correct too.

2023-01-25T16:50:53.467Z

This is my code,

     <DatePicker
        mode="time"
        date={date}
        modal
        open={pickupTimeModal1}
        onConfirm={time => console.log(time)}
        onCancel={() => {
          setPickupTimeModal1(false);
        }}
      />

Why is my code snippet not returning an alert?

Here is code:

document.addEventListener("DOMContentLoaded", () => {
  event.preventDefault();
  document.querySelector("#submit").onsubmit;
  () => {
    if (
      document.querySelector("#input").value === "" ||
      document.querySelector("#input").value === null
    ) {
      alert("Please enter your name.");
      return false;
    }
    let name = document.querySelector("#input").value;
    alert("Hello, " + name + "!");
  };
});
<form>
  <input id="input" placeholder="Name" type="text" autofocus autocapitalize="words" />
  <input id="submit" type="submit" />
</form>

When i run this code snippet it adds a question mark to the end of the url but doesn’t do an alert, any and all help appreciated

i’ve tried using the id called input instead of submit in the onsubmit but that gave the same result

PDF.js Setting a field value?

I hope you’re all doing well. So I’ve been working with PDF.js by Mozilla for a while now. We’re using it to display PDF forms to be filled out on a mobile app. Everything works great, I’m just trying to implement a feature where you can cache the users entries so that they can resume from where they left off. For a few reasons I can’t just download the PDF to save it and then load it back up when they wat to resume.

Essentially I want to store all the user entries and the Field ID for each of them, which I’ve already gotten working, and then when the user wants to resume I want it to load the empty PDF, and then automatically re-populate all the fields with the cached entries.

I know I could set the individual text fields, but when I do that it doesn’t apply to the annotationStorage so when I parse the form, those fields are read as blank.

I’ve tried the following lines of code in an attempt to set a field value with the id “5R”

PDFViewerApplication.pdfDocument.annotationStorage.setValue('5R', "Shirboogle");
PDFViewerApplication.pdfDocument.annotationStorage.getAll()['5R'].value = "Shirboogle";
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
objs['Address 1 Text Box'][0].value = "Shirboogle";
// and
objs['Address 1 Text Box'][0].defaultValue = "Shirboogle";
// This will actually set the value of the text field, but when I look for it in annotationStorage OR
// getFieldObjects() the value is still unchanged.
document.getElementById('pdfjs_internal_id_5R').value = 'Shapoopsies';

along with many other attempts. I’ve looked all over and nothing seems to be available, so if you have any ideas please let me know!

D3 Mitch Tree add Filter and Search Functionality

I am building a heirarchy tree that needs to be filterable and searchable. I am using D3 Mitch tree – https://d3-mitch-tree.netlify.app/

Right now I handle he filtering by

    document.getElementById('focusButton').addEventListener('click', function(){
    var value = 'filter1';
    var nodeMatchingText = treePlugin.getNodes().find(function(node){
    return node.data.name == value;    
    });
    treePlugin.focusToNode(nodeMatchingText);  
      
    });```


Then in the data json the name would have to be filter1 to make this match, and then it would open and focus on that node. This works, however I would like it to open all of the children related to that node. 

Search is where I am really struggling, I need it to do a full match or starts with or even partial on the names and then open ALL nodes that have the match in their children and close any that don't .

Currently I have this which will only open and focus on the first if it is an exact match. In the console log statement I can see all of the nodes but I am not sure how to get it to return and open those nodes.

document.getElementById('focusButton-search').addEventListener('click', function(){
var value = document.getElementById('search').value;
var nodeMatchingText = treePlugin.getNodes().find(function(node){
return node.data.name == value;
});
console.log(nodeMatchingText);
treePlugin.focusToNode(nodeMatchingText);

});